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

feat: add recoverable ingest queue controls

nash_su0fd925734f27
diff --git a/src/components/layout/activity-panel.tsx b/src/components/layout/activity-panel.tsx
index 55b81e23..44844fb5 100644
--- a/src/components/layout/activity-panel.tsx
+++ b/src/components/layout/activity-panel.tsx
@@ -3,6 +3,7 @@ import {
ChevronUp, ChevronDown, Loader2, CheckCircle2, AlertCircle,
FileText, Users, Lightbulb, BookOpen, GitMerge, BarChart3, HelpCircle, Layout,
RotateCcw, X, Clock, TrendingUp, Target, Pause, Play,
+ ArrowUp, ArrowDown,
} from "lucide-react"
import { useTranslation } from "react-i18next"
import { useActivityStore, type ActivityItem } from "@/stores/activity-store"
@@ -13,9 +14,12 @@ import {
getQueue,
getQueueSummary,
retryTask,
- retryAllFailedTasks,
+ retryAllStoppedTasks,
+ retryTasks,
cancelTask,
+ cancelTasks,
cancelAllTasks,
+ movePendingTask,
pauseProcessing,
resumeProcessing,
type IngestTask,
@@ -54,6 +58,8 @@ const WIKI_TYPE_ICON_KEYS: Record<string, keyof typeof FILE_TYPE_ICONS> = {
overview: "overview",
}
+const MAX_VISIBLE_QUEUE_TASKS = 300
+
function getFileTypeInfo(path: string): { icon: typeof FileText; typeKey: string } {
const inferred = inferWikiTypeFromPath(path)
if (inferred) {
@@ -80,6 +86,7 @@ export function ActivityPanel() {
const fileSyncError = useFileSyncStore((s) => s.lastError)
const [expanded, setExpanded] = useState(false)
const [queueTasks, setQueueTasks] = useState<IngestTask[]>(() => [...getQueue()])
+ const [selectedTaskIds, setSelectedTaskIds] = useState<Set<string>>(new Set())
const prevRunningRef = useRef(0)
const runningCount = items.filter((i) => i.status === "running").length
@@ -93,6 +100,14 @@ export function ActivityPanel() {
return () => clearInterval(interval)
}, [])
+ useEffect(() => {
+ const available = new Set(queueTasks.map((task) => task.id))
+ setSelectedTaskIds((current) => {
+ const next = new Set([...current].filter((id) => available.has(id)))
+ return next.size === current.size ? current : next
+ })
+ }, [queueTasks])
+
const queueSummary = getQueueSummary()
const hasQueue = queueSummary.total > 0
const shouldResumeQueue =
@@ -116,13 +131,42 @@ export function ActivityPanel() {
const handleRetryAllFailed = useCallback(() => {
if (!project) return
- void retryAllFailedTasks()
+ void retryAllStoppedTasks()
.then(() => setQueueTasks([...getQueue()]))
.catch((err) => {
console.error("[activity-panel] failed to retry failed ingest tasks:", err)
})
}, [project])
+ const handleRetrySelected = useCallback(() => {
+ if (!project) return
+ void retryTasks([...selectedTaskIds]).then(() => {
+ setSelectedTaskIds(new Set())
+ setQueueTasks([...getQueue()])
+ })
+ }, [project, selectedTaskIds])
+
+ const handleCancelSelected = useCallback(() => {
+ if (!project) return
+ void cancelTasks([...selectedTaskIds]).then(() => {
+ setSelectedTaskIds(new Set())
+ setQueueTasks([...getQueue()])
+ })
+ }, [project, selectedTaskIds])
+
+ const handleMoveTask = useCallback((taskId: string, direction: "up" | "down") => {
+ void movePendingTask(taskId, direction).then(() => setQueueTasks([...getQueue()]))
+ }, [])
+
+ const toggleTaskSelection = useCallback((taskId: string) => {
+ setSelectedTaskIds((current) => {
+ const next = new Set(current)
+ if (next.has(taskId)) next.delete(taskId)
+ else next.add(taskId)
+ return next
+ })
+ }, [])
+
const handleIngestCancel = useCallback((taskId: string) => {
if (!project) return
cancelTask(taskId)
@@ -193,13 +237,16 @@ export function ActivityPanel() {
// Build status text
let statusText = ""
if (queueSummary.processing > 0 || queueSummary.pending > 0) {
- const done = queueSummary.completed + queueSummary.failed
+ const done = queueSummary.completed + queueSummary.failed + queueSummary.cancelled
statusText = `Queue: ${done}/${queueSummary.total}`
if (queueSummary.failed > 0) statusText += ` (${queueSummary.failed} failed)`
} else if (runningCount > 0) {
statusText = `Processing: ${latestItem?.title ?? "..."}`
- } else if (queueSummary.failed > 0) {
- statusText = `${queueSummary.failed} failed task${queueSummary.failed > 1 ? "s" : ""}`
+ } else if (queueSummary.failed > 0 || queueSummary.cancelled > 0) {
+ statusText = t("activity.stoppedCount", {
+ failed: queueSummary.failed,
+ cancelled: queueSummary.cancelled,
+ })
} else if (fileSyncProcessing > 0 || fileSyncPending > 0) {
statusText = `File sync: ${fileSyncProcessing + fileSyncPending} pending`
} else if (fileSyncFailed > 0) {
@@ -211,6 +258,13 @@ export function ActivityPanel() {
}
const isActive = runningCount > 0 || queueSummary.processing > 0 || queueSummary.pending > 0 || fileSyncProcessing > 0 || fileSyncPending > 0
+ const orderedQueueTasks = [
+ ...queueTasks.filter((task) => task.status === "processing"),
+ ...queueTasks.filter((task) => task.status === "pending"),
+ ...queueTasks.filter((task) => task.status === "failed"),
+ ...queueTasks.filter((task) => task.status === "cancelled"),
+ ]
+ const visibleQueueTasks = orderedQueueTasks.slice(0, MAX_VISIBLE_QUEUE_TASKS)
return (
<div className="border-t bg-muted/30">
@@ -261,6 +315,39 @@ export function ActivityPanel() {
</div>
)}
+ {queueTasks.length > 0 && (
+ <div className="flex items-center gap-1 border-b border-border/50 px-3 py-1.5 text-[10px]">
+ <button
+ onClick={() => setSelectedTaskIds(
+ selectedTaskIds.size === queueTasks.length
+ ? new Set()
+ : new Set(queueTasks.map((task) => task.id)),
+ )}
+ className="rounded px-1.5 py-0.5 hover:bg-accent"
+ >
+ {selectedTaskIds.size === queueTasks.length
+ ? t("activity.clearSelection")
+ : t("activity.selectAll")}
+ </button>
+ <span className="flex-1 text-muted-foreground">
+ {t("activity.selectedCount", { count: selectedTaskIds.size })}
+ </span>
+ {selectedTaskIds.size > 0 && (
+ <>
+ <button onClick={handleRetrySelected} className="rounded px-1.5 py-0.5 hover:bg-accent">
+ {t("activity.restartSelected")}
+ </button>
+ <button
+ onClick={handleCancelSelected}
+ className="rounded px-1.5 py-0.5 text-destructive hover:bg-destructive/10"
+ >
+ {t("activity.cancelSelected")}
+ </button>
+ </>
+ )}
+ </div>
+ )}
+
{/* Queue progress bar */}
{hasQueue && (queueSummary.processing > 0 || queueSummary.pending > 0) && (
<div className="px-3 py-1.5 border-b border-border/50">
@@ -272,7 +359,7 @@ export function ActivityPanel() {
</span>
<span className="flex-1 text-right">
{t("activity.queueCompleteCount", {
- done: queueSummary.completed + queueSummary.failed,
+ done: queueSummary.completed + queueSummary.failed + queueSummary.cancelled,
total: queueSummary.total,
})}
</span>
@@ -303,7 +390,7 @@ export function ActivityPanel() {
{t("activity.cancelAll")}
</button>
)}
- {queueSummary.failed > 0 && (
+ {queueSummary.failed + queueSummary.cancelled > 0 && (
<button
onClick={handleRetryAllFailed}
className="rounded px-1.5 py-0.5 text-[10px] hover:bg-accent hover:text-foreground"
@@ -316,18 +403,21 @@ export function ActivityPanel() {
<div className="h-1.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full bg-primary transition-all"
- style={{ width: `${((queueSummary.completed + queueSummary.failed) / Math.max(queueSummary.total, 1)) * 100}%` }}
+ style={{ width: `${((queueSummary.completed + queueSummary.failed + queueSummary.cancelled) / Math.max(queueSummary.total, 1)) * 100}%` }}
/>
</div>
</div>
)}
- {hasQueue && queueSummary.processing === 0 && queueSummary.pending === 0 && queueSummary.failed > 0 && (
+ {hasQueue && queueSummary.processing === 0 && queueSummary.pending === 0 && queueSummary.failed + queueSummary.cancelled > 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 gap-2">
<span>{t("activity.ingestQueue")}</span>
<span className="flex-1 text-right">
- {t("activity.failedCount", { count: queueSummary.failed })}
+ {t("activity.stoppedCount", {
+ failed: queueSummary.failed,
+ cancelled: queueSummary.cancelled,
+ })}
</span>
<button
onClick={handleRetryAllFailed}
@@ -341,15 +431,14 @@ export function ActivityPanel() {
)}
{/* Queue tasks */}
- {queueTasks.filter((t) => t.status === "processing").map((task) => (
- <QueueRow key={task.id} task={task} onRetry={handleIngestRetry} onCancel={handleIngestCancel} />
- ))}
- {queueTasks.filter((t) => t.status === "pending").map((task) => (
- <QueueRow key={task.id} task={task} onRetry={handleIngestRetry} onCancel={handleIngestCancel} />
- ))}
- {queueTasks.filter((t) => t.status === "failed").map((task) => (
- <QueueRow key={task.id} task={task} onRetry={handleIngestRetry} onCancel={handleIngestCancel} />
+ {visibleQueueTasks.map((task) => (
+ <QueueRow key={task.id} task={task} selected={selectedTaskIds.has(task.id)} onSelect={toggleTaskSelection} onRetry={handleIngestRetry} onCancel={handleIngestCancel} onMove={handleMoveTask} />
))}
+ {orderedQueueTasks.length > visibleQueueTasks.length && (
+ <div className="border-b border-border/50 px-3 py-2 text-center text-[10px] text-muted-foreground">
+ {t("activity.moreTasks", { count: orderedQueueTasks.length - visibleQueueTasks.length })}
+ </div>
+ )}
{/* Activity items */}
{items.map((item) => {
@@ -379,17 +468,32 @@ export function ActivityPanel() {
)
}
-function QueueRow({ task, onRetry, onCancel }: { task: IngestTask; onRetry: (id: string) => void; onCancel: (id: string) => void }) {
+function QueueRow({ task, selected, onSelect, onRetry, onCancel, onMove }: {
+ task: IngestTask
+ selected: boolean
+ onSelect: (id: string) => void
+ onRetry: (id: string) => void
+ onCancel: (id: string) => void
+ onMove: (id: string, direction: "up" | "down") => void
+}) {
const { t } = useTranslation()
const fileName = getFileName(task.sourcePath)
return (
<div className="px-3 py-2 text-xs border-b border-border/50">
<div className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={selected}
+ onChange={() => onSelect(task.id)}
+ aria-label={t("activity.selectTask", { name: fileName })}
+ className="h-3.5 w-3.5 shrink-0"
+ />
<div className="shrink-0">
{task.status === "processing" && <Loader2 className="h-3 w-3 animate-spin text-primary" />}
{task.status === "pending" && <Clock className="h-3 w-3 text-muted-foreground" />}
{task.status === "failed" && <AlertCircle className="h-3 w-3 text-destructive" />}
+ {task.status === "cancelled" && <X className="h-3 w-3 text-muted-foreground" />}
</div>
<div className="min-w-0 flex-1">
<div className="font-medium truncate">{fileName}</div>
@@ -401,7 +505,7 @@ function QueueRow({ task, onRetry, onCancel }: { task: IngestTask; onRetry: (id:
)}
</div>
<div className="flex items-center gap-1 shrink-0">
- {task.status === "failed" && (
+ {(task.status === "failed" || task.status === "cancelled") && (
<button
onClick={() => onRetry(task.id)}
className="p-0.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground"
@@ -410,6 +514,16 @@ function QueueRow({ task, onRetry, onCancel }: { task: IngestTask; onRetry: (id:
<RotateCcw className="h-3 w-3" />
</button>
)}
+ {task.status === "pending" && (
+ <>
+ <button onClick={() => onMove(task.id, "up")} className="rounded p-0.5 text-muted-foreground hover:bg-accent" title={t("activity.moveUp")}>
+ <ArrowUp className="h-3 w-3" />
+ </button>
+ <button onClick={() => onMove(task.id, "down")} className="rounded p-0.5 text-muted-foreground hover:bg-accent" title={t("activity.moveDown")}>
+ <ArrowDown className="h-3 w-3" />
+ </button>
+ </>
+ )}
{(task.status === "pending" || task.status === "processing") && (
<button
onClick={() => onCancel(task.id)}
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 9123eade..5c4382ad 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -23,9 +23,12 @@ import { filterRawSourceTree } from "@/lib/source-filter"
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"
const SOURCE_TREE_INITIAL_ROWS = 160
const SOURCE_TREE_LOAD_BATCH = 160
+type SourceIngestStatus = "not-ingested" | "ingested" | IngestTask["status"]
export function SourcesView() {
const { t } = useTranslation()
@@ -45,6 +48,8 @@ export function SourcesView() {
const [urlInput, setUrlInput] = useState("")
const [urlError, setUrlError] = useState<string | null>(null)
const [urlResults, setUrlResults] = useState<UrlImportResult[]>([])
+ const [ingestedIdentities, setIngestedIdentities] = useState<string[]>([])
+ const [queueSnapshot, setQueueSnapshot] = useState<IngestTask[]>(() => [...getQueue()])
/**
* Path of the source-tree node currently in "click again to
* confirm delete" state. Lifted up here (rather than living
@@ -85,6 +90,46 @@ export function SourcesView() {
loadSources()
}, [loadSources, dataVersion])
+ useEffect(() => {
+ if (!project) {
+ setIngestedIdentities([])
+ return
+ }
+ let active = true
+ listIngestedSourceIdentities(project.path)
+ .then((identities) => {
+ if (active) setIngestedIdentities(identities)
+ })
+ .catch(() => {
+ if (active) setIngestedIdentities([])
+ })
+ return () => {
+ active = false
+ }
+ }, [project, dataVersion])
+
+ useEffect(() => {
+ const refresh = () => setQueueSnapshot([...getQueue()])
+ refresh()
+ const interval = setInterval(refresh, 1000)
+ return () => clearInterval(interval)
+ }, [project])
+
+ const sourceStatuses = useMemo(() => {
+ const statuses = new Map<string, SourceIngestStatus>()
+ if (!project) return statuses
+ const pp = normalizePath(project.path)
+ for (const identity of ingestedIdentities) {
+ statuses.set(`${pp}/raw/sources/${normalizePath(identity)}`, "ingested")
+ }
+ for (const task of queueSnapshot) {
+ if (task.projectId !== project.id || task.status === "done") continue
+ const path = normalizePath(task.sourcePath)
+ statuses.set(path.startsWith("/") || /^[A-Za-z]:\//.test(path) ? path : `${pp}/${path}`, task.status)
+ }
+ return statuses
+ }, [ingestedIdentities, project, queueSnapshot])
+
async function handleRefreshSources() {
if (!project || refreshing) return
setRefreshing(true)
@@ -400,6 +445,7 @@ export function SourcesView() {
pendingDeletePath={pendingDeletePath}
setPendingDeletePath={setPendingDeletePath}
ingestingPath={ingestingPath}
+ sourceStatuses={sourceStatuses}
/>
</div>
)}
@@ -481,6 +527,7 @@ function SourceTree({
pendingDeletePath,
setPendingDeletePath,
ingestingPath,
+ sourceStatuses,
}: {
nodes: FileNode[]
onOpen: (node: FileNode) => void
@@ -494,6 +541,7 @@ function SourceTree({
pendingDeletePath: string | null
setPendingDeletePath: (path: string | null) => void
ingestingPath: string | null
+ sourceStatuses: ReadonlyMap<string, SourceIngestStatus>
}) {
const { t } = useTranslation()
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})
@@ -552,6 +600,7 @@ function SourceTree({
<>
{visibleRows.map(({ node, depth }) => {
const isPendingDelete = pendingDeletePath === node.path
+ const ingestStatus = sourceStatuses.get(normalizePath(node.path)) ?? "not-ingested"
if (node.is_dir && node.children) {
const isCollapsed = collapsed[node.path] ?? false
return (
@@ -601,13 +650,28 @@ function SourceTree({
>
<FileText className="h-4 w-4 shrink-0" />
<span className="truncate">{node.name}</span>
+ <span
+ className={
+ ingestStatus === "failed"
+ ? "shrink-0 text-[10px] text-destructive"
+ : ingestStatus === "processing"
+ ? "shrink-0 text-[10px] text-primary"
+ : "shrink-0 text-[10px] text-muted-foreground"
+ }
+ >
+ {t(`sources.ingestStatus.${ingestStatus}`)}
+ </span>
</button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
title={t("sources.ingest")}
- disabled={ingestingPath === node.path}
+ disabled={
+ ingestingPath === node.path ||
+ ingestStatus === "pending" ||
+ ingestStatus === "processing"
+ }
onClick={() => onIngest(node)}
>
<BookOpen className="h-4 w-4" />
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 0763a67c..d3a19f9b 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -185,6 +185,15 @@
"refreshFolderTooltip": "Rescan the project source folder with the same rules as automatic monitoring. New or modified allowed files are queued for ingest; deleted sources trigger the normal wiki and index cleanup; then the file tree is rebuilt.",
"refreshFailed": "Failed to refresh sources: {{error}}",
"ingest": "Ingest",
+ "ingestStatus": {
+ "not-ingested": "Not ingested",
+ "ingested": "Ingested",
+ "pending": "Queued",
+ "processing": "Processing",
+ "done": "Done",
+ "failed": "Failed",
+ "cancelled": "Cancelled"
+ },
"delete": "Delete source and related wiki pages",
"deleteConfirm": "Delete \"{{name}}\" and its related wiki pages?\n\nThis will:\n- Delete the source file\n- Delete wiki pages generated from this source\n- Update index.md",
"deleteFolder": "Delete folder {{name}} (recursive)",
@@ -969,11 +978,21 @@
"resumeQueueTitle": "Resume processing queued ingest tasks",
"queueCompleteCount": "{{done}}/{{total}} complete",
"failedCount": "{{count}} failed",
+ "stoppedCount": "{{failed}} failed, {{cancelled}} cancelled",
"cancelAll": "Cancel all",
"cancelAllTitle": "Cancel all queued and in-progress tasks",
- "cancelAllConfirm": "Cancel all {{count}} queued/processing ingest tasks? Partial files from the in-progress task will be removed. Failed tasks will be kept so you can retry them.",
- "retryFailed": "Retry failed",
- "retryFailedTitle": "Retry all failed ingest tasks",
+ "cancelAllConfirm": "Cancel all {{count}} queued/processing ingest tasks? Partial files from the in-progress task will be removed. Cancelled tasks stay in the queue so you can restart them.",
+ "retryFailed": "Restart stopped",
+ "retryFailedTitle": "Restart all failed and cancelled ingest tasks",
+ "selectAll": "Select all",
+ "clearSelection": "Clear selection",
+ "selectedCount": "{{count}} selected",
+ "restartSelected": "Restart",
+ "cancelSelected": "Cancel",
+ "selectTask": "Select {{name}}",
+ "moveUp": "Move earlier",
+ "moveDown": "Move later",
+ "moreTasks": "{{count}} more tasks are retained in the queue",
"fileSync": "File Sync",
"rescan": "Rescan",
"rescanTitle": "Scan project files for external changes",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 81d36bb3..dc32ee25 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -185,6 +185,15 @@
"refreshFolderTooltip": "按自动监控相同规则重新扫描当前项目的资料文件夹。允许的新增或修改文件会加入提取队列;已删除的资料会走正常的 Wiki 与索引清理流程;随后重建文件树。",
"refreshFailed": "刷新原始资料失败:{{error}}",
"ingest": "提取到 Wiki",
+ "ingestStatus": {
+ "not-ingested": "未摄取",
+ "ingested": "已摄取",
+ "pending": "排队中",
+ "processing": "处理中",
+ "done": "已完成",
+ "failed": "失败",
+ "cancelled": "已取消"
+ },
"delete": "删除资料及相关 Wiki 页面",
"deleteConfirm": "删除「{{name}}」及其相关 Wiki 页面?\n\n此操作将:\n- 删除原始资料文件\n- 删除由该资料生成的 Wiki 页面\n- 更新 index.md",
"deleteFolder": "删除文件夹 {{name}}(递归)",
@@ -969,11 +978,21 @@
"resumeQueueTitle": "继续处理排队中的摄取任务",
"queueCompleteCount": "{{done}}/{{total}} 已完成",
"failedCount": "{{count}} 个失败",
+ "stoppedCount": "{{failed}} 个失败,{{cancelled}} 个已取消",
"cancelAll": "全部取消",
"cancelAllTitle": "取消所有排队和正在处理的任务",
- "cancelAllConfirm": "要取消全部 {{count}} 个排队/处理中摄取任务吗?正在处理任务产生的部分文件会被移除;失败任务会保留,之后仍可重试。",
- "retryFailed": "重试失败项",
- "retryFailedTitle": "重试所有失败的摄取任务",
+ "cancelAllConfirm": "要取消全部 {{count}} 个排队/处理中摄取任务吗?正在处理任务产生的部分文件会被移除;已取消任务会保留在队列中,之后可以重新启动。",
+ "retryFailed": "重启已停止任务",
+ "retryFailedTitle": "重新启动所有失败和已取消的摄取任务",
+ "selectAll": "全选",
+ "clearSelection": "清除选择",
+ "selectedCount": "已选择 {{count}} 项",
+ "restartSelected": "重新启动",
+ "cancelSelected": "取消",
+ "selectTask": "选择 {{name}}",
+ "moveUp": "提前",
+ "moveDown": "延后",
+ "moreTasks": "队列中还保留 {{count}} 个任务",
"fileSync": "文件同步",
"rescan": "重新扫描",
"rescanTitle": "扫描项目文件的外部变更",
diff --git a/src/lib/ingest-cache.ts b/src/lib/ingest-cache.ts
index eaa82d7d..4485a98d 100644
--- a/src/lib/ingest-cache.ts
+++ b/src/lib/ingest-cache.ts
@@ -38,6 +38,12 @@ async function loadCache(projectPath: string): Promise<CacheData> {
}
}
+/** Source identities with a recorded successful ingest result. */
+export async function listIngestedSourceIdentities(projectPath: string): Promise<string[]> {
+ const cache = await loadCache(projectPath)
+ return Object.keys(cache.entries)
+}
+
async function saveCache(projectPath: string, cache: CacheData): Promise<void> {
try {
await writeFile(cachePath(projectPath), JSON.stringify(cache, null, 2))
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index b595c3a1..a9850ac0 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -54,9 +54,12 @@ import {
enqueueIngest,
enqueueBatch,
retryTask,
+ retryTasks,
retryAllFailedTasks,
cancelTask,
+ cancelTasks,
cancelAllTasks,
+ movePendingTask,
clearCompletedTasks,
clearQueueState,
cleanupWrittenFiles,
@@ -268,7 +271,7 @@ describe("ingest-queue — retry & failure", () => {
})
describe("ingest-queue — cancel", () => {
- it("cancelTask removes a pending task without calling autoIngest", async () => {
+ it("cancelTask retains a pending task for restart without calling autoIngest", async () => {
mockAutoIngest.mockImplementation(() => new Promise(() => {})) // block first task
await enqueueBatch(TEST_ID, [
@@ -282,13 +285,93 @@ describe("ingest-queue — cancel", () => {
const second = queue.find((t) => t.sourcePath === "second.md")!
await cancelTask(second.id)
- expect(getQueue().find((t) => t.sourcePath === "second.md")).toBeUndefined()
+ expect(getQueue().find((t) => t.sourcePath === "second.md")?.status).toBe("cancelled")
expect(getQueue().find((t) => t.sourcePath === "first.md")).toBeDefined()
})
+
+ it("batch-cancelled tasks can be batch-restarted", async () => {
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
+ await enqueueBatch(TEST_ID, [
+ { sourcePath: "active.md", folderContext: "" },
+ { sourcePath: "b.md", folderContext: "" },
+ { sourcePath: "c.md", folderContext: "" },
+ ])
+ await flushMicrotasks(2)
+ const stopped = getQueue().filter((task) => task.status === "pending")
+
+ expect(await cancelTasks(stopped.map((task) => task.id))).toBe(2)
+ expect(getQueue().filter((task) => task.status === "cancelled")).toHaveLength(2)
+ expect(await retryTasks(stopped.map((task) => task.id))).toBe(2)
+ expect(getQueue().filter((task) => task.status === "pending")).toHaveLength(2)
+ })
+
+ it("enqueueing a cancelled source restarts the retained task without duplication", async () => {
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
+ await enqueueBatch(TEST_ID, [
+ { sourcePath: "active.md", folderContext: "" },
+ { sourcePath: "cancelled.md", folderContext: "old" },
+ ])
+ await flushMicrotasks(2)
+ const stopped = getQueue().find((task) => task.sourcePath === "cancelled.md")!
+ await cancelTask(stopped.id)
+
+ const restartedId = await enqueueIngest(TEST_ID, "cancelled.md", "new")
+
+ expect(restartedId).toBe(stopped.id)
+ expect(getQueue().filter((task) => task.sourcePath === "cancelled.md")).toHaveLength(1)
+ expect(getQueue().find((task) => task.id === stopped.id)).toMatchObject({
+ status: "pending",
+ folderContext: "new",
+ })
+ })
+
+ it("discards an old in-flight result when a cancelled task is immediately restarted", async () => {
+ let finishOldRun: ((files: string[]) => void) | undefined
+ mockAutoIngest
+ .mockImplementationOnce(
+ () => new Promise<string[]>((resolve) => {
+ finishOldRun = resolve
+ }),
+ )
+ .mockResolvedValueOnce(["wiki/restart-new.md"])
+
+ await enqueueIngest(TEST_ID, "restart.md")
+ await flushMicrotasks(2)
+ const task = getQueue()[0]
+ await cancelTask(task.id)
+ await retryTasks([task.id])
+
+ // Simulate a provider that ignores AbortSignal and completes the old run.
+ finishOldRun?.(["wiki/restart.md"])
+ await vi.waitFor(() => expect(mockAutoIngest).toHaveBeenCalledTimes(2))
+ await vi.waitFor(() => expect(getQueue()).toHaveLength(0))
+
+ expect(getQueueSummary().completed).toBe(1)
+ })
+
+ it("moves pending task priority without crossing the processing task", async () => {
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
+ await enqueueBatch(TEST_ID, [
+ { sourcePath: "active.md", folderContext: "" },
+ { sourcePath: "b.md", folderContext: "" },
+ { sourcePath: "c.md", folderContext: "" },
+ { sourcePath: "d.md", folderContext: "" },
+ ])
+ await flushMicrotasks(2)
+ const d = getQueue().find((task) => task.sourcePath === "d.md")!
+
+ expect(await movePendingTask(d.id, "up")).toBe(true)
+ expect(getQueue().map((task) => task.sourcePath)).toEqual([
+ "active.md",
+ "b.md",
+ "d.md",
+ "c.md",
+ ])
+ })
})
describe("ingest-queue — cancelAllTasks", () => {
- it("drops all pending and processing tasks but keeps failed ones", async () => {
+ it("retains pending and processing tasks as cancelled alongside failed ones", async () => {
// Block the processing task so it doesn't finish on its own.
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
@@ -305,10 +388,9 @@ describe("ingest-queue — cancelAllTasks", () => {
const removed = await cancelAllTasks()
- expect(removed).toBe(2) // a (processing) + b (pending) gone
- expect(getQueue()).toHaveLength(1)
- expect(getQueue()[0].sourcePath).toBe("c.md")
- expect(getQueue()[0].status).toBe("failed")
+ expect(removed).toBe(2)
+ expect(getQueue()).toHaveLength(3)
+ expect(getQueue().map((task) => task.status)).toEqual(["cancelled", "cancelled", "failed"])
})
it("returns 0 when the queue is empty", async () => {
@@ -840,7 +922,8 @@ describe("ingest-queue — pause/resume processing", () => {
await flushMicrotasks(10)
expect(mockAutoIngest).toHaveBeenCalledTimes(2)
expect(mockAutoIngest.mock.calls[1][1]).toBe(`${TEST_PATH}/fresh.md`)
- expect(getQueue()).toHaveLength(0)
+ expect(getQueue()).toHaveLength(1)
+ expect(getQueue()[0]).toMatchObject({ sourcePath: "only.md", status: "cancelled" })
})
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 4a34a05f..4d7f3273 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -15,7 +15,7 @@ export interface IngestTask {
projectId: string
sourcePath: string // relative to project: "raw/sources/folder/file.pdf"
folderContext: string // e.g. "AI-Research > papers" or ""
- status: "pending" | "processing" | "done" | "failed"
+ status: "pending" | "processing" | "done" | "failed" | "cancelled"
addedAt: number
error: string | null
retryCount: number
@@ -47,6 +47,11 @@ let currentProjectId = ""
let currentProjectPath = ""
let currentAbortController: AbortController | null = null
let lastWrittenFiles: string[] = [] // track files written by current ingest for cleanup
+/** Task runs cancelled while still inside autoIngest. This is separate from
+ * the persisted task status because the user may restart a retained task
+ * before the old run observes its AbortSignal. In that case the old output
+ * must still be discarded before the restarted pending task can run. */
+let cancelledInFlightTaskIds = new Set<string>()
let completedSinceIdle = 0
// Track whether any task has been processed since the last drain.
// Prevents the sweep from running on every idle/no-op call.
@@ -130,20 +135,20 @@ function upsertQueuedIngestTask(
resetQueueAccounting()
}
const normalizedSourcePath = normalizeSourcePathForQueue(sourcePath)
- const pendingOrFailed = queue.find((t) =>
+ const pendingOrStopped = queue.find((t) =>
t.projectId === projectId &&
- (t.status === "pending" || t.status === "failed") &&
+ (t.status === "pending" || t.status === "failed" || t.status === "cancelled") &&
sameQueuedSourcePath(t.sourcePath, normalizedSourcePath)
)
- if (pendingOrFailed) {
- restoredPausedTaskIds.delete(pendingOrFailed.id)
- pendingOrFailed.sourcePath = normalizedSourcePath
- pendingOrFailed.folderContext = folderContext || pendingOrFailed.folderContext
- pendingOrFailed.status = "pending"
- pendingOrFailed.error = null
- pendingOrFailed.retryCount = 0
- return pendingOrFailed.id
+ if (pendingOrStopped) {
+ restoredPausedTaskIds.delete(pendingOrStopped.id)
+ pendingOrStopped.sourcePath = normalizedSourcePath
+ pendingOrStopped.folderContext = folderContext || pendingOrStopped.folderContext
+ pendingOrStopped.status = "pending"
+ pendingOrStopped.error = null
+ pendingOrStopped.retryCount = 0
+ return pendingOrStopped.id
}
const processingTask = queue.find((t) =>
@@ -272,6 +277,29 @@ export async function retryTask(taskId: string): Promise<void> {
processNext(currentProjectId)
}
+/** Requeue selected failed or cancelled tasks in their existing priority order. */
+export async function retryTasks(taskIds: readonly string[]): Promise<number> {
+ if (!currentProjectId) return 0
+ const selected = new Set(taskIds)
+ let requeued = 0
+ for (const task of queue) {
+ if (
+ task.projectId !== currentProjectId ||
+ !selected.has(task.id) ||
+ (task.status !== "failed" && task.status !== "cancelled")
+ ) continue
+ restoredPausedTaskIds.delete(task.id)
+ task.status = "pending"
+ task.error = null
+ task.retryCount = 0
+ requeued += 1
+ }
+ if (requeued === 0) return 0
+ await saveQueue(currentProjectPath)
+ processNext(currentProjectId)
+ return requeued
+}
+
/**
* Retry every failed task for the active project.
* Returns the number of tasks requeued.
@@ -296,6 +324,36 @@ export async function retryAllFailedTasks(): Promise<number> {
return requeued
}
+export async function retryAllStoppedTasks(): Promise<number> {
+ return retryTasks(
+ queue
+ .filter(
+ (task) =>
+ task.projectId === currentProjectId &&
+ (task.status === "failed" || task.status === "cancelled"),
+ )
+ .map((task) => task.id),
+ )
+}
+
+/** Move a pending task one slot in queue priority without crossing active work. */
+export async function movePendingTask(
+ taskId: string,
+ direction: "up" | "down",
+): Promise<boolean> {
+ const pending = queue.filter(
+ (task) => task.projectId === currentProjectId && task.status === "pending",
+ )
+ const position = pending.findIndex((task) => task.id === taskId)
+ const swapPosition = direction === "up" ? position - 1 : position + 1
+ if (position < 0 || swapPosition < 0 || swapPosition >= pending.length) return false
+ const firstIndex = queue.findIndex((task) => task.id === pending[position].id)
+ const secondIndex = queue.findIndex((task) => task.id === pending[swapPosition].id)
+ ;[queue[firstIndex], queue[secondIndex]] = [queue[secondIndex], queue[firstIndex]]
+ await saveQueue(currentProjectPath)
+ return true
+}
+
/**
* Cancel a pending or processing task.
* If processing, aborts the LLM call and cleans up generated files.
@@ -305,7 +363,9 @@ export async function cancelTask(taskId: string): Promise<void> {
if (!task) return
if (task.projectId !== currentProjectId) return
- if (task.status === "processing") {
+ const wasProcessing = task.status === "processing"
+ if (wasProcessing) {
+ cancelledInFlightTaskIds.add(task.id)
// Abort the in-progress LLM call
if (currentAbortController) {
currentAbortController.abort()
@@ -319,19 +379,57 @@ export async function cancelTask(taskId: string): Promise<void> {
lastWrittenFiles = []
}
- processing = false
}
restoredPausedTaskIds.delete(taskId)
- queue = queue.filter((t) => t.id !== taskId)
+ task.status = "cancelled"
+ task.error = null
if (!queue.some((t) => t.status === "pending" || t.status === "processing")) {
paused = false
clearUsageLimitAutoResume()
}
await saveQueue(currentProjectPath)
- console.log(`[Ingest Queue] Cancelled: ${task.sourcePath}`)
+ console.log(`[Ingest Queue] Cancelled and retained for restart: ${task.sourcePath}`)
- processNext(currentProjectId)
+ // The in-flight run owns `processing` until it observes cancellation.
+ // Starting another task here would let the old abort handler race it.
+ if (!wasProcessing) processNext(currentProjectId)
+}
+
+/** Cancel selected pending/processing tasks while retaining them for restart. */
+export async function cancelTasks(taskIds: readonly string[]): Promise<number> {
+ const selected = new Set(taskIds)
+ const targets = queue.filter(
+ (task) =>
+ task.projectId === currentProjectId &&
+ selected.has(task.id) &&
+ (task.status === "pending" || task.status === "processing"),
+ )
+ if (targets.length === 0) return 0
+ const hadProcessingTask = targets.some((task) => task.status === "processing")
+ for (const task of targets) {
+ if (task.status === "processing") cancelledInFlightTaskIds.add(task.id)
+ }
+ if (hadProcessingTask && currentAbortController) {
+ currentAbortController.abort()
+ currentAbortController = null
+ }
+ if (hadProcessingTask && lastWrittenFiles.length > 0) {
+ await cleanupWrittenFiles(currentProjectPath, lastWrittenFiles)
+ lastWrittenFiles = []
+ }
+ for (const task of targets) {
+ restoredPausedTaskIds.delete(task.id)
+ task.status = "cancelled"
+ task.error = null
+ }
+ if (!queue.some((task) => task.status === "pending" || task.status === "processing")) {
+ paused = false
+ clearUsageLimitAutoResume()
+ }
+ await saveQueue(currentProjectPath)
+ if (!hadProcessingTask) processNext(currentProjectId)
+ return targets.length
}
/**
@@ -345,35 +443,46 @@ export async function clearCompletedTasks(): Promise<void> {
/**
* Cancel everything that's not finished in the active project's queue:
* aborts the running task (if any), cleans up its partial output, and
- * drops every pending + processing item.
+ * retains every pending + processing item as cancelled so it can be restarted.
*
* Failed tasks are retained so the user can still see / retry them.
* Returns the number of tasks removed from the queue.
*/
export async function cancelAllTasks(): Promise<number> {
+ const hadProcessingTask = queue.some(
+ (task) => task.projectId === currentProjectId && task.status === "processing",
+ )
+ for (const task of queue) {
+ if (task.projectId === currentProjectId && task.status === "processing") {
+ cancelledInFlightTaskIds.add(task.id)
+ }
+ }
if (currentAbortController) {
currentAbortController.abort()
currentAbortController = null
}
- processing = false
if (lastWrittenFiles.length > 0) {
await cleanupWrittenFiles(currentProjectPath, lastWrittenFiles)
lastWrittenFiles = []
}
- const before = queue.length
+ let cancelled = 0
for (const task of queue) {
- if (task.status !== "failed") restoredPausedTaskIds.delete(task.id)
+ if (task.status !== "pending" && task.status !== "processing") continue
+ restoredPausedTaskIds.delete(task.id)
+ task.status = "cancelled"
+ task.error = null
+ cancelled += 1
}
- queue = queue.filter((t) => t.status === "failed")
paused = false
clearUsageLimitAutoResume()
- const removed = before - queue.length
+ if (!hadProcessingTask) processing = false
await saveQueue(currentProjectPath)
- console.log(`[Ingest Queue] Cancelled all: ${removed} tasks removed`)
- return removed
+ console.log(`[Ingest Queue] Cancelled all and retained: ${cancelled} tasks`)
+ if (!hadProcessingTask) processNext(currentProjectId)
+ return cancelled
}
/**
@@ -436,6 +545,7 @@ export function getQueueSummary(): {
pending: number
processing: number
failed: number
+ cancelled: number
completed: number
total: number
paused: boolean
@@ -445,6 +555,7 @@ export function getQueueSummary(): {
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)
@@ -453,6 +564,7 @@ export function getQueueSummary(): {
pending,
processing: processingCount,
failed,
+ cancelled,
completed: completedSinceIdle,
total: activeTotal,
paused: paused || (restoredBacklogWaiting && processingCount === 0),
@@ -477,6 +589,7 @@ export function clearQueueState(): void {
}
queue = []
restoredPausedTaskIds.clear()
+ cancelledInFlightTaskIds.clear()
processing = false
paused = false
currentProjectId = ""
@@ -529,6 +642,7 @@ export async function pauseQueue(): Promise<void> {
queue = []
restoredPausedTaskIds.clear()
+ cancelledInFlightTaskIds.clear()
currentProjectId = ""
currentProjectPath = ""
lastWrittenFiles = []
@@ -555,6 +669,7 @@ export async function restoreQueue(
// pauseQueue, but clearing again costs nothing).
queue = []
restoredPausedTaskIds.clear()
+ cancelledInFlightTaskIds.clear()
processing = false
clearUsageLimitAutoResume()
// Every project loads un-paused. Pause is a current-session control;
@@ -757,6 +872,19 @@ async function processNext(projectId: string): Promise<void> {
if (currentProjectId !== projectId) return
lastWrittenFiles = writtenFiles
+ const currentTask = queue.find((task) => task.id === next.id)
+ if (cancelledInFlightTaskIds.delete(next.id) || currentTask?.status === "cancelled") {
+ if (lastWrittenFiles.length > 0) {
+ await cleanupWrittenFiles(pp, lastWrittenFiles)
+ lastWrittenFiles = []
+ }
+ currentAbortController = null
+ processing = false
+ await saveQueue(pp)
+ processNext(projectId)
+ return
+ }
+
// Safety net: autoIngest resolving with zero files means nothing
// was really ingested (e.g. abort during webview refresh where the
// historical `return []` error path masqueraded as success). Treat
@@ -768,6 +896,7 @@ async function processNext(projectId: string): Promise<void> {
// Success: remove from queue
currentAbortController = null
lastWrittenFiles = []
+ cancelledInFlightTaskIds.delete(next.id)
queue = queue.filter((t) => t.id !== next.id)
completedSinceIdle++
processedSinceDrain = true
@@ -778,6 +907,16 @@ async function processNext(projectId: string): Promise<void> {
if (currentProjectId !== projectId) return
currentAbortController = null
const currentTask = queue.find((t) => t.id === next.id)
+ if (cancelledInFlightTaskIds.delete(next.id) || currentTask?.status === "cancelled") {
+ if (lastWrittenFiles.length > 0) {
+ await cleanupWrittenFiles(pp, lastWrittenFiles)
+ lastWrittenFiles = []
+ }
+ processing = false
+ await saveQueue(pp)
+ processNext(projectId)
+ return
+ }
if (currentTask?.status === "pending") {
if (lastWrittenFiles.length > 0) {
await cleanupWrittenFiles(pp, lastWrittenFiles)