DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: refactor UX with toast notifications and FolderSyncManager component
ahmedjawedajaccfcb1d8eac
diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.pyindex 6d2c3737d..8394710bd 100644--- a/src/api/routers/knowledge.py+++ b/src/api/routers/knowledge.py@@ -83,6 +83,21 @@ class KnowledgeBaseInfo(BaseModel):statistics: dict+class LinkFolderRequest(BaseModel):+ """Request model for linking a local folder to a KB."""++ folder_path: str+++class LinkedFolderInfo(BaseModel):+ """Response model for linked folder information."""++ id: str+ path: str+ added_at: str+ file_count: int++async def run_initialization_task(initializer: KnowledgeBaseInitializer):"""Background task for knowledge base initialization"""task_manager = TaskIDManager.get_instance()@@ -566,3 +581,128 @@ async def websocket_progress(websocket: WebSocket, kb_name: str):await websocket.close()except:pass++[email protected]("/{kb_name}/link-folder", response_model=LinkedFolderInfo)+async def link_folder(kb_name: str, request: LinkFolderRequest):+ """+ Link a local folder to a knowledge base.++ This allows syncing documents from a local folder (which can be+ synced with SharePoint, Google Drive, OneLake, etc.) to the KB.++ The folder path supports:+ - Absolute paths: /Users/name/Documents or C:\\Users\\name\\Documents+ - Home directory: ~/Documents+ - Relative paths (resolved from server working directory)+ """+ try:+ manager = get_kb_manager()+ folder_info = manager.link_folder(kb_name, request.folder_path)+ logger.info(f"Linked folder '{request.folder_path}' to KB '{kb_name}'")+ return LinkedFolderInfo(**folder_info)+ except ValueError as e:+ error_msg = str(e)+ if "not found" in error_msg.lower():+ raise HTTPException(status_code=404, detail=error_msg)+ raise HTTPException(status_code=400, detail=error_msg)+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/{kb_name}/linked-folders", response_model=list[LinkedFolderInfo])+async def get_linked_folders(kb_name: str):+ """Get list of linked folders for a knowledge base."""+ try:+ manager = get_kb_manager()+ folders = manager.get_linked_folders(kb_name)+ return [LinkedFolderInfo(**f) for f in folders]+ except ValueError:+ raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/{kb_name}/linked-folders/{folder_id}")+async def unlink_folder(kb_name: str, folder_id: str):+ """Unlink a folder from a knowledge base."""+ try:+ manager = get_kb_manager()+ success = manager.unlink_folder(kb_name, folder_id)+ if not success:+ raise HTTPException(status_code=404, detail=f"Folder '{folder_id}' not found")+ logger.info(f"Unlinked folder '{folder_id}' from KB '{kb_name}'")+ return {"message": "Folder unlinked successfully", "folder_id": folder_id}+ except ValueError:+ raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/{kb_name}/sync-folder/{folder_id}")+async def sync_folder(kb_name: str, folder_id: str, background_tasks: BackgroundTasks):+ """+ Sync files from a linked folder to the knowledge base.++ This scans the linked folder for supported documents and processes+ any new files that haven't been added yet.+ """+ try:+ manager = get_kb_manager()++ # Get linked folders and find the one with matching ID+ folders = manager.get_linked_folders(kb_name)+ folder_info = next((f for f in folders if f["id"] == folder_id), None)++ if not folder_info:+ raise HTTPException(status_code=404, detail=f"Linked folder '{folder_id}' not found")++ folder_path = folder_info["path"]++ # Check for changes (new or modified files)+ changes = manager.detect_folder_changes(kb_name, folder_id)+ files_to_process = changes["new_files"] + changes["modified_files"]++ if not files_to_process:+ return {"message": "No new or modified files to sync", "files": [], "file_count": 0}++ # Get LLM config+ try:+ llm_config = get_llm_config()+ api_key = llm_config.api_key+ base_url = llm_config.base_url+ except ValueError as e:+ raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")++ logger.info(+ f"Syncing {len(files_to_process)} files from folder '{folder_path}' to KB '{kb_name}'"+ )++ # NOTE: We DO NOT update sync state here anymore.+ # It is updated in run_upload_processing_task only after successful processing.+ # This prevents marking files as synced if processing fails (race condition fix).++ # Add background task to process files+ background_tasks.add_task(+ run_upload_processing_task,+ kb_name=kb_name,+ base_dir=str(_kb_base_dir),+ api_key=api_key,+ base_url=base_url,+ uploaded_file_paths=files_to_process,+ folder_id=folder_id, # Pass folder_id to update state on success+ )++ return {+ "message": f"Syncing {len(files_to_process)} files from linked folder",+ "folder_path": folder_path,+ "new_files": changes["new_count"],+ "modified_files": changes["modified_count"],+ "file_count": len(files_to_process),+ }+ except HTTPException:+ raise+ except ValueError:+ raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))diff --git a/src/knowledge/manager.py b/src/knowledge/manager.pyindex c7538ef5e..8537e2bf9 100644--- a/src/knowledge/manager.py+++ b/src/knowledge/manager.py@@ -337,6 +337,290 @@ class KnowledgeBaseManager:return True+def main():+ # ============================================================++ def link_folder(self, kb_name: str, folder_path: str) -> dict:+ """+ Link a local folder to a knowledge base.++ Args:+ kb_name: Knowledge base name+ folder_path: Path to local folder (supports ~, relative paths)++ Returns:+ Dict with folder info including id, path, and file count++ Raises:+ ValueError: If KB not found or folder doesn't exist+ """+ if kb_name not in self.list_knowledge_bases():+ raise ValueError(f"Knowledge base not found: {kb_name}")++ # Normalize path (cross-platform: handles ~, relative paths, etc.)+ folder = Path(folder_path).expanduser().resolve()++ if not folder.exists():+ raise ValueError(f"Folder does not exist: {folder}")+ if not folder.is_dir():+ raise ValueError(f"Path is not a directory: {folder}")++ # Get supported files in folder+ supported_extensions = {".pdf", ".docx", ".doc", ".txt", ".md", ".markdown"}+ files = []+ 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]++ # Load existing linked folders from metadata+ kb_dir = self.base_dir / kb_name+ metadata_file = kb_dir / "metadata.json"+ metadata = {}++ if metadata_file.exists():+ try:+ with open(metadata_file, encoding="utf-8") as f:+ metadata = json.load(f)+ except Exception:+ metadata = {}++ if "linked_folders" not in metadata:+ metadata["linked_folders"] = []++ # Check if already linked+ existing_ids = [f["id"] for f 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++ # Add folder info+ folder_info = {+ "id": folder_id,+ "path": str(folder),+ "added_at": datetime.now().isoformat(),+ "file_count": len(files),+ }+ metadata["linked_folders"].append(folder_info)++ # Save metadata+ with open(metadata_file, "w", encoding="utf-8") as f:+ json.dump(metadata, f, indent=2, ensure_ascii=False)++ return folder_info++ def get_linked_folders(self, kb_name: str) -> list[dict]:+ """+ Get list of linked folders for a knowledge base.++ Args:+ kb_name: Knowledge base name++ Returns:+ List of linked folder info dicts+ """+ if kb_name not in self.list_knowledge_bases():+ raise ValueError(f"Knowledge base not found: {kb_name}")++ kb_dir = self.base_dir / kb_name+ metadata_file = kb_dir / "metadata.json"++ if not metadata_file.exists():+ return []++ try:+ with open(metadata_file, encoding="utf-8") as f:+ metadata = json.load(f)+ return metadata.get("linked_folders", [])+ except Exception:+ return []++ def unlink_folder(self, kb_name: str, folder_id: str) -> bool:+ """+ Unlink a folder from a knowledge base.++ Args:+ kb_name: Knowledge base name+ folder_id: Folder ID to unlink++ Returns:+ True if unlinked successfully, False if not found+ """+ if kb_name not in self.list_knowledge_bases():+ raise ValueError(f"Knowledge base not found: {kb_name}")++ kb_dir = self.base_dir / kb_name+ metadata_file = kb_dir / "metadata.json"++ if not metadata_file.exists():+ return False++ try:+ with open(metadata_file, encoding="utf-8") as f:+ metadata = json.load(f)+ except Exception:+ return False++ linked = metadata.get("linked_folders", [])+ new_linked = [f for f in linked if f["id"] != folder_id]++ if len(new_linked) == len(linked):+ return False # Not found++ metadata["linked_folders"] = new_linked++ with open(metadata_file, "w", encoding="utf-8") as f:+ json.dump(metadata, f, indent=2, ensure_ascii=False)++ return True++ def scan_linked_folder(self, folder_path: str) -> list[str]:+ """+ Scan a linked folder and return list of supported file paths.++ Args:+ folder_path: Path to folder++ Returns:+ List of file paths (as strings)+ """+ folder = Path(folder_path).expanduser().resolve()++ if not folder.exists() or not folder.is_dir():+ return []++ supported_extensions = {".pdf", ".docx", ".doc", ".txt", ".md", ".markdown"}+ files = []++ for ext in supported_extensions:+ for file_path in folder.glob(f"**/*{ext}"):+ files.append(str(file_path))++ return sorted(files)++ def detect_folder_changes(self, kb_name: str, folder_id: str) -> dict:+ """+ Detect new and modified files in a linked folder since last sync.++ This enables automatic sync of changes from local folders that may+ be synced with cloud services like SharePoint, Google Drive, etc.++ Args:+ kb_name: Knowledge base name+ folder_id: Folder ID to check for changes++ Returns:+ Dict with 'new_files', 'modified_files', and 'has_changes' keys+ """+ if kb_name not in self.list_knowledge_bases():+ raise ValueError(f"Knowledge base not found: {kb_name}")++ # Get folder info+ folders = self.get_linked_folders(kb_name)+ folder_info = next((f for f in folders if f["id"] == folder_id), None)++ if not folder_info:+ raise ValueError(f"Linked folder not found: {folder_id}")++ folder_path = Path(folder_info["path"]).expanduser().resolve()+ last_sync = folder_info.get("last_sync")+ synced_files = folder_info.get("synced_files", {})++ # Parse last sync timestamp+ last_sync_time = None+ if last_sync:+ try:+ last_sync_time = datetime.fromisoformat(last_sync)+ except Exception:+ pass++ # Scan current files+ supported_extensions = {".pdf", ".docx", ".doc", ".txt", ".md", ".markdown"}+ new_files = []+ modified_files = []++ for ext in supported_extensions:+ for file_path in folder_path.glob(f"**/*{ext}"):+ file_str = str(file_path)+ file_mtime = datetime.fromtimestamp(file_path.stat().st_mtime)++ if file_str in synced_files:+ # Check if modified since last sync+ prev_mtime_str = synced_files[file_str]+ try:+ prev_mtime = datetime.fromisoformat(prev_mtime_str)+ if file_mtime > prev_mtime:+ modified_files.append(file_str)+ except Exception:+ modified_files.append(file_str)+ else:+ # New file (not in synced files)+ new_files.append(file_str)++ return {+ "new_files": sorted(new_files),+ "modified_files": sorted(modified_files),+ "has_changes": len(new_files) > 0 or len(modified_files) > 0,+ "new_count": len(new_files),+ "modified_count": len(modified_files),+ }++ def update_folder_sync_state(self, kb_name: str, folder_id: str, synced_files: list[str]):+ """+ Update the sync state for a linked folder after successful sync.++ Records which files were synced and their modification times,+ enabling future change detection.++ Args:+ kb_name: Knowledge base name+ folder_id: Folder ID+ synced_files: List of file paths that were successfully synced+ """+ if kb_name not in self.list_knowledge_bases():+ raise ValueError(f"Knowledge base not found: {kb_name}")++ kb_dir = self.base_dir / kb_name+ metadata_file = kb_dir / "metadata.json"++ if not metadata_file.exists():+ return++ try:+ with open(metadata_file, encoding="utf-8") as f:+ metadata = json.load(f)+ except Exception:+ return++ linked = metadata.get("linked_folders", [])++ for folder in linked:+ if folder["id"] == folder_id:+ # Record sync timestamp+ folder["last_sync"] = datetime.now().isoformat()++ # Record file modification times+ file_states = folder.get("synced_files", {})+ for file_path in synced_files:+ try:+ p = Path(file_path)+ if p.exists():+ mtime = datetime.fromtimestamp(p.stat().st_mtime)+ file_states[file_path] = mtime.isoformat()+ except Exception:+ pass++ folder["synced_files"] = file_states+ folder["file_count"] = len(file_states)+ break++def main():"""Command-line interface for knowledge base manager"""import argparsediff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsxindex 2e39accf7..ce67655f3 100644--- a/web/app/knowledge/page.tsx+++ b/web/app/knowledge/page.tsx@@ -15,6 +15,8 @@ import {Loader2,X,RefreshCw,+ CheckCircle2,+ AlertCircle,} from "lucide-react";import { apiUrl, wsUrl } from "@/lib/api";@@ -58,6 +60,21 @@ export default function KnowledgePage() {const [progressMap, setProgressMap] = useState<Record<string, ProgressInfo>>({},);++ // Toast notification system+ const [toast, setToast] = useState<{+ message: string;+ type: "success" | "error" | "info";+ } | null>(null);++ const showToast = (+ message: string,+ type: "success" | "error" | "info" = "info",+ ) => {+ setToast({ message, type });+ setTimeout(() => setToast(null), 3000);+ };+// Use ref only for WebSocket connections (no need for state as it's not used in render)const wsConnectionsRef = useRef<Record<string, WebSocket>>({});const kbsNamesRef = useRef<string[]>([]);@@ -393,7 +410,7 @@ export default function KnowledgePage() {fetchKnowledgeBases();} catch (err) {console.error(err);- alert("Failed to delete knowledge base");+ showToast("Failed to delete knowledge base", "error");}};@@ -462,10 +479,10 @@ export default function KnowledgePage() {setFiles(null);// Refresh immediately to establish WebSocket connectionawait fetchKnowledgeBases();- alert("Files uploaded successfully! Processing started in background.");+ showToast("Files uploaded successfully! Processing started in background.", "success");} catch (err) {console.error(err);- alert("Failed to upload files");+ showToast("Failed to upload files", "error");} finally {setUploading(false);}@@ -538,12 +555,11 @@ export default function KnowledgePage() {await fetchKnowledgeBases();}, 1000);- alert(- "Knowledge base created successfully! Initialization started in background.",- );++ showToast("Knowledge base created successfully!", "success");} catch (err: any) {console.error(err);- alert(`Failed to create knowledge base: ${err.message}`);+ showToast(`Failed to create knowledge base: ${err.message}`, "error");} finally {setUploading(false);}@@ -879,11 +895,10 @@ 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 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"+ }`}onDragEnter={handleDrag}onDragLeave={handleDrag}onDragOver={handleDrag}diff --git a/web/components/knowledge/FolderSyncManager.tsx b/web/components/knowledge/FolderSyncManager.tsxnew file mode 100644index 000000000..0b28eb762--- /dev/null+++ b/web/components/knowledge/FolderSyncManager.tsx@@ -0,0 +1,167 @@+"use client";++import { useState } from "react";+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;+}++interface FolderInfo {+ id: string;+ path: string;+ added_at: string;+ file_count: number;+}++export default function FolderSyncManager({+ kbName,+ showToast,+ onFolderLinked,+ onFolderUnlinked,+ onSyncComplete+}: FolderSyncManagerProps) {+ 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;++ 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");++ 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>++ {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>++ <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-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>+ )}+ </>+ );+}