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 4 real-FS integration tests
nash_su1afd1ae16d75
diff --git a/src/lib/ingest-queue.integration.test.ts b/src/lib/ingest-queue.integration.test.tsnew file mode 100644index 00000000..374cc0b6--- /dev/null+++ b/src/lib/ingest-queue.integration.test.ts@@ -0,0 +1,272 @@+/**+ * Tier 4 — real-FS integration tests for ingest queue persistence.+ *+ * Exercises the actual `.llm-wiki/ingest-queue.json` write/read round-trip+ * against Node fs, catching JSON escape / Unicode / directory-creation bugs+ * that memory mocks would miss.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"+import { realFs, createTempProject, readFileRaw, writeFileRaw, fileExists } from "@/test-helpers/fs-temp"+import { waitFor, flushIO } from "@/test-helpers/deferred"++vi.mock("@/commands/fs", () => realFs)++// Prevent real LLM calls — hang forever so tasks stay in "processing" state+// where we can inspect the persisted file before success removes them.+vi.mock("./ingest", () => ({+ autoIngest: vi.fn(),+}))++// Sweep is tested separately; stub so drains don't explode+vi.mock("./sweep-reviews", () => ({+ sweepResolvedReviews: vi.fn().mockResolvedValue(0),+}))++import {+ enqueueIngest,+ enqueueBatch,+ clearQueueState,+ restoreQueue,+ getQueue,+} from "./ingest-queue"+import { autoIngest } from "./ingest"+import { useWikiStore } from "@/stores/wiki-store"++const mockAutoIngest = vi.mocked(autoIngest)++let tmp: { path: string; cleanup: () => Promise<void> }++beforeEach(async () => {+ clearQueueState()+ mockAutoIngest.mockReset()+ // Hang forever so the task stays in "processing" state and the+ // persisted file isn't cleared by successful-completion.+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))++ tmp = await createTempProject("ingestqueue")++ useWikiStore.getState().setLlmConfig({+ provider: "openai",+ apiKey: "k",+ model: "m",+ ollamaUrl: "",+ customEndpoint: "",+ maxContextSize: 128000,+ })+})++afterEach(async () => {+ clearQueueState()+ await tmp.cleanup()+})++async function readQueueFile(): Promise<string> {+ return readFileRaw(`${tmp.path}/.llm-wiki/ingest-queue.json`)+}++describe("ingest-queue persistence — write", () => {+ it("writes .llm-wiki/ingest-queue.json after enqueue", async () => {+ await enqueueIngest(tmp.path, "raw/sources/a.md")+ await waitFor(async () => {+ try {+ const c = await readQueueFile()+ return JSON.parse(c).length === 1+ } catch {+ return false+ }+ })+ const parsed = JSON.parse(await readQueueFile())+ expect(parsed[0].sourcePath).toBe("raw/sources/a.md")+ })++ it("persists Unicode source paths without corruption", async () => {+ await enqueueBatch(tmp.path, [+ { sourcePath: "raw/sources/注意力机制.pdf", folderContext: "AI研究 > 论文" },+ { sourcePath: "raw/日本語.md", folderContext: "" },+ ])+ await waitFor(async () => {+ try {+ const c = await readQueueFile()+ return JSON.parse(c).length === 2+ } catch {+ return false+ }+ })+ const parsed = JSON.parse(await readQueueFile()) as Array<{ sourcePath: string; folderContext: string }>+ const paths = parsed.map((p) => p.sourcePath)+ expect(paths).toContain("raw/sources/注意力机制.pdf")+ expect(paths).toContain("raw/日本語.md")+ expect(parsed.map((p) => p.folderContext)).toContain("AI研究 > 论文")+ })++ it("auto-creates .llm-wiki/ directory when it doesn't exist", async () => {+ expect(await fileExists(`${tmp.path}/.llm-wiki`)).toBe(false)+ await enqueueIngest(tmp.path, "x.md")+ await waitFor(() => fileExists(`${tmp.path}/.llm-wiki/ingest-queue.json`))+ })++ it("each enqueue updates the persisted JSON in-place", async () => {+ await enqueueIngest(tmp.path, "first.md")+ await waitFor(async () => {+ try {+ return JSON.parse(await readQueueFile()).length === 1+ } catch {+ return false+ }+ })++ await enqueueIngest(tmp.path, "second.md")+ await waitFor(async () => {+ try {+ return JSON.parse(await readQueueFile()).length === 2+ } catch {+ return false+ }+ })++ const arr = JSON.parse(await readQueueFile()) as Array<{ sourcePath: string }>+ expect(arr.map((t) => t.sourcePath)).toEqual(+ expect.arrayContaining(["first.md", "second.md"]),+ )+ })+})++describe("ingest-queue persistence — restore round-trip", () => {+ it("restoreQueue reads back exactly what enqueue wrote", async () => {+ await enqueueBatch(tmp.path, [+ { sourcePath: "a.md", folderContext: "ctx-a" },+ { sourcePath: "b.md", folderContext: "ctx-b" },+ ])+ // Wait for disk state to stabilize+ await waitFor(async () => {+ try {+ return JSON.parse(await readQueueFile()).length === 2+ } catch {+ return false+ }+ })++ // Simulate app restart: wipe in-memory, restore from disk+ clearQueueState()+ expect(getQueue()).toHaveLength(0)++ await restoreQueue(tmp.path)+ const restored = getQueue()+ expect(restored).toHaveLength(2)+ expect(restored.map((t) => t.sourcePath).sort()).toEqual(["a.md", "b.md"])+ })++ it("converts 'processing' back to 'pending' when restoring (interrupted app close)", async () => {+ const saved = [+ {+ id: "ingest-abc",+ sourcePath: "interrupted.md",+ folderContext: "",+ status: "processing",+ addedAt: 0,+ error: null,+ retryCount: 0,+ },+ ]+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/ingest-queue.json`,+ JSON.stringify(saved, null, 2),+ )++ await restoreQueue(tmp.path)+ await flushIO(2)++ const restored = getQueue()+ expect(restored).toHaveLength(1)+ // After restore + kick-off, either still reset to 'pending' or+ // bumped back into 'processing' as processNext picks it up.+ expect(["pending", "processing"]).toContain(restored[0].status)+ })++ it("preserves 'failed' status on restore (does NOT auto-retry)", async () => {+ const saved = [+ {+ id: "ingest-x",+ sourcePath: "broken.md",+ folderContext: "",+ status: "failed",+ addedAt: 0,+ error: "LLM hit its rate limit",+ retryCount: 3,+ },+ ]+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/ingest-queue.json`,+ JSON.stringify(saved, null, 2),+ )++ await restoreQueue(tmp.path)+ const restored = getQueue()+ expect(restored[0].status).toBe("failed")+ expect(restored[0].error).toBe("LLM hit its rate limit")+ expect(restored[0].retryCount).toBe(3)+ })++ it("returns empty queue when the file doesn't exist", async () => {+ await restoreQueue(tmp.path)+ expect(getQueue()).toEqual([])+ })++ it("returns empty queue when the file is corrupted JSON", async () => {+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/ingest-queue.json`,+ "{not valid json at all",+ )+ await restoreQueue(tmp.path)+ expect(getQueue()).toEqual([])+ })++ it("round-trips Unicode + folder context correctly", async () => {+ await enqueueBatch(tmp.path, [+ { sourcePath: "raw/sources/注意力.pdf", folderContext: "研究 > 深度学习" },+ ])+ await waitFor(async () => {+ try {+ return JSON.parse(await readQueueFile()).length === 1+ } catch {+ return false+ }+ })+ // Verify on-disk state before we blow away memory+ const onDisk = JSON.parse(await readQueueFile()) as Array<{ sourcePath: string; folderContext: string }>+ expect(onDisk[0].sourcePath).toBe("raw/sources/注意力.pdf")+ expect(onDisk[0].folderContext).toBe("研究 > 深度学习")++ clearQueueState()+ await restoreQueue(tmp.path)++ const restored = getQueue()+ expect(restored).toHaveLength(1)+ expect(restored[0].sourcePath).toBe("raw/sources/注意力.pdf")+ expect(restored[0].folderContext).toBe("研究 > 深度学习")+ })+})++describe("ingest-queue persistence — cross-project isolation", () => {+ it("restoreQueue from project A does not leak into project B", async () => {+ const other = await createTempProject("ingestqueue-other")+ try {+ // Populate project A+ await enqueueIngest(tmp.path, "a.md")+ await waitFor(async () => {+ try {+ return JSON.parse(await readQueueFile()).length === 1+ } catch {+ return false+ }+ })+ expect(getQueue()).toHaveLength(1)++ // Restore project B (empty) — should see empty queue, not A's+ await restoreQueue(other.path)+ expect(getQueue()).toEqual([])+ } finally {+ await other.cleanup()+ }+ })+})diff --git a/src/lib/persist.integration.test.ts b/src/lib/persist.integration.test.tsnew file mode 100644index 00000000..f8db30fb--- /dev/null+++ b/src/lib/persist.integration.test.ts@@ -0,0 +1,249 @@+/**+ * Tier 4 — real-FS integration tests for persistence.+ *+ * Tests exercise saveReviewItems / loadReviewItems and saveChatHistory /+ * loadChatHistory against a REAL filesystem (temp dir per test). Mocks only+ * the Tauri invoke boundary — Node fs is the real deal. This catches bugs+ * that memory mocks can't: Unicode path handling, JSON escape round-trip,+ * directory auto-creation, legacy-format fallback.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"+import { realFs, createTempProject, readFileRaw, writeFileRaw, fileExists } from "@/test-helpers/fs-temp"+import type { ReviewItem } from "@/stores/review-store"+import type { Conversation, DisplayMessage } from "@/stores/chat-store"++vi.mock("@/commands/fs", () => realFs)++import {+ saveReviewItems,+ loadReviewItems,+ saveChatHistory,+ loadChatHistory,+} from "./persist"++let tmp: { path: string; cleanup: () => Promise<void> }++function makeReview(overrides: Partial<ReviewItem> = {}): ReviewItem {+ return {+ id: "r-1",+ type: "missing-page",+ title: "Attention",+ description: "",+ options: [],+ resolved: false,+ createdAt: 0,+ ...overrides,+ }+}++beforeEach(async () => {+ tmp = await createTempProject("persist")+})++afterEach(async () => {+ await tmp.cleanup()+})++describe("review persistence — round-trip", () => {+ it("save then load returns identical items", async () => {+ const items: ReviewItem[] = [+ makeReview({ id: "r-1", title: "Alpha" }),+ makeReview({ id: "r-2", title: "Beta", type: "duplicate" }),+ ]+ await saveReviewItems(tmp.path, items)+ const loaded = await loadReviewItems(tmp.path)+ expect(loaded).toEqual(items)+ })++ it("creates the .llm-wiki directory on first save", async () => {+ expect(await fileExists(`${tmp.path}/.llm-wiki`)).toBe(false)+ await saveReviewItems(tmp.path, [makeReview()])+ expect(await fileExists(`${tmp.path}/.llm-wiki/review.json`)).toBe(true)+ })++ it("returns empty array when the file is absent", async () => {+ const loaded = await loadReviewItems(tmp.path)+ expect(loaded).toEqual([])+ })++ it("returns empty array when the file is corrupted JSON", async () => {+ await writeFileRaw(`${tmp.path}/.llm-wiki/review.json`, "{not valid json")+ const loaded = await loadReviewItems(tmp.path)+ expect(loaded).toEqual([])+ })++ it("preserves Unicode titles through JSON round-trip", async () => {+ const items = [+ makeReview({ id: "r-zh", title: "注意力机制", description: "Transformer 核心" }),+ makeReview({ id: "r-ja", title: "これは日本語" }),+ makeReview({ id: "r-emoji", title: "Edge 🔥 case" }),+ ]+ await saveReviewItems(tmp.path, items)+ const loaded = await loadReviewItems(tmp.path)+ expect(loaded).toEqual(items)+ expect(loaded[0].title).toBe("注意力机制")+ })++ it("overwrites existing file on subsequent saves", async () => {+ await saveReviewItems(tmp.path, [makeReview({ id: "r-1", title: "Old" })])+ await saveReviewItems(tmp.path, [makeReview({ id: "r-2", title: "New" })])+ const loaded = await loadReviewItems(tmp.path)+ expect(loaded).toHaveLength(1)+ expect(loaded[0].title).toBe("New")+ })++ it("normalizes Windows-style paths (backslashes) in projectPath", async () => {+ // projectPath may arrive with backslashes on Windows. Use a forward-slash+ // tmp path (already normalized) but also double up slashes to confirm+ // the helpers survive unusual input.+ const windowsy = tmp.path.replace(/\//g, "\\")+ await saveReviewItems(windowsy, [makeReview({ id: "r-1" })])+ const loaded = await loadReviewItems(windowsy)+ expect(loaded).toHaveLength(1)+ })+})++describe("chat persistence — round-trip (new format)", () => {+ function makeConv(id: string, title: string = "conv"): Conversation {+ return { id, title, createdAt: 0, updatedAt: 1 }+ }+ function makeMsg(id: string, convId: string, content: string): DisplayMessage {+ return { id, role: "user", content, timestamp: 0, conversationId: convId }+ }++ it("writes conversations.json + per-conversation chats/<id>.json", async () => {+ await saveChatHistory(+ tmp.path,+ [makeConv("c1"), makeConv("c2")],+ [+ makeMsg("m1", "c1", "hello"),+ makeMsg("m2", "c1", "world"),+ makeMsg("m3", "c2", "other"),+ ],+ )+ expect(await fileExists(`${tmp.path}/.llm-wiki/conversations.json`)).toBe(true)+ expect(await fileExists(`${tmp.path}/.llm-wiki/chats/c1.json`)).toBe(true)+ expect(await fileExists(`${tmp.path}/.llm-wiki/chats/c2.json`)).toBe(true)+ })++ it("round-trips conversations + messages", async () => {+ const convs = [makeConv("c1", "Conv 1"), makeConv("c2", "Conv 2")]+ const msgs = [+ makeMsg("m1", "c1", "hi"),+ makeMsg("m2", "c2", "你好"),+ ]+ await saveChatHistory(tmp.path, convs, msgs)+ const loaded = await loadChatHistory(tmp.path)++ expect(loaded.conversations).toEqual(convs)+ // Messages may be returned in a different order (grouped by conv file),+ // so compare as sets.+ expect(loaded.messages).toEqual(expect.arrayContaining(msgs))+ expect(loaded.messages).toHaveLength(2)+ })++ it("caps each conversation's persisted messages at 100 (oldest dropped)", async () => {+ const convs = [makeConv("c1")]+ const msgs = Array.from({ length: 150 }, (_, i) =>+ makeMsg(`m${i}`, "c1", `msg ${i}`),+ )+ await saveChatHistory(tmp.path, convs, msgs)+ const loaded = await loadChatHistory(tmp.path)+ expect(loaded.messages).toHaveLength(100)+ // Should have kept the LAST 100 (m50 .. m149)+ expect(loaded.messages[0].id).toBe("m50")+ expect(loaded.messages[99].id).toBe("m149")+ })++ it("returns empty data when no persistence file exists", async () => {+ const loaded = await loadChatHistory(tmp.path)+ expect(loaded).toEqual({ conversations: [], messages: [] })+ })++ it("skips missing per-conversation files without throwing", async () => {+ // conversations.json references c1 + c2, but chats/c2.json is missing+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/conversations.json`,+ JSON.stringify([makeConv("c1"), makeConv("c2")]),+ )+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/chats/c1.json`,+ JSON.stringify([makeMsg("m1", "c1", "hi")]),+ )+ const loaded = await loadChatHistory(tmp.path)+ expect(loaded.conversations).toHaveLength(2)+ expect(loaded.messages).toHaveLength(1)+ })++ it("preserves Unicode content through round-trip", async () => {+ const convs = [makeConv("c1", "中文对话 🎌")]+ const msgs = [+ makeMsg("m1", "c1", "你好,世界 🌍"),+ makeMsg("m2", "c1", "これはテスト"),+ ]+ await saveChatHistory(tmp.path, convs, msgs)+ const loaded = await loadChatHistory(tmp.path)+ expect(loaded.conversations[0].title).toBe("中文对话 🎌")+ expect(loaded.messages[0].content).toBe("你好,世界 🌍")+ })+})++describe("chat persistence — legacy format fallback", () => {+ function makeConv(id: string): Conversation {+ return { id, title: "t", createdAt: 0, updatedAt: 1 }+ }+ function makeMsg(id: string, convId: string): DisplayMessage {+ return { id, role: "user", content: "c", timestamp: 0, conversationId: convId }+ }++ it("falls back to chat-history.json flat-array format", async () => {+ // Very old format: flat array of messages+ const legacyMessages = [+ { id: "m1", role: "user", content: "old", timestamp: 100, conversationId: "ignored" },+ { id: "m2", role: "assistant", content: "older", timestamp: 200, conversationId: "ignored" },+ ]+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/chat-history.json`,+ JSON.stringify(legacyMessages),+ )++ const loaded = await loadChatHistory(tmp.path)+ expect(loaded.conversations).toHaveLength(1)+ expect(loaded.conversations[0].id).toBe("default")+ expect(loaded.messages).toHaveLength(2)+ expect(loaded.messages[0].conversationId).toBe("default")+ })++ it("falls back to chat-history.json combined-object format", async () => {+ const old = {+ conversations: [makeConv("c1")],+ messages: [makeMsg("m1", "c1")],+ }+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/chat-history.json`,+ JSON.stringify(old),+ )++ const loaded = await loadChatHistory(tmp.path)+ expect(loaded.conversations).toHaveLength(1)+ expect(loaded.messages).toHaveLength(1)+ })++ it("new format wins over legacy when both exist", async () => {+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/chat-history.json`,+ JSON.stringify({ conversations: [makeConv("legacy")], messages: [] }),+ )+ await writeFileRaw(+ `${tmp.path}/.llm-wiki/conversations.json`,+ JSON.stringify([makeConv("new")]),+ )+ await writeFileRaw(`${tmp.path}/.llm-wiki/chats/new.json`, "[]")++ const loaded = await loadChatHistory(tmp.path)+ expect(loaded.conversations[0].id).toBe("new")+ })+})++// Keep readFileRaw exported (referenced for a future direct-inspection test)+void readFileRawdiff --git a/src/test-helpers/deferred.ts b/src/test-helpers/deferred.tsindex b7afb399..2467b9f5 100644--- a/src/test-helpers/deferred.ts+++ b/src/test-helpers/deferred.ts@@ -43,3 +43,29 @@ export async function flushMicrotasks(ticks: number = 5): Promise<void> {await Promise.resolve()}}++/**+ * Yield to the event loop (macrotasks) so real I/O promises (fs.writeFile,+ * network, etc.) get a chance to settle. Use after triggering an async+ * operation backed by libuv rather than pure promise continuations.+ */+export async function flushIO(ticks: number = 3): Promise<void> {+ for (let i = 0; i < ticks; i++) {+ await new Promise<void>((resolve) => setImmediate(resolve))+ }+}++/**+ * Wait until `predicate()` returns true, or throw after `maxAttempts`.+ * Yields the event loop between attempts so real I/O can land.+ */+export async function waitFor(+ predicate: () => boolean | Promise<boolean>,+ maxAttempts: number = 100,+): Promise<void> {+ for (let i = 0; i < maxAttempts; i++) {+ if (await predicate()) return+ await new Promise<void>((resolve) => setImmediate(resolve))+ }+ throw new Error(`waitFor: predicate never became true after ${maxAttempts} attempts`)+}diff --git a/src/test-helpers/fs-temp.ts b/src/test-helpers/fs-temp.tsnew file mode 100644index 00000000..290926e4--- /dev/null+++ b/src/test-helpers/fs-temp.ts@@ -0,0 +1,125 @@+/**+ * Real-filesystem adapter for @/commands/fs. Tests that want to exercise+ * the actual JSON / path round-trip (rather than a vi.mock memory stub)+ * should call `installRealFs()` then use a per-test temp directory via+ * `createTempProject()`.+ *+ * The Tauri fs commands are replaced with implementations backed by+ * node:fs/promises, operating on whatever path the caller passes. The+ * caller is responsible for using a temp-dir root to prevent tests from+ * touching each other's state.+ */+import fs from "node:fs/promises"+import path from "node:path"+import os from "node:os"+import type { FileNode } from "@/types/wiki"++async function buildTree(dir: string): Promise<FileNode[]> {+ let entries+ try {+ entries = await fs.readdir(dir, { withFileTypes: true })+ } catch {+ return []+ }++ const nodes: FileNode[] = []+ for (const entry of entries) {+ const full = path.join(dir, entry.name).replace(/\\/g, "/")+ if (entry.isDirectory()) {+ nodes.push({+ name: entry.name,+ path: full,+ is_dir: true,+ children: await buildTree(full),+ } as FileNode)+ } else {+ nodes.push({+ name: entry.name,+ path: full,+ is_dir: false,+ children: [],+ } as FileNode)+ }+ }+ return nodes+}++/**+ * Implementations of the @/commands/fs API backed by node:fs.+ * Import this from a test file that calls `vi.mock("@/commands/fs", ...)`.+ */+export const realFs = {+ readFile: async (p: string): Promise<string> => {+ return fs.readFile(p, "utf-8")+ },+ writeFile: async (p: string, contents: string): Promise<void> => {+ await fs.mkdir(path.dirname(p), { recursive: true })+ await fs.writeFile(p, contents, "utf-8")+ },+ listDirectory: async (p: string): Promise<FileNode[]> => {+ return buildTree(p)+ },+ copyFile: async (source: string, destination: string): Promise<void> => {+ await fs.mkdir(path.dirname(destination), { recursive: true })+ await fs.copyFile(source, destination)+ },+ preprocessFile: async (p: string): Promise<string> => {+ return fs.readFile(p, "utf-8")+ },+ deleteFile: async (p: string): Promise<void> => {+ await fs.unlink(p).catch(() => {})+ },+ findRelatedWikiPages: async (): Promise<string[]> => {+ return []+ },+ createDirectory: async (p: string): Promise<void> => {+ await fs.mkdir(p, { recursive: true })+ },+ createProject: async () => {+ throw new Error("createProject not supported in tests")+ },+ openProject: async () => {+ throw new Error("openProject not supported in tests")+ },+ clipServerStatus: async (): Promise<string> => "ok",+}++/**+ * Create a fresh unique temp directory for a single test. Returns the+ * absolute path (with forward slashes) and a cleanup function.+ */+export async function createTempProject(label: string = "proj"): Promise<{+ path: string+ cleanup: () => Promise<void>+}> {+ const prefix = path.join(os.tmpdir(), `llmwiki-${label}-`)+ const dir = await fs.mkdtemp(prefix)+ const normalized = dir.replace(/\\/g, "/")+ return {+ path: normalized,+ cleanup: async () => {+ await fs.rm(normalized, { recursive: true, force: true }).catch(() => {})+ },+ }+}++/** Read a file directly (bypasses the mocked API) — used in assertions. */+export async function readFileRaw(p: string): Promise<string> {+ return fs.readFile(p, "utf-8")+}++/** Write a file directly (bypasses the mocked API) — used in fixture setup. */+export async function writeFileRaw(p: string, contents: string): Promise<void> {+ await fs.mkdir(path.dirname(p), { recursive: true })+ await fs.writeFile(p, contents, "utf-8")+}++/** Check if a file exists on disk. */+export async function fileExists(p: string): Promise<boolean> {+ try {+ await fs.access(p)+ return true+ } catch {+ return false+ }+}