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: monitor scheduled imports across projects

nash_suda979941b262
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index 43586183..d208e4c3 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -53,6 +53,7 @@ vi.mock("@/lib/project-identity", () => ({
import {
enqueueIngest,
enqueueBatch,
+ enqueueInactiveProjectBatch,
retryTask,
retryTasks,
retryAllFailedTasks,
@@ -116,6 +117,54 @@ beforeEach(async () => {
})
describe("ingest-queue — enqueue & basic processing", () => {
+ it("persists inactive-project tasks and starts them when that project opens", async () => {
+ const ids = await enqueueInactiveProjectBatch(TEST_ID_B, TEST_PATH_B, [
+ {
+ sourcePath: `${TEST_PATH_B}/raw/sources/scheduled-import/report.pdf`,
+ folderContext: "scheduled-import",
+ },
+ ])
+
+ expect(ids).toHaveLength(1)
+ const inactiveWrite = mockWriteFile.mock.calls.find(
+ ([path]) => path === `${TEST_PATH_B}/.llm-wiki/ingest-queue.json`,
+ )
+ expect(inactiveWrite).toBeDefined()
+ const persisted = JSON.parse(String(inactiveWrite?.[1])) as Array<{
+ sourcePath: string
+ status: string
+ autoStart?: boolean
+ }>
+ expect(persisted).toMatchObject([
+ {
+ sourcePath: "raw/sources/scheduled-import/report.pdf",
+ status: "pending",
+ autoStart: true,
+ },
+ ])
+
+ mockReadFile.mockImplementation(async (path: string) => {
+ if (path === `${TEST_PATH_B}/.llm-wiki/ingest-queue.json`) {
+ return String(inactiveWrite?.[1])
+ }
+ throw new Error("ENOENT")
+ })
+ mockAutoIngest.mockResolvedValue(["wiki/sources/report.md"])
+
+ await restoreQueue(TEST_ID_B, TEST_PATH_B)
+ await flushMicrotasks(20)
+
+ expect(mockAutoIngest).toHaveBeenCalledWith(
+ TEST_PATH_B,
+ `${TEST_PATH_B}/raw/sources/scheduled-import/report.pdf`,
+ expect.any(Object),
+ expect.any(AbortSignal),
+ "scheduled-import",
+ expect.any(Function),
+ )
+ expect(getQueue()).toHaveLength(0)
+ })
+
it("enqueueIngest adds a pending task and triggers processing", async () => {
mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index 6f5a7cba..0bae4241 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -19,6 +19,8 @@ export interface IngestTask {
addedAt: number
error: string | null
retryCount: number
+ /** Background scheduled imports start when their project is next opened. */
+ autoStart?: boolean
}
// ── State ─────────────────────────────────────────────────────────────────
@@ -59,6 +61,7 @@ let processedSinceDrain = false
// Abort controller for the review-sweep LLM call so switching projects
// cancels a long-running judgment instead of burning tokens.
let sweepAbortController: AbortController | null = null
+let inactiveQueueWrite: Promise<void> = Promise.resolve()
function resetQueueAccounting(): void {
completedSinceIdle = 0
@@ -260,6 +263,72 @@ export async function enqueueBatch(
return ids
}
+/**
+ * Persist ingest work for a project that is not currently open. No model work
+ * starts here; restoreQueue starts these marked tasks when the project is next
+ * opened. This keeps background folder monitoring project-isolated.
+ */
+export async function enqueueInactiveProjectBatch(
+ projectId: string,
+ projectPath: string,
+ files: Array<{ sourcePath: string; folderContext: string }>,
+): Promise<string[]> {
+ if (currentProjectId === projectId) {
+ return enqueueBatch(projectId, files)
+ }
+
+ const pp = normalizePath(projectPath)
+ const ids: string[] = []
+ let written = false
+ const previousWrite = inactiveQueueWrite
+ inactiveQueueWrite = (async () => {
+ await previousWrite
+ // restoreQueue sets currentProjectId before waiting for this write. If the
+ // user opened this project meanwhile, leave queuing to the active scanner
+ // instead of racing its in-memory queue with a stale disk snapshot.
+ if (currentProjectId === projectId) return
+ const persisted = await loadQueue(pp, projectId)
+ if (currentProjectId === projectId) return
+ for (const file of files) {
+ const normalizedSourcePath = normalizePath(file.sourcePath)
+ const sourcePath = normalizedSourcePath.startsWith(`${pp}/`)
+ ? normalizedSourcePath.slice(pp.length + 1)
+ : normalizedSourcePath
+ const existing = persisted.find((task) =>
+ task.projectId === projectId &&
+ task.status !== "done" &&
+ normalizePath(task.sourcePath) === sourcePath
+ )
+ if (existing) {
+ existing.status = "pending"
+ existing.error = null
+ existing.retryCount = 0
+ existing.folderContext = file.folderContext || existing.folderContext
+ existing.autoStart = true
+ ids.push(existing.id)
+ continue
+ }
+ const task: IngestTask = {
+ id: generateId(),
+ projectId,
+ sourcePath,
+ folderContext: file.folderContext,
+ status: "pending",
+ addedAt: Date.now(),
+ error: null,
+ retryCount: 0,
+ autoStart: true,
+ }
+ persisted.push(task)
+ ids.push(task.id)
+ }
+ await writeFile(queueFilePath(pp), JSON.stringify(persisted, null, 2))
+ written = true
+ })()
+ await inactiveQueueWrite
+ return written ? ids : []
+}
+
/**
* Retry a failed task. Only valid for tasks in the active project's
* queue.
@@ -730,6 +799,8 @@ export async function restoreQueue(
currentProjectId = projectId
currentProjectPath = pp
+ await inactiveQueueWrite
+
const saved = await loadQueue(pp, projectId)
if (saved.length === 0) return
@@ -755,7 +826,7 @@ export async function restoreQueue(
queue = mine
restoredPausedTaskIds = new Set(
queue
- .filter((t) => t.status === "pending")
+ .filter((t) => t.status === "pending" && !t.autoStart)
.map((t) => t.id),
)
await saveQueue(pp)
diff --git a/src/lib/scheduled-import.test.ts b/src/lib/scheduled-import.test.ts
index 89c8f583..76bcdf1c 100644
--- a/src/lib/scheduled-import.test.ts
+++ b/src/lib/scheduled-import.test.ts
@@ -16,6 +16,9 @@ const mocks = vi.hoisted(() => ({
isIngestableSourcePath: vi.fn(),
loadScheduledImportConfig: vi.fn(),
saveScheduledImportConfig: vi.fn(),
+ getRecentProjects: vi.fn(),
+ enqueueInactiveProjectBatch: vi.fn(),
+ folderContextForSourcePath: vi.fn(),
}))
vi.mock("@/commands/fs", () => ({
@@ -32,16 +35,19 @@ vi.mock("@/commands/fs", () => ({
vi.mock("@/lib/source-lifecycle", () => ({
deleteSourceFile: mocks.deleteSourceFile,
enqueueSourceIngest: mocks.enqueueSourceIngest,
+ folderContextForSourcePath: mocks.folderContextForSourcePath,
isIngestableSourcePath: mocks.isIngestableSourcePath,
}))
vi.mock("@/lib/ingest-queue", () => ({
discardTasksForSources: mocks.discardTasksForSources,
+ enqueueInactiveProjectBatch: mocks.enqueueInactiveProjectBatch,
}))
vi.mock("@/lib/project-store", () => ({
loadScheduledImportConfig: mocks.loadScheduledImportConfig,
saveScheduledImportConfig: mocks.saveScheduledImportConfig,
+ getRecentProjects: mocks.getRecentProjects,
}))
import {
@@ -49,6 +55,7 @@ import {
resolveImportPath,
scheduledImportDestinationForFile,
scanAndImport,
+ isScheduledImportDue,
shouldSkipScheduledImportConfigFile,
shouldSkipScheduledImportFile,
} from "./scheduled-import"
@@ -59,6 +66,19 @@ describe("scheduled import path handling", () => {
beforeEach(() => {
vi.clearAllMocks()
+ mocks.getRecentProjects.mockResolvedValue([])
+ })
+
+ it("runs scheduled imports only after their configured interval", () => {
+ const config = {
+ enabled: true,
+ path: "/Users/me/inbox",
+ interval: 30,
+ lastScan: 1_000,
+ }
+ expect(isScheduledImportDue(config, 1_000 + 29 * 60_000)).toBe(false)
+ expect(isScheduledImportDue(config, 1_000 + 30 * 60_000)).toBe(true)
+ expect(isScheduledImportDue({ ...config, enabled: false }, Number.MAX_SAFE_INTEGER)).toBe(false)
})
it("resolves relative paths from the project root", () => {
@@ -237,6 +257,8 @@ describe("scanAndImport failure handling", () => {
lastScan: null,
})
mocks.saveScheduledImportConfig.mockResolvedValue(undefined)
+ 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") {
@@ -327,6 +349,31 @@ describe("scanAndImport failure handling", () => {
expect(mocks.writeFileAtomic).toHaveBeenCalled()
})
+ it("copies and durably queues changed files for an inactive project", async () => {
+ useWikiStore.setState({
+ project: {
+ id: "active-project",
+ name: "Active",
+ path: "/Users/me/active-project",
+ },
+ })
+
+ await scanAndImport(project, "/Users/me/inbox", { allowInactive: true })
+
+ const destination = "/Users/me/wiki-project/raw/sources/scheduled-import/paper.pdf"
+ expect(mocks.copyFile).toHaveBeenCalledWith("/Users/me/inbox/paper.pdf", destination)
+ expect(mocks.enqueueSourceIngest).not.toHaveBeenCalled()
+ expect(mocks.enqueueInactiveProjectBatch).toHaveBeenCalledWith(
+ project.id,
+ project.path,
+ [{ sourcePath: destination, folderContext: "scheduled-import" }],
+ )
+ expect(mocks.writeFileAtomic).toHaveBeenCalledWith(
+ "/Users/me/wiki-project/.llm-wiki/scheduled-import-db.json",
+ expect.stringContaining('"/Users/me/inbox/paper.pdf": "md5-new"'),
+ )
+ })
+
it("skips large files before hashing or copying", async () => {
mocks.getFileSize.mockResolvedValue(101 * 1024 * 1024)
diff --git a/src/lib/scheduled-import.ts b/src/lib/scheduled-import.ts
index 7acddc6b..29534683 100644
--- a/src/lib/scheduled-import.ts
+++ b/src/lib/scheduled-import.ts
@@ -14,13 +14,15 @@ import type { ScheduledImportConfig } from "@/stores/wiki-store"
import {
loadScheduledImportConfig,
saveScheduledImportConfig,
+ getRecentProjects,
} from "@/lib/project-store"
import {
deleteSourceFile,
enqueueSourceIngest,
+ folderContextForSourcePath,
isIngestableSourcePath,
} from "@/lib/source-lifecycle"
-import { discardTasksForSources } from "@/lib/ingest-queue"
+import { discardTasksForSources, enqueueInactiveProjectBatch } from "@/lib/ingest-queue"
import { useActivityStore } from "@/stores/activity-store"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
@@ -41,6 +43,7 @@ interface ImportDbStore {
type ScanOptions = {
runId?: number
+ allowInactive?: boolean
}
const EMPTY_DB: ImportDb = {
@@ -398,8 +401,23 @@ function isCurrentProject(projectId: string): boolean {
return useWikiStore.getState().project?.id === projectId
}
-function isCurrentRun(projectId: string, runId?: number): boolean {
- return isCurrentProject(projectId) && (runId === undefined || runId === activeRunId)
+function isCurrentRun(
+ projectId: string,
+ runId?: number,
+ allowInactive = false,
+): boolean {
+ return (allowInactive || isCurrentProject(projectId)) &&
+ (runId === undefined || runId === activeRunId)
+}
+
+export function isScheduledImportDue(
+ config: ScheduledImportConfig,
+ now = Date.now(),
+): boolean {
+ if (!config.enabled || !config.path || config.interval <= 0) return false
+ if (!config.lastScan) return true
+ const intervalMs = Math.max(1, Math.min(1440, config.interval)) * 60 * 1000
+ return now - config.lastScan >= intervalMs
}
export async function scanAndImport(
@@ -415,7 +433,9 @@ export async function scanAndImport(
console.warn(
`[scheduled-import] skipped self-referential path "${importRoot}". Use source folder monitoring for project sources instead.`,
)
- notifyManagedScheduledImportPath(project, importRoot)
+ if (isCurrentProject(project.id)) {
+ notifyManagedScheduledImportPath(project, importRoot)
+ }
return
}
@@ -424,14 +444,13 @@ export async function scanAndImport(
scanning = true
try {
- if (!isCurrentRun(project.id, options.runId)) {
+ if (!isCurrentRun(project.id, options.runId, options.allowInactive)) {
return
}
const tree = await listDirectory(importRoot)
const db = await loadImportDb(projectPath, importRoot)
const nextDb: ImportDb = { files: {}, lastScan: Date.now() }
- const llmConfig = useWikiStore.getState().llmConfig
const changedFiles: Array<{ key: string; md5: string; destPath: string }> = []
const observedEligibleKeys = new Set<string>()
@@ -448,7 +467,7 @@ export async function scanAndImport(
const key = dbDirectoryKey(sourcePath)
- if (!isCurrentRun(project.id, options.runId)) {
+ if (!isCurrentRun(project.id, options.runId, options.allowInactive)) {
return
}
@@ -483,26 +502,48 @@ export async function scanAndImport(
}
}
- if (!isCurrentRun(project.id, options.runId)) {
+ if (!isCurrentRun(project.id, options.runId, options.allowInactive)) {
return
}
- const removedSourcesChanged = await cleanupRemovedScheduledImports(
- project,
- importRoot,
- db,
- observedEligibleKeys,
- nextDb,
- )
+ let removedSourcesChanged = false
+ if (isCurrentProject(project.id)) {
+ removedSourcesChanged = await cleanupRemovedScheduledImports(
+ project,
+ importRoot,
+ db,
+ observedEligibleKeys,
+ nextDb,
+ )
+ } else {
+ // Defer destructive cleanup until the project is opened. Preserve old
+ // records so the first active scan can still identify removals.
+ for (const [key, md5] of Object.entries(db.files)) {
+ if (!observedEligibleKeys.has(key)) nextDb.files[key] = md5
+ }
+ }
- if (!isCurrentRun(project.id, options.runId)) {
+ if (!isCurrentRun(project.id, options.runId, options.allowInactive)) {
return
}
if (changedFiles.length > 0) {
const destPaths = changedFiles.map((file) => file.destPath)
- if (isCurrentRun(project.id, options.runId)) {
- const ids = await enqueueSourceIngest(project, destPaths, llmConfig)
+ if (isCurrentRun(project.id, options.runId, options.allowInactive)) {
+ const ids = isCurrentProject(project.id)
+ ? await enqueueSourceIngest(
+ project,
+ destPaths,
+ useWikiStore.getState().llmConfig,
+ )
+ : await enqueueInactiveProjectBatch(
+ project.id,
+ project.path,
+ destPaths.map((sourcePath) => ({
+ sourcePath,
+ folderContext: folderContextForSourcePath(sourcePath),
+ })),
+ )
if (ids.length > 0) {
for (const file of changedFiles) {
nextDb.files[file.key] = file.md5
@@ -514,7 +555,10 @@ export async function scanAndImport(
}
- if (removedSourcesChanged || changedFiles.some((file) => nextDb.files[file.key])) {
+ if (
+ isCurrentProject(project.id) &&
+ (removedSourcesChanged || changedFiles.some((file) => nextDb.files[file.key]))
+ ) {
await refreshProjectFileTree(projectPath, {
projectId: project.id,
bumpDataVersion: true,
@@ -550,18 +594,41 @@ export function startScheduledImport(
): void {
stopScheduledImport()
- if (!config.enabled || !config.path || config.interval <= 0) {
- return
- }
-
const runId = ++activeRunId
- const intervalMs = Math.max(1, Math.min(1440, config.interval)) * 60 * 1000
-
- void scanAndImport(project, config.path, { runId })
+ void runScheduledImportSweep(project, config, runId, true)
scanTimer = setInterval(() => {
- void scanAndImport(project, config.path, { runId })
- }, intervalMs)
+ void runScheduledImportSweep(project, config, runId, false)
+ }, 60 * 1000)
+}
+
+async function runScheduledImportSweep(
+ activeProject: WikiProject,
+ activeConfig: ScheduledImportConfig,
+ runId: number,
+ forceActive: boolean,
+): Promise<void> {
+ const recents = await getRecentProjects()
+ const projects = [activeProject, ...recents.filter((item) => item.id !== activeProject.id)]
+ for (const project of projects) {
+ if (runId !== activeRunId) return
+ const config = project.id === activeProject.id
+ ? forceActive
+ ? activeConfig
+ : (await loadScheduledImportConfig(project.path)) ?? activeConfig
+ : await loadScheduledImportConfig(project.path)
+ if (!config) continue
+ if (!isScheduledImportDue(config) && !(project.id === activeProject.id && forceActive)) {
+ continue
+ }
+ if (!config.enabled || !config.path || config.interval <= 0) {
+ continue
+ }
+ await scanAndImport(project, config.path, {
+ runId,
+ allowInactive: project.id !== activeProject.id,
+ })
+ }
}
export function stopScheduledImport(): void {