LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: folder import + persistent ingest queue
nash_suad7aaca411be
diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex 9f40cf61..e1614ab6 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -730,6 +730,57 @@ pub fn copy_file(source: String, destination: String) -> Result<(), String> {Ok(())}+/// Recursively copy a directory, preserving structure.+/// Returns list of copied file paths (destination paths).+#[tauri::command]+pub fn copy_directory(source: String, destination: String) -> Result<Vec<String>, String> {+ let src = Path::new(&source);+ let dest = Path::new(&destination);++ if !src.is_dir() {+ return Err(format!("'{}' is not a directory", source));+ }++ let mut copied_files = Vec::new();++ fn copy_recursive(+ src: &Path,+ dest: &Path,+ files: &mut Vec<String>,+ ) -> Result<(), String> {+ fs::create_dir_all(dest)+ .map_err(|e| format!("Failed to create dir '{}': {}", dest.display(), e))?;++ let entries = fs::read_dir(src)+ .map_err(|e| format!("Failed to read dir '{}': {}", src.display(), e))?;++ for entry in entries {+ let entry = entry.map_err(|e| format!("Dir entry error: {}", e))?;+ let path = entry.path();+ let name = entry.file_name();+ let dest_path = dest.join(&name);++ // Skip hidden files/dirs+ if name.to_string_lossy().starts_with('.') {+ continue;+ }++ if path.is_dir() {+ copy_recursive(&path, &dest_path, files)?;+ } else {+ fs::copy(&path, &dest_path).map_err(|e| {+ format!("Failed to copy '{}': {}", path.display(), e)+ })?;+ files.push(dest_path.to_string_lossy().to_string());+ }+ }+ Ok(())+ }++ copy_recursive(src, dest, &mut copied_files)?;+ Ok(copied_files)+}+#[tauri::command]pub fn delete_file(path: String) -> Result<(), String> {let p = Path::new(&path);diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 35740176..83a63e5c 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -17,6 +17,7 @@ pub fn run() {commands::fs::write_file,commands::fs::list_directory,commands::fs::copy_file,+ commands::fs::copy_directory,commands::fs::preprocess_file,commands::fs::delete_file,commands::fs::find_related_wiki_pages,diff --git a/src/App.tsx b/src/App.tsxindex eb97bfaa..0ea0fcfb 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -72,6 +72,13 @@ function App() {setSelectedFile(null)setActiveView("wiki")await saveLastProject(proj)++ // Restore ingest queue (resume interrupted tasks)+ import("@/lib/ingest-queue").then(({ restoreQueue }) => {+ restoreQueue(proj.path).catch((err) =>+ console.error("Failed to restore ingest queue:", err)+ )+ })// Notify local clip server of the current project + all recent projectsfetch("http://127.0.0.1:19827/project", {method: "POST",diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsxindex 176c492d..6adde56b 100644--- a/src/components/sources/sources-view.tsx+++ b/src/components/sources/sources-view.tsx@@ -1,12 +1,14 @@import { useState, useEffect, useCallback } from "react"import { open } from "@tauri-apps/plugin-dialog"-import { Plus, FileText, RefreshCw, BookOpen, Trash2 } from "lucide-react"+import { invoke } from "@tauri-apps/api/core"+import { Plus, FileText, RefreshCw, BookOpen, Trash2, FolderOpen } from "lucide-react"import { Button } from "@/components/ui/button"import { ScrollArea } from "@/components/ui/scroll-area"import { useWikiStore } from "@/stores/wiki-store"import { copyFile, listDirectory, readFile, writeFile, deleteFile, findRelatedWikiPages, preprocessFile } from "@/commands/fs"import type { FileNode } from "@/types/wiki"import { startIngest, autoIngest } from "@/lib/ingest"+import { enqueueIngest, enqueueBatch } from "@/lib/ingest-queue"import { useTranslation } from "react-i18next"import { normalizePath, getFileName } from "@/lib/path-utils"@@ -102,17 +104,79 @@ export function SourcesView() {setImporting(false)await loadSources()- // Auto-ingest each imported file (runs in background, progress shown in activity panel)- if (llmConfig.apiKey || llmConfig.provider === "ollama") {+ // Enqueue for serial ingest (runs in background via ingest queue)+ if (llmConfig.apiKey || llmConfig.provider === "ollama" || llmConfig.provider === "custom") {for (const destPath of importedPaths) {- const name = getFileName(destPath)- autoIngest(pp, destPath, llmConfig).catch((err) =>- console.error(`Failed to auto-ingest ${name}:`, err)+ enqueueIngest(pp, destPath).catch((err) =>+ console.error(`Failed to enqueue ingest:`, err))}}}+ async function handleImportFolder() {+ if (!project) return++ const selected = await open({+ directory: true,+ title: "Import Source Folder",+ })++ if (!selected || typeof selected !== "string") return++ setImporting(true)+ const pp = normalizePath(project.path)+ const folderName = getFileName(selected) || "imported"+ const destDir = `${pp}/raw/sources/${folderName}`++ try {+ // Recursively copy the folder+ const copiedFiles: string[] = await invoke("copy_directory", {+ source: selected,+ destination: destDir,+ })++ console.log(`[Folder Import] Copied ${copiedFiles.length} files from ${folderName}`)++ // Preprocess all files+ for (const filePath of copiedFiles) {+ preprocessFile(filePath).catch(() => {})+ }++ setImporting(false)+ await loadSources()++ // Build ingest tasks with folder context+ if (llmConfig.apiKey || llmConfig.provider === "ollama" || llmConfig.provider === "custom") {+ const tasks = copiedFiles+ .filter((fp) => {+ const ext = fp.split(".").pop()?.toLowerCase() ?? ""+ // Only ingest text-based files, skip images/media+ return ["md", "mdx", "txt", "pdf", "docx", "pptx", "xlsx", "xls",+ "csv", "json", "html", "htm", "rtf", "xml", "yaml", "yml"].includes(ext)+ })+ .map((filePath) => {+ // Build folder context from relative path+ const relPath = filePath.replace(destDir + "/", "")+ const parts = relPath.split("/")+ parts.pop() // remove filename+ const context = parts.length > 0+ ? `${folderName} > ${parts.join(" > ")}`+ : folderName+ return { sourcePath: filePath, folderContext: context }+ })++ if (tasks.length > 0) {+ await enqueueBatch(pp, tasks)+ console.log(`[Folder Import] Enqueued ${tasks.length} files for ingest`)+ }+ }+ } catch (err) {+ console.error(`Failed to import folder:`, err)+ setImporting(false)+ }+ }+async function handleOpenSource(node: FileNode) {setActiveView("wiki")setSelectedFile(node.path)@@ -286,6 +350,10 @@ export function SourcesView() {<Plus className="mr-1 h-4 w-4" />{importing ? t("sources.importing") : t("sources.import")}</Button>+ <Button size="sm" variant="outline" onClick={handleImportFolder} disabled={importing}>+ <FolderOpen className="mr-1 h-4 w-4" />+ Folder+ </Button></div></div>@@ -294,10 +362,16 @@ export function SourcesView() {<div className="flex flex-col items-center justify-center gap-3 p-8 text-center text-sm text-muted-foreground"><p>{t("sources.noSources")}</p><p>{t("sources.importHint")}</p>- <Button variant="outline" size="sm" onClick={handleImport}>- <Plus className="mr-1 h-4 w-4" />- {t("sources.importFiles")}- </Button>+ <div className="flex gap-2">+ <Button variant="outline" size="sm" onClick={handleImport}>+ <Plus className="mr-1 h-4 w-4" />+ {t("sources.importFiles")}+ </Button>+ <Button variant="outline" size="sm" onClick={handleImportFolder}>+ <FolderOpen className="mr-1 h-4 w-4" />+ Folder+ </Button>+ </div></div>) : (<div className="p-2">diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.tsnew file mode 100644index 00000000..3b2ccc22--- /dev/null+++ b/src/lib/ingest-queue.ts@@ -0,0 +1,259 @@+import { readFile, writeFile } from "@/commands/fs"+import { autoIngest } from "./ingest"+import { useWikiStore } from "@/stores/wiki-store"+import { useActivityStore } from "@/stores/activity-store"+import { normalizePath } from "@/lib/path-utils"++// ── Types ─────────────────────────────────────────────────────────────────++export interface IngestTask {+ id: string+ sourcePath: string // relative to project: "raw/sources/folder/file.pdf"+ folderContext: string // e.g. "AI-Research > papers" or ""+ status: "pending" | "processing" | "done" | "failed"+ addedAt: number+ error: string | null+ retryCount: number+}++// ── State ─────────────────────────────────────────────────────────────────++let queue: IngestTask[] = []+let processing = false+let currentProjectPath = ""++// ── Persistence ───────────────────────────────────────────────────────────++function queueFilePath(projectPath: string): string {+ return `${normalizePath(projectPath)}/.llm-wiki/ingest-queue.json`+}++async function saveQueue(projectPath: string): Promise<void> {+ try {+ // Only save pending and failed tasks (done tasks are removed)+ const toSave = queue.filter((t) => t.status !== "done")+ await writeFile(queueFilePath(projectPath), JSON.stringify(toSave, null, 2))+ } catch {+ // non-critical+ }+}++async function loadQueue(projectPath: string): Promise<IngestTask[]> {+ try {+ const raw = await readFile(queueFilePath(projectPath))+ return JSON.parse(raw) as IngestTask[]+ } catch {+ return []+ }+}++// ── Queue Operations ──────────────────────────────────────────────────────++function generateId(): string {+ return `ingest-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`+}++/**+ * Add a file to the ingest queue.+ */+export async function enqueueIngest(+ projectPath: string,+ sourcePath: string,+ folderContext: string = "",+): Promise<string> {+ const pp = normalizePath(projectPath)+ currentProjectPath = pp++ const task: IngestTask = {+ id: generateId(),+ sourcePath,+ folderContext,+ status: "pending",+ addedAt: Date.now(),+ error: null,+ retryCount: 0,+ }++ queue.push(task)+ await saveQueue(pp)++ // Start processing if not already running+ processNext(pp)++ return task.id+}++/**+ * Add multiple files to the queue at once.+ */+export async function enqueueBatch(+ projectPath: string,+ files: Array<{ sourcePath: string; folderContext: string }>,+): Promise<string[]> {+ const pp = normalizePath(projectPath)+ currentProjectPath = pp+ const ids: string[] = []++ for (const file of files) {+ const task: IngestTask = {+ id: generateId(),+ sourcePath: file.sourcePath,+ folderContext: file.folderContext,+ status: "pending",+ addedAt: Date.now(),+ error: null,+ retryCount: 0,+ }+ queue.push(task)+ ids.push(task.id)+ }++ await saveQueue(pp)+ console.log(`[Ingest Queue] Enqueued ${files.length} files`)+ processNext(pp)++ return ids+}++/**+ * Retry a failed task.+ */+export async function retryTask(projectPath: string, taskId: string): Promise<void> {+ const task = queue.find((t) => t.id === taskId)+ if (!task) return++ task.status = "pending"+ task.error = null+ await saveQueue(projectPath)+ processNext(normalizePath(projectPath))+}++/**+ * Cancel a pending task.+ */+export async function cancelTask(projectPath: string, taskId: string): Promise<void> {+ queue = queue.filter((t) => t.id !== taskId)+ await saveQueue(projectPath)+}++/**+ * Clear all done/failed tasks from the queue.+ */+export async function clearCompletedTasks(projectPath: string): Promise<void> {+ queue = queue.filter((t) => t.status === "pending" || t.status === "processing")+ await saveQueue(projectPath)+}++/**+ * Get current queue state.+ */+export function getQueue(): readonly IngestTask[] {+ return queue+}++/**+ * Get queue summary.+ */+export function getQueueSummary(): { pending: number; processing: number; failed: number; total: number } {+ return {+ pending: queue.filter((t) => t.status === "pending").length,+ processing: queue.filter((t) => t.status === "processing").length,+ failed: queue.filter((t) => t.status === "failed").length,+ total: queue.length,+ }+}++// ── Restore on startup ───────────────────────────────────────────────────++/**+ * Load queue from disk and resume processing.+ * Called on app startup.+ */+export async function restoreQueue(projectPath: string): Promise<void> {+ const pp = normalizePath(projectPath)+ currentProjectPath = pp+ const saved = await loadQueue(pp)++ if (saved.length === 0) return++ // Reset any "processing" tasks back to "pending" (interrupted by app close)+ let restored = 0+ for (const task of saved) {+ if (task.status === "processing") {+ task.status = "pending"+ restored+++ }+ }++ queue = saved+ await saveQueue(pp)++ const pending = queue.filter((t) => t.status === "pending").length+ const failed = queue.filter((t) => t.status === "failed").length++ if (pending > 0 || restored > 0) {+ console.log(`[Ingest Queue] Restored: ${pending} pending, ${failed} failed, ${restored} resumed from interrupted`)+ processNext(pp)+ }+}++// ── Processing ────────────────────────────────────────────────────────────++const MAX_RETRIES = 3++async function processNext(projectPath: string): Promise<void> {+ if (processing) return++ const next = queue.find((t) => t.status === "pending")+ if (!next) return++ processing = true+ next.status = "processing"+ await saveQueue(projectPath)++ const pp = normalizePath(projectPath)+ const llmConfig = useWikiStore.getState().llmConfig++ // Check if LLM is configured+ if (!llmConfig.apiKey && llmConfig.provider !== "ollama" && llmConfig.provider !== "custom") {+ next.status = "failed"+ next.error = "LLM not configured — set API key in Settings"+ processing = false+ await saveQueue(pp)+ processNext(pp)+ return+ }++ const fullSourcePath = next.sourcePath.startsWith("/")+ ? next.sourcePath+ : `${pp}/${next.sourcePath}`++ console.log(`[Ingest Queue] Processing: ${next.sourcePath} (${queue.filter((t) => t.status === "pending").length} remaining)`)++ try {+ await autoIngest(pp, fullSourcePath, llmConfig, undefined, next.folderContext)++ // Success: remove from queue+ queue = queue.filter((t) => t.id !== next.id)+ await saveQueue(pp)++ console.log(`[Ingest Queue] Done: ${next.sourcePath}`)+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err)+ next.retryCount+++ next.error = message++ if (next.retryCount >= MAX_RETRIES) {+ next.status = "failed"+ console.log(`[Ingest Queue] Failed (${next.retryCount}x): ${next.sourcePath} — ${message}`)+ } else {+ next.status = "pending" // will retry+ console.log(`[Ingest Queue] Error (retry ${next.retryCount}/${MAX_RETRIES}): ${next.sourcePath} — ${message}`)+ }++ await saveQueue(pp)+ }++ processing = false+ processNext(pp)+}diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 64cf0569..4d5a08f7 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -21,6 +21,7 @@ export async function autoIngest(sourcePath: string,llmConfig: LlmConfig,signal?: AbortSignal,+ folderContext?: string,): Promise<string[]> {const pp = normalizePath(projectPath)const sp = normalizePath(sourcePath)@@ -68,7 +69,7 @@ export async function autoIngest(llmConfig,[{ role: "system", content: buildAnalysisPrompt(purpose, index) },- { role: "user", content: `Analyze this source document:\n\n**File:** ${fileName}\n\n---\n\n${truncatedContent}` },+ { role: "user", content: `Analyze this source document:\n\n**File:** ${fileName}${folderContext ? `\n**Folder context:** ${folderContext}` : ""}\n\n---\n\n${truncatedContent}` },],{onToken: (token) => { analysis += token },@@ -351,6 +352,8 @@ function buildAnalysisPrompt(purpose: string, index: string): string {"","Be thorough but concise. Focus on what's genuinely important.","",+ "If a folder context is provided, use it as a hint for categorization — the folder structure often reflects the user's organizational intent (e.g., 'papers/energy' suggests the file is an energy-related paper).",+ "",purpose ? `## Wiki Purpose (for context)\n${purpose}` : "",index ? `## Current Wiki Index (for checking existing content)\n${index}` : "",].filter(Boolean).join("\n")