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

test: add Tier 1+2 suite — pure functions and store behavior

nash_su84025ea5d23a
diff --git a/package-lock.json b/package-lock.json
index 8596016f..da3a079e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "llm-wiki",
- "version": "0.2.0",
+ "version": "0.3.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "llm-wiki",
- "version": "0.2.0",
+ "version": "0.3.1",
"dependencies": {
"@base-ui/react": "^1.3.0",
"@fontsource-variable/geist": "^5.2.8",
diff --git a/src/lib/detect-language.test.ts b/src/lib/detect-language.test.ts
new file mode 100644
index 00000000..ef29db5b
--- /dev/null
+++ b/src/lib/detect-language.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect } from "vitest"
+import { detectLanguage } from "./detect-language"
+
+describe("detectLanguage", () => {
+ describe("defaults", () => {
+ it("returns English for empty string", () => {
+ expect(detectLanguage("")).toBe("English")
+ })
+
+ it("returns English for pure ASCII without language clues", () => {
+ expect(detectLanguage("abc xyz 123")).toBe("English")
+ })
+ })
+
+ describe("non-Latin scripts", () => {
+ it("detects Chinese (CJK Unified Ideographs)", () => {
+ expect(detectLanguage("注意力机制是什么")).toBe("Chinese")
+ })
+
+ it("detects Japanese (Hiragana)", () => {
+ expect(detectLanguage("これはテストです")).toBe("Japanese")
+ })
+
+ it("detects Korean (Hangul)", () => {
+ expect(detectLanguage("안녕하세요")).toBe("Korean")
+ })
+
+ it("detects Arabic", () => {
+ expect(detectLanguage("مرحبا بالعالم")).toBe("Arabic")
+ })
+
+ it("detects Thai", () => {
+ expect(detectLanguage("สวัสดีครับ")).toBe("Thai")
+ })
+
+ it("detects Hindi (Devanagari)", () => {
+ expect(detectLanguage("नमस्ते दुनिया")).toBe("Hindi")
+ })
+
+ it("detects Russian (Cyrillic)", () => {
+ expect(detectLanguage("привет мир")).toBe("Russian")
+ })
+
+ it("detects Greek", () => {
+ expect(detectLanguage("Γειά σου κόσμε")).toBe("Greek")
+ })
+
+ it("requires at least 2 non-Latin chars to commit", () => {
+ // Single CJK char alone falls through to Latin detection, then English
+ expect(detectLanguage("x中")).toBe("English")
+ })
+
+ it("picks the dominant script when mixed", () => {
+ // Mostly Chinese with a few English words
+ expect(detectLanguage("机器学习 machine learning 深度学习 神经网络")).toBe("Chinese")
+ })
+ })
+
+ describe("Latin-script languages", () => {
+ it("detects Vietnamese via hook mark (ử, ả)", () => {
+ expect(detectLanguage("Xử lý nước thải")).toBe("Vietnamese")
+ })
+
+ it("detects Vietnamese via tone-combination marks (ệ, ớ)", () => {
+ expect(detectLanguage("Việt Nam là một quốc gia xinh đẹp")).toBe("Vietnamese")
+ })
+
+ it("detects French via word patterns (no shared diacritics)", () => {
+ expect(detectLanguage("le chat noir et les chiens blancs, un homme et une femme")).toBe("French")
+ })
+
+ it("detects French via its own diacritics (é, è, ê, à)", () => {
+ // Regression guard: these chars must NOT be misclassified as Vietnamese.
+ expect(detectLanguage("le chat est là, les étudiants préfèrent le café")).toBe("French")
+ })
+
+ it("detects German via word patterns", () => {
+ expect(detectLanguage("der Hund und die Katze sind nicht das Problem")).toBe("German")
+ })
+
+ it("detects Spanish via word patterns", () => {
+ expect(detectLanguage("el nino y los libros del colegio que son para todos")).toBe("Spanish")
+ })
+
+ it("detects Polish via diacritics", () => {
+ expect(detectLanguage("dzień dobry świat")).toBe("Polish")
+ })
+
+ it("detects Portuguese with ã / ç (regression: no longer misclassified as VN)", () => {
+ expect(detectLanguage("o coração do Brasil é um lugar de paz e que encanta")).toBe("Portuguese")
+ })
+ })
+
+ describe("edge cases", () => {
+ it("ignores plain ASCII digits and punctuation", () => {
+ expect(detectLanguage("123 !@#$")).toBe("English")
+ })
+
+ it("handles very long pure-ASCII strings", () => {
+ expect(detectLanguage("a".repeat(10000))).toBe("English")
+ })
+ })
+})
diff --git a/src/lib/output-language.test.ts b/src/lib/output-language.test.ts
new file mode 100644
index 00000000..3bf753c7
--- /dev/null
+++ b/src/lib/output-language.test.ts
@@ -0,0 +1,91 @@
+import { describe, it, expect, beforeEach } from "vitest"
+import { getOutputLanguage, buildLanguageDirective, buildLanguageReminder } from "./output-language"
+import { useWikiStore } from "@/stores/wiki-store"
+
+// Reset the outputLanguage back to "auto" before each test so tests can't
+// leak state into one another via the shared Zustand store.
+beforeEach(() => {
+ useWikiStore.getState().setOutputLanguage("auto")
+})
+
+describe("getOutputLanguage", () => {
+ it("uses the explicit user setting verbatim (Chinese)", () => {
+ useWikiStore.getState().setOutputLanguage("Chinese")
+ expect(getOutputLanguage("whatever fallback text")).toBe("Chinese")
+ })
+
+ it("explicit user setting beats fallback detection (source is English, setting is Japanese)", () => {
+ useWikiStore.getState().setOutputLanguage("Japanese")
+ expect(getOutputLanguage("This is clearly English text")).toBe("Japanese")
+ })
+
+ it("auto mode falls back to detectLanguage on the fallback text", () => {
+ useWikiStore.getState().setOutputLanguage("auto")
+ expect(getOutputLanguage("注意力机制是什么")).toBe("Chinese")
+ })
+
+ it("auto mode with empty fallback defaults to English", () => {
+ useWikiStore.getState().setOutputLanguage("auto")
+ expect(getOutputLanguage("")).toBe("English")
+ })
+
+ it("auto mode with no fallback arg defaults to English", () => {
+ useWikiStore.getState().setOutputLanguage("auto")
+ expect(getOutputLanguage()).toBe("English")
+ })
+})
+
+describe("buildLanguageDirective", () => {
+ it("contains the MANDATORY OUTPUT LANGUAGE header", () => {
+ useWikiStore.getState().setOutputLanguage("Chinese")
+ const directive = buildLanguageDirective()
+ expect(directive).toContain("MANDATORY OUTPUT LANGUAGE: Chinese")
+ })
+
+ it("names the language multiple times for emphasis", () => {
+ useWikiStore.getState().setOutputLanguage("Japanese")
+ const directive = buildLanguageDirective()
+ // Should include 'Japanese' at least 4× (header + instructions)
+ const count = (directive.match(/Japanese/g) || []).length
+ expect(count).toBeGreaterThanOrEqual(4)
+ })
+
+ it("follows the explicit setting even when fallback text is in another language", () => {
+ useWikiStore.getState().setOutputLanguage("Vietnamese")
+ const directive = buildLanguageDirective("这段文字是中文")
+ expect(directive).toContain("Vietnamese")
+ expect(directive).not.toContain("MANDATORY OUTPUT LANGUAGE: Chinese")
+ })
+
+ it("uses detected language in auto mode", () => {
+ useWikiStore.getState().setOutputLanguage("auto")
+ const directive = buildLanguageDirective("Xử lý nước thải là vấn đề quan trọng")
+ expect(directive).toContain("Vietnamese")
+ })
+
+ it("explicitly overrides source content language", () => {
+ useWikiStore.getState().setOutputLanguage("English")
+ const directive = buildLanguageDirective()
+ expect(directive).toContain("IRRELEVANT to your output language")
+ })
+})
+
+describe("buildLanguageReminder", () => {
+ it("is a concise reminder, not a full directive", () => {
+ useWikiStore.getState().setOutputLanguage("Chinese")
+ const reminder = buildLanguageReminder()
+ expect(reminder).toMatch(/All output must be in Chinese/)
+ // Reminder should be ONE line, not a multi-line block
+ expect(reminder.split("\n").length).toBe(1)
+ })
+
+ it("uses the explicit setting", () => {
+ useWikiStore.getState().setOutputLanguage("Korean")
+ expect(buildLanguageReminder("ignored fallback")).toContain("Korean")
+ })
+
+ it("uses detected language in auto mode", () => {
+ useWikiStore.getState().setOutputLanguage("auto")
+ expect(buildLanguageReminder("これは日本語です")).toContain("Japanese")
+ })
+})
diff --git a/src/lib/path-utils.test.ts b/src/lib/path-utils.test.ts
new file mode 100644
index 00000000..d22661f9
--- /dev/null
+++ b/src/lib/path-utils.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect } from "vitest"
+import { normalizePath, joinPath, getFileName, getFileStem, getRelativePath } from "./path-utils"
+
+describe("normalizePath", () => {
+ it("converts backslashes to forward slashes", () => {
+ expect(normalizePath("C:\\Users\\foo\\bar")).toBe("C:/Users/foo/bar")
+ })
+
+ it("leaves forward slash paths unchanged", () => {
+ expect(normalizePath("/Users/foo/bar")).toBe("/Users/foo/bar")
+ })
+
+ it("handles mixed separators", () => {
+ expect(normalizePath("C:\\mixed/path\\here")).toBe("C:/mixed/path/here")
+ })
+
+ it("handles empty string", () => {
+ expect(normalizePath("")).toBe("")
+ })
+
+ it("doesn't collapse consecutive slashes (by design)", () => {
+ // normalizePath only does separator replacement, not deduplication
+ expect(normalizePath("a\\\\b")).toBe("a//b")
+ })
+})
+
+describe("joinPath", () => {
+ it("joins simple segments with forward slashes", () => {
+ expect(joinPath("a", "b", "c")).toBe("a/b/c")
+ })
+
+ it("collapses duplicate slashes at the join boundary", () => {
+ expect(joinPath("a/", "/b", "c")).toBe("a/b/c")
+ })
+
+ it("normalizes backslashes inside segments", () => {
+ expect(joinPath("C:\\Users", "foo", "bar")).toBe("C:/Users/foo/bar")
+ })
+
+ it("preserves a leading slash", () => {
+ expect(joinPath("/abs", "path")).toBe("/abs/path")
+ })
+
+ it("joins a single segment", () => {
+ expect(joinPath("only")).toBe("only")
+ })
+})
+
+describe("getFileName", () => {
+ it("returns the last segment of a POSIX path", () => {
+ expect(getFileName("/a/b/c.md")).toBe("c.md")
+ })
+
+ it("returns the last segment of a Windows path", () => {
+ expect(getFileName("C:\\Users\\foo\\bar.pdf")).toBe("bar.pdf")
+ })
+
+ it("returns the original string when no separators", () => {
+ expect(getFileName("solo.md")).toBe("solo.md")
+ })
+
+ it("returns empty string when path ends with separator", () => {
+ expect(getFileName("/dir/")).toBe("")
+ })
+})
+
+describe("getFileStem", () => {
+ it("strips a single extension", () => {
+ expect(getFileStem("/a/b/note.md")).toBe("note")
+ })
+
+ it("strips only the LAST extension for double extensions", () => {
+ expect(getFileStem("archive.tar.gz")).toBe("archive.tar")
+ })
+
+ it("returns the name unchanged for dotfiles (leading dot)", () => {
+ // lastDot > 0 — so .env stays as .env
+ expect(getFileStem(".env")).toBe(".env")
+ })
+
+ it("works across separators", () => {
+ expect(getFileStem("C:\\dir\\notes.txt")).toBe("notes")
+ })
+
+ it("handles names with no extension", () => {
+ expect(getFileStem("README")).toBe("README")
+ })
+})
+
+describe("getRelativePath", () => {
+ it("strips the base prefix", () => {
+ expect(getRelativePath("/project/wiki/note.md", "/project")).toBe("wiki/note.md")
+ })
+
+ it("handles base with trailing slash", () => {
+ expect(getRelativePath("/project/wiki/note.md", "/project/")).toBe("wiki/note.md")
+ })
+
+ it("normalizes separators on both sides", () => {
+ expect(getRelativePath("C:\\project\\wiki\\note.md", "C:\\project")).toBe("wiki/note.md")
+ })
+
+ it("returns the full path if base doesn't prefix it", () => {
+ expect(getRelativePath("/other/path", "/project")).toBe("/other/path")
+ })
+
+ it("requires an exact segment boundary (not just prefix match)", () => {
+ // '/projector' should NOT be considered a base of '/project...'
+ // The impl adds '/' to base for matching, so this is handled.
+ expect(getRelativePath("/projector/a", "/project")).toBe("/projector/a")
+ })
+})
diff --git a/src/lib/review-utils.test.ts b/src/lib/review-utils.test.ts
new file mode 100644
index 00000000..7537344a
--- /dev/null
+++ b/src/lib/review-utils.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect } from "vitest"
+import { normalizeReviewTitle } from "./review-utils"
+
+describe("normalizeReviewTitle", () => {
+ it("returns the title lowercased when no prefix", () => {
+ expect(normalizeReviewTitle("Attention Mechanism")).toBe("attention mechanism")
+ })
+
+ it("strips English 'Missing page:' prefix", () => {
+ expect(normalizeReviewTitle("Missing page: Attention")).toBe("attention")
+ })
+
+ it("strips hyphenated 'Missing-Page:' prefix", () => {
+ expect(normalizeReviewTitle("Missing-Page: Attention")).toBe("attention")
+ })
+
+ it("strips Chinese '缺失页面:' prefix (full-width colon)", () => {
+ expect(normalizeReviewTitle("缺失页面:注意力机制")).toBe("注意力机制")
+ })
+
+ it("strips Chinese '缺失页面:' prefix (half-width colon)", () => {
+ expect(normalizeReviewTitle("缺失页面: 注意力机制")).toBe("注意力机制")
+ })
+
+ it("strips alternative '缺少页面:' prefix", () => {
+ expect(normalizeReviewTitle("缺少页面: 注意力")).toBe("注意力")
+ })
+
+ it("strips English 'Duplicate page:' prefix", () => {
+ expect(normalizeReviewTitle("Duplicate page: LLM")).toBe("llm")
+ })
+
+ it("strips Chinese '重复页面:' prefix", () => {
+ expect(normalizeReviewTitle("重复页面:大模型")).toBe("大模型")
+ })
+
+ it("strips 'Possible duplicate:' prefix", () => {
+ expect(normalizeReviewTitle("Possible duplicate: Graph RAG")).toBe("graph rag")
+ })
+
+ it("collapses internal whitespace", () => {
+ expect(normalizeReviewTitle("Missing page: Attention Mechanism")).toBe("attention mechanism")
+ })
+
+ it("is case-insensitive on the prefix match", () => {
+ expect(normalizeReviewTitle("MISSING PAGE: Attention")).toBe("attention")
+ expect(normalizeReviewTitle("missing page: Attention")).toBe("attention")
+ expect(normalizeReviewTitle("MiSsInG pAgE: Attention")).toBe("attention")
+ })
+
+ it("considers two variant-prefixed titles equal after normalization", () => {
+ const a = normalizeReviewTitle("Missing page: 注意力机制")
+ const b = normalizeReviewTitle("缺失页面: 注意力机制")
+ expect(a).toBe(b)
+ })
+
+ it("handles empty string", () => {
+ expect(normalizeReviewTitle("")).toBe("")
+ })
+
+ it("handles only-prefix input", () => {
+ expect(normalizeReviewTitle("Missing page: ")).toBe("")
+ })
+
+ it("preserves colons inside the title body (not as prefix)", () => {
+ // 'Overview' is not a recognized prefix, so the colon after it must stay
+ expect(normalizeReviewTitle("Overview: Some Topic")).toBe("overview: some topic")
+ })
+
+ it("only strips ONE prefix occurrence (no recursive stripping)", () => {
+ // If the title accidentally has a double prefix, only the first is stripped
+ expect(normalizeReviewTitle("Missing page: 缺失页面: Foo")).toBe("缺失页面: foo")
+ })
+})
diff --git a/src/lib/sweep-reviews.test.ts b/src/lib/sweep-reviews.test.ts
new file mode 100644
index 00000000..f2ff23e2
--- /dev/null
+++ b/src/lib/sweep-reviews.test.ts
@@ -0,0 +1,131 @@
+import { describe, it, expect } from "vitest"
+import { extractJsonObject } from "./sweep-reviews"
+
+describe("extractJsonObject", () => {
+ describe("bare JSON", () => {
+ it("extracts a simple object", () => {
+ expect(extractJsonObject('{"resolved":["a","b"]}')).toBe('{"resolved":["a","b"]}')
+ })
+
+ it("extracts an empty object", () => {
+ expect(extractJsonObject("{}")).toBe("{}")
+ })
+
+ it("extracts JSON with empty array", () => {
+ expect(extractJsonObject('{"resolved":[]}')).toBe('{"resolved":[]}')
+ })
+
+ it("preserves whitespace inside the object", () => {
+ const raw = '{\n "resolved": [\n "id-1"\n ]\n}'
+ expect(extractJsonObject(raw)).toBe(raw)
+ })
+ })
+
+ describe("markdown fences", () => {
+ it("strips ```json ... ``` multi-line fence", () => {
+ const raw = '```json\n{"resolved":["a"]}\n```'
+ expect(extractJsonObject(raw)).toBe('{"resolved":["a"]}')
+ })
+
+ it("strips bare ``` ... ``` multi-line fence", () => {
+ const raw = '```\n{"resolved":["a"]}\n```'
+ expect(extractJsonObject(raw)).toBe('{"resolved":["a"]}')
+ })
+
+ it("strips single-line ```json {...}``` fence", () => {
+ const raw = '```json {"resolved":["x"]}```'
+ expect(extractJsonObject(raw)).toBe('{"resolved":["x"]}')
+ })
+
+ it("handles fences with surrounding whitespace", () => {
+ const raw = ' \n ```json\n{"resolved":[]}\n``` \n '
+ expect(extractJsonObject(raw)).toBe('{"resolved":[]}')
+ })
+
+ it("is case-insensitive on the 'json' language tag", () => {
+ const raw = "```JSON\n{}\n```"
+ expect(extractJsonObject(raw)).toBe("{}")
+ })
+ })
+
+ describe("prose-wrapped JSON", () => {
+ it("finds JSON at the end of prose", () => {
+ const raw = 'Here is the answer: {"resolved":["a"]}'
+ expect(extractJsonObject(raw)).toBe('{"resolved":["a"]}')
+ })
+
+ it("returns the FIRST balanced object when prose has other braces before", () => {
+ // First balanced {...} is the prose one — expected behavior,
+ // callers then try JSON.parse and fall back on failure.
+ const raw = 'An example: {maybe like this}. Real answer: {"resolved":["a"]}'
+ const result = extractJsonObject(raw)
+ expect(result).toBe("{maybe like this}")
+ })
+
+ it("handles JSON with nested objects", () => {
+ const raw = '{"outer":{"inner":[1,2,3]}}'
+ expect(extractJsonObject(raw)).toBe(raw)
+ })
+ })
+
+ describe("string / escape handling", () => {
+ it("ignores braces inside string values", () => {
+ const raw = '{"note":"this { has } braces"}'
+ expect(extractJsonObject(raw)).toBe(raw)
+ })
+
+ it("handles escaped quotes inside strings", () => {
+ const raw = '{"q":"she said \\"hi\\""}'
+ expect(extractJsonObject(raw)).toBe(raw)
+ })
+
+ it("handles escaped backslash", () => {
+ const raw = '{"path":"C:\\\\foo"}'
+ expect(extractJsonObject(raw)).toBe(raw)
+ })
+ })
+
+ describe("malformed input", () => {
+ it("returns empty string for no JSON at all", () => {
+ expect(extractJsonObject("no json here")).toBe("")
+ })
+
+ it("returns empty string for empty input", () => {
+ expect(extractJsonObject("")).toBe("")
+ })
+
+ it("returns empty string for whitespace-only input", () => {
+ expect(extractJsonObject(" \n \t ")).toBe("")
+ })
+
+ it("returns empty string for unclosed object", () => {
+ expect(extractJsonObject('{"resolved":')).toBe("")
+ })
+
+ it("returns empty string when only opening brace", () => {
+ expect(extractJsonObject("{")).toBe("")
+ })
+
+ it("handles a fence with no inner JSON", () => {
+ expect(extractJsonObject("```json\n```")).toBe("")
+ })
+ })
+
+ describe("realistic LLM responses", () => {
+ it("parses the expected fenced output from our prompt", () => {
+ const raw = '```json\n{"resolved": ["review-1", "review-5"]}\n```'
+ const extracted = extractJsonObject(raw)
+ expect(JSON.parse(extracted)).toEqual({ resolved: ["review-1", "review-5"] })
+ })
+
+ it("parses a bare response with no fence", () => {
+ const raw = '{"resolved": []}'
+ expect(JSON.parse(extractJsonObject(raw))).toEqual({ resolved: [] })
+ })
+
+ it("survives a chatty preamble", () => {
+ const raw = 'I analyzed the reviews. Final answer:\n\n{"resolved": ["abc"]}'
+ expect(JSON.parse(extractJsonObject(raw))).toEqual({ resolved: ["abc"] })
+ })
+ })
+})
diff --git a/src/lib/sweep-reviews.ts b/src/lib/sweep-reviews.ts
index f12fb8ce..27a1407d 100644
--- a/src/lib/sweep-reviews.ts
+++ b/src/lib/sweep-reviews.ts
@@ -129,8 +129,10 @@ function pageExists(name: string, index: WikiIndex): boolean {
* - Wrapped in prose: find the first balanced `{...}` object via brace depth
*
* Returns empty string if no balanced object is found.
+ *
+ * @internal Exported for unit tests only.
*/
-function extractJsonObject(raw: string): string {
+export function extractJsonObject(raw: string): string {
let text = raw.trim()
// Strip an opening ```json or ``` fence (with or without newline)
diff --git a/src/stores/review-store.test.ts b/src/stores/review-store.test.ts
new file mode 100644
index 00000000..afd9d3f5
--- /dev/null
+++ b/src/stores/review-store.test.ts
@@ -0,0 +1,215 @@
+import { describe, it, expect, beforeEach } from "vitest"
+import { useReviewStore, type ReviewItem } from "./review-store"
+
+// Minimal builder so each test only specifies what it cares about.
+function makeInput(overrides: Partial<Omit<ReviewItem, "id" | "resolved" | "createdAt">> = {}) {
+ return {
+ type: "missing-page" as ReviewItem["type"],
+ title: "Attention",
+ description: "description",
+ options: [],
+ ...overrides,
+ }
+}
+
+// Reset the store between tests — Zustand stores are module-level singletons.
+beforeEach(() => {
+ useReviewStore.setState({ items: [] })
+})
+
+describe("review-store addItem", () => {
+ it("adds a single item with generated id and resolved=false", () => {
+ useReviewStore.getState().addItem(makeInput())
+ const items = useReviewStore.getState().items
+ expect(items).toHaveLength(1)
+ expect(items[0].id).toMatch(/^review-\d+$/)
+ expect(items[0].resolved).toBe(false)
+ expect(items[0].createdAt).toBeTypeOf("number")
+ })
+
+ it("does NOT dedupe in addItem (single-item path is append-only)", () => {
+ // By design — dedupe only applies to addItems (bulk path from ingest).
+ const store = useReviewStore.getState()
+ store.addItem(makeInput({ title: "Same" }))
+ store.addItem(makeInput({ title: "Same" }))
+ expect(useReviewStore.getState().items).toHaveLength(2)
+ })
+})
+
+describe("review-store addItems dedupe", () => {
+ it("merges two incoming items with the same type + normalized title", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "Missing page: Attention", affectedPages: ["a.md"] }),
+ makeInput({ title: "缺失页面: Attention", affectedPages: ["b.md"] }),
+ ])
+ const items = useReviewStore.getState().items
+ expect(items).toHaveLength(1)
+ expect(items[0].affectedPages).toEqual(expect.arrayContaining(["a.md", "b.md"]))
+ })
+
+ it("merges against existing pending items", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "Attention", affectedPages: ["x.md"] }),
+ ])
+ useReviewStore.getState().addItems([
+ makeInput({ title: "Missing page: Attention", affectedPages: ["y.md"] }),
+ ])
+ const items = useReviewStore.getState().items
+ expect(items).toHaveLength(1)
+ expect(items[0].affectedPages).toEqual(expect.arrayContaining(["x.md", "y.md"]))
+ })
+
+ it("does NOT merge across different types", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ type: "missing-page", title: "Attention" }),
+ makeInput({ type: "duplicate", title: "Attention" }),
+ ])
+ expect(useReviewStore.getState().items).toHaveLength(2)
+ })
+
+ it("does NOT merge into a resolved item (creates a new one)", () => {
+ const store = useReviewStore.getState()
+ store.addItems([makeInput({ title: "Attention" })])
+ const oldId = useReviewStore.getState().items[0].id
+ store.resolveItem(oldId, "user-resolved")
+ store.addItems([makeInput({ title: "Attention", affectedPages: ["new.md"] })])
+ const items = useReviewStore.getState().items
+ expect(items).toHaveLength(2)
+ expect(items.find((i) => i.resolved)?.id).toBe(oldId)
+ expect(items.find((i) => !i.resolved)?.affectedPages).toEqual(["new.md"])
+ })
+
+ it("covers contradiction type (was previously skipped in dedupe)", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ type: "contradiction", title: "Conflict A", affectedPages: ["a.md"] }),
+ makeInput({ type: "contradiction", title: "Conflict A", affectedPages: ["b.md"] }),
+ ])
+ const items = useReviewStore.getState().items
+ expect(items).toHaveLength(1)
+ expect(items[0].affectedPages).toEqual(expect.arrayContaining(["a.md", "b.md"]))
+ })
+
+ it("covers confirm type", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ type: "confirm", title: "Confirm X" }),
+ makeInput({ type: "confirm", title: "Confirm X" }),
+ ])
+ expect(useReviewStore.getState().items).toHaveLength(1)
+ })
+
+ it("prefers the newer non-empty description on merge", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", description: "old desc" }),
+ ])
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", description: "new desc" }),
+ ])
+ expect(useReviewStore.getState().items[0].description).toBe("new desc")
+ })
+
+ it("keeps old description if incoming is empty", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", description: "keep me" }),
+ ])
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", description: "" }),
+ ])
+ expect(useReviewStore.getState().items[0].description).toBe("keep me")
+ })
+
+ it("deduplicates affectedPages within the merge", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", affectedPages: ["x.md", "y.md"] }),
+ ])
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", affectedPages: ["y.md", "z.md"] }),
+ ])
+ const merged = useReviewStore.getState().items[0]
+ expect(merged.affectedPages).toEqual(["x.md", "y.md", "z.md"])
+ })
+
+ it("merges searchQueries without duplicates", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", searchQueries: ["q1"] }),
+ ])
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", searchQueries: ["q1", "q2"] }),
+ ])
+ expect(useReviewStore.getState().items[0].searchQueries).toEqual(["q1", "q2"])
+ })
+
+ it("sets affectedPages to undefined when the merged result is empty", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A" }),
+ makeInput({ title: "A" }),
+ ])
+ expect(useReviewStore.getState().items[0].affectedPages).toBeUndefined()
+ })
+
+ it("handles many incoming items at once, merging same-key pairs", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A", affectedPages: ["1.md"] }),
+ makeInput({ title: "A", affectedPages: ["2.md"] }),
+ makeInput({ title: "B", affectedPages: ["3.md"] }),
+ makeInput({ title: "A", affectedPages: ["4.md"] }),
+ ])
+ const items = useReviewStore.getState().items
+ expect(items).toHaveLength(2)
+ const a = items.find((i) => i.title.toLowerCase().includes("a"))
+ const b = items.find((i) => i.title.toLowerCase().includes("b"))
+ expect(a?.affectedPages).toEqual(["1.md", "2.md", "4.md"])
+ expect(b?.affectedPages).toEqual(["3.md"])
+ })
+
+ it("invariant: after addItems, no two pending items share (type, normalized title)", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ type: "missing-page", title: "Missing page: Foo" }),
+ makeInput({ type: "missing-page", title: "缺失页面: Foo" }),
+ makeInput({ type: "missing-page", title: "Foo" }),
+ makeInput({ type: "duplicate", title: "Foo" }),
+ makeInput({ type: "duplicate", title: "Duplicate page: Foo" }),
+ ])
+ const pending = useReviewStore.getState().items.filter((i) => !i.resolved)
+ const keys = pending.map((i) => `${i.type}::${i.title.toLowerCase().replace(/^(missing|duplicate).*?:\s*/i, "").trim()}`)
+ expect(new Set(keys).size).toBe(pending.length)
+ })
+})
+
+describe("review-store resolveItem / dismissItem / clearResolved", () => {
+ it("resolveItem flips the flag and stores action", () => {
+ useReviewStore.getState().addItem(makeInput())
+ const id = useReviewStore.getState().items[0].id
+ useReviewStore.getState().resolveItem(id, "auto-resolved")
+ const resolved = useReviewStore.getState().items.find((i) => i.id === id)
+ expect(resolved?.resolved).toBe(true)
+ expect(resolved?.resolvedAction).toBe("auto-resolved")
+ })
+
+ it("resolveItem on missing id is a no-op (doesn't throw)", () => {
+ useReviewStore.getState().addItem(makeInput())
+ expect(() => useReviewStore.getState().resolveItem("nonexistent", "x")).not.toThrow()
+ expect(useReviewStore.getState().items[0].resolved).toBe(false)
+ })
+
+ it("dismissItem removes the item entirely", () => {
+ useReviewStore.getState().addItem(makeInput())
+ const id = useReviewStore.getState().items[0].id
+ useReviewStore.getState().dismissItem(id)
+ expect(useReviewStore.getState().items).toHaveLength(0)
+ })
+
+ it("clearResolved keeps only unresolved items", () => {
+ useReviewStore.getState().addItems([
+ makeInput({ title: "A" }),
+ makeInput({ title: "B" }),
+ makeInput({ title: "C" }),
+ ])
+ const items = useReviewStore.getState().items
+ useReviewStore.getState().resolveItem(items[0].id, "user-resolved")
+ useReviewStore.getState().resolveItem(items[2].id, "user-resolved")
+ useReviewStore.getState().clearResolved()
+ const remaining = useReviewStore.getState().items
+ expect(remaining).toHaveLength(1)
+ expect(remaining[0].title).toBe("B")
+ })
+})