Skip to content

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

fix: reduce background scan and queue overhead

nash_su1e1186f621a8
diff --git a/src-tauri/src/commands/file_sync.rs b/src-tauri/src/commands/file_sync.rs
index 0befe1a6..998b5f5f 100644
--- a/src-tauri/src/commands/file_sync.rs
+++ b/src-tauri/src/commands/file_sync.rs
@@ -9,6 +9,7 @@ use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use md5::{Digest, Md5};
+use notify::event::{AccessKind, AccessMode, EventKind};
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, State};
@@ -273,6 +274,9 @@ pub fn start_project_file_watcher(
let mut watcher = RecommendedWatcher::new(
move |res: notify::Result<Event>| match res {
Ok(event) => {
+ if !is_content_change_event(&event.kind) {
+ return;
+ }
for path in event.paths {
if tx_for_watcher.try_send(path).is_err() {
let _ = tx_for_watcher.try_send(root_for_overflow.clone());
@@ -1443,6 +1447,22 @@ fn normalize_path_key(path: &Path) -> String {
normalize_key(&path.to_string_lossy().replace('\\', "/"))
}
+/// Whether a watcher event can mean the file *content* changed.
+///
+/// On Linux the inotify backend of `notify` also reports read-only activity
+/// (`IN_OPEN`, `IN_CLOSE_NOWRITE`, `IN_ACCESS`). Handling a change re-reads
+/// files (`md5_file`), which emits new read events, which schedule another pass:
+/// a self-sustaining loop that keeps a CPU core busy even when nothing on disk
+/// changes. Only a finished write (`IN_CLOSE_WRITE`) is an access-type event
+/// that matters; every non-access kind (create / modify / remove / rename / ...)
+/// is still forwarded.
+fn is_content_change_event(kind: &EventKind) -> bool {
+ match kind {
+ EventKind::Access(access) => matches!(access, AccessKind::Close(AccessMode::Write)),
+ _ => true,
+ }
+}
+
fn is_app_write_ignored(path: &Path) -> bool {
let key = path_key(path);
let now = now_ms();
@@ -1459,6 +1479,37 @@ fn is_app_write_ignored(path: &Path) -> bool {
#[cfg(test)]
mod tests {
use super::*;
+ use notify::event::{CreateKind, ModifyKind, RemoveKind, RenameMode};
+
+ #[test]
+ fn read_only_access_events_do_not_count_as_content_changes() {
+ assert!(!is_content_change_event(&EventKind::Access(AccessKind::Open(
+ AccessMode::Any
+ ))));
+ assert!(!is_content_change_event(&EventKind::Access(AccessKind::Open(
+ AccessMode::Read
+ ))));
+ assert!(!is_content_change_event(&EventKind::Access(AccessKind::Read)));
+ assert!(!is_content_change_event(&EventKind::Access(AccessKind::Close(
+ AccessMode::Read
+ ))));
+ assert!(!is_content_change_event(&EventKind::Access(AccessKind::Any)));
+ }
+
+ #[test]
+ fn finished_writes_and_non_access_events_still_count() {
+ assert!(is_content_change_event(&EventKind::Access(AccessKind::Close(
+ AccessMode::Write
+ ))));
+ assert!(is_content_change_event(&EventKind::Create(CreateKind::File)));
+ assert!(is_content_change_event(&EventKind::Modify(ModifyKind::Any)));
+ assert!(is_content_change_event(&EventKind::Modify(ModifyKind::Name(
+ RenameMode::To
+ ))));
+ assert!(is_content_change_event(&EventKind::Remove(RemoveKind::File)));
+ assert!(is_content_change_event(&EventKind::Any));
+ assert!(is_content_change_event(&EventKind::Other));
+ }
fn temp_root(name: &str) -> PathBuf {
let stamp = std::time::SystemTime::now()
diff --git a/src/components/layout/activity-panel.tsx b/src/components/layout/activity-panel.tsx
index a6398239..f93686e3 100644
--- a/src/components/layout/activity-panel.tsx
+++ b/src/components/layout/activity-panel.tsx
@@ -27,6 +27,7 @@ import {
movePendingTask,
pauseProcessing,
resumeProcessing,
+ subscribeIngestQueue,
type IngestTask,
} from "@/lib/ingest-queue"
import {
@@ -98,12 +99,10 @@ export function ActivityPanel() {
const runningCount = items.filter((i) => i.status === "running").length
const hasItems = items.length > 0
- // Poll queue state
+ // Queue changes are pushed by the queue module. Avoid cloning and rendering
+ // the entire queue every second while large imports are idle.
useEffect(() => {
- const interval = setInterval(() => {
- setQueueTasks([...getQueue()])
- }, 1000)
- return () => clearInterval(interval)
+ return subscribeIngestQueue((tasks) => setQueueTasks([...tasks]))
}, [])
useEffect(() => {
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 45e5b5b1..7c98afb5 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -28,7 +28,7 @@ import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { importSourceUrls, parseImportUrls, type UrlImportResult } from "@/lib/url-source-import"
import { listIngestedSourceIdentities } from "@/lib/ingest-cache"
-import { getQueue, type IngestTask } from "@/lib/ingest-queue"
+import { getQueue, subscribeIngestQueue, type IngestTask } from "@/lib/ingest-queue"
const SOURCE_TREE_INITIAL_ROWS = 160
const SOURCE_TREE_LOAD_BATCH = 160
@@ -122,10 +122,7 @@ export function SourcesView() {
}, [project, dataVersion])
useEffect(() => {
- const refresh = () => setQueueSnapshot([...getQueue()])
- refresh()
- const interval = setInterval(refresh, 1000)
- return () => clearInterval(interval)
+ return subscribeIngestQueue((tasks) => setQueueSnapshot([...tasks]))
}, [project])
const sourceStatuses = useMemo(() => {
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index 3859fff6..51a401c2 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -75,6 +75,7 @@ import {
isQueuePaused,
setIngestWorkerLimit,
getIngestWorkerLimit,
+ subscribeIngestQueue,
} from "./ingest-queue"
import { autoIngest } from "./ingest"
import { deleteFile, readFile, writeFile } from "@/commands/fs"
@@ -128,6 +129,35 @@ beforeEach(async () => {
})
describe("ingest-queue — enqueue & basic processing", () => {
+ it("pushes queue snapshots only while a subscriber is active", async () => {
+ const run = createDeferred<string[]>()
+ mockAutoIngest.mockReturnValue(run.promise)
+ const snapshots: string[][] = []
+ const unsubscribe = subscribeIngestQueue((tasks) => {
+ snapshots.push(tasks.map((task) => task.sourcePath))
+ })
+
+ await enqueueIngest(TEST_ID, "raw/sources/report.pdf")
+ expect(snapshots.some((paths) => paths.includes("raw/sources/report.pdf"))).toBe(true)
+
+ const countBeforeUnsubscribe = snapshots.length
+ unsubscribe()
+ clearQueueState()
+ expect(snapshots).toHaveLength(countBeforeUnsubscribe)
+ run.resolve([])
+ })
+
+ it("does not let a queue subscriber failure block persistence", async () => {
+ mockAutoIngest.mockReturnValue(new Promise(() => {}))
+ const unsubscribe = subscribeIngestQueue(() => {
+ throw new Error("subscriber failed")
+ })
+
+ await expect(enqueueIngest(TEST_ID, "raw/sources/report.pdf")).resolves.toBeTypeOf("string")
+ expect(mockWriteFile).toHaveBeenCalled()
+ unsubscribe()
+ })
+
it("clamps the configurable worker limit", () => {
setIngestWorkerLimit(0)
expect(getIngestWorkerLimit()).toBe(1)
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index 232aaab3..5f6b8601 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -26,6 +26,29 @@ export interface IngestTask {
// ── State ─────────────────────────────────────────────────────────────────
let queue: IngestTask[] = []
+type QueueListener = (tasks: readonly IngestTask[]) => void
+const queueListeners = new Set<QueueListener>()
+
+function notifyQueueListeners(): void {
+ const snapshot = queue.map((task) => ({ ...task }))
+ for (const listener of queueListeners) {
+ try {
+ listener(snapshot)
+ } catch (err) {
+ console.warn("[Ingest Queue] Queue subscriber failed:", err)
+ }
+ }
+}
+
+export function subscribeIngestQueue(listener: QueueListener): () => void {
+ queueListeners.add(listener)
+ try {
+ listener(queue.map((task) => ({ ...task })))
+ } catch (err) {
+ console.warn("[Ingest Queue] Queue subscriber failed:", err)
+ }
+ return () => queueListeners.delete(listener)
+}
interface ActiveIngestRun {
taskId: string
epoch: number
@@ -103,6 +126,7 @@ async function saveQueue(projectPath: string): Promise<void> {
// Capture the snapshot now, then serialize writes so an older async write
// can never land after a newer queue state.
const toSave = queue.filter((t) => t.status !== "done")
+ notifyQueueListeners()
const snapshot = JSON.stringify(toSave, null, 2)
await new Promise<void>((resolve) => {
pendingActiveQueueWrites.push({
@@ -848,6 +872,7 @@ export function clearQueueState(): void {
for (const request of pendingActiveQueueWrites.splice(0)) request.resolve()
commitCoordinator = new IngestCommitCoordinator()
workerLimit = 1
+ notifyQueueListeners()
}
/**
@@ -914,6 +939,7 @@ export async function pauseQueue(): Promise<void> {
currentProjectPath = ""
processedSinceDrain = false
resetQueueAccounting()
+ notifyQueueListeners()
}
// ── Restore on startup ───────────────────────────────────────────────────
@@ -951,7 +977,10 @@ export async function restoreQueue(
const saved = await loadQueue(pp, projectId)
- if (saved.length === 0) return
+ if (saved.length === 0) {
+ notifyQueueListeners()
+ return
+ }
// Drop any cross-project contamination (shouldn't happen in practice
// but defends against a corrupt queue file).
diff --git a/src/lib/scheduled-import.test.ts b/src/lib/scheduled-import.test.ts
index 88ad2fdf..01381c3f 100644
--- a/src/lib/scheduled-import.test.ts
+++ b/src/lib/scheduled-import.test.ts
@@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({
copyFile: vi.fn(),
fileExists: vi.fn(),
getFileMd5: vi.fn(),
+ getFileModifiedTime: vi.fn(),
getFileSize: vi.fn(),
listDirectory: vi.fn(),
preprocessFile: vi.fn(),
@@ -26,6 +27,7 @@ vi.mock("@/commands/fs", () => ({
copyFile: mocks.copyFile,
fileExists: mocks.fileExists,
getFileMd5: mocks.getFileMd5,
+ getFileModifiedTime: mocks.getFileModifiedTime,
getFileSize: mocks.getFileSize,
listDirectory: mocks.listDirectory,
preprocessFile: mocks.preprocessFile,
@@ -255,6 +257,7 @@ describe("scanAndImport failure handling", () => {
mocks.fileExists.mockResolvedValue(false)
mocks.readFile.mockResolvedValue("")
mocks.getFileSize.mockResolvedValue(1024)
+ mocks.getFileModifiedTime.mockResolvedValue(1111)
mocks.getFileMd5.mockResolvedValue("md5-new")
mocks.copyFile.mockResolvedValue(undefined)
mocks.deleteSourceFile.mockResolvedValue({
@@ -586,3 +589,142 @@ describe("scanAndImport failure handling", () => {
expect(mocks.copyFile).not.toHaveBeenCalled()
})
})
+
+describe("scanAndImport stat-cache fast path", () => {
+ const project: WikiProject = {
+ id: "project-1",
+ name: "Project",
+ path: "/Users/me/wiki-project",
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useWikiStore.setState({
+ project,
+ sourceWatchConfig: {
+ enabled: true,
+ autoIngest: true,
+ persistExtractedMarkdown: true,
+ parsingConcurrency: 2,
+ ingestConcurrency: 2,
+ includeExtensions: [],
+ excludeExtensions: [],
+ excludeDirs: [],
+ excludeGlobs: [],
+ maxFileSizeMb: 100,
+ },
+ llmConfig: {
+ provider: "openai",
+ apiKey: "test-key",
+ model: "gpt-test",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 1000,
+ },
+ })
+ mocks.fileExists.mockResolvedValue(true)
+ mocks.readFile.mockResolvedValue("")
+ mocks.getFileSize.mockResolvedValue(1024)
+ mocks.getFileModifiedTime.mockResolvedValue(1111)
+ mocks.getFileMd5.mockResolvedValue("md5-new")
+ mocks.copyFile.mockResolvedValue(undefined)
+ mocks.deleteSourceFile.mockResolvedValue({
+ deletedWikiPaths: [],
+ rewrittenSourcePages: 0,
+ })
+ mocks.discardTasksForSources.mockResolvedValue(0)
+ mocks.preprocessFile.mockResolvedValue("")
+ mocks.isIngestableSourcePath.mockReturnValue(true)
+ mocks.loadScheduledImportConfig.mockResolvedValue({
+ enabled: true,
+ path: "/Users/me/inbox",
+ interval: 60,
+ lastScan: null,
+ })
+ mocks.loadSourceWatchConfig.mockResolvedValue(
+ useWikiStore.getState().sourceWatchConfig,
+ )
+ mocks.saveScheduledImportConfig.mockResolvedValue(undefined)
+ mocks.enqueueSourceIngest.mockResolvedValue(["task-1"])
+ mocks.enqueueInactiveProjectBatch.mockResolvedValue(["background-task-1"])
+ mocks.folderContextForSourcePath.mockReturnValue("scheduled-import")
+ mocks.writeFileAtomic.mockResolvedValue(undefined)
+ mocks.listDirectory.mockImplementation(async (path: string) => {
+ if (path === "/Users/me/inbox") {
+ return [
+ { name: "paper.pdf", path: "/Users/me/inbox/paper.pdf", is_dir: false },
+ ]
+ }
+ return []
+ })
+ })
+
+ function dbWithStatCache(md5: string, stat: { size: number; mtime: number }) {
+ return JSON.stringify({
+ version: 1,
+ directories: {
+ "/Users/me/inbox": {
+ files: { "/Users/me/inbox/paper.pdf": md5 },
+ statCache: { "/Users/me/inbox/paper.pdf": stat },
+ lastScan: 123,
+ },
+ },
+ })
+ }
+
+ it("reuses the recorded hash when size and mtime are unchanged", async () => {
+ mocks.readFile.mockResolvedValue(dbWithStatCache("stable-md5", { size: 1024, mtime: 1111 }))
+
+ await scanAndImport(project, "/Users/me/inbox")
+
+ expect(mocks.getFileMd5).not.toHaveBeenCalled()
+ expect(mocks.copyFile).not.toHaveBeenCalled()
+ expect(mocks.enqueueSourceIngest).not.toHaveBeenCalled()
+ expect(mocks.writeFileAtomic).toHaveBeenCalledWith(
+ "/Users/me/wiki-project/.llm-wiki/scheduled-import-db.json",
+ expect.stringContaining('"stable-md5"'),
+ )
+ })
+
+ it("re-hashes when the stat changed but keeps the record when content is identical", async () => {
+ mocks.readFile.mockResolvedValue(dbWithStatCache("stable-md5", { size: 1024, mtime: 1111 }))
+ mocks.getFileModifiedTime.mockResolvedValue(2222)
+ mocks.getFileMd5.mockResolvedValue("stable-md5")
+
+ await scanAndImport(project, "/Users/me/inbox")
+
+ expect(mocks.getFileMd5).toHaveBeenCalledTimes(1)
+ expect(mocks.copyFile).not.toHaveBeenCalled()
+ expect(mocks.enqueueSourceIngest).not.toHaveBeenCalled()
+ const calls = mocks.writeFileAtomic.mock.calls
+ const written = String(calls[calls.length - 1]?.[1] ?? "")
+ expect(written).toContain('"stable-md5"')
+ expect(written).toContain('"mtime": 2222')
+ })
+
+ it("hashes and imports files that have no stat cache yet", async () => {
+ mocks.readFile.mockResolvedValue(JSON.stringify({
+ version: 1,
+ directories: {
+ "/Users/me/inbox": {
+ files: { "/Users/me/inbox/paper.pdf": "old-md5" },
+ lastScan: 123,
+ },
+ },
+ }))
+ mocks.getFileMd5.mockResolvedValue("fresh-md5")
+
+ await scanAndImport(project, "/Users/me/inbox")
+
+ expect(mocks.getFileMd5).toHaveBeenCalledTimes(1)
+ expect(mocks.copyFile).toHaveBeenCalledWith(
+ "/Users/me/inbox/paper.pdf",
+ "/Users/me/wiki-project/raw/sources/scheduled-import/paper.pdf",
+ )
+ expect(mocks.enqueueSourceIngest).toHaveBeenCalled()
+ const calls = mocks.writeFileAtomic.mock.calls
+ const written = String(calls[calls.length - 1]?.[1] ?? "")
+ expect(written).toContain('"fresh-md5"')
+ expect(written).toContain('"mtime": 1111')
+ })
+})
diff --git a/src/lib/scheduled-import.ts b/src/lib/scheduled-import.ts
index ca3d766e..3ffd04ae 100644
--- a/src/lib/scheduled-import.ts
+++ b/src/lib/scheduled-import.ts
@@ -2,6 +2,7 @@ import {
copyFile,
fileExists,
getFileMd5,
+ getFileModifiedTime,
getFileSize,
listDirectory,
readFile,
@@ -31,8 +32,20 @@ import { discardTasksForSources, enqueueInactiveProjectBatch } from "@/lib/inges
import { useActivityStore } from "@/stores/activity-store"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
+interface ImportStat {
+ size: number
+ mtime: number
+}
+
interface ImportDb {
files: Record<string, string>
+ /**
+ * Size + mtime (ms) per source path. Lets a scan reuse the recorded content
+ * hash for files that did not change instead of re-reading and re-hashing
+ * every file on every run. Optional and additive: databases written by
+ * older builds simply lack it and fall back to hashing once.
+ */
+ statCache?: Record<string, ImportStat>
lastScan: number | null
}
@@ -54,6 +67,7 @@ type ScanOptions = {
const EMPTY_DB: ImportDb = {
files: {},
+ statCache: {},
lastScan: null,
}
@@ -115,6 +129,7 @@ function caseFoldPath(normalized: string): string {
function cloneDb(db: ImportDb): ImportDb {
return {
files: { ...db.files },
+ statCache: { ...(db.statCache ?? {}) },
lastScan: db.lastScan,
}
}
@@ -385,6 +400,9 @@ async function loadImportDb(
files: Object.fromEntries(
Object.entries(db.files).map(([path, md5]) => [dbDirectoryKey(path), md5]),
),
+ statCache: Object.fromEntries(
+ Object.entries(db.statCache ?? {}).map(([path, stat]) => [dbDirectoryKey(path), stat]),
+ ),
lastScan: db.lastScan,
}
}
@@ -464,6 +482,7 @@ export async function scanAndImport(
const maxFileSizeBytes = sourceWatchConfig.maxFileSizeMb * 1024 * 1024
const db = await loadImportDb(projectPath, importRoot)
const nextDb: ImportDb = { files: {}, lastScan: Date.now() }
+ const nextStatCache: Record<string, ImportStat> = {}
const changedFiles: Array<{ key: string; md5: string; destPath: string }> = []
const observedEligibleKeys = new Set<string>()
@@ -496,7 +515,21 @@ export async function scanAndImport(
observedEligibleKeys.add(key)
+ // Fast path: if size and mtime are unchanged since the last scan,
+ // reuse the recorded hash instead of re-reading and re-hashing the
+ // file. Files whose stat differs, including imports from older
+ // builds that have no cache entry yet, are still verified by content
+ // hash below.
+ const cachedStat = db.statCache?.[key]
+ const mtime = await getFileModifiedTime(sourcePath)
+ if (cachedStat && db.files[key] && cachedStat.size === size && cachedStat.mtime === mtime) {
+ nextDb.files[key] = db.files[key]
+ nextStatCache[key] = cachedStat
+ continue
+ }
+
const md5 = await getFileMd5(sourcePath)
+ nextStatCache[key] = { size, mtime }
if (db.files[key] === md5) {
nextDb.files[key] = md5
@@ -580,6 +613,8 @@ export async function scanAndImport(
})
}
+ nextDb.statCache = nextStatCache
+
await saveImportDb(projectPath, importRoot, nextDb)
const currentConfig = await loadScheduledImportConfig(projectPath)