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

Process source watch startup changes

sunilkumarvalmiki7707c731eb1f
diff --git a/src-tauri/src/commands/file_sync.rs b/src-tauri/src/commands/file_sync.rs
index 260559e5..6bc8ce6a 100644
--- a/src-tauri/src/commands/file_sync.rs
+++ b/src-tauri/src/commands/file_sync.rs
@@ -193,7 +193,7 @@ pub fn start_project_file_watcher(
project_id: String,
project_path: String,
source_watch_config: Option<SourceWatchConfig>,
-) -> Result<FileChangeQueue, String> {
+) -> Result<FileChangeRescanResult, String> {
run_guarded("start_project_file_watcher", || {
let root = PathBuf::from(project_path);
let source_watch_config = normalize_source_watch_config(source_watch_config);
@@ -201,7 +201,7 @@ pub fn start_project_file_watcher(
ensure_sync_dir(&root)?;
with_queue_lock(&root, || reset_processing_tasks(&root, &project_id))?;
enqueue_rescan_changes(&root, &project_id, &source_watch_config)?;
- process_queue(&app, &root, &project_id)?;
+ let changed_tasks = process_queue(&app, &root, &project_id)?;
let (tx, rx) = mpsc::sync_channel::<PathBuf>(8_192);
let app_for_thread = app.clone();
@@ -307,7 +307,10 @@ pub fn start_project_file_watcher(
let queue = with_queue_lock(&root, || read_queue(&root))?;
emit_queue(&app, &project_id, &queue);
- Ok(queue)
+ Ok(FileChangeRescanResult {
+ queue,
+ changed_tasks,
+ })
})
}
diff --git a/src/commands/file-sync.ts b/src/commands/file-sync.ts
index 05822491..205be6ce 100644
--- a/src/commands/file-sync.ts
+++ b/src/commands/file-sync.ts
@@ -41,8 +41,8 @@ export function startProjectFileWatcher(
projectId: string,
projectPath: string,
sourceWatchConfig?: SourceWatchConfig,
-): Promise<FileChangeQueue> {
- return invoke<FileChangeQueue>("start_project_file_watcher", {
+): Promise<FileChangeRescanResult> {
+ return invoke<FileChangeRescanResult>("start_project_file_watcher", {
projectId,
projectPath,
sourceWatchConfig: normalizeSourceWatchConfig(sourceWatchConfig),
diff --git a/src/lib/project-file-sync.test.ts b/src/lib/project-file-sync.test.ts
index 9ef51492..7348babc 100644
--- a/src/lib/project-file-sync.test.ts
+++ b/src/lib/project-file-sync.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
const mocks = vi.hoisted(() => {
- const resolvers: Array<(value: { version: number; tasks: Array<{ id: string; projectId: string; path: string; kind: "modified"; status: "pending"; createdAt: number; updatedAt: number; retryCount: number; needsRerun: boolean }> }) => void> = []
+ const resolvers: Array<(value: { queue: { version: number; tasks: Array<{ id: string; projectId: string; path: string; kind: "modified"; status: "pending"; createdAt: number; updatedAt: number; retryCount: number; needsRerun: boolean }> }; changedTasks: Array<{ id: string; projectId: string; path: string; kind: "modified"; status: "pending"; createdAt: number; updatedAt: number; retryCount: number; needsRerun: boolean }> }) => void> = []
const listeners: Record<string, (event: { payload: unknown }) => void> = {}
return {
listen: vi.fn(async (event: string, cb: (event: { payload: unknown }) => void) => {
@@ -52,18 +52,21 @@ const mocks = vi.hoisted(() => {
resolvers.push(resolve)
})),
resolveStart: (index: number, projectId: string) => resolvers[index]?.({
- version: 1,
- tasks: [{
- id: "t1",
- projectId,
- path: "raw/sources/a.md",
- kind: "modified",
- status: "pending",
- createdAt: 1,
- updatedAt: 1,
- retryCount: 0,
- needsRerun: false,
- }],
+ queue: {
+ version: 1,
+ tasks: [{
+ id: "t1",
+ projectId,
+ path: "raw/sources/a.md",
+ kind: "modified",
+ status: "pending",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ }],
+ },
+ changedTasks: [],
}),
clearResolvers: () => {
resolvers.length = 0
@@ -319,6 +322,54 @@ describe("project file sync", () => {
])
})
+ it("enqueues existing XML when source watch restarts with xml newly allowed", async () => {
+ const { startProjectFileSync } = await import("@/lib/project-file-sync")
+ const { useWikiStore } = await import("@/stores/wiki-store")
+
+ const project = { id: "A", name: "A", path: "/tmp/a" }
+ useWikiStore.getState().setProject(project)
+ mocks.startProjectFileWatcher.mockImplementationOnce(async () => ({
+ queue: {
+ version: 1,
+ tasks: [],
+ },
+ changedTasks: [
+ {
+ id: "t1",
+ projectId: "A",
+ path: "raw/sources/existing.xml",
+ kind: "created",
+ status: "done",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ },
+ ],
+ }) as never)
+
+ await startProjectFileSync(project, {
+ enabled: true,
+ autoIngest: true,
+ includeExtensions: ["md", "xml"],
+ excludeExtensions: [],
+ excludeDirs: [],
+ excludeGlobs: [],
+ maxFileSizeMb: 100,
+ })
+
+ expect(mocks.startProjectFileWatcher).toHaveBeenCalledWith(
+ "A",
+ "/tmp/a",
+ expect.objectContaining({
+ includeExtensions: expect.arrayContaining(["xml"]),
+ }),
+ )
+ expect(mocks.enqueueBatch).toHaveBeenCalledWith("A", [
+ { sourcePath: "raw/sources/existing.xml", folderContext: "" },
+ ])
+ })
+
it("manual rescan uses returned changed tasks while the watcher is running", async () => {
const { startProjectFileSync, rescanProjectFileSync } = await import("@/lib/project-file-sync")
const { useWikiStore } = await import("@/stores/wiki-store")
diff --git a/src/lib/project-file-sync.ts b/src/lib/project-file-sync.ts
index a31b2848..cfd25ee8 100644
--- a/src/lib/project-file-sync.ts
+++ b/src/lib/project-file-sync.ts
@@ -27,6 +27,7 @@ let refreshTimer: ReturnType<typeof setTimeout> | null = null
let pendingRefreshPaths = new Set<string>()
let pendingChangeTasks = new Map<string, FileChangeTask>()
let activeSourceWatchConfig = normalizeSourceWatchConfig()
+let handledChangeTaskKeys = new Set<string>()
export async function startProjectFileSync(
project: WikiProject,
@@ -50,9 +51,24 @@ export async function startProjectFileSync(
})
try {
- const queue = await startProjectFileWatcher(project.id, normalizePath(project.path), activeSourceWatchConfig)
+ const result = await startProjectFileWatcher(project.id, normalizePath(project.path), activeSourceWatchConfig)
if (seq !== startSeq || project.id !== useWikiStore.getState().project?.id) return
- useFileSyncStore.getState().setTasks(queue.tasks)
+ const startupChangedTasks = mergeChangeTasks([
+ ...result.changedTasks,
+ ...pendingChangeTasks.values(),
+ ].filter((task) => task.projectId === project.id))
+ .filter((task) => !handledChangeTaskKeys.has(changeTaskKey(task)))
+ pendingRefreshPaths.clear()
+ pendingChangeTasks.clear()
+ if (refreshTimer) {
+ clearTimeout(refreshTimer)
+ refreshTimer = null
+ }
+ useFileSyncStore.getState().setTasks(result.queue.tasks)
+ if (startupChangedTasks.length > 0) {
+ const paths = [...new Set(startupChangedTasks.map((task) => task.path))]
+ await processFileChangeBatch(project, paths, startupChangedTasks)
+ }
} catch (err) {
unlistenQueue?.()
unlistenChanged?.()
@@ -79,6 +95,7 @@ export async function stopProjectFileSync(): Promise<void> {
}
pendingRefreshPaths.clear()
pendingChangeTasks.clear()
+ handledChangeTaskKeys.clear()
useFileSyncStore.getState().clear()
try {
await stopProjectFileWatcher()
@@ -122,19 +139,37 @@ function scheduleRefreshAfterFileChanges(tasks: FileChangeTask[]): void {
pendingChangeTasks.clear()
return
}
- const paths = [...pendingRefreshPaths]
- const tasks = [...pendingChangeTasks.values()]
+ const tasks = mergeChangeTasks([...pendingChangeTasks.values()])
+ .filter((task) => !handledChangeTaskKeys.has(changeTaskKey(task)))
+ const paths = tasks.length > 0
+ ? [...new Set(tasks.map((task) => task.path))]
+ : [...pendingRefreshPaths]
pendingRefreshPaths.clear()
pendingChangeTasks.clear()
void processFileChangeBatch(project, paths, tasks)
}, 250)
}
+function mergeChangeTasks(tasks: FileChangeTask[]): FileChangeTask[] {
+ const byKey = new Map<string, FileChangeTask>()
+ for (const task of tasks) {
+ byKey.set(changeTaskKey(task), task)
+ }
+ return [...byKey.values()]
+}
+
+function changeTaskKey(task: FileChangeTask): string {
+ return task.id || `${task.projectId}:${task.path}:${task.kind}`
+}
+
async function processFileChangeBatch(
project: WikiProject,
paths: string[],
tasks: FileChangeTask[],
): Promise<void> {
+ for (const task of tasks) {
+ handledChangeTaskKeys.add(changeTaskKey(task))
+ }
await cleanupDeletedFiles(project, tasks)
await enqueueRawSourceChanges(project, tasks)
await refreshAfterFileChanges(project, paths)