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: resume ingest queue and recover missed source events

nash_su4d1bae04d6de
diff --git a/src-tauri/src/commands/file_sync.rs b/src-tauri/src/commands/file_sync.rs
index 7811a59b..0befe1a6 100644
--- a/src-tauri/src/commands/file_sync.rs
+++ b/src-tauri/src/commands/file_sync.rs
@@ -24,7 +24,12 @@ const MAX_HASH_BYTES: u64 = 32 * 1024 * 1024;
const MAX_RETRY_COUNT: u32 = 3;
const APP_WRITE_IGNORE_MS: i64 = 4_000;
const QUEUE_EMIT_EVERY: usize = 25;
-const LINUX_RESCAN_INTERVAL_MS: i64 = 10_000;
+// Native watcher backends can lose events after overflow, sleep/wake, network
+// share reconnects, or long Windows sessions without terminating the watcher.
+// A low-frequency snapshot reconciliation makes the watcher self-healing on
+// every supported platform while keeping steady-state filesystem load small.
+const LINUX_WATCHER_RESCAN_INTERVAL_MS: i64 = 10_000;
+const OTHER_WATCHER_RESCAN_INTERVAL_MS: i64 = 60_000;
const DEFAULT_SOURCE_WATCH_CONFIG_JSON: &str =
include_str!("../../../src/lib/source-watch-defaults.json");
@@ -518,10 +523,14 @@ fn maybe_periodic_rescan(
watcher_generation: u64,
last_periodic_rescan: &mut i64,
) {
- if !cfg!(target_os = "linux") || now_ms() - *last_periodic_rescan < LINUX_RESCAN_INTERVAL_MS {
+ let interval = if cfg!(target_os = "linux") {
+ LINUX_WATCHER_RESCAN_INTERVAL_MS
+ } else {
+ OTHER_WATCHER_RESCAN_INTERVAL_MS
+ };
+ if now_ms() - *last_periodic_rescan < interval {
return;
}
- *last_periodic_rescan = now_ms();
let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
rescan_watch_roots(
app,
@@ -531,6 +540,7 @@ fn maybe_periodic_rescan(
watcher_generation,
)
}));
+ *last_periodic_rescan = now_ms();
match result {
Ok(Ok(())) => {}
Ok(Err(err)) => eprintln!("[file-sync] periodic rescan failed: {err}"),
@@ -548,12 +558,15 @@ fn rescan_watch_roots(
if !is_active_watcher_generation(watcher_generation) {
return Ok(());
}
- enqueue_rescan_changes_for_prefixes(
- root,
- project_id,
- &["raw/sources", "wiki", "purpose.md", "schema.md"],
- source_watch_config,
- )?;
+ // Linux retains the broader reconciliation because recursive inotify
+ // watches can miss subtree creation. Other platforms reconcile source
+ // inputs only to avoid a recurring generated-wiki scan.
+ let prefixes = if cfg!(target_os = "linux") {
+ &["raw/sources", "wiki", "purpose.md", "schema.md"][..]
+ } else {
+ &["raw/sources"][..]
+ };
+ enqueue_rescan_changes_for_prefixes(root, project_id, prefixes, source_watch_config)?;
if !is_active_watcher_generation(watcher_generation) {
return Ok(());
}
@@ -687,6 +700,7 @@ fn enqueue_rescan_changes_for_prefixes(
) -> Result<(), String> {
let rules = SourceWatchRules::new(source_watch_config);
let mut rels = BTreeSet::<String>::new();
+ let mut app_written_rels = BTreeSet::<String>::new();
let snapshot = with_queue_lock(root, || read_snapshot(root))?;
for prefix in prefixes {
let path = root.join(prefix);
@@ -697,6 +711,10 @@ fn enqueue_rescan_changes_for_prefixes(
&rules,
fs::metadata(&path).ok().map(|m| m.len()),
) {
+ if is_app_write_ignored(&path) {
+ app_written_rels.insert(rel);
+ continue;
+ }
let old = snapshot.files.get(&rel);
let fast = read_meta_fast(root, &rel)?;
if old.map(|m| (m.size, m.mtime_ms)) != fast.as_ref().map(|m| (m.size, m.mtime_ms))
@@ -713,6 +731,10 @@ fn enqueue_rescan_changes_for_prefixes(
&rules,
entry.metadata().ok().map(|m| m.len()),
) {
+ if is_app_write_ignored(entry.path()) {
+ app_written_rels.insert(rel);
+ continue;
+ }
let old = snapshot.files.get(&rel);
let fast = read_meta_fast(root, &rel)?;
if old.map(|m| (m.size, m.mtime_ms))
@@ -736,6 +758,9 @@ fn enqueue_rescan_changes_for_prefixes(
}
}
+ if !app_written_rels.is_empty() {
+ sync_snapshot_paths(root, app_written_rels)?;
+ }
enqueue_paths(root, project_id, rels)
}
@@ -1568,18 +1593,14 @@ mod tests {
vec![rel.to_string()],
)
.unwrap();
- enqueue_rescan_changes_for_prefixes(
- &root,
- "p1",
- &["raw/sources"],
- &default_watch_config(),
- )
- .unwrap();
+ enqueue_rescan_changes_for_prefixes(&root, "p1", &["raw/sources"], &default_watch_config())
+ .unwrap();
let queue = read_queue(&root).unwrap();
- assert!(queue.tasks.iter().any(|task| {
- task.path == rel && task.kind == FileChangeKind::Created
- }));
+ assert!(queue
+ .tasks
+ .iter()
+ .any(|task| { task.path == rel && task.kind == FileChangeKind::Created }));
let _ = fs::remove_dir_all(root);
}
diff --git a/src/components/layout/activity-panel.tsx b/src/components/layout/activity-panel.tsx
index f38fd951..37a9d6d0 100644
--- a/src/components/layout/activity-panel.tsx
+++ b/src/components/layout/activity-panel.tsx
@@ -112,9 +112,7 @@ export function ActivityPanel() {
const queueSummary = getQueueSummary()
const hasQueue = queueSummary.total > 0
- const shouldResumeQueue =
- queueSummary.userPaused ||
- (queueSummary.restoredBacklogWaiting && queueSummary.processing === 0)
+ const shouldResumeQueue = queueSummary.userPaused || queueSummary.blockedOnLlmConfig
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
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index e934dfd2..238171fe 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -148,13 +148,11 @@ describe("ingest-queue — enqueue & basic processing", () => {
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,
},
])
@@ -212,7 +210,6 @@ describe("ingest-queue — enqueue & basic processing", () => {
addedAt: 1,
error: null,
retryCount: 0,
- autoStart: true,
},
{
id: "keep-me",
@@ -223,7 +220,6 @@ describe("ingest-queue — enqueue & basic processing", () => {
addedAt: 2,
error: null,
retryCount: 0,
- autoStart: true,
},
])
}
@@ -821,7 +817,7 @@ describe("ingest-queue — restoreQueue", () => {
expect(getQueue()).toHaveLength(0)
})
- it("converts 'processing' tasks back to 'pending' on restore (interrupted by app close)", async () => {
+ it("restarts an interrupted processing task on restore", async () => {
const saved = [
{
id: "ingest-abc",
@@ -834,14 +830,15 @@ describe("ingest-queue — restoreQueue", () => {
},
]
mockReadFile.mockResolvedValue(JSON.stringify(saved))
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
await restoreQueue(TEST_ID, TEST_PATH)
await flushMicrotasks(2)
const queue = getQueue()
expect(queue).toHaveLength(1)
- expect(queue[0].status).toBe("pending")
- expect(getQueueSummary().paused).toBe(true)
- expect(mockAutoIngest).not.toHaveBeenCalled()
+ expect(queue[0].status).toBe("processing")
+ expect(getQueueSummary().paused).toBe(false)
+ expect(mockAutoIngest).toHaveBeenCalledTimes(1)
})
it("leaves 'failed' tasks as failed on restore", async () => {
@@ -882,14 +879,15 @@ describe("ingest-queue — restoreQueue", () => {
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
await restoreQueue(TEST_ID, TEST_PATH)
+ await flushMicrotasks(2)
const queue = getQueue()
expect(queue).toHaveLength(1)
expect(queue[0].projectId).toBe(TEST_ID)
- expect(queue[0].status).toBe("pending")
- expect(mockAutoIngest).not.toHaveBeenCalled()
+ expect(queue[0].status).toBe("processing")
+ expect(mockAutoIngest).toHaveBeenCalledTimes(1)
})
- it("resumeProcessing starts restored pending tasks", async () => {
+ it("automatically resumes restored pending tasks", async () => {
const saved = [
{
id: "ingest-restored",
@@ -905,11 +903,6 @@ describe("ingest-queue — restoreQueue", () => {
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)
@@ -917,7 +910,62 @@ describe("ingest-queue — restoreQueue", () => {
expect(getQueueSummary().paused).toBe(false)
})
- it("runs new live tasks while restored backlog waits for manual resume", async () => {
+ it("keeps restored tasks pending when the ingest model is not configured", async () => {
+ const { useWikiStore } = await import("@/stores/wiki-store")
+ useWikiStore.getState().setLlmConfig({
+ provider: "openai",
+ apiKey: "",
+ model: "",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ })
+ mockReadFile.mockResolvedValue(JSON.stringify([
+ {
+ id: "pending-a",
+ sourcePath: "a.md",
+ folderContext: "",
+ status: "pending",
+ addedAt: 0,
+ error: null,
+ retryCount: 0,
+ },
+ {
+ id: "pending-b",
+ sourcePath: "b.md",
+ folderContext: "",
+ status: "pending",
+ addedAt: 0,
+ error: null,
+ retryCount: 0,
+ },
+ ]))
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ await flushMicrotasks(4)
+
+ expect(getQueue().map((task) => task.status)).toEqual(["pending", "pending"])
+ expect(getQueueSummary().blockedOnLlmConfig).toBe(true)
+ expect(mockAutoIngest).not.toHaveBeenCalled()
+
+ useWikiStore.getState().setLlmConfig({
+ provider: "openai",
+ apiKey: "configured",
+ model: "model",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ })
+ mockAutoIngest.mockResolvedValue(["wiki/sources/restored.md"])
+ resumeProcessing()
+ await flushMicrotasks(20)
+
+ expect(mockAutoIngest).toHaveBeenCalledTimes(2)
+ expect(getQueue()).toHaveLength(0)
+ expect(getQueueSummary().blockedOnLlmConfig).toBe(false)
+ })
+
+ it("finishes restored backlog before accepting a new live task", async () => {
const saved = [
{
id: "ingest-restored",
@@ -930,20 +978,23 @@ describe("ingest-queue — restoreQueue", () => {
},
]
mockReadFile.mockResolvedValue(JSON.stringify(saved))
- mockAutoIngest.mockResolvedValue(["wiki/sources/live.md"])
+ mockAutoIngest.mockImplementation(async (_projectPath, sourcePath) => [
+ `wiki/sources/${String(sourcePath).replace(/\.md$/, "")}.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)
+ expect(mockAutoIngest).toHaveBeenCalledTimes(2)
+ expect(mockAutoIngest.mock.calls[0][1]).toBe(`${TEST_PATH}/restored.md`)
+ expect(mockAutoIngest.mock.calls[1][1]).toBe(`${TEST_PATH}/live.md`)
+ expect(getQueue()).toHaveLength(0)
+ expect(getQueueSummary().paused).toBe(false)
})
- it("distinguishes active live processing from user pause while restored backlog waits", async () => {
+ it("reports an automatically restored task as active processing", async () => {
const saved = [
{
id: "ingest-restored",
@@ -960,18 +1011,14 @@ describe("ingest-queue — restoreQueue", () => {
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 () => {
+ it("queues a rerun when a live event touches a restored task already processing", async () => {
const saved = [
{
id: "ingest-restored",
@@ -984,14 +1031,23 @@ describe("ingest-queue — restoreQueue", () => {
},
]
mockReadFile.mockResolvedValue(JSON.stringify(saved))
- mockAutoIngest.mockResolvedValue(["wiki/sources/same.md"])
+ const firstRun = createDeferred<string[]>()
+ mockAutoIngest
+ .mockImplementationOnce(() => firstRun.promise)
+ .mockResolvedValueOnce(["wiki/sources/same.md"])
await restoreQueue(TEST_ID, TEST_PATH)
await flushMicrotasks(2)
await enqueueIngest(TEST_ID, "same.md")
- await flushMicrotasks(10)
+ await flushMicrotasks(2)
expect(mockAutoIngest).toHaveBeenCalledTimes(1)
+ expect(getQueue().filter((task) => task.status === "pending")).toHaveLength(1)
+
+ firstRun.resolve(["wiki/sources/same.md"])
+ await flushMicrotasks(10)
+
+ expect(mockAutoIngest).toHaveBeenCalledTimes(2)
expect(mockAutoIngest.mock.calls[0][1]).toBe(`${TEST_PATH}/same.md`)
expect(getQueue()).toHaveLength(0)
expect(getQueueSummary().paused).toBe(false)
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index 66e4da86..9ac9c1a4 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -21,8 +21,6 @@ export interface IngestTask {
addedAt: number
error: string | null
retryCount: number
- /** Background scheduled imports start when their project is next opened. */
- autoStart?: boolean
}
// ── State ─────────────────────────────────────────────────────────────────
@@ -50,11 +48,8 @@ let queueEpoch = 0
* 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>()
+/** Pending work is blocked until the ingest model is configured. */
+let blockedOnLlmConfig = false
/** 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. */
@@ -200,7 +195,6 @@ function upsertQueuedIngestTask(
)
if (pendingOrStopped) {
- restoredPausedTaskIds.delete(pendingOrStopped.id)
pendingOrStopped.sourcePath = normalizedSourcePath
pendingOrStopped.folderContext = folderContext || pendingOrStopped.folderContext
pendingOrStopped.status = "pending"
@@ -359,7 +353,6 @@ export async function enqueueInactiveProjectBatch(
existing.error = null
existing.retryCount = 0
existing.folderContext = file.folderContext || existing.folderContext
- existing.autoStart = true
ids.push(existing.id)
continue
}
@@ -372,7 +365,6 @@ export async function enqueueInactiveProjectBatch(
addedAt: Date.now(),
error: null,
retryCount: 0,
- autoStart: true,
}
persisted.push(task)
ids.push(task.id)
@@ -446,7 +438,6 @@ export async function retryTask(taskId: string): Promise<void> {
if (task.projectId !== currentProjectId) return
if (task.status !== "failed" && task.status !== "cancelled") return
- restoredPausedTaskIds.delete(task.id)
task.status = "pending"
task.error = null
task.retryCount = 0
@@ -465,7 +456,6 @@ export async function retryTasks(taskIds: readonly string[]): Promise<number> {
!selected.has(task.id) ||
(task.status !== "failed" && task.status !== "cancelled")
) continue
- restoredPausedTaskIds.delete(task.id)
task.status = "pending"
task.error = null
task.retryCount = 0
@@ -487,7 +477,6 @@ 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
@@ -548,7 +537,6 @@ export async function cancelTask(taskId: string): Promise<void> {
run?.controller.abort()
}
- restoredPausedTaskIds.delete(taskId)
task.status = "cancelled"
task.error = null
if (!queue.some((t) => t.status === "pending" || t.status === "processing")) {
@@ -581,7 +569,6 @@ export async function cancelTasks(taskIds: readonly string[]): Promise<number> {
run?.controller.abort()
}
for (const task of targets) {
- restoredPausedTaskIds.delete(task.id)
task.status = "cancelled"
task.error = null
}
@@ -621,7 +608,6 @@ export async function discardTasksForSources(
const targetIds = new Set(targets.map((task) => task.id))
const hadProcessingTask = targets.some((task) => task.status === "processing")
for (const task of targets) {
- restoredPausedTaskIds.delete(task.id)
if (task.status === "processing") cancelledInFlightTaskIds.add(task.id)
}
for (const task of targets) {
@@ -671,7 +657,6 @@ export async function cancelAllTasks(): Promise<number> {
let cancelled = 0
for (const task of queue) {
if (task.status !== "pending" && task.status !== "processing") continue
- restoredPausedTaskIds.delete(task.id)
task.status = "cancelled"
task.error = null
cancelled += 1
@@ -719,14 +704,14 @@ export function pauseProcessing(): void {
export function resumeProcessing(): void {
clearUsageLimitAutoResume()
paused = false
- restoredPausedTaskIds.clear()
+ blockedOnLlmConfig = false
console.log("[Ingest Queue] Resumed")
if (currentProjectId) processNext(currentProjectId)
}
/** Whether queue processing is currently paused by the user. */
export function isQueuePaused(): boolean {
- return paused || queue.some((t) => t.status === "pending" && restoredPausedTaskIds.has(t.id))
+ return paused
}
/**
@@ -748,16 +733,13 @@ export function getQueueSummary(): {
total: number
paused: boolean
userPaused: boolean
- restoredBacklogWaiting: boolean
+ blockedOnLlmConfig: 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 cancelled = queue.filter((t) => t.status === "cancelled").length
const activeTotal = queue.length + completedSinceIdle
- const restoredBacklogWaiting = queue.some((t) =>
- t.status === "pending" && restoredPausedTaskIds.has(t.id)
- )
return {
pending,
processing: processingCount,
@@ -765,9 +747,9 @@ export function getQueueSummary(): {
cancelled,
completed: completedSinceIdle,
total: activeTotal,
- paused: paused || (restoredBacklogWaiting && processingCount === 0),
+ paused,
userPaused: paused,
- restoredBacklogWaiting,
+ blockedOnLlmConfig,
}
}
@@ -788,11 +770,11 @@ export function clearQueueState(): void {
sweepAbortController.abort()
}
queue = []
- restoredPausedTaskIds.clear()
cancelledInFlightTaskIds.clear()
activeRuns.clear()
scheduling = false
paused = false
+ blockedOnLlmConfig = false
currentProjectId = ""
currentProjectPath = ""
sweepAbortController = null
@@ -863,8 +845,8 @@ export async function pauseQueue(): Promise<void> {
await saveQueue(pausedProjectPath)
queue = []
- restoredPausedTaskIds.clear()
cancelledInFlightTaskIds.clear()
+ blockedOnLlmConfig = false
currentProjectId = ""
currentProjectPath = ""
processedSinceDrain = false
@@ -875,8 +857,8 @@ export async function pauseQueue(): Promise<void> {
/**
* 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.
+ * to a project. Restored pending tasks resume automatically; otherwise a
+ * process restart can leave durable work stalled with no visible failure.
* `pauseQueue()` must have been called first (or the active project already
* cleared) so that in-memory state is not contaminated from the previous
* project.
@@ -890,7 +872,6 @@ export async function restoreQueue(
// Defensive: reset in-memory state (should already be empty via
// pauseQueue, but clearing again costs nothing).
queue = []
- restoredPausedTaskIds.clear()
cancelledInFlightTaskIds.clear()
activeRuns.clear()
scheduling = false
@@ -898,6 +879,7 @@ export async function restoreQueue(
// Every project loads un-paused. Pause is a current-session control;
// it does not carry across project switches or app restarts.
paused = false
+ blockedOnLlmConfig = false
resetQueueAccounting()
currentProjectId = projectId
currentProjectPath = pp
@@ -927,18 +909,26 @@ export async function restoreQueue(
}
queue = mine
- restoredPausedTaskIds = new Set(
- queue
- .filter((t) => t.status === "pending" && !t.autoStart)
- .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 paused for manual resume, ${failed} failed, ${restored} reset from interrupted`)
+ if (!hasUsableLlm(getTaskLlmConfig("ingest"))) {
+ blockedOnLlmConfig = true
+ for (const task of queue) {
+ if (task.status === "pending" && !task.error) {
+ task.error = "LLM not configured — set an ingest model in Settings, then resume"
+ }
+ }
+ await saveQueue(pp)
+ console.warn(
+ `[Ingest Queue] Restored ${pending} pending task(s), but ingest LLM is not configured; leaving them pending`,
+ )
+ return
+ }
+ console.log(`[Ingest Queue] Restored: ${pending} pending resumed automatically, ${failed} failed, ${restored} reset from interrupted`)
processNext(projectId)
}
}
@@ -1101,11 +1091,13 @@ async function startTask(projectId: string, task: IngestTask): Promise<boolean>
const llmConfig = getTaskLlmConfig("ingest")
if (!hasUsableLlm(llmConfig)) {
- task.status = "failed"
- task.error = "LLM not configured — set API key in Settings"
+ blockedOnLlmConfig = true
+ task.status = "pending"
+ task.error ||= "LLM not configured — set an ingest model in Settings, then resume"
await saveQueue(projectPath)
- return true
+ return false
}
+ task.error = null
const reservation = commitCoordinator.reserve()
const run: ActiveIngestRun = {
@@ -1117,7 +1109,6 @@ async function startTask(projectId: string, task: IngestTask): Promise<boolean>
commitActive: false,
completion: Promise.resolve(),
}
- restoredPausedTaskIds.delete(task.id)
task.status = "processing"
activeRuns.set(task.id, run)
await saveQueue(projectPath)
@@ -1145,32 +1136,29 @@ async function startTask(projectId: string, task: IngestTask): Promise<boolean>
async function processNext(projectId: string): Promise<void> {
if (scheduling || currentProjectId !== projectId) return
if (paused) return
+ if (blockedOnLlmConfig) {
+ if (!hasUsableLlm(getTaskLlmConfig("ingest"))) return
+ blockedOnLlmConfig = false
+ }
const epoch = queueEpoch
scheduling = true
try {
- while (activeRuns.size < workerLimit && currentProjectId === projectId && !paused) {
+ while (activeRuns.size < workerLimit && currentProjectId === projectId && !paused && !blockedOnLlmConfig) {
const next = queue.find((task) =>
task.projectId === projectId &&
task.status === "pending" &&
- !activeRuns.has(task.id) &&
- !restoredPausedTaskIds.has(task.id)
+ !activeRuns.has(task.id)
)
if (!next) break
- await startTask(projectId, next)
+ if (!(await startTask(projectId, next))) break
}
const hasRunnablePending = queue.some((task) =>
task.projectId === projectId &&
task.status === "pending" &&
- !activeRuns.has(task.id) &&
- !restoredPausedTaskIds.has(task.id)
- )
- const hasRestoredPending = queue.some((task) =>
- task.projectId === projectId &&
- task.status === "pending" &&
- restoredPausedTaskIds.has(task.id)
+ !activeRuns.has(task.id)
)
- if (activeRuns.size === 0 && !hasRunnablePending && !hasRestoredPending) {
+ if (activeRuns.size === 0 && !hasRunnablePending) {
const pathAtDrain = currentProjectPath
onQueueDrained(projectId, pathAtDrain, epoch).catch((err) =>
console.error("[Ingest Queue] sweep failed:", err)
@@ -1181,15 +1169,14 @@ async function processNext(projectId: string): Promise<void> {
const hasRunnable = queue.some((task) =>
task.projectId === projectId &&
task.status === "pending" &&
- !activeRuns.has(task.id) &&
- !restoredPausedTaskIds.has(task.id)
+ !activeRuns.has(task.id)
)
const hasAnyPending = queue.some((task) =>
task.projectId === projectId && task.status === "pending"
)
const needsDrain = processedSinceDrain && activeRuns.size === 0 && !hasAnyPending
const hasWorkerCapacity = activeRuns.size < workerLimit
- if (currentProjectId === projectId && !paused && ((hasWorkerCapacity && hasRunnable) || needsDrain)) {
+ if (currentProjectId === projectId && !paused && !blockedOnLlmConfig && ((hasWorkerCapacity && hasRunnable) || needsDrain)) {
queueMicrotask(() => void processNext(projectId))
}
}