DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: env, file upload, web refactor, llm details
Pancakef5b7a2e2df67
diff --git a/.env.example b/.env.exampleindex aeec7bfad..b1274db6b 100644--- a/.env.example+++ b/.env.example@@ -1,4 +1,4 @@-# ==============================================================================+# ==============================================================================# DeepTutor Environment Configuration# ==============================================================================# Copy this file to `.env` and fill in the values.@@ -19,7 +19,9 @@ FRONTEND_PORT=3782# ==============================================================================# Primary LLM for all AI operations (chat, research, solve, etc.)-# [Required] Provider binding: openai, azure_openai, anthropic+# [Required] Provider binding: openai, azure_openai, anthropic,+# deepseek, openrouter, groq, together, mistral+# ollama, lm_studio, vllm, llama_cppLLM_BINDING=openai# [Required] Model name (e.g., gpt-4o, deepseek-chat, claude-3-5-sonnet)@@ -39,7 +41,8 @@ LLM_API_VERSION=# ==============================================================================# Embedding model for RAG (Retrieval-Augmented Generation)-# [Optional] Provider: openai, azure_openai, jina, cohere, ollama+# [Required] Provider: openai, azure_openai, jina,+# cohere, huggingface, google, ollama, lm_studioEMBEDDING_BINDING=openai# [Required] Model namediff --git a/.env.example_CN b/.env.example_CNindex e70fda6eb..5057bb43b 100644--- a/.env.example_CN+++ b/.env.example_CN@@ -1,4 +1,4 @@-# ============================================================================+# ============================================================================# Deep-Tutor 环境配置文件# ============================================================================# 将此文件复制为 .env 并填写您的 API 密钥和设置。@@ -51,7 +51,9 @@ LLM_MODE=hybrid# 您也可以通过设置界面添加提供商,活动时将优先使用。# LLM 服务提供商类型-# 选项:openai、azure_openai、ollama、anthropic+# 提供选项: openai, azure_openai, anthropic,+# deepseek, openrouter, groq, together, mistral+# ollama, lm_studio, vllm, llama_cppLLM_BINDING=openai# LLM 模型名称@@ -86,7 +88,8 @@ DISABLE_SSL_VERIFY=false# 知识库功能必需。# 嵌入服务提供商类型-# 选项:openai、azure_openai、ollama、lollms+# 选项:openai, azure_openai, jina,+# cohere, huggingface, google, ollama, lm_studioEMBEDDING_BINDING=openai# 嵌入模型名称diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex ec179fc43..3c2e5b052 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -72,11 +72,14 @@ repos:pass_filenames: false# Replaced Safety with pip-audit due to version 3.x breakdown- - repo: https://github.com/pypa/pip-audit- rev: v2.7.3- hooks:- - id: pip-audit- args: ["--desc", "on"]+ # NOTE: pip-audit disabled due to pip-api upstream bug with non-ASCII paths on Windows+ # (UnicodeDecodeError when username contains Chinese characters)+ # See: https://github.com/di/pip-api/issues/123+ # - repo: https://github.com/pypa/pip-audit+ # rev: v2.7.3+ # hooks:+ # - id: pip-audit+ # args: ["--desc", "on"]- repo: https://github.com/PyCQA/banditrev: 1.8.0diff --git a/README.md b/README.mdindex 47f62b1d1..8c463e625 100644--- a/README.md+++ b/README.md@@ -245,10 +245,11 @@> 🌟 Star to follow our future updates!- [ x ] Multi-linguistic support- [ x ] DeepTutor Community-- [ x ] Incremental Knowledge-base Edit-- [ x ] Personalized Workspace+- [ x ] Video & Audio file support+- [ x ] Atomic RAG pipeline customize+- [ - ] Incremental Knowledge-base Edit+- [ - ] Personalized Workspace- [ - ] DataBase Visualization-- [ - ] Atomic RAG pipeline customize- [ - ] Online Demo## 🚀 Getting Started@@ -1360,6 +1361,66 @@ docker run -d --name deeptutor \</details>+<details>+<summary><b>Settings page shows "Error loading data" with HTTPS reverse proxy?</b></summary>++**Problem**++When deploying behind an HTTPS reverse proxy (e.g., nginx), the Settings page shows "Error loading data" and browser DevTools reveals that HTTPS requests are being redirected to HTTP (307 redirect).++**Cause**++This issue has been fixed in v0.5.0+. If you're using an older version, the problem was caused by FastAPI's automatic trailing slash redirects generating HTTP URLs instead of preserving the original HTTPS protocol.++**Solution (for v0.5.0+)**++Update to the latest version. The fix disables automatic slash redirects to prevent protocol downgrade.++**Recommended nginx Configuration**++When using nginx as an HTTPS reverse proxy, use the following configuration:++```nginx+# Frontend+location / {+ proxy_pass http://localhost:3782;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+}++# Backend API+location /api/ {+ proxy_pass http://localhost:8001;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme; # Important: preserves original protocol+}++# WebSocket support+location /api/v1/ {+ proxy_pass http://localhost:8001;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection "upgrade";+ proxy_set_header Host $host;+ proxy_set_header X-Forwarded-Proto $scheme;+}+```++**Environment Variable**++Set in `.env`:+```bash+NEXT_PUBLIC_API_BASE=https://your-domain.com:port+```++See: [GitHub Issue #112](https://github.com/HKUDS/DeepTutor/issues/112)++</details>+<details><summary><b>Where are module outputs stored?</b></summary>diff --git a/src/agents/base_agent.py b/src/agents/base_agent.pyindex e91f9a53b..db2802239 100644--- a/src/agents/base_agent.py+++ b/src/agents/base_agent.py@@ -211,6 +211,32 @@ class BaseAgent(ABC):"""return self.agent_config.get("max_retries", settings.retry.max_retries)+ def refresh_config(self) -> None:+ """+ Refresh LLM configuration from the current active settings.++ This method reloads the LLM configuration from the unified config service,+ allowing agents to pick up configuration changes made by users in Settings+ without needing to restart the server or recreate the agent instance.++ Call this method before processing requests if you want to ensure+ the agent uses the latest user-configured LLM settings.+ """+ try:+ llm_config = get_llm_config()+ self.api_key = llm_config.api_key+ self.base_url = llm_config.base_url+ self.model = llm_config.model+ self.api_version = getattr(llm_config, "api_version", None)+ self.binding = getattr(llm_config, "binding", "openai")+ self.logger.debug(+ f"Config refreshed: model={self.model}, base_url={self.base_url[:30]}..."+ if self.base_url+ else f"Config refreshed: model={self.model}"+ )+ except Exception as e:+ self.logger.warning(f"Failed to refresh config: {e}")+# -------------------------------------------------------------------------# Token Tracking# -------------------------------------------------------------------------diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.pyindex 37317111f..02f5ff280 100644--- a/src/agents/co_writer/edit_agent.py+++ b/src/agents/co_writer/edit_agent.py@@ -57,6 +57,16 @@ class EditAgent(BaseAgent):"""Co-writer editing agent using unified BaseAgent."""def __init__(self, language: str = "en"):+ """+ Initialize EditAgent.++ Args:+ language: Language setting ('en' | 'zh'), default 'en'++ Note: LLM configuration (api_key, base_url, model, etc.) is loaded+ automatically from the unified config service. Use refresh_config()+ to pick up configuration changes made in Settings.+ """super().__init__(module_name="co_writer",agent_name="edit_agent",diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.pyindex 5ecb8fd59..9d5100e54 100644--- a/src/agents/co_writer/narrator_agent.py+++ b/src/agents/co_writer/narrator_agent.py@@ -34,6 +34,16 @@ class NarratorAgent(BaseAgent):"""Note Narration Agent - Generate narration script and convert to audio"""def __init__(self, language: str = "en"):+ """+ Initialize NarratorAgent.++ Args:+ language: Language setting ('en' | 'zh'), default 'en'++ Note: LLM configuration (api_key, base_url, model, etc.) is loaded+ automatically from the unified config service. Use refresh_config()+ to pick up configuration changes made in Settings.+ """# Use "narrator" as module_name to get independent temperature/max_tokens configsuper().__init__(module_name="narrator",diff --git a/src/api/main.py b/src/api/main.pyindex cf864fca0..e13763ed8 100644--- a/src/api/main.py+++ b/src/api/main.py@@ -135,7 +135,16 @@ async def lifespan(app: FastAPI):logger.info("Application shutdown")-app = FastAPI(title="DeepTutor API", version="1.0.0", lifespan=lifespan)+app = FastAPI(+ title="DeepTutor API",+ version="1.0.0",+ lifespan=lifespan,+ # Disable automatic trailing slash redirects to prevent protocol downgrade issues+ # when deployed behind HTTPS reverse proxies (e.g., nginx).+ # Without this, FastAPI's 307 redirects may change HTTPS to HTTP.+ # See: https://github.com/HKUDS/DeepTutor/issues/112+ redirect_slashes=False,+)# Configure CORSapp.add_middleware(diff --git a/src/api/routers/co_writer.py b/src/api/routers/co_writer.pyindex bd4d8d6d7..ac43c25e4 100644--- a/src/api/routers/co_writer.py+++ b/src/api/routers/co_writer.py@@ -33,16 +33,44 @@ config = load_config_with_main("solve_config.yaml", project_root) # Use any conlog_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")logger = get_logger("CoWriter", level="INFO", log_dir=log_dir)-agent = EditAgent()+# Get system language for agent+_system_language = config.get("system", {}).get("language", "en")-# Lazy load NarratorAgent (because TTS config may not exist)-_narrator_agent = None+# Singleton agent instances - use refresh_config() before each request+# to pick up any configuration changes from Settings+_edit_agent: EditAgent | None = None+_narrator_agent: NarratorAgent | None = None-def get_narrator_agent():+def get_edit_agent() -> EditAgent:+ """+ Get the singleton EditAgent instance with refreshed configuration.++ Uses a singleton pattern with refresh_config() to ensure:+ 1. Efficient reuse of the agent instance+ 2. Latest LLM configuration from Settings is always used+ """+ global _edit_agent+ if _edit_agent is None:+ _edit_agent = EditAgent(language=_system_language)+ # Refresh config to pick up any changes from Settings+ _edit_agent.refresh_config()+ return _edit_agent+++def get_narrator_agent() -> NarratorAgent:+ """+ Get the singleton NarratorAgent instance with refreshed configuration.++ Uses a singleton pattern with refresh_config() to ensure:+ 1. Efficient reuse of the agent instance+ 2. Latest LLM configuration from Settings is always used+ """global _narrator_agentif _narrator_agent is None:- _narrator_agent = NarratorAgent()+ _narrator_agent = NarratorAgent(language=_system_language)+ # Refresh config to pick up any changes from Settings+ _narrator_agent.refresh_config()return _narrator_agent@@ -71,6 +99,9 @@ class AutoMarkResponse(BaseModel):@router.post("/edit", response_model=EditResponse)async def edit_text(request: EditRequest):try:+ # Get agent with refreshed LLM configuration from Settings+ agent = get_edit_agent()+result = await agent.process(text=request.text,instruction=request.instruction,@@ -93,6 +124,9 @@ async def edit_text(request: EditRequest):async def auto_mark_text(request: AutoMarkRequest):"""AI auto-mark text"""try:+ # Get agent with refreshed LLM configuration from Settings+ agent = get_edit_agent()+result = await agent.auto_mark(text=request.text)# Print token statsdiff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.pyindex e5017a7ac..14556dfaf 100644--- a/src/api/routers/knowledge.py+++ b/src/api/routers/knowledge.py@@ -240,7 +240,7 @@ 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:@@ -253,7 +253,7 @@ 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}@@ -267,7 +267,7 @@ 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)}@@ -281,7 +281,7 @@ 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"}@@ -307,11 +307,11 @@ async def set_default_kb(kb_name: str):"""Set the default knowledge base."""try:manager = get_kb_manager()-+# Verify KB existsif 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:diff --git a/src/api/routers/system.py b/src/api/routers/system.pyindex 48e00feb6..d509a294f 100644--- a/src/api/routers/system.py+++ b/src/api/routers/system.py@@ -82,7 +82,7 @@ async def get_system_status():return result[email protected]("/test/llm/", response_model=TestResponse)[email protected]("/test/llm", response_model=TestResponse)async def test_llm_connection():"""Test LLM model connection by sending a simple completion request@@ -150,7 +150,7 @@ async def test_llm_connection():)[email protected]("/test/embeddings/", response_model=TestResponse)[email protected]("/test/embeddings", response_model=TestResponse)async def test_embeddings_connection():"""Test Embeddings model connection by sending a simple embedding request@@ -201,7 +201,7 @@ async def test_embeddings_connection():)[email protected]("/test/tts/", response_model=TestResponse)[email protected]("/test/tts", response_model=TestResponse)async def test_tts_connection():"""Test TTS model connection by checking configurationdiff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.pyindex 56d6ff8f8..bb7ff46da 100644--- a/src/knowledge/add_documents.py+++ b/src/knowledge/add_documents.py@@ -530,10 +530,11 @@ class DocumentAdder:# Update RAG provider if specifiedif self.rag_provider:metadata["rag_provider"] = self.rag_provider-+# Also save to centralized config filetry: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:diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.pyindex edd4c067d..2ed8deef7 100644--- a/src/knowledge/initializer.py+++ b/src/knowledge/initializer.py@@ -73,7 +73,7 @@ class KnowledgeBaseInitializer:if "knowledge_bases" not in config:config["knowledge_bases"] = {}-+# Remove old "default" field if exists (migration)if "default" in config:del config["default"]@@ -110,16 +110,17 @@ 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 filetry: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")+ logger.info(" ✓ 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 3b950172c..1b42612a8 100644--- a/src/knowledge/manager.py+++ b/src/knowledge/manager.py@@ -7,6 +7,7 @@ Manages multiple knowledge bases and provides utilities for accessing them."""from datetime import datetime+import hashlibimport jsonfrom pathlib import Pathimport shutil@@ -134,6 +135,7 @@ class KnowledgeBaseManager:# 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:@@ -142,7 +144,7 @@ class KnowledgeBaseManager:def get_default(self) -> str | None:"""Get default knowledge base name.-+Priority:1. Centralized config service (knowledge_base_configs.json)2. First knowledge base in the list (auto-fallback)@@ -150,18 +152,19 @@ class KnowledgeBaseManager:# Try centralized config firsttry: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_kbexcept Exception:pass-+# Fallback to first knowledge base in sorted listkb_list = self.list_knowledge_bases()if kb_list:return kb_list[0]-+return Nonedef get_metadata(self, name: str | None = None) -> dict:@@ -378,10 +381,6 @@ class KnowledgeBaseManager:print(f"✓ RAG storage cleaned for '{kb_name}'")return True--def main():- # ============================================================-def link_folder(self, kb_name: str, folder_path: str) -> dict:"""Link a local folder to a knowledge base.@@ -409,14 +408,12 @@ def main():# Get supported files in foldersupported_extensions = {".pdf", ".docx", ".doc", ".txt", ".md", ".markdown"}- files = []+ files: list[Path] = []for ext in supported_extensions:files.extend(folder.glob(f"**/*{ext}"))# Generate folder ID- import hashlib-- folder_id = hashlib.md5(str(folder).encode()).hexdigest()[:8]+ folder_id = hashlib.md5(str(folder).encode(), usedforsecurity=False).hexdigest()[:8]# Load existing linked folders from metadatakb_dir = self.base_dir / kb_name@@ -434,13 +431,13 @@ def main():metadata["linked_folders"] = []# Check if already linked- existing_ids = [f["id"] for f in metadata.get("linked_folders", [])]+ existing_ids = [lf["id"] for lf in metadata.get("linked_folders", [])]if folder_id in existing_ids:# If already linked, treat as success (idempotent)# Find and return existing info- for f in metadata.get("linked_folders", []):- if f["id"] == folder_id:- return f+ for linked in metadata.get("linked_folders", []):+ if linked["id"] == folder_id:+ return linked# Add folder infofolder_info = {diff --git a/src/services/config/__init__.py b/src/services/config/__init__.pyindex b74893491..9f7863906 100644--- a/src/services/config/__init__.py+++ b/src/services/config/__init__.py@@ -16,6 +16,11 @@ Provides three types of configuration:"""# Re-export everything from loader.py (existing functionality)+# Export knowledge base config service+from .knowledge_base_config import (+ KnowledgeBaseConfigService,+ get_kb_config_service,+)from .loader import (PROJECT_ROOT,get_agent_params,@@ -35,12 +40,6 @@ 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",diff --git a/src/services/config/knowledge_base_config.py b/src/services/config/knowledge_base_config.pyindex 399c86012..95f5713e1 100644--- a/src/services/config/knowledge_base_config.py+++ b/src/services/config/knowledge_base_config.py@@ -15,30 +15,36 @@ from src.logging import get_loggerlogger = get_logger("KBConfigService")# Default config file path-DEFAULT_CONFIG_PATH = Path(__file__).parent.parent.parent.parent / "data" / "user" / "settings" / "knowledge_base_configs.json"+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_PATHself._config: Dict[str, Any] = self._load_config()-+@classmethoddef 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():@@ -47,17 +53,14 @@ class KnowledgeBaseConfigService:return json.load(f)except Exception as e:logger.warning(f"Failed to load KB config: {e}")-+# Return default configreturn {"configs": {},"default_kb": None,- "global_defaults": {- "rag_provider": "llamaindex",- "search_mode": "hybrid"- }+ "global_defaults": {"rag_provider": "llamaindex", "search_mode": "hybrid"},}-+def _save_config(self):"""Save configuration to file."""try:@@ -66,133 +69,134 @@ class KnowledgeBaseConfigService: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 defaultsreturn {- "rag_provider": kb_config.get("rag_provider") or defaults.get("rag_provider", "llamaindex"),+ "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+ **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 nameconfig: Configuration dict"""if "configs" not in self._config:self._config["configs"] = {}-+# Merge with existing configexisting = 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_nameself._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 namekb_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 metadataconfig = {}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"@@ -204,4 +208,3 @@ class KnowledgeBaseConfigService:def get_kb_config_service() -> KnowledgeBaseConfigService:"""Get the knowledge base config service instance."""return KnowledgeBaseConfigService.get_instance()-diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.pyindex a79865e06..f33f23972 100644--- a/src/services/config/unified_config.py+++ b/src/services/config/unified_config.py@@ -130,6 +130,126 @@ class UnifiedConfigManager:SETTINGS_DIR.mkdir(parents=True, exist_ok=True)self._initialized = True+ # Ensure default configs exist and are synced with env on startup+ self._ensure_default_configs()++ def _ensure_default_configs(self) -> None:+ """+ Ensure default configurations exist in storage files and sync with env.++ This method is called on startup to:+ 1. Create a "default" config entry in each config file if it doesn't exist+ 2. Sync the model/provider fields from env variables (these may change)+ 3. Store base_url/api_key as {"use_env": "VAR_NAME"} references+ """+ for config_type in ConfigType:+ try:+ self._ensure_default_config_for_type(config_type)+ except Exception as e:+ logger.warning(f"Failed to ensure default config for {config_type.value}: {e}")++ def _ensure_default_config_for_type(self, config_type: ConfigType) -> None:+ """Ensure default config exists and is synced for a specific config type."""+ env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})+ data = self._load_configs(config_type)++ # Find existing default config in the configs list+ default_config = None+ default_index = -1+ for i, cfg in enumerate(data.get("configs", [])):+ if cfg.get("id") == "default":+ default_config = cfg+ default_index = i+ break++ # Build the default config to store+ stored_default = self._build_stored_default_config(config_type, env_mapping)++ if default_config is None:+ # Add default config to the list+ if "configs" not in data:+ data["configs"] = []+ data["configs"].insert(0, stored_default)+ logger.info(f"Created default config for {config_type.value}")+ else:+ # Update only the dynamic fields (model, provider) from env+ # Keep other fields unchanged (they reference env vars)+ if config_type == ConfigType.LLM:+ default_config["model"] = _get_env_value(env_mapping.get("model")) or ""+ default_config["provider"] = _get_env_value(env_mapping.get("provider")) or "openai"+ elif config_type == ConfigType.EMBEDDING:+ default_config["model"] = _get_env_value(env_mapping.get("model")) or ""+ default_config["provider"] = _get_env_value(env_mapping.get("provider")) or "openai"+ dim_str = _get_env_value(env_mapping.get("dimensions"))+ default_config["dimensions"] = (+ int(dim_str) if dim_str and dim_str.isdigit() else 3072+ )+ elif config_type == ConfigType.TTS:+ default_config["model"] = _get_env_value(env_mapping.get("model")) or ""+ default_config["provider"] = _get_env_value(env_mapping.get("provider")) or "openai"+ default_config["voice"] = _get_env_value(env_mapping.get("voice")) or "alloy"+ elif config_type == ConfigType.SEARCH:+ default_config["provider"] = (+ _get_env_value(env_mapping.get("provider")) or "perplexity"+ )++ data["configs"][default_index] = default_config+ logger.debug(f"Updated default config for {config_type.value}")++ self._save_configs(config_type, data)++ def _build_stored_default_config(+ self, config_type: ConfigType, env_mapping: Dict[str, str]+ ) -> Dict[str, Any]:+ """Build the default configuration to be stored in JSON (with env references)."""+ base_config = {+ "id": "default",+ "name": "Default (from .env)",+ "is_default": True,+ }++ if config_type == ConfigType.LLM:+ return {+ **base_config,+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "base_url": {"use_env": "LLM_HOST"},+ "api_key": {"use_env": "LLM_API_KEY"},+ "api_version": {"use_env": "LLM_API_VERSION"},+ }++ elif config_type == ConfigType.EMBEDDING:+ dim_str = _get_env_value(env_mapping.get("dimensions"))+ return {+ **base_config,+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "dimensions": int(dim_str) if dim_str and dim_str.isdigit() else 3072,+ "base_url": {"use_env": "EMBEDDING_HOST"},+ "api_key": {"use_env": "EMBEDDING_API_KEY"},+ "api_version": {"use_env": "EMBEDDING_API_VERSION"},+ }++ elif config_type == ConfigType.TTS:+ return {+ **base_config,+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "voice": _get_env_value(env_mapping.get("voice")) or "alloy",+ "base_url": {"use_env": "TTS_URL"},+ "api_key": {"use_env": "TTS_API_KEY"},+ "api_version": {"use_env": "TTS_BINDING_API_VERSION"},+ }++ elif config_type == ConfigType.SEARCH:+ return {+ **base_config,+ "provider": _get_env_value(env_mapping.get("provider")) or "perplexity",+ "api_key": {"use_env": "SEARCH_API_KEY"},+ }++ return base_config+def _get_storage_path(self, config_type: ConfigType) -> Path:"""Get the storage file path for a config type."""return SETTINGS_DIR / f"{config_type.value}_configs.json"@@ -280,23 +400,46 @@ class UnifiedConfigManager:"""List all configurations for a service type.Includes the default config (from .env) and user-defined configs.++ For display purposes, the default config shows:+ - Current model/provider from env (dynamically refreshed)+ - base_url/api_key as "***" (hidden for security)"""data = self._load_configs(config_type)-- # Build default config- default_config = self._build_default_config(config_type)-- # Get user configs- user_configs = data.get("configs", [])-- # Mark active config+ configs = data.get("configs", [])active_id = data.get("active_id", "default")- all_configs = [default_config] + user_configs- for cfg in all_configs:- cfg["is_active"] = cfg.get("id") == active_id+ # Build a display version of the default config (with current env values)+ display_default = self._build_default_config(config_type)- return all_configs+ # Process all configs for display+ result = []+ has_default = False++ for cfg in configs:+ if cfg.get("id") == "default":+ # Use the dynamically built display config for default+ has_default = True+ display_cfg = display_default.copy()+ display_cfg["is_active"] = active_id == "default"+ result.append(display_cfg)+ else:+ # For user configs, create a display copy+ display_cfg = dict(cfg)+ # Hide api_key if it's not an env reference+ if "api_key" in display_cfg:+ api_key = display_cfg["api_key"]+ if not isinstance(api_key, dict): # Not {"use_env": ...}+ display_cfg["api_key"] = "***"+ display_cfg["is_active"] = cfg.get("id") == active_id+ result.append(display_cfg)++ # If no default config found in file, prepend the display default+ if not has_default:+ display_default["is_active"] = active_id == "default"+ result.insert(0, display_default)++ return resultdef get_config(self, config_type: ConfigType, config_id: str) -> Optional[Dict[str, Any]]:"""Get a specific configuration by ID."""diff --git a/src/services/rag/components/routing.py b/src/services/rag/components/routing.pyindex 13af2a298..25fcc8d4d 100644--- a/src/services/rag/components/routing.py+++ b/src/services/rag/components/routing.py@@ -284,4 +284,3 @@ class FileTypeRouter:"""doc_type = cls.get_document_type(file_path)return doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN)-diff --git a/tests/services/__init__.py b/tests/services/__init__.pynew file mode 100644index 000000000..e31e57ad7--- /dev/null+++ b/tests/services/__init__.py@@ -0,0 +1 @@+# Tests for src/services modulediff --git a/tests/services/rag/__init__.py b/tests/services/rag/__init__.pynew file mode 100644index 000000000..ada87d305--- /dev/null+++ b/tests/services/rag/__init__.py@@ -0,0 +1 @@+# Tests for RAG pipelinediff --git a/tests/services/rag/test_pipeline_integration.py b/tests/services/rag/test_pipeline_integration.pynew file mode 100644index 000000000..9f617f459--- /dev/null+++ b/tests/services/rag/test_pipeline_integration.py@@ -0,0 +1,443 @@+#!/usr/bin/env python+"""+RAG Pipeline Integration Tests+==============================++Complete integration tests for RAG pipelines.+Tests the full workflow: initialize -> search -> delete++Usage:+ # Test specific pipeline+ python tests/services/rag/test_pipeline_integration.py --pipeline llamaindex++ # Test all pipelines+ python tests/services/rag/test_pipeline_integration.py --pipeline all++ # Using pytest+ pytest tests/services/rag/test_pipeline_integration.py -v --pipeline llamaindex+"""++import argparse+import asyncio+import os+import shutil+import sys+import tempfile+from pathlib import Path++# Add project root to path+project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.insert(0, str(project_root))++from dotenv import load_dotenv+load_dotenv(project_root / "DeepTutor.env", override=False)+load_dotenv(project_root / ".env", override=False)+++# Test file path+TEST_FILE = project_root / "tests" / "services" / "rag" / "testfile.txt"+++class Colors:+ """Terminal colors"""+ GREEN = "\033[92m"+ YELLOW = "\033[93m"+ RED = "\033[91m"+ BLUE = "\033[94m"+ BOLD = "\033[1m"+ END = "\033[0m"+++def print_header(text: str):+ print(f"\n{Colors.BOLD}{Colors.BLUE}{'=' * 60}")+ print(f" {text}")+ print(f"{'=' * 60}{Colors.END}\n")+++def print_success(text: str):+ print(f" {Colors.GREEN}✓{Colors.END} {text}")+++def print_warning(text: str):+ print(f" {Colors.YELLOW}⚠{Colors.END} {text}")+++def print_error(text: str):+ print(f" {Colors.RED}✗{Colors.END} {text}")+++def print_info(text: str):+ print(f" {Colors.BLUE}ℹ{Colors.END} {text}")+++class PipelineIntegrationTest:+ """+ Integration test for a specific RAG pipeline.++ Tests:+ 1. Knowledge base initialization with test file+ 2. Search/retrieval+ 3. Knowledge base deletion+ """++ def __init__(self, pipeline_name: str, test_file: Path = TEST_FILE):+ self.pipeline_name = pipeline_name+ self.test_file = test_file+ self.temp_dir = None+ self.kb_name = f"test_kb_{pipeline_name}"+ self.service = None++ async def setup(self):+ """Setup test environment"""+ # Create temporary directory+ self.temp_dir = tempfile.mkdtemp(prefix=f"rag_test_{self.pipeline_name}_")+ print_info(f"Created temp directory: {self.temp_dir}")++ # Initialize service with temp directory+ from src.services.rag import RAGService+ self.service = RAGService(+ kb_base_dir=self.temp_dir,+ provider=self.pipeline_name+ )++ # Verify test file exists+ if not self.test_file.exists():+ raise FileNotFoundError(f"Test file not found: {self.test_file}")++ print_info(f"Test file: {self.test_file}")+ print_info(f"Provider: {self.pipeline_name}")++ async def teardown(self):+ """Cleanup test environment"""+ if self.temp_dir and os.path.exists(self.temp_dir):+ shutil.rmtree(self.temp_dir)+ print_info(f"Cleaned up temp directory: {self.temp_dir}")++ async def test_initialize(self) -> bool:+ """Test knowledge base initialization"""+ print("\n 📚 Testing initialization...")++ try:+ success = await self.service.initialize(+ kb_name=self.kb_name,+ file_paths=[str(self.test_file)],+ )++ if success:+ print_success("Knowledge base initialized successfully")++ # Verify KB directory was created+ kb_dir = Path(self.temp_dir) / self.kb_name+ if kb_dir.exists():+ print_success(f"KB directory created: {kb_dir}")+ # List contents+ contents = list(kb_dir.rglob("*"))+ print_info(f"KB contains {len(contents)} files/directories")+ else:+ print_warning("KB directory not found after initialization")++ return True+ else:+ print_error("Initialization returned False")+ return False++ except Exception as e:+ print_error(f"Initialization failed: {e}")+ import traceback+ traceback.print_exc()+ return False++ async def test_search(self) -> bool:+ """Test search/retrieval"""+ print("\n 🔍 Testing search...")++ # Test query based on test file content+ # testfile.txt contains: "Shandong province has a pancake."+ test_queries = [+ ("Shandong", "Search for 'Shandong'"),+ ("pancake", "Search for 'pancake'"),+ ("What does Shandong have?", "Natural question"),+ ]++ all_passed = True++ for query, description in test_queries:+ try:+ print_info(f"Query: {query} ({description})")++ result = await self.service.search(+ query=query,+ kb_name=self.kb_name,+ mode="naive" if self.pipeline_name in ["llamaindex"] else "hybrid",+ )++ # Check result structure+ if not isinstance(result, dict):+ print_error(f"Result is not a dict: {type(result)}")+ all_passed = False+ continue++ # Check required fields+ required_fields = ["query", "answer", "content", "provider"]+ missing = [f for f in required_fields if f not in result]+ if missing:+ print_warning(f"Missing fields: {missing}")++ # Check content+ answer = result.get("answer", "")+ if answer:+ print_success(f"Got answer ({len(answer)} chars)")+ # Show preview+ preview = answer[:200] + "..." if len(answer) > 200 else answer+ print_info(f"Preview: {preview}")+ else:+ print_warning("Empty answer")++ except Exception as e:+ print_error(f"Search failed: {e}")+ import traceback+ traceback.print_exc()+ all_passed = False++ return all_passed++ async def test_search_via_rag_tool(self) -> bool:+ """Test search via rag_tool.py (the actual interface used by agents)"""+ print("\n 🔧 Testing via rag_tool.py...")++ try:+ from src.tools.rag_tool import rag_search++ result = await rag_search(+ query="What does Shandong have?",+ kb_name=self.kb_name,+ provider=self.pipeline_name,+ kb_base_dir=self.temp_dir,+ mode="naive",+ )++ if result and result.get("answer"):+ print_success(f"rag_tool.py search successful")+ print_info(f"Provider: {result.get('provider')}")+ print_info(f"Answer preview: {result['answer'][:100]}...")+ return True+ else:+ print_warning("rag_tool.py returned empty result")+ return False++ except Exception as e:+ print_error(f"rag_tool.py search failed: {e}")+ import traceback+ traceback.print_exc()+ return False++ async def test_delete(self) -> bool:+ """Test knowledge base deletion"""+ print("\n 🗑️ Testing deletion...")++ try:+ success = await self.service.delete(kb_name=self.kb_name)++ if success:+ print_success("Knowledge base deleted successfully")++ # Verify KB directory was removed+ kb_dir = Path(self.temp_dir) / self.kb_name+ if not kb_dir.exists():+ print_success("KB directory removed")+ else:+ print_warning("KB directory still exists after deletion")++ return True+ else:+ print_warning("Deletion returned False (KB may not exist)")+ return True # Not necessarily a failure++ except Exception as e:+ print_error(f"Deletion failed: {e}")+ return False++ async def run_all_tests(self) -> dict:+ """Run all tests for this pipeline"""+ print_header(f"Testing Pipeline: {self.pipeline_name}")++ results = {+ "pipeline": self.pipeline_name,+ "setup": False,+ "initialize": False,+ "search": False,+ "rag_tool": False,+ "delete": False,+ "cleanup": False,+ }++ try:+ # Setup+ await self.setup()+ results["setup"] = True++ # Initialize+ results["initialize"] = await self.test_initialize()++ # Search (only if initialize succeeded)+ if results["initialize"]:+ results["search"] = await self.test_search()+ results["rag_tool"] = await self.test_search_via_rag_tool()++ # Delete+ results["delete"] = await self.test_delete()++ except Exception as e:+ print_error(f"Test failed with exception: {e}")+ import traceback+ traceback.print_exc()+ finally:+ # Cleanup+ try:+ await self.teardown()+ results["cleanup"] = True+ except Exception as e:+ print_error(f"Cleanup failed: {e}")++ return results+++def get_available_pipelines():+ """Get list of available pipelines"""+ from src.services.rag import RAGService+ return [p["id"] for p in RAGService.list_providers()]+++async def run_pipeline_test(pipeline_name: str) -> dict:+ """Run test for a specific pipeline"""+ test = PipelineIntegrationTest(pipeline_name)+ return await test.run_all_tests()+++async def run_all_pipeline_tests() -> list:+ """Run tests for all pipelines"""+ pipelines = get_available_pipelines()+ results = []++ for pipeline in pipelines:+ result = await run_pipeline_test(pipeline)+ results.append(result)++ return results+++def print_summary(results: list):+ """Print test summary"""+ print_header("Test Summary")++ all_passed = True++ for result in results:+ pipeline = result["pipeline"]+ tests = ["setup", "initialize", "search", "rag_tool", "delete", "cleanup"]+ passed = sum(1 for t in tests if result.get(t, False))+ total = len(tests)++ if passed == total:+ print_success(f"{pipeline}: {passed}/{total} tests passed")+ else:+ print_error(f"{pipeline}: {passed}/{total} tests passed")+ all_passed = False++ # Show failed tests+ for test in tests:+ if not result.get(test, False):+ print_error(f" - {test} failed")++ print()+ if all_passed:+ print(f"{Colors.GREEN}{Colors.BOLD}All tests passed!{Colors.END}")+ else:+ print(f"{Colors.RED}{Colors.BOLD}Some tests failed.{Colors.END}")++ return all_passed+++async def main():+ """Main entry point"""+ parser = argparse.ArgumentParser(description="RAG Pipeline Integration Tests")+ parser.add_argument(+ "--pipeline", "-p",+ type=str,+ default="llamaindex",+ help="Pipeline to test (or 'all' for all pipelines). Default: llamaindex"+ )+ parser.add_argument(+ "--list", "-l",+ action="store_true",+ help="List available pipelines"+ )++ args = parser.parse_args()++ # List pipelines+ if args.list:+ print_header("Available Pipelines")+ for pipeline in get_available_pipelines():+ print_info(pipeline)+ return++ # Run tests+ if args.pipeline.lower() == "all":+ results = await run_all_pipeline_tests()+ else:+ # Validate pipeline name+ available = get_available_pipelines()+ if args.pipeline not in available:+ print_error(f"Unknown pipeline: {args.pipeline}")+ print_info(f"Available: {available}")+ sys.exit(1)++ results = [await run_pipeline_test(args.pipeline)]++ # Print summary+ success = print_summary(results)+ sys.exit(0 if success else 1)+++# Pytest support+def pytest_addoption(parser):+ """Add pytest command line options"""+ parser.addoption(+ "--pipeline",+ action="store",+ default="llamaindex",+ help="Pipeline to test"+ )+++class TestPipelineIntegration:+ """Pytest test class"""++ @staticmethod+ def test_pipeline(request):+ """Test the specified pipeline"""+ pipeline_name = request.config.getoption("--pipeline")++ async def _run():+ if pipeline_name.lower() == "all":+ results = await run_all_pipeline_tests()+ else:+ results = [await run_pipeline_test(pipeline_name)]++ # Assert all tests passed+ for result in results:+ assert result["setup"], f"{result['pipeline']}: Setup failed"+ assert result["initialize"], f"{result['pipeline']}: Initialize failed"+ assert result["search"], f"{result['pipeline']}: Search failed"+ assert result["rag_tool"], f"{result['pipeline']}: rag_tool test failed"+ assert result["delete"], f"{result['pipeline']}: Delete failed"++ asyncio.run(_run())+++if __name__ == "__main__":+ if sys.platform == "win32":+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())++ asyncio.run(main())diff --git a/tests/services/rag/test_rag_pipelines.py b/tests/services/rag/test_rag_pipelines.pynew file mode 100644index 000000000..bef019720--- /dev/null+++ b/tests/services/rag/test_rag_pipelines.py@@ -0,0 +1,610 @@+#!/usr/bin/env python+"""+RAG Pipeline Integration Tests+==============================++测试所有RAG pipeline的完整功能:+- 知识库初始化(文档处理)+- 检索/搜索功能+- 删除知识库++运行方式:+ python -m pytest tests/services/rag/test_rag_pipelines.py -v++或直接运行:+ python tests/services/rag/test_rag_pipelines.py+"""++import asyncio+import json+import os+import shutil+import sys+import tempfile+from pathlib import Path+from typing import Dict, List, Optional+import unittest++# Add project root to path+project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.insert(0, str(project_root))++from dotenv import load_dotenv+load_dotenv(project_root / "DeepTutor.env", override=False)+load_dotenv(project_root / ".env", override=False)+++class RAGPipelineTestBase:+ """Base class for RAG pipeline tests"""++ TEST_KB_NAME = "test_rag_pipeline"+ TEST_QUERY = "What is machine learning?"++ @classmethod+ def create_test_document(cls, temp_dir: str) -> str:+ """Create a test document for testing"""+ test_content = """+# Introduction to Machine Learning++Machine learning is a subset of artificial intelligence (AI) that provides systems+the ability to automatically learn and improve from experience without being explicitly+programmed.++## Types of Machine Learning++### Supervised Learning+Supervised learning is a type of machine learning where the model is trained on labeled data.+The model learns to map input features to output labels.++Examples:+- Classification: Predicting discrete labels+- Regression: Predicting continuous values++### Unsupervised Learning+Unsupervised learning is a type of machine learning where the model is trained on unlabeled data.+The model learns to find patterns and structures in the data.++Examples:+- Clustering: Grouping similar data points+- Dimensionality reduction: Reducing the number of features++### Reinforcement Learning+Reinforcement learning is a type of machine learning where an agent learns to make decisions+by interacting with an environment and receiving rewards or penalties.++## Key Concepts++### Training Data+Training data is the dataset used to train a machine learning model.++### Features+Features are the input variables used to make predictions.++### Labels+Labels are the output variables (targets) in supervised learning.++### Model+A model is a mathematical representation of a real-world process.++## Conclusion++Machine learning has many applications in various fields including:+- Natural language processing+- Computer vision+- Recommendation systems+- Autonomous vehicles+"""++ # Create both .md and .txt versions+ md_path = os.path.join(temp_dir, "ml_intro.md")+ with open(md_path, "w", encoding="utf-8") as f:+ f.write(test_content)++ return md_path+++class TestRAGToolIntegration(unittest.IsolatedAsyncioTestCase):+ """Test rag_tool.py interface with all pipelines"""++ async def test_list_available_providers(self):+ """Test listing available RAG providers"""+ from src.tools.rag_tool import get_available_providers, list_pipelines++ providers = get_available_providers()+ print("\n=== Available RAG Providers ===")+ for p in providers:+ print(f" - {p['id']}: {p['name']} - {p['description']}")++ self.assertIsInstance(providers, list)+ self.assertGreater(len(providers), 0)++ # Check expected providers+ provider_ids = [p["id"] for p in providers]+ expected = ["raganything", "lightrag", "llamaindex", "academic"]+ for expected_id in expected:+ self.assertIn(expected_id, provider_ids, f"Missing provider: {expected_id}")++ async def test_get_current_provider(self):+ """Test getting current RAG provider"""+ from src.tools.rag_tool import get_current_provider++ provider = get_current_provider()+ print(f"\n=== Current Provider: {provider} ===")++ self.assertIsInstance(provider, str)+ self.assertIn(provider, ["raganything", "lightrag", "llamaindex", "academic"])++ async def test_has_pipeline_valid(self):+ """Test has_pipeline with valid pipeline names"""+ from src.services.rag.factory import has_pipeline++ for name in ["raganything", "lightrag", "llamaindex", "academic"]:+ self.assertTrue(has_pipeline(name), f"Pipeline {name} should exist")++ async def test_has_pipeline_invalid(self):+ """Test has_pipeline with invalid pipeline name"""+ from src.services.rag.factory import has_pipeline++ self.assertFalse(has_pipeline("nonexistent"))+ self.assertFalse(has_pipeline(""))+++class TestPipelineFactory(unittest.IsolatedAsyncioTestCase):+ """Test pipeline factory functionality"""++ async def test_get_pipeline_raganything(self):+ """Test getting RAGAnything pipeline"""+ from src.services.rag.factory import get_pipeline+ from src.services.rag.pipelines.raganything import RAGAnythingPipeline++ pipeline = get_pipeline("raganything")+ self.assertIsInstance(pipeline, RAGAnythingPipeline)+ print(f"\n✓ RAGAnything pipeline created: {type(pipeline).__name__}")++ async def test_get_pipeline_lightrag(self):+ """Test getting LightRAG pipeline"""+ from src.services.rag.factory import get_pipeline+ from src.services.rag.pipeline import RAGPipeline++ pipeline = get_pipeline("lightrag")+ self.assertIsInstance(pipeline, RAGPipeline)+ self.assertEqual(pipeline.name, "lightrag")+ print(f"\n✓ LightRAG pipeline created: {pipeline.name}")++ async def test_get_pipeline_llamaindex(self):+ """Test getting LlamaIndex pipeline"""+ from src.services.rag.factory import get_pipeline+ from src.services.rag.pipeline import RAGPipeline++ pipeline = get_pipeline("llamaindex")+ self.assertIsInstance(pipeline, RAGPipeline)+ self.assertEqual(pipeline.name, "llamaindex")+ print(f"\n✓ LlamaIndex pipeline created: {pipeline.name}")++ async def test_get_pipeline_academic(self):+ """Test getting Academic pipeline"""+ from src.services.rag.factory import get_pipeline+ from src.services.rag.pipeline import RAGPipeline++ pipeline = get_pipeline("academic")+ self.assertIsInstance(pipeline, RAGPipeline)+ self.assertEqual(pipeline.name, "academic")+ print(f"\n✓ Academic pipeline created: {pipeline.name}")++ async def test_get_pipeline_invalid(self):+ """Test getting invalid pipeline raises error"""+ from src.services.rag.factory import get_pipeline++ with self.assertRaises(ValueError) as context:+ get_pipeline("nonexistent")++ self.assertIn("Unknown pipeline", str(context.exception))+ print(f"\n✓ Invalid pipeline correctly raises error")+++class TestRAGAnythingPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):+ """Test RAGAnything pipeline (requires RAG-Anything library)"""++ def setUp(self):+ """Set up test fixtures"""+ self.temp_dir = tempfile.mkdtemp()+ self.test_doc = self.create_test_document(self.temp_dir)+ self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")+ os.makedirs(self.test_kb_dir, exist_ok=True)++ def tearDown(self):+ """Clean up test fixtures"""+ shutil.rmtree(self.temp_dir, ignore_errors=True)++ async def test_raganything_availability(self):+ """Test if RAGAnything dependencies are available"""+ print("\n=== Testing RAGAnything Availability ===")++ try:+ from src.services.rag.pipelines.raganything import RAGAnythingPipeline+ pipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)+ print("✓ RAGAnythingPipeline class available")++ # Check RAG-Anything import+ try:+ pipeline._setup_raganything_path()+ from raganything import RAGAnything, RAGAnythingConfig+ print("✓ RAG-Anything library available")+ return True+ except ImportError as e:+ print(f"⚠ RAG-Anything library not available: {e}")+ print(" Install RAG-Anything to enable full functionality")+ return False++ except ImportError as e:+ print(f"✗ Failed to import RAGAnythingPipeline: {e}")+ return False++ @unittest.skipUnless(+ os.environ.get("TEST_RAG_ANYTHING", "").lower() == "true",+ "Set TEST_RAG_ANYTHING=true to run RAGAnything tests"+ )+ async def test_raganything_full_workflow(self):+ """Test RAGAnything full workflow: initialize -> search -> delete"""+ print("\n=== Testing RAGAnything Full Workflow ===")++ from src.services.rag.pipelines.raganything import RAGAnythingPipeline++ pipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)++ # Test initialization+ print(f"Initializing KB with document: {self.test_doc}")+ success = await pipeline.initialize(+ kb_name=self.TEST_KB_NAME,+ file_paths=[self.test_doc],+ extract_numbered_items=False # Skip for speed+ )+ self.assertTrue(success)+ print("✓ Knowledge base initialized")++ # Test search+ print(f"Searching: {self.TEST_QUERY}")+ result = await pipeline.search(+ query=self.TEST_QUERY,+ kb_name=self.TEST_KB_NAME,+ mode="naive"+ )+ self.assertIn("answer", result)+ self.assertIn("content", result)+ print(f"✓ Search result: {result['answer'][:100]}...")++ # Test delete+ deleted = await pipeline.delete(kb_name=self.TEST_KB_NAME)+ self.assertTrue(deleted)+ print("✓ Knowledge base deleted")+++class TestLlamaIndexPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):+ """Test LlamaIndex pipeline (lightweight implementation)"""++ def setUp(self):+ """Set up test fixtures"""+ self.temp_dir = tempfile.mkdtemp()+ self.test_doc = self.create_test_document(self.temp_dir)+ self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")+ os.makedirs(self.test_kb_dir, exist_ok=True)++ def tearDown(self):+ """Clean up test fixtures"""+ shutil.rmtree(self.temp_dir, ignore_errors=True)++ async def test_llamaindex_components(self):+ """Test LlamaIndex pipeline components are properly configured"""+ print("\n=== Testing LlamaIndex Pipeline Components ===")++ from src.services.rag.factory import get_pipeline++ pipeline = get_pipeline("llamaindex")++ # Check components+ self.assertIsNotNone(pipeline._parser)+ self.assertGreater(len(pipeline._chunkers), 0)+ self.assertIsNotNone(pipeline._embedder)+ self.assertGreater(len(pipeline._indexers), 0)+ self.assertIsNotNone(pipeline._retriever)++ print(f"✓ Parser: {pipeline._parser.name}")+ print(f"✓ Chunkers: {[c.name for c in pipeline._chunkers]}")+ print(f"✓ Embedder: {pipeline._embedder.name}")+ print(f"✓ Indexers: {[i.name for i in pipeline._indexers]}")+ print(f"✓ Retriever: {pipeline._retriever.name}")++ @unittest.skipUnless(+ os.environ.get("TEST_LLAMAINDEX", "").lower() == "true" or+ os.environ.get("TEST_ALL_PIPELINES", "").lower() == "true",+ "Set TEST_LLAMAINDEX=true to run LlamaIndex tests"+ )+ async def test_llamaindex_full_workflow(self):+ """Test LlamaIndex pipeline full workflow"""+ print("\n=== Testing LlamaIndex Full Workflow ===")++ from src.services.rag.factory import get_pipeline++ pipeline = get_pipeline("llamaindex")++ # Patch the kb_base_dir for indexer and retriever+ for indexer in pipeline._indexers:+ indexer.kb_base_dir = self.test_kb_dir+ pipeline._retriever.kb_base_dir = self.test_kb_dir++ # Test initialization+ print(f"Initializing KB with document: {self.test_doc}")+ try:+ success = await pipeline.initialize(+ kb_name=self.TEST_KB_NAME,+ file_paths=[self.test_doc]+ )+ self.assertTrue(success)+ print("✓ Knowledge base initialized")+ except Exception as e:+ print(f"⚠ Initialization failed (may need PDF support): {e}")+ return++ # Test search+ print(f"Searching: {self.TEST_QUERY}")+ result = await pipeline.search(+ query=self.TEST_QUERY,+ kb_name=self.TEST_KB_NAME+ )+ self.assertIn("answer", result)+ print(f"✓ Search result: {result.get('answer', '')[:100]}...")+++class TestLightRAGPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):+ """Test LightRAG pipeline (requires RAG-Anything)"""++ async def test_lightrag_components(self):+ """Test LightRAG pipeline components are properly configured"""+ print("\n=== Testing LightRAG Pipeline Components ===")++ from src.services.rag.factory import get_pipeline++ pipeline = get_pipeline("lightrag")++ # Check components+ self.assertIsNotNone(pipeline._parser)+ self.assertGreater(len(pipeline._chunkers), 0)+ self.assertIsNotNone(pipeline._embedder)+ self.assertGreater(len(pipeline._indexers), 0)+ self.assertIsNotNone(pipeline._retriever)++ print(f"✓ Parser: {pipeline._parser.name}")+ print(f"✓ Chunkers: {[c.name for c in pipeline._chunkers]}")+ print(f"✓ Embedder: {pipeline._embedder.name}")+ print(f"✓ Indexers: {[i.name for i in pipeline._indexers]}")+ print(f"✓ Retriever: {pipeline._retriever.name}")++ # Note: This pipeline requires RAG-Anything for full functionality+ print("\n⚠ Note: LightRAG pipeline requires RAG-Anything for search/indexing")+++class TestAcademicPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):+ """Test Academic pipeline (requires RAG-Anything)"""++ async def test_academic_components(self):+ """Test Academic pipeline components are properly configured"""+ print("\n=== Testing Academic Pipeline Components ===")++ from src.services.rag.factory import get_pipeline++ pipeline = get_pipeline("academic")++ # Check components - Academic has 2 chunkers+ self.assertIsNotNone(pipeline._parser)+ self.assertEqual(len(pipeline._chunkers), 2) # SemanticChunker + NumberedItemExtractor+ self.assertIsNotNone(pipeline._embedder)+ self.assertGreater(len(pipeline._indexers), 0)+ self.assertIsNotNone(pipeline._retriever)++ print(f"✓ Parser: {pipeline._parser.name}")+ print(f"✓ Chunkers: {[c.name for c in pipeline._chunkers]}")+ print(f"✓ Embedder: {pipeline._embedder.name}")+ print(f"✓ Indexers: {[i.name for i in pipeline._indexers]}")+ print(f"✓ Retriever: {pipeline._retriever.name}")++ # Note: This pipeline requires RAG-Anything for full functionality+ print("\n⚠ Note: Academic pipeline requires RAG-Anything for search/indexing")+++class TestRAGToolWithProviders(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):+ """Test rag_tool.py with different providers"""++ def setUp(self):+ """Set up test fixtures"""+ self.temp_dir = tempfile.mkdtemp()+ self.test_doc = self.create_test_document(self.temp_dir)+ self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")+ os.makedirs(self.test_kb_dir, exist_ok=True)++ def tearDown(self):+ """Clean up test fixtures"""+ shutil.rmtree(self.temp_dir, ignore_errors=True)++ async def test_rag_search_invalid_provider(self):+ """Test rag_search with invalid provider raises error"""+ from src.tools.rag_tool import rag_search++ print("\n=== Testing Invalid Provider Error ===")++ with self.assertRaises(ValueError) as context:+ await rag_search(+ query=self.TEST_QUERY,+ kb_name=self.TEST_KB_NAME,+ provider="nonexistent"+ )++ self.assertIn("not found", str(context.exception))+ print(f"✓ Invalid provider correctly raises error: {context.exception}")++ async def test_rag_search_default_provider(self):+ """Test rag_search uses default provider from env"""+ from src.tools.rag_tool import get_current_provider, DEFAULT_RAG_PROVIDER++ print("\n=== Testing Default Provider ===")++ current = get_current_provider()+ print(f"✓ Default provider from env: {DEFAULT_RAG_PROVIDER}")+ print(f"✓ Current provider: {current}")++ # They should match+ self.assertEqual(current, os.getenv("RAG_PROVIDER", "raganything"))+++class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):+ """Test individual component availability"""++ async def test_parsers_available(self):+ """Test all parsers can be imported"""+ print("\n=== Testing Parser Availability ===")++ from src.services.rag.components.parsers import PDFParser, MarkdownParser++ pdf_parser = PDFParser()+ print(f"✓ PDFParser: {pdf_parser.name}")++ md_parser = MarkdownParser()+ print(f"✓ MarkdownParser: {md_parser.name}")++ async def test_chunkers_available(self):+ """Test all chunkers can be imported"""+ print("\n=== Testing Chunker Availability ===")++ from src.services.rag.components.chunkers import (+ SemanticChunker, FixedSizeChunker, NumberedItemExtractor+ )++ semantic = SemanticChunker()+ print(f"✓ SemanticChunker: {semantic.name}")++ fixed = FixedSizeChunker()+ print(f"✓ FixedSizeChunker: {fixed.name}")++ numbered = NumberedItemExtractor()+ print(f"✓ NumberedItemExtractor: {numbered.name}")++ async def test_embedders_available(self):+ """Test all embedders can be imported"""+ print("\n=== Testing Embedder Availability ===")++ from src.services.rag.components.embedders import OpenAIEmbedder++ embedder = OpenAIEmbedder()+ print(f"✓ OpenAIEmbedder: {embedder.name}")++ async def test_indexers_available(self):+ """Test all indexers can be imported"""+ print("\n=== Testing Indexer Availability ===")++ from src.services.rag.components.indexers import VectorIndexer, GraphIndexer++ vector = VectorIndexer()+ print(f"✓ VectorIndexer: {vector.name}")++ graph = GraphIndexer()+ print(f"✓ GraphIndexer: {graph.name}")++ async def test_retrievers_available(self):+ """Test all retrievers can be imported"""+ print("\n=== Testing Retriever Availability ===")++ from src.services.rag.components.retrievers import DenseRetriever, HybridRetriever++ dense = DenseRetriever()+ print(f"✓ DenseRetriever: {dense.name}")++ hybrid = HybridRetriever()+ print(f"✓ HybridRetriever: {hybrid.name}")+++class TestExistingKnowledgeBase(unittest.IsolatedAsyncioTestCase):+ """Test search on existing knowledge bases"""++ @unittest.skipUnless(+ os.environ.get("TEST_EXISTING_KB", "").lower() == "true",+ "Set TEST_EXISTING_KB=true to test existing KBs"+ )+ async def test_search_existing_kb(self):+ """Test search on an existing knowledge base"""+ print("\n=== Testing Existing Knowledge Base ===")++ from src.tools.rag_tool import rag_search++ # Use default or specified KB+ kb_name = os.environ.get("TEST_KB_NAME", "ai-textbook")+ query = os.environ.get("TEST_QUERY", "What is machine learning?")++ print(f"KB: {kb_name}")+ print(f"Query: {query}")++ # Test with different modes+ for mode in ["naive", "hybrid"]:+ print(f"\n--- Mode: {mode} ---")+ try:+ result = await rag_search(+ query=query,+ kb_name=kb_name,+ mode=mode+ )+ print(f"✓ Provider: {result.get('provider', 'unknown')}")+ print(f"✓ Answer length: {len(result.get('answer', ''))} chars")+ print(f"✓ Preview: {result.get('answer', '')[:200]}...")+ except Exception as e:+ print(f"✗ Failed: {e}")+++def run_quick_tests():+ """Run quick tests that don't require external services"""+ print("=" * 60)+ print("Running Quick RAG Pipeline Tests")+ print("=" * 60)++ # Run only fast tests+ loader = unittest.TestLoader()+ suite = unittest.TestSuite()++ # Add quick tests+ suite.addTests(loader.loadTestsFromTestCase(TestRAGToolIntegration))+ suite.addTests(loader.loadTestsFromTestCase(TestPipelineFactory))+ suite.addTests(loader.loadTestsFromTestCase(TestComponentAvailability))++ runner = unittest.TextTestRunner(verbosity=2)+ result = runner.run(suite)++ return result.wasSuccessful()+++def run_all_tests():+ """Run all tests including those requiring external services"""+ print("=" * 60)+ print("Running All RAG Pipeline Tests")+ print("=" * 60)+ print("\nEnvironment variables for full testing:")+ print(" TEST_RAG_ANYTHING=true - Run RAGAnything tests")+ print(" TEST_LLAMAINDEX=true - Run LlamaIndex tests")+ print(" TEST_ALL_PIPELINES=true - Run all pipeline tests")+ print(" TEST_EXISTING_KB=true - Test existing KBs")+ print(" TEST_KB_NAME=<name> - KB name for existing KB test")+ print(" TEST_QUERY=<query> - Query for existing KB test")+ print("=" * 60 + "\n")++ unittest.main(verbosity=2)+++if __name__ == "__main__":+ import argparse++ parser = argparse.ArgumentParser(description="RAG Pipeline Tests")+ parser.add_argument("--quick", action="store_true", help="Run only quick tests")+ parser.add_argument("--all", action="store_true", help="Run all tests")+ args = parser.parse_args()++ if args.quick:+ success = run_quick_tests()+ sys.exit(0 if success else 1)+ else:+ run_all_tests()diff --git a/tests/services/rag/testfile.txt b/tests/services/rag/testfile.txtnew file mode 100644index 000000000..774a88dff--- /dev/null+++ b/tests/services/rag/testfile.txt@@ -0,0 +1,2 @@+this is a test file+Shandong province has a pancake.\ No newline at end of filediff --git a/web/.env.local b/web/.env.localindex 0b6543af3..8840a64d6 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.tsxindex 34b5cf646..9fadfa634 100644--- a/web/app/guide/components/ChatPanel.tsx+++ b/web/app/guide/components/ChatPanel.tsx@@ -159,4 +159,3 @@ export default function ChatPanel({</div>);}-diff --git a/web/app/guide/components/CompletionSummary.tsx b/web/app/guide/components/CompletionSummary.tsxindex e9c57a1bf..1b2b2b7aa 100644--- a/web/app/guide/components/CompletionSummary.tsx+++ b/web/app/guide/components/CompletionSummary.tsx@@ -70,4 +70,3 @@ export default function CompletionSummary({ summary }: CompletionSummaryProps) {</div>);}-diff --git a/web/app/guide/components/DebugModal.tsx b/web/app/guide/components/DebugModal.tsxindex 8654514c1..0aeee67e2 100644--- a/web/app/guide/components/DebugModal.tsx+++ b/web/app/guide/components/DebugModal.tsx@@ -9,7 +9,11 @@ interface DebugModalProps {onFix: (description: string) => Promise<boolean>;}-export default function DebugModal({ isOpen, onClose, onFix }: DebugModalProps) {+export default function DebugModal({+ isOpen,+ onClose,+ onFix,+}: DebugModalProps) {const [description, setDescription] = useState("");const [fixing, setFixing] = useState(false);@@ -91,4 +95,3 @@ export default function DebugModal({ isOpen, onClose, onFix }: DebugModalProps)</div>);}-diff --git a/web/app/guide/components/HTMLViewer.tsx b/web/app/guide/components/HTMLViewer.tsxindex 2c287caa3..509328747 100644--- a/web/app/guide/components/HTMLViewer.tsx+++ b/web/app/guide/components/HTMLViewer.tsx@@ -106,4 +106,3 @@ export default function HTMLViewer({</div>);}-diff --git a/web/app/guide/components/NotebookSelector.tsx b/web/app/guide/components/NotebookSelector.tsxindex 369691ca5..4907c17bc 100644--- a/web/app/guide/components/NotebookSelector.tsx+++ b/web/app/guide/components/NotebookSelector.tsx@@ -228,4 +228,3 @@ export default function NotebookSelector({</div>);}-diff --git a/web/app/guide/components/ProgressPanel.tsx b/web/app/guide/components/ProgressPanel.tsxindex 092f45b95..f49d64593 100644--- a/web/app/guide/components/ProgressPanel.tsx+++ b/web/app/guide/components/ProgressPanel.tsx@@ -110,4 +110,3 @@ export default function ProgressPanel({</div>);}-diff --git a/web/app/guide/components/index.ts b/web/app/guide/components/index.tsindex a014699e3..ec383f05d 100644--- a/web/app/guide/components/index.ts+++ b/web/app/guide/components/index.ts@@ -4,4 +4,3 @@ 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.tsindex f8f272b9d..87268e73a 100644--- a/web/app/guide/hooks/index.ts+++ b/web/app/guide/hooks/index.ts@@ -1,4 +1,3 @@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.tsindex f9181c4fc..6b50a345c 100644--- a/web/app/guide/hooks/useGuideSession.ts+++ b/web/app/guide/hooks/useGuideSession.ts@@ -12,8 +12,9 @@ import {* Hook for managing guide session state and API interactions*/export function useGuideSession() {- const [sessionState, setSessionState] =- useState<SessionState>(INITIAL_SESSION_STATE);+ const [sessionState, setSessionState] = useState<SessionState>(+ INITIAL_SESSION_STATE,+ );const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);const [isLoading, setIsLoading] = useState(false);const [loadingMessage, setLoadingMessage] = useState("");@@ -34,11 +35,7 @@ export function useGuideSession() {}, []);const addChatMessage = useCallback(- (- role: "user" | "assistant" | "system",- content: string,- id?: string,- ) => {+ (role: "user" | "assistant" | "system", content: string, id?: string) => {setChatMessages((prev) => [...prev,{@@ -408,4 +405,3 @@ export function useGuideSession() {fixHtml,};}-diff --git a/web/app/guide/hooks/useKaTeXInjection.ts b/web/app/guide/hooks/useKaTeXInjection.tsindex 09c479fc7..840f8cdf4 100644--- a/web/app/guide/hooks/useKaTeXInjection.ts+++ b/web/app/guide/hooks/useKaTeXInjection.ts@@ -69,4 +69,3 @@ ${html}return { injectKaTeX };}-diff --git a/web/app/guide/hooks/useNotebookSelection.ts b/web/app/guide/hooks/useNotebookSelection.tsindex dbf16a164..8d0f61db7 100644--- a/web/app/guide/hooks/useNotebookSelection.ts+++ b/web/app/guide/hooks/useNotebookSelection.ts@@ -144,4 +144,3 @@ export function useNotebookSelection() {clearAllSelections,};}-diff --git a/web/app/guide/types.ts b/web/app/guide/types.tsindex 9bf46082c..44174101b 100644--- a/web/app/guide/types.ts+++ b/web/app/guide/types.ts@@ -73,4 +73,3 @@ export function getTypeColor(type: string): string {return "bg-slate-100 text-slate-700 border-slate-200";}}-diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsxindex 31e5d2219..ab26e96a3 100644--- a/web/app/knowledge/page.tsx+++ b/web/app/knowledge/page.tsx@@ -1,6 +1,37 @@"use client";import { useState, useEffect, useCallback, useRef } from "react";++// Type declarations for FileSystem Entry API (drag & drop folder support)+interface FileSystemEntry {+ isFile: boolean;+ isDirectory: boolean;+ name: string;+}++interface FileSystemFileEntry extends FileSystemEntry {+ file(+ successCallback: (file: File) => void,+ errorCallback?: (error: Error) => void,+ ): void;+}++interface FileSystemDirectoryEntry extends FileSystemEntry {+ createReader(): FileSystemDirectoryReader;+}++interface FileSystemDirectoryReader {+ readEntries(+ successCallback: (entries: FileSystemEntry[]) => void,+ errorCallback?: (error: Error) => void,+ ): void;+}++declare global {+ interface DataTransferItem {+ webkitGetAsEntry?(): FileSystemEntry | null;+ }+}import {BookOpen,Database,@@ -48,6 +79,14 @@ interface ProgressInfo {error?: string;}+interface UploadFile {+ file: File;+ id: string;+ name: string;+ type: string;+ size: number;+}+export default function KnowledgePage() {const [kbs, setKbs] = useState<KnowledgeBase[]>([]);const [loading, setLoading] = useState(true);@@ -56,7 +95,7 @@ export default function KnowledgePage() {const [createModalOpen, setCreateModalOpen] = useState(false);const [targetKb, setTargetKb] = useState<string>("");const [uploading, setUploading] = useState(false);- const [files, setFiles] = useState<FileList | null>(null);+ const [uploadFiles, setUploadFiles] = useState<UploadFile[]>([]);const [newKbName, setNewKbName] = useState("");const [dragActive, setDragActive] = useState(false);const [ragProvider, setRagProvider] = useState<string>("llamaindex");@@ -73,6 +112,219 @@ export default function KnowledgePage() {type: "success" | "error" | "info";} | null>(null);+ // Helper function to generate unique ID+ const generateFileId = () => Math.random().toString(36).substring(2, 15);++ // Helper function to get file extension+ const getFileExtension = (filename: string): string => {+ const parts = filename.split(".");+ return parts.length > 1 ? parts.pop()?.toLowerCase() || "" : "";+ };++ // Supported file extensions (matching backend DocumentValidator.ALLOWED_EXTENSIONS)+ const SUPPORTED_EXTENSIONS = [+ "pdf",+ "txt",+ "md", // Documents+ "doc",+ "docx",+ "rtf", // Word documents+ "html",+ "htm",+ "xml",+ "json", // Web/Data formats+ "csv",+ "xlsx",+ "xls", // Spreadsheets+ "pptx",+ "ppt", // Presentations+ ];++ const isSupportedFile = (filename: string): boolean => {+ const ext = getFileExtension(filename);+ return SUPPORTED_EXTENSIONS.includes(ext);+ };++ // Helper function to convert File to UploadFile+ const fileToUploadFile = (file: File): UploadFile => ({+ file,+ id: generateFileId(),+ name: file.name,+ type: getFileExtension(file.name),+ size: file.size,+ });++ // Helper function to add files (avoiding duplicates)+ const addFiles = (newFiles: File[]) => {+ setUploadFiles((prev) => {+ const existingNames = new Set(prev.map((f) => f.name));+ const uniqueNewFiles = newFiles+ .filter((f) => !existingNames.has(f.name))+ .map(fileToUploadFile);+ return [...prev, ...uniqueNewFiles];+ });+ };++ // Helper function to remove a file+ const removeFile = (fileId: string) => {+ setUploadFiles((prev) => prev.filter((f) => f.id !== fileId));+ };++ // Helper function to clear all files+ const clearAllFiles = () => {+ setUploadFiles([]);+ };++ // Helper function to recursively read directory entries+ const readDirectoryRecursively = async (+ dirEntry: FileSystemDirectoryEntry,+ ): Promise<File[]> => {+ const files: File[] = [];+ const reader = dirEntry.createReader();++ const readEntries = (): Promise<FileSystemEntry[]> => {+ return new Promise((resolve, reject) => {+ reader.readEntries(resolve, reject);+ });+ };++ const getFile = (fileEntry: FileSystemFileEntry): Promise<File> => {+ return new Promise((resolve, reject) => {+ fileEntry.file(resolve, reject);+ });+ };++ let entries: FileSystemEntry[];+ do {+ entries = await readEntries();+ for (const entry of entries) {+ if (entry.isFile) {+ const file = await getFile(entry as FileSystemFileEntry);+ // Filter supported file types+ if (isSupportedFile(file.name)) {+ files.push(file);+ }+ } else if (entry.isDirectory) {+ const subFiles = await readDirectoryRecursively(+ entry as FileSystemDirectoryEntry,+ );+ files.push(...subFiles);+ }+ }+ } while (entries.length > 0);++ return files;+ };++ // Helper function to process dropped items (files and folders)+ const processDroppedItems = async (dataTransfer: DataTransfer) => {+ const items = dataTransfer.items;+ const allFiles: File[] = [];++ const processItem = async (item: DataTransferItem): Promise<File[]> => {+ const entry = item.webkitGetAsEntry?.();+ if (!entry) {+ // Fallback: try to get as file+ const file = item.getAsFile();+ if (file && isSupportedFile(file.name)) {+ return [file];+ }+ return [];+ }++ if (entry.isFile) {+ return new Promise((resolve) => {+ (entry as FileSystemFileEntry).file(+ (file) => {+ if (isSupportedFile(file.name)) {+ resolve([file]);+ } else {+ resolve([]);+ }+ },+ () => resolve([]),+ );+ });+ } else if (entry.isDirectory) {+ return readDirectoryRecursively(entry as FileSystemDirectoryEntry);+ }+ return [];+ };++ // Process all items in parallel+ const promises: Promise<File[]>[] = [];+ for (let i = 0; i < items.length; i++) {+ promises.push(processItem(items[i]));+ }++ const results = await Promise.all(promises);+ results.forEach((files) => allFiles.push(...files));++ return allFiles;+ };++ // Helper function to format file size+ const formatFileSize = (bytes: number): string => {+ if (bytes === 0) return "0 B";+ const k = 1024;+ const sizes = ["B", "KB", "MB", "GB"];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];+ };++ // Helper function to get file icon based on type+ const getFileIcon = (type: string) => {+ switch (type) {+ case "pdf":+ return <FileText className="w-4 h-4 text-red-500" />;+ case "md":+ return <FileText className="w-4 h-4 text-blue-500" />;+ case "txt":+ return <FileText className="w-4 h-4 text-slate-500" />;+ case "doc":+ case "docx":+ case "rtf":+ return <FileText className="w-4 h-4 text-blue-600" />;+ case "html":+ case "htm":+ case "xml":+ return <FileText className="w-4 h-4 text-orange-500" />;+ case "json":+ return <FileText className="w-4 h-4 text-yellow-600" />;+ case "csv":+ case "xlsx":+ case "xls":+ return <FileText className="w-4 h-4 text-green-600" />;+ case "pptx":+ case "ppt":+ return <FileText className="w-4 h-4 text-orange-600" />;+ default:+ return <FileText className="w-4 h-4 text-slate-400" />;+ }+ };++ // Helper function to get file type label+ const getFileTypeLabel = (type: string): string => {+ const labels: Record<string, string> = {+ pdf: "PDF",+ md: "Markdown",+ txt: "Text",+ doc: "Word",+ docx: "Word",+ rtf: "RTF",+ html: "HTML",+ htm: "HTML",+ xml: "XML",+ json: "JSON",+ csv: "CSV",+ xlsx: "Excel",+ xls: "Excel",+ pptx: "PowerPoint",+ ppt: "PowerPoint",+ };+ return labels[type] || type.toUpperCase();+ };+const showToast = (message: string,type: "success" | "error" | "info" = "info",@@ -482,12 +734,12 @@ export default function KnowledgePage() {const handleUpload = async (e: React.FormEvent) => {e.preventDefault();- if (!files || files.length === 0 || !targetKb) return;+ if (uploadFiles.length === 0 || !targetKb) return;setUploading(true);const formData = new FormData();- Array.from(files).forEach((file) => {- formData.append("files", file);+ uploadFiles.forEach((uploadFile) => {+ formData.append("files", uploadFile.file);});// Add rag_provider to form data if user selected one different from KB's existing provider@@ -503,10 +755,13 @@ export default function KnowledgePage() {if (!res.ok) throw new Error("Upload failed");setUploadModalOpen(false);- setFiles(null);+ clearAllFiles();// Refresh immediately to establish WebSocket connectionawait fetchKnowledgeBases();- showToast("Files uploaded successfully! Processing started in background.", "success");+ showToast(+ "Files uploaded successfully! Processing started in background.",+ "success",+ );} catch (err) {console.error(err);showToast("Failed to upload files", "error");@@ -517,14 +772,14 @@ export default function KnowledgePage() {const handleCreate = async (e: React.FormEvent) => {e.preventDefault();- if (!newKbName || !files || files.length === 0) return;+ if (!newKbName || uploadFiles.length === 0) return;setUploading(true);const formData = new FormData();formData.append("name", newKbName);formData.append("rag_provider", ragProvider);- Array.from(files).forEach((file) => {- formData.append("files", file);+ uploadFiles.forEach((uploadFile) => {+ formData.append("files", uploadFile.file);});try {@@ -576,7 +831,7 @@ export default function KnowledgePage() {}));setCreateModalOpen(false);- setFiles(null);+ clearAllFiles();setNewKbName("");setRagProvider("llamaindex"); // Reset to default@@ -585,7 +840,6 @@ export default function KnowledgePage() {await fetchKnowledgeBases();}, 1000);-showToast("Knowledge base created successfully!", "success");} catch (err: any) {console.error(err);@@ -605,12 +859,25 @@ export default function KnowledgePage() {}}, []);- const handleDrop = useCallback((e: React.DragEvent) => {+ const handleDrop = useCallback(async (e: React.DragEvent) => {e.preventDefault();e.stopPropagation();setDragActive(false);- if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {- setFiles(e.dataTransfer.files);++ if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {+ // Use the new folder-aware processing+ const droppedFiles = await processDroppedItems(e.dataTransfer);+ if (droppedFiles.length > 0) {+ addFiles(droppedFiles);+ }+ } else if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {+ // Fallback for browsers that don't support DataTransferItem+ const validFiles = Array.from(e.dataTransfer.files).filter((file) =>+ isSupportedFile(file.name),+ );+ if (validFiles.length > 0) {+ addFiles(validFiles);+ }}}, []);@@ -641,7 +908,7 @@ export default function KnowledgePage() {</button><buttononClick={() => {- setFiles(null);+ clearAllFiles();setNewKbName("");setRagProvider("llamaindex");setCreateModalOpen(true);@@ -699,16 +966,21 @@ export default function KnowledgePage() {</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'+ <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>)}@@ -720,15 +992,24 @@ export default function KnowledgePage() {<buttononClick={async () => {try {- const res = await fetch(apiUrl(`/api/v1/knowledge/default/${kb.name}`), {- method: "PUT",- });+ 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");+ showToast(+ `Set "${kb.name}" as default knowledge base`,+ "success",+ );fetchKnowledgeBases();} catch (err) {console.error(err);- showToast("Failed to set default knowledge base", "error");+ 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"@@ -740,7 +1021,7 @@ export default function KnowledgePage() {<buttononClick={() => {setTargetKb(kb.name);- setFiles(null);+ clearAllFiles();// Set RAG provider to KB's existing provider or defaultsetRagProvider(kb.statistics.rag_provider || "llamaindex",@@ -1038,10 +1319,11 @@ export default function KnowledgePage() {Upload Documents</label><div- className={`border-2 border-dashed rounded-xl p-8 text-center transition-colors ${dragActive- ? "border-blue-500 bg-blue-50 dark:bg-blue-900/30"- : "border-slate-200 dark:border-slate-600 hover:border-blue-400 dark:hover:border-blue-500 bg-slate-50 dark:bg-slate-700/50"- }`}+ className={`border-2 border-dashed rounded-xl transition-colors ${+ dragActive+ ? "border-blue-500 bg-blue-50 dark:bg-blue-900/30"+ : "border-slate-200 dark:border-slate-600 hover:border-blue-400 dark:hover:border-blue-500 bg-slate-50 dark:bg-slate-700/50"+ }`}onDragEnter={handleDrag}onDragLeave={handleDrag}onDragOver={handleDrag}@@ -1052,25 +1334,92 @@ export default function KnowledgePage() {multipleclassName="hidden"id="kb-file-upload"- onChange={(e) => setFiles(e.target.files)}- accept=".pdf,.txt,.md"+ onChange={(e) => {+ if (e.target.files) {+ const validFiles = Array.from(e.target.files).filter(+ (file) => isSupportedFile(file.name),+ );+ addFiles(validFiles);+ }+ e.target.value = ""; // Reset input to allow re-selecting same files+ }}+ accept=".pdf,.txt,.md,.doc,.docx,.rtf,.html,.htm,.xml,.json,.csv,.xlsx,.xls,.pptx,.ppt"/>++ {/* Drop zone / Click to upload area */}<labelhtmlFor="kb-file-upload"- className="cursor-pointer flex flex-col items-center gap-2"+ className={`cursor-pointer flex flex-col items-center gap-2 ${uploadFiles.length > 0 ? "p-4" : "p-8"}`}><Upload- className={`w-8 h-8 ${dragActive ? "text-blue-500 dark:text-blue-400" : "text-slate-400 dark:text-slate-500"}`}+ className={`w-6 h-6 ${dragActive ? "text-blue-500 dark:text-blue-400" : "text-slate-400 dark:text-slate-500"}`}/><span className="text-sm font-medium text-slate-600 dark:text-slate-300">- {files && files.length > 0- ? `${files.length} files selected`- : "Drag & drop files here or click to browse"}+ {uploadFiles.length > 0+ ? "Click or drop to add more files"+ : "Drag & drop files or folders here"}</span><span className="text-xs text-slate-400 dark:text-slate-500">- Supports PDF, TXT, MD+ PDF, Word, Excel, PPT, TXT, MD, HTML, CSV, JSON...</span></label>++ {/* File list */}+ {uploadFiles.length > 0 && (+ <div className="border-t border-slate-200 dark:border-slate-600 px-3 py-2 max-h-48 overflow-y-auto">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs font-medium text-slate-500 dark:text-slate-400">+ {uploadFiles.length} file+ {uploadFiles.length > 1 ? "s" : ""} selected+ </span>+ <button+ type="button"+ onClick={(e) => {+ e.preventDefault();+ clearAllFiles();+ }}+ className="text-xs text-red-500 hover:text-red-600 dark:text-red-400 dark:hover:text-red-300 font-medium"+ >+ Clear all+ </button>+ </div>+ <div className="space-y-1">+ {uploadFiles.map((file) => (+ <div+ key={file.id}+ className="flex items-center justify-between gap-2 p-2 bg-white dark:bg-slate-700 rounded-lg border border-slate-100 dark:border-slate-600 group"+ >+ <div className="flex items-center gap-2 min-w-0 flex-1">+ {getFileIcon(file.type)}+ <div className="min-w-0 flex-1">+ <p+ className="text-sm font-medium text-slate-700 dark:text-slate-200 truncate"+ title={file.name}+ >+ {file.name}+ </p>+ <p className="text-xs text-slate-400 dark:text-slate-500">+ {getFileTypeLabel(file.type)} •{" "}+ {formatFileSize(file.size)}+ </p>+ </div>+ </div>+ <button+ type="button"+ onClick={(e) => {+ e.preventDefault();+ removeFile(file.id);+ }}+ className="p-1 text-slate-400 hover:text-red-500 dark:text-slate-500 dark:hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"+ title="Remove file"+ >+ <X className="w-4 h-4" />+ </button>+ </div>+ ))}+ </div>+ </div>+ )}</div></div>@@ -1084,9 +1433,7 @@ export default function KnowledgePage() {</button><buttontype="submit"- disabled={- !newKbName || !files || files.length === 0 || uploading- }+ disabled={!newKbName || uploadFiles.length === 0 || uploading}className="flex-1 py-2.5 rounded-xl bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 font-medium hover:bg-slate-800 dark:hover:bg-slate-200 disabled:opacity-50 flex items-center justify-center gap-2">{uploading ? (@@ -1117,11 +1464,10 @@ export default function KnowledgePage() {</button></div><p className="text-sm text-slate-500 dark:text-slate-400 mb-4">- Upload PDF, TXT, or MD files to{" "}+ Upload documents to{" "}<strong className="text-slate-700 dark:text-slate-200">{targetKb}</strong>- .</p><form onSubmit={handleUpload} className="space-y-4">@@ -1178,26 +1524,108 @@ export default function KnowledgePage() {</p></div>- <div className="border-2 border-dashed border-slate-200 dark:border-slate-600 rounded-xl p-8 text-center hover:border-blue-400 dark:hover:border-blue-500 transition-colors bg-slate-50 dark:bg-slate-700/50">+ <div+ className={`border-2 border-dashed rounded-xl transition-colors ${+ dragActive+ ? "border-blue-500 bg-blue-50 dark:bg-blue-900/30"+ : "border-slate-200 dark:border-slate-600 hover:border-blue-400 dark:hover:border-blue-500 bg-slate-50 dark:bg-slate-700/50"+ }`}+ onDragEnter={handleDrag}+ onDragLeave={handleDrag}+ onDragOver={handleDrag}+ onDrop={handleDrop}+ ><inputtype="file"multipleclassName="hidden"id="file-upload"- onChange={(e) => setFiles(e.target.files)}- accept=".pdf,.txt,.md"+ onChange={(e) => {+ if (e.target.files) {+ const validFiles = Array.from(e.target.files).filter(+ (file) => isSupportedFile(file.name),+ );+ addFiles(validFiles);+ }+ e.target.value = ""; // Reset input to allow re-selecting same files+ }}+ accept=".pdf,.txt,.md,.doc,.docx,.rtf,.html,.htm,.xml,.json,.csv,.xlsx,.xls,.pptx,.ppt"/>++ {/* Drop zone / Click to upload area */}<labelhtmlFor="file-upload"- className="cursor-pointer flex flex-col items-center gap-2"+ className={`cursor-pointer flex flex-col items-center gap-2 ${uploadFiles.length > 0 ? "p-4" : "p-8"}`}>- <Upload className="w-8 h-8 text-slate-400 dark:text-slate-500" />+ <Upload+ className={`w-6 h-6 ${dragActive ? "text-blue-500 dark:text-blue-400" : "text-slate-400 dark:text-slate-500"}`}+ /><span className="text-sm font-medium text-slate-600 dark:text-slate-300">- {files && files.length > 0- ? `${files.length} files selected`- : "Click to browse files"}+ {uploadFiles.length > 0+ ? "Click or drop to add more files"+ : "Drag & drop files or folders here"}+ </span>+ <span className="text-xs text-slate-400 dark:text-slate-500">+ PDF, Word, Excel, PPT, TXT, MD, HTML, CSV, JSON...</span></label>++ {/* File list */}+ {uploadFiles.length > 0 && (+ <div className="border-t border-slate-200 dark:border-slate-600 px-3 py-2 max-h-48 overflow-y-auto">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs font-medium text-slate-500 dark:text-slate-400">+ {uploadFiles.length} file+ {uploadFiles.length > 1 ? "s" : ""} selected+ </span>+ <button+ type="button"+ onClick={(e) => {+ e.preventDefault();+ clearAllFiles();+ }}+ className="text-xs text-red-500 hover:text-red-600 dark:text-red-400 dark:hover:text-red-300 font-medium"+ >+ Clear all+ </button>+ </div>+ <div className="space-y-1">+ {uploadFiles.map((file) => (+ <div+ key={file.id}+ className="flex items-center justify-between gap-2 p-2 bg-white dark:bg-slate-700 rounded-lg border border-slate-100 dark:border-slate-600 group"+ >+ <div className="flex items-center gap-2 min-w-0 flex-1">+ {getFileIcon(file.type)}+ <div className="min-w-0 flex-1">+ <p+ className="text-sm font-medium text-slate-700 dark:text-slate-200 truncate"+ title={file.name}+ >+ {file.name}+ </p>+ <p className="text-xs text-slate-400 dark:text-slate-500">+ {getFileTypeLabel(file.type)} •{" "}+ {formatFileSize(file.size)}+ </p>+ </div>+ </div>+ <button+ type="button"+ onClick={(e) => {+ e.preventDefault();+ removeFile(file.id);+ }}+ className="p-1 text-slate-400 hover:text-red-500 dark:text-slate-500 dark:hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"+ title="Remove file"+ >+ <X className="w-4 h-4" />+ </button>+ </div>+ ))}+ </div>+ </div>+ )}</div><div className="flex gap-3">@@ -1210,7 +1638,7 @@ export default function KnowledgePage() {</button><buttontype="submit"- disabled={!files || uploading}+ disabled={uploadFiles.length === 0 || uploading}className="flex-1 py-2.5 rounded-xl bg-blue-600 text-white font-medium hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2">{uploading ? (diff --git a/web/app/notebook/page.tsx b/web/app/notebook/page.tsxindex 9ebe2199d..8f02caa39 100644--- a/web/app/notebook/page.tsx+++ b/web/app/notebook/page.tsx@@ -30,6 +30,7 @@ import {MessageSquare,} 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";@@ -875,7 +876,7 @@ export default function NotebookPage() {<div className="p-4 bg-slate-50 dark:bg-slate-700/50 rounded-xl border border-slate-100 dark:border-slate-600"><div className="prose prose-slate dark:prose-invert max-w-none prose-sm"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(selectedRecord.output)}diff --git a/web/app/page.tsx b/web/app/page.tsxindex aa85bcc51..26d2ff602 100644--- a/web/app/page.tsx+++ b/web/app/page.tsx@@ -23,6 +23,7 @@ import {} from "lucide-react";import Link from "next/link";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";@@ -414,7 +415,7 @@ export default function HomePage() {<div className="bg-white dark:bg-slate-800 px-5 py-4 rounded-2xl rounded-tl-none border border-slate-200 dark:border-slate-700 shadow-sm"><div className="prose prose-slate dark:prose-invert prose-sm max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(msg.content)}diff --git a/web/app/question/page.tsx b/web/app/question/page.tsxindex eb2c68fd2..8387280ad 100644--- a/web/app/question/page.tsx+++ b/web/app/question/page.tsx@@ -21,6 +21,7 @@ import {} from "lucide-react";import { useGlobal } from "@/context/GlobalContext";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";@@ -637,7 +638,7 @@ export default function QuestionPage() {{/* Question Text */}<div className="prose prose-slate dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(@@ -697,7 +698,7 @@ export default function QuestionPage() {</span><div className="flex-1"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(String(val))}@@ -731,7 +732,7 @@ export default function QuestionPage() {</p><div className="text-emerald-800 dark:text-emerald-200 prose prose-sm dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(@@ -751,7 +752,7 @@ export default function QuestionPage() {</p><div className="text-slate-700 dark:text-slate-300 prose prose-sm dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(@@ -798,7 +799,10 @@ export default function QuestionPage() {</div><div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[+ remarkGfm,+ remarkMath,+ ]}rehypePlugins={[rehypeKatex]}>{processLatexContent(@@ -818,7 +822,10 @@ export default function QuestionPage() {</div><div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[+ remarkGfm,+ remarkMath,+ ]}rehypePlugins={[rehypeKatex]}>{processLatexContent(@@ -839,7 +846,10 @@ export default function QuestionPage() {</div><div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[+ remarkGfm,+ remarkMath,+ ]}rehypePlugins={[rehypeKatex]}>{processLatexContent(@@ -860,7 +870,10 @@ export default function QuestionPage() {</div><div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[+ remarkGfm,+ remarkMath,+ ]}rehypePlugins={[rehypeKatex]}>{processLatexContent(@@ -878,7 +891,10 @@ export default function QuestionPage() {</div><div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[+ remarkGfm,+ remarkMath,+ ]}rehypePlugins={[rehypeKatex]}>{processLatexContent(diff --git a/web/app/research/page.tsx b/web/app/research/page.tsxindex 841f64dce..5c633e79c 100644--- a/web/app/research/page.tsx+++ b/web/app/research/page.tsx@@ -463,7 +463,12 @@ export default function ResearchPage() {</div>) : (<div className="prose prose-sm dark:prose-invert max-w-none">- <ReactMarkdown>{msg.content}</ReactMarkdown>+ <ReactMarkdown+ remarkPlugins={[remarkGfm, remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {msg.content}+ </ReactMarkdown></div>)}</div>diff --git a/web/app/settings/components/ConfigForm.tsx b/web/app/settings/components/ConfigForm.tsxindex 62bc330f2..de398cd93 100644--- a/web/app/settings/components/ConfigForm.tsx+++ b/web/app/settings/components/ConfigForm.tsx@@ -510,4 +510,3 @@ export default function ConfigForm({</form>);}-diff --git a/web/app/settings/components/ConfigTab.tsx b/web/app/settings/components/ConfigTab.tsxindex 943406230..0e995de4f 100644--- a/web/app/settings/components/ConfigTab.tsx+++ b/web/app/settings/components/ConfigTab.tsx@@ -276,4 +276,3 @@ export default function ConfigTab({</div>);}-diff --git a/web/app/settings/components/OverviewTab.tsx b/web/app/settings/components/OverviewTab.tsxindex d26c2947e..da4dfd624 100644--- a/web/app/settings/components/OverviewTab.tsx+++ b/web/app/settings/components/OverviewTab.tsx@@ -155,4 +155,3 @@ export default function OverviewTab({</div>);}-diff --git a/web/app/settings/components/index.ts b/web/app/settings/components/index.tsindex 1e48bc750..c7a3d8cea 100644--- a/web/app/settings/components/index.ts+++ b/web/app/settings/components/index.ts@@ -1,4 +1,3 @@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.tsindex 7deb899eb..7cf69e195 100644--- a/web/app/settings/constants.ts+++ b/web/app/settings/constants.ts@@ -51,7 +51,14 @@ export const LOCAL_PROVIDER_URLS: Record<string, string> = {};// Voice options for TTS-export const VOICE_OPTIONS = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];+export const VOICE_OPTIONS = [+ "alloy",+ "echo",+ "fable",+ "onyx",+ "nova",+ "shimmer",+];// Helper functions to get env var namesexport function getEnvVarForBaseUrl(configType: ConfigType): string {@@ -73,4 +80,3 @@ export function getEnvVarForApiKey(configType: ConfigType): string {};return mapping[configType];}-diff --git a/web/app/settings/types.ts b/web/app/settings/types.tsindex 17c84ad16..6b31cbcfa 100644--- a/web/app/settings/types.ts+++ b/web/app/settings/types.ts@@ -38,4 +38,3 @@ export interface PortsInfo {export type ConfigType = "llm" | "embedding" | "tts" | "search";export type TabType = "overview" | ConfigType;-diff --git a/web/app/solver/page.tsx b/web/app/solver/page.tsxindex a72d2b0bb..8a9ddf29e 100644--- a/web/app/solver/page.tsx+++ b/web/app/solver/page.tsx@@ -17,6 +17,7 @@ import {FileText,} 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";@@ -246,7 +247,7 @@ export default function SolverPage() {<div className="flex-1 bg-slate-100 dark:bg-slate-700 px-5 py-3.5 rounded-2xl rounded-tl-none text-slate-800 dark:text-slate-200 leading-relaxed shadow-sm overflow-hidden min-w-0 break-words"><div className="prose prose-slate dark:prose-invert max-w-none prose-headings:font-bold prose-p:leading-relaxed prose-pre:bg-slate-900 prose-pre:shadow-inner prose-pre:overflow-x-auto prose-code:break-words prose-a:break-all"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}urlTransform={(url) =>resolveArtifactUrl(url, msg.outputDir)@@ -316,7 +317,7 @@ export default function SolverPage() {<div className="flex-1 bg-white dark:bg-slate-800 px-6 py-5 rounded-2xl rounded-tl-none border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden min-w-0 break-words"><div className="prose prose-slate dark:prose-invert prose-blue max-w-none prose-headings:font-bold prose-p:leading-relaxed prose-pre:bg-slate-900 prose-pre:shadow-inner prose-pre:overflow-x-auto prose-code:break-words prose-a:break-all"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}urlTransform={(url) =>resolveArtifactUrl(url, msg.outputDir)diff --git a/web/components/ActivityDetail.tsx b/web/components/ActivityDetail.tsxindex ebc1b41f1..e50476745 100644--- a/web/components/ActivityDetail.tsx+++ b/web/components/ActivityDetail.tsx@@ -4,6 +4,7 @@ import { useState, useEffect } from "react";import { createPortal } from "react-dom";import { X, FileText, HelpCircle, Search, Clock, Database } 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";@@ -129,7 +130,7 @@ export default function ActivityDetail({<div className="p-6 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm"><div className="prose prose-slate dark:prose-invert max-w-none prose-sm"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(activity.content.answer)}diff --git a/web/components/ChatSessionDetail.tsx b/web/components/ChatSessionDetail.tsxindex 59f021034..31728d8b9 100644--- a/web/components/ChatSessionDetail.tsx+++ b/web/components/ChatSessionDetail.tsx@@ -13,6 +13,7 @@ import {ExternalLink,} 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";@@ -208,7 +209,7 @@ export default function ChatSessionDetail({) : (<div className="prose prose-sm dark:prose-invert max-w-none prose-p:my-2 prose-headings:my-2"><ReactMarkdown- remarkPlugins={[remarkMath]}+ remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(msg.content)}diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsxindex 01cf47b3a..95a188c98 100644--- a/web/components/common/MarkdownRenderer.tsx+++ b/web/components/common/MarkdownRenderer.tsx@@ -70,7 +70,13 @@ export default function MarkdownRenderer({// Code block stylingconst codeComponents = {- code: ({ node, inline, className: codeClassName, children, ...props }: any) => {+ code: ({+ node,+ inline,+ className: codeClassName,+ children,+ ...props+ }: any) => {if (inline) {return (<code@@ -117,4 +123,3 @@ export default function MarkdownRenderer({</div>);}-diff --git a/web/components/common/Modal.tsx b/web/components/common/Modal.tsxindex f95b940f1..957ad9d78 100644--- a/web/components/common/Modal.tsx+++ b/web/components/common/Modal.tsx@@ -103,4 +103,3 @@ export default function Modal({</div>);}-diff --git a/web/components/common/index.ts b/web/components/common/index.tsindex 65cc55079..dba226ae4 100644--- a/web/components/common/index.ts+++ b/web/components/common/index.ts@@ -1,3 +1,2 @@export { default as MarkdownRenderer } from "./MarkdownRenderer";export { default as Modal } from "./Modal";-diff --git a/web/components/knowledge/FolderSyncManager.tsx b/web/components/knowledge/FolderSyncManager.tsxindex 0b28eb762..2cd54985d 100644--- a/web/components/knowledge/FolderSyncManager.tsx+++ b/web/components/knowledge/FolderSyncManager.tsx@@ -5,163 +5,166 @@ import { Loader2, FolderOpen, Link as LinkIcon, X } from "lucide-react";import { apiUrl } from "@/lib/api";interface FolderSyncManagerProps {- kbName: string;- showToast: (message: string, type: "success" | "error" | "info") => void;- onFolderLinked?: () => void;- onFolderUnlinked?: () => void;- onSyncComplete?: () => void;+ kbName: string;+ showToast: (message: string, type: "success" | "error" | "info") => void;+ onFolderLinked?: () => void;+ onFolderUnlinked?: () => void;+ onSyncComplete?: () => void;}interface FolderInfo {- id: string;- path: string;- added_at: string;- file_count: number;+ id: string;+ path: string;+ added_at: string;+ file_count: number;}export default function FolderSyncManager({- kbName,- showToast,- onFolderLinked,- onFolderUnlinked,- onSyncComplete+ kbName,+ showToast,+ onFolderLinked,+ onFolderUnlinked,+ onSyncComplete,}: FolderSyncManagerProps) {- const [modalOpen, setModalOpen] = useState(false);- const [folderPath, setFolderPath] = useState("");- const [linking, setLinking] = useState(false);+ const [modalOpen, setModalOpen] = useState(false);+ const [folderPath, setFolderPath] = useState("");+ const [linking, setLinking] = useState(false);- const handleLinkFolder = async (e: React.FormEvent) => {- e.preventDefault();- if (!folderPath || !kbName) return;+ const handleLinkFolder = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!folderPath || !kbName) return;- setLinking(true);- try {- const res = await fetch(apiUrl(`/api/v1/knowledge/${kbName}/link-folder`), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ folder_path: folderPath }),- });+ setLinking(true);+ try {+ const res = await fetch(+ apiUrl(`/api/v1/knowledge/${kbName}/link-folder`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ folder_path: folderPath }),+ },+ );- if (!res.ok) throw new Error("Failed to link folder");+ if (!res.ok) throw new Error("Failed to link folder");- showToast("Folder linked successfully!", "success");- setModalOpen(false);- setFolderPath("");- onFolderLinked?.();- } catch (err: any) {- showToast(err.message || "Failed to link folder", "error");- } finally {- setLinking(false);- }- };+ showToast("Folder linked successfully!", "success");+ setModalOpen(false);+ setFolderPath("");+ onFolderLinked?.();+ } catch (err: any) {+ showToast(err.message || "Failed to link folder", "error");+ } finally {+ setLinking(false);+ }+ };- return (- <>- <button- onClick={() => setModalOpen(true)}- className="flex items-center gap-1 px-2 py-1 text-xs text-emerald-600 dark:text-emerald-400 hover:bg-emerald-50 dark:hover:bg-emerald-900/30 rounded-lg transition-colors"- >- <FolderOpen className="w-3 h-3" />- Link Folder- </button>+ return (+ <>+ <button+ onClick={() => setModalOpen(true)}+ className="flex items-center gap-1 px-2 py-1 text-xs text-emerald-600 dark:text-emerald-400 hover:bg-emerald-50 dark:hover:bg-emerald-900/30 rounded-lg transition-colors"+ >+ <FolderOpen className="w-3 h-3" />+ Link Folder+ </button>- {modalOpen && (- <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50">- <div className="bg-white dark:bg-slate-800 rounded-2xl p-6 w-full max-w-md shadow-2xl border border-slate-200 dark:border-slate-700 animate-fade-in">- <div className="flex justify-between items-center mb-4">- <h2 className="text-xl font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">- <FolderOpen className="w-5 h-5 text-emerald-500" />- Link Local Folder- </h2>- <button- onClick={() => setModalOpen(false)}- className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300"- >- <X className="w-5 h-5" />- </button>- </div>+ {modalOpen && (+ <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50">+ <div className="bg-white dark:bg-slate-800 rounded-2xl p-6 w-full max-w-md shadow-2xl border border-slate-200 dark:border-slate-700 animate-fade-in">+ <div className="flex justify-between items-center mb-4">+ <h2 className="text-xl font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">+ <FolderOpen className="w-5 h-5 text-emerald-500" />+ Link Local Folder+ </h2>+ <button+ onClick={() => setModalOpen(false)}+ className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300"+ >+ <X className="w-5 h-5" />+ </button>+ </div>- <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">- Link a local folder to{" "}- <span className="font-semibold text-slate-700 dark:text-slate-200">- {kbName}- </span>- . Documents in the folder will be processed and added to this- knowledge base.- </p>+ <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">+ Link a local folder to{" "}+ <span className="font-semibold text-slate-700 dark:text-slate-200">+ {kbName}+ </span>+ . Documents in the folder will be processed and added to this+ knowledge base.+ </p>- <form onSubmit={handleLinkFolder} className="space-y-4">- <div>- <label- htmlFor="folder-path"- className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1"- >- Folder Path- </label>- <input- type="text"- id="folder-path"- value={folderPath}- onChange={(e) => setFolderPath(e.target.value)}- placeholder="Paste or type the full folder path"- className="w-full px-4 py-2.5 border border-slate-200 dark:border-slate-600 rounded-xl bg-slate-50 dark:bg-slate-700 text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent"- />- <div className="mt-2 space-y-1">- <p className="text-xs text-slate-400 dark:text-slate-500">- <strong>macOS/Linux:</strong> ~/Documents/papers or- /Users/name/folder- </p>- <p className="text-xs text-slate-400 dark:text-slate-500">- <strong>Windows:</strong> C:\Users\name\Documents\papers- </p>- </div>- </div>+ <form onSubmit={handleLinkFolder} className="space-y-4">+ <div>+ <label+ htmlFor="folder-path"+ className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1"+ >+ Folder Path+ </label>+ <input+ type="text"+ id="folder-path"+ value={folderPath}+ onChange={(e) => setFolderPath(e.target.value)}+ placeholder="Paste or type the full folder path"+ className="w-full px-4 py-2.5 border border-slate-200 dark:border-slate-600 rounded-xl bg-slate-50 dark:bg-slate-700 text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent"+ />+ <div className="mt-2 space-y-1">+ <p className="text-xs text-slate-400 dark:text-slate-500">+ <strong>macOS/Linux:</strong> ~/Documents/papers or+ /Users/name/folder+ </p>+ <p className="text-xs text-slate-400 dark:text-slate-500">+ <strong>Windows:</strong> C:\Users\name\Documents\papers+ </p>+ </div>+ </div>- <div className="bg-slate-50 dark:bg-slate-700/50 rounded-lg p-3">- <p className="text-xs font-medium text-slate-600 dark:text-slate-300 mb-1">- 📄 Supported files: PDF, DOCX, TXT, MD- </p>- <p className="text-[10px] text-slate-400 dark:text-slate-500">- New and modified files will be automatically detected when you- sync.- </p>- </div>+ <div className="bg-slate-50 dark:bg-slate-700/50 rounded-lg p-3">+ <p className="text-xs font-medium text-slate-600 dark:text-slate-300 mb-1">+ 📄 Supported files: PDF, DOCX, TXT, MD+ </p>+ <p className="text-[10px] text-slate-400 dark:text-slate-500">+ New and modified files will be automatically detected when you+ sync.+ </p>+ </div>- <div className="bg-emerald-50 dark:bg-emerald-900/20 rounded-lg p-3 border border-emerald-100 dark:border-emerald-800">- <p className="text-xs text-emerald-700 dark:text-emerald-400">- <strong>💡 Tip:</strong> Use folders synced with Google Drive,- OneDrive, SharePoint, or Dropbox for automatic cloud- integration.- </p>- </div>+ <div className="bg-emerald-50 dark:bg-emerald-900/20 rounded-lg p-3 border border-emerald-100 dark:border-emerald-800">+ <p className="text-xs text-emerald-700 dark:text-emerald-400">+ <strong>💡 Tip:</strong> Use folders synced with Google Drive,+ OneDrive, SharePoint, or Dropbox for automatic cloud+ integration.+ </p>+ </div>- <div className="flex gap-3">- <button- type="button"- onClick={() => setModalOpen(false)}- className="flex-1 py-2.5 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 font-medium hover:bg-slate-50 dark:hover:bg-slate-700"- >- Cancel- </button>- <button- type="submit"- disabled={!folderPath || linking}- className="flex-1 py-2.5 rounded-xl bg-emerald-600 text-white font-medium hover:bg-emerald-700 disabled:opacity-50 flex items-center justify-center gap-2"- >- {linking ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : (- <>- <LinkIcon className="w-4 h-4" />- Link Folder- </>- )}- </button>- </div>- </form>- </div>- </div>- )}- </>- );+ <div className="flex gap-3">+ <button+ type="button"+ onClick={() => setModalOpen(false)}+ className="flex-1 py-2.5 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 font-medium hover:bg-slate-50 dark:hover:bg-slate-700"+ >+ Cancel+ </button>+ <button+ type="submit"+ disabled={!folderPath || linking}+ className="flex-1 py-2.5 rounded-xl bg-emerald-600 text-white font-medium hover:bg-emerald-700 disabled:opacity-50 flex items-center justify-center gap-2"+ >+ {linking ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ <>+ <LinkIcon className="w-4 h-4" />+ Link Folder+ </>+ )}+ </button>+ </div>+ </form>+ </div>+ </div>+ )}+ </>+ );}diff --git a/web/context/CompositeProvider.tsx b/web/context/CompositeProvider.tsxindex 5b7763c43..5ccd1fcf1 100644--- a/web/context/CompositeProvider.tsx+++ b/web/context/CompositeProvider.tsx@@ -29,4 +29,3 @@ export function CompositeProvider({ children }: { children: React.ReactNode }) {</UISettingsProvider>);}-diff --git a/web/context/chat/ChatContext.tsx b/web/context/chat/ChatContext.tsxindex e0980315d..f9e805e34 100644--- a/web/context/chat/ChatContext.tsx+++ b/web/context/chat/ChatContext.tsx@@ -8,11 +8,7 @@ import React, {useCallback,} from "react";import { wsUrl, apiUrl } from "@/lib/api";-import {- ChatState,- HomeChatMessage,- INITIAL_CHAT_STATE,-} from "@/types/chat";+import { ChatState, HomeChatMessage, INITIAL_CHAT_STATE } from "@/types/chat";// Context typeinterface ChatContextType {@@ -269,4 +265,3 @@ export const useChat = () => {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.tsindex 2a4d0f878..377b802e3 100644--- a/web/context/chat/index.ts+++ b/web/context/chat/index.ts@@ -1,2 +1 @@export { ChatProvider, useChat } from "./ChatContext";-diff --git a/web/context/ideagen/IdeaGenContext.tsx b/web/context/ideagen/IdeaGenContext.tsxindex ada178c86..d825d6477 100644--- a/web/context/ideagen/IdeaGenContext.tsx+++ b/web/context/ideagen/IdeaGenContext.tsx@@ -12,8 +12,9 @@ interface IdeaGenContextType {const IdeaGenContext = createContext<IdeaGenContextType | undefined>(undefined);export function IdeaGenProvider({ children }: { children: React.ReactNode }) {- const [ideaGenState, setIdeaGenState] =- useState<IdeaGenState>(INITIAL_IDEAGEN_STATE);+ const [ideaGenState, setIdeaGenState] = useState<IdeaGenState>(+ INITIAL_IDEAGEN_STATE,+ );return (<IdeaGenContext.Provider@@ -33,4 +34,3 @@ export const useIdeaGen = () => {throw new Error("useIdeaGen must be used within IdeaGenProvider");return context;};-diff --git a/web/context/ideagen/index.ts b/web/context/ideagen/index.tsindex f65cfcb4c..fa70f541d 100644--- a/web/context/ideagen/index.ts+++ b/web/context/ideagen/index.ts@@ -1,2 +1 @@export { IdeaGenProvider, useIdeaGen } from "./IdeaGenContext";-diff --git a/web/context/index.ts b/web/context/index.tsindex 83c110816..8a3fc43e4 100644--- a/web/context/index.ts+++ b/web/context/index.ts@@ -20,4 +20,3 @@ export type { SidebarNavOrder } from "./settings";// Legacy compatibility - useGlobal hook that combines all contexts// This allows gradual migration without breaking existing codeexport { useGlobal, GlobalProvider } from "./GlobalContext";-diff --git a/web/context/question/QuestionContext.tsx b/web/context/question/QuestionContext.tsxindex 53d69ab5a..344e0cfc2 100644--- a/web/context/question/QuestionContext.tsx+++ b/web/context/question/QuestionContext.tsx@@ -113,7 +113,8 @@ export function QuestionProvider({ children }: { children: React.ReactNode }) {...prev.progress,progress: {...prev.progress.progress,- total: data.total_questions || data.reference_questions.length,+ total:+ data.total_questions || data.reference_questions.length,},},}));@@ -442,8 +443,7 @@ export function QuestionProvider({ children }: { children: React.ReactNode }) {...prev.results,{success: true,- question_id:- data.question_id || `q_${prev.results.length + 1}`,+ question_id: data.question_id || `q_${prev.results.length + 1}`,question: data.question,validation: data.validation,rounds: data.rounds || 1,@@ -654,4 +654,3 @@ export const useQuestion = () => {throw new Error("useQuestion must be used within QuestionProvider");return context;};-diff --git a/web/context/question/index.ts b/web/context/question/index.tsindex 9353c4fb2..d40450303 100644--- a/web/context/question/index.ts+++ b/web/context/question/index.ts@@ -1,2 +1 @@export { QuestionProvider, useQuestion } from "./QuestionContext";-diff --git a/web/context/research/ResearchContext.tsx b/web/context/research/ResearchContext.tsxindex 82055bc55..6b47b397f 100644--- a/web/context/research/ResearchContext.tsx+++ b/web/context/research/ResearchContext.tsx@@ -227,4 +227,3 @@ export const useResearch = () => {throw new Error("useResearch must be used within ResearchProvider");return context;};-diff --git a/web/context/research/index.ts b/web/context/research/index.tsindex 4931ded3a..7b92dfb92 100644--- a/web/context/research/index.ts+++ b/web/context/research/index.ts@@ -1,2 +1 @@export { ResearchProvider, useResearch } from "./ResearchContext";-diff --git a/web/context/settings/SidebarContext.tsx b/web/context/settings/SidebarContext.tsxindex 9e0998152..aabe5e230 100644--- a/web/context/settings/SidebarContext.tsx+++ b/web/context/settings/SidebarContext.tsx@@ -36,8 +36,9 @@ 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 [sidebarWidth, setSidebarWidthState] = useState<number>(+ SIDEBAR_DEFAULT_WIDTH,+ );const [sidebarCollapsed, setSidebarCollapsedState] = useState<boolean>(false);// Sidebar customization state@@ -175,4 +176,3 @@ export const useSidebar = () => {// Re-export the SidebarNavOrder type for convenienceexport type { SidebarNavOrder };-diff --git a/web/context/settings/UISettingsContext.tsx b/web/context/settings/UISettingsContext.tsxindex 50e1c76e5..1e4d5809d 100644--- a/web/context/settings/UISettingsContext.tsx+++ b/web/context/settings/UISettingsContext.tsx@@ -8,11 +8,7 @@ import React, {useCallback,} from "react";import { apiUrl } from "@/lib/api";-import {- initializeTheme,- setTheme,- getStoredTheme,-} from "@/lib/theme";+import { initializeTheme, setTheme, getStoredTheme } from "@/lib/theme";import { UISettings, Theme, Language } from "@/types/common";// Language storage key@@ -159,4 +155,3 @@ export const useUISettings = () => {throw new Error("useUISettings must be used within UISettingsProvider");return context;};-diff --git a/web/context/settings/index.ts b/web/context/settings/index.tsindex b229a6e69..86e0edd93 100644--- a/web/context/settings/index.ts+++ b/web/context/settings/index.ts@@ -1,4 +1,3 @@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.tsxindex ff514ff7b..50821aecc 100644--- a/web/context/solver/SolverContext.tsx+++ b/web/context/solver/SolverContext.tsx@@ -180,8 +180,6 @@ export function SolverProvider({ children }: { children: React.ReactNode }) {export const useSolver = () => {const context = useContext(SolverContext);- if (!context)- throw new Error("useSolver must be used within SolverProvider");+ 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.tsindex 87b96928c..29a2bc5d5 100644--- a/web/context/solver/index.ts+++ b/web/context/solver/index.ts@@ -1,2 +1 @@export { SolverProvider, useSolver } from "./SolverContext";-diff --git a/web/types/chat.ts b/web/types/chat.tsindex 88f4f13e4..3327cde40 100644--- a/web/types/chat.ts+++ b/web/types/chat.ts@@ -43,4 +43,3 @@ export const INITIAL_CHAT_STATE: ChatState = {enableWebSearch: false,currentStage: null,};-diff --git a/web/types/common.ts b/web/types/common.tsindex a06e57a0e..3832936d8 100644--- a/web/types/common.ts+++ b/web/types/common.ts@@ -46,4 +46,3 @@ export interface UISettings {theme: Theme;language: Language;}-diff --git a/web/types/ideagen.ts b/web/types/ideagen.tsindex 78f989eb5..9cc01f6f7 100644--- a/web/types/ideagen.ts+++ b/web/types/ideagen.ts@@ -32,4 +32,3 @@ export const INITIAL_IDEAGEN_STATE: IdeaGenState = {generatedIdeas: [],progress: null,};-diff --git a/web/types/index.ts b/web/types/index.tsindex f53fca17a..dec92a5aa 100644--- a/web/types/index.ts+++ b/web/types/index.ts@@ -10,4 +10,3 @@ export * from "./research";export * from "./chat";export * from "./sidebar";export * from "./ideagen";-diff --git a/web/types/sidebar.ts b/web/types/sidebar.tsindex 09eff3313..51b97281e 100644--- a/web/types/sidebar.ts+++ b/web/types/sidebar.ts@@ -35,4 +35,3 @@ export const DEFAULT_NAV_ORDER: SidebarNavOrder = {"/co_writer",],};-diff --git a/web/types/solver.ts b/web/types/solver.tsindex eb6cfd540..08956dfe8 100644--- a/web/types/solver.ts+++ b/web/types/solver.ts@@ -80,4 +80,3 @@ export const INITIAL_SOLVER_STATE: SolverState = {progress: {},},};-