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
test: Tier 2 remainder + Tier 3 race/concurrency suite
nash_su7ffdf1ecf0ec
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.tsnew file mode 100644index 00000000..d26565c0--- /dev/null+++ b/src/lib/ingest-queue.test.ts@@ -0,0 +1,323 @@+import { describe, it, expect, beforeEach, vi } from "vitest"+import { flushMicrotasks } from "@/test-helpers/deferred"++// Mock autoIngest so tests control success/failure timing.+vi.mock("./ingest", () => ({+ autoIngest: vi.fn(),+}))++// Mock fs so we don't hit the real filesystem.+vi.mock("@/commands/fs", () => ({+ readFile: vi.fn(),+ writeFile: vi.fn(),+ listDirectory: vi.fn(),+ deleteFile: vi.fn(),+}))++// Mock sweep-reviews since the queue drain dynamically imports it. The+// sweep itself has its own test file; here we just confirm it's triggered.+vi.mock("./sweep-reviews", () => ({+ sweepResolvedReviews: vi.fn().mockResolvedValue(0),+}))++import {+ enqueueIngest,+ enqueueBatch,+ retryTask,+ cancelTask,+ clearCompletedTasks,+ clearQueueState,+ getQueue,+ getQueueSummary,+ restoreQueue,+} from "./ingest-queue"+import { autoIngest } from "./ingest"+import { readFile, writeFile } from "@/commands/fs"+import { sweepResolvedReviews } from "./sweep-reviews"+import { useWikiStore } from "@/stores/wiki-store"++const mockAutoIngest = vi.mocked(autoIngest)+const mockReadFile = vi.mocked(readFile)+const mockWriteFile = vi.mocked(writeFile)+const mockSweep = vi.mocked(sweepResolvedReviews)++beforeEach(() => {+ clearQueueState()+ mockAutoIngest.mockReset()+ mockReadFile.mockReset()+ mockWriteFile.mockReset()+ mockSweep.mockReset()+ mockSweep.mockResolvedValue(0)++ // Default: persisted queue file doesn't exist+ mockReadFile.mockRejectedValue(new Error("ENOENT"))+ mockWriteFile.mockResolvedValue(undefined as unknown as void)++ // Default: a valid LLM config so processNext doesn't reject.+ useWikiStore.getState().setLlmConfig({+ provider: "openai",+ apiKey: "test-key",+ model: "gpt-4",+ ollamaUrl: "",+ customEndpoint: "",+ maxContextSize: 128000,+ })+})++describe("ingest-queue — enqueue & basic processing", () => {+ it("enqueueIngest adds a pending task and triggers processing", async () => {+ mockAutoIngest.mockResolvedValue([])++ const id = await enqueueIngest("/project", "raw/sources/a.md")+ expect(id).toMatch(/^ingest-/)++ // Let the async processing loop run+ await flushMicrotasks(10)++ // Task should have been processed and removed+ expect(mockAutoIngest).toHaveBeenCalledOnce()+ expect(getQueue()).toHaveLength(0)+ })++ it("persists queue to disk on enqueue", async () => {+ mockAutoIngest.mockImplementation(() => new Promise(() => {})) // never resolves+ await enqueueIngest("/project", "a.md")+ await flushMicrotasks(2)++ // writeFile should have been called to save the queue+ const calls = mockWriteFile.mock.calls+ expect(calls.length).toBeGreaterThan(0)+ const queuePath = calls[0][0]+ expect(queuePath).toContain(".llm-wiki/ingest-queue.json")+ })++ it("enqueueBatch queues multiple tasks and processes them serially", async () => {+ mockAutoIngest.mockResolvedValue([])++ await enqueueBatch("/project", [+ { sourcePath: "a.md", folderContext: "" },+ { sourcePath: "b.md", folderContext: "" },+ { sourcePath: "c.md", folderContext: "" },+ ])++ await flushMicrotasks(50)++ expect(mockAutoIngest).toHaveBeenCalledTimes(3)+ expect(getQueue()).toHaveLength(0)+ })+})++describe("ingest-queue — retry & failure", () => {+ it("retries a failing task up to MAX_RETRIES=3 then marks failed", async () => {+ mockAutoIngest.mockRejectedValue(new Error("LLM error"))++ await enqueueIngest("/project", "bad.md")+ await flushMicrotasks(30)++ expect(mockAutoIngest).toHaveBeenCalledTimes(3)+ const queue = getQueue()+ expect(queue).toHaveLength(1)+ expect(queue[0].status).toBe("failed")+ expect(queue[0].error).toContain("LLM error")+ expect(queue[0].retryCount).toBe(3)+ })++ it("succeeds on retry after transient failure", async () => {+ mockAutoIngest+ .mockRejectedValueOnce(new Error("transient"))+ .mockRejectedValueOnce(new Error("transient"))+ .mockResolvedValueOnce([])++ await enqueueIngest("/project", "flaky.md")+ await flushMicrotasks(30)++ expect(mockAutoIngest).toHaveBeenCalledTimes(3)+ expect(getQueue()).toHaveLength(0)+ })++ it("retryTask resets a failed task to pending and reprocesses it", async () => {+ mockAutoIngest.mockRejectedValue(new Error("always fails"))++ await enqueueIngest("/project", "x.md")+ await flushMicrotasks(20)+ expect(getQueue()[0].status).toBe("failed")++ const taskId = getQueue()[0].id+ mockAutoIngest.mockResolvedValueOnce([])+ await retryTask("/project", taskId)+ await flushMicrotasks(10)++ expect(getQueue()).toHaveLength(0)+ })+})++describe("ingest-queue — cancel", () => {+ it("cancelTask removes a pending task without calling autoIngest", async () => {+ mockAutoIngest.mockImplementation(() => new Promise(() => {})) // block first task++ await enqueueBatch("/project", [+ { sourcePath: "first.md", folderContext: "" },+ { sourcePath: "second.md", folderContext: "" },+ ])+ await flushMicrotasks(2)++ // first.md is processing; cancel second.md (still pending)+ const queue = getQueue()+ const second = queue.find((t) => t.sourcePath === "second.md")!+ await cancelTask("/project", second.id)++ expect(getQueue().find((t) => t.sourcePath === "second.md")).toBeUndefined()+ expect(getQueue().find((t) => t.sourcePath === "first.md")).toBeDefined()+ })+})++describe("ingest-queue — clearCompletedTasks & summary", () => {+ it("getQueueSummary returns accurate counts", async () => {+ mockAutoIngest.mockRejectedValue(new Error("fail"))+ await enqueueIngest("/project", "fail.md")+ await flushMicrotasks(20)++ const summary = getQueueSummary()+ expect(summary.failed).toBe(1)+ expect(summary.pending).toBe(0)+ expect(summary.total).toBe(1)+ })++ it("clearCompletedTasks drops failed tasks", async () => {+ mockAutoIngest.mockRejectedValue(new Error("fail"))+ await enqueueIngest("/project", "f.md")+ await flushMicrotasks(20)++ expect(getQueue()).toHaveLength(1)+ await clearCompletedTasks("/project")+ expect(getQueue()).toHaveLength(0)+ })+})++describe("ingest-queue — queue-drain triggers review sweep", () => {+ it("calls sweepResolvedReviews once after a successful task drains the queue", async () => {+ mockAutoIngest.mockResolvedValue([])++ await enqueueIngest("/project", "ok.md")+ await flushMicrotasks(30)++ expect(mockSweep).toHaveBeenCalledOnce()+ expect(mockSweep).toHaveBeenCalledWith("/project", expect.any(AbortSignal))+ })++ it("does NOT trigger sweep when no task has been processed since the last drain", async () => {+ // No tasks enqueued — processedSinceDrain flag stays false+ // (We simulate an idle condition by enqueueing, processing, draining once)+ mockAutoIngest.mockResolvedValue([])+ await enqueueIngest("/project", "a.md")+ await flushMicrotasks(20)+ expect(mockSweep).toHaveBeenCalledTimes(1)++ // Now the queue is empty. Calling cancelTask on a nonexistent id is a+ // no-op but internally may call processNext → no drain fire (nothing+ // was processed since the last drain).+ await cancelTask("/project", "nonexistent")+ await flushMicrotasks(5)+ expect(mockSweep).toHaveBeenCalledTimes(1)+ })++ it("does NOT trigger sweep when all tasks fail (nothing was successfully ingested)", async () => {+ mockAutoIngest.mockRejectedValue(new Error("always fails"))++ await enqueueIngest("/project", "bad.md")+ await flushMicrotasks(30)++ expect(mockSweep).not.toHaveBeenCalled()+ })+})++describe("ingest-queue — clearQueueState", () => {+ it("clears pending tasks and resets processing flag", async () => {+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))+ await enqueueBatch("/project", [+ { sourcePath: "a.md", folderContext: "" },+ { sourcePath: "b.md", folderContext: "" },+ ])+ await flushMicrotasks(2)++ expect(getQueue().length).toBeGreaterThan(0)++ clearQueueState()+ expect(getQueue()).toHaveLength(0)+ })++ it("processedSinceDrain flag resets so a post-switch no-op won't trigger sweep", async () => {+ mockAutoIngest.mockResolvedValue([])+ await enqueueIngest("/project", "x.md")+ await flushMicrotasks(20)+ mockSweep.mockClear()++ clearQueueState()+ // Simulate new drain trigger on an empty queue — no sweep.+ await flushMicrotasks(5)+ expect(mockSweep).not.toHaveBeenCalled()+ })+})++describe("ingest-queue — restoreQueue", () => {+ it("resets in-memory state before loading, preventing cross-project bleed", async () => {+ // Seed in-memory state from project A+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))+ await enqueueIngest("/project-A", "a.md")+ await flushMicrotasks(2)+ expect(getQueue().length).toBeGreaterThan(0)++ // Now restore project B — should reset and load B's saved queue (empty)+ mockReadFile.mockRejectedValue(new Error("ENOENT"))+ await restoreQueue("/project-B")+ expect(getQueue()).toHaveLength(0)+ })++ it("converts 'processing' tasks back to 'pending' on restore (interrupted by app close)", async () => {+ const saved = [+ {+ id: "ingest-abc",+ sourcePath: "a.md",+ folderContext: "",+ status: "processing",+ addedAt: 0,+ error: null,+ retryCount: 0,+ },+ ]+ mockReadFile.mockResolvedValue(JSON.stringify(saved))+ // Prevent the reprocessing kickoff from completing forever:+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))++ await restoreQueue("/project")+ 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)+ })++ it("leaves 'failed' tasks as failed on restore", async () => {+ const saved = [+ {+ id: "ingest-x",+ sourcePath: "x.md",+ folderContext: "",+ status: "failed",+ addedAt: 0,+ error: "prior failure",+ retryCount: 3,+ },+ ]+ mockReadFile.mockResolvedValue(JSON.stringify(saved))++ await restoreQueue("/project")+ const queue = getQueue()+ expect(queue).toHaveLength(1)+ expect(queue[0].status).toBe("failed")+ expect(queue[0].error).toBe("prior failure")+ })+})diff --git a/src/lib/reset-project-state.test.ts b/src/lib/reset-project-state.test.tsnew file mode 100644index 00000000..e70a4e9a--- /dev/null+++ b/src/lib/reset-project-state.test.ts@@ -0,0 +1,171 @@+import { describe, it, expect, beforeEach, vi } from "vitest"+import { resetProjectState } from "./reset-project-state"+import { useChatStore } from "@/stores/chat-store"+import { useReviewStore } from "@/stores/review-store"+import { useActivityStore } from "@/stores/activity-store"+import { useResearchStore } from "@/stores/research-store"+import { getQueue, clearQueueState } from "./ingest-queue"++// Dynamic-import mocks: resetProjectState uses `import("@/lib/ingest-queue")`+// and `import("@/lib/graph-relevance")` at runtime. vi.mock hoists these+// so the promise resolves to our stub immediately.+vi.mock("./ingest-queue", async () => {+ const actual = await vi.importActual<typeof import("./ingest-queue")>("./ingest-queue")+ return {+ ...actual,+ clearQueueState: vi.fn(),+ }+})++vi.mock("./graph-relevance", () => ({+ clearGraphCache: vi.fn(),+}))++import { clearGraphCache } from "./graph-relevance"++const mockClearQueueState = vi.mocked(clearQueueState)+const mockClearGraphCache = vi.mocked(clearGraphCache)++beforeEach(() => {+ mockClearQueueState.mockReset()+ mockClearGraphCache.mockReset()+})++describe("resetProjectState — Zustand stores", () => {+ it("clears chat store conversations and messages", async () => {+ useChatStore.setState({+ conversations: [{ id: "c1", title: "x", createdAt: 0, updatedAt: 0 }],+ messages: [+ { id: "m1", role: "user", content: "hi", timestamp: 0, conversationId: "c1" },+ ],+ activeConversationId: "c1",+ isStreaming: true,+ streamingContent: "partial",+ mode: "ingest",+ ingestSource: "/some/file",+ })++ await resetProjectState()++ const chat = useChatStore.getState()+ expect(chat.conversations).toEqual([])+ expect(chat.messages).toEqual([])+ expect(chat.activeConversationId).toBeNull()+ expect(chat.isStreaming).toBe(false)+ expect(chat.streamingContent).toBe("")+ expect(chat.mode).toBe("chat")+ expect(chat.ingestSource).toBeNull()+ })++ it("clears review store items", async () => {+ useReviewStore.setState({+ items: [+ {+ id: "r1",+ type: "missing-page",+ title: "x",+ description: "",+ options: [],+ resolved: false,+ createdAt: 0,+ },+ ],+ })++ await resetProjectState()+ expect(useReviewStore.getState().items).toEqual([])+ })++ it("clears activity store items", async () => {+ useActivityStore.setState({+ items: [+ {+ id: "a1",+ type: "query",+ title: "t",+ status: "done",+ detail: "",+ filesWritten: [],+ createdAt: 0,+ },+ ],+ })++ await resetProjectState()+ expect(useActivityStore.getState().items).toEqual([])+ })++ it("clears research store tasks and closes panel", async () => {+ useResearchStore.setState({+ tasks: [+ {+ id: "t1",+ type: "gap",+ topic: "x",+ searchQueries: [],+ status: "pending",+ createdAt: 0,+ } as unknown as ReturnType<typeof useResearchStore.getState>["tasks"][number],+ ],+ panelOpen: true,+ })++ await resetProjectState()+ expect(useResearchStore.getState().tasks).toEqual([])+ expect(useResearchStore.getState().panelOpen).toBe(false)+ })+})++describe("resetProjectState — module-level caches are awaited", () => {+ it("calls clearQueueState before the returned promise resolves", async () => {+ await resetProjectState()+ expect(mockClearQueueState).toHaveBeenCalledOnce()+ })++ it("calls clearGraphCache before the returned promise resolves", async () => {+ await resetProjectState()+ expect(mockClearGraphCache).toHaveBeenCalledOnce()+ })++ it("ordering: when resolve() fires, BOTH module caches are already cleared", async () => {+ // This is the regression guard against fire-and-forget resets.+ // By the time the outer await returns, BOTH clears must be done.+ await resetProjectState()+ expect(mockClearQueueState).toHaveBeenCalledOnce()+ expect(mockClearGraphCache).toHaveBeenCalledOnce()+ })++ it("does not throw when clearQueueState itself throws — logs and continues", async () => {+ mockClearQueueState.mockImplementationOnce(() => {+ throw new Error("boom")+ })+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})++ await expect(resetProjectState()).resolves.toBeUndefined()+ expect(warnSpy).toHaveBeenCalled()+ expect(mockClearGraphCache).toHaveBeenCalledOnce() // still runs despite sibling failure+ warnSpy.mockRestore()+ })++ it("does not throw when clearGraphCache itself throws", async () => {+ mockClearGraphCache.mockImplementationOnce(() => {+ throw new Error("boom")+ })+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})++ await expect(resetProjectState()).resolves.toBeUndefined()+ expect(warnSpy).toHaveBeenCalled()+ warnSpy.mockRestore()+ })+})++describe("resetProjectState — leaves unrelated store keys alone", () => {+ it("preserves maxHistoryMessages on chat store (config, not project data)", async () => {+ useChatStore.setState({ maxHistoryMessages: 42 })+ await resetProjectState()+ expect(useChatStore.getState().maxHistoryMessages).toBe(42)+ })+})++// Silence the "unused import" warning on getQueue (kept for potential future tests).+void getQueuediff --git a/src/lib/sweep-reviews.race.test.ts b/src/lib/sweep-reviews.race.test.tsnew file mode 100644index 00000000..52f2defa--- /dev/null+++ b/src/lib/sweep-reviews.race.test.ts@@ -0,0 +1,366 @@+import { describe, it, expect, beforeEach, vi } from "vitest"+import { createDeferred, flushMicrotasks } from "@/test-helpers/deferred"+import { createStreamChatHarness } from "@/test-helpers/mock-stream-chat"++// Mock streamChat via the harness (installed via vi.mock below)+const harness = createStreamChatHarness()+vi.mock("./llm-client", () => ({+ streamChat: (...args: unknown[]) => harness.mock(...args),+}))++// Mock fs: listDirectory for buildWikiIndex, readFile for page content+vi.mock("@/commands/fs", () => ({+ readFile: vi.fn(),+ writeFile: vi.fn(),+ listDirectory: vi.fn(),+}))++import { sweepResolvedReviews } from "./sweep-reviews"+import { useWikiStore } from "@/stores/wiki-store"+import { useReviewStore, type ReviewItem } from "@/stores/review-store"+import { listDirectory, readFile } from "@/commands/fs"+import type { FileNode } from "@/types/wiki"++const mockListDirectory = vi.mocked(listDirectory)+const mockReadFile = vi.mocked(readFile)++function fileNode(name: string): FileNode {+ return {+ name,+ path: `/project/wiki/${name}`,+ is_dir: false,+ children: [],+ } as FileNode+}++function addPending(items: Array<Partial<ReviewItem>>) {+ const input = items.map((p) => ({+ type: "missing-page" as ReviewItem["type"],+ title: "X",+ description: "",+ options: [],+ ...p,+ }))+ useReviewStore.getState().addItems(input)+}++function setProject(path: string) {+ useWikiStore.setState({+ project: {+ name: "p",+ path,+ createdAt: 0,+ purposeText: "",+ fileTree: [],+ } as unknown as ReturnType<typeof useWikiStore.getState>["project"],+ })+ useWikiStore.getState().setLlmConfig({+ provider: "openai",+ apiKey: "k",+ model: "m",+ ollamaUrl: "",+ customEndpoint: "",+ maxContextSize: 128000,+ })+}++/** Clear the API key so the LLM stage short-circuits without a call. */+function disableLlm() {+ useWikiStore.setState({+ llmConfig: {+ provider: "openai",+ apiKey: "",+ model: "",+ ollamaUrl: "",+ customEndpoint: "",+ maxContextSize: 0,+ },+ })+}++/** Wait until a condition is true, or throw after `maxTicks` microtask flushes. */+async function waitUntil(+ predicate: () => boolean,+ maxTicks: number = 50,+ perTick: number = 3,+): Promise<void> {+ for (let i = 0; i < maxTicks; i++) {+ if (predicate()) return+ await flushMicrotasks(perTick)+ }+ throw new Error(`waitUntil: predicate never became true after ${maxTicks} ticks`)+}++beforeEach(() => {+ harness.reset()+ mockListDirectory.mockReset()+ mockReadFile.mockReset()+ useReviewStore.setState({ items: [] })++ // Default: empty wiki dir, no files+ mockListDirectory.mockResolvedValue([])+ mockReadFile.mockResolvedValue("")+})++describe("sweep race — project-identity guard", () => {+ it("bails immediately if projectPath does not match current project", async () => {+ setProject("/project-A")+ addPending([{ title: "Missing page: Foo" }])++ const resolved = await sweepResolvedReviews("/project-B")+ expect(resolved).toBe(0)+ // Store untouched+ expect(useReviewStore.getState().items.filter((i) => i.resolved)).toHaveLength(0)+ })++ it("does not apply resolveItem if user switches projects mid-sweep (after buildWikiIndex)", async () => {+ setProject("/project-A")+ addPending([{ title: "Missing page: Foo" }])++ // Set up the wiki dir to contain foo.md so the rule stage WOULD have+ // resolved the review. The project switch should prevent that write.+ mockListDirectory.mockResolvedValue([fileNode("foo.md")])+ mockReadFile.mockResolvedValue("---\ntitle: Foo\n---\n")++ const sweepPromise = sweepResolvedReviews("/project-A")+ // Switch projects before sweep has a chance to finish+ setProject("/project-B")++ const resolved = await sweepPromise+ // After project switch, the identity guard aborts before any resolveItem+ expect(resolved).toBe(0)+ expect(useReviewStore.getState().items.every((i) => !i.resolved)).toBe(true)+ })++ it("bails before LLM stage if project path mismatches when entering stage 2", async () => {+ setProject("/project-A")+ addPending([{ title: "Ambiguous concept", type: "suggestion" }])++ // Pause buildWikiIndex so we can switch projects at a deterministic point.+ const listDirDeferred = createDeferred<FileNode[]>()+ mockListDirectory.mockReturnValue(listDirDeferred.promise)++ const sweepPromise = sweepResolvedReviews("/project-A")+ await flushMicrotasks(3)++ // Switch project BEFORE buildWikiIndex resolves+ useWikiStore.setState({ project: null })++ // Now let buildWikiIndex finish; the post-await identity guard should bail+ listDirDeferred.resolve([])++ const resolved = await sweepPromise+ expect(resolved).toBe(0)+ expect(harness.pending).toHaveLength(0)+ })+})++describe("sweep race — abort signal", () => {+ it("honors an abort signal that fires before the sweep starts", async () => {+ setProject("/project-A")+ addPending([{ title: "Something" }])++ const ac = new AbortController()+ ac.abort()+ const resolved = await sweepResolvedReviews("/project-A", ac.signal)+ expect(resolved).toBe(0)+ })++ it("does not invoke streamChat if aborted before stage 2", async () => {+ setProject("/project-A")+ addPending([{ title: "Cannot be rule-resolved" }])++ const ac = new AbortController()+ ac.abort()++ await sweepResolvedReviews("/project-A", ac.signal)+ expect(harness.pending).toHaveLength(0)+ })++ it("signal aborted during streamChat — harness sees abort, sweep returns 0 LLM resolutions", async () => {+ setProject("/project-A")+ addPending([{ title: "Concept needing LLM" }])++ const ac = new AbortController()+ const sweepPromise = sweepResolvedReviews("/project-A", ac.signal)++ // Wait until the harness has received the LLM call+ await flushMicrotasks(5)+ expect(harness.pending).toHaveLength(1)++ ac.abort()+ const result = await sweepPromise+ expect(result).toBe(0)+ expect(harness.anyAborted()).toBe(true)+ })+})++describe("sweep — rule-based auto-resolution", () => {+ it("auto-resolves a missing-page review when the page now exists by filename", async () => {+ setProject("/project")+ addPending([{ title: "Missing page: attention", type: "missing-page" }])++ mockListDirectory.mockResolvedValue([fileNode("attention.md")])+ mockReadFile.mockResolvedValue("no frontmatter")++ const resolved = await sweepResolvedReviews("/project")+ expect(resolved).toBe(1)++ const items = useReviewStore.getState().items+ expect(items[0].resolved).toBe(true)+ expect(items[0].resolvedAction).toBe("auto-resolved")+ })++ it("does not resolve when the page doesn't exist", async () => {+ setProject("/project")+ disableLlm() // prevent stage-2 LLM stage from running+ addPending([{ title: "Missing page: neverwritten", type: "missing-page" }])++ mockListDirectory.mockResolvedValue([fileNode("other.md")])+ mockReadFile.mockResolvedValue("")++ const resolved = await sweepResolvedReviews("/project")+ expect(resolved).toBe(0)+ expect(useReviewStore.getState().items[0].resolved).toBe(false)+ })+})++describe("sweep — LLM batch loop", () => {+ it("processes pending items in batches of JUDGE_BATCH_SIZE=40 and breaks when a batch resolves nothing", async () => {+ setProject("/project")+ // 80 pending items, none rule-resolvable (suggestion bypasses rule stage)+ const items = Array.from({ length: 80 }, (_, i) => ({+ type: "suggestion" as ReviewItem["type"],+ title: `Suggestion ${i}`,+ }))+ addPending(items)+ // Snapshot the original insertion order — this is what sweep's stillPending+ // will contain, and the batches splice from the FRONT of that array.+ const orderedIds = useReviewStore.getState().items.map((i) => i.id)++ const sweepPromise = sweepResolvedReviews("/project")+ await waitUntil(() => harness.pending.length === 1)++ // Batch 1 = items 0..39. Resolve the first 3.+ await harness.complete(JSON.stringify({ resolved: orderedIds.slice(0, 3) }))+ await waitUntil(() => harness.pending.length === 2)++ // Batch 2 = items 40..79. Resolve nothing → loop should break.+ await harness.complete(JSON.stringify({ resolved: [] }))++ const total = await sweepPromise+ expect(total).toBe(3)+ // Early-break: no third batch was fired+ expect(harness.pending).toHaveLength(2)+ })++ it("continues across batches when each resolves something", async () => {+ setProject("/project")+ const items = Array.from({ length: 120 }, (_, i) => ({+ type: "suggestion" as ReviewItem["type"],+ title: `S${i}`,+ }))+ addPending(items)+ const orderedIds = useReviewStore.getState().items.map((i) => i.id)++ const sweepPromise = sweepResolvedReviews("/project")++ // 120 items / 40 per batch = 3 batches. For each, resolve the first 5+ // ids of THAT batch's slice from the original insertion order.+ for (let batch = 0; batch < 3; batch++) {+ await waitUntil(() => harness.pending.length === batch + 1)+ const start = batch * 40+ const batchIds = orderedIds.slice(start, start + 40).slice(0, 5)+ await harness.complete(JSON.stringify({ resolved: batchIds }))+ }++ const total = await sweepPromise+ expect(total).toBe(15) // 5 per batch × 3 batches+ expect(harness.pending).toHaveLength(3)+ })++ it("caps at MAX_JUDGE_BATCHES=5 even if more batches would have content", async () => {+ setProject("/project")+ // 300 items — would be 8 batches at 40/each, but capped at 5+ const items = Array.from({ length: 300 }, (_, i) => ({+ type: "suggestion" as ReviewItem["type"],+ title: `S${i}`,+ }))+ addPending(items)+ const orderedIds = useReviewStore.getState().items.map((i) => i.id)++ const sweepPromise = sweepResolvedReviews("/project")++ for (let b = 0; b < 5; b++) {+ await waitUntil(() => harness.pending.length === b + 1)+ const batchIds = orderedIds.slice(b * 40, b * 40 + 40).slice(0, 2)+ await harness.complete(JSON.stringify({ resolved: batchIds }))+ }+ await sweepPromise++ // Exactly 5 LLM calls fired, not 8 (the cap)+ expect(harness.pending).toHaveLength(5)+ })+})++describe("sweep — resolveItem safety after project switch", () => {+ it("does not apply LLM results if project switched while LLM was running", async () => {+ setProject("/project-A")+ const items = Array.from({ length: 3 }, (_, i) => ({+ type: "suggestion" as ReviewItem["type"],+ title: `S${i}`,+ }))+ addPending(items)+ const aIds = useReviewStore.getState().items.map((i) => i.id)++ const ac = new AbortController()+ const sweepPromise = sweepResolvedReviews("/project-A", ac.signal)++ await flushMicrotasks(5)+ expect(harness.pending).toHaveLength(1)++ // Switch project mid-LLM: reset review store to B's state+ setProject("/project-B")+ useReviewStore.setState({ items: [] })+ // Also abort, as the real clearQueueState would+ ac.abort()++ // Complete the LLM call (ignored because aborted + project changed)+ await harness.complete(JSON.stringify({ resolved: aIds }))+ await sweepPromise++ // Nothing in the (now-B) store should be resolved+ expect(useReviewStore.getState().items).toHaveLength(0)+ })+})++describe("sweep — empty / no-op cases", () => {+ it("returns 0 and does not touch the LLM when there are no pending items", async () => {+ setProject("/project")+ const resolved = await sweepResolvedReviews("/project")+ expect(resolved).toBe(0)+ expect(harness.pending).toHaveLength(0)+ })++ it("returns 0 when LLM is not configured", async () => {+ setProject("/project")+ useWikiStore.setState({+ llmConfig: {+ provider: "openai",+ apiKey: "",+ model: "",+ ollamaUrl: "",+ customEndpoint: "",+ maxContextSize: 0,+ },+ })+ addPending([{ title: "X", type: "suggestion" }])++ const resolved = await sweepResolvedReviews("/project")+ expect(resolved).toBe(0)+ expect(harness.pending).toHaveLength(0)+ })+})++// Keep unused import silent+void createDeferreddiff --git a/src/test-helpers/deferred.ts b/src/test-helpers/deferred.tsnew file mode 100644index 00000000..b7afb399--- /dev/null+++ b/src/test-helpers/deferred.ts@@ -0,0 +1,45 @@+/**+ * A promise whose resolve/reject handles are exposed so tests can drive+ * completion timing manually. Essential for race/abort/concurrency tests+ * where we need to pause a long-running operation at a specific await point.+ */+export interface Deferred<T> {+ promise: Promise<T>+ resolve: (value: T) => void+ reject: (error: unknown) => void+ settled: boolean+}++export function createDeferred<T = void>(): Deferred<T> {+ let resolve!: (v: T) => void+ let reject!: (e: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ const d: Deferred<T> = {+ promise,+ resolve: (v) => {+ if (d.settled) return+ d.settled = true+ resolve(v)+ },+ reject: (e) => {+ if (d.settled) return+ d.settled = true+ reject(e)+ },+ settled: false,+ }+ return d+}++/**+ * Yield to the microtask queue so pending .then / await continuations run.+ * Use after triggering an async operation you want to observe mid-flight.+ */+export async function flushMicrotasks(ticks: number = 5): Promise<void> {+ for (let i = 0; i < ticks; i++) {+ await Promise.resolve()+ }+}diff --git a/src/test-helpers/mock-stream-chat.ts b/src/test-helpers/mock-stream-chat.tsnew file mode 100644index 00000000..02df759a--- /dev/null+++ b/src/test-helpers/mock-stream-chat.ts@@ -0,0 +1,101 @@+/**+ * Controllable streamChat mock for race / concurrency tests.+ *+ * Unlike the instant-response mocks used in Tier 5 prompt tests, this+ * harness lets each call HANG until the test manually resolves it with+ * `complete(response)` or `fail(error)`. Combine with AbortSignal to test+ * mid-flight cancellation.+ */+import { vi, type Mock } from "vitest"+import type { LlmConfig } from "@/stores/wiki-store"+import type { ChatMessage, StreamCallbacks } from "@/lib/llm-providers"+import { createDeferred, type Deferred } from "./deferred"++interface PendingCall {+ config: LlmConfig+ messages: ChatMessage[]+ callbacks: StreamCallbacks+ signal: AbortSignal | undefined+ deferred: Deferred<void>+ aborted: boolean+}++export interface StreamChatHarness {+ mock: Mock+ pending: PendingCall[]+ latest(): PendingCall | undefined+ complete(response: string, index?: number): Promise<void>+ fail(error: Error, index?: number): Promise<void>+ reset(): void+ /** True if any call saw its abort signal fire. */+ anyAborted(): boolean+}++export function createStreamChatHarness(): StreamChatHarness {+ const pending: PendingCall[] = []++ const mock = vi.fn(+ async (+ config: LlmConfig,+ messages: ChatMessage[],+ callbacks: StreamCallbacks,+ signal?: AbortSignal,+ ): Promise<void> => {+ const deferred = createDeferred<void>()+ const entry: PendingCall = {+ config,+ messages,+ callbacks,+ signal,+ deferred,+ aborted: false,+ }+ pending.push(entry)++ if (signal) {+ if (signal.aborted) {+ entry.aborted = true+ callbacks.onDone()+ deferred.resolve()+ } else {+ signal.addEventListener("abort", () => {+ entry.aborted = true+ callbacks.onDone()+ deferred.resolve()+ })+ }+ }++ await deferred.promise+ },+ )++ return {+ mock,+ pending,+ latest: () => pending[pending.length - 1],+ async complete(response: string, index?: number) {+ const i = index ?? pending.length - 1+ const call = pending[i]+ if (!call || call.deferred.settled) return+ call.callbacks.onToken(response)+ call.callbacks.onDone()+ call.deferred.resolve()+ // yield so caller's await can unwind+ await Promise.resolve()+ },+ async fail(error: Error, index?: number) {+ const i = index ?? pending.length - 1+ const call = pending[i]+ if (!call || call.deferred.settled) return+ call.callbacks.onError(error)+ call.deferred.resolve()+ await Promise.resolve()+ },+ reset() {+ pending.length = 0+ mock.mockClear()+ },+ anyAborted: () => pending.some((c) => c.aborted),+ }+}