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: prevent startup ingest auto-resume

nash_su2a3747fa0434
diff --git a/src/components/layout/activity-panel.tsx b/src/components/layout/activity-panel.tsx
index cf0aade5..8befeac4 100644
--- a/src/components/layout/activity-panel.tsx
+++ b/src/components/layout/activity-panel.tsx
@@ -95,6 +95,9 @@ export function ActivityPanel() {
const queueSummary = getQueueSummary()
const hasQueue = queueSummary.total > 0
+ const shouldResumeQueue =
+ queueSummary.userPaused ||
+ (queueSummary.restoredBacklogWaiting && queueSummary.processing === 0)
const hasFileSync = fileSyncTasks.length > 0 || Boolean(fileSyncError)
const fileSyncPending = fileSyncTasks.filter((t) => t.status === "pending").length
const fileSyncProcessing = fileSyncTasks.filter((t) => t.status === "processing").length
@@ -135,12 +138,12 @@ export function ActivityPanel() {
const handleTogglePause = useCallback(() => {
if (!project) return
- if (queueSummary.paused) {
+ if (shouldResumeQueue) {
resumeProcessing()
} else {
pauseProcessing()
}
- }, [project, queueSummary.paused])
+ }, [project, shouldResumeQueue])
const handleFileSyncRescan = useCallback(() => {
if (!project) return
@@ -262,25 +265,33 @@ export function ActivityPanel() {
{hasQueue && (queueSummary.processing > 0 || queueSummary.pending > 0) && (
<div className="px-3 py-1.5 border-b border-border/50">
<div className="flex items-center justify-between text-[10px] text-muted-foreground mb-1 gap-2">
- <span>{queueSummary.paused ? t("activity.ingestQueuePaused") : t("activity.ingestQueue")}</span>
+ <span>
+ {queueSummary.paused && queueSummary.processing === 0
+ ? t("activity.ingestQueuePaused")
+ : t("activity.ingestQueue")}
+ </span>
<span className="flex-1 text-right">
{t("activity.queueCompleteCount", {
done: queueSummary.completed + queueSummary.failed,
total: queueSummary.total,
})}
</span>
- {(queueSummary.pending > 0 || queueSummary.paused) && (
+ {(queueSummary.processing > 0 || queueSummary.pending > 0 || queueSummary.paused) && (
<button
onClick={handleTogglePause}
className="flex items-center gap-0.5 rounded px-1.5 py-0.5 text-[10px] hover:bg-accent hover:text-foreground"
title={
- queueSummary.paused
+ shouldResumeQueue
? t("activity.resumeQueueTitle")
: t("activity.pauseQueueTitle")
}
>
- {queueSummary.paused ? <Play className="h-2.5 w-2.5" /> : <Pause className="h-2.5 w-2.5" />}
- {queueSummary.paused ? t("activity.resumeQueue") : t("activity.pauseQueue")}
+ {shouldResumeQueue
+ ? <Play className="h-2.5 w-2.5" />
+ : <Pause className="h-2.5 w-2.5" />}
+ {shouldResumeQueue
+ ? t("activity.resumeQueue")
+ : t("activity.pauseQueue")}
</button>
)}
{queueSummary.pending + queueSummary.processing >= 2 && (
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index ea8a0ff8..d5c56c84 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -460,18 +460,14 @@ describe("ingest-queue — restoreQueue", () => {
},
]
mockReadFile.mockResolvedValue(JSON.stringify(saved))
- // Prevent the reprocessing kickoff from completing forever:
- mockAutoIngest.mockImplementation(() => new Promise(() => {}))
-
await restoreQueue(TEST_ID, TEST_PATH)
await flushMicrotasks(2)
const queue = getQueue()
expect(queue).toHaveLength(1)
- // After restore + kick-off of processNext, the task transitions back to
- // "processing" — but the RESTORED-from-disk value was "pending". We can
- // still assert it's not "failed" / "done".
- expect(["pending", "processing"]).toContain(queue[0].status)
+ expect(queue[0].status).toBe("pending")
+ expect(getQueueSummary().paused).toBe(true)
+ expect(mockAutoIngest).not.toHaveBeenCalled()
})
it("leaves 'failed' tasks as failed on restore", async () => {
@@ -515,6 +511,116 @@ describe("ingest-queue — restoreQueue", () => {
const queue = getQueue()
expect(queue).toHaveLength(1)
expect(queue[0].projectId).toBe(TEST_ID)
+ expect(queue[0].status).toBe("pending")
+ expect(mockAutoIngest).not.toHaveBeenCalled()
+ })
+
+ it("resumeProcessing starts restored pending tasks", async () => {
+ const saved = [
+ {
+ id: "ingest-restored",
+ sourcePath: "restored.md",
+ folderContext: "",
+ status: "pending",
+ addedAt: 0,
+ error: null,
+ retryCount: 0,
+ },
+ ]
+ mockReadFile.mockResolvedValue(JSON.stringify(saved))
+ mockAutoIngest.mockResolvedValue(["wiki/sources/restored.md"])
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ await flushMicrotasks(2)
+ expect(mockAutoIngest).not.toHaveBeenCalled()
+ expect(getQueueSummary().paused).toBe(true)
+
+ resumeProcessing()
+ await flushMicrotasks(10)
+
+ expect(mockAutoIngest).toHaveBeenCalledTimes(1)
+ expect(getQueue()).toHaveLength(0)
+ expect(getQueueSummary().paused).toBe(false)
+ })
+
+ it("runs new live tasks while restored backlog waits for manual resume", async () => {
+ const saved = [
+ {
+ id: "ingest-restored",
+ sourcePath: "restored.md",
+ folderContext: "",
+ status: "pending",
+ addedAt: 0,
+ error: null,
+ retryCount: 0,
+ },
+ ]
+ mockReadFile.mockResolvedValue(JSON.stringify(saved))
+ mockAutoIngest.mockResolvedValue(["wiki/sources/live.md"])
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ await flushMicrotasks(2)
+ await enqueueIngest(TEST_ID, "live.md")
+ await flushMicrotasks(10)
+
+ expect(mockAutoIngest).toHaveBeenCalledTimes(1)
+ expect(mockAutoIngest.mock.calls[0][1]).toBe(`${TEST_PATH}/live.md`)
+ expect(getQueue().map((task) => task.sourcePath)).toEqual(["restored.md"])
+ expect(getQueueSummary().paused).toBe(true)
+ })
+
+ it("distinguishes active live processing from user pause while restored backlog waits", async () => {
+ const saved = [
+ {
+ id: "ingest-restored",
+ sourcePath: "restored.md",
+ folderContext: "",
+ status: "pending",
+ addedAt: 0,
+ error: null,
+ retryCount: 0,
+ },
+ ]
+ mockReadFile.mockResolvedValue(JSON.stringify(saved))
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ await flushMicrotasks(2)
+ await enqueueIngest(TEST_ID, "live.md")
+ await flushMicrotasks(2)
+
+ expect(getQueueSummary()).toMatchObject({
+ processing: 1,
+ paused: false,
+ userPaused: false,
+ restoredBacklogWaiting: true,
+ })
+ })
+
+ it("promotes a restored task when a live event touches the same source", async () => {
+ const saved = [
+ {
+ id: "ingest-restored",
+ sourcePath: "same.md",
+ folderContext: "",
+ status: "pending",
+ addedAt: 0,
+ error: null,
+ retryCount: 0,
+ },
+ ]
+ mockReadFile.mockResolvedValue(JSON.stringify(saved))
+ mockAutoIngest.mockResolvedValue(["wiki/sources/same.md"])
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ await flushMicrotasks(2)
+ await enqueueIngest(TEST_ID, "same.md")
+ await flushMicrotasks(10)
+
+ expect(mockAutoIngest).toHaveBeenCalledTimes(1)
+ expect(mockAutoIngest.mock.calls[0][1]).toBe(`${TEST_PATH}/same.md`)
+ expect(getQueue()).toHaveLength(0)
+ expect(getQueueSummary().paused).toBe(false)
})
})
@@ -605,12 +711,12 @@ describe("ingest-queue — pauseQueue & switch-project survival", () => {
})
describe("ingest-queue — pause/resume processing", () => {
- it("finishes the in-flight task but does not start the next while paused", async () => {
- // First task is controllable; later calls would resolve immediately,
- // but we assert they never happen while paused.
- let resolveFirst: (f: string[]) => void = () => {}
+ it("aborts the in-flight task and does not start the next while paused", async () => {
mockAutoIngest.mockImplementationOnce(
- () => new Promise<string[]>((r) => { resolveFirst = r }),
+ (_projectPath, _sourcePath, _llmConfig, signal) =>
+ new Promise<string[]>((_resolve, reject) => {
+ signal?.addEventListener("abort", () => reject(new Error("aborted")))
+ }),
)
mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
@@ -621,25 +727,26 @@ describe("ingest-queue — pause/resume processing", () => {
await flushMicrotasks(2)
expect(getQueue().find((t) => t.sourcePath === "a.md")?.status).toBe("processing")
- // Pause while a.md is in flight — it must keep running, b.md must wait.
+ // Pause while a.md is in flight — it should be aborted and returned
+ // to pending; no other task starts while paused.
pauseProcessing()
expect(isQueuePaused()).toBe(true)
-
- // a.md completes normally (pause never aborts in-flight work).
- resolveFirst(["wiki/sources/a.md"])
await flushMicrotasks(10)
- // a.md drained; b.md stays pending; autoIngest was called exactly once.
expect(mockAutoIngest).toHaveBeenCalledTimes(1)
- expect(getQueue().find((t) => t.sourcePath === "a.md")).toBeUndefined()
+ expect(getQueue().find((t) => t.sourcePath === "a.md")?.status).toBe("pending")
+ expect(getQueue().find((t) => t.sourcePath === "a.md")?.retryCount).toBe(0)
+ expect(getQueue().find((t) => t.sourcePath === "a.md")?.error).toBeNull()
expect(getQueue().find((t) => t.sourcePath === "b.md")?.status).toBe("pending")
expect(getQueueSummary().paused).toBe(true)
})
it("resumeProcessing restarts the queue and processes the pending task", async () => {
- let resolveFirst: (f: string[]) => void = () => {}
mockAutoIngest.mockImplementationOnce(
- () => new Promise<string[]>((r) => { resolveFirst = r }),
+ (_projectPath, _sourcePath, _llmConfig, signal) =>
+ new Promise<string[]>((_resolve, reject) => {
+ signal?.addEventListener("abort", () => reject(new Error("aborted")))
+ }),
)
mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
@@ -649,34 +756,91 @@ describe("ingest-queue — pause/resume processing", () => {
])
await flushMicrotasks(2)
pauseProcessing()
- resolveFirst(["wiki/sources/a.md"])
await flushMicrotasks(10)
expect(mockAutoIngest).toHaveBeenCalledTimes(1)
+ expect(getQueue().find((t) => t.sourcePath === "a.md")?.status).toBe("pending")
expect(getQueue().find((t) => t.sourcePath === "b.md")?.status).toBe("pending")
- // Resume → b.md is handed to the LLM and drains.
+ // Resume → aborted a.md restarts first, then b.md drains.
resumeProcessing()
await flushMicrotasks(10)
- expect(mockAutoIngest).toHaveBeenCalledTimes(2)
+ expect(mockAutoIngest).toHaveBeenCalledTimes(3)
expect(getQueue()).toHaveLength(0)
expect(isQueuePaused()).toBe(false)
})
it("does not run the drain-sweep while paused (no token spend)", async () => {
- let resolveFirst: (f: string[]) => void = () => {}
mockAutoIngest.mockImplementationOnce(
- () => new Promise<string[]>((r) => { resolveFirst = r }),
+ (_projectPath, _sourcePath, _llmConfig, signal) =>
+ new Promise<string[]>((_resolve, reject) => {
+ signal?.addEventListener("abort", () => reject(new Error("aborted")))
+ }),
)
await enqueueIngest(TEST_ID, "only.md")
await flushMicrotasks(2)
pauseProcessing()
- resolveFirst(["wiki/sources/only.md"])
await flushMicrotasks(10)
- // Queue is empty after the in-flight task drained, but the paused
- // guard short-circuits processNext before onQueueDrained fires.
+ // The task is back to pending and no drain sweep runs while paused.
+ expect(getQueue().find((t) => t.sourcePath === "only.md")?.status).toBe("pending")
expect(mockSweep).not.toHaveBeenCalled()
+ expect(isQueuePaused()).toBe(true)
+ })
+
+ it("does not start a duplicate runner if resumed before the abort settles", async () => {
+ let rejectFirst: (err: Error) => void = () => {}
+ mockAutoIngest.mockImplementationOnce(
+ (_projectPath, _sourcePath, _llmConfig, signal) =>
+ new Promise<string[]>((_resolve, reject) => {
+ rejectFirst = reject
+ signal?.addEventListener("abort", () => {})
+ }),
+ )
+ mockAutoIngest.mockResolvedValue(["wiki/sources/next.md"])
+
+ await enqueueIngest(TEST_ID, "only.md")
+ await flushMicrotasks(2)
+ pauseProcessing()
+ expect(isQueuePaused()).toBe(true)
+ expect(getQueue().find((t) => t.sourcePath === "only.md")?.status).toBe("pending")
+
+ resumeProcessing()
+ await flushMicrotasks(5)
+ expect(mockAutoIngest).toHaveBeenCalledTimes(1)
+
+ rejectFirst(new Error("aborted"))
+ await flushMicrotasks(10)
+ expect(isQueuePaused()).toBe(false)
+ expect(mockAutoIngest).toHaveBeenCalledTimes(2)
+ expect(getQueue()).toHaveLength(0)
+ })
+
+ it("clears pause when the only paused task is cancelled so future imports can run", async () => {
+ mockAutoIngest.mockImplementationOnce(
+ (_projectPath, _sourcePath, _llmConfig, signal) =>
+ new Promise<string[]>((_resolve, reject) => {
+ signal?.addEventListener("abort", () => reject(new Error("aborted")))
+ }),
+ )
+ mockAutoIngest.mockResolvedValue(["wiki/sources/fresh.md"])
+
+ await enqueueIngest(TEST_ID, "only.md")
+ await flushMicrotasks(2)
+ pauseProcessing()
+ await flushMicrotasks(10)
+ const only = getQueue().find((t) => t.sourcePath === "only.md")
+ expect(only?.status).toBe("pending")
+ expect(getQueueSummary().paused).toBe(true)
+
+ await cancelTask(only!.id)
+ expect(getQueueSummary().paused).toBe(false)
+
+ await enqueueIngest(TEST_ID, "fresh.md")
+ await flushMicrotasks(10)
+ expect(mockAutoIngest).toHaveBeenCalledTimes(2)
+ expect(mockAutoIngest.mock.calls[1][1]).toBe(`${TEST_PATH}/fresh.md`)
+ expect(getQueue()).toHaveLength(0)
})
it("restoreQueue resets the paused flag — every project loads un-paused", async () => {
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index c7a8fead..06954e5b 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -26,13 +26,17 @@ export interface IngestTask {
let queue: IngestTask[] = []
let processing = false
/** User-controlled pause. When true, processNext stops handing pending
- * tasks to the LLM — but the in-flight task (if any) is NOT aborted, it
- * runs to completion. The drain-sweep (also an LLM call) is suppressed
- * too, which is intentional for a "stop spending tokens" pause.
- * In-memory only: not persisted, reset to false on restoreQueue (so
- * every project loads un-paused) and clearQueueState. A pending queue
- * therefore auto-resumes on app restart — see resumeProcessing. */
+ * tasks to the LLM. If a task is in flight, pauseProcessing aborts it
+ * and returns it to pending so token spend stops promptly. The drain-
+ * sweep (also an LLM call) is suppressed too, which is intentional.
+ * In-memory only: not persisted, reset to false on restoreQueue and
+ * clearQueueState. */
let paused = false
+/** Pending task IDs loaded from disk on startup/project open. These are
+ * intentionally not auto-run to avoid surprise LLM/MinerU spend when the
+ * app opens. New live tasks still run; if a live enqueue touches the same
+ * source, it promotes that restored task out of this set. */
+let restoredPausedTaskIds = new Set<string>()
/** UUID of the currently-active project. Used as a stale-context guard
* in processNext: if this changes mid-ingest (user switched projects),
* the orphaned runner bails instead of writing to the old project. */
@@ -105,6 +109,18 @@ function sameQueuedSourcePath(a: string, b: string): boolean {
return normalizeSourcePathForQueue(a) === normalizeSourcePathForQueue(b)
}
+function isStructuralWikiPath(filePath: string): boolean {
+ const normalized = normalizePath(filePath)
+ return (
+ normalized.endsWith("/wiki/index.md") ||
+ normalized.endsWith("/wiki/log.md") ||
+ normalized.endsWith("/wiki/overview.md") ||
+ normalized === "wiki/index.md" ||
+ normalized === "wiki/log.md" ||
+ normalized === "wiki/overview.md"
+ )
+}
+
function upsertQueuedIngestTask(
projectId: string,
sourcePath: string,
@@ -121,6 +137,7 @@ function upsertQueuedIngestTask(
)
if (pendingOrFailed) {
+ restoredPausedTaskIds.delete(pendingOrFailed.id)
pendingOrFailed.sourcePath = normalizedSourcePath
pendingOrFailed.folderContext = folderContext || pendingOrFailed.folderContext
pendingOrFailed.status = "pending"
@@ -176,6 +193,7 @@ export async function cleanupWrittenFiles(
): Promise<void> {
const { cascadeDeleteWikiPage } = await import("@/lib/wiki-page-delete")
for (const filePath of filePaths) {
+ if (isStructuralWikiPath(filePath)) continue
const fullPath = isAbsolutePath(filePath)
? normalizePath(filePath)
: `${projectPath}/${filePath}`
@@ -246,6 +264,7 @@ export async function retryTask(taskId: string): Promise<void> {
if (!task) return
if (task.projectId !== currentProjectId) return
+ restoredPausedTaskIds.delete(task.id)
task.status = "pending"
task.error = null
task.retryCount = 0
@@ -263,6 +282,7 @@ export async function retryAllFailedTasks(): Promise<number> {
let requeued = 0
for (const task of queue) {
if (task.projectId !== currentProjectId || task.status !== "failed") continue
+ restoredPausedTaskIds.delete(task.id)
task.status = "pending"
task.error = null
task.retryCount = 0
@@ -302,7 +322,11 @@ export async function cancelTask(taskId: string): Promise<void> {
processing = false
}
+ restoredPausedTaskIds.delete(taskId)
queue = queue.filter((t) => t.id !== taskId)
+ if (!queue.some((t) => t.status === "pending" || t.status === "processing")) {
+ paused = false
+ }
await saveQueue(currentProjectPath)
console.log(`[Ingest Queue] Cancelled: ${task.sourcePath}`)
@@ -338,7 +362,11 @@ export async function cancelAllTasks(): Promise<number> {
}
const before = queue.length
+ for (const task of queue) {
+ if (task.status !== "failed") restoredPausedTaskIds.delete(task.id)
+ }
queue = queue.filter((t) => t.status === "failed")
+ paused = false
const removed = before - queue.length
await saveQueue(currentProjectPath)
@@ -347,17 +375,30 @@ export async function cancelAllTasks(): Promise<number> {
}
/**
- * Pause queue processing. The currently-running task (if any) finishes
- * normally — pause never aborts in-flight work — but no further pending
- * tasks are handed to the LLM until resumeProcessing() is called. Use
- * this to stop token spend without losing the queue or cancelling work.
+ * Pause queue processing. The currently-running task (if any) is aborted
+ * and returned to pending; no pending tasks are handed to the LLM until
+ * resumeProcessing() is called. Use this to stop token spend without
+ * losing the queue or cancelling work.
*
* In-memory only: a paused queue auto-resumes on app restart / project
* switch (pending tasks are picked up by restoreQueue).
*/
export function pauseProcessing(): void {
paused = true
- console.log("[Ingest Queue] Paused — in-flight task will finish; no new tasks will start")
+ const processingTask = queue.find(
+ (t) => t.projectId === currentProjectId && t.status === "processing",
+ )
+ if (processingTask) {
+ processingTask.status = "pending"
+ if (currentAbortController) {
+ currentAbortController.abort()
+ currentAbortController = null
+ }
+ saveQueue(currentProjectPath).catch((err) => {
+ console.warn("[Ingest Queue] Failed to persist paused queue:", err)
+ })
+ }
+ console.log("[Ingest Queue] Paused — in-flight task aborted; no new tasks will start")
}
/**
@@ -367,13 +408,14 @@ export function pauseProcessing(): void {
*/
export function resumeProcessing(): void {
paused = false
+ restoredPausedTaskIds.clear()
console.log("[Ingest Queue] Resumed")
if (currentProjectId) processNext(currentProjectId)
}
/** Whether queue processing is currently paused by the user. */
export function isQueuePaused(): boolean {
- return paused
+ return paused || queue.some((t) => t.status === "pending" && restoredPausedTaskIds.has(t.id))
}
/**
@@ -386,15 +428,32 @@ export function getQueue(): readonly IngestTask[] {
/**
* Get queue summary.
*/
-export function getQueueSummary(): { pending: number; processing: number; failed: number; completed: number; total: number; paused: boolean } {
+export function getQueueSummary(): {
+ pending: number
+ processing: number
+ failed: number
+ completed: number
+ total: number
+ paused: boolean
+ userPaused: boolean
+ restoredBacklogWaiting: boolean
+} {
+ const pending = queue.filter((t) => t.status === "pending").length
+ const processingCount = queue.filter((t) => t.status === "processing").length
+ const failed = queue.filter((t) => t.status === "failed").length
const activeTotal = queue.length + completedSinceIdle
+ const restoredBacklogWaiting = queue.some((t) =>
+ t.status === "pending" && restoredPausedTaskIds.has(t.id)
+ )
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,
+ pending,
+ processing: processingCount,
+ failed,
completed: completedSinceIdle,
total: activeTotal,
- paused,
+ paused: paused || (restoredBacklogWaiting && processingCount === 0),
+ userPaused: paused,
+ restoredBacklogWaiting,
}
}
@@ -412,6 +471,7 @@ export function clearQueueState(): void {
sweepAbortController.abort()
}
queue = []
+ restoredPausedTaskIds.clear()
processing = false
paused = false
currentProjectId = ""
@@ -462,6 +522,7 @@ export async function pauseQueue(): Promise<void> {
await saveQueue(pausedProjectPath)
queue = []
+ restoredPausedTaskIds.clear()
currentProjectId = ""
currentProjectPath = ""
lastWrittenFiles = []
@@ -472,10 +533,12 @@ export async function pauseQueue(): Promise<void> {
// ── Restore on startup ───────────────────────────────────────────────────
/**
- * Load queue from disk and resume processing. Called on app startup
- * and when opening / switching to a project. `pauseQueue()` must have
- * been called first (or the active project already cleared) so that
- * in-memory state is not contaminated from the previous project.
+ * Load queue from disk. Called on app startup and when opening / switching
+ * to a project. Restored pending tasks are hydrated but not auto-run; the
+ * user can resume them from the Activity panel. New live enqueues still run.
+ * `pauseQueue()` must have been called first (or the active project already
+ * cleared) so that in-memory state is not contaminated from the previous
+ * project.
*/
export async function restoreQueue(
projectId: string,
@@ -485,6 +548,7 @@ export async function restoreQueue(
// Defensive: reset in-memory state (should already be empty via
// pauseQueue, but clearing again costs nothing).
queue = []
+ restoredPausedTaskIds.clear()
processing = false
// Every project loads un-paused. Pause is a current-session control;
// it does not carry across project switches or app restarts.
@@ -518,13 +582,18 @@ export async function restoreQueue(
}
queue = mine
+ restoredPausedTaskIds = new Set(
+ queue
+ .filter((t) => t.status === "pending")
+ .map((t) => t.id),
+ )
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`)
+ console.log(`[Ingest Queue] Restored: ${pending} pending paused for manual resume, ${failed} failed, ${restored} reset from interrupted`)
processNext(projectId)
}
}
@@ -560,14 +629,30 @@ async function processNext(projectId: string): Promise<void> {
// Stale-context guard: processNext may be invoked by an orphaned
// recursion from a previous project. If we're no longer active, bail.
if (currentProjectId !== projectId) return
- // User pause: don't hand the next pending task to the LLM. The
- // in-flight task already running is unaffected (we don't abort it);
- // it finishes, calls processNext again, and lands back here. Also
+ // User pause: don't hand the next pending task to the LLM. Also
// skips the drain-sweep below — intended, since that's an LLM call.
- if (paused) return
+ if (paused) {
+ const hasPending = queue.some((t) => t.projectId === projectId && t.status === "pending")
+ if (hasPending) return
+ // Pause applies to the current queue, not to future imports forever.
+ // If the in-flight task completed despite the abort and nothing is left,
+ // clear it so a later explicit import can run normally.
+ paused = false
+ return
+ }
- const next = queue.find((t) => t.projectId === projectId && t.status === "pending")
+ const next = queue.find((t) =>
+ t.projectId === projectId &&
+ t.status === "pending" &&
+ !restoredPausedTaskIds.has(t.id)
+ )
if (!next) {
+ const hasRestoredPending = queue.some((t) =>
+ t.projectId === projectId &&
+ t.status === "pending" &&
+ restoredPausedTaskIds.has(t.id)
+ )
+ if (hasRestoredPending) return
// Queue drained — trigger review cleanup (auto-resolve stale items)
const pathAtDrain = currentProjectPath
onQueueDrained(projectId, pathAtDrain).catch((err) =>
@@ -594,6 +679,7 @@ async function processNext(projectId: string): Promise<void> {
}
processing = true
+ restoredPausedTaskIds.delete(next.id)
next.status = "processing"
await saveQueue(pp)
if (currentProjectId !== projectId) return
@@ -618,9 +704,21 @@ async function processNext(projectId: string): Promise<void> {
currentAbortController = new AbortController()
lastWrittenFiles = []
+ const trackWrittenFile = (relativePath: string): void => {
+ if (!lastWrittenFiles.includes(relativePath)) {
+ lastWrittenFiles.push(relativePath)
+ }
+ }
try {
- const writtenFiles = await autoIngest(pp, fullSourcePath, llmConfig, currentAbortController.signal, next.folderContext)
+ const writtenFiles = await autoIngest(
+ pp,
+ fullSourcePath,
+ llmConfig,
+ currentAbortController.signal,
+ next.folderContext,
+ trackWrittenFile,
+ )
// Stale-context guard: project switched during the long LLM call.
// Bail without mutating queue or writing to disk — pauseQueue has
// already persisted the correct state to the old project's file,
@@ -648,6 +746,17 @@ async function processNext(projectId: string): Promise<void> {
} catch (err) {
if (currentProjectId !== projectId) return
currentAbortController = null
+ const currentTask = queue.find((t) => t.id === next.id)
+ if (currentTask?.status === "pending") {
+ if (lastWrittenFiles.length > 0) {
+ await cleanupWrittenFiles(pp, lastWrittenFiles)
+ lastWrittenFiles = []
+ }
+ processing = false
+ await saveQueue(pp)
+ if (!paused) processNext(projectId)
+ return
+ }
const message = err instanceof Error ? err.message : String(err)
next.retryCount++
next.error = message
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 26713e9d..07c1e1c9 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -476,9 +476,10 @@ export async function autoIngest(
llmConfig: LlmConfig,
signal?: AbortSignal,
folderContext?: string,
+ onFileWritten?: (relativePath: string) => void,
): Promise<string[]> {
return withProjectLock(normalizePath(projectPath), () =>
- autoIngestImpl(projectPath, sourcePath, llmConfig, signal, folderContext),
+ autoIngestImpl(projectPath, sourcePath, llmConfig, signal, folderContext, onFileWritten),
)
}
@@ -499,6 +500,7 @@ async function autoIngestImpl(
llmConfig: LlmConfig,
signal?: AbortSignal,
folderContext?: string,
+ onFileWritten?: (relativePath: string) => void,
): Promise<string[]> {
const pp = normalizePath(projectPath)
const sp = normalizePath(sourcePath)
@@ -958,6 +960,7 @@ async function autoIngestImpl(
sourceSummaryPath,
signal,
activityId,
+ onFileWritten,
)
throwIfIngestAborted(signal, activityId)
const writtenPaths = writeResult.writtenPaths
@@ -1033,6 +1036,7 @@ async function autoIngestImpl(
sourceSummaryPath,
signal,
activityId,
+ onFileWritten,
)
writtenPaths.push(...repairResult.writtenPaths)
writeWarnings.push(...repairResult.warnings)
@@ -1088,6 +1092,7 @@ async function autoIngestImpl(
try {
await writeFile(sourceSummaryFullPath, fallbackContent)
writtenPaths.push(sourceSummaryPath)
+ onFileWritten?.(sourceSummaryPath)
} catch {
// non-critical
}
@@ -1536,6 +1541,7 @@ async function writeFileBlocks(
sourceSummaryPath?: string,
signal?: AbortSignal,
activityId?: string,
+ onFileWritten?: (relativePath: string) => void,
): Promise<{ writtenPaths: string[]; warnings: string[]; hardFailures: string[] }> {
const { blocks, warnings: parseWarnings } = parseFileBlocks(text)
const warnings = [...parseWarnings]
@@ -1673,6 +1679,7 @@ async function writeFileBlocks(
await writeFile(fullPath, toWrite)
}
writtenPaths.push(relativePath)
+ onFileWritten?.(relativePath)
} catch (err) {
const msg = `Failed to write "${relativePath}": ${err instanceof Error ? err.message : String(err)}`
console.error(`[ingest] ${msg}`)