DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor frontend & rag
Bingxi Zhao388bc1359af6
diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.pyindex e9fe35b79..e5017a7ac 100644--- a/src/api/routers/knowledge.py+++ b/src/api/routers/knowledge.py@@ -235,6 +235,92 @@ async def get_rag_providers():raise HTTPException(status_code=500, detail=str(e))[email protected]("/configs")+async def get_all_kb_configs():+ """Get all knowledge base configurations from centralized config file."""+ try:+ from src.services.config import get_kb_config_service++ service = get_kb_config_service()+ return service.get_all_configs()+ except Exception as e:+ logger.error(f"Error getting KB configs: {e}")+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/{kb_name}/config")+async def get_kb_config(kb_name: str):+ """Get configuration for a specific knowledge base."""+ try:+ from src.services.config import get_kb_config_service++ service = get_kb_config_service()+ config = service.get_kb_config(kb_name)+ return {"kb_name": kb_name, "config": config}+ except Exception as e:+ logger.error(f"Error getting config for KB '{kb_name}': {e}")+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/{kb_name}/config")+async def update_kb_config(kb_name: str, config: dict):+ """Update configuration for a specific knowledge base."""+ try:+ from src.services.config import get_kb_config_service++ service = get_kb_config_service()+ service.set_kb_config(kb_name, config)+ return {"status": "success", "kb_name": kb_name, "config": service.get_kb_config(kb_name)}+ except Exception as e:+ logger.error(f"Error updating config for KB '{kb_name}': {e}")+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/configs/sync")+async def sync_configs_from_metadata():+ """Sync all KB configurations from their metadata.json files to centralized config."""+ try:+ from src.services.config import get_kb_config_service++ service = get_kb_config_service()+ service.sync_all_from_metadata(_kb_base_dir)+ return {"status": "success", "message": "Configurations synced from metadata files"}+ except Exception as e:+ logger.error(f"Error syncing configs: {e}")+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/default")+async def get_default_kb():+ """Get the default knowledge base."""+ try:+ manager = get_kb_manager()+ default_kb = manager.get_default()+ return {"default_kb": default_kb}+ except Exception as e:+ logger.error(f"Error getting default KB: {e}")+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/default/{kb_name}")+async def set_default_kb(kb_name: str):+ """Set the default knowledge base."""+ try:+ manager = get_kb_manager()++ # Verify KB exists+ if kb_name not in manager.list_knowledge_bases():+ raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")++ manager.set_default(kb_name)+ return {"status": "success", "default_kb": kb_name}+ except HTTPException:+ raise+ except Exception as e:+ logger.error(f"Error setting default KB: {e}")+ raise HTTPException(status_code=500, detail=str(e))++@router.get("/list", response_model=list[KnowledgeBaseInfo])async def list_knowledge_bases():"""List all available knowledge bases with their details."""diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.pyindex 9e6d963a5..56d6ff8f8 100644--- a/src/knowledge/add_documents.py+++ b/src/knowledge/add_documents.py@@ -199,13 +199,21 @@ class DocumentAdder:return files_to_processasync def process_new_documents(self, new_files: List[Path]):- """Async phase: Ingests files into the RAG system."""+ """+ Async phase: Ingests files into the RAG system.++ Uses FileTypeRouter to classify files and route them appropriately:+ - PDF/DOCX/images -> MinerU parser (full document analysis)+ - Text/Markdown -> Direct read + LightRAG insert (fast)+ """if not new_files:return Noneif raganything_cls is None:raise ImportError("RAGAnything module not found.")+ from src.services.rag.components.routing import FileTypeRouter+# Pre-import progress stage if needed to avoid overhead in loopProgressStage: Any = Noneif self.progress_tracker:@@ -337,15 +345,31 @@ class DocumentAdder:if hasattr(rag, "_ensure_lightrag_initialized"):await rag._ensure_lightrag_initialized()+ # Classify files by type+ file_paths_str = [str(f) for f in new_files]+ classification = FileTypeRouter.classify_files(file_paths_str)++ logger.info(+ f"File classification: {len(classification.needs_mineru)} need MinerU, "+ f"{len(classification.text_files)} text files, "+ f"{len(classification.unsupported)} unsupported"+ )+processed_files = []- for idx, doc_file in enumerate(new_files, 1):+ total_files = len(classification.needs_mineru) + len(classification.text_files)+ idx = 0++ # Process files requiring MinerU (PDF, DOCX, images)+ for doc_file_str in classification.needs_mineru:+ doc_file = Path(doc_file_str)+ idx += 1try:if self.progress_tracker and ProgressStage:self.progress_tracker.update(ProgressStage.PROCESSING_FILE,- f"Ingesting {doc_file.name}",+ f"Ingesting (MinerU) {doc_file.name}",current=idx,- total=len(new_files),+ total=total_files,)# Verify file still exists in raw/ (it should, as we staged it)@@ -364,10 +388,45 @@ class DocumentAdder:processed_files.append(doc_file)# Store hash on success - "Canonizing" the fileself._record_successful_hash(doc_file)- logger.info(f" ✓ Processed & Indexed: {doc_file.name}")+ logger.info(f" ✓ Processed (MinerU): {doc_file.name}")+ except Exception as e:+ logger.exception(f" ✗ Failed {doc_file.name}: {e}")++ # Process text files directly (fast path - no MinerU)+ for doc_file_str in classification.text_files:+ doc_file = Path(doc_file_str)+ idx += 1+ try:+ if self.progress_tracker and ProgressStage:+ self.progress_tracker.update(+ ProgressStage.PROCESSING_FILE,+ f"Ingesting (text) {doc_file.name}",+ current=idx,+ total=total_files,+ )++ # Verify file still exists+ if not doc_file.exists():+ logger.error(f" ✗ Failed: Staged file missing {doc_file.name}")+ continue++ # Read text file directly+ content = await FileTypeRouter.read_text_file(str(doc_file))+ if content.strip():+ # Insert directly into LightRAG, bypassing MinerU+ await rag.lightrag.ainsert(content)+ processed_files.append(doc_file)+ self._record_successful_hash(doc_file)+ logger.info(f" ✓ Processed (text): {doc_file.name}")+ else:+ logger.warning(f" ⚠ Skipped empty file: {doc_file.name}")except Exception as e:logger.exception(f" ✗ Failed {doc_file.name}: {e}")+ # Log unsupported files+ for doc_file_str in classification.unsupported:+ logger.warning(f" ⚠ Skipped unsupported file: {Path(doc_file_str).name}")+await self.fix_structure()return processed_files@@ -471,6 +530,14 @@ class DocumentAdder:# Update RAG provider if specifiedif self.rag_provider:metadata["rag_provider"] = self.rag_provider++ # Also save to centralized config file+ try:+ from src.services.config import get_kb_config_service+ kb_config_service = get_kb_config_service()+ kb_config_service.set_rag_provider(self.kb_name, self.rag_provider)+ except Exception as config_err:+ logger.warning(f"Failed to save to centralized config: {config_err}")history = metadata.get("update_history", [])history.append(diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.pyindex 7b7a39973..edd4c067d 100644--- a/src/knowledge/initializer.py+++ b/src/knowledge/initializer.py@@ -59,7 +59,7 @@ class KnowledgeBaseInitializer:self.rag_provider = rag_providerdef _register_to_config(self):- """Register KB to kb_config.json."""+ """Register KB to kb_config.json (only knowledge_bases list, no default)."""config_file = self.base_dir / "kb_config.json"if config_file.exists():try:@@ -67,12 +67,16 @@ class KnowledgeBaseInitializer:config = json.load(f)except Exception as e:logger.warning(f"Failed to read config: {e}, creating new")- config = {"knowledge_bases": {}, "default": None}+ config = {"knowledge_bases": {}}else:- config = {"knowledge_bases": {}, "default": None}+ config = {"knowledge_bases": {}}if "knowledge_bases" not in config:config["knowledge_bases"] = {}++ # Remove old "default" field if exists (migration)+ if "default" in config:+ del config["default"]if self.kb_name not in config.get("knowledge_bases", {}):config["knowledge_bases"][self.kb_name] = {@@ -80,9 +84,6 @@ class KnowledgeBaseInitializer:"description": f"Knowledge base: {self.kb_name}",}- if not config.get("default"):- config["default"] = self.kb_name-try:with open(config_file, "w", encoding="utf-8") as f:json.dump(config, indent=2, ensure_ascii=False, fp=f)@@ -93,7 +94,7 @@ class KnowledgeBaseInitializer:logger.info(" ✓ Already registered in kb_config.json")def _update_metadata_with_provider(self, provider: str):- """Update metadata.json with the RAG provider used."""+ """Update metadata.json and centralized config with the RAG provider used."""metadata_file = self.kb_dir / "metadata.json"try:if metadata_file.exists():@@ -109,6 +110,16 @@ class KnowledgeBaseInitializer:json.dump(metadata, indent=2, ensure_ascii=False, fp=f)logger.info(f" ✓ Updated metadata with RAG provider: {provider}")++ # Also save to centralized config file+ try:+ from src.services.config import get_kb_config_service+ kb_config_service = get_kb_config_service()+ kb_config_service.set_rag_provider(self.kb_name, provider)+ logger.info(f" ✓ Saved RAG provider to centralized config")+ except Exception as config_err:+ logger.warning(f"Failed to save to centralized config: {config_err}")+except Exception as e:logger.warning(f"Failed to update metadata with provider: {e}")diff --git a/src/knowledge/manager.py b/src/knowledge/manager.pyindex 94c7d7692..3b950172c 100644--- a/src/knowledge/manager.py+++ b/src/knowledge/manager.py@@ -24,11 +24,21 @@ class KnowledgeBaseManager:self.config = self._load_config()def _load_config(self) -> dict:- """Load knowledge base configuration"""+ """Load knowledge base configuration (kb_config.json only stores KB list)"""if self.config_file.exists():with open(self.config_file, encoding="utf-8") as f:- return json.load(f)- return {"knowledge_bases": {}, "default": None}+ config = json.load(f)+ # Migration: remove old "default" field if present+ if "default" in config:+ del config["default"]+ # Save cleaned config+ try:+ with open(self.config_file, "w", encoding="utf-8") as wf:+ json.dump(config, wf, indent=2, ensure_ascii=False)+ except Exception:+ pass+ return config+ return {"knowledge_bases": {}}def _save_config(self):"""Save knowledge base configuration"""@@ -74,8 +84,9 @@ class KnowledgeBaseManager:self.config["knowledge_bases"][name] = {"path": name, "description": description}- if set_default or not self.config.get("default"):- self.config["default"] = name+ # Only set default if explicitly requested+ if set_default:+ self.set_default(name)self._save_config()@@ -116,16 +127,42 @@ class KnowledgeBaseManager:return kb_dir / "raw"def set_default(self, name: str):- """Set default knowledge base"""+ """Set default knowledge base using centralized config service."""if name not in self.list_knowledge_bases():raise ValueError(f"Knowledge base not found: {name}")- self.config["default"] = name- self._save_config()+ # Use centralized config service only (no longer stored in kb_config.json)+ try:+ from src.services.config import get_kb_config_service+ kb_config_service = get_kb_config_service()+ kb_config_service.set_default_kb(name)+ except Exception as e:+ print(f"Warning: Failed to save default to centralized config: {e}")def get_default(self) -> str | None:- """Get default knowledge base name"""- return self.config.get("default")+ """+ Get default knowledge base name.++ Priority:+ 1. Centralized config service (knowledge_base_configs.json)+ 2. First knowledge base in the list (auto-fallback)+ """+ # Try centralized config first+ try:+ from src.services.config import get_kb_config_service+ kb_config_service = get_kb_config_service()+ default_kb = kb_config_service.get_default_kb()+ if default_kb and default_kb in self.list_knowledge_bases():+ return default_kb+ except Exception:+ pass++ # Fallback to first knowledge base in sorted list+ kb_list = self.list_knowledge_bases()+ if kb_list:+ return kb_list[0]++ return Nonedef get_metadata(self, name: str | None = None) -> dict:"""Get knowledge base metadata"""diff --git a/src/services/config/__init__.py b/src/services/config/__init__.pyindex 5cc6a39cf..b74893491 100644--- a/src/services/config/__init__.py+++ b/src/services/config/__init__.py@@ -2,7 +2,7 @@Configuration Service=====================-Provides two types of configuration:+Provides three types of configuration:1. **YAML Configuration (loader.py)** - For application settings from config/*.yaml- PROJECT_ROOT, load_config_with_main, get_path_from_config, parse_language, get_agent_params@@ -10,6 +10,9 @@ Provides two types of configuration:2. **Unified Config Service (unified_config.py)** - For service configurations (LLM, Embedding, TTS, Search)- ConfigType, UnifiedConfigManager, get_config_manager- get_active_llm_config, get_active_embedding_config, get_active_tts_config, get_active_search_config++3. **Knowledge Base Config Service (knowledge_base_config.py)** - For KB-specific settings+ - KnowledgeBaseConfigService, get_kb_config_service"""# Re-export everything from loader.py (existing functionality)@@ -32,6 +35,12 @@ from .unified_config import (get_config_manager,)+# Export knowledge base config service+from .knowledge_base_config import (+ KnowledgeBaseConfigService,+ get_kb_config_service,+)+__all__ = [# From loader.py"PROJECT_ROOT",@@ -47,4 +56,7 @@ __all__ = ["get_active_embedding_config","get_active_tts_config","get_active_search_config",+ # From knowledge_base_config.py+ "KnowledgeBaseConfigService",+ "get_kb_config_service",]diff --git a/src/services/config/knowledge_base_config.py b/src/services/config/knowledge_base_config.pynew file mode 100644index 000000000..399c86012--- /dev/null+++ b/src/services/config/knowledge_base_config.py@@ -0,0 +1,207 @@+"""+Knowledge Base Configuration Service+=====================================++Centralized configuration management for knowledge bases.+Stores KB-specific settings like RAG provider, search mode, etc.+"""++import json+from pathlib import Path+from typing import Any, Dict, Optional++from src.logging import get_logger++logger = get_logger("KBConfigService")++# Default config file path+DEFAULT_CONFIG_PATH = Path(__file__).parent.parent.parent.parent / "data" / "user" / "settings" / "knowledge_base_configs.json"+++class KnowledgeBaseConfigService:+ """+ Service for managing knowledge base configurations.++ Provides a centralized way to store and retrieve KB-specific settings,+ separate from the per-KB metadata.json files.+ """++ _instance: Optional["KnowledgeBaseConfigService"] = None++ def __init__(self, config_path: Optional[Path] = None):+ self.config_path = config_path or DEFAULT_CONFIG_PATH+ self._config: Dict[str, Any] = self._load_config()++ @classmethod+ def get_instance(cls, config_path: Optional[Path] = None) -> "KnowledgeBaseConfigService":+ """Get singleton instance."""+ if cls._instance is None:+ cls._instance = cls(config_path)+ return cls._instance++ def _load_config(self) -> Dict[str, Any]:+ """Load configuration from file."""+ if self.config_path.exists():+ try:+ with open(self.config_path, "r", encoding="utf-8") as f:+ return json.load(f)+ except Exception as e:+ logger.warning(f"Failed to load KB config: {e}")++ # Return default config+ return {+ "configs": {},+ "default_kb": None,+ "global_defaults": {+ "rag_provider": "llamaindex",+ "search_mode": "hybrid"+ }+ }++ def _save_config(self):+ """Save configuration to file."""+ try:+ self.config_path.parent.mkdir(parents=True, exist_ok=True)+ with open(self.config_path, "w", encoding="utf-8") as f:+ json.dump(self._config, f, indent=2, ensure_ascii=False)+ except Exception as e:+ logger.error(f"Failed to save KB config: {e}")++ def get_kb_config(self, kb_name: str) -> Dict[str, Any]:+ """+ Get configuration for a specific knowledge base.++ Args:+ kb_name: Knowledge base name++ Returns:+ KB configuration dict with defaults applied+ """+ kb_config = self._config.get("configs", {}).get(kb_name, {})+ defaults = self._config.get("global_defaults", {})++ # Merge with defaults+ return {+ "rag_provider": kb_config.get("rag_provider") or defaults.get("rag_provider", "llamaindex"),+ "search_mode": kb_config.get("search_mode") or defaults.get("search_mode", "hybrid"),+ **kb_config+ }++ def set_kb_config(self, kb_name: str, config: Dict[str, Any]):+ """+ Set configuration for a specific knowledge base.++ Args:+ kb_name: Knowledge base name+ config: Configuration dict+ """+ if "configs" not in self._config:+ self._config["configs"] = {}++ # Merge with existing config+ existing = self._config["configs"].get(kb_name, {})+ existing.update(config)+ self._config["configs"][kb_name] = existing++ self._save_config()+ logger.info(f"Updated config for KB '{kb_name}': {config}")++ def get_rag_provider(self, kb_name: str) -> str:+ """Get RAG provider for a knowledge base."""+ return self.get_kb_config(kb_name).get("rag_provider", "llamaindex")++ def set_rag_provider(self, kb_name: str, provider: str):+ """Set RAG provider for a knowledge base."""+ self.set_kb_config(kb_name, {"rag_provider": provider})++ def get_search_mode(self, kb_name: str) -> str:+ """Get search mode for a knowledge base."""+ return self.get_kb_config(kb_name).get("search_mode", "hybrid")++ def set_search_mode(self, kb_name: str, mode: str):+ """Set search mode for a knowledge base."""+ self.set_kb_config(kb_name, {"search_mode": mode})++ def delete_kb_config(self, kb_name: str):+ """Delete configuration for a knowledge base."""+ if "configs" in self._config and kb_name in self._config["configs"]:+ del self._config["configs"][kb_name]+ self._save_config()+ logger.info(f"Deleted config for KB '{kb_name}'")++ def get_all_configs(self) -> Dict[str, Any]:+ """Get all knowledge base configurations."""+ return self._config++ def set_global_defaults(self, defaults: Dict[str, Any]):+ """Set global default values."""+ if "global_defaults" not in self._config:+ self._config["global_defaults"] = {}++ self._config["global_defaults"].update(defaults)+ self._save_config()+ logger.info(f"Updated global defaults: {defaults}")++ def set_default_kb(self, kb_name: Optional[str]):+ """Set the default knowledge base."""+ self._config["default_kb"] = kb_name+ self._save_config()+ logger.info(f"Set default KB: {kb_name}")++ def get_default_kb(self) -> Optional[str]:+ """Get the default knowledge base name."""+ return self._config.get("default_kb")++ def sync_from_metadata(self, kb_name: str, kb_base_dir: Path):+ """+ Sync configuration from a KB's metadata.json file.++ Useful for migrating existing KBs to the centralized config.++ Args:+ kb_name: Knowledge base name+ kb_base_dir: Base directory for knowledge bases+ """+ metadata_file = kb_base_dir / kb_name / "metadata.json"++ if not metadata_file.exists():+ return++ try:+ with open(metadata_file, "r", encoding="utf-8") as f:+ metadata = json.load(f)++ # Extract relevant config from metadata+ config = {}+ if "rag_provider" in metadata and metadata["rag_provider"]:+ config["rag_provider"] = metadata["rag_provider"]++ if config:+ self.set_kb_config(kb_name, config)+ logger.info(f"Synced config for KB '{kb_name}' from metadata.json")++ except Exception as e:+ logger.warning(f"Failed to sync config from metadata for '{kb_name}': {e}")++ def sync_all_from_metadata(self, kb_base_dir: Path):+ """+ Sync configurations from all KBs' metadata.json files.++ Args:+ kb_base_dir: Base directory for knowledge bases+ """+ if not kb_base_dir.exists():+ return++ for kb_dir in kb_base_dir.iterdir():+ if kb_dir.is_dir() and kb_dir.name != "__pycache__":+ metadata_file = kb_dir / "metadata.json"+ if metadata_file.exists():+ self.sync_from_metadata(kb_dir.name, kb_base_dir)+++# Convenience function+def get_kb_config_service() -> KnowledgeBaseConfigService:+ """Get the knowledge base config service instance."""+ return KnowledgeBaseConfigService.get_instance()+diff --git a/src/services/rag/components/__init__.py b/src/services/rag/components/__init__.pyindex c8e1c713a..aa9ef36b5 100644--- a/src/services/rag/components/__init__.py+++ b/src/services/rag/components/__init__.py@@ -12,6 +12,7 @@ Components follow a simple protocol:# Import component modules for conveniencefrom . import chunkers, embedders, indexers, parsers, retrieversfrom .base import BaseComponent, Component+from .routing import DocumentType, FileClassification, FileTypeRouter__all__ = ["Component",@@ -21,4 +22,8 @@ __all__ = ["embedders","indexers","retrievers",+ # File type routing+ "FileTypeRouter",+ "FileClassification",+ "DocumentType",]diff --git a/src/services/rag/components/routing.py b/src/services/rag/components/routing.pynew file mode 100644index 000000000..13af2a298--- /dev/null+++ b/src/services/rag/components/routing.py@@ -0,0 +1,287 @@+"""+File Type Router+================++Centralized file type classification and routing for RAG pipelines.+Determines the appropriate processing method for each document type.+"""++from dataclasses import dataclass+from enum import Enum+from pathlib import Path+from typing import List++from src.logging import get_logger++logger = get_logger("FileTypeRouter")+++class DocumentType(Enum):+ """Document type classification"""++ PDF = "pdf" # Requires MinerU complex parsing+ TEXT = "text" # Plain text, direct read+ MARKDOWN = "markdown" # Structured text+ DOCX = "docx" # Word documents+ IMAGE = "image" # Images (may need OCR)+ UNKNOWN = "unknown" # Unsupported+++@dataclass+class FileClassification:+ """+ Result of file classification.++ Attributes:+ needs_mineru: Files requiring MinerU parsing (PDF, etc.)+ text_files: Files that can be read directly as text+ unsupported: Files with unsupported formats+ """++ needs_mineru: List[str]+ text_files: List[str]+ unsupported: List[str]+++class FileTypeRouter:+ """+ File type router for RAG pipelines.++ Classifies files before processing to route them to appropriate handlers:+ - PDF files -> MinerU parser (complex document parsing)+ - Text files -> Direct read (fast, simple)+ - Unsupported -> Skip with warning++ Usage:+ router = FileTypeRouter()+ classification = router.classify_files(file_paths)++ # Process PDF files with MinerU+ for pdf in classification.needs_mineru:+ await rag.process_document_complete(pdf, ...)++ # Process text files directly+ for txt in classification.text_files:+ content = await FileTypeRouter.read_text_file(txt)+ await rag.lightrag.ainsert(content)+ """++ # Extensions requiring MinerU parsing (complex document formats)+ MINERU_EXTENSIONS = {".pdf"}++ # Extensions for direct text reading+ TEXT_EXTENSIONS = {+ # Plain text+ ".txt",+ ".text",+ ".log",+ # Markup languages+ ".md",+ ".markdown",+ ".rst",+ ".asciidoc",+ # Data formats+ ".json",+ ".yaml",+ ".yml",+ ".toml",+ ".csv",+ ".tsv",+ # LaTeX+ ".tex",+ ".latex",+ ".bib",+ # Code files+ ".py",+ ".js",+ ".ts",+ ".jsx",+ ".tsx",+ ".java",+ ".c",+ ".cpp",+ ".h",+ ".hpp",+ ".go",+ ".rs",+ ".rb",+ ".php",+ ".swift",+ ".kt",+ ".scala",+ ".r",+ ".sql",+ ".sh",+ ".bash",+ ".zsh",+ ".ps1",+ # Web+ ".html",+ ".htm",+ ".xml",+ ".css",+ ".scss",+ ".sass",+ ".less",+ # Config+ ".ini",+ ".cfg",+ ".conf",+ ".env",+ ".properties",+ }++ # Word document extensions (special handling)+ DOCX_EXTENSIONS = {".docx", ".doc"}++ # Image extensions (may need OCR)+ IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif"}++ @classmethod+ def get_document_type(cls, file_path: str) -> DocumentType:+ """+ Classify a single file by its type.++ Args:+ file_path: Path to the file++ Returns:+ DocumentType enum value+ """+ ext = Path(file_path).suffix.lower()++ if ext in cls.MINERU_EXTENSIONS:+ return DocumentType.PDF+ elif ext in cls.TEXT_EXTENSIONS:+ return DocumentType.TEXT+ elif ext in cls.DOCX_EXTENSIONS:+ return DocumentType.DOCX+ elif ext in cls.IMAGE_EXTENSIONS:+ return DocumentType.IMAGE+ else:+ # Try to detect if it's a text file by content+ if cls._is_text_file(file_path):+ return DocumentType.TEXT+ return DocumentType.UNKNOWN++ @classmethod+ def _is_text_file(cls, file_path: str, sample_size: int = 8192) -> bool:+ """+ Detect if a file is text-based by examining its content.++ Args:+ file_path: Path to the file+ sample_size: Number of bytes to sample++ Returns:+ True if file appears to be text+ """+ try:+ with open(file_path, "rb") as f:+ chunk = f.read(sample_size)++ # Check for null bytes (binary file indicator)+ if b"\x00" in chunk:+ return False++ # Try to decode as UTF-8+ chunk.decode("utf-8")+ return True+ except (UnicodeDecodeError, IOError, OSError):+ return False++ @classmethod+ def classify_files(cls, file_paths: List[str]) -> FileClassification:+ """+ Classify a list of files by processing method.++ Args:+ file_paths: List of file paths to classify++ Returns:+ FileClassification with files grouped by processing method+ """+ needs_mineru = []+ text_files = []+ unsupported = []++ for path in file_paths:+ doc_type = cls.get_document_type(path)++ if doc_type == DocumentType.PDF:+ needs_mineru.append(path)+ elif doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN):+ text_files.append(path)+ elif doc_type == DocumentType.DOCX:+ # DOCX files need special handling+ # For now, route to MinerU which can handle them+ needs_mineru.append(path)+ elif doc_type == DocumentType.IMAGE:+ # Images might need OCR - route to MinerU if multimodal is enabled+ needs_mineru.append(path)+ else:+ unsupported.append(path)++ logger.debug(+ f"Classified {len(file_paths)} files: "+ f"{len(needs_mineru)} MinerU, {len(text_files)} text, {len(unsupported)} unsupported"+ )++ return FileClassification(+ needs_mineru=needs_mineru,+ text_files=text_files,+ unsupported=unsupported,+ )++ @classmethod+ async def read_text_file(cls, file_path: str) -> str:+ """+ Read a text file with automatic encoding detection.++ Args:+ file_path: Path to the text file++ Returns:+ File content as string+ """+ encodings = ["utf-8", "utf-8-sig", "gbk", "gb2312", "gb18030", "latin-1", "cp1252"]++ for encoding in encodings:+ try:+ with open(file_path, "r", encoding=encoding) as f:+ return f.read()+ except UnicodeDecodeError:+ continue++ # Last resort: read with error replacement+ with open(file_path, "rb") as f:+ return f.read().decode("utf-8", errors="replace")++ @classmethod+ def needs_mineru(cls, file_path: str) -> bool:+ """+ Quick check if a single file needs MinerU parsing.++ Args:+ file_path: Path to the file++ Returns:+ True if file requires MinerU+ """+ doc_type = cls.get_document_type(file_path)+ return doc_type in (DocumentType.PDF, DocumentType.DOCX, DocumentType.IMAGE)++ @classmethod+ def is_text_readable(cls, file_path: str) -> bool:+ """+ Check if a file can be read directly as text.++ Args:+ file_path: Path to the file++ Returns:+ True if file can be read as text+ """+ doc_type = cls.get_document_type(file_path)+ return doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN)+diff --git a/src/services/rag/pipeline.py b/src/services/rag/pipeline.pyindex c9bf09601..97ba6363a 100644--- a/src/services/rag/pipeline.py+++ b/src/services/rag/pipeline.py@@ -13,6 +13,8 @@ from typing import Any, Dict, List, Optionalfrom src.logging import get_loggerfrom .components.base import Component+from .components.routing import FileTypeRouter+from .types import Document# Default knowledge base directoryDEFAULT_KB_BASE_DIR = str(@@ -86,6 +88,10 @@ class RAGPipeline:"""Run full initialization pipeline.+ Uses FileTypeRouter to classify files and route them appropriately:+ - PDF/complex files -> configured parser (e.g., PDFParser)+ - Text files -> direct text reading (fast path)+Args:kb_name: Knowledge base namefile_paths: List of file paths to process@@ -99,13 +105,43 @@ class RAGPipeline:if not self._parser:raise ValueError("No parser configured. Use .parser() to set one")- # Stage 1: Parse documents+ # Stage 1: Parse documents with file type routingself.logger.info("Stage 1: Parsing documents...")++ # Classify files by type+ classification = FileTypeRouter.classify_files(file_paths)+ self.logger.info(+ f"File classification: {len(classification.needs_mineru)} complex, "+ f"{len(classification.text_files)} text, "+ f"{len(classification.unsupported)} unsupported"+ )+documents = []- for path in file_paths:++ # Process complex files (PDF, etc.) with configured parser+ for path in classification.needs_mineru:+ self.logger.info(f"Parsing (parser): {Path(path).name}")doc = await self._parser.process(path, **kwargs)documents.append(doc)+ # Process text files directly (fast path)+ for path in classification.text_files:+ self.logger.info(f"Parsing (direct text): {Path(path).name}")+ content = await FileTypeRouter.read_text_file(path)+ doc = Document(+ content=content,+ file_path=str(path),+ metadata={+ "filename": Path(path).name,+ "parser": "direct_text",+ },+ )+ documents.append(doc)++ # Log unsupported files+ for path in classification.unsupported:+ self.logger.warning(f"Skipped unsupported file: {Path(path).name}")+# Stage 2: Chunk (sequential - later chunkers see earlier results)if self._chunkers:self.logger.info("Stage 2: Chunking...")diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.pyindex cc9de9492..c072d8884 100644--- a/src/services/rag/pipelines/raganything.py+++ b/src/services/rag/pipelines/raganything.py@@ -199,6 +199,10 @@ class RAGAnythingPipeline:"""Initialize KB using RAG-Anything's process_document_complete().+ Uses FileTypeRouter to classify files and route them appropriately:+ - PDF files -> MinerU parser (full document analysis)+ - Text files -> Direct read + LightRAG insert (fast)+Args:kb_name: Knowledge base namefile_paths: List of file paths to process@@ -208,24 +212,57 @@ class RAGAnythingPipeline:Returns:True if successful"""+ from ..components.routing import FileTypeRouter+self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")kb_dir = Path(self.kb_base_dir) / kb_namecontent_list_dir = kb_dir / "content_list"content_list_dir.mkdir(parents=True, exist_ok=True)+ # Classify files by type+ classification = FileTypeRouter.classify_files(file_paths)++ self.logger.info(+ f"File classification: {len(classification.needs_mineru)} need MinerU, "+ f"{len(classification.text_files)} text files, "+ f"{len(classification.unsupported)} unsupported"+ )+with LightRAGLogContext(scene="knowledge_init"):rag = self._get_rag_instance(kb_name)await rag._ensure_lightrag_initialized()- for idx, file_path in enumerate(file_paths, 1):- self.logger.info(f"Processing [{idx}/{len(file_paths)}]: {Path(file_path).name}")+ total_files = len(classification.needs_mineru) + len(classification.text_files)+ idx = 0++ # Process files requiring MinerU (PDF, DOCX, images)+ for file_path in classification.needs_mineru:+ idx += 1+ self.logger.info(+ f"Processing [{idx}/{total_files}] (MinerU): {Path(file_path).name}"+ )await rag.process_document_complete(file_path=file_path,output_dir=str(content_list_dir),parse_method="auto",)+ # Process text files directly (fast path)+ for file_path in classification.text_files:+ idx += 1+ self.logger.info(+ f"Processing [{idx}/{total_files}] (direct text): {Path(file_path).name}"+ )+ content = await FileTypeRouter.read_text_file(file_path)+ if content.strip():+ # Insert directly into LightRAG, bypassing MinerU+ await rag.lightrag.ainsert(content)++ # Log unsupported files+ for file_path in classification.unsupported:+ self.logger.warning(f"Skipped unsupported file: {Path(file_path).name}")+if extract_numbered_items:await self._extract_numbered_items(kb_name)diff --git a/web/.env.local b/web/.env.localindex 8840a64d6..0b6543af3 100644--- a/web/.env.local+++ b/web/.env.local@@ -3,7 +3,7 @@# ============================================# This file is automatically updated based on config/main.yaml# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)-#+## To configure for remote access, set in your .env file:# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001# ============================================diff --git a/web/app/guide/components/ChatPanel.tsx b/web/app/guide/components/ChatPanel.tsxnew file mode 100644index 000000000..34b5cf646--- /dev/null+++ b/web/app/guide/components/ChatPanel.tsx@@ -0,0 +1,162 @@+"use client";++import { useRef, useEffect, useState } from "react";+import { MessageSquare, Send, Loader2 } from "lucide-react";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";+import rehypeKatex from "rehype-katex";+import "katex/dist/katex.min.css";+import { processLatexContent } from "@/lib/latex";+import { ChatMessage } from "../types";++interface ChatPanelProps {+ messages: ChatMessage[];+ isLearning: boolean;+ onSendMessage: (message: string) => void;+}++export default function ChatPanel({+ messages,+ isLearning,+ onSendMessage,+}: ChatPanelProps) {+ const [inputMessage, setInputMessage] = useState("");+ const [sendingMessage, setSendingMessage] = useState(false);+ const chatContainerRef = useRef<HTMLDivElement>(null);++ // Auto-scroll chat+ useEffect(() => {+ if (chatContainerRef.current) {+ chatContainerRef.current.scrollTo({+ top: chatContainerRef.current.scrollHeight,+ behavior: "smooth",+ });+ }+ }, [messages]);++ const handleSendMessage = async () => {+ if (!inputMessage.trim() || sendingMessage) return;++ setSendingMessage(true);+ const message = inputMessage;+ setInputMessage("");++ try {+ await onSendMessage(message);+ } finally {+ setSendingMessage(false);+ }+ };++ // Table components for ReactMarkdown+ const tableComponents = {+ table: ({ node, ...props }: any) => (+ <div className="overflow-x-auto my-4 rounded-lg border border-slate-200 shadow-sm">+ <table+ className="min-w-full divide-y divide-slate-200 text-sm"+ {...props}+ />+ </div>+ ),+ thead: ({ node, ...props }: any) => (+ <thead className="bg-slate-50" {...props} />+ ),+ th: ({ node, ...props }: any) => (+ <th+ className="px-3 py-2 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"+ {...props}+ />+ ),+ tbody: ({ node, ...props }: any) => (+ <tbody className="divide-y divide-slate-100 bg-white" {...props} />+ ),+ td: ({ node, ...props }: any) => (+ <td+ className="px-3 py-2 text-slate-600 border-b border-slate-100"+ {...props}+ />+ ),+ tr: ({ node, ...props }: any) => (+ <tr className="hover:bg-slate-50/50 transition-colors" {...props} />+ ),+ };++ return (+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">+ <MessageSquare className="w-4 h-4" />+ Learning Assistant+ </div>++ <div+ ref={chatContainerRef}+ className="flex-1 overflow-y-auto p-4 space-y-4 bg-slate-50/30 dark:bg-slate-800/30"+ >+ {messages.map((msg) => (+ <div+ key={msg.id}+ className={`flex flex-col ${msg.role === "user" ? "items-end" : "items-start"}`}+ >+ <div+ className={`max-w-[90%] rounded-2xl px-4 py-3 text-sm ${+ msg.role === "user"+ ? "bg-indigo-600 text-white rounded-tr-none shadow-md shadow-indigo-500/20"+ : msg.role === "system" && msg.content.includes("⏳")+ ? "bg-amber-50 border border-amber-200 text-amber-900 rounded-tl-none"+ : msg.role === "system"+ ? "bg-blue-50 border border-blue-200 text-blue-900 rounded-tl-none"+ : "bg-white border border-slate-200 text-slate-700 rounded-tl-none shadow-sm"+ }`}+ >+ {msg.role === "system" || msg.role === "assistant" ? (+ <div className="prose prose-sm max-w-none prose-slate">+ <ReactMarkdown+ remarkPlugins={[remarkGfm, remarkMath]}+ rehypePlugins={[rehypeKatex]}+ components={tableComponents}+ >+ {processLatexContent(msg.content)}+ </ReactMarkdown>+ </div>+ ) : (+ <p>{msg.content}</p>+ )}+ </div>+ </div>+ ))}+ </div>++ {/* Input Area */}+ {isLearning && (+ <div className="p-3 bg-white dark:bg-slate-800 border-t border-slate-100 dark:border-slate-700">+ <div className="relative flex items-center gap-2">+ <input+ type="text"+ value={inputMessage}+ onChange={(e) => setInputMessage(e.target.value)}+ onKeyDown={(e) =>+ e.key === "Enter" && !e.shiftKey && handleSendMessage()+ }+ placeholder="Have any questions? Feel free to ask..."+ disabled={sendingMessage}+ className="flex-1 pl-4 pr-10 py-2.5 bg-slate-100 dark:bg-slate-700 border-transparent focus:bg-white dark:focus:bg-slate-600 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 rounded-xl text-sm text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 transition-all outline-none disabled:opacity-50 disabled:cursor-not-allowed"+ />+ <button+ onClick={handleSendMessage}+ disabled={!inputMessage.trim() || sendingMessage}+ className="p-2.5 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 active:scale-95 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-indigo-500/20"+ >+ {sendingMessage ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ <Send className="w-4 h-4" />+ )}+ </button>+ </div>+ </div>+ )}+ </div>+ );+}+diff --git a/web/app/guide/components/CompletionSummary.tsx b/web/app/guide/components/CompletionSummary.tsxnew file mode 100644index 000000000..e9c57a1bf--- /dev/null+++ b/web/app/guide/components/CompletionSummary.tsx@@ -0,0 +1,73 @@+"use client";++import { CheckCircle2 } from "lucide-react";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";+import rehypeKatex from "rehype-katex";+import "katex/dist/katex.min.css";+import { processLatexContent } from "@/lib/latex";++interface CompletionSummaryProps {+ summary: string;+}++export default function CompletionSummary({ summary }: CompletionSummaryProps) {+ // Table components for ReactMarkdown+ const tableComponents = {+ table: ({ node, ...props }: any) => (+ <div className="overflow-x-auto my-6 rounded-lg border border-slate-200 shadow-sm">+ <table+ className="min-w-full divide-y divide-slate-200 text-sm"+ {...props}+ />+ </div>+ ),+ thead: ({ node, ...props }: any) => (+ <thead className="bg-slate-50" {...props} />+ ),+ th: ({ node, ...props }: any) => (+ <th+ className="px-4 py-3 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"+ {...props}+ />+ ),+ tbody: ({ node, ...props }: any) => (+ <tbody className="divide-y divide-slate-100 bg-white" {...props} />+ ),+ td: ({ node, ...props }: any) => (+ <td+ className="px-4 py-3 text-slate-600 border-b border-slate-100"+ {...props}+ />+ ),+ tr: ({ node, ...props }: any) => (+ <tr className="hover:bg-slate-50/50 transition-colors" {...props} />+ ),+ };++ return (+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">+ {/* Summary Header */}+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-emerald-50 to-indigo-50 dark:from-emerald-900/20 dark:to-indigo-900/20 flex items-center justify-between shrink-0">+ <h2 className="font-bold text-slate-800 dark:text-slate-100 flex items-center gap-2">+ <CheckCircle2 className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />+ Learning Summary+ </h2>+ </div>+ {/* Summary Content */}+ <div className="flex-1 overflow-y-auto p-8 bg-white dark:bg-slate-800">+ <div className="prose prose-slate dark:prose-invert prose-headings:font-bold prose-h1:text-2xl prose-h2:text-xl max-w-none">+ <ReactMarkdown+ remarkPlugins={[remarkGfm, remarkMath]}+ rehypePlugins={[rehypeKatex]}+ components={tableComponents}+ >+ {processLatexContent(summary || "")}+ </ReactMarkdown>+ </div>+ </div>+ </div>+ );+}+diff --git a/web/app/guide/components/DebugModal.tsx b/web/app/guide/components/DebugModal.tsxnew file mode 100644index 000000000..8654514c1--- /dev/null+++ b/web/app/guide/components/DebugModal.tsx@@ -0,0 +1,94 @@+"use client";++import { useState } from "react";+import { Bug, X, Loader2 } from "lucide-react";++interface DebugModalProps {+ isOpen: boolean;+ onClose: () => void;+ onFix: (description: string) => Promise<boolean>;+}++export default function DebugModal({ isOpen, onClose, onFix }: DebugModalProps) {+ const [description, setDescription] = useState("");+ const [fixing, setFixing] = useState(false);++ if (!isOpen) return null;++ const handleFix = async () => {+ if (!description.trim() || fixing) return;++ setFixing(true);+ const success = await onFix(description);+ setFixing(false);++ if (success) {+ setDescription("");+ onClose();+ }+ };++ const handleClose = () => {+ setDescription("");+ onClose();+ };++ return (+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[500px] animate-in zoom-in-95">+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">+ <h3 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">+ <Bug className="w-5 h-5 text-amber-600 dark:text-amber-400" />+ Fix HTML Issue+ </h3>+ <button+ onClick={handleClose}+ className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"+ >+ <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />+ </button>+ </div>+ <div className="p-6 space-y-4">+ <div>+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">+ Issue Description+ </label>+ <textarea+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ placeholder="Describe the HTML issue, e.g.: button not clickable, style display error, interaction not working..."+ rows={6}+ className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 outline-none resize-none"+ />+ </div>+ </div>+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2">+ <button+ onClick={handleClose}+ className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleFix}+ disabled={!description.trim() || fixing}+ className="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors disabled:opacity-50 flex items-center gap-2"+ >+ {fixing ? (+ <>+ <Loader2 className="w-4 h-4 animate-spin" />+ Fixing...+ </>+ ) : (+ <>+ <Bug className="w-4 h-4" />+ Fix+ </>+ )}+ </button>+ </div>+ </div>+ </div>+ );+}+diff --git a/web/app/guide/components/HTMLViewer.tsx b/web/app/guide/components/HTMLViewer.tsxnew file mode 100644index 000000000..2c287caa3--- /dev/null+++ b/web/app/guide/components/HTMLViewer.tsx@@ -0,0 +1,109 @@+"use client";++import { useRef, useEffect } from "react";+import { Bug, Loader2 } from "lucide-react";+import { useKaTeXInjection } from "../hooks";++interface HTMLViewerProps {+ html: string;+ currentIndex: number;+ loadingMessage: string;+ onOpenDebugModal: () => void;+}++export default function HTMLViewer({+ html,+ currentIndex,+ loadingMessage,+ onOpenDebugModal,+}: HTMLViewerProps) {+ const htmlFrameRef = useRef<HTMLIFrameElement>(null);+ const { injectKaTeX } = useKaTeXInjection();++ // Update HTML iframe+ useEffect(() => {+ if (!html) return;++ const timer = setTimeout(() => {+ if (htmlFrameRef.current) {+ const iframe = htmlFrameRef.current;+ console.log("Updating iframe with HTML, length:", html.length);++ // Inject KaTeX support if needed+ const htmlWithKaTeX = injectKaTeX(html);++ // Use srcdoc attribute (most reliable method)+ try {+ iframe.srcdoc = htmlWithKaTeX;+ console.log("Iframe srcdoc set successfully with KaTeX support");+ } catch (e) {+ console.warn("srcdoc not supported, using contentDocument:", e);+ // Fallback to contentDocument if srcdoc not supported+ const handleLoad = () => {+ try {+ const doc =+ iframe.contentDocument || iframe.contentWindow?.document;+ if (doc) {+ doc.open();+ doc.write(htmlWithKaTeX);+ doc.close();+ console.log(+ "Iframe content written via contentDocument with KaTeX support",+ );+ }+ } catch (err) {+ console.error("Failed to write to iframe:", err);+ }+ };++ if (+ iframe.contentDocument &&+ iframe.contentDocument.readyState === "complete"+ ) {+ handleLoad();+ } else {+ iframe.onload = handleLoad;+ }+ }+ } else {+ console.warn("htmlFrameRef.current is null");+ }+ }, 100);++ return () => clearTimeout(timer);+ }, [html, currentIndex, injectKaTeX]);++ if (!html) {+ return (+ <div className="flex-1 flex flex-col items-center justify-center">+ <Loader2 className="w-12 h-12 text-indigo-400 dark:text-indigo-500 animate-spin mb-4" />+ <p className="text-slate-500 dark:text-slate-400">+ {loadingMessage || "Loading learning content..."}+ </p>+ </div>+ );+ }++ return (+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">+ {/* Debug Button */}+ <button+ onClick={onOpenDebugModal}+ className="absolute top-4 right-4 z-10 p-2 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-lg transition-colors shadow-sm"+ title="Fix HTML"+ >+ <Bug className="w-4 h-4 text-slate-600 dark:text-slate-300" />+ </button>++ {/* HTML Content */}+ <iframe+ ref={htmlFrameRef}+ className="w-full h-full border-0"+ title="Interactive Learning Content"+ sandbox="allow-scripts allow-same-origin"+ key={`html-${currentIndex}-${html.length}`}+ />+ </div>+ );+}+diff --git a/web/app/guide/components/NotebookSelector.tsx b/web/app/guide/components/NotebookSelector.tsxnew file mode 100644index 000000000..369691ca5--- /dev/null+++ b/web/app/guide/components/NotebookSelector.tsx@@ -0,0 +1,231 @@+"use client";++import {+ BookOpen,+ Loader2,+ ChevronRight,+ ChevronDown,+ Sparkles,+ Check,+} from "lucide-react";+import {+ Notebook,+ NotebookRecord,+ SelectedRecord,+ getTypeColor,+} from "../types";++interface NotebookSelectorProps {+ notebooks: Notebook[];+ expandedNotebooks: Set<string>;+ notebookRecordsMap: Map<string, NotebookRecord[]>;+ selectedRecords: Map<string, SelectedRecord>;+ loadingNotebooks: boolean;+ loadingRecordsFor: Set<string>;+ isLoading: boolean;+ onToggleExpanded: (notebookId: string) => void;+ onToggleRecord: (+ record: NotebookRecord,+ notebookId: string,+ notebookName: string,+ ) => void;+ onSelectAll: (notebookId: string, notebookName: string) => void;+ onDeselectAll: (notebookId: string) => void;+ onClearAll: () => void;+ onCreateSession: () => void;+}++export default function NotebookSelector({+ notebooks,+ expandedNotebooks,+ notebookRecordsMap,+ selectedRecords,+ loadingNotebooks,+ loadingRecordsFor,+ isLoading,+ onToggleExpanded,+ onToggleRecord,+ onSelectAll,+ onDeselectAll,+ onClearAll,+ onCreateSession,+}: NotebookSelectorProps) {+ return (+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">+ <h2 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">+ <BookOpen className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />+ Select Source (Cross-Notebook)+ </h2>+ {selectedRecords.size > 0 && (+ <button+ onClick={onClearAll}+ className="text-xs text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400"+ >+ Clear ({selectedRecords.size})+ </button>+ )}+ </div>++ <div className="flex-1 overflow-y-auto max-h-[400px]">+ {loadingNotebooks ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 className="w-5 h-5 animate-spin text-indigo-600 dark:text-indigo-400" />+ </div>+ ) : notebooks.length === 0 ? (+ <div className="p-4 text-center text-sm text-slate-400 dark:text-slate-500">+ No notebooks with records found+ </div>+ ) : (+ <div className="divide-y divide-slate-100 dark:divide-slate-700">+ {notebooks.map((notebook) => {+ const isExpanded = expandedNotebooks.has(notebook.id);+ const records = notebookRecordsMap.get(notebook.id) || [];+ const isLoadingRecords = loadingRecordsFor.has(notebook.id);+ const selectedFromThis = records.filter((r) =>+ selectedRecords.has(r.id),+ ).length;++ return (+ <div key={notebook.id}>+ {/* Notebook Header */}+ <div+ className="p-3 flex items-center gap-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"+ onClick={() => onToggleExpanded(notebook.id)}+ >+ {isExpanded ? (+ <ChevronDown className="w-4 h-4 text-slate-400 dark:text-slate-500" />+ ) : (+ <ChevronRight className="w-4 h-4 text-slate-400 dark:text-slate-500" />+ )}+ <div+ className="w-3 h-3 rounded-full"+ style={{+ backgroundColor: notebook.color || "#94a3b8",+ }}+ />+ <span className="flex-1 text-sm font-medium text-slate-700 dark:text-slate-200 truncate">+ {notebook.name}+ </span>+ <span className="text-xs text-slate-400 dark:text-slate-500">+ {selectedFromThis > 0 && (+ <span className="text-indigo-600 dark:text-indigo-400 font-medium">+ {selectedFromThis}/+ </span>+ )}+ {notebook.record_count}+ </span>+ </div>++ {/* Records List */}+ {isExpanded && (+ <div className="pl-6 pr-2 pb-2 bg-slate-50/50 dark:bg-slate-800/50">+ {isLoadingRecords ? (+ <div className="flex items-center justify-center py-4">+ <Loader2 className="w-4 h-4 animate-spin text-indigo-600 dark:text-indigo-400" />+ </div>+ ) : records.length === 0 ? (+ <div className="py-2 text-xs text-slate-400 dark:text-slate-500 text-center">+ No records+ </div>+ ) : (+ <>+ <div className="flex gap-2 mb-2">+ <button+ onClick={(e) => {+ e.stopPropagation();+ onSelectAll(notebook.id, notebook.name);+ }}+ className="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300"+ >+ Select All+ </button>+ <button+ onClick={(e) => {+ e.stopPropagation();+ onDeselectAll(notebook.id);+ }}+ className="text-xs text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"+ >+ Deselect+ </button>+ </div>+ <div className="space-y-1">+ {records.map((record) => (+ <div+ key={record.id}+ onClick={(e) => {+ e.stopPropagation();+ onToggleRecord(+ record,+ notebook.id,+ notebook.name,+ );+ }}+ className={`p-2 rounded-lg cursor-pointer transition-all border ${+ selectedRecords.has(record.id)+ ? "bg-indigo-50 dark:bg-indigo-900/30 border-indigo-200 dark:border-indigo-700"+ : "hover:bg-white dark:hover:bg-slate-700 border-transparent hover:border-slate-200 dark:hover:border-slate-600"+ }`}+ >+ <div className="flex items-center gap-2">+ <div+ className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${+ selectedRecords.has(record.id)+ ? "bg-indigo-500 border-indigo-500 text-white"+ : "border-slate-300 dark:border-slate-500"+ }`}+ >+ {selectedRecords.has(record.id) && (+ <Check className="w-2.5 h-2.5" />+ )}+ </div>+ <div className="flex-1 min-w-0">+ <span+ className={`text-[10px] font-bold uppercase px-1 py-0.5 rounded ${getTypeColor(record.type)}`}+ >+ {record.type}+ </span>+ <span className="text-xs text-slate-700 dark:text-slate-200 ml-2 truncate">+ {record.title}+ </span>+ </div>+ </div>+ </div>+ ))}+ </div>+ </>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>++ {/* Generate Button */}+ <div className="p-3 border-t border-slate-100 dark:border-slate-700">+ <button+ onClick={onCreateSession}+ disabled={isLoading || selectedRecords.size === 0}+ className="w-full px-4 py-2.5 bg-gradient-to-r from-indigo-500 to-purple-500 text-white rounded-xl hover:from-indigo-600 hover:to-purple-600 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 font-medium shadow-md shadow-indigo-500/20"+ >+ {isLoading ? (+ <>+ <Loader2 className="w-4 h-4 animate-spin" />+ Generating...+ </>+ ) : (+ <>+ <Sparkles className="w-4 h-4" />+ Generate Learning Plan ({selectedRecords.size} items)+ </>+ )}+ </button>+ </div>+ </div>+ );+}+diff --git a/web/app/guide/components/ProgressPanel.tsx b/web/app/guide/components/ProgressPanel.tsxnew file mode 100644index 000000000..092f45b95--- /dev/null+++ b/web/app/guide/components/ProgressPanel.tsx@@ -0,0 +1,113 @@+"use client";++import { Loader2, Play, ChevronRight, CheckCircle2 } from "lucide-react";+import { SessionState } from "../types";++interface ProgressPanelProps {+ sessionState: SessionState;+ isLoading: boolean;+ canStart: boolean;+ canNext: boolean;+ isLastKnowledge: boolean;+ onStartLearning: () => void;+ onNextKnowledge: () => void;+}++export default function ProgressPanel({+ sessionState,+ isLoading,+ canStart,+ canNext,+ isLastKnowledge,+ onStartLearning,+ onNextKnowledge,+}: ProgressPanelProps) {+ return (+ <div className="bg-white dark:bg-slate-800 p-4 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">+ Learning Progress+ </span>+ <span className="text-xs text-slate-400 dark:text-slate-500">+ {sessionState.progress}%+ </span>+ </div>+ <div className="h-2 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden mb-4">+ <div+ className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 rounded-full transition-all duration-500"+ style={{ width: `${sessionState.progress}%` }}+ />+ </div>+ {sessionState.knowledge_points.length > 0 && (+ <p className="text-xs text-slate-400 dark:text-slate-500 mb-4">+ Knowledge Point {sessionState.current_index + 1} /{" "}+ {sessionState.knowledge_points.length}+ </p>+ )}++ {/* Action Buttons */}+ <div className="flex gap-2">+ {canStart && (+ <button+ onClick={onStartLearning}+ disabled={isLoading}+ className="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"+ >+ {isLoading ? (+ <>+ <Loader2 className="w-4 h-4 animate-spin" />+ Generating...+ </>+ ) : (+ <>+ <Play className="w-4 h-4" />+ Start Learning+ </>+ )}+ </button>+ )}++ {canNext && (+ <button+ onClick={onNextKnowledge}+ disabled={isLoading}+ className="flex-1 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"+ >+ {isLoading ? (+ <>+ <Loader2 className="w-4 h-4 animate-spin" />+ Loading...+ </>+ ) : (+ <>+ <ChevronRight className="w-4 h-4" />+ Next+ </>+ )}+ </button>+ )}++ {isLastKnowledge && (+ <button+ onClick={onNextKnowledge}+ disabled={isLoading}+ className="flex-1 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"+ >+ {isLoading ? (+ <>+ <Loader2 className="w-4 h-4 animate-spin" />+ Generating Summary...+ </>+ ) : (+ <>+ <CheckCircle2 className="w-4 h-4" />+ Complete Learning+ </>+ )}+ </button>+ )}+ </div>+ </div>+ );+}+diff --git a/web/app/guide/components/index.ts b/web/app/guide/components/index.tsnew file mode 100644index 000000000..a014699e3--- /dev/null+++ b/web/app/guide/components/index.ts@@ -0,0 +1,7 @@+export { default as NotebookSelector } from "./NotebookSelector";+export { default as ProgressPanel } from "./ProgressPanel";+export { default as ChatPanel } from "./ChatPanel";+export { default as HTMLViewer } from "./HTMLViewer";+export { default as DebugModal } from "./DebugModal";+export { default as CompletionSummary } from "./CompletionSummary";+diff --git a/web/app/guide/hooks/index.ts b/web/app/guide/hooks/index.tsnew file mode 100644index 000000000..f8f272b9d--- /dev/null+++ b/web/app/guide/hooks/index.ts@@ -0,0 +1,4 @@+export { useGuideSession } from "./useGuideSession";+export { useNotebookSelection } from "./useNotebookSelection";+export { useKaTeXInjection } from "./useKaTeXInjection";+diff --git a/web/app/guide/hooks/useGuideSession.ts b/web/app/guide/hooks/useGuideSession.tsnew file mode 100644index 000000000..f9181c4fc--- /dev/null+++ b/web/app/guide/hooks/useGuideSession.ts@@ -0,0 +1,411 @@+import { useState, useCallback } from "react";+import { apiUrl } from "@/lib/api";+import {+ SessionState,+ ChatMessage,+ KnowledgePoint,+ SelectedRecord,+ INITIAL_SESSION_STATE,+} from "../types";++/**+ * Hook for managing guide session state and API interactions+ */+export function useGuideSession() {+ const [sessionState, setSessionState] =+ useState<SessionState>(INITIAL_SESSION_STATE);+ const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [loadingMessage, setLoadingMessage] = useState("");++ const addLoadingMessage = useCallback((message: string) => {+ const loadingMsg: ChatMessage = {+ id: `loading-${Date.now()}`,+ role: "system",+ content: `⏳ ${message}`,+ timestamp: Date.now(),+ };+ setChatMessages((prev) => [...prev, loadingMsg]);+ return loadingMsg.id;+ }, []);++ const removeLoadingMessage = useCallback((id: string) => {+ setChatMessages((prev) => prev.filter((msg) => msg.id !== id));+ }, []);++ const addChatMessage = useCallback(+ (+ role: "user" | "assistant" | "system",+ content: string,+ id?: string,+ ) => {+ setChatMessages((prev) => [+ ...prev,+ {+ id: id || `${role}-${Date.now()}`,+ role,+ content,+ timestamp: Date.now(),+ },+ ]);+ },+ [],+ );++ const createSession = useCallback(+ async (selectedRecords: Map<string, SelectedRecord>) => {+ if (selectedRecords.size === 0) return;++ setIsLoading(true);+ setLoadingMessage("Analyzing notes and generating learning plan...");+ const loadingId = addLoadingMessage(+ "Analyzing notes and generating learning plan...",+ );++ try {+ const recordsArray = Array.from(selectedRecords.values()).map((r) => ({+ id: r.id,+ title: r.title,+ user_query: r.user_query,+ output: r.output,+ type: r.type,+ }));++ const res = await fetch(apiUrl("/api/v1/guide/create_session"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ records: recordsArray }),+ });+ const data = await res.json();++ removeLoadingMessage(loadingId);+ setIsLoading(false);+ setLoadingMessage("");++ if (data.success) {+ const notebookNames = Array.from(+ new Set(+ Array.from(selectedRecords.values()).map((r) => r.notebookName),+ ),+ );+ const notebookName =+ notebookNames.length === 1+ ? notebookNames[0]+ : `Cross-Notebook (${notebookNames.length} notebooks, ${selectedRecords.size} records)`;++ setSessionState({+ session_id: data.session_id,+ notebook_id: "cross_notebook",+ notebook_name: notebookName,+ knowledge_points: data.knowledge_points || [],+ current_index: -1,+ current_html: "",+ status: "initialized",+ progress: 0,+ summary: "",+ });++ const planMessage = `📚 Learning plan generated with **${data.total_points}** knowledge points:\n\n${data.knowledge_points.map((kp: KnowledgePoint, idx: number) => `${idx + 1}. ${kp.knowledge_title}`).join("\n")}\n\nClick "Start Learning" button above to begin!`;+ setChatMessages([+ {+ id: "plan",+ role: "system",+ content: planMessage,+ timestamp: Date.now(),+ },+ ]);+ } else {+ addChatMessage(+ "system",+ `❌ Failed to create session: ${data.error}`,+ `error-${Date.now()}`,+ );+ }+ } catch (err) {+ removeLoadingMessage(loadingId);+ setIsLoading(false);+ setLoadingMessage("");+ console.error("Failed to create session:", err);+ addChatMessage(+ "system",+ "❌ Failed to create session, please try again later",+ `error-${Date.now()}`,+ );+ }+ },+ [addLoadingMessage, removeLoadingMessage, addChatMessage],+ );++ const startLearning = useCallback(async () => {+ if (!sessionState.session_id) return;++ setIsLoading(true);+ setLoadingMessage("Generating interactive learning page...");+ const loadingId = addLoadingMessage(+ "Generating interactive learning page...",+ );++ try {+ const res = await fetch(apiUrl("/api/v1/guide/start"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_id: sessionState.session_id }),+ });+ const data = await res.json();++ removeLoadingMessage(loadingId);+ setIsLoading(false);+ setLoadingMessage("");++ if (data.success) {+ const htmlContent = data.html || "";+ console.log("Start learning - HTML length:", htmlContent.length);++ setSessionState((prev) => ({+ ...prev,+ current_index: data.current_index,+ current_html: htmlContent,+ status: "learning",+ progress: data.progress || 0,+ }));++ addChatMessage(+ "system",+ data.message || "Starting the first knowledge point",+ `start-${Date.now()}`,+ );+ } else {+ addChatMessage(+ "system",+ `❌ Failed to start learning: ${data.error || "Unknown error"}`,+ `error-${Date.now()}`,+ );+ }+ } catch (err) {+ removeLoadingMessage(loadingId);+ setIsLoading(false);+ setLoadingMessage("");+ console.error("Failed to start learning:", err);+ addChatMessage(+ "system",+ "❌ Failed to start learning, please try again later",+ `error-${Date.now()}`,+ );+ }+ }, [+ sessionState.session_id,+ addLoadingMessage,+ removeLoadingMessage,+ addChatMessage,+ ]);++ const nextKnowledge = useCallback(async () => {+ if (!sessionState.session_id) return;++ setIsLoading(true);+ setLoadingMessage("Generating next knowledge point...");+ const loadingId = addLoadingMessage("Generating next knowledge point...");++ try {+ const res = await fetch(apiUrl("/api/v1/guide/next"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_id: sessionState.session_id }),+ });+ const data = await res.json();++ removeLoadingMessage(loadingId);+ setIsLoading(false);+ setLoadingMessage("");++ if (data.success) {+ if (data.status === "completed") {+ setSessionState((prev) => ({+ ...prev,+ status: "completed",+ summary: data.summary || "",+ progress: 100,+ }));++ addChatMessage(+ "system",+ data.message ||+ "🎉 Congratulations on completing all knowledge points!",+ `complete-${Date.now()}`,+ );+ } else {+ setSessionState((prev) => ({+ ...prev,+ current_index: data.current_index,+ current_html: data.html || "",+ progress: data.progress || 0,+ }));++ addChatMessage(+ "system",+ data.message || "Moving to next knowledge point",+ `next-${Date.now()}`,+ );+ }+ } else {+ addChatMessage(+ "system",+ `❌ Failed to move to next: ${data.error || "Unknown error"}`,+ `error-${Date.now()}`,+ );+ }+ } catch (err) {+ removeLoadingMessage(loadingId);+ setIsLoading(false);+ setLoadingMessage("");+ console.error("Failed to move to next:", err);+ addChatMessage(+ "system",+ "❌ Failed to move to next, please try again later",+ `error-${Date.now()}`,+ );+ }+ }, [+ sessionState.session_id,+ addLoadingMessage,+ removeLoadingMessage,+ addChatMessage,+ ]);++ const sendMessage = useCallback(+ async (message: string) => {+ if (!message.trim() || !sessionState.session_id) return;++ addChatMessage("user", message, `user-${Date.now()}`);+ const loadingId = addLoadingMessage("Thinking...");++ try {+ const res = await fetch(apiUrl("/api/v1/guide/chat"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ session_id: sessionState.session_id,+ message,+ }),+ });+ const data = await res.json();++ removeLoadingMessage(loadingId);++ if (data.success) {+ addChatMessage(+ "assistant",+ data.answer || "",+ `assistant-${Date.now()}`,+ );+ } else {+ addChatMessage(+ "assistant",+ `❌ Error: ${data.error || "Failed to respond"}`,+ `error-${Date.now()}`,+ );+ }+ } catch (err) {+ removeLoadingMessage(loadingId);+ console.error("Failed to send message:", err);+ addChatMessage(+ "assistant",+ "❌ Failed to send message, please try again later",+ `error-${Date.now()}`,+ );+ }+ },+ [+ sessionState.session_id,+ addLoadingMessage,+ removeLoadingMessage,+ addChatMessage,+ ],+ );++ const fixHtml = useCallback(+ async (bugDescription: string) => {+ if (!sessionState.session_id || !bugDescription.trim()) return false;++ const loadingId = addLoadingMessage("Fixing HTML page...");++ try {+ const res = await fetch(apiUrl("/api/v1/guide/fix_html"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ session_id: sessionState.session_id,+ bug_description: bugDescription,+ }),+ });+ const data = await res.json();++ removeLoadingMessage(loadingId);++ if (data.success) {+ setSessionState((prev) => ({+ ...prev,+ current_html: data.html || prev.current_html,+ }));+ addChatMessage(+ "system",+ "✅ HTML page has been fixed!",+ `fix-${Date.now()}`,+ );+ return true;+ } else {+ addChatMessage(+ "system",+ `❌ Fix failed: ${data.error || "Unknown error"}`,+ `error-${Date.now()}`,+ );+ return false;+ }+ } catch (err) {+ removeLoadingMessage(loadingId);+ console.error("Failed to fix HTML:", err);+ addChatMessage(+ "system",+ "❌ Fix failed, please try again later",+ `error-${Date.now()}`,+ );+ return false;+ }+ },+ [+ sessionState.session_id,+ addLoadingMessage,+ removeLoadingMessage,+ addChatMessage,+ ],+ );++ // Computed states+ const canStart =+ sessionState.status === "initialized" &&+ sessionState.knowledge_points.length > 0;+ const canNext =+ sessionState.status === "learning" &&+ sessionState.current_index < sessionState.knowledge_points.length - 1;+ const isCompleted = sessionState.status === "completed";+ const isLastKnowledge =+ sessionState.status === "learning" &&+ sessionState.current_index === sessionState.knowledge_points.length - 1;++ return {+ sessionState,+ chatMessages,+ isLoading,+ loadingMessage,+ canStart,+ canNext,+ isCompleted,+ isLastKnowledge,+ createSession,+ startLearning,+ nextKnowledge,+ sendMessage,+ fixHtml,+ };+}+diff --git a/web/app/guide/hooks/useKaTeXInjection.ts b/web/app/guide/hooks/useKaTeXInjection.tsnew file mode 100644index 000000000..09c479fc7--- /dev/null+++ b/web/app/guide/hooks/useKaTeXInjection.ts@@ -0,0 +1,72 @@+/**+ * Hook for injecting KaTeX support into HTML content+ */+export function useKaTeXInjection() {+ /**+ * Inject KaTeX CSS and JS into HTML if not already present+ */+ const injectKaTeX = (html: string): string => {+ // Check if KaTeX is already included (case-insensitive)+ const htmlLower = html.toLowerCase();+ const hasKaTeX =+ htmlLower.includes("katex.min.css") ||+ htmlLower.includes("katex.min.js") ||+ htmlLower.includes("katex@") ||+ htmlLower.includes("cdn.jsdelivr.net/npm/katex") ||+ htmlLower.includes("unpkg.com/katex");++ if (hasKaTeX) {+ console.log("KaTeX already included in HTML, skipping injection");+ return html;+ }++ // KaTeX CDN links (using version 0.16.9 for compatibility)+ const katexCSS =+ '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">';+ const katexJS =+ '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>';+ const katexAutoRender =+ '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117n7w6ODWgRrA7TlVzRsFtwW3ZxUo8h4w20Z5J3d3xjfcw" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>';++ const katexInjection = ` ${katexCSS}\n ${katexJS}\n ${katexAutoRender}`;++ // Try to inject into </head> section (most common case)+ if (html.includes("</head>")) {+ console.log("Injecting KaTeX before </head> tag");+ return html.replace("</head>", `${katexInjection}\n</head>`);+ }++ // If no </head> tag, try to inject after <head> tag+ if (html.includes("<head>")) {+ console.log("Injecting KaTeX after <head> tag");+ // Use regex to handle <head> with attributes+ return html.replace(/<head([^>]*)>/i, `<head$1>\n${katexInjection}`);+ }++ // If HTML structure exists but no <head>, add it+ if (html.includes("<html")) {+ console.log("Adding <head> section with KaTeX");+ return html.replace(+ /(<html[^>]*>)/i,+ `$1\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n${katexInjection}\n</head>`,+ );+ }++ // If no HTML structure, wrap it with full HTML document+ console.log("Wrapping content with full HTML document including KaTeX");+ return `<!DOCTYPE html>+<html lang="zh">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+${katexInjection}+</head>+<body>+${html}+</body>+</html>`;+ };++ return { injectKaTeX };+}+diff --git a/web/app/guide/hooks/useNotebookSelection.ts b/web/app/guide/hooks/useNotebookSelection.tsnew file mode 100644index 000000000..dbf16a164--- /dev/null+++ b/web/app/guide/hooks/useNotebookSelection.ts@@ -0,0 +1,147 @@+import { useState, useCallback } from "react";+import { apiUrl } from "@/lib/api";+import { Notebook, NotebookRecord, SelectedRecord } from "../types";++/**+ * Hook for managing notebook and record selection+ */+export function useNotebookSelection() {+ const [notebooks, setNotebooks] = useState<Notebook[]>([]);+ const [expandedNotebooks, setExpandedNotebooks] = useState<Set<string>>(+ new Set(),+ );+ const [notebookRecordsMap, setNotebookRecordsMap] = useState<+ Map<string, NotebookRecord[]>+ >(new Map());+ const [selectedRecords, setSelectedRecords] = useState<+ Map<string, SelectedRecord>+ >(new Map());+ const [loadingNotebooks, setLoadingNotebooks] = useState(true);+ const [loadingRecordsFor, setLoadingRecordsFor] = useState<Set<string>>(+ new Set(),+ );++ const fetchNotebooks = useCallback(async () => {+ try {+ const res = await fetch(apiUrl("/api/v1/notebook/list"));+ const data = await res.json();+ const notebooksWithRecords = (data.notebooks || []).filter(+ (nb: Notebook) => nb.record_count > 0,+ );+ setNotebooks(notebooksWithRecords);+ setLoadingNotebooks(false);+ } catch (err) {+ console.error("Failed to fetch notebooks:", err);+ setLoadingNotebooks(false);+ }+ }, []);++ const fetchNotebookRecords = useCallback(+ async (notebookId: string) => {+ if (notebookRecordsMap.has(notebookId)) return;++ setLoadingRecordsFor((prev) => {+ const newSet = new Set(prev);+ newSet.add(notebookId);+ return newSet;+ });+ try {+ const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));+ const data = await res.json();+ setNotebookRecordsMap((prev) =>+ new Map(prev).set(notebookId, data.records || []),+ );+ } catch (err) {+ console.error("Failed to fetch notebook records:", err);+ } finally {+ setLoadingRecordsFor((prev) => {+ const newSet = new Set(prev);+ newSet.delete(notebookId);+ return newSet;+ });+ }+ },+ [notebookRecordsMap],+ );++ const toggleNotebookExpanded = useCallback(+ (notebookId: string) => {+ const notebook = notebooks.find((nb) => nb.id === notebookId);+ if (!notebook) return;++ setExpandedNotebooks((prev) => {+ const newSet = new Set(prev);+ if (newSet.has(notebookId)) {+ newSet.delete(notebookId);+ } else {+ newSet.add(notebookId);+ fetchNotebookRecords(notebookId);+ }+ return newSet;+ });+ },+ [notebooks, fetchNotebookRecords],+ );++ const toggleRecordSelection = useCallback(+ (record: NotebookRecord, notebookId: string, notebookName: string) => {+ setSelectedRecords((prev) => {+ const newMap = new Map(prev);+ if (newMap.has(record.id)) {+ newMap.delete(record.id);+ } else {+ newMap.set(record.id, { ...record, notebookId, notebookName });+ }+ return newMap;+ });+ },+ [],+ );++ const selectAllFromNotebook = useCallback(+ (notebookId: string, notebookName: string) => {+ const records = notebookRecordsMap.get(notebookId) || [];+ setSelectedRecords((prev) => {+ const newMap = new Map(prev);+ records.forEach((r) =>+ newMap.set(r.id, { ...r, notebookId, notebookName }),+ );+ return newMap;+ });+ },+ [notebookRecordsMap],+ );++ const deselectAllFromNotebook = useCallback(+ (notebookId: string) => {+ const records = notebookRecordsMap.get(notebookId) || [];+ const recordIds = new Set(records.map((r) => r.id));+ setSelectedRecords((prev) => {+ const newMap = new Map(prev);+ recordIds.forEach((id) => newMap.delete(id));+ return newMap;+ });+ },+ [notebookRecordsMap],+ );++ const clearAllSelections = useCallback(() => {+ setSelectedRecords(new Map());+ }, []);++ return {+ notebooks,+ expandedNotebooks,+ notebookRecordsMap,+ selectedRecords,+ loadingNotebooks,+ loadingRecordsFor,+ fetchNotebooks,+ toggleNotebookExpanded,+ toggleRecordSelection,+ selectAllFromNotebook,+ deselectAllFromNotebook,+ clearAllSelections,+ };+}+diff --git a/web/app/guide/page.tsx b/web/app/guide/page.tsxindex 8442ce58e..3a30b1e3f 100644--- a/web/app/guide/page.tsx+++ b/web/app/guide/page.tsx@@ -1,793 +1,81 @@"use client";-import { useState, useEffect, useRef } from "react";+import { useState, useEffect } from "react";import {- BookOpen,- MessageSquare,- Send,- Loader2,- ChevronRight,- ChevronDown,- Bug,- CheckCircle2,GraduationCap,- Sparkles,- ArrowRight,- Play,- FileText,+ ChevronRight,ChevronLeft,- X,- Check,- Circle,+ ArrowRight,+ Loader2,} from "lucide-react";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";-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";--interface Notebook {- id: string;- name: string;- description: string;- record_count: number;- color: string;-}-interface NotebookRecord {- id: string;- title: string;- user_query: string;- output: string;- type: string;-}--interface SelectedRecord extends NotebookRecord {- notebookId: string;- notebookName: string;-}--interface KnowledgePoint {- knowledge_title: string;- knowledge_summary: string;- user_difficulty: string;-}--interface ChatMessage {- id: string;- role: "user" | "assistant" | "system";- content: string;- timestamp?: number;-}--interface SessionState {- session_id: string | null;- notebook_id: string | null;- notebook_name: string;- knowledge_points: KnowledgePoint[];- current_index: number;- current_html: string;- status: "idle" | "initialized" | "learning" | "completed";- progress: number;- summary: string;-}+import {+ NotebookSelector,+ ProgressPanel,+ ChatPanel,+ HTMLViewer,+ DebugModal,+ CompletionSummary,+} from "./components";+import { useGuideSession, useNotebookSelection } from "./hooks";export default function GuidePage() {- // Multi-notebook selection (same as ideagen)- const [notebooks, setNotebooks] = useState<Notebook[]>([]);- const [expandedNotebooks, setExpandedNotebooks] = useState<Set<string>>(- new Set(),- );- const [notebookRecordsMap, setNotebookRecordsMap] = useState<- Map<string, NotebookRecord[]>- >(new Map());- const [selectedRecords, setSelectedRecords] = useState<- Map<string, SelectedRecord>- >(new Map()); // recordId -> record with notebook info- const [loadingNotebooks, setLoadingNotebooks] = useState(true);- const [loadingRecordsFor, setLoadingRecordsFor] = useState<Set<string>>(- new Set(),- );-- // Session state- const [sessionState, setSessionState] = useState<SessionState>({- session_id: null,- notebook_id: null,- notebook_name: "",- knowledge_points: [],- current_index: -1,- current_html: "",- status: "idle",- progress: 0,- summary: "",- });-- // Chat state- const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);- const [inputMessage, setInputMessage] = useState("");- const [sendingMessage, setSendingMessage] = useState(false);+ // Notebook selection hook+ const {+ notebooks,+ expandedNotebooks,+ notebookRecordsMap,+ selectedRecords,+ loadingNotebooks,+ loadingRecordsFor,+ fetchNotebooks,+ toggleNotebookExpanded,+ toggleRecordSelection,+ selectAllFromNotebook,+ deselectAllFromNotebook,+ clearAllSelections,+ } = useNotebookSelection();++ // Session management hook+ const {+ sessionState,+ chatMessages,+ isLoading,+ loadingMessage,+ canStart,+ canNext,+ isCompleted,+ isLastKnowledge,+ createSession,+ startLearning,+ nextKnowledge,+ sendMessage,+ fixHtml,+ } = useGuideSession();// UI stateconst [showDebugModal, setShowDebugModal] = useState(false);- const [debugDescription, setDebugDescription] = useState("");- const [fixingHtml, setFixingHtml] = useState(false);-- // Sidebar stateconst [sidebarCollapsed, setSidebarCollapsed] = useState(false);- const [sidebarWide, setSidebarWide] = useState(false); // false: 1:3, true: 3:1- const [isLoading, setIsLoading] = useState(false);- const [loadingMessage, setLoadingMessage] = useState("");-- const chatContainerRef = useRef<HTMLDivElement>(null);- const htmlFrameRef = useRef<HTMLIFrameElement>(null);+ const [sidebarWide, setSidebarWide] = useState(false);- // Load notebooks+ // Load notebooks on mountuseEffect(() => {fetchNotebooks();- }, []);-- // Auto-scroll chat- useEffect(() => {- if (chatContainerRef.current) {- chatContainerRef.current.scrollTo({- top: chatContainerRef.current.scrollHeight,- behavior: "smooth",- });- }- }, [chatMessages]);-- // Helper function to inject KaTeX into HTML if needed- const injectKaTeX = (html: string): string => {- // Check if KaTeX is already included (case-insensitive)- const htmlLower = html.toLowerCase();- const hasKaTeX =- htmlLower.includes("katex.min.css") ||- htmlLower.includes("katex.min.js") ||- htmlLower.includes("katex@") ||- htmlLower.includes("cdn.jsdelivr.net/npm/katex") ||- htmlLower.includes("unpkg.com/katex");-- if (hasKaTeX) {- console.log("KaTeX already included in HTML, skipping injection");- return html;- }-- // KaTeX CDN links (using version 0.16.9 for compatibility)- const katexCSS =- '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">';- const katexJS =- '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>';- const katexAutoRender =- '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117n7w6ODWgRrA7TlVzRsFtwW3ZxUo8h4w20Z5J3d3xjfcw" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>';-- const katexInjection = ` ${katexCSS}\n ${katexJS}\n ${katexAutoRender}`;-- // Try to inject into </head> section (most common case)- if (html.includes("</head>")) {- console.log("Injecting KaTeX before </head> tag");- return html.replace("</head>", `${katexInjection}\n</head>`);- }-- // If no </head> tag, try to inject after <head> tag- if (html.includes("<head>")) {- console.log("Injecting KaTeX after <head> tag");- // Use regex to handle <head> with attributes- return html.replace(/<head([^>]*)>/i, `<head$1>\n${katexInjection}`);- }-- // If HTML structure exists but no <head>, add it- if (html.includes("<html")) {- console.log("Adding <head> section with KaTeX");- return html.replace(- /(<html[^>]*>)/i,- `$1\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n${katexInjection}\n</head>`,- );- }-- // If no HTML structure, wrap it with full HTML document- console.log("Wrapping content with full HTML document including KaTeX");- return `<!DOCTYPE html>-<html lang="zh">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">-${katexInjection}-</head>-<body>-${html}-</body>-</html>`;- };-- // Update HTML iframe- useEffect(() => {- if (!sessionState.current_html) {- return;- }-- // Use setTimeout to ensure DOM is updated- const timer = setTimeout(() => {- if (htmlFrameRef.current) {- const iframe = htmlFrameRef.current;- console.log(- "Updating iframe with HTML, length:",- sessionState.current_html.length,- );-- // Inject KaTeX support if needed- const htmlWithKaTeX = injectKaTeX(sessionState.current_html);-- // Use srcdoc attribute (most reliable method)- try {- iframe.srcdoc = htmlWithKaTeX;- console.log("Iframe srcdoc set successfully with KaTeX support");- } catch (e) {- console.warn("srcdoc not supported, using contentDocument:", e);- // Fallback to contentDocument if srcdoc not supported- const handleLoad = () => {- try {- const doc =- iframe.contentDocument || iframe.contentWindow?.document;- if (doc) {- doc.open();- doc.write(htmlWithKaTeX);- doc.close();- console.log(- "Iframe content written via contentDocument with KaTeX support",- );- }- } catch (err) {- console.error("Failed to write to iframe:", err);- }- };-- if (- iframe.contentDocument &&- iframe.contentDocument.readyState === "complete"- ) {- handleLoad();- } else {- iframe.onload = handleLoad;- }- }- } else {- console.warn("htmlFrameRef.current is null");- }- }, 100);-- return () => clearTimeout(timer);- }, [sessionState.current_html, sessionState.current_index]);-- const addLoadingMessage = (message: string) => {- const loadingMsg: ChatMessage = {- id: `loading-${Date.now()}`,- role: "system",- content: `⏳ ${message}`,- timestamp: Date.now(),- };- setChatMessages((prev) => [...prev, loadingMsg]);- return loadingMsg.id;- };-- const removeLoadingMessage = (id: string) => {- setChatMessages((prev) => prev.filter((msg) => msg.id !== id));- };-- const fetchNotebooks = async () => {- try {- const res = await fetch(apiUrl("/api/v1/notebook/list"));- const data = await res.json();- const notebooksWithRecords = (data.notebooks || []).filter(- (nb: Notebook) => nb.record_count > 0,- );- setNotebooks(notebooksWithRecords);- setLoadingNotebooks(false);- } catch (err) {- console.error("Failed to fetch notebooks:", err);- setLoadingNotebooks(false);- }- };-- const fetchNotebookRecords = async (notebookId: string) => {- if (notebookRecordsMap.has(notebookId)) return; // Already fetched-- setLoadingRecordsFor((prev) => {- const newSet = new Set(prev);- newSet.add(notebookId);- return newSet;- });- try {- const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));- const data = await res.json();- setNotebookRecordsMap((prev) =>- new Map(prev).set(notebookId, data.records || []),- );- } catch (err) {- console.error("Failed to fetch notebook records:", err);- } finally {- setLoadingRecordsFor((prev) => {- const newSet = new Set(prev);- newSet.delete(notebookId);- return newSet;- });- }- };-- const toggleNotebookExpanded = (notebookId: string) => {- const notebook = notebooks.find((nb) => nb.id === notebookId);- if (!notebook) return;-- setExpandedNotebooks((prev) => {- const newSet = new Set(prev);- if (newSet.has(notebookId)) {- newSet.delete(notebookId);- } else {- newSet.add(notebookId);- // Fetch records when expanding- fetchNotebookRecords(notebookId);- }- return newSet;- });- };-- const toggleRecordSelection = (- record: NotebookRecord,- notebookId: string,- notebookName: string,- ) => {- setSelectedRecords((prev) => {- const newMap = new Map(prev);- if (newMap.has(record.id)) {- newMap.delete(record.id);- } else {- newMap.set(record.id, { ...record, notebookId, notebookName });- }- return newMap;- });- };-- const selectAllFromNotebook = (notebookId: string, notebookName: string) => {- const records = notebookRecordsMap.get(notebookId) || [];- setSelectedRecords((prev) => {- const newMap = new Map(prev);- records.forEach((r) =>- newMap.set(r.id, { ...r, notebookId, notebookName }),- );- return newMap;- });- };-- const deselectAllFromNotebook = (notebookId: string) => {- const records = notebookRecordsMap.get(notebookId) || [];- const recordIds = new Set(records.map((r) => r.id));- setSelectedRecords((prev) => {- const newMap = new Map(prev);- recordIds.forEach((id) => newMap.delete(id));- return newMap;- });- };-- const clearAllSelections = () => {- setSelectedRecords(new Map());- };-- const getTypeColor = (type: string) => {- switch (type) {- case "solve":- return "bg-blue-100 text-blue-700 border-blue-200";- case "question":- return "bg-purple-100 text-purple-700 border-purple-200";- case "research":- return "bg-emerald-100 text-emerald-700 border-emerald-200";- case "co_writer":- return "bg-amber-100 text-amber-700 border-amber-200";- default:- return "bg-slate-100 text-slate-700 border-slate-200";- }- };-- const handleCreateSession = async () => {- if (selectedRecords.size === 0) return;-- setIsLoading(true);- setLoadingMessage("Analyzing notes and generating learning plan...");- const loadingId = addLoadingMessage(- "Analyzing notes and generating learning plan...",- );-- try {- // Send records directly for cross-notebook support- const recordsArray = Array.from(selectedRecords.values()).map((r) => ({- id: r.id,- title: r.title,- user_query: r.user_query,- output: r.output,- type: r.type,- }));+ }, [fetchNotebooks]);- const res = await fetch(apiUrl("/api/v1/guide/create_session"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ records: recordsArray }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");-- if (data.success) {- // Get notebook names from selected records- const notebookNames = Array.from(- new Set(- Array.from(selectedRecords.values()).map((r) => r.notebookName),- ),- );- const notebookName =- notebookNames.length === 1- ? notebookNames[0]- : `Cross-Notebook (${notebookNames.length} notebooks, ${selectedRecords.size} records)`;-- setSessionState({- session_id: data.session_id,- notebook_id: "cross_notebook",- notebook_name: notebookName,- knowledge_points: data.knowledge_points || [],- current_index: -1,- current_html: "",- status: "initialized",- progress: 0,- summary: "",- });-- // Add system message: show learning plan- const planMessage = `📚 Learning plan generated with **${data.total_points}** knowledge points:\n\n${data.knowledge_points.map((kp: KnowledgePoint, idx: number) => `${idx + 1}. ${kp.knowledge_title}`).join("\n")}\n\nClick "Start Learning" button above to begin!`;- setChatMessages([- {- id: "plan",- role: "system",- content: planMessage,- timestamp: Date.now(),- },- ]);- } else {- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: `❌ Failed to create session: ${data.error}`,- timestamp: Date.now(),- },- ]);- }- } catch (err) {- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");- console.error("Failed to create session:", err);- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: "❌ Failed to create session, please try again later",- timestamp: Date.now(),- },- ]);- }- };-- const handleStartLearning = async () => {- if (!sessionState.session_id) return;-- setIsLoading(true);- setLoadingMessage("Generating interactive learning page...");- const loadingId = addLoadingMessage(- "Generating interactive learning page...",- );-- try {- const res = await fetch(apiUrl("/api/v1/guide/start"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ session_id: sessionState.session_id }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");-- if (data.success) {- // Ensure HTML exists- const htmlContent = data.html || "";- console.log("Start learning - HTML length:", htmlContent.length);-- setSessionState((prev) => ({- ...prev,- current_index: data.current_index,- current_html: htmlContent,- status: "learning",- progress: data.progress || 0,- }));-- // Add system message- setChatMessages((prev) => [- ...prev,- {- id: `start-${Date.now()}`,- role: "system",- content: data.message || "Starting the first knowledge point",- timestamp: Date.now(),- },- ]);- } else {- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: `❌ Failed to start learning: ${data.error || "Unknown error"}`,- timestamp: Date.now(),- },- ]);- }- } catch (err) {- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");- console.error("Failed to start learning:", err);- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: "❌ Failed to start learning, please try again later",- timestamp: Date.now(),- },- ]);- }- };-- const handleNextKnowledge = async () => {- if (!sessionState.session_id) return;-- setIsLoading(true);- setLoadingMessage("Generating next knowledge point...");- const loadingId = addLoadingMessage("Generating next knowledge point...");-- try {- const res = await fetch(apiUrl("/api/v1/guide/next"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ session_id: sessionState.session_id }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");-- if (data.success) {- if (data.status === "completed") {- // Learning completed- setSessionState((prev) => ({- ...prev,- status: "completed",- summary: data.summary || "",- progress: 100,- }));-- setChatMessages((prev) => [- ...prev,- {- id: `complete-${Date.now()}`,- role: "system",- content:- data.message ||- "🎉 Congratulations on completing all knowledge points!",- timestamp: Date.now(),- },- ]);- } else {- // Move to next knowledge point- setSessionState((prev) => ({- ...prev,- current_index: data.current_index,- current_html: data.html || "",- progress: data.progress || 0,- }));-- setChatMessages((prev) => [- ...prev,- {- id: `next-${Date.now()}`,- role: "system",- content: data.message || "Moving to next knowledge point",- timestamp: Date.now(),- },- ]);- }- } else {- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: `❌ Failed to move to next: ${data.error || "Unknown error"}`,- timestamp: Date.now(),- },- ]);- }- } catch (err) {- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");- console.error("Failed to move to next:", err);- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: "❌ Failed to move to next, please try again later",- timestamp: Date.now(),- },- ]);- }- };-- const handleSendMessage = async () => {- if (!inputMessage.trim() || !sessionState.session_id || sendingMessage)- return;-- const userMsg: ChatMessage = {- id: `user-${Date.now()}`,- role: "user",- content: inputMessage,- timestamp: Date.now(),- };-- setChatMessages((prev) => [...prev, userMsg]);- const userInput = inputMessage;- setInputMessage("");- setSendingMessage(true);-- // Add thinking indicator- const thinkingId = addLoadingMessage("Thinking...");-- try {- const res = await fetch(apiUrl("/api/v1/guide/chat"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- session_id: sessionState.session_id,- message: userInput,- }),- });- const data = await res.json();-- removeLoadingMessage(thinkingId);+ // Calculate widths based on ratio+ const leftWidthPercent = sidebarCollapsed ? 0 : sidebarWide ? 75 : 25;+ const rightWidthPercent = sidebarCollapsed ? 100 : sidebarWide ? 25 : 75;- if (data.success) {- setChatMessages((prev) => [- ...prev,- {- id: `assistant-${Date.now()}`,- role: "assistant",- content: data.answer || "",- timestamp: Date.now(),- },- ]);- } else {- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "assistant",- content: `❌ Error: ${data.error || "Failed to respond"}`,- timestamp: Date.now(),- },- ]);- }- } catch (err) {- removeLoadingMessage(thinkingId);- console.error("Failed to send message:", err);- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "assistant",- content: "❌ Failed to send message, please try again later",- timestamp: Date.now(),- },- ]);- } finally {- setSendingMessage(false);- }+ const handleCreateSession = () => {+ createSession(selectedRecords);};- const handleFixHtml = async () => {- if (!sessionState.session_id || !debugDescription.trim() || fixingHtml)- return;-- setFixingHtml(true);- const loadingId = addLoadingMessage("Fixing HTML page...");-- try {- const res = await fetch(apiUrl("/api/v1/guide/fix_html"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- session_id: sessionState.session_id,- bug_description: debugDescription,- }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);-- if (data.success) {- setSessionState((prev) => ({- ...prev,- current_html: data.html || prev.current_html,- }));- setShowDebugModal(false);- setDebugDescription("");- setChatMessages((prev) => [- ...prev,- {- id: `fix-${Date.now()}`,- role: "system",- content: "✅ HTML page has been fixed!",- timestamp: Date.now(),- },- ]);- } else {- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: `❌ Fix failed: ${data.error || "Unknown error"}`,- timestamp: Date.now(),- },- ]);- }- } catch (err) {- removeLoadingMessage(loadingId);- console.error("Failed to fix HTML:", err);- setChatMessages((prev) => [- ...prev,- {- id: `error-${Date.now()}`,- role: "system",- content: "❌ Fix failed, please try again later",- timestamp: Date.now(),- },- ]);- } finally {- setFixingHtml(false);- }+ const handleFixHtml = async (description: string) => {+ return await fixHtml(description);};- const canStart =- sessionState.status === "initialized" &&- sessionState.knowledge_points.length > 0;- const canNext =- sessionState.status === "learning" &&- sessionState.current_index < sessionState.knowledge_points.length - 1;- const isCompleted = sessionState.status === "completed";- const isLastKnowledge =- sessionState.status === "learning" &&- sessionState.current_index === sessionState.knowledge_points.length - 1;-- // Calculate widths based on ratio- const leftWidthPercent = sidebarCollapsed ? 0 : sidebarWide ? 75 : 25; // 3:1 or 1:3- const rightWidthPercent = sidebarCollapsed ? 100 : sidebarWide ? 25 : 75;-return (<div className="h-screen flex gap-0 p-4 animate-fade-in relative">{/* LEFT PANEL: Chat & Control */}@@ -801,434 +89,44 @@ ${html}maxWidth: sidebarCollapsed ? 0 : `${leftWidthPercent}%`,}}>- {/* Multi-Notebook Selection (same as ideagen) */}+ {/* Multi-Notebook Selection */}{sessionState.status === "idle" && (- <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">- <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">- <h2 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">- <BookOpen className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />- Select Source (Cross-Notebook)- </h2>- {selectedRecords.size > 0 && (- <button- onClick={clearAllSelections}- className="text-xs text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400"- >- Clear ({selectedRecords.size})- </button>- )}- </div>-- <div className="flex-1 overflow-y-auto max-h-[400px]">- {loadingNotebooks ? (- <div className="flex items-center justify-center py-8">- <Loader2 className="w-5 h-5 animate-spin text-indigo-600 dark:text-indigo-400" />- </div>- ) : notebooks.length === 0 ? (- <div className="p-4 text-center text-sm text-slate-400 dark:text-slate-500">- No notebooks with records found- </div>- ) : (- <div className="divide-y divide-slate-100 dark:divide-slate-700">- {notebooks.map((notebook) => {- const isExpanded = expandedNotebooks.has(notebook.id);- const records = notebookRecordsMap.get(notebook.id) || [];- const isLoading = loadingRecordsFor.has(notebook.id);- const selectedFromThis = records.filter((r) =>- selectedRecords.has(r.id),- ).length;-- return (- <div key={notebook.id}>- {/* Notebook Header */}- <div- className="p-3 flex items-center gap-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"- onClick={() => toggleNotebookExpanded(notebook.id)}- >- {isExpanded ? (- <ChevronDown className="w-4 h-4 text-slate-400 dark:text-slate-500" />- ) : (- <ChevronRight className="w-4 h-4 text-slate-400 dark:text-slate-500" />- )}- <div- className="w-3 h-3 rounded-full"- style={{- backgroundColor: notebook.color || "#94a3b8",- }}- />- <span className="flex-1 text-sm font-medium text-slate-700 dark:text-slate-200 truncate">- {notebook.name}- </span>- <span className="text-xs text-slate-400 dark:text-slate-500">- {selectedFromThis > 0 && (- <span className="text-indigo-600 dark:text-indigo-400 font-medium">- {selectedFromThis}/- </span>- )}- {notebook.record_count}- </span>- </div>-- {/* Records List */}- {isExpanded && (- <div className="pl-6 pr-2 pb-2 bg-slate-50/50 dark:bg-slate-800/50">- {isLoading ? (- <div className="flex items-center justify-center py-4">- <Loader2 className="w-4 h-4 animate-spin text-indigo-600 dark:text-indigo-400" />- </div>- ) : records.length === 0 ? (- <div className="py-2 text-xs text-slate-400 dark:text-slate-500 text-center">- No records- </div>- ) : (- <>- <div className="flex gap-2 mb-2">- <button- onClick={(e) => {- e.stopPropagation();- selectAllFromNotebook(- notebook.id,- notebook.name,- );- }}- className="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300"- >- Select All- </button>- <button- onClick={(e) => {- e.stopPropagation();- deselectAllFromNotebook(notebook.id);- }}- className="text-xs text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"- >- Deselect- </button>- </div>- <div className="space-y-1">- {records.map((record) => (- <div- key={record.id}- onClick={(e) => {- e.stopPropagation();- toggleRecordSelection(- record,- notebook.id,- notebook.name,- );- }}- className={`p-2 rounded-lg cursor-pointer transition-all border ${- selectedRecords.has(record.id)- ? "bg-indigo-50 dark:bg-indigo-900/30 border-indigo-200 dark:border-indigo-700"- : "hover:bg-white dark:hover:bg-slate-700 border-transparent hover:border-slate-200 dark:hover:border-slate-600"- }`}- >- <div className="flex items-center gap-2">- <div- className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${- selectedRecords.has(record.id)- ? "bg-indigo-500 border-indigo-500 text-white"- : "border-slate-300 dark:border-slate-500"- }`}- >- {selectedRecords.has(record.id) && (- <Check className="w-2.5 h-2.5" />- )}- </div>- <div className="flex-1 min-w-0">- <span- className={`text-[10px] font-bold uppercase px-1 py-0.5 rounded ${getTypeColor(record.type)}`}- >- {record.type}- </span>- <span className="text-xs text-slate-700 dark:text-slate-200 ml-2 truncate">- {record.title}- </span>- </div>- </div>- </div>- ))}- </div>- </>- )}- </div>- )}- </div>- );- })}- </div>- )}- </div>-- {/* Generate Button */}- <div className="p-3 border-t border-slate-100 dark:border-slate-700">- <button- onClick={handleCreateSession}- disabled={isLoading || selectedRecords.size === 0}- className="w-full px-4 py-2.5 bg-gradient-to-r from-indigo-500 to-purple-500 text-white rounded-xl hover:from-indigo-600 hover:to-purple-600 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 font-medium shadow-md shadow-indigo-500/20"- >- {isLoading ? (- <>- <Loader2 className="w-4 h-4 animate-spin" />- Generating...- </>- ) : (- <>- <Sparkles className="w-4 h-4" />- Generate Learning Plan ({selectedRecords.size} items)- </>- )}- </button>- </div>- </div>+ <NotebookSelector+ notebooks={notebooks}+ expandedNotebooks={expandedNotebooks}+ notebookRecordsMap={notebookRecordsMap}+ selectedRecords={selectedRecords}+ loadingNotebooks={loadingNotebooks}+ loadingRecordsFor={loadingRecordsFor}+ isLoading={isLoading}+ onToggleExpanded={toggleNotebookExpanded}+ onToggleRecord={toggleRecordSelection}+ onSelectAll={selectAllFromNotebook}+ onDeselectAll={deselectAllFromNotebook}+ onClearAll={clearAllSelections}+ onCreateSession={handleCreateSession}+ />)}{/* Progress Bar with Action Buttons */}{sessionState.status !== "idle" && (- <div className="bg-white dark:bg-slate-800 p-4 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700">- <div className="flex items-center justify-between mb-2">- <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">- Learning Progress- </span>- <span className="text-xs text-slate-400 dark:text-slate-500">- {sessionState.progress}%- </span>- </div>- <div className="h-2 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden mb-4">- <div- className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 rounded-full transition-all duration-500"- style={{ width: `${sessionState.progress}%` }}- />- </div>- {sessionState.knowledge_points.length > 0 && (- <p className="text-xs text-slate-400 dark:text-slate-500 mb-4">- Knowledge Point {sessionState.current_index + 1} /{" "}- {sessionState.knowledge_points.length}- </p>- )}-- {/* Action Buttons */}- <div className="flex gap-2">- {canStart && (- <button- onClick={handleStartLearning}- disabled={isLoading}- className="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"- >- {isLoading ? (- <>- <Loader2 className="w-4 h-4 animate-spin" />- Generating...- </>- ) : (- <>- <Play className="w-4 h-4" />- Start Learning- </>- )}- </button>- )}-- {canNext && (- <button- onClick={handleNextKnowledge}- disabled={isLoading}- className="flex-1 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"- >- {isLoading ? (- <>- <Loader2 className="w-4 h-4 animate-spin" />- Loading...- </>- ) : (- <>- <ChevronRight className="w-4 h-4" />- Next- </>- )}- </button>- )}-- {isLastKnowledge && (- <button- onClick={handleNextKnowledge}- disabled={isLoading}- className="flex-1 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"- >- {isLoading ? (- <>- <Loader2 className="w-4 h-4 animate-spin" />- Generating Summary...- </>- ) : (- <>- <CheckCircle2 className="w-4 h-4" />- Complete Learning- </>- )}- </button>- )}- </div>- </div>+ <ProgressPanel+ sessionState={sessionState}+ isLoading={isLoading}+ canStart={canStart}+ canNext={canNext}+ isLastKnowledge={isLastKnowledge}+ onStartLearning={startLearning}+ onNextKnowledge={nextKnowledge}+ />)}{/* Chat Interface */}- <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">- <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">- <MessageSquare className="w-4 h-4" />- Learning Assistant- </div>-- <div- ref={chatContainerRef}- className="flex-1 overflow-y-auto p-4 space-y-4 bg-slate-50/30 dark:bg-slate-800/30"- >- {chatMessages.map((msg) => (- <div- key={msg.id}- className={`flex flex-col ${msg.role === "user" ? "items-end" : "items-start"}`}- >- <div- className={`max-w-[90%] rounded-2xl px-4 py-3 text-sm ${- msg.role === "user"- ? "bg-indigo-600 text-white rounded-tr-none shadow-md shadow-indigo-500/20"- : msg.role === "system" && msg.content.includes("⏳")- ? "bg-amber-50 border border-amber-200 text-amber-900 rounded-tl-none"- : msg.role === "system"- ? "bg-blue-50 border border-blue-200 text-blue-900 rounded-tl-none"- : "bg-white border border-slate-200 text-slate-700 rounded-tl-none shadow-sm"- }`}- >- {msg.role === "system" ? (- <div className="prose prose-sm max-w-none">- <ReactMarkdown- remarkPlugins={[remarkGfm, remarkMath]}- rehypePlugins={[rehypeKatex]}- components={{- table: ({ node, ...props }) => (- <div className="overflow-x-auto my-4 rounded-lg border border-slate-200 shadow-sm">- <table- className="min-w-full divide-y divide-slate-200 text-sm"- {...props}- />- </div>- ),- thead: ({ node, ...props }) => (- <thead className="bg-slate-50" {...props} />- ),- th: ({ node, ...props }) => (- <th- className="px-3 py-2 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"- {...props}- />- ),- tbody: ({ node, ...props }) => (- <tbody- className="divide-y divide-slate-100 bg-white"- {...props}- />- ),- td: ({ node, ...props }) => (- <td- className="px-3 py-2 text-slate-600 border-b border-slate-100"- {...props}- />- ),- tr: ({ node, ...props }) => (- <tr- className="hover:bg-slate-50/50 transition-colors"- {...props}- />- ),- }}- >- {processLatexContent(msg.content)}- </ReactMarkdown>- </div>- ) : msg.role === "assistant" ? (- <div className="prose prose-sm max-w-none prose-slate">- <ReactMarkdown- remarkPlugins={[remarkGfm, remarkMath]}- rehypePlugins={[rehypeKatex]}- components={{- table: ({ node, ...props }) => (- <div className="overflow-x-auto my-4 rounded-lg border border-slate-200 shadow-sm">- <table- className="min-w-full divide-y divide-slate-200 text-sm"- {...props}- />- </div>- ),- thead: ({ node, ...props }) => (- <thead className="bg-slate-50" {...props} />- ),- th: ({ node, ...props }) => (- <th- className="px-3 py-2 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"- {...props}- />- ),- tbody: ({ node, ...props }) => (- <tbody- className="divide-y divide-slate-100 bg-white"- {...props}- />- ),- td: ({ node, ...props }) => (- <td- className="px-3 py-2 text-slate-600 border-b border-slate-100"- {...props}- />- ),- tr: ({ node, ...props }) => (- <tr- className="hover:bg-slate-50/50 transition-colors"- {...props}- />- ),- }}- >- {processLatexContent(msg.content)}- </ReactMarkdown>- </div>- ) : (- <p>{msg.content}</p>- )}- </div>- </div>- ))}- </div>-- {/* Input Area */}- {sessionState.status === "learning" && (- <div className="p-3 bg-white dark:bg-slate-800 border-t border-slate-100 dark:border-slate-700">- <div className="relative flex items-center gap-2">- <input- type="text"- value={inputMessage}- onChange={(e) => setInputMessage(e.target.value)}- onKeyDown={(e) =>- e.key === "Enter" && !e.shiftKey && handleSendMessage()- }- placeholder="Have any questions? Feel free to ask..."- disabled={sendingMessage}- className="flex-1 pl-4 pr-10 py-2.5 bg-slate-100 dark:bg-slate-700 border-transparent focus:bg-white dark:focus:bg-slate-600 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 rounded-xl text-sm text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 transition-all outline-none disabled:opacity-50 disabled:cursor-not-allowed"- />- <button- onClick={handleSendMessage}- disabled={!inputMessage.trim() || sendingMessage}- className="p-2.5 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 active:scale-95 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-indigo-500/20"- >- {sendingMessage ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : (- <Send className="w-4 h-4" />- )}- </button>- </div>- </div>- )}- </div>+ <ChatPanel+ messages={chatMessages}+ isLearning={sessionState.status === "learning"}+ onSendMessage={sendMessage}+ /></div>{/* RIGHT PANEL: Interactive Content */}@@ -1236,7 +134,7 @@ ${html}className="flex flex-col h-full overflow-hidden transition-all duration-300 flex-1 relative"style={{ width: `${rightWidthPercent}%` }}>- {/* Collapse/Expand and Width Toggle Button - positioned relative to right panel */}+ {/* Collapse/Expand and Width Toggle Button */}<div className="absolute top-4 left-4 z-20 flex gap-2"><buttononClick={() => setSidebarCollapsed(!sidebarCollapsed)}@@ -1265,6 +163,8 @@ ${html}</button>)}</div>++ {/* Content based on state */}{sessionState.status === "idle" ? (<div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col items-center justify-center text-slate-300 dark:text-slate-600 p-8"><GraduationCap className="w-24 h-24 text-slate-200 dark:text-slate-600 mb-6" />@@ -1278,92 +178,14 @@ ${html}</p></div>) : isCompleted ? (- <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">- {/* Summary Header */}- <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-emerald-50 to-indigo-50 dark:from-emerald-900/20 dark:to-indigo-900/20 flex items-center justify-between shrink-0">- <h2 className="font-bold text-slate-800 dark:text-slate-100 flex items-center gap-2">- <CheckCircle2 className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />- Learning Summary- </h2>- </div>- {/* Summary Content */}- <div className="flex-1 overflow-y-auto p-8 bg-white dark:bg-slate-800">- <div className="prose prose-slate dark:prose-invert prose-headings:font-bold prose-h1:text-2xl prose-h2:text-xl max-w-none">- <ReactMarkdown- remarkPlugins={[remarkGfm, remarkMath]}- rehypePlugins={[rehypeKatex]}- components={{- table: ({ node, ...props }) => (- <div className="overflow-x-auto my-6 rounded-lg border border-slate-200 shadow-sm">- <table- className="min-w-full divide-y divide-slate-200 text-sm"- {...props}- />- </div>- ),- thead: ({ node, ...props }) => (- <thead className="bg-slate-50" {...props} />- ),- th: ({ node, ...props }) => (- <th- className="px-4 py-3 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"- {...props}- />- ),- tbody: ({ node, ...props }) => (- <tbody- className="divide-y divide-slate-100 bg-white"- {...props}- />- ),- td: ({ node, ...props }) => (- <td- className="px-4 py-3 text-slate-600 border-b border-slate-100"- {...props}- />- ),- tr: ({ node, ...props }) => (- <tr- className="hover:bg-slate-50/50 transition-colors"- {...props}- />- ),- }}- >- {processLatexContent(sessionState.summary || "")}- </ReactMarkdown>- </div>- </div>- </div>+ <CompletionSummary summary={sessionState.summary} />) : sessionState.status === "learning" ? (- <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">- {/* Debug Button */}- <button- onClick={() => setShowDebugModal(true)}- className="absolute top-4 right-4 z-10 p-2 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-lg transition-colors shadow-sm"- title="Fix HTML"- >- <Bug className="w-4 h-4 text-slate-600 dark:text-slate-300" />- </button>-- {/* HTML Content */}- {sessionState.current_html ? (- <iframe- ref={htmlFrameRef}- className="w-full h-full border-0"- title="Interactive Learning Content"- sandbox="allow-scripts allow-same-origin"- key={`html-${sessionState.current_index}-${sessionState.current_html.length}`}- />- ) : (- <div className="flex-1 flex items-center justify-center">- <Loader2 className="w-12 h-12 text-indigo-400 dark:text-indigo-500 animate-spin mb-4" />- <p className="text-slate-500 dark:text-slate-400">- {loadingMessage || "Loading learning content..."}- </p>- </div>- )}- </div>+ <HTMLViewer+ html={sessionState.current_html}+ currentIndex={sessionState.current_index}+ loadingMessage={loadingMessage}+ onOpenDebugModal={() => setShowDebugModal(true)}+ />) : (<div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col items-center justify-center text-slate-300 dark:text-slate-600 p-8"><Loader2 className="w-12 h-12 text-indigo-400 dark:text-indigo-500 animate-spin mb-4" />@@ -1375,69 +197,11 @@ ${html}</div>{/* Debug Modal */}- {showDebugModal && (- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">- <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[500px] animate-in zoom-in-95">- <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">- <h3 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">- <Bug className="w-5 h-5 text-amber-600 dark:text-amber-400" />- Fix HTML Issue- </h3>- <button- onClick={() => {- setShowDebugModal(false);- setDebugDescription("");- }}- className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"- >- <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />- </button>- </div>- <div className="p-6 space-y-4">- <div>- <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">- Issue Description- </label>- <textarea- value={debugDescription}- onChange={(e) => setDebugDescription(e.target.value)}- placeholder="Describe the HTML issue, e.g.: button not clickable, style display error, interaction not working..."- rows={6}- className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 outline-none resize-none"- />- </div>- </div>- <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2">- <button- onClick={() => {- setShowDebugModal(false);- setDebugDescription("");- }}- className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"- >- Cancel- </button>- <button- onClick={handleFixHtml}- disabled={!debugDescription.trim() || fixingHtml}- className="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors disabled:opacity-50 flex items-center gap-2"- >- {fixingHtml ? (- <>- <Loader2 className="w-4 h-4 animate-spin" />- Fixing...- </>- ) : (- <>- <Bug className="w-4 h-4" />- Fix- </>- )}- </button>- </div>- </div>- </div>- )}+ <DebugModal+ isOpen={showDebugModal}+ onClose={() => setShowDebugModal(false)}+ onFix={handleFixHtml}+ /></div>);}diff --git a/web/app/guide/types.ts b/web/app/guide/types.tsnew file mode 100644index 000000000..9bf46082c--- /dev/null+++ b/web/app/guide/types.ts@@ -0,0 +1,76 @@+// Guide page types++export interface Notebook {+ id: string;+ name: string;+ description: string;+ record_count: number;+ color: string;+}++export interface NotebookRecord {+ id: string;+ title: string;+ user_query: string;+ output: string;+ type: string;+}++export interface SelectedRecord extends NotebookRecord {+ notebookId: string;+ notebookName: string;+}++export interface KnowledgePoint {+ knowledge_title: string;+ knowledge_summary: string;+ user_difficulty: string;+}++export interface ChatMessage {+ id: string;+ role: "user" | "assistant" | "system";+ content: string;+ timestamp?: number;+}++export interface SessionState {+ session_id: string | null;+ notebook_id: string | null;+ notebook_name: string;+ knowledge_points: KnowledgePoint[];+ current_index: number;+ current_html: string;+ status: "idle" | "initialized" | "learning" | "completed";+ progress: number;+ summary: string;+}++export const INITIAL_SESSION_STATE: SessionState = {+ session_id: null,+ notebook_id: null,+ notebook_name: "",+ knowledge_points: [],+ current_index: -1,+ current_html: "",+ status: "idle",+ progress: 0,+ summary: "",+};++// Helper to get record type color+export function getTypeColor(type: string): string {+ switch (type) {+ case "solve":+ return "bg-blue-100 text-blue-700 border-blue-200";+ case "question":+ return "bg-purple-100 text-purple-700 border-purple-200";+ case "research":+ return "bg-emerald-100 text-emerald-700 border-emerald-200";+ case "co_writer":+ return "bg-amber-100 text-amber-700 border-amber-200";+ default:+ return "bg-slate-100 text-slate-700 border-slate-200";+ }+}+diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsxindex 48eb8eea4..31e5d2219 100644--- a/web/app/knowledge/page.tsx+++ b/web/app/knowledge/page.tsx@@ -17,6 +17,7 @@ import {RefreshCw,CheckCircle2,AlertCircle,+ Star,} from "lucide-react";import { apiUrl, wsUrl } from "@/lib/api";@@ -691,14 +692,51 @@ export default function KnowledgePage() {<h3 className="font-bold text-slate-900 dark:text-slate-100">{kb.name}</h3>- {kb.is_default && (- <span className="inline-flex items-center px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400 text-[10px] font-bold uppercase tracking-wide border border-blue-100 dark:border-blue-800 mt-1">- Default- </span>- )}+ <div className="flex items-center gap-1.5 mt-1">+ {kb.is_default && (+ <span className="inline-flex items-center px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400 text-[10px] font-bold uppercase tracking-wide border border-blue-100 dark:border-blue-800">+ Default+ </span>+ )}+ {kb.statistics.rag_provider && (+ <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide border ${+ kb.statistics.rag_provider === 'raganything'+ ? 'bg-purple-50 dark:bg-purple-900/40 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800'+ : kb.statistics.rag_provider === 'lightrag'+ ? 'bg-emerald-50 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800'+ : 'bg-amber-50 dark:bg-amber-900/40 text-amber-600 dark:text-amber-400 border-amber-100 dark:border-amber-800'+ }`}>+ {kb.statistics.rag_provider === 'raganything' ? 'RAG-Anything'+ : kb.statistics.rag_provider === 'lightrag' ? 'LightRAG'+ : kb.statistics.rag_provider === 'llamaindex' ? 'LlamaIndex'+ : kb.statistics.rag_provider}+ </span>+ )}+ </div></div></div><div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">+ {!kb.is_default && (+ <button+ onClick={async () => {+ try {+ const res = await fetch(apiUrl(`/api/v1/knowledge/default/${kb.name}`), {+ method: "PUT",+ });+ if (!res.ok) throw new Error("Failed to set default");+ showToast(`Set "${kb.name}" as default knowledge base`, "success");+ fetchKnowledgeBases();+ } catch (err) {+ console.error(err);+ showToast("Failed to set default knowledge base", "error");+ }+ }}+ className="p-2 hover:bg-amber-100 dark:hover:bg-amber-900/40 rounded-lg text-slate-500 dark:text-slate-400 hover:text-amber-600 dark:hover:text-amber-400 transition-colors"+ title="Set as Default"+ >+ <Star className="w-4 h-4" />+ </button>+ )}<buttononClick={() => {setTargetKb(kb.name);diff --git a/web/app/settings/components/ConfigForm.tsx b/web/app/settings/components/ConfigForm.tsxnew file mode 100644index 000000000..62bc330f2--- /dev/null+++ b/web/app/settings/components/ConfigForm.tsx@@ -0,0 +1,513 @@+"use client";++import { useState } from "react";+import {+ Plus,+ Check,+ Loader2,+ Eye,+ EyeOff,+ ChevronDown,+ TestTube,+} from "lucide-react";+import { apiUrl } from "@/lib/api";+import { ConfigItem, ConfigType } from "../types";+import {+ PROVIDER_OPTIONS,+ LOCAL_PROVIDERS,+ LOCAL_PROVIDER_URLS,+ VOICE_OPTIONS,+ getEnvVarForBaseUrl,+ getEnvVarForApiKey,+} from "../constants";++interface ConfigFormProps {+ configType: ConfigType;+ showDimensions: boolean;+ showVoice: boolean;+ isSearchConfig: boolean;+ editConfig?: ConfigItem | null;+ onSuccess: () => void;+ onCancel: () => void;+}++export default function ConfigForm({+ configType,+ showDimensions,+ showVoice,+ isSearchConfig,+ editConfig,+ onSuccess,+ onCancel,+}: ConfigFormProps) {+ const isEditMode = !!editConfig;+ const [saving, setSaving] = useState(false);+ const [testing, setTesting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [testResult, setTestResult] = useState<{+ success: boolean;+ message: string;+ } | null>(null);++ // Helper to check if a value uses env reference format+ const isEnvReference = (value: any): boolean => {+ return !!(value && typeof value === "object" && "use_env" in value);+ };++ // Helper to get display value+ const getDisplayValue = (value: any): string => {+ if (isEnvReference(value)) return "";+ return typeof value === "string" ? value : "";+ };++ // Check initial env reference states+ const initialUseEnvBaseUrl = editConfig+ ? isEnvReference(editConfig.base_url)+ : false;+ const initialUseEnvApiKey = editConfig+ ? isEnvReference(editConfig.api_key)+ : false;++ // Form state+ const [name, setName] = useState(editConfig?.name || "");+ const [provider, setProvider] = useState(+ editConfig?.provider || PROVIDER_OPTIONS[configType][0],+ );+ const [baseUrl, setBaseUrl] = useState(+ editConfig ? getDisplayValue(editConfig.base_url) : "",+ );+ const [useEnvBaseUrl, setUseEnvBaseUrl] =+ useState<boolean>(initialUseEnvBaseUrl);+ const [apiKey, setApiKey] = useState("");+ const [useEnvApiKey, setUseEnvApiKey] =+ useState<boolean>(initialUseEnvApiKey);+ const [showApiKey, setShowApiKey] = useState(false);+ const [model, setModel] = useState(editConfig?.model || "");+ const [dimensions, setDimensions] = useState(editConfig?.dimensions || 3072);+ const [voice, setVoice] = useState(editConfig?.voice || "alloy");++ const isLocalProvider = LOCAL_PROVIDERS.includes(provider);++ const handleProviderChange = (newProvider: string) => {+ setProvider(newProvider);+ if (+ LOCAL_PROVIDERS.includes(newProvider) &&+ LOCAL_PROVIDER_URLS[newProvider]+ ) {+ setBaseUrl(LOCAL_PROVIDER_URLS[newProvider]);+ setUseEnvBaseUrl(false);+ setUseEnvApiKey(false);+ setApiKey("");+ }+ };++ const handleTestConnection = async () => {+ if (isSearchConfig) return;++ if (!useEnvBaseUrl && !baseUrl) {+ setTestResult({+ success: false,+ message: "Base URL is required for testing",+ });+ return;+ }+ if (!isLocalProvider && !useEnvApiKey && !apiKey) {+ setTestResult({+ success: false,+ message: "API Key is required for cloud providers",+ });+ return;+ }+ if (!model) {+ setTestResult({ success: false, message: "Model name is required" });+ return;+ }+ if (configType === "embedding" && !dimensions) {+ setTestResult({+ success: false,+ message: "Dimensions is required for embedding models",+ });+ return;+ }++ setTesting(true);+ setTestResult(null);++ try {+ const res = await fetch(apiUrl(`/api/v1/config/${configType}/test`), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ provider,+ base_url: useEnvBaseUrl+ ? { use_env: getEnvVarForBaseUrl(configType) }+ : baseUrl,+ api_key: isLocalProvider+ ? ""+ : useEnvApiKey+ ? { use_env: getEnvVarForApiKey(configType) }+ : apiKey,+ model,+ ...(configType === "embedding"+ ? { dimensions: Number(dimensions) }+ : {}),+ ...(configType === "tts" && voice ? { voice } : {}),+ }),+ });+ const data = await res.json();+ setTestResult({+ success: data.success ?? false,+ message:+ data.message ||+ (data.success ? "Connection successful" : "Connection failed"),+ });+ } catch (e: any) {+ setTestResult({+ success: false,+ message: e?.message || "Connection test failed - network error",+ });+ } finally {+ setTesting(false);+ }+ };++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ setSaving(true);+ setError(null);++ try {+ const payload: Record<string, any> = {+ name,+ provider,+ api_key: isLocalProvider+ ? apiKey || ""+ : useEnvApiKey+ ? { use_env: getEnvVarForApiKey(configType) }+ : apiKey,+ };++ if (!isSearchConfig) {+ payload.base_url = useEnvBaseUrl+ ? { use_env: getEnvVarForBaseUrl(configType) }+ : baseUrl;+ payload.model = model;+ }++ if (showDimensions) {+ payload.dimensions = dimensions;+ }++ if (showVoice) {+ payload.voice = voice;+ }++ const url = isEditMode+ ? apiUrl(`/api/v1/config/${configType}/${editConfig.id}`)+ : apiUrl(`/api/v1/config/${configType}`);+ const method = isEditMode ? "PUT" : "POST";++ const res = await fetch(url, {+ method,+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });++ if (res.ok) {+ onSuccess();+ } else {+ const data = await res.json();+ setError(+ data.detail ||+ `Failed to ${isEditMode ? "update" : "add"} configuration`,+ );+ }+ } catch (e) {+ setError(`Failed to ${isEditMode ? "update" : "add"} configuration`);+ } finally {+ setSaving(false);+ }+ };++ return (+ <form+ onSubmit={handleSubmit}+ className="mb-6 p-4 rounded-xl border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/20"+ >+ <h3 className="font-medium text-slate-900 dark:text-slate-100 mb-4">+ {isEditMode+ ? `Edit Configuration: ${editConfig.name}`+ : "Add New Configuration"}+ </h3>++ {error && (+ <div className="mb-4 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 text-sm border border-red-200 dark:border-red-800">+ {error}+ </div>+ )}++ {testResult && (+ <div+ className={`mb-4 p-3 rounded-lg text-sm ${+ testResult.success+ ? "bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800"+ : "bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800"+ }`}+ >+ {testResult.message}+ </div>+ )}++ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ {/* Name */}+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Name+ </label>+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ required+ placeholder="My Configuration"+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ />+ </div>++ {/* Provider */}+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Provider+ </label>+ <div className="relative">+ <select+ value={provider}+ onChange={(e) => handleProviderChange(e.target.value)}+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm appearance-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ >+ {PROVIDER_OPTIONS[configType].map((p) => (+ <option key={p} value={p}>+ {p}+ {LOCAL_PROVIDERS.includes(p) ? " (local)" : ""}+ </option>+ ))}+ </select>+ <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />+ </div>+ </div>++ {/* Base URL (not for search) */}+ {!isSearchConfig && (+ <div className="md:col-span-2">+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Base URL+ {useEnvBaseUrl && (+ <span className="ml-2 text-xs font-normal text-blue-500">+ (using ${getEnvVarForBaseUrl(configType)})+ </span>+ )}+ </label>+ <div className="flex items-center gap-3">+ <div className="flex-1">+ <input+ type="text"+ value={useEnvBaseUrl ? "" : baseUrl}+ onChange={(e) => setBaseUrl(e.target.value)}+ disabled={useEnvBaseUrl}+ placeholder={+ useEnvBaseUrl+ ? `Using ${getEnvVarForBaseUrl(configType)} from .env`+ : "https://api.openai.com/v1"+ }+ className={`w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${+ useEnvBaseUrl+ ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic"+ : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600"+ }`}+ />+ </div>+ <label className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400 whitespace-nowrap">+ <input+ type="checkbox"+ checked={useEnvBaseUrl}+ onChange={(e) => {+ setUseEnvBaseUrl(e.target.checked);+ if (e.target.checked) setBaseUrl("");+ }}+ className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"+ />+ Use .env+ </label>+ </div>+ </div>+ )}++ {/* API Key */}+ <div className="md:col-span-2">+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ API Key+ {isLocalProvider ? (+ <span className="ml-2 text-xs font-normal text-slate-400">+ (optional for local providers)+ </span>+ ) : useEnvApiKey ? (+ <span className="ml-2 text-xs font-normal text-blue-500">+ (using ${getEnvVarForApiKey(configType)})+ </span>+ ) : null}+ </label>+ <div className="flex items-center gap-3">+ <div className="flex-1 relative">+ <input+ type={showApiKey ? "text" : "password"}+ value={useEnvApiKey ? "" : apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ disabled={useEnvApiKey}+ placeholder={+ isLocalProvider+ ? "Not required"+ : useEnvApiKey+ ? `Using ${getEnvVarForApiKey(configType)} from .env`+ : "sk-..."+ }+ className={`w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${+ useEnvApiKey+ ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic"+ : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600"+ }`}+ />+ {!useEnvApiKey && (+ <button+ type="button"+ onClick={() => setShowApiKey(!showApiKey)}+ className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"+ >+ {showApiKey ? (+ <EyeOff className="w-4 h-4" />+ ) : (+ <Eye className="w-4 h-4" />+ )}+ </button>+ )}+ </div>+ {!isLocalProvider && (+ <label className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400 whitespace-nowrap">+ <input+ type="checkbox"+ checked={useEnvApiKey}+ onChange={(e) => {+ setUseEnvApiKey(e.target.checked);+ if (e.target.checked) setApiKey("");+ }}+ className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"+ />+ Use .env+ </label>+ )}+ </div>+ </div>++ {/* Model (not for search) */}+ {!isSearchConfig && (+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Model+ </label>+ <input+ type="text"+ value={model}+ onChange={(e) => setModel(e.target.value)}+ required+ placeholder="gpt-4o"+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ />+ </div>+ )}++ {/* Dimensions (embedding only) */}+ {showDimensions && (+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Dimensions+ </label>+ <input+ type="number"+ value={dimensions}+ onChange={(e) => setDimensions(parseInt(e.target.value))}+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ />+ </div>+ )}++ {/* Voice (TTS only) */}+ {showVoice && (+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Voice+ </label>+ <div className="relative">+ <select+ value={voice}+ onChange={(e) => setVoice(e.target.value)}+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm appearance-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ >+ {VOICE_OPTIONS.map((v) => (+ <option key={v} value={v}>+ {v}+ </option>+ ))}+ </select>+ <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />+ </div>+ </div>+ )}+ </div>++ {/* Actions */}+ <div className="flex justify-between items-center mt-4">+ <div>+ {!isSearchConfig && (+ <button+ type="button"+ onClick={handleTestConnection}+ disabled={testing || (!baseUrl && !useEnvBaseUrl)}+ className="flex items-center gap-2 px-4 py-2 text-sm text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 rounded-lg transition-colors"+ >+ {testing ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ <TestTube className="w-4 h-4" />+ )}+ Test Connection+ </button>+ )}+ </div>++ <div className="flex gap-3">+ <button+ type="button"+ onClick={onCancel}+ className="px-4 py-2 text-sm text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"+ >+ Cancel+ </button>+ <button+ type="submit"+ disabled={saving}+ className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg text-sm font-medium transition-colors"+ >+ {saving ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : isEditMode ? (+ <Check className="w-4 h-4" />+ ) : (+ <Plus className="w-4 h-4" />+ )}+ {isEditMode ? "Save Changes" : "Add Configuration"}+ </button>+ </div>+ </div>+ </form>+ );+}+diff --git a/web/app/settings/components/ConfigTab.tsx b/web/app/settings/components/ConfigTab.tsxnew file mode 100644index 000000000..943406230--- /dev/null+++ b/web/app/settings/components/ConfigTab.tsx@@ -0,0 +1,279 @@+"use client";++import { useState, useEffect } from "react";+import { Plus, Trash2, Loader2, Pencil } from "lucide-react";+import { apiUrl } from "@/lib/api";+import { ConfigItem, ConfigType } from "../types";+import ConfigForm from "./ConfigForm";++interface ConfigTabProps {+ configType: ConfigType;+ title: string;+ description: string;+ onUpdate: () => void;+ showDimensions?: boolean;+ showVoice?: boolean;+ isSearchConfig?: boolean;+}++export default function ConfigTab({+ configType,+ title,+ description,+ onUpdate,+ showDimensions = false,+ showVoice = false,+ isSearchConfig = false,+}: ConfigTabProps) {+ const [configs, setConfigs] = useState<ConfigItem[]>([]);+ const [loading, setLoading] = useState(true);+ const [showAddForm, setShowAddForm] = useState(false);+ const [editingConfig, setEditingConfig] = useState<ConfigItem | null>(null);+ const [testing, setTesting] = useState<string | null>(null);+ const [testResult, setTestResult] = useState<{+ success: boolean;+ message: string;+ } | null>(null);++ useEffect(() => {+ loadConfigs();+ }, [configType]);++ const loadConfigs = async () => {+ try {+ const res = await fetch(apiUrl(`/api/v1/config/${configType}`));+ if (res.ok) {+ const data = await res.json();+ setConfigs(data.configs || []);+ }+ } catch (e) {+ console.error(`Failed to load ${configType} configs:`, e);+ } finally {+ setLoading(false);+ }+ };++ const setActive = async (configId: string) => {+ try {+ const res = await fetch(+ apiUrl(`/api/v1/config/${configType}/${configId}/active`),+ {+ method: "POST",+ },+ );+ if (res.ok) {+ loadConfigs();+ onUpdate();+ }+ } catch (e) {+ console.error("Failed to set active config:", e);+ }+ };++ const deleteConfig = async (configId: string) => {+ if (!confirm("Are you sure you want to delete this configuration?")) return;++ try {+ const res = await fetch(+ apiUrl(`/api/v1/config/${configType}/${configId}`),+ {+ method: "DELETE",+ },+ );+ if (res.ok) {+ loadConfigs();+ onUpdate();+ }+ } catch (e) {+ console.error("Failed to delete config:", e);+ }+ };++ const testConnection = async (config: ConfigItem) => {+ if (isSearchConfig) return;++ setTesting(config.id);+ setTestResult(null);++ try {+ const res = await fetch(+ apiUrl(`/api/v1/config/${configType}/${config.id}/test`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ },+ );+ const data = await res.json();+ setTestResult(data);+ } catch (e) {+ setTestResult({ success: false, message: "Connection test failed" });+ } finally {+ setTesting(null);+ }+ };++ if (loading) {+ return (+ <div className="p-8 flex justify-center">+ <Loader2 className="w-6 h-6 animate-spin text-blue-500" />+ </div>+ );+ }++ return (+ <div className="p-6">+ {/* Header */}+ <div className="flex items-center justify-between mb-6">+ <div>+ <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">+ {title}+ </h2>+ <p className="text-sm text-slate-500 dark:text-slate-400">+ {description}+ </p>+ </div>+ <button+ onClick={() => setShowAddForm(!showAddForm)}+ className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"+ >+ <Plus className="w-4 h-4" />+ Add Configuration+ </button>+ </div>++ {/* Add/Edit Form */}+ {(showAddForm || editingConfig) && (+ <ConfigForm+ configType={configType}+ showDimensions={showDimensions}+ showVoice={showVoice}+ isSearchConfig={isSearchConfig}+ editConfig={editingConfig}+ onSuccess={() => {+ setShowAddForm(false);+ setEditingConfig(null);+ loadConfigs();+ onUpdate();+ }}+ onCancel={() => {+ setShowAddForm(false);+ setEditingConfig(null);+ }}+ />+ )}++ {/* Test Result */}+ {testResult && (+ <div+ className={`mb-4 p-3 rounded-lg text-sm ${+ testResult.success+ ? "bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800"+ : "bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800"+ }`}+ >+ {testResult.message}+ </div>+ )}++ {/* Configuration List */}+ <div className="space-y-3">+ {configs.map((config) => (+ <div+ key={config.id}+ className={`p-4 rounded-xl border transition-all ${+ config.is_active+ ? "border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20"+ : "border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50"+ }`}+ >+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ {config.is_active && (+ <div className="w-2 h-2 rounded-full bg-blue-500" />+ )}+ <div>+ <div className="flex items-center gap-2">+ <span className="font-medium text-slate-900 dark:text-slate-100">+ {config.name}+ </span>+ {config.is_default && (+ <span className="px-2 py-0.5 text-xs bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-400 rounded">+ Default+ </span>+ )}+ {config.is_active && (+ <span className="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 rounded">+ Active+ </span>+ )}+ </div>+ <div className="flex items-center gap-3 mt-1 text-sm text-slate-500 dark:text-slate-400">+ <span>Provider: {config.provider}</span>+ {config.model && <span>Model: {config.model}</span>}+ {showDimensions && config.dimensions && (+ <span>Dimensions: {config.dimensions}</span>+ )}+ {showVoice && config.voice && (+ <span>Voice: {config.voice}</span>+ )}+ </div>+ </div>+ </div>+ <div className="flex items-center gap-2">+ {!config.is_active && (+ <button+ onClick={() => setActive(config.id)}+ className="px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors"+ >+ Set Active+ </button>+ )}+ {!isSearchConfig && (+ <button+ onClick={() => testConnection(config)}+ disabled={testing === config.id}+ className="px-3 py-1.5 text-sm text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"+ >+ {testing === config.id ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ "Test"+ )}+ </button>+ )}+ {!config.is_default && (+ <button+ onClick={() => {+ setEditingConfig(config);+ setShowAddForm(false);+ }}+ className="p-1.5 text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"+ title="Edit"+ >+ <Pencil className="w-4 h-4" />+ </button>+ )}+ {!config.is_default && (+ <button+ onClick={() => deleteConfig(config.id)}+ className="p-1.5 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"+ title="Delete"+ >+ <Trash2 className="w-4 h-4" />+ </button>+ )}+ </div>+ </div>+ </div>+ ))}++ {configs.length === 0 && (+ <div className="text-center py-8 text-slate-500 dark:text-slate-400">+ No configurations found. Add one to get started.+ </div>+ )}+ </div>+ </div>+ );+}+diff --git a/web/app/settings/components/OverviewTab.tsx b/web/app/settings/components/OverviewTab.tsxnew file mode 100644index 000000000..d26c2947e--- /dev/null+++ b/web/app/settings/components/OverviewTab.tsx@@ -0,0 +1,158 @@+"use client";++import {+ Brain,+ Database,+ Volume2,+ Search,+ Check,+ AlertCircle,+ Server,+ RefreshCw,+} from "lucide-react";+import { FullStatus, PortsInfo, ConfigType } from "../types";++interface OverviewTabProps {+ status: FullStatus | null;+ ports: PortsInfo | null;+ onRefresh: () => void;+}++const services: {+ key: ConfigType;+ label: string;+ icon: typeof Brain;+ color: string;+}[] = [+ { key: "llm", label: "LLM", icon: Brain, color: "purple" },+ { key: "embedding", label: "Embedding", icon: Database, color: "indigo" },+ { key: "tts", label: "TTS", icon: Volume2, color: "emerald" },+ { key: "search", label: "Search", icon: Search, color: "amber" },+];++export default function OverviewTab({+ status,+ ports,+ onRefresh,+}: OverviewTabProps) {+ return (+ <div className="p-6 space-y-6">+ {/* Refresh Button */}+ <div className="flex justify-end">+ <button+ onClick={onRefresh}+ className="flex items-center gap-2 px-3 py-1.5 text-sm text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"+ >+ <RefreshCw className="w-4 h-4" />+ Refresh+ </button>+ </div>++ {/* Service Status Cards */}+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ {services.map((service) => {+ const s = status?.[service.key];+ const Icon = service.icon;+ const isConfigured = s?.configured;++ return (+ <div+ key={service.key}+ className={`p-4 rounded-xl border ${+ isConfigured+ ? "border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-900/20"+ : "border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50"+ }`}+ >+ <div className="flex items-start justify-between">+ <div className="flex items-center gap-3">+ <div+ className={`p-2 rounded-lg ${+ isConfigured+ ? "bg-green-100 dark:bg-green-800/50"+ : "bg-slate-100 dark:bg-slate-700"+ }`}+ >+ <Icon+ className={`w-5 h-5 ${+ isConfigured+ ? "text-green-600 dark:text-green-400"+ : "text-slate-400"+ }`}+ />+ </div>+ <div>+ <h3 className="font-semibold text-slate-900 dark:text-slate-100">+ {service.label}+ </h3>+ <p className="text-sm text-slate-500 dark:text-slate-400">+ {s?.active_config_name || "Not configured"}+ </p>+ </div>+ </div>+ {isConfigured ? (+ <Check className="w-5 h-5 text-green-500" />+ ) : (+ <AlertCircle className="w-5 h-5 text-slate-400" />+ )}+ </div>+ {s?.model && (+ <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-700">+ <div className="flex items-center gap-2 text-sm">+ <span className="text-slate-500 dark:text-slate-400">+ Model:+ </span>+ <span className="font-mono text-slate-700 dark:text-slate-300">+ {s.model}+ </span>+ </div>+ {s.provider && (+ <div className="flex items-center gap-2 text-sm mt-1">+ <span className="text-slate-500 dark:text-slate-400">+ Provider:+ </span>+ <span className="text-slate-700 dark:text-slate-300">+ {s.provider}+ </span>+ </div>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>++ {/* Port Information */}+ {ports && (+ <div className="p-4 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50">+ <div className="flex items-center gap-2 mb-3">+ <Server className="w-5 h-5 text-slate-400" />+ <h3 className="font-semibold text-slate-900 dark:text-slate-100">+ Port Configuration+ </h3>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div>+ <span className="text-sm text-slate-500 dark:text-slate-400">+ Backend Port+ </span>+ <p className="font-mono text-lg text-slate-700 dark:text-slate-300">+ {ports.backend_port}+ </p>+ </div>+ <div>+ <span className="text-sm text-slate-500 dark:text-slate-400">+ Frontend Port+ </span>+ <p className="font-mono text-lg text-slate-700 dark:text-slate-300">+ {ports.frontend_port}+ </p>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}+diff --git a/web/app/settings/components/index.ts b/web/app/settings/components/index.tsnew file mode 100644index 000000000..1e48bc750--- /dev/null+++ b/web/app/settings/components/index.ts@@ -0,0 +1,4 @@+export { default as OverviewTab } from "./OverviewTab";+export { default as ConfigTab } from "./ConfigTab";+export { default as ConfigForm } from "./ConfigForm";+diff --git a/web/app/settings/constants.ts b/web/app/settings/constants.tsnew file mode 100644index 000000000..7deb899eb--- /dev/null+++ b/web/app/settings/constants.ts@@ -0,0 +1,76 @@+// Settings page constants++import { ConfigType } from "./types";++// Language options+export const LANGUAGE_OPTIONS = [+ { value: "en" as const, label: "English" },+ { value: "zh" as const, label: "中文" },+];++// Provider options - Cloud services first, then local deployments+export const PROVIDER_OPTIONS: Record<ConfigType, string[]> = {+ llm: [+ // Cloud providers+ "openai",+ "anthropic",+ "azure_openai",+ "deepseek",+ "openrouter",+ // Local providers+ "ollama",+ "lm_studio",+ "vllm",+ "llama_cpp",+ ],+ embedding: [+ // Cloud providers+ "openai",+ "azure_openai",+ "jina",+ "cohere",+ "huggingface",+ "google",+ // Local providers+ "ollama",+ "lm_studio",+ ],+ tts: ["openai", "azure_openai"],+ search: ["perplexity", "tavily", "exa", "jina", "serper", "baidu"],+};++// Local providers that don't require API keys+export const LOCAL_PROVIDERS = ["ollama", "lm_studio", "vllm", "llama_cpp"];++// Default base URLs for local providers+export const LOCAL_PROVIDER_URLS: Record<string, string> = {+ ollama: "http://localhost:11434/v1",+ lm_studio: "http://localhost:1234/v1",+ vllm: "http://localhost:8000/v1",+ llama_cpp: "http://localhost:8080/v1",+};++// Voice options for TTS+export const VOICE_OPTIONS = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];++// Helper functions to get env var names+export function getEnvVarForBaseUrl(configType: ConfigType): string {+ const mapping: Record<ConfigType, string> = {+ llm: "LLM_HOST",+ embedding: "EMBEDDING_HOST",+ tts: "TTS_URL",+ search: "SEARCH_PROVIDER",+ };+ return mapping[configType];+}++export function getEnvVarForApiKey(configType: ConfigType): string {+ const mapping: Record<ConfigType, string> = {+ llm: "LLM_API_KEY",+ embedding: "EMBEDDING_API_KEY",+ tts: "TTS_API_KEY",+ search: "SEARCH_API_KEY",+ };+ return mapping[configType];+}+diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsxindex 34c78ff61..359cef8f4 100644--- a/web/app/settings/page.tsx+++ b/web/app/settings/page.tsx@@ -7,121 +7,19 @@ import {Database,Volume2,Search,- Plus,- Trash2,- Check,Loader2,- AlertCircle,- Server,- Eye,- EyeOff,- RefreshCw,- ChevronDown,Sun,Moon,Globe,- Pencil,- TestTube,} from "lucide-react";import { apiUrl } from "@/lib/api";import { useGlobal } from "@/context/GlobalContext";-import { getTranslation } from "@/lib/i18n";--// Language options-const LANGUAGE_OPTIONS = [- { value: "en" as const, label: "English" },- { value: "zh" as const, label: "中文" },-];--// Types-interface ConfigItem {- id: string;- name: string;- provider: string;- base_url?: string;- api_key?: string;- model?: string;- dimensions?: number;- voice?: string;- api_version?: string;- is_default?: boolean;- is_active?: boolean;-}--interface ConfigStatus {- configured: boolean;- active_config_id: string;- active_config_name: string;- model: string | null;- provider: string | null;- env_configured: Record<string, boolean>;- total_configs: number;-}--interface FullStatus {- llm: ConfigStatus;- embedding: ConfigStatus;- tts: ConfigStatus;- search: ConfigStatus;-}--interface PortsInfo {- backend_port: number;- frontend_port: number;-}--type ConfigType = "llm" | "embedding" | "tts" | "search";-type TabType = "overview" | ConfigType;--// Provider options-// Provider options - Cloud services first, then local deployments-const PROVIDER_OPTIONS: Record<ConfigType, string[]> = {- llm: [- // Cloud providers- "openai",- "anthropic",- "azure_openai",- "deepseek",- "openrouter",- // Local providers- "ollama",- "lm_studio",- "vllm",- "llama_cpp",- ],- embedding: [- // Cloud providers- "openai",- "azure_openai",- "jina",- "cohere",- "huggingface",- "google",- // Local providers- "ollama",- "lm_studio",- ],- tts: ["openai", "azure_openai"],- search: ["perplexity", "tavily", "exa", "jina", "serper", "baidu"],-};--// Local providers that don't require API keys-const LOCAL_PROVIDERS = ["ollama", "lm_studio", "vllm", "llama_cpp"];--// Default base URLs for local providers-const LOCAL_PROVIDER_URLS: Record<string, string> = {- ollama: "http://localhost:11434/v1",- lm_studio: "http://localhost:1234/v1",- vllm: "http://localhost:8000/v1",- llama_cpp: "http://localhost:8080/v1",-};--// Voice options for TTS-const VOICE_OPTIONS = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];+import { OverviewTab, ConfigTab } from "./components";+import { FullStatus, PortsInfo, TabType } from "./types";+import { LANGUAGE_OPTIONS } from "./constants";export default function SettingsPage() {const { uiSettings, updateTheme, updateLanguage } = useGlobal();- const t = (key: string) => getTranslation(uiSettings.language, key);const [activeTab, setActiveTab] = useState<TabType>("overview");const [status, setStatus] = useState<FullStatus | null>(null);@@ -336,940 +234,3 @@ export default function SettingsPage() {</div>);}--// Overview Tab Component-function OverviewTab({- status,- ports,- onRefresh,-}: {- status: FullStatus | null;- ports: PortsInfo | null;- onRefresh: () => void;-}) {- const services = [- { key: "llm" as const, label: "LLM", icon: Brain, color: "purple" },- {- key: "embedding" as const,- label: "Embedding",- icon: Database,- color: "indigo",- },- { key: "tts" as const, label: "TTS", icon: Volume2, color: "emerald" },- { key: "search" as const, label: "Search", icon: Search, color: "amber" },- ];-- return (- <div className="p-6 space-y-6">- {/* Refresh Button */}- <div className="flex justify-end">- <button- onClick={onRefresh}- className="flex items-center gap-2 px-3 py-1.5 text-sm text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"- >- <RefreshCw className="w-4 h-4" />- Refresh- </button>- </div>-- {/* Service Status Cards */}- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- {services.map((service) => {- const s = status?.[service.key];- const Icon = service.icon;- const isConfigured = s?.configured;-- return (- <div- key={service.key}- className={`p-4 rounded-xl border ${- isConfigured- ? "border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-900/20"- : "border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50"- }`}- >- <div className="flex items-start justify-between">- <div className="flex items-center gap-3">- <div- className={`p-2 rounded-lg ${- isConfigured- ? "bg-green-100 dark:bg-green-800/50"- : "bg-slate-100 dark:bg-slate-700"- }`}- >- <Icon- className={`w-5 h-5 ${- isConfigured- ? "text-green-600 dark:text-green-400"- : "text-slate-400"- }`}- />- </div>- <div>- <h3 className="font-semibold text-slate-900 dark:text-slate-100">- {service.label}- </h3>- <p className="text-sm text-slate-500 dark:text-slate-400">- {s?.active_config_name || "Not configured"}- </p>- </div>- </div>- {isConfigured ? (- <Check className="w-5 h-5 text-green-500" />- ) : (- <AlertCircle className="w-5 h-5 text-slate-400" />- )}- </div>- {s?.model && (- <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-700">- <div className="flex items-center gap-2 text-sm">- <span className="text-slate-500 dark:text-slate-400">- Model:- </span>- <span className="font-mono text-slate-700 dark:text-slate-300">- {s.model}- </span>- </div>- {s.provider && (- <div className="flex items-center gap-2 text-sm mt-1">- <span className="text-slate-500 dark:text-slate-400">- Provider:- </span>- <span className="text-slate-700 dark:text-slate-300">- {s.provider}- </span>- </div>- )}- </div>- )}- </div>- );- })}- </div>-- {/* Port Information */}- {ports && (- <div className="p-4 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50">- <div className="flex items-center gap-2 mb-3">- <Server className="w-5 h-5 text-slate-400" />- <h3 className="font-semibold text-slate-900 dark:text-slate-100">- Port Configuration- </h3>- </div>- <div className="grid grid-cols-2 gap-4">- <div>- <span className="text-sm text-slate-500 dark:text-slate-400">- Backend Port- </span>- <p className="font-mono text-lg text-slate-700 dark:text-slate-300">- {ports.backend_port}- </p>- </div>- <div>- <span className="text-sm text-slate-500 dark:text-slate-400">- Frontend Port- </span>- <p className="font-mono text-lg text-slate-700 dark:text-slate-300">- {ports.frontend_port}- </p>- </div>- </div>- </div>- )}- </div>- );-}--// Configuration Tab Component-function ConfigTab({- configType,- title,- description,- onUpdate,- showDimensions = false,- showVoice = false,- isSearchConfig = false,-}: {- configType: ConfigType;- title: string;- description: string;- onUpdate: () => void;- showDimensions?: boolean;- showVoice?: boolean;- isSearchConfig?: boolean;-}) {- const [configs, setConfigs] = useState<ConfigItem[]>([]);- const [loading, setLoading] = useState(true);- const [showAddForm, setShowAddForm] = useState(false);- const [editingConfig, setEditingConfig] = useState<ConfigItem | null>(null);- const [testing, setTesting] = useState<string | null>(null);- const [testResult, setTestResult] = useState<{- success: boolean;- message: string;- } | null>(null);-- useEffect(() => {- loadConfigs();- }, [configType]);-- const loadConfigs = async () => {- try {- const res = await fetch(apiUrl(`/api/v1/config/${configType}`));- if (res.ok) {- const data = await res.json();- setConfigs(data.configs || []);- }- } catch (e) {- console.error(`Failed to load ${configType} configs:`, e);- } finally {- setLoading(false);- }- };-- const setActive = async (configId: string) => {- try {- const res = await fetch(- apiUrl(`/api/v1/config/${configType}/${configId}/active`),- {- method: "POST",- },- );- if (res.ok) {- loadConfigs();- onUpdate();- }- } catch (e) {- console.error("Failed to set active config:", e);- }- };-- const deleteConfig = async (configId: string) => {- if (!confirm("Are you sure you want to delete this configuration?")) return;-- try {- const res = await fetch(- apiUrl(`/api/v1/config/${configType}/${configId}`),- {- method: "DELETE",- },- );- if (res.ok) {- loadConfigs();- onUpdate();- }- } catch (e) {- console.error("Failed to delete config:", e);- }- };-- const testConnection = async (config: ConfigItem) => {- // Search configs don't support testing- if (isSearchConfig) return;-- setTesting(config.id);- setTestResult(null);-- try {- // Use the config ID based test endpoint - this resolves use_env references on the backend- const res = await fetch(- apiUrl(`/api/v1/config/${configType}/${config.id}/test`),- {- method: "POST",- headers: { "Content-Type": "application/json" },- },- );- const data = await res.json();- setTestResult(data);- } catch (e) {- setTestResult({ success: false, message: "Connection test failed" });- } finally {- setTesting(null);- }- };-- if (loading) {- return (- <div className="p-8 flex justify-center">- <Loader2 className="w-6 h-6 animate-spin text-blue-500" />- </div>- );- }-- return (- <div className="p-6">- {/* Header */}- <div className="flex items-center justify-between mb-6">- <div>- <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">- {title}- </h2>- <p className="text-sm text-slate-500 dark:text-slate-400">- {description}- </p>- </div>- <button- onClick={() => setShowAddForm(!showAddForm)}- className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"- >- <Plus className="w-4 h-4" />- Add Configuration- </button>- </div>-- {/* Add/Edit Form */}- {(showAddForm || editingConfig) && (- <ConfigForm- configType={configType}- showDimensions={showDimensions}- showVoice={showVoice}- isSearchConfig={isSearchConfig}- editConfig={editingConfig}- onSuccess={() => {- setShowAddForm(false);- setEditingConfig(null);- loadConfigs();- onUpdate();- }}- onCancel={() => {- setShowAddForm(false);- setEditingConfig(null);- }}- />- )}-- {/* Test Result */}- {testResult && (- <div- className={`mb-4 p-3 rounded-lg text-sm ${- testResult.success- ? "bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800"- : "bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800"- }`}- >- {testResult.message}- </div>- )}-- {/* Configuration List */}- <div className="space-y-3">- {configs.map((config) => (- <div- key={config.id}- className={`p-4 rounded-xl border transition-all ${- config.is_active- ? "border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20"- : "border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50"- }`}- >- <div className="flex items-center justify-between">- <div className="flex items-center gap-3">- {config.is_active && (- <div className="w-2 h-2 rounded-full bg-blue-500" />- )}- <div>- <div className="flex items-center gap-2">- <span className="font-medium text-slate-900 dark:text-slate-100">- {config.name}- </span>- {config.is_default && (- <span className="px-2 py-0.5 text-xs bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-400 rounded">- Default- </span>- )}- {config.is_active && (- <span className="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 rounded">- Active- </span>- )}- </div>- <div className="flex items-center gap-3 mt-1 text-sm text-slate-500 dark:text-slate-400">- <span>Provider: {config.provider}</span>- {config.model && <span>Model: {config.model}</span>}- {showDimensions && config.dimensions && (- <span>Dimensions: {config.dimensions}</span>- )}- {showVoice && config.voice && (- <span>Voice: {config.voice}</span>- )}- </div>- </div>- </div>- <div className="flex items-center gap-2">- {!config.is_active && (- <button- onClick={() => setActive(config.id)}- className="px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors"- >- Set Active- </button>- )}- {!isSearchConfig && (- <button- onClick={() => testConnection(config)}- disabled={testing === config.id}- className="px-3 py-1.5 text-sm text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"- >- {testing === config.id ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : (- "Test"- )}- </button>- )}- {!config.is_default && (- <button- onClick={() => {- setEditingConfig(config);- setShowAddForm(false);- }}- className="p-1.5 text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"- title="Edit"- >- <Pencil className="w-4 h-4" />- </button>- )}- {!config.is_default && (- <button- onClick={() => deleteConfig(config.id)}- className="p-1.5 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"- title="Delete"- >- <Trash2 className="w-4 h-4" />- </button>- )}- </div>- </div>- </div>- ))}-- {configs.length === 0 && (- <div className="text-center py-8 text-slate-500 dark:text-slate-400">- No configurations found. Add one to get started.- </div>- )}- </div>- </div>- );-}--// Configuration Form Component (Add/Edit)-function ConfigForm({- configType,- showDimensions,- showVoice,- isSearchConfig,- editConfig,- onSuccess,- onCancel,-}: {- configType: ConfigType;- showDimensions: boolean;- showVoice: boolean;- isSearchConfig: boolean;- editConfig?: ConfigItem | null;- onSuccess: () => void;- onCancel: () => void;-}) {- const isEditMode = !!editConfig;- const [saving, setSaving] = useState(false);- const [testing, setTesting] = useState(false);- const [error, setError] = useState<string | null>(null);- const [testResult, setTestResult] = useState<{- success: boolean;- message: string;- } | null>(null);-- // Helper to check if a value uses env reference format {use_env: "VAR_NAME"}- const isEnvReference = (value: any): boolean => {- return !!(value && typeof value === "object" && "use_env" in value);- };-- // Helper to get display value - returns empty string if env reference, otherwise the value- const getDisplayValue = (value: any): string => {- if (isEnvReference(value)) return "";- return typeof value === "string" ? value : "";- };-- // Check initial env reference states (computed once based on editConfig)- const initialUseEnvBaseUrl = editConfig- ? isEnvReference(editConfig.base_url)- : false;- const initialUseEnvApiKey = editConfig- ? isEnvReference(editConfig.api_key)- : false;-- // Form state - initialize from editConfig if editing, handle env references- const [name, setName] = useState(editConfig?.name || "");- const [provider, setProvider] = useState(- editConfig?.provider || PROVIDER_OPTIONS[configType][0],- );- const [baseUrl, setBaseUrl] = useState(- editConfig ? getDisplayValue(editConfig.base_url) : "",- );- const [useEnvBaseUrl, setUseEnvBaseUrl] =- useState<boolean>(initialUseEnvBaseUrl);- const [apiKey, setApiKey] = useState(""); // Never pre-fill API key for security- const [useEnvApiKey, setUseEnvApiKey] =- useState<boolean>(initialUseEnvApiKey);- const [showApiKey, setShowApiKey] = useState(false);- const [model, setModel] = useState(editConfig?.model || "");- const [dimensions, setDimensions] = useState(editConfig?.dimensions || 3072);- const [voice, setVoice] = useState(editConfig?.voice || "alloy");-- // Check if current provider is local (doesn't require API key)- const isLocalProvider = LOCAL_PROVIDERS.includes(provider);-- // Auto-fill base URL when switching to local provider- const handleProviderChange = (newProvider: string) => {- setProvider(newProvider);- if (- LOCAL_PROVIDERS.includes(newProvider) &&- LOCAL_PROVIDER_URLS[newProvider]- ) {- setBaseUrl(LOCAL_PROVIDER_URLS[newProvider]);- setUseEnvBaseUrl(false);- setUseEnvApiKey(false);- setApiKey("");- }- };-- // Test connection before saving- const handleTestConnection = async () => {- if (isSearchConfig) return;-- // Validate required fields- if (!useEnvBaseUrl && !baseUrl) {- setTestResult({- success: false,- message: "Base URL is required for testing",- });- return;- }- if (!isLocalProvider && !useEnvApiKey && !apiKey) {- setTestResult({- success: false,- message: "API Key is required for cloud providers",- });- return;- }- if (!model) {- setTestResult({ success: false, message: "Model name is required" });- return;- }- if (configType === "embedding" && !dimensions) {- setTestResult({- success: false,- message: "Dimensions is required for embedding models",- });- return;- }-- setTesting(true);- setTestResult(null);-- try {- const res = await fetch(apiUrl(`/api/v1/config/${configType}/test`), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- provider,- // Send use_env object if using env, otherwise send the actual value- base_url: useEnvBaseUrl- ? { use_env: getEnvVarForBaseUrl(configType) }- : baseUrl,- api_key: isLocalProvider- ? ""- : useEnvApiKey- ? { use_env: getEnvVarForApiKey(configType) }- : apiKey,- model,- // Include dimensions for embedding configs- ...(configType === "embedding"- ? { dimensions: Number(dimensions) }- : {}),- // Include voice for TTS configs- ...(configType === "tts" && voice ? { voice } : {}),- }),- });- const data = await res.json();- // Ensure message is not empty- setTestResult({- success: data.success ?? false,- message:- data.message ||- (data.success ? "Connection successful" : "Connection failed"),- });- } catch (e: any) {- setTestResult({- success: false,- message: e?.message || "Connection test failed - network error",- });- } finally {- setTesting(false);- }- };-- const handleSubmit = async (e: React.FormEvent) => {- e.preventDefault();- setSaving(true);- setError(null);-- try {- const payload: Record<string, any> = {- name,- provider,- // For local providers, API key is optional; for cloud providers, use env or direct value- api_key: isLocalProvider- ? apiKey || "" // Empty string for local providers if not provided- : useEnvApiKey- ? { use_env: getEnvVarForApiKey(configType) }- : apiKey,- };-- if (!isSearchConfig) {- payload.base_url = useEnvBaseUrl- ? { use_env: getEnvVarForBaseUrl(configType) }- : baseUrl;- payload.model = model;- }-- if (showDimensions) {- payload.dimensions = dimensions;- }-- if (showVoice) {- payload.voice = voice;- }-- // Use PUT for edit, POST for add- const url = isEditMode- ? apiUrl(`/api/v1/config/${configType}/${editConfig.id}`)- : apiUrl(`/api/v1/config/${configType}`);- const method = isEditMode ? "PUT" : "POST";-- const res = await fetch(url, {- method,- headers: { "Content-Type": "application/json" },- body: JSON.stringify(payload),- });-- if (res.ok) {- onSuccess();- } else {- const data = await res.json();- setError(- data.detail ||- `Failed to ${isEditMode ? "update" : "add"} configuration`,- );- }- } catch (e) {- setError(`Failed to ${isEditMode ? "update" : "add"} configuration`);- } finally {- setSaving(false);- }- };-- return (- <form- onSubmit={handleSubmit}- className="mb-6 p-4 rounded-xl border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/20"- >- <h3 className="font-medium text-slate-900 dark:text-slate-100 mb-4">- {isEditMode- ? `Edit Configuration: ${editConfig.name}`- : "Add New Configuration"}- </h3>-- {error && (- <div className="mb-4 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 text-sm border border-red-200 dark:border-red-800">- {error}- </div>- )}-- {testResult && (- <div- className={`mb-4 p-3 rounded-lg text-sm ${- testResult.success- ? "bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800"- : "bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800"- }`}- >- {testResult.message}- </div>- )}-- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- {/* Name */}- <div>- <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">- Name- </label>- <input- type="text"- value={name}- onChange={(e) => setName(e.target.value)}- required- placeholder="My Configuration"- className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"- />- </div>-- {/* Provider */}- <div>- <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">- Provider- </label>- <div className="relative">- <select- value={provider}- onChange={(e) => handleProviderChange(e.target.value)}- className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm appearance-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"- >- {PROVIDER_OPTIONS[configType].map((p) => (- <option key={p} value={p}>- {p}- {LOCAL_PROVIDERS.includes(p) ? " (local)" : ""}- </option>- ))}- </select>- <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />- </div>- </div>-- {/* Base URL (not for search) */}- {!isSearchConfig && (- <div className="md:col-span-2">- <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">- Base URL- {useEnvBaseUrl && (- <span className="ml-2 text-xs font-normal text-blue-500">- (using ${getEnvVarForBaseUrl(configType)})- </span>- )}- </label>- <div className="flex items-center gap-3">- <div className="flex-1">- <input- type="text"- value={useEnvBaseUrl ? "" : baseUrl}- onChange={(e) => setBaseUrl(e.target.value)}- disabled={useEnvBaseUrl}- placeholder={- useEnvBaseUrl- ? `Using ${getEnvVarForBaseUrl(configType)} from .env`- : "https://api.openai.com/v1"- }- className={`w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${- useEnvBaseUrl- ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic"- : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600"- }`}- />- </div>- <label className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400 whitespace-nowrap">- <input- type="checkbox"- checked={useEnvBaseUrl}- onChange={(e) => {- setUseEnvBaseUrl(e.target.checked);- if (e.target.checked) setBaseUrl("");- }}- className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"- />- Use .env- </label>- </div>- </div>- )}-- {/* API Key - Optional for local providers */}- <div className="md:col-span-2">- <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">- API Key- {isLocalProvider ? (- <span className="ml-2 text-xs font-normal text-slate-400">- (optional for local providers)- </span>- ) : useEnvApiKey ? (- <span className="ml-2 text-xs font-normal text-blue-500">- (using ${getEnvVarForApiKey(configType)})- </span>- ) : null}- </label>- <div className="flex items-center gap-3">- <div className="flex-1 relative">- <input- type={showApiKey ? "text" : "password"}- value={useEnvApiKey ? "" : apiKey}- onChange={(e) => setApiKey(e.target.value)}- disabled={useEnvApiKey}- placeholder={- isLocalProvider- ? "Not required"- : useEnvApiKey- ? `Using ${getEnvVarForApiKey(configType)} from .env`- : "sk-..."- }- className={`w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${- useEnvApiKey- ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic"- : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600"- }`}- />- {!useEnvApiKey && (- <button- type="button"- onClick={() => setShowApiKey(!showApiKey)}- className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"- >- {showApiKey ? (- <EyeOff className="w-4 h-4" />- ) : (- <Eye className="w-4 h-4" />- )}- </button>- )}- </div>- {!isLocalProvider && (- <label className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400 whitespace-nowrap">- <input- type="checkbox"- checked={useEnvApiKey}- onChange={(e) => {- setUseEnvApiKey(e.target.checked);- if (e.target.checked) setApiKey("");- }}- className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"- />- Use .env- </label>- )}- </div>- </div>-- {/* Model (not for search) */}- {!isSearchConfig && (- <div>- <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">- Model- </label>- <input- type="text"- value={model}- onChange={(e) => setModel(e.target.value)}- required- placeholder="gpt-4o"- className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"- />- </div>- )}-- {/* Dimensions (embedding only) */}- {showDimensions && (- <div>- <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">- Dimensions- </label>- <input- type="number"- value={dimensions}- onChange={(e) => setDimensions(parseInt(e.target.value))}- className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"- />- </div>- )}-- {/* Voice (TTS only) */}- {showVoice && (- <div>- <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">- Voice- </label>- <div className="relative">- <select- value={voice}- onChange={(e) => setVoice(e.target.value)}- className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm appearance-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"- >- {VOICE_OPTIONS.map((v) => (- <option key={v} value={v}>- {v}- </option>- ))}- </select>- <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />- </div>- </div>- )}- </div>-- {/* Actions */}- <div className="flex justify-between items-center mt-4">- {/* Test Connection Button (left side) */}- <div>- {!isSearchConfig && (- <button- type="button"- onClick={handleTestConnection}- disabled={testing || (!baseUrl && !useEnvBaseUrl)}- className="flex items-center gap-2 px-4 py-2 text-sm text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 rounded-lg transition-colors"- >- {testing ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : (- <TestTube className="w-4 h-4" />- )}- Test Connection- </button>- )}- </div>-- {/* Cancel and Save Buttons (right side) */}- <div className="flex gap-3">- <button- type="button"- onClick={onCancel}- className="px-4 py-2 text-sm text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"- >- Cancel- </button>- <button- type="submit"- disabled={saving}- className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg text-sm font-medium transition-colors"- >- {saving ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : isEditMode ? (- <Check className="w-4 h-4" />- ) : (- <Plus className="w-4 h-4" />- )}- {isEditMode ? "Save Changes" : "Add Configuration"}- </button>- </div>- </div>- </form>- );-}--// Helper functions to get env var names-function getEnvVarForBaseUrl(configType: ConfigType): string {- const mapping: Record<ConfigType, string> = {- llm: "LLM_HOST",- embedding: "EMBEDDING_HOST",- tts: "TTS_URL",- search: "SEARCH_PROVIDER", // Provider name, not URL (search uses SEARCH_API_KEY for auth)- };- return mapping[configType];-}--function getEnvVarForApiKey(configType: ConfigType): string {- const mapping: Record<ConfigType, string> = {- llm: "LLM_API_KEY",- embedding: "EMBEDDING_API_KEY",- tts: "TTS_API_KEY",- search: "SEARCH_API_KEY", // Unified API key for all search providers- };- return mapping[configType];-}diff --git a/web/app/settings/types.ts b/web/app/settings/types.tsnew file mode 100644index 000000000..17c84ad16--- /dev/null+++ b/web/app/settings/types.ts@@ -0,0 +1,41 @@+// Settings page types++export interface ConfigItem {+ id: string;+ name: string;+ provider: string;+ base_url?: string;+ api_key?: string;+ model?: string;+ dimensions?: number;+ voice?: string;+ api_version?: string;+ is_default?: boolean;+ is_active?: boolean;+}++export interface ConfigStatus {+ configured: boolean;+ active_config_id: string;+ active_config_name: string;+ model: string | null;+ provider: string | null;+ env_configured: Record<string, boolean>;+ total_configs: number;+}++export interface FullStatus {+ llm: ConfigStatus;+ embedding: ConfigStatus;+ tts: ConfigStatus;+ search: ConfigStatus;+}++export interface PortsInfo {+ backend_port: number;+ frontend_port: number;+}++export type ConfigType = "llm" | "embedding" | "tts" | "search";+export type TabType = "overview" | ConfigType;+diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsxnew file mode 100644index 000000000..01cf47b3a--- /dev/null+++ b/web/components/common/MarkdownRenderer.tsx@@ -0,0 +1,120 @@+"use client";++import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";+import rehypeKatex from "rehype-katex";+import "katex/dist/katex.min.css";+import { processLatexContent } from "@/lib/latex";++interface MarkdownRendererProps {+ content: string;+ className?: string;+ variant?: "default" | "compact" | "prose";+}++/**+ * Shared MarkdownRenderer component with KaTeX support and consistent table styling+ */+export default function MarkdownRenderer({+ content,+ className = "",+ variant = "default",+}: MarkdownRendererProps) {+ // Table components with consistent styling+ const tableComponents = {+ table: ({ node, ...props }: any) => (+ <div+ className={`overflow-x-auto rounded-lg border border-slate-200 dark:border-slate-700 shadow-sm ${+ variant === "compact" ? "my-2" : "my-4"+ }`}+ >+ <table+ className="min-w-full divide-y divide-slate-200 dark:divide-slate-700 text-sm"+ {...props}+ />+ </div>+ ),+ thead: ({ node, ...props }: any) => (+ <thead className="bg-slate-50 dark:bg-slate-800" {...props} />+ ),+ th: ({ node, ...props }: any) => (+ <th+ className={`text-left font-semibold text-slate-700 dark:text-slate-300 whitespace-nowrap border-b border-slate-200 dark:border-slate-700 ${+ variant === "compact" ? "px-2 py-1.5" : "px-3 py-2"+ }`}+ {...props}+ />+ ),+ tbody: ({ node, ...props }: any) => (+ <tbody+ className="divide-y divide-slate-100 dark:divide-slate-700 bg-white dark:bg-slate-900"+ {...props}+ />+ ),+ td: ({ node, ...props }: any) => (+ <td+ className={`text-slate-600 dark:text-slate-400 border-b border-slate-100 dark:border-slate-700 ${+ variant === "compact" ? "px-2 py-1.5" : "px-3 py-2"+ }`}+ {...props}+ />+ ),+ tr: ({ node, ...props }: any) => (+ <tr+ className="hover:bg-slate-50/50 dark:hover:bg-slate-800/50 transition-colors"+ {...props}+ />+ ),+ };++ // Code block styling+ const codeComponents = {+ code: ({ node, inline, className: codeClassName, children, ...props }: any) => {+ if (inline) {+ return (+ <code+ className="px-1.5 py-0.5 bg-slate-100 dark:bg-slate-800 text-slate-800 dark:text-slate-200 rounded text-sm font-mono"+ {...props}+ >+ {children}+ </code>+ );+ }+ return (+ <code+ className={`block p-3 bg-slate-900 dark:bg-slate-950 text-slate-100 rounded-lg overflow-x-auto text-sm font-mono ${codeClassName || ""}`}+ {...props}+ >+ {children}+ </code>+ );+ },+ pre: ({ node, children, ...props }: any) => (+ <pre className="my-4" {...props}>+ {children}+ </pre>+ ),+ };++ const proseClasses =+ variant === "prose"+ ? "prose prose-slate dark:prose-invert prose-headings:font-bold prose-h1:text-2xl prose-h2:text-xl max-w-none"+ : "prose prose-sm max-w-none";++ return (+ <div className={`${proseClasses} ${className}`}>+ <ReactMarkdown+ remarkPlugins={[remarkGfm, remarkMath]}+ rehypePlugins={[rehypeKatex]}+ components={{+ ...tableComponents,+ ...codeComponents,+ }}+ >+ {processLatexContent(content)}+ </ReactMarkdown>+ </div>+ );+}+diff --git a/web/components/common/Modal.tsx b/web/components/common/Modal.tsxnew file mode 100644index 000000000..f95b940f1--- /dev/null+++ b/web/components/common/Modal.tsx@@ -0,0 +1,106 @@+"use client";++import { useEffect, useCallback } from "react";+import { X } from "lucide-react";++interface ModalProps {+ isOpen: boolean;+ onClose: () => void;+ title?: string;+ titleIcon?: React.ReactNode;+ children: React.ReactNode;+ footer?: React.ReactNode;+ width?: "sm" | "md" | "lg" | "xl";+ closeOnBackdrop?: boolean;+ closeOnEscape?: boolean;+}++const widthClasses = {+ sm: "w-[400px]",+ md: "w-[500px]",+ lg: "w-[600px]",+ xl: "w-[800px]",+};++/**+ * Shared Modal base component+ */+export default function Modal({+ isOpen,+ onClose,+ title,+ titleIcon,+ children,+ footer,+ width = "md",+ closeOnBackdrop = true,+ closeOnEscape = true,+}: ModalProps) {+ // Handle escape key+ const handleEscape = useCallback(+ (e: KeyboardEvent) => {+ if (closeOnEscape && e.key === "Escape") {+ onClose();+ }+ },+ [closeOnEscape, onClose],+ );++ useEffect(() => {+ if (isOpen) {+ document.addEventListener("keydown", handleEscape);+ // Prevent body scroll when modal is open+ document.body.style.overflow = "hidden";+ }+ return () => {+ document.removeEventListener("keydown", handleEscape);+ document.body.style.overflow = "";+ };+ }, [isOpen, handleEscape]);++ if (!isOpen) return null;++ const handleBackdropClick = (e: React.MouseEvent) => {+ if (closeOnBackdrop && e.target === e.currentTarget) {+ onClose();+ }+ };++ return (+ <div+ className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in"+ onClick={handleBackdropClick}+ >+ <div+ className={`bg-white dark:bg-slate-800 rounded-2xl shadow-2xl ${widthClasses[width]} max-h-[90vh] flex flex-col animate-in zoom-in-95`}+ >+ {/* Header */}+ {(title || titleIcon) && (+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between shrink-0">+ <h3 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">+ {titleIcon}+ {title}+ </h3>+ <button+ onClick={onClose}+ className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"+ >+ <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />+ </button>+ </div>+ )}++ {/* Content */}+ <div className="flex-1 overflow-y-auto">{children}</div>++ {/* Footer */}+ {footer && (+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 shrink-0">+ {footer}+ </div>+ )}+ </div>+ </div>+ );+}+diff --git a/web/components/common/index.ts b/web/components/common/index.tsnew file mode 100644index 000000000..65cc55079--- /dev/null+++ b/web/components/common/index.ts@@ -0,0 +1,3 @@+export { default as MarkdownRenderer } from "./MarkdownRenderer";+export { default as Modal } from "./Modal";+diff --git a/web/context/CompositeProvider.tsx b/web/context/CompositeProvider.tsxnew file mode 100644index 000000000..5b7763c43--- /dev/null+++ b/web/context/CompositeProvider.tsx@@ -0,0 +1,32 @@+"use client";++import React from "react";+import { SolverProvider } from "./solver";+import { QuestionProvider } from "./question";+import { ResearchProvider } from "./research";+import { ChatProvider } from "./chat";+import { UISettingsProvider, SidebarProvider } from "./settings";+import { IdeaGenProvider } from "./ideagen";++/**+ * CompositeProvider combines all context providers into a single component.+ * This simplifies the provider hierarchy in the app layout.+ */+export function CompositeProvider({ children }: { children: React.ReactNode }) {+ return (+ <UISettingsProvider>+ <SidebarProvider>+ <SolverProvider>+ <QuestionProvider>+ <ResearchProvider>+ <ChatProvider>+ <IdeaGenProvider>{children}</IdeaGenProvider>+ </ChatProvider>+ </ResearchProvider>+ </QuestionProvider>+ </SolverProvider>+ </SidebarProvider>+ </UISettingsProvider>+ );+}+diff --git a/web/context/chat/ChatContext.tsx b/web/context/chat/ChatContext.tsxnew file mode 100644index 000000000..e0980315d--- /dev/null+++ b/web/context/chat/ChatContext.tsx@@ -0,0 +1,272 @@+"use client";++import React, {+ createContext,+ useContext,+ useRef,+ useState,+ useCallback,+} from "react";+import { wsUrl, apiUrl } from "@/lib/api";+import {+ ChatState,+ HomeChatMessage,+ INITIAL_CHAT_STATE,+} from "@/types/chat";++// Context type+interface ChatContextType {+ chatState: ChatState;+ setChatState: React.Dispatch<React.SetStateAction<ChatState>>;+ sendChatMessage: (message: string) => void;+ clearChatHistory: () => void;+ loadChatSession: (sessionId: string) => Promise<void>;+ newChatSession: () => void;+}++const ChatContext = createContext<ChatContextType | undefined>(undefined);++export function ChatProvider({ children }: { children: React.ReactNode }) {+ const [chatState, setChatState] = useState<ChatState>(INITIAL_CHAT_STATE);+ const chatWs = useRef<WebSocket | null>(null);+ // Use ref to always have the latest sessionId in WebSocket callbacks+ const sessionIdRef = useRef<string | null>(null);++ const sendChatMessage = useCallback(+ (message: string) => {+ if (!message.trim() || chatState.isLoading) return;++ // Add user message+ setChatState((prev) => ({+ ...prev,+ isLoading: true,+ currentStage: "connecting",+ messages: [...prev.messages, { role: "user", content: message }],+ }));++ // Close existing connection if any+ if (chatWs.current) {+ chatWs.current.close();+ }++ const ws = new WebSocket(wsUrl("/api/v1/chat"));+ chatWs.current = ws;++ let assistantMessage = "";++ ws.onopen = () => {+ // Build history from current messages (excluding the one just added)+ const history = chatState.messages.map((msg) => ({+ role: msg.role,+ content: msg.content,+ }));++ ws.send(+ JSON.stringify({+ message,+ session_id: sessionIdRef.current,+ history,+ kb_name: chatState.selectedKb,+ enable_rag: chatState.enableRag,+ enable_web_search: chatState.enableWebSearch,+ }),+ );+ };++ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);++ if (data.type === "session") {+ sessionIdRef.current = data.session_id;+ setChatState((prev) => ({+ ...prev,+ sessionId: data.session_id,+ }));+ } else if (data.type === "status") {+ setChatState((prev) => ({+ ...prev,+ currentStage: data.stage || data.message,+ }));+ } else if (data.type === "stream") {+ assistantMessage += data.content;+ setChatState((prev) => {+ const messages = [...prev.messages];+ const lastMessage = messages[messages.length - 1];+ if (lastMessage?.role === "assistant" && lastMessage?.isStreaming) {+ messages[messages.length - 1] = {+ ...lastMessage,+ content: assistantMessage,+ };+ } else {+ messages.push({+ role: "assistant",+ content: assistantMessage,+ isStreaming: true,+ });+ }+ return { ...prev, messages, currentStage: "generating" };+ });+ } else if (data.type === "sources") {+ setChatState((prev) => {+ const messages = [...prev.messages];+ const lastMessage = messages[messages.length - 1];+ if (lastMessage?.role === "assistant") {+ messages[messages.length - 1] = {+ ...lastMessage,+ sources: { rag: data.rag, web: data.web },+ };+ }+ return { ...prev, messages };+ });+ } else if (data.type === "result") {+ setChatState((prev) => {+ const messages = [...prev.messages];+ const lastMessage = messages[messages.length - 1];+ if (lastMessage?.role === "assistant") {+ messages[messages.length - 1] = {+ ...lastMessage,+ content: data.content,+ isStreaming: false,+ };+ }+ return {+ ...prev,+ messages,+ isLoading: false,+ currentStage: null,+ };+ });+ ws.close();+ } else if (data.type === "error") {+ setChatState((prev) => ({+ ...prev,+ isLoading: false,+ currentStage: null,+ messages: [+ ...prev.messages,+ { role: "assistant", content: `Error: ${data.message}` },+ ],+ }));+ ws.close();+ }+ };++ ws.onerror = () => {+ setChatState((prev) => ({+ ...prev,+ isLoading: false,+ currentStage: null,+ messages: [+ ...prev.messages,+ {+ role: "assistant",+ content: "Connection error. Please try again.",+ },+ ],+ }));+ };++ ws.onclose = () => {+ if (chatWs.current === ws) {+ chatWs.current = null;+ }+ setChatState((prev) => ({+ ...prev,+ isLoading: false,+ currentStage: null,+ }));+ };+ },+ [+ chatState.isLoading,+ chatState.messages,+ chatState.selectedKb,+ chatState.enableRag,+ chatState.enableWebSearch,+ ],+ );++ const clearChatHistory = useCallback(() => {+ sessionIdRef.current = null;+ setChatState((prev) => ({+ ...prev,+ sessionId: null,+ messages: [],+ currentStage: null,+ }));+ }, []);++ const newChatSession = useCallback(() => {+ if (chatWs.current) {+ chatWs.current.close();+ chatWs.current = null;+ }+ sessionIdRef.current = null;+ setChatState((prev) => ({+ ...prev,+ sessionId: null,+ messages: [],+ isLoading: false,+ currentStage: null,+ }));+ }, []);++ const loadChatSession = useCallback(async (sessionId: string) => {+ try {+ const response = await fetch(+ apiUrl(`/api/v1/chat/sessions/${sessionId}`),+ );+ if (!response.ok) {+ throw new Error("Session not found");+ }+ const session = await response.json();++ const messages: HomeChatMessage[] = session.messages.map((msg: any) => ({+ role: msg.role,+ content: msg.content,+ sources: msg.sources,+ isStreaming: false,+ }));++ const settings = session.settings || {};++ sessionIdRef.current = session.session_id;++ setChatState((prev) => ({+ ...prev,+ sessionId: session.session_id,+ messages,+ selectedKb: settings.kb_name || prev.selectedKb,+ enableRag: settings.enable_rag ?? prev.enableRag,+ enableWebSearch: settings.enable_web_search ?? prev.enableWebSearch,+ isLoading: false,+ currentStage: null,+ }));+ } catch (error) {+ console.error("Failed to load session:", error);+ throw error;+ }+ }, []);++ return (+ <ChatContext.Provider+ value={{+ chatState,+ setChatState,+ sendChatMessage,+ clearChatHistory,+ loadChatSession,+ newChatSession,+ }}+ >+ {children}+ </ChatContext.Provider>+ );+}++export const useChat = () => {+ const context = useContext(ChatContext);+ if (!context) throw new Error("useChat must be used within ChatProvider");+ return context;+};+diff --git a/web/context/chat/index.ts b/web/context/chat/index.tsnew file mode 100644index 000000000..2a4d0f878--- /dev/null+++ b/web/context/chat/index.ts@@ -0,0 +1,2 @@+export { ChatProvider, useChat } from "./ChatContext";+diff --git a/web/context/ideagen/IdeaGenContext.tsx b/web/context/ideagen/IdeaGenContext.tsxnew file mode 100644index 000000000..ada178c86--- /dev/null+++ b/web/context/ideagen/IdeaGenContext.tsx@@ -0,0 +1,36 @@+"use client";++import React, { createContext, useContext, useState } from "react";+import { IdeaGenState, INITIAL_IDEAGEN_STATE } from "@/types/ideagen";++// Context type+interface IdeaGenContextType {+ ideaGenState: IdeaGenState;+ setIdeaGenState: React.Dispatch<React.SetStateAction<IdeaGenState>>;+}++const IdeaGenContext = createContext<IdeaGenContextType | undefined>(undefined);++export function IdeaGenProvider({ children }: { children: React.ReactNode }) {+ const [ideaGenState, setIdeaGenState] =+ useState<IdeaGenState>(INITIAL_IDEAGEN_STATE);++ return (+ <IdeaGenContext.Provider+ value={{+ ideaGenState,+ setIdeaGenState,+ }}+ >+ {children}+ </IdeaGenContext.Provider>+ );+}++export const useIdeaGen = () => {+ const context = useContext(IdeaGenContext);+ if (!context)+ throw new Error("useIdeaGen must be used within IdeaGenProvider");+ return context;+};+diff --git a/web/context/ideagen/index.ts b/web/context/ideagen/index.tsnew file mode 100644index 000000000..f65cfcb4c--- /dev/null+++ b/web/context/ideagen/index.ts@@ -0,0 +1,2 @@+export { IdeaGenProvider, useIdeaGen } from "./IdeaGenContext";+diff --git a/web/context/index.ts b/web/context/index.tsnew file mode 100644index 000000000..83c110816--- /dev/null+++ b/web/context/index.ts@@ -0,0 +1,23 @@+/**+ * Context exports - central export point for all contexts+ */++// Composite provider for app layout+export { CompositeProvider } from "./CompositeProvider";++// Individual context hooks+export { useSolver, SolverProvider } from "./solver";+export { useQuestion, QuestionProvider } from "./question";+export { useResearch, ResearchProvider } from "./research";+export { useChat, ChatProvider } from "./chat";+export { useUISettings, UISettingsProvider } from "./settings";+export { useSidebar, SidebarProvider } from "./settings";+export { useIdeaGen, IdeaGenProvider } from "./ideagen";++// Re-export types+export type { SidebarNavOrder } from "./settings";++// Legacy compatibility - useGlobal hook that combines all contexts+// This allows gradual migration without breaking existing code+export { useGlobal, GlobalProvider } from "./GlobalContext";+diff --git a/web/context/question/QuestionContext.tsx b/web/context/question/QuestionContext.tsxnew file mode 100644index 000000000..53d69ab5a--- /dev/null+++ b/web/context/question/QuestionContext.tsx@@ -0,0 +1,657 @@+"use client";++import React, {+ createContext,+ useContext,+ useRef,+ useState,+ useCallback,+} from "react";+import { wsUrl } from "@/lib/api";+import {+ QuestionContextState,+ QuestionProgressInfo,+ INITIAL_QUESTION_CONTEXT_STATE,+ DEFAULT_QUESTION_AGENT_STATUS,+ DEFAULT_QUESTION_TOKEN_STATS,+} from "@/types/question";+import { LogEntry } from "@/types/common";++// Context type+interface QuestionContextType {+ questionState: QuestionContextState;+ setQuestionState: React.Dispatch<React.SetStateAction<QuestionContextState>>;+ startQuestionGen: (+ topic: string,+ diff: string,+ type: string,+ count: number,+ kb: string,+ ) => void;+ startMimicQuestionGen: (+ file: File | null,+ paperPath: string,+ kb: string,+ maxQuestions?: number,+ ) => void;+ resetQuestionGen: () => void;+}++const QuestionContext = createContext<QuestionContextType | undefined>(+ undefined,+);++export function QuestionProvider({ children }: { children: React.ReactNode }) {+ const [questionState, setQuestionState] = useState<QuestionContextState>(+ INITIAL_QUESTION_CONTEXT_STATE,+ );+ const questionWs = useRef<WebSocket | null>(null);++ const addQuestionLog = useCallback((log: LogEntry) => {+ setQuestionState((prev) => ({ ...prev, logs: [...prev.logs, log] }));+ }, []);++ // Helper function to handle mimic WebSocket messages+ const handleMimicWsMessage = useCallback(+ (data: any, ws: WebSocket) => {+ const stageMap: Record<string, string> = {+ init: "uploading",+ upload: "uploading",+ parsing: "parsing",+ processing: "extracting",+ };++ switch (data.type) {+ case "log":+ addQuestionLog(data);+ break;++ case "status": {+ const mappedStage = stageMap[data.stage] || data.stage;+ addQuestionLog({+ type: "system",+ content: data.content || data.message || `Stage: ${data.stage}`,+ });+ if (mappedStage) {+ setQuestionState((prev) => ({+ ...prev,+ progress: { ...prev.progress, stage: mappedStage },+ }));+ }+ break;+ }++ case "progress": {+ const stage = data.stage || "generating";+ if (data.message) {+ addQuestionLog({ type: "system", content: data.message });+ }+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ stage: stage,+ progress: {+ ...prev.progress.progress,+ current: data.current ?? prev.progress.progress.current,+ total:+ data.total_questions ??+ data.total ??+ prev.progress.progress.total,+ status: data.status,+ },+ },+ }));+ if (+ stage === "extracting" &&+ data.status === "complete" &&+ data.reference_questions+ ) {+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ progress: {+ ...prev.progress.progress,+ total: data.total_questions || data.reference_questions.length,+ },+ },+ }));+ }+ break;+ }++ case "question_update": {+ const statusMessage =+ data.status === "generating"+ ? `Generating mimic question ${data.index}...`+ : data.status === "failed"+ ? `Question ${data.index} failed: ${data.error}`+ : `Question ${data.index}: ${data.status}`;+ addQuestionLog({+ type: data.status === "failed" ? "warning" : "system",+ content: statusMessage,+ });+ if (data.current !== undefined) {+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ progress: { ...prev.progress.progress, current: data.current },+ },+ }));+ }+ break;+ }++ case "result": {+ const isExtended =+ data.extended || data.validation?.decision === "extended";+ addQuestionLog({+ type: "success",+ content: `✅ Question ${data.index || (data.current ?? 0)} generated successfully`,+ });+ setQuestionState((prev) => ({+ ...prev,+ results: [+ ...prev.results,+ {+ success: true,+ question_id: data.question_id || `q_${prev.results.length + 1}`,+ question: data.question,+ validation: data.validation,+ rounds: data.rounds || 1,+ reference_question: data.reference_question,+ extended: isExtended,+ },+ ],+ progress: {+ ...prev.progress,+ stage: "generating",+ progress: {+ ...prev.progress.progress,+ current: data.current ?? prev.results.length + 1,+ total: data.total ?? prev.progress.progress.total ?? 1,+ },+ extendedQuestions:+ (prev.progress.extendedQuestions || 0) + (isExtended ? 1 : 0),+ },+ }));+ break;+ }++ case "summary":+ addQuestionLog({+ type: "success",+ content: `Generation complete: ${data.successful}/${data.total_reference} succeeded`,+ });+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ stage: "generating",+ progress: {+ current: data.successful,+ total: data.total_reference,+ },+ completedQuestions: data.successful,+ failedQuestions: data.failed,+ },+ }));+ break;++ case "complete":+ addQuestionLog({+ type: "success",+ content: "✅ Mimic generation completed!",+ });+ setQuestionState((prev) => ({+ ...prev,+ step: "result",+ progress: {+ ...prev.progress,+ stage: "complete",+ completedQuestions: prev.results.length,+ },+ }));+ ws.close();+ break;++ case "error":+ addQuestionLog({+ type: "error",+ content: `Error: ${data.content || data.message || "Unknown error"}`,+ });+ setQuestionState((prev) => ({+ ...prev,+ step: "config",+ progress: { stage: null, progress: {} },+ }));+ break;+ }+ },+ [addQuestionLog],+ );++ const startQuestionGen = useCallback(+ (topic: string, diff: string, type: string, count: number, kb: string) => {+ if (questionWs.current) questionWs.current.close();++ setQuestionState((prev) => ({+ ...prev,+ step: "generating",+ mode: "knowledge",+ logs: [],+ results: [],+ topic,+ difficulty: diff,+ type,+ count,+ selectedKb: kb,+ progress: {+ stage: count > 1 ? "planning" : "generating",+ progress: { current: 0, total: count },+ subFocuses: [],+ activeQuestions: [],+ completedQuestions: 0,+ failedQuestions: 0,+ },+ agentStatus: { ...DEFAULT_QUESTION_AGENT_STATUS },+ tokenStats: { ...DEFAULT_QUESTION_TOKEN_STATS },+ }));++ const ws = new WebSocket(wsUrl("/api/v1/question/generate"));+ questionWs.current = ws;++ ws.onopen = () => {+ ws.send(+ JSON.stringify({+ requirement: {+ knowledge_point: topic,+ difficulty: diff,+ question_type: type,+ additional_requirements: "Ensure clarity and academic rigor.",+ },+ count: count,+ kb_name: kb,+ }),+ );+ addQuestionLog({+ type: "system",+ content: "Initializing Generator...",+ });+ };++ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ if (data.type === "log") {+ addQuestionLog(data);+ // Parse progress info from log content+ if (data.content.includes("Generating question")) {+ const match = data.content.match(/(\d+)\/(\d+)/);+ if (match) {+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ stage: "generating",+ progress: {+ current: parseInt(match[1]),+ total: parseInt(match[2]),+ },+ },+ }));+ }+ }+ if (+ data.content.includes("Round") ||+ data.content.includes("round")+ ) {+ const match = data.content.match(/Round\s+(\d+)/i);+ if (match) {+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ progress: {+ ...prev.progress.progress,+ round: parseInt(match[1]),+ },+ },+ }));+ }+ }+ if (+ data.content.includes("Validation") ||+ data.content.includes("validation")+ ) {+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ stage: "validating",+ },+ }));+ }+ } else if (data.type === "agent_status") {+ setQuestionState((prev) => ({+ ...prev,+ agentStatus: data.all_agents || {+ ...prev.agentStatus,+ [data.agent]: data.status,+ },+ }));+ } else if (data.type === "token_stats") {+ setQuestionState((prev) => ({+ ...prev,+ tokenStats: data.stats || prev.tokenStats,+ }));+ } else if (data.type === "progress") {+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ stage: data.stage || prev.progress.stage,+ progress: {+ ...prev.progress.progress,+ ...data.progress,+ total: data.total ?? prev.progress.progress.total,+ },+ subFocuses:+ data.focuses || data.sub_focuses || prev.progress.subFocuses,+ activeQuestions: prev.progress.activeQuestions,+ completedQuestions:+ data.completed ?? prev.progress.completedQuestions,+ failedQuestions: data.failed ?? prev.progress.failedQuestions,+ },+ }));+ } else if (data.type === "question_update") {+ const statusLabel =+ data.status === "analyzing"+ ? "Analyzing relevance"+ : data.status === "generating"+ ? "Generating"+ : data.status === "done"+ ? "Completed"+ : data.status;+ addQuestionLog({+ type: data.status === "done" ? "success" : "system",+ content: `[${data.question_id}] ${statusLabel}${data.focus ? `: ${data.focus.slice(0, 50)}...` : ""}`,+ });+ } else if (data.type === "question_error") {+ addQuestionLog({+ type: "error",+ content: `[${data.question_id}] Error: ${data.error}${data.reason ? ` - ${data.reason}` : ""}`,+ });+ } else if (data.type === "knowledge_saved") {+ addQuestionLog({+ type: "success",+ content: `Background knowledge retrieved (${data.queries?.length || 0} queries)`,+ });+ } else if (data.type === "plan_ready") {+ const focuses = data.focuses || data.plan?.focuses || [];+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ stage: "planning",+ subFocuses: focuses,+ progress: {+ ...prev.progress.progress,+ status: "plan_ready",+ },+ },+ }));+ addQuestionLog({+ type: "success",+ content: `Question plan created with ${focuses.length} focuses`,+ });+ } else if (data.type === "batch_summary") {+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ ...prev.progress,+ subFocuses:+ data.sub_focuses ||+ data.plan?.focuses ||+ prev.progress.subFocuses,+ completedQuestions: data.completed || prev.results.length,+ failedQuestions: data.failed || 0,+ progress: {+ ...prev.progress.progress,+ current: data.completed || prev.results.length,+ total: data.requested || prev.count,+ },+ },+ }));+ addQuestionLog({+ type: "success",+ content: `Generation complete: ${data.completed}/${data.requested} questions generated${data.failed > 0 ? `, ${data.failed} failed` : ""}`,+ });+ } else if (data.type === "result") {+ const isExtended =+ data.extended || data.validation?.decision === "extended";+ const questionPreview =+ data.question?.question?.slice(0, 50) || "Unknown";+ addQuestionLog({+ type: "success",+ content: `Question ${data.question_id || (data.index !== undefined ? `#${data.index + 1}` : "")} generated: ${questionPreview}...`,+ });+ setQuestionState((prev) => ({+ ...prev,+ results: [+ ...prev.results,+ {+ success: true,+ question_id:+ data.question_id || `q_${prev.results.length + 1}`,+ question: data.question,+ validation: data.validation,+ rounds: data.rounds || 1,+ extended: isExtended,+ },+ ],+ progress: {+ ...prev.progress,+ stage: "generating",+ completedQuestions: prev.results.length + 1,+ progress: {+ ...prev.progress.progress,+ current: prev.results.length + 1,+ total: prev.count,+ round: data.rounds || 1,+ },+ extendedQuestions:+ (prev.progress.extendedQuestions || 0) + (isExtended ? 1 : 0),+ },+ }));+ } else if (data.type === "complete") {+ setQuestionState((prev) => ({+ ...prev,+ step: "result",+ progress: {+ ...prev.progress,+ stage: "complete",+ completedQuestions: prev.results.length,+ },+ }));+ ws.close();+ } else if (data.type === "error") {+ addQuestionLog({+ type: "error",+ content: `Error: ${data.content || data.message || "Unknown error"}`,+ });+ setQuestionState((prev) => ({+ ...prev,+ progress: {+ stage: null,+ progress: {},+ },+ }));+ }+ };++ ws.onerror = () => {+ addQuestionLog({+ type: "error",+ content: "WebSocket connection error",+ });+ setQuestionState((prev) => ({+ ...prev,+ step: "config",+ progress: {+ stage: null,+ progress: {},+ },+ agentStatus: { ...DEFAULT_QUESTION_AGENT_STATUS },+ }));+ };++ ws.onclose = () => {+ if (questionWs.current === ws) {+ questionWs.current = null;+ }+ };+ },+ [addQuestionLog],+ );++ const startMimicQuestionGen = useCallback(+ async (+ file: File | null,+ paperPath: string,+ kb: string,+ maxQuestions?: number,+ ) => {+ if (questionWs.current) questionWs.current.close();++ const hasFile = file !== null;+ const hasParsedPath = paperPath && paperPath.trim() !== "";++ if (!hasFile && !hasParsedPath) {+ addQuestionLog({+ type: "error",+ content:+ "Please upload a PDF file or provide a parsed exam directory",+ });+ return;+ }++ setQuestionState((prev) => ({+ ...prev,+ step: "generating",+ mode: "mimic",+ logs: [],+ results: [],+ selectedKb: kb,+ uploadedFile: file,+ paperPath: paperPath,+ progress: {+ stage: hasFile ? "uploading" : "parsing",+ progress: { current: 0, total: maxQuestions || 1 },+ },+ agentStatus: { ...DEFAULT_QUESTION_AGENT_STATUS },+ tokenStats: { ...DEFAULT_QUESTION_TOKEN_STATS },+ }));++ const ws = new WebSocket(wsUrl("/api/v1/question/mimic"));+ questionWs.current = ws;++ ws.onopen = async () => {+ if (hasFile && file) {+ addQuestionLog({+ type: "system",+ content: "Preparing to upload PDF file...",+ });+ const reader = new FileReader();+ reader.onload = () => {+ const base64Data = (reader.result as string).split(",")[1];+ ws.send(+ JSON.stringify({+ mode: "upload",+ pdf_data: base64Data,+ pdf_name: file.name,+ kb_name: kb,+ max_questions: maxQuestions,+ }),+ );+ addQuestionLog({+ type: "system",+ content: `Uploaded: ${file.name}, parsing...`,+ });+ };+ reader.readAsDataURL(file);+ } else {+ ws.send(+ JSON.stringify({+ mode: "parsed",+ paper_path: paperPath,+ kb_name: kb,+ max_questions: maxQuestions,+ }),+ );+ addQuestionLog({+ type: "system",+ content: "Initializing Mimic Generator...",+ });+ }+ };++ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ handleMimicWsMessage(data, ws);+ };++ ws.onerror = () => {+ addQuestionLog({+ type: "error",+ content: "WebSocket connection error",+ });+ setQuestionState((prev) => ({ ...prev, step: "config" }));+ };+ },+ [addQuestionLog, handleMimicWsMessage],+ );++ const resetQuestionGen = useCallback(() => {+ setQuestionState((prev) => ({+ ...prev,+ step: "config",+ results: [],+ logs: [],+ progress: {+ stage: null,+ progress: {},+ subFocuses: [],+ activeQuestions: [],+ completedQuestions: 0,+ failedQuestions: 0,+ },+ agentStatus: { ...DEFAULT_QUESTION_AGENT_STATUS },+ tokenStats: { ...DEFAULT_QUESTION_TOKEN_STATS },+ uploadedFile: null,+ paperPath: "",+ }));+ }, []);++ return (+ <QuestionContext.Provider+ value={{+ questionState,+ setQuestionState,+ startQuestionGen,+ startMimicQuestionGen,+ resetQuestionGen,+ }}+ >+ {children}+ </QuestionContext.Provider>+ );+}++export const useQuestion = () => {+ const context = useContext(QuestionContext);+ if (!context)+ throw new Error("useQuestion must be used within QuestionProvider");+ return context;+};+diff --git a/web/context/question/index.ts b/web/context/question/index.tsnew file mode 100644index 000000000..9353c4fb2--- /dev/null+++ b/web/context/question/index.ts@@ -0,0 +1,2 @@+export { QuestionProvider, useQuestion } from "./QuestionContext";+diff --git a/web/context/research/ResearchContext.tsx b/web/context/research/ResearchContext.tsxnew file mode 100644index 000000000..82055bc55--- /dev/null+++ b/web/context/research/ResearchContext.tsx@@ -0,0 +1,230 @@+"use client";++import React, {+ createContext,+ useContext,+ useRef,+ useState,+ useCallback,+} from "react";+import { wsUrl } from "@/lib/api";+import {+ ResearchContextState,+ ResearchProgress,+ ActiveTaskInfo,+ QueryInfo,+ INITIAL_RESEARCH_CONTEXT_STATE,+} from "@/types/research";+import { LogEntry } from "@/types/common";++// Context type+interface ResearchContextType {+ researchState: ResearchContextState;+ setResearchState: React.Dispatch<React.SetStateAction<ResearchContextState>>;+ startResearch: (+ topic: string,+ kb: string,+ planMode?: string,+ enabledTools?: string[],+ skipRephrase?: boolean,+ ) => void;+}++const ResearchContext = createContext<ResearchContextType | undefined>(+ undefined,+);++export function ResearchProvider({ children }: { children: React.ReactNode }) {+ const [researchState, setResearchState] = useState<ResearchContextState>(+ INITIAL_RESEARCH_CONTEXT_STATE,+ );+ const researchWs = useRef<WebSocket | null>(null);++ const addResearchLog = useCallback((log: LogEntry) => {+ setResearchState((prev) => ({ ...prev, logs: [...prev.logs, log] }));+ }, []);++ const startResearch = useCallback(+ (+ topic: string,+ kb: string,+ planMode: string = "medium",+ enabledTools: string[] = ["RAG"],+ skipRephrase: boolean = false,+ ) => {+ if (researchWs.current) researchWs.current.close();++ setResearchState((prev) => ({+ ...prev,+ status: "running",+ logs: [],+ report: null,+ topic,+ selectedKb: kb,+ progress: {+ stage: null,+ status: "",+ executionMode: undefined,+ totalBlocks: undefined,+ currentBlock: undefined,+ currentSubTopic: undefined,+ currentBlockId: undefined,+ iterations: undefined,+ maxIterations: undefined,+ toolsUsed: undefined,+ currentTool: undefined,+ currentQuery: undefined,+ currentRationale: undefined,+ queriesUsed: undefined,+ activeTasks: undefined,+ activeCount: undefined,+ completedCount: undefined,+ keptBlocks: undefined,+ sections: undefined,+ wordCount: undefined,+ citations: undefined,+ },+ }));++ const ws = new WebSocket(wsUrl("/api/v1/research/run"));+ researchWs.current = ws;++ ws.onopen = () => {+ ws.send(+ JSON.stringify({+ topic,+ kb_name: kb,+ plan_mode: planMode,+ enabled_tools: enabledTools,+ skip_rephrase: skipRephrase,+ }),+ );+ addResearchLog({+ type: "system",+ content: `Starting Research Pipeline (Plan: ${planMode}, Tools: ${enabledTools.join("+")}, Optimization: ${!skipRephrase ? "On" : "Off/Pre-done"})...`,+ });+ };++ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ if (data.type === "log") {+ addResearchLog(data);+ } else if (data.type === "progress") {+ setResearchState((prev) => {+ // Parse active tasks for parallel mode+ const activeTasks: ActiveTaskInfo[] =+ data.active_tasks?.map((t: any) => ({+ block_id: t.block_id,+ sub_topic: t.sub_topic,+ status: t.status,+ iteration: t.iteration || 0,+ max_iterations: t.max_iterations,+ current_tool: t.current_tool,+ current_query: t.current_query,+ tools_used: t.tools_used,+ })) ?? prev.progress.activeTasks;++ // Parse queries used+ const queriesUsed: QueryInfo[] =+ data.queries_used?.map((q: any) => ({+ query: q.query,+ tool_type: q.tool_type,+ rationale: q.rationale,+ iteration: q.iteration,+ })) ?? prev.progress.queriesUsed;++ return {+ ...prev,+ progress: {+ stage: data.stage,+ status: data.status,+ executionMode:+ data.execution_mode ?? prev.progress.executionMode,+ totalBlocks: data.total_blocks ?? prev.progress.totalBlocks,+ currentBlock: data.current_block ?? prev.progress.currentBlock,+ currentSubTopic:+ data.sub_topic ?? prev.progress.currentSubTopic,+ currentBlockId: data.block_id ?? prev.progress.currentBlockId,+ iterations:+ data.iteration ?? data.iterations ?? prev.progress.iterations,+ maxIterations:+ data.max_iterations ?? prev.progress.maxIterations,+ toolsUsed: data.tools_used ?? prev.progress.toolsUsed,+ currentTool: data.tool_type ?? prev.progress.currentTool,+ currentQuery: data.query ?? prev.progress.currentQuery,+ currentRationale:+ data.rationale ?? prev.progress.currentRationale,+ queriesUsed: queriesUsed,+ activeTasks: activeTasks,+ activeCount: data.active_count ?? prev.progress.activeCount,+ completedCount:+ data.completed_count ?? prev.progress.completedCount,+ keptBlocks: data.kept_blocks ?? prev.progress.keptBlocks,+ sections: data.sections ?? prev.progress.sections,+ wordCount: data.word_count ?? prev.progress.wordCount,+ citations: data.citations ?? prev.progress.citations,+ },+ };+ });+ } else if (data.type === "result") {+ setResearchState((prev) => ({+ ...prev,+ status: "completed",+ report: data.report,+ }));+ ws.close();+ } else if (data.type === "error") {+ addResearchLog({+ type: "error",+ content: `Error: ${data.content || data.message || "Unknown error"}`,+ });+ setResearchState((prev) => ({ ...prev, status: "idle" }));+ }+ };++ ws.onerror = () => {+ addResearchLog({+ type: "error",+ content: "WebSocket connection error",+ });+ setResearchState((prev) => ({+ ...prev,+ status: "idle",+ progress: {+ stage: null,+ status: "",+ executionMode: undefined,+ activeTasks: undefined,+ },+ }));+ };++ ws.onclose = () => {+ if (researchWs.current === ws) {+ researchWs.current = null;+ }+ };+ },+ [addResearchLog],+ );++ return (+ <ResearchContext.Provider+ value={{+ researchState,+ setResearchState,+ startResearch,+ }}+ >+ {children}+ </ResearchContext.Provider>+ );+}++export const useResearch = () => {+ const context = useContext(ResearchContext);+ if (!context)+ throw new Error("useResearch must be used within ResearchProvider");+ return context;+};+diff --git a/web/context/research/index.ts b/web/context/research/index.tsnew file mode 100644index 000000000..4931ded3a--- /dev/null+++ b/web/context/research/index.ts@@ -0,0 +1,2 @@+export { ResearchProvider, useResearch } from "./ResearchContext";+diff --git a/web/context/settings/SidebarContext.tsx b/web/context/settings/SidebarContext.tsxnew file mode 100644index 000000000..9e0998152--- /dev/null+++ b/web/context/settings/SidebarContext.tsx@@ -0,0 +1,178 @@+"use client";++import React, {+ createContext,+ useContext,+ useState,+ useEffect,+ useCallback,+} from "react";+import { apiUrl } from "@/lib/api";+import {+ SidebarNavOrder,+ SIDEBAR_MIN_WIDTH,+ SIDEBAR_MAX_WIDTH,+ SIDEBAR_DEFAULT_WIDTH,+ DEFAULT_SIDEBAR_DESCRIPTION,+ DEFAULT_NAV_ORDER,+} from "@/types/sidebar";++// Context type+interface SidebarContextType {+ // Sidebar dimensions+ sidebarWidth: number;+ setSidebarWidth: (width: number) => void;+ sidebarCollapsed: boolean;+ setSidebarCollapsed: (collapsed: boolean) => void;+ toggleSidebar: () => void;+ // Sidebar customization+ sidebarDescription: string;+ setSidebarDescription: (description: string) => Promise<void>;+ sidebarNavOrder: SidebarNavOrder;+ setSidebarNavOrder: (order: SidebarNavOrder) => Promise<void>;+}++const SidebarContext = createContext<SidebarContextType | undefined>(undefined);++export function SidebarProvider({ children }: { children: React.ReactNode }) {+ // Sidebar dimensions state+ const [sidebarWidth, setSidebarWidthState] =+ useState<number>(SIDEBAR_DEFAULT_WIDTH);+ const [sidebarCollapsed, setSidebarCollapsedState] = useState<boolean>(false);++ // Sidebar customization state+ const [sidebarDescription, setSidebarDescriptionState] = useState<string>(+ DEFAULT_SIDEBAR_DESCRIPTION,+ );+ const [sidebarNavOrder, setSidebarNavOrderState] =+ useState<SidebarNavOrder>(DEFAULT_NAV_ORDER);++ // Initialize sidebar state from localStorage+ useEffect(() => {+ if (typeof window !== "undefined") {+ const storedWidth = localStorage.getItem("sidebarWidth");+ const storedCollapsed = localStorage.getItem("sidebarCollapsed");++ if (storedWidth) {+ const width = parseInt(storedWidth, 10);+ if (+ !isNaN(width) &&+ width >= SIDEBAR_MIN_WIDTH &&+ width <= SIDEBAR_MAX_WIDTH+ ) {+ setSidebarWidthState(width);+ }+ }++ if (storedCollapsed) {+ setSidebarCollapsedState(storedCollapsed === "true");+ }+ }+ }, []);++ // Initialize sidebar customization from backend API+ useEffect(() => {+ const loadSidebarSettings = async () => {+ try {+ const response = await fetch(apiUrl("/api/v1/settings/sidebar"));+ if (response.ok) {+ const data = await response.json();+ if (data.description) {+ setSidebarDescriptionState(data.description);+ }+ if (data.nav_order) {+ setSidebarNavOrderState(data.nav_order);+ }+ }+ } catch (e) {+ console.error("Failed to load sidebar settings from backend:", e);+ }+ };+ loadSidebarSettings();+ }, []);++ const setSidebarWidth = useCallback((width: number) => {+ const clampedWidth = Math.max(+ SIDEBAR_MIN_WIDTH,+ Math.min(SIDEBAR_MAX_WIDTH, width),+ );+ setSidebarWidthState(clampedWidth);+ if (typeof window !== "undefined") {+ localStorage.setItem("sidebarWidth", clampedWidth.toString());+ }+ }, []);++ const setSidebarCollapsed = useCallback((collapsed: boolean) => {+ setSidebarCollapsedState(collapsed);+ if (typeof window !== "undefined") {+ localStorage.setItem("sidebarCollapsed", collapsed.toString());+ }+ }, []);++ const toggleSidebar = useCallback(() => {+ setSidebarCollapsedState((prev) => {+ const newValue = !prev;+ if (typeof window !== "undefined") {+ localStorage.setItem("sidebarCollapsed", newValue.toString());+ }+ return newValue;+ });+ }, []);++ const setSidebarDescription = useCallback(async (description: string) => {+ setSidebarDescriptionState(description);+ // Save to backend+ try {+ await fetch(apiUrl("/api/v1/settings/sidebar/description"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ description }),+ });+ } catch (e) {+ console.error("Failed to save sidebar description:", e);+ }+ }, []);++ const setSidebarNavOrder = useCallback(async (order: SidebarNavOrder) => {+ setSidebarNavOrderState(order);+ // Save to backend+ try {+ await fetch(apiUrl("/api/v1/settings/sidebar/nav-order"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ nav_order: order }),+ });+ } catch (e) {+ console.error("Failed to save sidebar nav order:", e);+ }+ }, []);++ return (+ <SidebarContext.Provider+ value={{+ sidebarWidth,+ setSidebarWidth,+ sidebarCollapsed,+ setSidebarCollapsed,+ toggleSidebar,+ sidebarDescription,+ setSidebarDescription,+ sidebarNavOrder,+ setSidebarNavOrder,+ }}+ >+ {children}+ </SidebarContext.Provider>+ );+}++export const useSidebar = () => {+ const context = useContext(SidebarContext);+ if (!context)+ throw new Error("useSidebar must be used within SidebarProvider");+ return context;+};++// Re-export the SidebarNavOrder type for convenience+export type { SidebarNavOrder };+diff --git a/web/context/settings/UISettingsContext.tsx b/web/context/settings/UISettingsContext.tsxnew file mode 100644index 000000000..50e1c76e5--- /dev/null+++ b/web/context/settings/UISettingsContext.tsx@@ -0,0 +1,162 @@+"use client";++import React, {+ createContext,+ useContext,+ useState,+ useEffect,+ useCallback,+} from "react";+import { apiUrl } from "@/lib/api";+import {+ initializeTheme,+ setTheme,+ getStoredTheme,+} from "@/lib/theme";+import { UISettings, Theme, Language } from "@/types/common";++// Language storage key+const LANGUAGE_STORAGE_KEY = "deeptutor-language";++// Context type+interface UISettingsContextType {+ uiSettings: UISettings;+ refreshSettings: () => Promise<void>;+ updateTheme: (theme: Theme) => Promise<void>;+ updateLanguage: (language: Language) => Promise<void>;+}++const UISettingsContext = createContext<UISettingsContextType | undefined>(+ undefined,+);++export function UISettingsProvider({+ children,+}: {+ children: React.ReactNode;+}) {+ const [uiSettings, setUiSettings] = useState<UISettings>({+ theme: "light",+ language: "en",+ });+ const [isInitialized, setIsInitialized] = useState(false);++ const refreshSettings = useCallback(async () => {+ // Try to load from backend API first, fallback to localStorage+ try {+ const res = await fetch(apiUrl("/api/v1/settings"));+ if (res.ok) {+ const data = await res.json();+ const serverTheme = data.ui?.theme || "light";+ const serverLanguage = data.ui?.language || "en";+ setUiSettings({+ theme: serverTheme,+ language: serverLanguage,+ });+ setTheme(serverTheme);+ // Sync to localStorage as cache+ if (typeof window !== "undefined") {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, serverLanguage);+ }+ return;+ }+ } catch (e) {+ console.warn(+ "Failed to load settings from server, using localStorage:",+ e,+ );+ }++ // Fallback to localStorage+ const storedTheme = getStoredTheme();+ const storedLanguage =+ typeof window !== "undefined"+ ? (localStorage.getItem(LANGUAGE_STORAGE_KEY) as Language) || "en"+ : "en";++ const themeToUse = storedTheme || "light";+ setUiSettings({+ theme: themeToUse,+ language: storedLanguage,+ });+ setTheme(themeToUse);+ }, []);++ const updateTheme = useCallback(async (newTheme: Theme) => {+ // Update UI immediately+ setTheme(newTheme);+ setUiSettings((prev) => ({ ...prev, theme: newTheme }));++ // Persist to backend+ try {+ await fetch(apiUrl("/api/v1/settings/theme"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ theme: newTheme }),+ });+ } catch (e) {+ console.warn("Failed to save theme to server:", e);+ }+ }, []);++ const updateLanguage = useCallback(async (newLanguage: Language) => {+ // Update UI immediately+ setUiSettings((prev) => ({ ...prev, language: newLanguage }));+ if (typeof window !== "undefined") {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, newLanguage);+ }++ // Persist to backend+ try {+ await fetch(apiUrl("/api/v1/settings/language"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ language: newLanguage }),+ });+ } catch (e) {+ console.warn("Failed to save language to server:", e);+ }+ }, []);++ useEffect(() => {+ // Initialize settings on first render+ if (!isInitialized) {+ // First apply localStorage theme immediately to avoid flash+ const initialTheme = initializeTheme();+ const storedLanguage =+ typeof window !== "undefined"+ ? (localStorage.getItem(LANGUAGE_STORAGE_KEY) as Language) || "en"+ : "en";++ setUiSettings({+ theme: initialTheme,+ language: storedLanguage,+ });+ setIsInitialized(true);++ // Then async load from server (which may override)+ refreshSettings();+ }+ }, [isInitialized, refreshSettings]);++ return (+ <UISettingsContext.Provider+ value={{+ uiSettings,+ refreshSettings,+ updateTheme,+ updateLanguage,+ }}+ >+ {children}+ </UISettingsContext.Provider>+ );+}++export const useUISettings = () => {+ const context = useContext(UISettingsContext);+ if (!context)+ throw new Error("useUISettings must be used within UISettingsProvider");+ return context;+};+diff --git a/web/context/settings/index.ts b/web/context/settings/index.tsnew file mode 100644index 000000000..b229a6e69--- /dev/null+++ b/web/context/settings/index.ts@@ -0,0 +1,4 @@+export { UISettingsProvider, useUISettings } from "./UISettingsContext";+export { SidebarProvider, useSidebar } from "./SidebarContext";+export type { SidebarNavOrder } from "./SidebarContext";+diff --git a/web/context/solver/SolverContext.tsx b/web/context/solver/SolverContext.tsxnew file mode 100644index 000000000..ff514ff7b--- /dev/null+++ b/web/context/solver/SolverContext.tsx@@ -0,0 +1,187 @@+"use client";++import React, {+ createContext,+ useContext,+ useRef,+ useState,+ useCallback,+} from "react";+import { wsUrl } from "@/lib/api";+import {+ SolverState,+ SolverChatMessage,+ SolverProgressInfo,+ INITIAL_SOLVER_STATE,+ DEFAULT_SOLVER_AGENT_STATUS,+ DEFAULT_TOKEN_STATS,+} from "@/types/solver";+import { LogEntry, AgentStatus, TokenStats } from "@/types/common";++// Context type+interface SolverContextType {+ solverState: SolverState;+ setSolverState: React.Dispatch<React.SetStateAction<SolverState>>;+ startSolver: (question: string, kb: string) => void;+ stopSolver: () => void;+}++const SolverContext = createContext<SolverContextType | undefined>(undefined);++export function SolverProvider({ children }: { children: React.ReactNode }) {+ const [solverState, setSolverState] =+ useState<SolverState>(INITIAL_SOLVER_STATE);+ const solverWs = useRef<WebSocket | null>(null);++ const addSolverLog = useCallback((log: LogEntry) => {+ setSolverState((prev) => ({ ...prev, logs: [...prev.logs, log] }));+ }, []);++ const startSolver = useCallback(+ (question: string, kb: string) => {+ if (solverWs.current) solverWs.current.close();++ setSolverState((prev) => ({+ ...prev,+ isSolving: true,+ logs: [],+ messages: [+ ...prev.messages,+ { role: "user" as const, content: question },+ ],+ question,+ selectedKb: kb,+ agentStatus: { ...DEFAULT_SOLVER_AGENT_STATUS },+ tokenStats: { ...DEFAULT_TOKEN_STATS },+ progress: {+ stage: null,+ progress: {},+ },+ }));++ const ws = new WebSocket(wsUrl("/api/v1/solve"));+ solverWs.current = ws;++ ws.onopen = () => {+ ws.send(JSON.stringify({ question, kb_name: kb }));+ addSolverLog({ type: "system", content: "Initializing connection..." });+ };++ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ if (data.type === "log") {+ addSolverLog(data);+ } else if (data.type === "agent_status") {+ setSolverState((prev) => ({+ ...prev,+ agentStatus: data.all_agents || {+ ...prev.agentStatus,+ [data.agent]: data.status,+ },+ }));+ } else if (data.type === "token_stats") {+ setSolverState((prev) => ({+ ...prev,+ tokenStats: data.stats || prev.tokenStats,+ }));+ } else if (data.type === "progress") {+ setSolverState((prev) => ({+ ...prev,+ progress: {+ stage: data.stage,+ progress: data.progress || {},+ },+ }));+ } else if (data.type === "result") {+ // Extract relative path from output_dir+ let dirName = "";+ if (data.output_dir) {+ const parts = data.output_dir.split(/[/\\]/);+ dirName = parts[parts.length - 1];+ }++ setSolverState((prev) => ({+ ...prev,+ messages: [+ ...prev.messages,+ {+ role: "assistant" as const,+ content: data.final_answer,+ outputDir: dirName,+ },+ ],+ isSolving: false,+ }));+ ws.close();+ } else if (data.type === "error") {+ addSolverLog({+ type: "error",+ content: `Error: ${data.content || data.message || "Unknown error"}`,+ });+ setSolverState((prev) => ({ ...prev, isSolving: false }));+ }+ };++ ws.onerror = () => {+ addSolverLog({ type: "error", content: "Connection error" });+ setSolverState((prev) => ({+ ...prev,+ isSolving: false,+ agentStatus: {+ InvestigateAgent: "error",+ NoteAgent: "error",+ ManagerAgent: "error",+ SolveAgent: "error",+ ToolAgent: "error",+ ResponseAgent: "error",+ PrecisionAnswerAgent: "error",+ },+ progress: {+ stage: null,+ progress: {},+ },+ }));+ };++ ws.onclose = () => {+ if (solverWs.current === ws) {+ solverWs.current = null;+ }+ };+ },+ [addSolverLog],+ );++ const stopSolver = useCallback(() => {+ if (solverWs.current) {+ solverWs.current.close();+ solverWs.current = null;+ }+ setSolverState((prev) => ({+ ...prev,+ isSolving: false,+ }));+ addSolverLog({ type: "system", content: "Solver stopped by user." });+ }, [addSolverLog]);++ return (+ <SolverContext.Provider+ value={{+ solverState,+ setSolverState,+ startSolver,+ stopSolver,+ }}+ >+ {children}+ </SolverContext.Provider>+ );+}++export const useSolver = () => {+ const context = useContext(SolverContext);+ if (!context)+ throw new Error("useSolver must be used within SolverProvider");+ return context;+};+diff --git a/web/context/solver/index.ts b/web/context/solver/index.tsnew file mode 100644index 000000000..87b96928c--- /dev/null+++ b/web/context/solver/index.ts@@ -0,0 +1,2 @@+export { SolverProvider, useSolver } from "./SolverContext";+diff --git a/web/types/chat.ts b/web/types/chat.tsnew file mode 100644index 000000000..88f4f13e4--- /dev/null+++ b/web/types/chat.ts@@ -0,0 +1,46 @@+// Chat-specific types for home page chat++/**+ * Source references for chat messages+ */+export interface ChatSource {+ rag?: Array<{ kb_name: string; content: string }>;+ web?: Array<{ url: string; title?: string; snippet?: string }>;+}++/**+ * Chat message with sources and streaming state+ */+export interface HomeChatMessage {+ role: "user" | "assistant";+ content: string;+ sources?: ChatSource;+ isStreaming?: boolean;+}++/**+ * Chat state+ */+export interface ChatState {+ sessionId: string | null;+ messages: HomeChatMessage[];+ isLoading: boolean;+ selectedKb: string;+ enableRag: boolean;+ enableWebSearch: boolean;+ currentStage: string | null;+}++/**+ * Initial chat state+ */+export const INITIAL_CHAT_STATE: ChatState = {+ sessionId: null,+ messages: [],+ isLoading: false,+ selectedKb: "",+ enableRag: false,+ enableWebSearch: false,+ currentStage: null,+};+diff --git a/web/types/common.ts b/web/types/common.tsnew file mode 100644index 000000000..a06e57a0e--- /dev/null+++ b/web/types/common.ts@@ -0,0 +1,49 @@+// Shared types used across multiple contexts++/**+ * Generic log entry used by Solver, Question, Research contexts+ */+export interface LogEntry {+ type: string;+ content: string;+ timestamp?: number;+ level?: string;+}++/**+ * Generic agent status mapping+ */+export interface AgentStatus {+ [key: string]: "pending" | "running" | "done" | "error";+}++/**+ * Token usage statistics+ */+export interface TokenStats {+ model: string;+ calls: number;+ tokens: number;+ input_tokens: number;+ output_tokens: number;+ cost: number;+}++/**+ * UI theme type+ */+export type Theme = "light" | "dark";++/**+ * Supported languages+ */+export type Language = "en" | "zh";++/**+ * UI Settings+ */+export interface UISettings {+ theme: Theme;+ language: Language;+}+diff --git a/web/types/ideagen.ts b/web/types/ideagen.tsnew file mode 100644index 000000000..78f989eb5--- /dev/null+++ b/web/types/ideagen.ts@@ -0,0 +1,35 @@+// IdeaGen-specific types++/**+ * Research idea item+ */+export interface ResearchIdea {+ id: string;+ knowledge_point: string;+ description: string;+ research_ideas: string[];+ statement: string;+ expanded: boolean;+ selected: boolean;+}++/**+ * IdeaGen state+ */+export interface IdeaGenState {+ isGenerating: boolean;+ generationStatus: string;+ generatedIdeas: ResearchIdea[];+ progress: { current: number; total: number } | null;+}++/**+ * Initial IdeaGen state+ */+export const INITIAL_IDEAGEN_STATE: IdeaGenState = {+ isGenerating: false,+ generationStatus: "",+ generatedIdeas: [],+ progress: null,+};+diff --git a/web/types/index.ts b/web/types/index.tsnew file mode 100644index 000000000..f53fca17a--- /dev/null+++ b/web/types/index.ts@@ -0,0 +1,13 @@+// Type exports - central export point for all types++// Common types+export * from "./common";++// Domain-specific types+export * from "./solver";+export * from "./question";+export * from "./research";+export * from "./chat";+export * from "./sidebar";+export * from "./ideagen";+diff --git a/web/types/question.ts b/web/types/question.tsindex 8fe1bb949..1c77bbd55 100644--- a/web/types/question.ts+++ b/web/types/question.ts@@ -260,3 +260,105 @@ export interface MimicConfig {selectedKb: string;maxQuestions?: number;}++// ============================================+// Context-specific types (used in GlobalContext)+// ============================================++/**+ * Question progress info for context state+ */+export interface QuestionProgressInfo {+ stage:+ | "planning"+ | "researching"+ | "generating"+ | "validating"+ | "complete"+ // Mimic mode stages+ | "uploading"+ | "parsing"+ | "extracting"+ | null;+ progress: {+ current?: number;+ total?: number;+ round?: number;+ max_rounds?: number;+ status?: string;+ };+ // Parallel generation info+ subFocuses?: Array<{ id: string; focus: string; scenario_hint?: string }>;+ activeQuestions?: string[];+ completedQuestions?: number;+ failedQuestions?: number;+ extendedQuestions?: number;+}++/**+ * Question context state (used in QuestionContext)+ */+export interface QuestionContextState {+ step: "config" | "generating" | "result";+ mode: "knowledge" | "mimic";+ logs: Array<{ type: string; content: string; timestamp?: number }>;+ results: QuestionResult[];+ topic: string;+ difficulty: string;+ type: string;+ count: number;+ selectedKb: string;+ progress: QuestionProgressInfo;+ agentStatus: QuestionAgentStatus;+ tokenStats: QuestionTokenStats;+ uploadedFile: File | null;+ paperPath: string;+}++/**+ * Default question agent status+ */+export const DEFAULT_QUESTION_AGENT_STATUS: QuestionAgentStatus = {+ QuestionGenerationAgent: "pending",+ ValidationWorkflow: "pending",+ RetrievalTool: "pending",+};++/**+ * Default question token stats+ */+export const DEFAULT_QUESTION_TOKEN_STATS: QuestionTokenStats = {+ model: "Unknown",+ calls: 0,+ tokens: 0,+ input_tokens: 0,+ output_tokens: 0,+ cost: 0.0,+};++/**+ * Initial question context state+ */+export const INITIAL_QUESTION_CONTEXT_STATE: QuestionContextState = {+ step: "config",+ mode: "knowledge",+ logs: [],+ results: [],+ topic: "",+ difficulty: "medium",+ type: "choice",+ count: 1,+ selectedKb: "",+ progress: {+ stage: null,+ progress: {},+ subFocuses: [],+ activeQuestions: [],+ completedQuestions: 0,+ failedQuestions: 0,+ },+ agentStatus: DEFAULT_QUESTION_AGENT_STATUS,+ tokenStats: DEFAULT_QUESTION_TOKEN_STATS,+ uploadedFile: null,+ paperPath: "",+};diff --git a/web/types/research.ts b/web/types/research.tsindex 7655815f8..f216a9aa9 100644--- a/web/types/research.ts+++ b/web/types/research.ts@@ -159,3 +159,104 @@ export interface ResearchEvent {research_id?: string;[key: string]: any; // Payload}++// ============================================+// Context-specific types (used in GlobalContext)+// ============================================++/**+ * Active task info for parallel mode+ */+export interface ActiveTaskInfo {+ block_id: string;+ sub_topic: string;+ status: string;+ iteration: number;+ max_iterations?: number;+ current_tool?: string;+ current_query?: string;+ tools_used?: string[];+}++/**+ * Query info for tracking all queries+ */+export interface QueryInfo {+ query: string;+ tool_type: string;+ rationale?: string;+ iteration: number;+}++/**+ * Research progress for context state+ */+export interface ResearchProgress {+ stage: "planning" | "researching" | "reporting" | null;+ status: string;+ executionMode?: "series" | "parallel";+ totalBlocks?: number;+ currentBlock?: number;+ currentSubTopic?: string;+ currentBlockId?: string;+ iterations?: number;+ maxIterations?: number;+ toolsUsed?: string[];+ currentTool?: string;+ currentQuery?: string;+ currentRationale?: string;+ queriesUsed?: QueryInfo[];+ activeTasks?: ActiveTaskInfo[];+ activeCount?: number;+ completedCount?: number;+ keptBlocks?: number;+ sections?: number;+ wordCount?: number;+ citations?: number;+}++/**+ * Research context state (used in ResearchContext)+ */+export interface ResearchContextState {+ status: "idle" | "running" | "completed";+ logs: Array<{ type: string; content: string; timestamp?: number }>;+ report: string | null;+ topic: string;+ selectedKb: string;+ progress: ResearchProgress;+}++/**+ * Initial research context state+ */+export const INITIAL_RESEARCH_CONTEXT_STATE: ResearchContextState = {+ status: "idle",+ logs: [],+ report: null,+ topic: "",+ selectedKb: "",+ progress: {+ stage: null,+ status: "",+ executionMode: undefined,+ totalBlocks: undefined,+ currentBlock: undefined,+ currentSubTopic: undefined,+ currentBlockId: undefined,+ iterations: undefined,+ maxIterations: undefined,+ toolsUsed: undefined,+ currentTool: undefined,+ currentQuery: undefined,+ currentRationale: undefined,+ queriesUsed: undefined,+ activeTasks: undefined,+ activeCount: undefined,+ completedCount: undefined,+ keptBlocks: undefined,+ sections: undefined,+ wordCount: undefined,+ citations: undefined,+ },+};diff --git a/web/types/sidebar.ts b/web/types/sidebar.tsnew file mode 100644index 000000000..09eff3313--- /dev/null+++ b/web/types/sidebar.ts@@ -0,0 +1,38 @@+// Sidebar-specific types++/**+ * Sidebar navigation order configuration+ */+export interface SidebarNavOrder {+ start: string[]; // Array of href paths for START group+ learnResearch: string[]; // Array of href paths for LEARN & RESEARCH group+}++/**+ * Sidebar constants+ */+export const SIDEBAR_MIN_WIDTH = 64;+export const SIDEBAR_MAX_WIDTH = 320;+export const SIDEBAR_DEFAULT_WIDTH = 256;+export const SIDEBAR_COLLAPSED_WIDTH = 64;++/**+ * Default sidebar description+ */+export const DEFAULT_SIDEBAR_DESCRIPTION = "✨ Data Intelligence Lab @ HKU";++/**+ * Default navigation order+ */+export const DEFAULT_NAV_ORDER: SidebarNavOrder = {+ start: ["/", "/history", "/knowledge", "/notebook"],+ learnResearch: [+ "/question",+ "/solver",+ "/guide",+ "/ideagen",+ "/research",+ "/co_writer",+ ],+};+diff --git a/web/types/solver.ts b/web/types/solver.tsnew file mode 100644index 000000000..eb6cfd540--- /dev/null+++ b/web/types/solver.ts@@ -0,0 +1,83 @@+// Solver-specific types++import { LogEntry, AgentStatus, TokenStats } from "./common";++/**+ * Chat message in solver conversation+ */+export interface SolverChatMessage {+ role: "user" | "assistant";+ content: string;+ outputDir?: string;+}++/**+ * Solver progress information+ */+export interface SolverProgressInfo {+ stage: "investigate" | "solve" | "response" | null;+ progress: {+ round?: number;+ queries?: string[];+ step_index?: number;+ step_id?: string;+ step_target?: string;+ };+}++/**+ * Solver state+ */+export interface SolverState {+ isSolving: boolean;+ logs: LogEntry[];+ messages: SolverChatMessage[];+ question: string;+ selectedKb: string;+ agentStatus: AgentStatus;+ tokenStats: TokenStats;+ progress: SolverProgressInfo;+}++/**+ * Default agent status for solver+ */+export const DEFAULT_SOLVER_AGENT_STATUS: AgentStatus = {+ InvestigateAgent: "pending",+ NoteAgent: "pending",+ ManagerAgent: "pending",+ SolveAgent: "pending",+ ToolAgent: "pending",+ ResponseAgent: "pending",+ PrecisionAnswerAgent: "pending",+};++/**+ * Default token stats+ */+export const DEFAULT_TOKEN_STATS: TokenStats = {+ model: "Unknown",+ calls: 0,+ tokens: 0,+ input_tokens: 0,+ output_tokens: 0,+ cost: 0.0,+};++/**+ * Initial solver state+ */+export const INITIAL_SOLVER_STATE: SolverState = {+ isSolving: false,+ logs: [],+ messages: [],+ question: "",+ selectedKb: "",+ agentStatus: DEFAULT_SOLVER_AGENT_STATUS,+ tokenStats: DEFAULT_TOKEN_STATS,+ progress: {+ stage: null,+ progress: {},+ },+};+