DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix docker & KB init
Bingxi Zhao0a96e701ecae
diff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yamlindex d00143d29..6101e4e0d 100644--- a/.github/workflows/linting.yaml+++ b/.github/workflows/linting.yaml@@ -90,7 +90,8 @@ jobs:working-directory: ./webrun: |echo "π Running ESLint on frontend code..."- npm run lint 2>&1 || {+ # Use npx next lint with explicit directory to avoid path issues+ npx next lint --dir . 2>&1 || {echo ""echo "βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"echo "β β ESLint checks failed! β"diff --git a/README.md b/README.mdindex 76f13c8c7..cc2d68536 100644--- a/README.md+++ b/README.md@@ -338,8 +338,8 @@ cp .env.example .env**Quick Start** β Build from source:```bash-docker compose up --build -d # Build and start (~5-10 min first run)-docker compose logs -f # View logs+docker compose up # Build and start (~11 min first run on mac mini M4)+docker compose build --no-cache # Clear cache and rebuild after pull the newest repo```**Or use pre-built image** (faster):diff --git a/requirements.txt b/requirements.txtindex 8ecf5e36e..a4ccf82e4 100644--- a/requirements.txt+++ b/requirements.txt@@ -42,7 +42,6 @@ pydantic>=2.0.0# ============================================# RAG and knowledge base# ============================================-lightrag-hku>=1.0.0raganything>=0.1.0docling>=2.31.0 # Document parser for Office/HTML (alternative to MinerU)diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.pyindex 14556dfaf..5982a8f94 100644--- a/src/api/routers/knowledge.py+++ b/src/api/routers/knowledge.py@@ -531,13 +531,28 @@ async def create_knowledge_base(except ValueError as e:raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")- progress_tracker = ProgressTracker(name, _kb_base_dir)-logger.info(f"Creating KB: {name}")- progress_tracker.update(- ProgressStage.INITIALIZING, "Initializing knowledge base...", current=0, total=0+ # Register KB to kb_config.json immediately with "initializing" status+ # This ensures the KB appears in the list right away+ manager.update_kb_status(+ name=name,+ status="initializing",+ progress={+ "stage": "initializing",+ "message": "Initializing knowledge base...",+ "percent": 0,+ "current": 0,+ "total": len(files),+ },)+ # Also store rag_provider in config (reload and update)+ manager.config = manager._load_config()+ if name in manager.config.get("knowledge_bases", {}):+ manager.config["knowledge_bases"][name]["rag_provider"] = rag_provider+ manager._save_config()++ progress_tracker = ProgressTracker(name, _kb_base_dir)initializer = KnowledgeBaseInitializer(kb_name=name,diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.pyindex cff436ec1..76eff0b76 100644--- a/src/knowledge/initializer.py+++ b/src/knowledge/initializer.py@@ -60,39 +60,33 @@ class KnowledgeBaseInitializer:self.rag_provider = rag_providerdef _register_to_config(self):- """Register KB to kb_config.json (only knowledge_bases list, no default)."""- config_file = self.base_dir / "kb_config.json"- if config_file.exists():- try:- with open(config_file, encoding="utf-8") as f:- config = json.load(f)- except Exception as e:- logger.warning(f"Failed to read config: {e}, creating new")- config = {"knowledge_bases": {}}- else:- config = {"knowledge_bases": {}}-- if "knowledge_bases" not in config:- config["knowledge_bases"] = {}-- # Remove old "default" field if exists (migration)- if "default" in config:- del config["default"]-- if self.kb_name not in config.get("knowledge_bases", {}):- config["knowledge_bases"][self.kb_name] = {- "path": self.kb_name,- "description": f"Knowledge base: {self.kb_name}",- }-- try:- with open(config_file, "w", encoding="utf-8") as f:- json.dump(config, indent=2, ensure_ascii=False, fp=f)- logger.info(" β Registered to kb_config.json")- except Exception as e:- logger.warning(f"Failed to update config: {e}")- else:- logger.info(" β Already registered in kb_config.json")+ """Register KB to kb_config.json using KnowledgeBaseManager for consistency."""+ try:+ from src.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=str(self.base_dir))++ # Check if already registered (reload config to get latest)+ manager.config = manager._load_config()+ if self.kb_name in manager.config.get("knowledge_bases", {}):+ logger.info(" β Already registered in kb_config.json")+ return++ # Register with initializing status+ manager.update_kb_status(+ name=self.kb_name,+ status="initializing",+ progress={+ "stage": "initializing",+ "message": "Creating directory structure...",+ "percent": 0,+ "current": 0,+ "total": 0,+ },+ )+ logger.info(" β Registered to kb_config.json")+ except Exception as e:+ logger.warning(f"Failed to register to config: {e}")def _update_metadata_with_provider(self, provider: str):"""Update metadata.json and centralized config with the RAG provider used."""diff --git a/src/knowledge/manager.py b/src/knowledge/manager.pyindex ba200af77..52b15d09b 100644--- a/src/knowledge/manager.py+++ b/src/knowledge/manager.py@@ -9,6 +9,7 @@ Manages multiple knowledge bases and provides utilities for accessing them.from datetime import datetimeimport hashlibimport json+import osfrom pathlib import Pathimport shutil@@ -28,43 +29,124 @@ class KnowledgeBaseManager:def _load_config(self) -> dict:"""Load knowledge base configuration (kb_config.json only stores KB list)"""+ import fcntl+if self.config_file.exists():- with open(self.config_file, encoding="utf-8") as f:- config = json.load(f)+ try:+ with open(self.config_file, encoding="utf-8") as f:+ fcntl.flock(f.fileno(), fcntl.LOCK_SH) # Shared lock for reading+ try:+ content = f.read()+ if not content.strip():+ # Empty file, return default+ return {"knowledge_bases": {}}+ config = json.loads(content)+ finally:+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)++ # Ensure knowledge_bases key exists+ if "knowledge_bases" not in config:+ config["knowledge_bases"] = {}+# Migration: remove old "default" field if presentif "default" in config:del config["default"]- # Save cleaned config- try:- with open(self.config_file, "w", encoding="utf-8") as wf:- json.dump(config, wf, indent=2, ensure_ascii=False)- except Exception:- pass+ # Note: Don't save during load to avoid recursion issues+ # The next _save_config() call will persist this change+return config+ except (json.JSONDecodeError, Exception) as e:+ print(f"[KnowledgeBaseManager] Error loading config: {e}")+ return {"knowledge_bases": {}}return {"knowledge_bases": {}}def _save_config(self):- """Save knowledge base configuration"""+ """Save knowledge base configuration (thread-safe with file locking)"""+ import fcntl++ # Use exclusive lock for writingwith open(self.config_file, "w", encoding="utf-8") as f:- json.dump(self.config, f, indent=2, ensure_ascii=False)+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)+ try:+ json.dump(self.config, f, indent=2, ensure_ascii=False)+ f.flush()+ os.fsync(f.fileno()) # Ensure data is written to disk+ finally:+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)++ def update_kb_status(+ self,+ name: str,+ status: str,+ progress: dict | None = None,+ ):+ """+ Update knowledge base status and progress in kb_config.json.++ Args:+ name: Knowledge base name+ status: Status string ("initializing", "processing", "ready", "error")+ progress: Optional progress dict with keys like:+ - stage: Current stage name+ - message: Human-readable message+ - percent: Progress percentage (0-100)+ - current: Current item number+ - total: Total items+ - file_name: Current file being processed+ - error: Error message (if status is "error")+ """+ # Reload config to get latest state+ self.config = self._load_config()++ if "knowledge_bases" not in self.config:+ self.config["knowledge_bases"] = {}++ if name not in self.config["knowledge_bases"]:+ # Auto-register if not exists+ self.config["knowledge_bases"][name] = {+ "path": name,+ "description": f"Knowledge base: {name}",+ }++ kb_config = self.config["knowledge_bases"][name]+ kb_config["status"] = status+ kb_config["updated_at"] = datetime.now().isoformat()++ if progress is not None:+ kb_config["progress"] = progress+ elif status == "ready":+ # Clear progress when ready+ kb_config["progress"] = {+ "stage": "completed",+ "message": "Ready",+ "percent": 100,+ }++ self._save_config()++ def get_kb_status(self, name: str) -> dict | None:+ """Get status and progress for a knowledge base."""+ self.config = self._load_config()+ kb_config = self.config.get("knowledge_bases", {}).get(name)+ if not kb_config:+ return None+ return {+ "status": kb_config.get("status", "unknown"),+ "progress": kb_config.get("progress"),+ "updated_at": kb_config.get("updated_at"),+ }def list_knowledge_bases(self) -> list[str]:"""List all available knowledge bases from kb_config.json"""- kb_list = []+ # Always reload config from file to ensure we have the latest data+ # This is important when new KBs are created by other processes/requests+ self.config = self._load_config()# Read knowledge base list from config file (this is the authoritative source)+ # Return all KBs in config, regardless of directory status+ # (status field indicates if KB is ready or still initializing)config_kbs = self.config.get("knowledge_bases", {})-- for kb_name in config_kbs.keys():- # Verify knowledge base directory exists- kb_dir = self.base_dir / kb_name- if kb_dir.exists() and kb_dir.is_dir():- kb_list.append(kb_name)- else:- # If in config but directory doesn't exist, log warning but don't add- print(- f"Warning: Knowledge base '{kb_name}' is in config but directory does not exist: {kb_dir}"- )+ kb_list = list(config_kbs.keys())# If no config file or config is empty, fallback to scanning directory (backward compatibility)if not kb_list and self.base_dir.exists():@@ -185,83 +267,115 @@ class KnowledgeBaseManager:This method:1. Gets the KB name (from parameter or default)- 2. Reads metadata.json from the KB directory- 3. Collects statistics about files and RAG status+ 2. Reads status and progress from kb_config.json+ 3. Reads metadata.json from the KB directory (if exists)+ 4. Collects statistics about files and RAG status"""+ # Reload config to get latest status+ self.config = self._load_config()+kb_name = name or self.get_default()if kb_name is None:raise ValueError("No knowledge base name provided and no default set")# Get knowledge base pathkb_dir = self.base_dir / kb_name- if not kb_dir.exists():- raise ValueError(f"Knowledge base directory does not exist: {kb_dir}")- # Verify knowledge base is in config (if not, give warning but don't block)- if kb_name not in self.config.get("knowledge_bases", {}):- print(- f"Warning: Knowledge base '{kb_name}' is not in kb_config.json, but directory exists"- )+ # Get status and progress from kb_config.json+ kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})+ status = kb_config.get("status")+ progress = kb_config.get("progress")++ # KB might not have a directory yet if still initializing+ dir_exists = kb_dir.exists()++ # For old KBs without status field, determine status from rag_storage+ if not status and dir_exists:+ rag_storage_dir = kb_dir / "rag_storage"+ if rag_storage_dir.exists() and any(rag_storage_dir.iterdir()):+ status = "ready"+ else:+ status = "unknown"+ elif not status:+ status = "unknown"info = {"name": kb_name,"path": str(kb_dir),"is_default": kb_name == self.get_default(),"metadata": {},+ "status": status,+ "progress": progress,}# Read metadata.json (if exists)- metadata_file = kb_dir / "metadata.json"- if metadata_file.exists():- try:- with open(metadata_file, encoding="utf-8") as f:- info["metadata"] = json.load(f)- except Exception as e:- print(f"Warning: Failed to read metadata.json for KB '{kb_name}': {e}")- info["metadata"] = {}- else:- # metadata.json doesn't exist, use empty dict- info["metadata"] = {}+ if dir_exists:+ metadata_file = kb_dir / "metadata.json"+ if metadata_file.exists():+ try:+ with open(metadata_file, encoding="utf-8") as f:+ info["metadata"] = json.load(f)+ except Exception as e:+ print(f"Warning: Failed to read metadata.json for KB '{kb_name}': {e}")+ info["metadata"] = {}# Count files - handle errors gracefully- raw_dir = kb_dir / "raw"- images_dir = kb_dir / "images"- content_list_dir = kb_dir / "content_list"- rag_storage_dir = kb_dir / "rag_storage"+ raw_dir = kb_dir / "raw" if dir_exists else None+ images_dir = kb_dir / "images" if dir_exists else None+ content_list_dir = kb_dir / "content_list" if dir_exists else None+ rag_storage_dir = kb_dir / "rag_storage" if dir_exists else None- try:- raw_count = (- len([f for f in raw_dir.iterdir() if f.is_file()]) if raw_dir.exists() else 0- )- except Exception:- raw_count = 0+ raw_count = 0+ images_count = 0+ content_lists_count = 0- try:- images_count = (- len([f for f in images_dir.iterdir() if f.is_file()]) if images_dir.exists() else 0- )- except Exception:- images_count = 0+ if dir_exists:+ try:+ raw_count = (+ len([f for f in raw_dir.iterdir() if f.is_file()]) if raw_dir.exists() else 0+ )+ except Exception:+ pass- try:- content_lists_count = (- len(list(content_list_dir.glob("*.json"))) if content_list_dir.exists() else 0- )- except Exception:- content_lists_count = 0+ try:+ images_count = (+ len([f for f in images_dir.iterdir() if f.is_file()])+ if images_dir.exists()+ else 0+ )+ except Exception:+ pass++ try:+ content_lists_count = (+ len(list(content_list_dir.glob("*.json"))) if content_list_dir.exists() else 0+ )+ except Exception:+ passmetadata = info["metadata"]rag_provider = metadata.get("rag_provider") if isinstance(metadata, dict) else None+ # Also check kb_config for rag_provider (fallback)+ if not rag_provider:+ rag_provider = kb_config.get("rag_provider")++ rag_initialized = (+ dir_exists and rag_storage_dir and rag_storage_dir.exists() and rag_storage_dir.is_dir()+ )+info["statistics"] = {"raw_documents": raw_count,"images": images_count,"content_lists": content_lists_count,- "rag_initialized": rag_storage_dir.exists() and rag_storage_dir.is_dir(),- "rag_provider": rag_provider, # Add RAG provider info+ "rag_initialized": rag_initialized,+ "rag_provider": rag_provider,+ # Include status and progress in statistics for backward compatibility+ "status": status,+ "progress": progress,}# Try to get RAG statistics- if rag_storage_dir.exists() and rag_storage_dir.is_dir():+ if rag_initialized:try:entities_file = rag_storage_dir / "kv_store_full_entities.json"relations_file = rag_storage_dir / "kv_store_full_relations.json"diff --git a/src/knowledge/progress_tracker.py b/src/knowledge/progress_tracker.pyindex a635b12eb..cd81c9e75 100644--- a/src/knowledge/progress_tracker.py+++ b/src/knowledge/progress_tracker.py@@ -99,13 +99,54 @@ class ProgressTracker:print(f"[ProgressTracker] Callback error: {e}")def _save_progress(self, progress: dict):- """Save progress to file"""+ """Save progress to kb_config.json and local .progress.json file"""+ # Save to kb_config.json (centralized config)+ try:+ from src.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=str(self.base_dir))++ # Determine status based on stage+ stage = progress.get("stage", "")+ if stage == "completed":+ status = "ready"+ elif stage == "error":+ status = "error"+ elif stage in [+ "initializing",+ "processing_documents",+ "processing_file",+ "extracting_items",+ ]:+ status = "processing"+ else:+ status = "initializing"++ # Update kb_config.json with status and progress+ manager.update_kb_status(+ name=self.kb_name,+ status=status,+ progress={+ "stage": progress.get("stage"),+ "message": progress.get("message"),+ "percent": progress.get("progress_percent", 0),+ "current": progress.get("current", 0),+ "total": progress.get("total", 0),+ "file_name": progress.get("file_name"),+ "error": progress.get("error"),+ "timestamp": progress.get("timestamp"),+ },+ )+ except Exception as e:+ print(f"[ProgressTracker] Failed to save progress to kb_config.json: {e}")++ # Also save to local .progress.json file (for backward compatibility)try:self.kb_dir.mkdir(parents=True, exist_ok=True)with open(self.progress_file, "w", encoding="utf-8") as f:json.dump(progress, f, indent=2, ensure_ascii=False)except Exception as e:- print(f"[ProgressTracker] Failed to save progress: {e}")+ print(f"[ProgressTracker] Failed to save progress to local file: {e}")def update(self,diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsxindex abef3eef4..a319d48d0 100644--- a/web/app/knowledge/page.tsx+++ b/web/app/knowledge/page.tsx@@ -47,15 +47,31 @@ import {} from "lucide-react";import { apiUrl, wsUrl } from "@/lib/api";+interface ProgressInfo {+ stage: string;+ message: string;+ percent?: number;+ progress_percent?: number; // Legacy field from WebSocket+ current: number;+ total: number;+ file_name?: string;+ error?: string;+ timestamp?: string;+}+interface KnowledgeBase {name: string;is_default: boolean;+ status?: string; // "initializing", "processing", "ready", "error"+ progress?: ProgressInfo;statistics: {raw_documents: number;images: number;content_lists: number;rag_initialized: boolean;rag_provider?: string;+ status?: string;+ progress?: ProgressInfo;rag?: {chunks?: number;entities?: number;@@ -64,16 +80,6 @@ interface KnowledgeBase {};}-interface ProgressInfo {- stage: string;- message: string;- current: number;- total: number;- file_name?: string;- progress_percent: number;- error?: string;-}-interface UploadFile {file: File;id: string;@@ -554,6 +560,26 @@ export default function KnowledgePage() {fetchKnowledgeBases();}, [fetchKnowledgeBases]);+ // Auto-poll when any KB is processing/initializing+ useEffect(() => {+ // Check if any KB is in processing/initializing state+ const hasProcessingKb = kbs.some((kb) => {+ const status = kb.statistics.status || kb.status;+ return status === "initializing" || status === "processing";+ });++ if (!hasProcessingKb) {+ return;+ }++ // Poll every 3 seconds while processing+ const intervalId = setInterval(() => {+ fetchKnowledgeBases();+ }, 3000);++ return () => clearInterval(intervalId);+ }, [kbs, fetchKnowledgeBases]);+// Fetch RAG providersuseEffect(() => {const fetchRagProviders = async () => {@@ -869,51 +895,14 @@ export default function KnowledgePage() {const result = await res.json();- // Immediately display new KB in frontend (optimistic update)- const newKb: KnowledgeBase = {- name: result.name,- is_default: false,- statistics: {- raw_documents: result.files?.length || 0,- images: 0,- content_lists: 0,- rag_initialized: false,- rag_provider: ragProvider,- },- };-- // Add to list (if not exists)- setKbs((prev) => {- const exists = prev.some((kb) => kb.name === newKb.name);- if (exists) {- return prev;- }- return [newKb, ...prev];- });-- // Initialize progress state- setProgressMap((prev) => ({- ...prev,- [newKb.name]: {- stage: "initializing",- message: "Initializing knowledge base...",- current: 0,- total: 0,- file_name: "",- progress_percent: 0,- timestamp: new Date().toISOString(),- },- }));-setCreateModalOpen(false);clearAllFiles();setNewKbName("");setRagProvider("llamaindex"); // Reset to default- // Delay refresh to get full info (but user can already see the new KB)- setTimeout(async () => {- await fetchKnowledgeBases();- }, 1000);+ // Immediately refresh to get the new KB from backend+ // (Backend now registers KB to kb_config.json immediately with status)+ await fetchKnowledgeBases();showToast("Knowledge base created successfully!", "success");} catch (err: any) {@@ -1145,37 +1134,53 @@ export default function KnowledgePage() {<Layers className="w-3 h-3" /> Status</span>{(() => {- const progress = progressMap[kb.name];- if (progress) {- if (progress.stage === "completed") {- return (- <span className="text-emerald-600 dark:text-emerald-400 font-bold">- Ready- </span>- );- } else if (progress.stage === "error") {- return (- <span className="text-red-600 dark:text-red-400 font-bold">- Error- </span>- );- } else {- // Display current stage and progress- const stageLabels: Record<string, string> = {- initializing: "Initializing",- processing_documents: "Processing",- processing_file: "Processing File",- extracting_items: "Extracting Items",- };- const stageLabel =- stageLabels[progress.stage] || progress.stage;- return (- <span className="text-blue-600 dark:text-blue-400 font-bold flex items-center gap-1">- <Loader2 className="w-3 h-3 animate-spin" />- {stageLabel} {progress.progress_percent}%- </span>- );- }+ // Priority: API progress > WebSocket progressMap > rag_initialized+ const apiProgress = kb.statistics.progress || kb.progress;+ const wsProgress = progressMap[kb.name];+ const progress = apiProgress || wsProgress;+ const status = kb.statistics.status || kb.status;++ if (+ status === "ready" ||+ progress?.stage === "completed"+ ) {+ return (+ <span className="text-emerald-600 dark:text-emerald-400 font-bold">+ Ready+ </span>+ );+ } else if (+ status === "error" ||+ progress?.stage === "error"+ ) {+ return (+ <span className="text-red-600 dark:text-red-400 font-bold">+ Error+ </span>+ );+ } else if (+ status === "initializing" ||+ status === "processing" ||+ progress+ ) {+ // Display current stage and progress+ const stageLabels: Record<string, string> = {+ initializing: "Initializing",+ processing_documents: "Processing",+ processing_file: "Processing File",+ extracting_items: "Extracting Items",+ };+ const stage =+ progress?.stage || status || "initializing";+ const stageLabel = stageLabels[stage] || stage;+ const percent =+ progress?.percent ?? progress?.progress_percent ?? 0;+ return (+ <span className="text-blue-600 dark:text-blue-400 font-bold flex items-center gap-1">+ <Loader2 className="w-3 h-3 animate-spin" />+ {stageLabel} {percent}%+ </span>+ );}return (<span@@ -1194,19 +1199,36 @@ export default function KnowledgePage() {</div><div className="w-full bg-slate-100 dark:bg-slate-700 rounded-full h-1.5 overflow-hidden">{(() => {- const progress = progressMap[kb.name];- if (progress) {- const percent = progress.progress_percent;+ const apiProgress = kb.statistics.progress || kb.progress;+ const wsProgress = progressMap[kb.name];+ const progress = apiProgress || wsProgress;+ const status = kb.statistics.status || kb.status;++ if (+ progress ||+ status === "initializing" ||+ status === "processing"+ ) {+ const percent =+ progress?.percent ?? progress?.progress_percent ?? 0;let bgColor = "bg-blue-500";- if (progress.stage === "completed") {+ if (+ status === "ready" ||+ progress?.stage === "completed"+ ) {bgColor = "bg-emerald-500";- } else if (progress.stage === "error") {+ } else if (+ status === "error" ||+ progress?.stage === "error"+ ) {bgColor = "bg-red-500";}return (<divclassName={`h-full rounded-full ${bgColor} transition-all duration-300`}- style={{ width: `${percent}%` }}+ style={{+ width: `${Math.max(percent, status === "initializing" ? 5 : 0)}%`,+ }}/>);}@@ -1218,29 +1240,39 @@ export default function KnowledgePage() {})()}</div>{(() => {- const progress = progressMap[kb.name];- if (progress && progress.message) {+ const apiProgress = kb.statistics.progress || kb.progress;+ const wsProgress = progressMap[kb.name];+ const progress = apiProgress || wsProgress;+ const status = kb.statistics.status || kb.status;++ if (+ progress?.message ||+ (status && status !== "ready" && status !== "unknown")+ ) {return (<div className="mt-2 space-y-1"><div className="text-[10px] text-slate-600 dark:text-slate-400 font-medium flex items-center justify-between">- <span>{progress.message}</span>+ <span>+ {progress?.message || `Status: ${status}`}+ </span>{/* Clear button for stuck states */}- {progress.stage !== "completed" && (- <button- onClick={async (e) => {- e.stopPropagation();- await clearProgress(kb.name);- // Refresh KB list to show correct status- fetchKnowledgeBases();- }}- className="text-slate-400 dark:text-slate-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"- title="Clear progress status"- >- <X className="w-3 h-3" />- </button>- )}+ {progress?.stage !== "completed" &&+ status !== "ready" && (+ <button+ onClick={async (e) => {+ e.stopPropagation();+ await clearProgress(kb.name);+ // Refresh KB list to show correct status+ fetchKnowledgeBases();+ }}+ className="text-slate-400 dark:text-slate-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"+ title="Clear progress status"+ >+ <X className="w-3 h-3" />+ </button>+ )}</div>- {progress.file_name && (+ {progress?.file_name && (<div className="text-[10px] text-slate-500 dark:text-slate-400 flex items-center gap-1"><FileText className="w-3 h-3" /><span className="truncate">@@ -1248,12 +1280,14 @@ export default function KnowledgePage() {</span></div>)}- {progress.current > 0 && progress.total > 0 && (- <div className="text-[10px] text-slate-400 dark:text-slate-500">- File {progress.current} of {progress.total}- </div>- )}- {progress.error && (+ {progress &&+ progress.current > 0 &&+ progress.total > 0 && (+ <div className="text-[10px] text-slate-400 dark:text-slate-500">+ File {progress.current} of {progress.total}+ </div>+ )}+ {progress?.error && (<div className="text-[10px] text-red-600 dark:text-red-400 mt-1">Error: {progress.error}</div>