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(embedding/rag Phase 5): Settings UI + RAG test coverage

nash_su5f8389a2eecd
diff --git a/package.json b/package.json
index 9787c8db..e96b0b76 100644
--- a/package.json
+++ b/package.json
@@ -8,8 +8,9 @@
"typecheck": "tsc --build --pretty",
"build": "npm run typecheck && vite build",
"preview": "vite preview",
- "test": "vitest run --exclude='**/*.real-llm.test.ts'",
- "test:llm": "RUN_LLM_TESTS=1 vitest run real-llm --no-file-parallelism --reporter=verbose",
+ "test": "npm run test:mocks && npm run test:llm",
+ "test:mocks": "vitest run --exclude='**/*.real-llm.test.ts'",
+ "test:llm": "vitest run real-llm --no-file-parallelism --reporter=verbose",
"tauri": "tauri"
},
"dependencies": {
diff --git a/src/components/settings/sections/embedding-section.tsx b/src/components/settings/sections/embedding-section.tsx
index 2092408f..35f66f8d 100644
--- a/src/components/settings/sections/embedding-section.tsx
+++ b/src/components/settings/sections/embedding-section.tsx
@@ -1,6 +1,16 @@
+import { useCallback, useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
+import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
+import { useWikiStore } from "@/stores/wiki-store"
+import {
+ dropLegacyVectorTable,
+ embedAllPages,
+ getEmbeddingCount,
+ getLastEmbeddingError,
+ legacyVectorRowCount,
+} from "@/lib/embedding"
import type { SettingsDraft, DraftSetter } from "../settings-types"
interface Props {
@@ -8,8 +18,61 @@ interface Props {
setDraft: DraftSetter
}
+type ReindexState =
+ | { kind: "idle" }
+ | { kind: "running"; done: number; total: number }
+ | { kind: "done"; count: number }
+
export function EmbeddingSection({ draft, setDraft }: Props) {
const { t } = useTranslation()
+ const project = useWikiStore((s) => s.project)
+ const embeddingConfig = useWikiStore((s) => s.embeddingConfig)
+
+ const [chunkCount, setChunkCount] = useState<number | null>(null)
+ const [legacyCount, setLegacyCount] = useState<number>(0)
+ const [lastError, setLastError] = useState<string | null>(null)
+ const [reindex, setReindex] = useState<ReindexState>({ kind: "idle" })
+ const [legacyDropped, setLegacyDropped] = useState(false)
+
+ const refreshStats = useCallback(async () => {
+ if (!project) return
+ try {
+ const [chunks, legacy] = await Promise.all([
+ getEmbeddingCount(project.path),
+ legacyVectorRowCount(project.path),
+ ])
+ setChunkCount(chunks)
+ setLegacyCount(legacy)
+ } catch {
+ setChunkCount(null)
+ }
+ setLastError(getLastEmbeddingError())
+ }, [project])
+
+ useEffect(() => {
+ void refreshStats()
+ }, [refreshStats])
+
+ const handleReindex = useCallback(async () => {
+ if (!project) return
+ setReindex({ kind: "running", done: 0, total: 0 })
+ const count = await embedAllPages(project.path, embeddingConfig, (done, total) => {
+ setReindex({ kind: "running", done, total })
+ })
+ setReindex({ kind: "done", count })
+ await refreshStats()
+ }, [project, embeddingConfig, refreshStats])
+
+ const handleDropLegacy = useCallback(async () => {
+ if (!project) return
+ await dropLegacyVectorTable(project.path)
+ setLegacyCount(0)
+ setLegacyDropped(true)
+ }, [project])
+
+ const showLegacyMigration =
+ legacyCount > 0 && (chunkCount === null || chunkCount === 0)
+
return (
<div className="space-y-6">
<div>
@@ -70,6 +133,124 @@ export function EmbeddingSection({ draft, setDraft }: Props) {
placeholder="e.g. text-embedding-qwen3-embedding-0.6b"
/>
</div>
+
+ <div className="space-y-3 rounded-md border p-3">
+ <div className="text-sm font-medium">
+ {t("settings.sections.embedding.chunking")}
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t("settings.sections.embedding.maxChunkChars")}</Label>
+ <Input
+ type="number"
+ min={200}
+ step={100}
+ value={draft.embeddingMaxChunkChars ?? ""}
+ onChange={(e) => {
+ const v = e.target.value.trim()
+ setDraft(
+ "embeddingMaxChunkChars",
+ v === "" ? undefined : Number(v),
+ )
+ }}
+ placeholder="1000"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.embedding.maxChunkCharsHint")}
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t("settings.sections.embedding.overlapChunkChars")}</Label>
+ <Input
+ type="number"
+ min={0}
+ step={50}
+ value={draft.embeddingOverlapChunkChars ?? ""}
+ onChange={(e) => {
+ const v = e.target.value.trim()
+ setDraft(
+ "embeddingOverlapChunkChars",
+ v === "" ? undefined : Number(v),
+ )
+ }}
+ placeholder="200"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.embedding.overlapChunkCharsHint")}
+ </p>
+ </div>
+ </div>
+
+ {showLegacyMigration && (
+ <div className="space-y-2 rounded-md border border-destructive/40 bg-destructive/5 p-3">
+ <div className="text-sm font-medium text-destructive">
+ {t("settings.sections.embedding.legacyPromptTitle")}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.embedding.legacyPromptBody", { count: legacyCount })}
+ </p>
+ </div>
+ )}
+
+ <div className="space-y-3 rounded-md border p-3">
+ <div className="text-sm font-medium">
+ {t("settings.sections.embedding.statsHeading")}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.embedding.chunkCount", { count: chunkCount ?? 0 })}
+ </p>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleReindex}
+ disabled={reindex.kind === "running" || !project}
+ >
+ {reindex.kind === "running"
+ ? t("settings.sections.embedding.reindexing", {
+ done: reindex.done,
+ total: reindex.total,
+ })
+ : t("settings.sections.embedding.reindexAll")}
+ </Button>
+
+ {legacyCount > 0 && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleDropLegacy}
+ disabled={!project}
+ >
+ {t("settings.sections.embedding.dropLegacy")}
+ </Button>
+ )}
+ </div>
+
+ {reindex.kind === "done" && (
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.embedding.reindexDone", { count: reindex.count })}
+ </p>
+ )}
+
+ {legacyDropped && (
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.embedding.dropLegacyDone")}
+ </p>
+ )}
+
+ {lastError && (
+ <div className="space-y-1">
+ <div className="text-xs font-medium">
+ {t("settings.sections.embedding.lastErrorHeading")}
+ </div>
+ <pre className="max-h-32 overflow-auto rounded bg-muted/50 p-2 text-[11px] leading-snug text-muted-foreground">
+ {lastError}
+ </pre>
+ </div>
+ )}
+ </div>
</>
)}
</div>
diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.ts
index a74a8e82..491d19e9 100644
--- a/src/components/settings/settings-types.ts
+++ b/src/components/settings/settings-types.ts
@@ -21,6 +21,10 @@ export interface SettingsDraft {
embeddingEndpoint: string
embeddingApiKey: string
embeddingModel: string
+ /** Target characters per chunk. Empty = use chunker default (1000). */
+ embeddingMaxChunkChars: number | undefined
+ /** Overlap characters between adjacent chunks. Empty = default (200). */
+ embeddingOverlapChunkChars: number | undefined
// Web search
searchProvider: "tavily" | "none"
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index 2ddbc624..caa06a4c 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -67,6 +67,8 @@ function initialDraft(
embeddingEndpoint: embed.endpoint,
embeddingApiKey: embed.apiKey,
embeddingModel: embed.model,
+ embeddingMaxChunkChars: embed.maxChunkChars,
+ embeddingOverlapChunkChars: embed.overlapChunkChars,
searchProvider: search.provider,
searchApiKey: search.apiKey,
outputLanguage,
@@ -148,6 +150,8 @@ export function SettingsView() {
endpoint: draft.embeddingEndpoint,
apiKey: draft.embeddingApiKey,
model: draft.embeddingModel,
+ maxChunkChars: draft.embeddingMaxChunkChars,
+ overlapChunkChars: draft.embeddingOverlapChunkChars,
}
setLlmConfig(newLlm)
diff --git a/src/i18n/en.json b/src/i18n/en.json
index a29c4fcb..1abed70d 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -129,7 +129,22 @@
"endpoint": "Endpoint",
"apiKey": "API Key (optional)",
"apiKeyPlaceholder": "Leave empty for local models",
- "model": "Model"
+ "model": "Model",
+ "chunking": "Chunking",
+ "maxChunkChars": "Max chunk size (characters)",
+ "maxChunkCharsHint": "Target size of each chunk. Lower this (e.g. 500) when your endpoint's context is small (llama.cpp n_ctx=512, mxbai-embed-large, etc.).",
+ "overlapChunkChars": "Overlap (characters)",
+ "overlapChunkCharsHint": "Characters of overlap between adjacent chunks so ideas aren't severed at boundaries.",
+ "statsHeading": "Index status",
+ "chunkCount": "{{count}} chunks indexed",
+ "lastErrorHeading": "Last embedding error",
+ "reindexAll": "Re-index all pages",
+ "reindexing": "Indexing {{done}}/{{total}}…",
+ "reindexDone": "Indexed {{count}} pages.",
+ "legacyPromptTitle": "Legacy per-page index detected",
+ "legacyPromptBody": "Your project has {{count}} entries in the old per-page vector store. The new per-chunk index gives better retrieval but needs a one-time re-embed. Run \"Re-index all pages\" to upgrade.",
+ "dropLegacy": "Drop legacy index",
+ "dropLegacyDone": "Legacy index removed."
},
"webSearch": {
"title": "Web Search",
diff --git a/src/i18n/i18n-parity.test.ts b/src/i18n/i18n-parity.test.ts
new file mode 100644
index 00000000..48a189d3
--- /dev/null
+++ b/src/i18n/i18n-parity.test.ts
@@ -0,0 +1,87 @@
+/**
+ * Structural parity check for the translation bundles.
+ *
+ * If en.json grows a key that zh.json doesn't have (or vice-versa),
+ * the app either falls back to the raw key at runtime (ugly) or
+ * silently shows the English string to Chinese users. Both are
+ * regressions we want to catch at test time.
+ *
+ * This test is deliberately string-based rather than going through
+ * i18next's runtime — it should fail on the FILE contents before
+ * anyone notices in the UI.
+ */
+import { describe, it, expect } from "vitest"
+import en from "./en.json"
+import zh from "./zh.json"
+
+/** Flattens a nested translation object to "a.b.c" dot-path keys. */
+function flattenKeys(obj: unknown, prefix = ""): string[] {
+ if (obj === null || typeof obj !== "object") return []
+ const out: string[] = []
+ for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {
+ const path = prefix ? `${prefix}.${k}` : k
+ if (v !== null && typeof v === "object") {
+ out.push(...flattenKeys(v, path))
+ } else {
+ out.push(path)
+ }
+ }
+ return out
+}
+
+describe("i18n bundle parity (en.json ↔ zh.json)", () => {
+ const enKeys = new Set(flattenKeys(en))
+ const zhKeys = new Set(flattenKeys(zh))
+
+ it("every en.json key is also in zh.json", () => {
+ const missing = [...enKeys].filter((k) => !zhKeys.has(k)).sort()
+ expect(
+ missing,
+ `Keys in en.json but missing from zh.json — add Chinese translations for:\n ${missing.join("\n ")}`,
+ ).toEqual([])
+ })
+
+ it("every zh.json key is also in en.json (no orphaned zh-only strings)", () => {
+ const orphaned = [...zhKeys].filter((k) => !enKeys.has(k)).sort()
+ expect(
+ orphaned,
+ `Keys in zh.json but missing from en.json — either add English translations or remove the stale zh-only keys:\n ${orphaned.join("\n ")}`,
+ ).toEqual([])
+ })
+
+ it("every leaf value is a non-empty string (no null / empty / placeholder slips)", () => {
+ const check = (bundle: unknown, label: string) => {
+ const keys = flattenKeys(bundle)
+ for (const path of keys) {
+ // Walk back to pull the value.
+ let ref: unknown = bundle
+ for (const part of path.split(".")) {
+ ref = (ref as Record<string, unknown>)[part]
+ }
+ expect(typeof ref, `${label}: ${path} is not a string`).toBe("string")
+ expect((ref as string).length, `${label}: ${path} is empty`).toBeGreaterThan(0)
+ }
+ }
+ check(en, "en.json")
+ check(zh, "zh.json")
+ })
+
+ it("pluralization keys come in pairs: every foo_plural has a matching foo", () => {
+ // i18next plural convention — a `foo_plural` without `foo` means
+ // the singular form will fall back to the raw key at runtime.
+ const check = (bundle: unknown, label: string) => {
+ const keys = new Set(flattenKeys(bundle))
+ for (const k of keys) {
+ if (k.endsWith("_plural")) {
+ const singular = k.slice(0, -"_plural".length)
+ expect(
+ keys.has(singular),
+ `${label}: found ${k} but no matching ${singular} (i18next will fall back to the raw key for count=1)`,
+ ).toBe(true)
+ }
+ }
+ }
+ check(en, "en.json")
+ check(zh, "zh.json")
+ })
+})
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index f8162f2b..153f9dc4 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -129,7 +129,22 @@
"endpoint": "Endpoint",
"apiKey": "API Key(可选)",
"apiKeyPlaceholder": "本地模型留空即可",
- "model": "Model"
+ "model": "Model",
+ "chunking": "切分参数",
+ "maxChunkChars": "每块最大字符数",
+ "maxChunkCharsHint": "单个 chunk 的目标长度。endpoint 上下文较小时(llama.cpp n_ctx=512、mxbai-embed-large 等)调低(如 500)。",
+ "overlapChunkChars": "重叠字符数",
+ "overlapChunkCharsHint": "相邻 chunk 之间的重叠字符数,避免语义在边界被切断。",
+ "statsHeading": "索引状态",
+ "chunkCount": "已索引 {{count}} 个 chunk",
+ "lastErrorHeading": "上次 embedding 错误",
+ "reindexAll": "重新索引全部页面",
+ "reindexing": "索引中 {{done}}/{{total}}…",
+ "reindexDone": "已索引 {{count}} 个页面。",
+ "legacyPromptTitle": "检测到旧版(按页)索引",
+ "legacyPromptBody": "当前项目在旧版按页向量存储里有 {{count}} 条记录。新版按 chunk 索引检索质量更高,但需要一次性重新 embed。点击\"重新索引全部页面\"完成升级。",
+ "dropLegacy": "删除旧版索引",
+ "dropLegacyDone": "旧版索引已删除。"
},
"webSearch": {
"title": "网页搜索",
diff --git a/src/lib/embedding.real-llm.test.ts b/src/lib/embedding.real-llm.test.ts
new file mode 100644
index 00000000..48bfcd65
--- /dev/null
+++ b/src/lib/embedding.real-llm.test.ts
@@ -0,0 +1,973 @@
+/**
+ * Real embedding-endpoint tests — covers what mock tests CANNOT:
+ *
+ * 1. The HTTP response actually parses into `number[]` with the
+ * expected shape.
+ * 2. The endpoint returns semantically-meaningful vectors — similar
+ * sentences really do land closer than unrelated ones. If the
+ * mocked pipeline is green but this suite fails, the bug is in
+ * the server / model / response parsing, not the control flow.
+ * 3. The `looksLikeOversizeError` heuristic keywords match the
+ * actual phrasing a real server returns on oversize input (the
+ * mock tests use a synthetic body — a heuristic-miss regression
+ * would only show up here).
+ * 4. The auto-halve loop actually recovers from real oversize
+ * responses end-to-end (plugin-http / fetch / body-parse edge
+ * cases, not just the retry arithmetic).
+ *
+ * Gated behind `RUN_LLM_TESTS=1` AND an explicit `EMBEDDING_ENDPOINT`
+ * env. We deliberately DON'T default to a known host — tests must
+ * target the user's own endpoint (LM Studio / Ollama / a hosted
+ * service) so the cost stays local.
+ *
+ * Tauri `invoke` is stubbed: LanceDB isn't reachable under Node, and
+ * the Rust side has its own 15-test suite. We only exercise the
+ * TypeScript HTTP layer + the semantic contract here.
+ */
+import { describe, it, expect, vi, beforeAll } from "vitest"
+import { createServer, type Server } from "node:http"
+import type { AddressInfo } from "node:net"
+
+// A scriptable `invoke` stub so individual tests can (a) capture what
+// embedPage tries to write to LanceDB, and (b) swap in an in-memory
+// implementation of vector_search_chunks so we can exercise
+// searchByEmbedding end-to-end without a real LanceDB instance.
+const mockInvoke = vi.fn<(cmd: string, args?: unknown) => Promise<unknown>>()
+vi.mock("@tauri-apps/api/core", () => ({
+ invoke: (cmd: string, args?: unknown) => mockInvoke(cmd, args),
+}))
+
+vi.mock("@/commands/fs", () => ({
+ readFile: vi.fn(),
+ listDirectory: vi.fn(),
+}))
+
+import {
+ embedPage,
+ fetchEmbedding,
+ looksLikeOversizeError,
+ getLastEmbeddingError,
+ searchByEmbedding,
+} from "./embedding"
+
+const ENABLED =
+ process.env.RUN_LLM_TESTS === "1" &&
+ !!process.env.EMBEDDING_ENDPOINT &&
+ !!process.env.EMBEDDING_MODEL
+
+const cfg = {
+ enabled: true,
+ endpoint: process.env.EMBEDDING_ENDPOINT ?? "",
+ apiKey: process.env.EMBEDDING_API_KEY ?? "",
+ model: process.env.EMBEDDING_MODEL ?? "",
+}
+
+/** Cosine similarity — defined here (not imported) so the ranking
+ * logic and the test's idea of "similar" stay independent. */
+function cosineSim(a: number[], b: number[]): number {
+ if (a.length !== b.length) throw new Error(`dim mismatch: ${a.length} vs ${b.length}`)
+ let dot = 0
+ let na = 0
+ let nb = 0
+ for (let i = 0; i < a.length; i++) {
+ dot += a[i] * b[i]
+ na += a[i] * a[i]
+ nb += b[i] * b[i]
+ }
+ return dot / (Math.sqrt(na) * Math.sqrt(nb))
+}
+
+const TEST_TIMEOUT_MS = 2 * 60 * 1000
+
+describe("real-embedding endpoint contract", () => {
+ it.skipIf(!ENABLED)(
+ "returns a finite-number vector of consistent dim for short input",
+ async () => {
+ const v1 = await fetchEmbedding("hello world", cfg)
+ expect(v1, `fetchEmbedding failed: ${getLastEmbeddingError()}`).not.toBeNull()
+ expect(Array.isArray(v1)).toBe(true)
+ expect(v1!.length).toBeGreaterThan(0)
+ // Every element must be a finite number — NaN / Infinity in the
+ // returned vector would poison LanceDB's distance math.
+ for (const x of v1!) {
+ expect(typeof x).toBe("number")
+ expect(Number.isFinite(x)).toBe(true)
+ }
+
+ // Two more calls to pin dim consistency — a regression that
+ // flipped between two endpoints or two models would show up as
+ // length drift here.
+ const v2 = await fetchEmbedding("another sentence", cfg)
+ const v3 = await fetchEmbedding("a third one", cfg)
+ expect(v2!.length).toBe(v1!.length)
+ expect(v3!.length).toBe(v1!.length)
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)(
+ "embeds the same text twice to near-identical vectors (determinism)",
+ async () => {
+ const text = "Rotary positional embeddings in Transformers."
+ const a = (await fetchEmbedding(text, cfg))!
+ const b = (await fetchEmbedding(text, cfg))!
+ const sim = cosineSim(a, b)
+ // Most servers are deterministic (sim ≈ 1.0). Some add a tiny
+ // bit of quantization noise. Anything below 0.99 means the
+ // endpoint is non-deterministic or the pipeline is corrupting
+ // the response — either way, search ranking becomes unstable.
+ expect(sim).toBeGreaterThan(0.99)
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)(
+ "embeds semantically-similar sentences to closer vectors than unrelated ones",
+ async () => {
+ // A ~ B (both about RoPE / positional encoding in Transformers)
+ // C: an unrelated dessert topic.
+ const A = "Rotary positional embeddings are a Transformer position-encoding scheme."
+ const B = "RoPE is a rotary positional embedding method commonly used in LLM attention."
+ const C = "Chocolate ice cream is a classic dessert flavor made from cream, sugar, and cocoa."
+
+ const [vA, vB, vC] = await Promise.all([
+ fetchEmbedding(A, cfg),
+ fetchEmbedding(B, cfg),
+ fetchEmbedding(C, cfg),
+ ])
+ expect(vA).not.toBeNull()
+ expect(vB).not.toBeNull()
+ expect(vC).not.toBeNull()
+
+ const simAB = cosineSim(vA!, vB!)
+ const simAC = cosineSim(vA!, vC!)
+ const simBC = cosineSim(vB!, vC!)
+
+ // eslint-disable-next-line no-console
+ console.log(
+ `[real-embedding] similarity — A~B: ${simAB.toFixed(4)}, A~C: ${simAC.toFixed(4)}, B~C: ${simBC.toFixed(4)}`,
+ )
+
+ // The margin (0.05) is conservative: even weaker embedding
+ // models should comfortably separate "RoPE" from "ice cream".
+ // If this fails, the endpoint is almost certainly returning
+ // a near-constant vector or the model id is wrong.
+ expect(simAB).toBeGreaterThan(simAC + 0.05)
+ expect(simAB).toBeGreaterThan(simBC + 0.05)
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)(
+ "oversize phrase heuristic matches what the real server returns on oversize input",
+ async () => {
+ // Blast the endpoint with a deliberately-huge input via raw
+ // fetch (bypassing fetchEmbedding's auto-halve). If the server
+ // accepts it, we have nothing to validate — skip. If it rejects,
+ // the error body must match `looksLikeOversizeError`, otherwise
+ // the heuristic is missing a phrase used by this server.
+ const huge = "a".repeat(500_000)
+ const resp = await fetch(cfg.endpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...(cfg.apiKey ? { Authorization: `Bearer ${cfg.apiKey}` } : {}),
+ },
+ body: JSON.stringify({ model: cfg.model, input: huge }),
+ })
+
+ if (resp.ok) {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[real-embedding] endpoint accepted 500k-char input (context is large); skipping oversize-phrase assertion`,
+ )
+ return
+ }
+
+ const body = await resp.text()
+ // eslint-disable-next-line no-console
+ console.log(`[real-embedding] oversize response: HTTP ${resp.status} — ${body.slice(0, 200)}`)
+
+ expect(
+ looksLikeOversizeError(resp.status, body),
+ `Heuristic missed the real server's oversize phrasing. status=${resp.status} body=${body.slice(0, 300)}. Add the missing phrase to looksLikeOversizeError.`,
+ ).toBe(true)
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)(
+ "auto-halve recovers or surfaces the specific error on the real endpoint (best-effort — many large-context servers silently truncate)",
+ async () => {
+ const bigText = "The quick brown fox jumps over the lazy dog. ".repeat(5_000)
+ const v = await fetchEmbedding(bigText, cfg)
+
+ if (v !== null) {
+ expect(Number.isFinite(v[0])).toBe(true)
+ expect(getLastEmbeddingError()).toBeNull()
+ // eslint-disable-next-line no-console
+ console.log(
+ `[real-embedding] NOTE: endpoint accepted ~225k-char input without rejecting — real halving path was NOT exercised against this server. ` +
+ `See the "fake small-context server" test below for the end-to-end halving proof.`,
+ )
+ return
+ }
+
+ const err = getLastEmbeddingError()!
+ // eslint-disable-next-line no-console
+ console.log(`[real-embedding] auto-halve gave up: ${err}`)
+ expect(
+ err,
+ "fetchEmbedding returned null on oversize input but error isn't the oversize-specific message — looksLikeOversizeError missed the server's phrasing",
+ ).toContain("Endpoint rejected input even at")
+ },
+ TEST_TIMEOUT_MS,
+ )
+})
+
+// ── Fake small-context HTTP server — guarantees the halving path ───
+//
+// The real embedding endpoint (qwen3-embedding-0.6b on LM Studio)
+// silently truncates multi-megabyte inputs, which means the halving
+// retry loop is NEVER exercised end-to-end against it. This block
+// spins up a tiny local HTTP server that rejects inputs longer than
+// a configured threshold with a llama.cpp-style error body, so we
+// can prove the full HTTP → parse → looksLikeOversizeError → halve
+// → retry → success cycle actually works over real TCP. Unlike the
+// mocked tests (which swap out getHttpFetch entirely), this exercises
+// the same plugin-http / globalThis.fetch code path production uses.
+
+interface FakeServerHandle {
+ url: string
+ requestCount: () => number
+ requestSizes: () => number[]
+ close: () => Promise<void>
+}
+
+/**
+ * Starts a local HTTP server on 127.0.0.1 that behaves like an
+ * OpenAI-compatible /v1/embeddings endpoint with a small context:
+ *
+ * - input.length > maxInputChars → HTTP 400 with the error body
+ * `{"error":"input length N exceeds maximum context M"}` (matches
+ * the phrasing looksLikeOversizeError is designed to catch).
+ * - otherwise → HTTP 200 with a deterministic vector of the given
+ * dimension (value = sin(i) so it's not all-zeros).
+ */
+async function startFakeEmbeddingServer(
+ maxInputChars: number,
+ dim = 8,
+): Promise<FakeServerHandle> {
+ let server: Server | null = null
+ const sizes: number[] = []
+ const url = await new Promise<string>((resolve, reject) => {
+ server = createServer((req, res) => {
+ const chunks: Buffer[] = []
+ req.on("data", (c: Buffer) => chunks.push(c))
+ req.on("end", () => {
+ try {
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf-8")) as {
+ input: string
+ }
+ sizes.push(body.input.length)
+ if (body.input.length > maxInputChars) {
+ res.statusCode = 400
+ res.setHeader("Content-Type", "application/json")
+ res.end(
+ JSON.stringify({
+ error: `input length ${body.input.length} exceeds maximum context ${maxInputChars}`,
+ }),
+ )
+ return
+ }
+ const vec = Array.from({ length: dim }, (_, i) => Math.sin(i + 1) * 0.1)
+ res.statusCode = 200
+ res.setHeader("Content-Type", "application/json")
+ res.end(JSON.stringify({ data: [{ embedding: vec }] }))
+ } catch (err) {
+ res.statusCode = 500
+ res.end(String(err))
+ }
+ })
+ })
+ server.on("error", reject)
+ server.listen(0, "127.0.0.1", () => {
+ const addr = server!.address() as AddressInfo
+ resolve(`http://127.0.0.1:${addr.port}/v1/embeddings`)
+ })
+ })
+ return {
+ url,
+ requestCount: () => sizes.length,
+ requestSizes: () => [...sizes],
+ close: () =>
+ new Promise<void>((resolve) => {
+ if (server) server.close(() => resolve())
+ else resolve()
+ }),
+ }
+}
+
+describe("fetchEmbedding against a fake small-context server (real TCP)", () => {
+ it("halves an oversize input and eventually succeeds", async () => {
+ const server = await startFakeEmbeddingServer(/* maxInputChars */ 200)
+ try {
+ const smallCfg = {
+ enabled: true,
+ endpoint: server.url,
+ apiKey: "",
+ model: "fake-embed",
+ }
+ // 800 chars of "a" → must halve 800 → 400 → 200 (3 attempts:
+ // first 2 rejected, third accepted at the boundary). Proves:
+ // (a) looksLikeOversizeError matched the server's phrasing
+ // (b) the request body is re-serialized cleanly on each retry
+ // (c) the response parser correctly handles the error body
+ // on rejects AND the success body on acceptance
+ const v = await fetchEmbedding("a".repeat(800), smallCfg)
+ expect(v, `halving failed: ${getLastEmbeddingError()}`).not.toBeNull()
+ expect(v!.length).toBe(8)
+ expect(getLastEmbeddingError()).toBeNull()
+ expect(server.requestSizes()).toEqual([800, 400, 200])
+ } finally {
+ await server.close()
+ }
+ })
+
+ it("surfaces the 'rejected input even at N chars' error when every halving round fails", async () => {
+ // max 50 chars — below the 64-char halving floor, so the
+ // halving loop will retry 2048 → 1024 → 512 → 256 (exhausting
+ // the 3-retry budget) and give up with the specific oversize
+ // error message, NOT the generic API-error message.
+ const server = await startFakeEmbeddingServer(/* maxInputChars */ 50)
+ try {
+ const smallCfg = {
+ enabled: true,
+ endpoint: server.url,
+ apiKey: "",
+ model: "fake-embed",
+ }
+ const v = await fetchEmbedding("a".repeat(2048), smallCfg)
+ expect(v).toBeNull()
+ expect(server.requestSizes()).toEqual([2048, 1024, 512, 256])
+
+ const err = getLastEmbeddingError()!
+ expect(err).toContain("Endpoint rejected input even at 256 chars")
+ expect(err).toContain("Lower Settings → Embedding → Max Chunk Chars")
+ } finally {
+ await server.close()
+ }
+ })
+
+ it("stops halving at the 64-char floor and reports the specific error (128 → 64, no further)", async () => {
+ // Server rejects everything over 0 chars, so every attempt fails.
+ // Input 128 → halve to 64 → 64 is NOT > 64 so loop exits. Exactly
+ // 2 server hits.
+ const server = await startFakeEmbeddingServer(/* maxInputChars */ 0)
+ try {
+ const smallCfg = {
+ enabled: true,
+ endpoint: server.url,
+ apiKey: "",
+ model: "fake-embed",
+ }
+ const v = await fetchEmbedding("a".repeat(128), smallCfg)
+ expect(v).toBeNull()
+ expect(server.requestSizes()).toEqual([128, 64])
+ const err = getLastEmbeddingError()!
+ expect(err).toContain("Endpoint rejected input even at 64 chars")
+ } finally {
+ await server.close()
+ }
+ })
+})
+
+// ── Multi-page RAG pipeline — real chunking + embedding + retrieval ──
+//
+// What this block actually proves:
+//
+// The earlier tests pin the HTTP contract and pairwise similarity on
+// synthetic strings. These tests build 4 ground-truth wiki pages
+// (frontmatter, headings, code, CJK, a table), run each through the
+// REAL embedPage pipeline (chunker → enrichment → fetchEmbedding →
+// upsert payload), capture the resulting vectors, then drive
+// searchByEmbedding against an in-memory LanceDB stand-in and assert
+// that semantic queries pick the right page. If any stage in that
+// chain regresses, a query stops routing to the correct page and
+// this suite fires — whereas the mocked tests would stay green.
+//
+// LanceDB is stubbed (not reachable under Node), but the Rust side has
+// its own 15-test suite; we're concerned with the TypeScript pipeline
+// here.
+
+interface StoredChunk {
+ chunk_id: string
+ page_id: string
+ chunk_index: number
+ chunk_text: string
+ heading_path: string
+ embedding: number[]
+}
+
+/** Cosine score identical to LanceDB's default `cosine` metric. */
+function cosineScore(a: number[], b: number[]): number {
+ let dot = 0
+ let na = 0
+ let nb = 0
+ for (let i = 0; i < a.length; i++) {
+ dot += a[i] * b[i]
+ na += a[i] * a[i]
+ nb += b[i] * b[i]
+ }
+ return dot / (Math.sqrt(na) * Math.sqrt(nb))
+}
+
+// Deterministic fixture set with clear semantic boundaries. Each page
+// is purposely ≥ 1500 chars so the chunker emits ≥ 2 chunks, giving
+// the tail-sum blending a chance to kick in.
+const FIXTURES: Array<{ id: string; title: string; content: string }> = [
+ {
+ id: "rope",
+ title: "RoPE 旋转位置编码",
+ content: `---
+title: "RoPE 旋转位置编码"
+type: concept
+---
+
+# RoPE 旋转位置编码
+
+Rotary positional embeddings (RoPE) are a relative position-encoding
+scheme for Transformer attention. Instead of adding an absolute
+positional vector to token embeddings, RoPE rotates the query and key
+vectors in the complex plane by an angle that depends on the token's
+position. Two tokens separated by the same distance therefore land at
+the same relative rotation, giving the attention score a clean
+translation-equivariance property.
+
+## 数学原理
+
+Given a query vector \`q\` at position \`m\` and a key vector \`k\` at
+position \`n\`, RoPE rotates each pair of dimensions by an angle
+proportional to the position index. The dot product between the
+rotated vectors depends only on the relative offset \`m - n\`, which
+is why RoPE generalizes better to longer contexts than additive
+absolute encodings.
+
+\`\`\`python
+# 2D rotation applied to each adjacent pair of dims
+theta_i = base ** (-2 * i / d)
+q_rot = q * cos(m * theta) + rotate_half(q) * sin(m * theta)
+\`\`\`
+
+## 与 Flash Attention 的关系
+
+RoPE 只改变 Q 和 K 的旋转,不影响 Value,所以它可以和 Flash Attention
+kernel 无缝叠加。这两项技术共同支撑了大部分现代长上下文模型的推理流程。`,
+ },
+ {
+ id: "flash-attention",
+ title: "Flash Attention",
+ content: `---
+title: "Flash Attention"
+type: concept
+---
+
+# Flash Attention
+
+Flash Attention is a memory-efficient exact attention algorithm that
+reorganizes the attention computation to minimize traffic between
+GPU HBM and SRAM. The standard attention kernel materializes the full
+N×N attention matrix in HBM, which dominates memory bandwidth and
+caps the practical context length. Flash Attention instead computes
+attention in a tiled, fused fashion: it streams blocks of queries and
+keys through fast on-chip SRAM, accumulating the softmax-weighted
+outputs incrementally without ever writing the full attention matrix
+to HBM.
+
+## Why it matters
+
+The win is not asymptotic — it is still O(N²) in FLOPs — but the
+constant factor on memory movement drops by an order of magnitude,
+which turns "run out of memory at 4k tokens" into "comfortably train
+at 64k". This memory-bandwidth reduction is the single biggest
+practical enabler of long-context LLM training and inference on
+commodity H100 / A100 hardware.
+
+## IO-aware tiling details
+
+The tiling block size is chosen so that a tile of Q, K, and V fits
+into SRAM simultaneously. The softmax is made numerically stable
+across tiles via an online running-max trick, so accuracy matches the
+standard implementation exactly.
+
+| 变体 | 用途 |
+|-----------------|----------------------------------------|
+| FlashAttn v1 | 推理 + 训练,float16 |
+| FlashAttn v2 | 更细的 warp-level 切分, 2x 吞吐 |
+| FlashAttn v3 | Hopper H100 TMA + async softmax |`,
+ },
+ {
+ id: "ice-cream",
+ title: "Chocolate Ice Cream",
+ content: `---
+title: "Chocolate Ice Cream"
+type: recipe
+---
+
+# Chocolate Ice Cream
+
+Chocolate ice cream is a popular frozen dessert made by churning a
+custard base of heavy cream, milk, sugar, egg yolks, and cocoa or
+melted dark chocolate. The churning incorporates air while freezing
+the water content into very small ice crystals, producing the
+characteristic smooth, scoopable texture.
+
+## A classic home recipe
+
+You can make a traditional French-style chocolate ice cream at home
+with a stand mixer and an ice cream maker. Start by heating the
+cream, milk, and half the sugar over medium heat until the sugar
+dissolves. Whisk the yolks with the remaining sugar until pale, then
+temper in the hot cream and return to the pot to cook into a custard.
+Stir in cocoa powder and melted dark chocolate off the heat, then
+chill the base thoroughly before churning.
+
+## Serving suggestions
+
+Serve in chilled glass bowls with whipped cream, toasted almonds, or
+fresh berries. A pinch of flaky salt on top brings out the cocoa
+notes. Pairs well with espresso, hot fudge, or a simple shortbread
+cookie on the side.`,
+ },
+ {
+ id: "tea-ceremony-ja",
+ title: "日本茶道",
+ content: `---
+title: "日本茶道"
+type: culture
+---
+
+# 日本茶道 (Japanese Tea Ceremony)
+
+日本茶道,也称"茶の湯",是以准备和奉上抹茶 (matcha) 为中心的传统仪式。
+它融合了禅宗哲学、陶瓷艺术、书道和插花 (ikebana),强调"和敬清寂"四个
+核心精神:和谐、尊重、纯净、寂静。
+
+## 仪式流程
+
+客人进入茶室前,会先在露地 (roji,茶庭) 中净手、净口;主人则按照严格的
+顺序清洁器具、点茶、奉茶。一场正式的茶事 (chaji) 会持续约四小时,
+包含怀石料理、浓茶、薄茶等多个阶段,每一个动作都有精确的规范。
+
+## 茶具与流派
+
+主要流派有里千家、表千家、武者小路千家三大千家,各自在手法与道具上略
+有差异。常用器具包括茶碗 (chawan)、茶筅 (chasen)、茶杓 (chashaku) 和
+枣 (natsume)。`,
+ },
+]
+
+describe("real-embedding RAG pipeline — multi-page retrieval", () => {
+ const CHUNK_STORE: StoredChunk[] = []
+ const PROJECT_PATH = "/tmp/real-llm-rag"
+ let beforeAllError: Error | null = null
+
+ beforeAll(async () => {
+ if (!ENABLED) return
+ try {
+ mockInvoke.mockReset()
+ // Default handler: upsert captures into our in-memory store,
+ // search delegates to cosine-sim over that store. No other
+ // Tauri commands are called by the pipeline.
+ mockInvoke.mockImplementation(async (cmd, args) => {
+ if (cmd === "vector_upsert_chunks") {
+ const payload = args as {
+ pageId: string
+ chunks: Array<{
+ chunk_index: number
+ chunk_text: string
+ heading_path: string
+ embedding: number[]
+ }>
+ }
+ // Delete existing chunks for this page, then append. Mirrors
+ // the Rust side's delete-then-add semantics.
+ for (let i = CHUNK_STORE.length - 1; i >= 0; i--) {
+ if (CHUNK_STORE[i].page_id === payload.pageId) CHUNK_STORE.splice(i, 1)
+ }
+ for (const c of payload.chunks) {
+ CHUNK_STORE.push({
+ chunk_id: `${payload.pageId}#${c.chunk_index}`,
+ page_id: payload.pageId,
+ chunk_index: c.chunk_index,
+ chunk_text: c.chunk_text,
+ heading_path: c.heading_path,
+ embedding: c.embedding,
+ })
+ }
+ return undefined
+ }
+ if (cmd === "vector_search_chunks") {
+ const { queryEmbedding, topK } = args as {
+ queryEmbedding: number[]
+ topK: number
+ }
+ return CHUNK_STORE.map((c) => ({
+ chunk_id: c.chunk_id,
+ page_id: c.page_id,
+ chunk_index: c.chunk_index,
+ chunk_text: c.chunk_text,
+ heading_path: c.heading_path,
+ score: cosineScore(queryEmbedding, c.embedding),
+ }))
+ .sort((a, b) => b.score - a.score)
+ .slice(0, topK)
+ }
+ return undefined
+ })
+
+ // Embed each fixture page — this exercises chunker + enrichment +
+ // fetchEmbedding + the upsert payload construction with REAL
+ // vectors. All four pages go through the same default config, so
+ // the chunker tuning is what the production code uses.
+ for (const page of FIXTURES) {
+ await embedPage(PROJECT_PATH, page.id, page.title, page.content, cfg)
+ }
+ } catch (err) {
+ beforeAllError = err instanceof Error ? err : new Error(String(err))
+ }
+ }, 3 * 60 * 1000)
+
+ // ── Contract tests on the captured upsert payloads ─────────────
+ it.skipIf(!ENABLED)("embedded every fixture page with ≥ 2 chunks and valid vectors", () => {
+ if (beforeAllError) throw beforeAllError
+
+ // Every fixture must contribute at least 2 chunks to the store,
+ // proving the chunker actually split long sections.
+ for (const page of FIXTURES) {
+ const pageChunks = CHUNK_STORE.filter((c) => c.page_id === page.id)
+ expect(pageChunks.length, `page "${page.id}" produced too few chunks`).toBeGreaterThanOrEqual(2)
+
+ // Chunk indexes must be contiguous 0..N-1.
+ const idxs = pageChunks.map((c) => c.chunk_index).sort((a, b) => a - b)
+ expect(idxs).toEqual(idxs.map((_, i) => i))
+
+ // Every chunk has a real embedding vector of consistent dim,
+ // every component finite. A regression that dropped Math.fround
+ // or corrupted the response would show up as NaN here.
+ const dim = pageChunks[0].embedding.length
+ expect(dim).toBeGreaterThan(0)
+ for (const c of pageChunks) {
+ expect(c.embedding.length).toBe(dim)
+ for (const x of c.embedding) {
+ expect(Number.isFinite(x)).toBe(true)
+ }
+ }
+ }
+
+ // Every chunk should carry SOME heading breadcrumb — fixture
+ // pages all have H1/H2/H3 structure, and the preamble that sits
+ // directly under the H1 still inherits "# Title".
+ const noHeading = CHUNK_STORE.filter((c) => c.heading_path.length === 0)
+ expect(noHeading, `chunks missing heading path: ${noHeading.map((c) => c.chunk_id).join(", ")}`).toHaveLength(0)
+ })
+
+ // ── Semantic retrieval queries — the actual RAG quality test ────
+
+ /**
+ * For each query, drive `searchByEmbedding` (which calls the real
+ * embedding endpoint for the query, then our in-memory search mock
+ * for the chunk scan) and assert the expected page ranks first.
+ */
+ const queries: Array<{ q: string; expectedTop: string; lang: string }> = [
+ { q: "positional encoding in transformer attention", expectedTop: "rope", lang: "en" },
+ { q: "how to reduce attention memory and avoid OOM at long context", expectedTop: "flash-attention", lang: "en" },
+ { q: "homemade dessert with heavy cream and cocoa", expectedTop: "ice-cream", lang: "en" },
+ { q: "抹茶 仪式 禅宗", expectedTop: "tea-ceremony-ja", lang: "zh" },
+ { q: "旋转位置编码如何注入位置信息", expectedTop: "rope", lang: "zh" },
+ ]
+
+ for (const { q, expectedTop, lang } of queries) {
+ it.skipIf(!ENABLED)(
+ `query ranks "${expectedTop}" first: [${lang}] "${q}"`,
+ async () => {
+ if (beforeAllError) throw beforeAllError
+
+ const out = await searchByEmbedding(PROJECT_PATH, q, cfg, 3)
+ const ordered = out.map((p) => `${p.id}(${p.score.toFixed(3)})`).join(" > ")
+ // eslint-disable-next-line no-console
+ console.log(`[RAG] "${q}" → ${ordered}`)
+
+ expect(out.length).toBeGreaterThan(0)
+ expect(
+ out[0].id,
+ `expected "${expectedTop}" at rank 1, got ranking: ${ordered}`,
+ ).toBe(expectedTop)
+
+ // The winning page must be meaningfully ahead of the runner-up,
+ // not a coin-flip tie. 5% of the top score is a modest margin
+ // that still catches "barely winning by noise".
+ if (out.length >= 2) {
+ const gap = out[0].score - out[1].score
+ expect(
+ gap,
+ `top-1 score gap too small (${gap.toFixed(4)}) — ${ordered}`,
+ ).toBeGreaterThan(out[0].score * 0.05)
+ }
+
+ // The winning page should expose matched chunks with the
+ // highest-similarity chunk actually coming from the expected
+ // page — i.e. the retrieval isn't winning because of blended
+ // tail noise.
+ expect(out[0].matchedChunks, "winning page missing matchedChunks").toBeTruthy()
+ expect(out[0].matchedChunks![0].score).toBeGreaterThan(0.3)
+ },
+ TEST_TIMEOUT_MS,
+ )
+ }
+
+ it.skipIf(!ENABLED)(
+ "heading-path enrichment: query naming the H2 of a chunk routes to that chunk",
+ async () => {
+ if (beforeAllError) throw beforeAllError
+ // "IO-aware tiling" is the exact H2 inside flash-attention. The
+ // text of that section's body is short-ish; without the heading
+ // being prefixed into the embedded input, retrieval would likely
+ // miss it. Asserting this specific chunk wins its page verifies
+ // the `enrichChunkForEmbedding` contribution end-to-end.
+ const out = await searchByEmbedding(PROJECT_PATH, "IO-aware tiling block size SRAM", cfg, 3)
+ expect(out[0].id).toBe("flash-attention")
+ const topChunk = out[0].matchedChunks![0]
+ expect(
+ topChunk.headingPath,
+ `top chunk's heading path doesn't name IO-aware tiling: ${topChunk.headingPath}`,
+ ).toContain("IO-aware")
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ // ── Precision / exclusion — "what should NOT rank highly" ──────
+
+ /**
+ * For each query, the fixture set includes obviously-unrelated
+ * pages whose raw cosine similarity should be clearly lower than
+ * the on-topic page. This doesn't re-check the winner (already
+ * tested above); it pins *how far behind* the wrong pages land.
+ *
+ * If retrieval regresses into near-random ordering — e.g. a
+ * title-prefix dominates the vector so everything scores ≈ 0.8 —
+ * the winner might still be right but the margin collapses, and
+ * these thresholds fire.
+ */
+ const precisionCases: Array<{
+ q: string
+ expectedTop: string
+ mustBeBelow: Record<string, number>
+ }> = [
+ {
+ q: "positional encoding in transformer attention",
+ expectedTop: "rope",
+ // Ice cream and tea ceremony have nothing to do with Transformers.
+ // Past real runs scored them 0.22 / 0.30 respectively — 0.5 is a
+ // conservative ceiling that still catches a serious regression.
+ mustBeBelow: { "ice-cream": 0.5, "tea-ceremony-ja": 0.5 },
+ },
+ {
+ q: "homemade dessert with heavy cream and cocoa",
+ expectedTop: "ice-cream",
+ // RoPE / Flash Attention should be the bottom here.
+ mustBeBelow: { rope: 0.5, "flash-attention": 0.5 },
+ },
+ {
+ q: "抹茶 仪式 禅宗",
+ expectedTop: "tea-ceremony-ja",
+ mustBeBelow: { rope: 0.5, "flash-attention": 0.5 },
+ },
+ ]
+
+ for (const { q, expectedTop, mustBeBelow } of precisionCases) {
+ it.skipIf(!ENABLED)(
+ `precision: "${q}" ranks ${expectedTop} first and keeps unrelated pages below thresholds`,
+ async () => {
+ if (beforeAllError) throw beforeAllError
+ // Fetch all pages (topK large enough to see every page_id) so
+ // we can assert on both the winner and the tail.
+ const out = await searchByEmbedding(PROJECT_PATH, q, cfg, 10)
+ expect(out[0].id).toBe(expectedTop)
+
+ const byId = new Map(out.map((p) => [p.id, p.score]))
+ for (const [id, ceiling] of Object.entries(mustBeBelow)) {
+ const score = byId.get(id)
+ expect(
+ score,
+ `"${id}" missing from search output for query "${q}" — expected to appear with a low score`,
+ ).toBeDefined()
+ expect(
+ score!,
+ `"${id}" scored ${score?.toFixed(3)} for query "${q}", above the ${ceiling} ceiling. Full ordering: ${out
+ .map((p) => `${p.id}(${p.score.toFixed(3)})`)
+ .join(" > ")}`,
+ ).toBeLessThan(ceiling)
+ }
+ },
+ TEST_TIMEOUT_MS,
+ )
+ }
+
+ it.skipIf(!ENABLED)(
+ "out-of-domain query: top score is lower than in-domain queries (confidence signal)",
+ async () => {
+ if (beforeAllError) throw beforeAllError
+ // No fixture page discusses JVM garbage collection. The top
+ // match still has to be something (retrieval always returns
+ // the most-similar page available), but its BLENDED score
+ // should be noticeably lower than an in-domain query's top
+ // score — otherwise the UI has no signal for "I'm not sure
+ // anything here is a match."
+ const inDomain = await searchByEmbedding(
+ PROJECT_PATH,
+ "positional encoding in transformer attention",
+ cfg,
+ 3,
+ )
+ const outOfDomain = await searchByEmbedding(
+ PROJECT_PATH,
+ "JVM generational garbage collector tuning G1 vs ZGC",
+ cfg,
+ 3,
+ )
+ // eslint-disable-next-line no-console
+ console.log(
+ `[RAG] in-domain top=${inDomain[0].score.toFixed(3)} (${inDomain[0].id}), ` +
+ `out-of-domain top=${outOfDomain[0].score.toFixed(3)} (${outOfDomain[0].id})`,
+ )
+ expect(
+ outOfDomain[0].score,
+ `out-of-domain query's top score (${outOfDomain[0].score.toFixed(3)}) should be lower than in-domain (${inDomain[0].score.toFixed(3)}). If they tie, retrieval has no confidence signal.`,
+ ).toBeLessThan(inDomain[0].score - 0.2)
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)(
+ "exact title query ranks the named page first with a very high score",
+ async () => {
+ if (beforeAllError) throw beforeAllError
+ const out = await searchByEmbedding(PROJECT_PATH, "Flash Attention", cfg, 3)
+ expect(out[0].id).toBe("flash-attention")
+ // An exact title match should comfortably clear 0.8. Lower
+ // would indicate a regression in title-prefix enrichment.
+ expect(out[0].score).toBeGreaterThan(0.8)
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)("topK cutoff: requesting 2 returns exactly 2 pages (not more, not fewer)", async () => {
+ if (beforeAllError) throw beforeAllError
+ const out = await searchByEmbedding(PROJECT_PATH, "attention memory", cfg, 2)
+ expect(out).toHaveLength(2)
+ })
+
+ it.skipIf(!ENABLED)(
+ "topK larger than corpus returns every page exactly once (no duplicates, no synthetic padding)",
+ async () => {
+ if (beforeAllError) throw beforeAllError
+ const out = await searchByEmbedding(PROJECT_PATH, "knowledge", cfg, 100)
+ // 4 fixture pages → exactly 4 results, no dup page_ids.
+ expect(out).toHaveLength(FIXTURES.length)
+ const ids = out.map((p) => p.id).sort()
+ expect(ids).toEqual(FIXTURES.map((f) => f.id).sort())
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)(
+ "re-embedding the same pageId replaces its chunks (no accumulation / duplication)",
+ async () => {
+ if (beforeAllError) throw beforeAllError
+
+ // Use a scratch pageId that isn't one of the canonical FIXTURES
+ // so we don't contaminate state for other tests in this block.
+ const scratchId = "scratch-replace-test"
+ const original = `# Original\n\n${"Original body about Transformer decoders. ".repeat(20)}`
+ const updated = `# Updated\n\n${"Updated body about kangaroo migration patterns across Australia. ".repeat(20)}`
+
+ try {
+ // First ingest.
+ await embedPage(PROJECT_PATH, scratchId, "Original", original, cfg)
+ const firstCount = CHUNK_STORE.filter((c) => c.page_id === scratchId).length
+ expect(firstCount, "first ingest produced zero chunks").toBeGreaterThan(0)
+ const originalSample = CHUNK_STORE.find((c) => c.page_id === scratchId)!.chunk_text
+ expect(originalSample).toContain("Original body about Transformer")
+
+ // Re-ingest with completely different content under the SAME id.
+ await embedPage(PROJECT_PATH, scratchId, "Updated", updated, cfg)
+ const afterChunks = CHUNK_STORE.filter((c) => c.page_id === scratchId)
+
+ // If delete-then-append regressed to pure append, we'd see
+ // firstCount + newCount chunks. The contract is: only the
+ // updated content remains.
+ expect(
+ afterChunks.some((c) => c.chunk_text.includes("Original body about Transformer")),
+ "old chunks not purged — saw Original content after re-embed, indicating append semantics instead of replace",
+ ).toBe(false)
+ expect(
+ afterChunks.some((c) => c.chunk_text.includes("kangaroo migration")),
+ "new content missing from store after re-embed",
+ ).toBe(true)
+
+ // Retrieval signal: a query that matched the OLD content must
+ // no longer rank the scratch page first.
+ const oldQueryOut = await searchByEmbedding(
+ PROJECT_PATH,
+ "Transformer decoder body",
+ cfg,
+ FIXTURES.length + 1,
+ )
+ const scratchRank = oldQueryOut.findIndex((p) => p.id === scratchId)
+ if (scratchRank >= 0) {
+ expect(
+ oldQueryOut[scratchRank].score,
+ `scratch page still scored high (${oldQueryOut[scratchRank].score}) for old-content query — replace semantics likely broken`,
+ ).toBeLessThan(0.6)
+ }
+ } finally {
+ // Always clean up so a failure mid-test doesn't leak state
+ // into the "empty query" test at the end of the describe.
+ for (let i = CHUNK_STORE.length - 1; i >= 0; i--) {
+ if (CHUNK_STORE[i].page_id === scratchId) CHUNK_STORE.splice(i, 1)
+ }
+ }
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it.skipIf(!ENABLED)(
+ "empty / whitespace-only query: does not crash; returns an array with only finite scores",
+ async () => {
+ if (beforeAllError) throw beforeAllError
+ // The UI gates search on a non-empty trimmed query, but the
+ // library MUST NOT crash on degenerate input. A regression
+ // here would be a runtime error, not just a bad ranking.
+ const emptyOut = await searchByEmbedding(PROJECT_PATH, "", cfg, 5)
+ const whitespaceOut = await searchByEmbedding(PROJECT_PATH, " \n\t", cfg, 5)
+
+ // Contract: return type is always Array (never undefined/null),
+ // so callers can `.map` / `.length` without guards.
+ expect(Array.isArray(emptyOut), "empty query returned non-array").toBe(true)
+ expect(Array.isArray(whitespaceOut), "whitespace query returned non-array").toBe(true)
+
+ for (const [label, out] of [
+ ["empty", emptyOut],
+ ["whitespace", whitespaceOut],
+ ] as const) {
+ for (const p of out) {
+ expect(Number.isFinite(p.score), `${label}: NaN/Infinity score leaked into ${p.id}`).toBe(true)
+ expect(typeof p.id, `${label}: non-string page id`).toBe("string")
+ expect(p.id.length, `${label}: empty page id`).toBeGreaterThan(0)
+ }
+ }
+ },
+ TEST_TIMEOUT_MS,
+ )
+})
diff --git a/src/lib/embedding.test.ts b/src/lib/embedding.test.ts
index 557eae65..fd085594 100644
--- a/src/lib/embedding.test.ts
+++ b/src/lib/embedding.test.ts
@@ -37,7 +37,12 @@ vi.mock("@/commands/fs", () => ({
import {
searchByEmbedding,
embedPage,
+ embedAllPages,
getLastEmbeddingError,
+ legacyVectorRowCount,
+ dropLegacyVectorTable,
+ getEmbeddingCount,
+ removePageEmbedding,
type PageSearchResult,
} from "./embedding"
@@ -110,14 +115,13 @@ describe("searchByEmbedding — aggregation", () => {
expect(out[2].score).toBeCloseTo(0.2, 5)
})
- it("caps tail contribution so a page with many weak chunks can't overtake a strong single-chunk page", async () => {
+ it("caps tail contribution so the blended score cannot exceed 1.0", async () => {
mockHttpFetch.mockResolvedValue(okResponse([0.1, 0.2, 0.3]))
// Page X: one chunk at 0.6, four chunks at 0.4 each (tail sum = 1.6).
- // top=0.6, tail_weighted = 0.3 * 1.6 = 0.48, capped at 1 - 0.6 = 0.4
- // blended = 0.6 + 0.4 = 1.0
- // Page Y: single 0.95 chunk.
- // blended = 0.95
- // X would unfairly win if we didn't cap the tail.
+ // top=0.6, tail_weighted = 0.3 * 1.6 = 0.48
+ // UNCAPPED blended = 0.6 + 0.48 = 1.08 (would exceed 1.0)
+ // CAPPED blended = 0.6 + min(0.48, 1-0.6=0.4) = 1.0
+ // Page Y: single 0.95 chunk. blended = 0.95.
mockInvoke.mockResolvedValueOnce([
{ chunk_id: "X#0", page_id: "X", chunk_index: 0, chunk_text: "", heading_path: "", score: 0.6 },
{ chunk_id: "X#1", page_id: "X", chunk_index: 1, chunk_text: "", heading_path: "", score: 0.4 },
@@ -127,11 +131,65 @@ describe("searchByEmbedding — aggregation", () => {
{ chunk_id: "Y#0", page_id: "Y", chunk_index: 0, chunk_text: "", heading_path: "", score: 0.95 },
])
const out: PageSearchResult[] = await searchByEmbedding("/tmp/p", "q", cfg, 10)
- // X can reach 1.0 but Y is 0.95 — both are valid cap outcomes; the
- // key assertion is that X does NOT score 0.6 + 0.48 = 1.08 (uncapped
- // math), which the cap is designed to prevent.
- const x = out.find((p) => p.id === "X")!
- expect(x.score).toBeLessThanOrEqual(1.0 + 1e-6)
+
+ // Order must be X then Y (X at the exact cap of 1.0 beats Y at 0.95).
+ expect(out.map((p) => p.id)).toEqual(["X", "Y"])
+ // Exact pinned score: if the cap regressed (e.g. uncapped sum),
+ // X would land at 1.08 and this assertion would fail loudly.
+ expect(out[0].score).toBeCloseTo(1.0, 10)
+ expect(out[1].score).toBeCloseTo(0.95, 10)
+ })
+
+ it("applies the tail contribution below the cap when weighted tail < (1 - top)", async () => {
+ mockHttpFetch.mockResolvedValue(okResponse([0.1]))
+ // top=0.5, tail=[0.1, 0.1]. weighted = 0.3 * 0.2 = 0.06.
+ // cap room = 1 - 0.5 = 0.5. min(0.06, 0.5) = 0.06.
+ // blended = 0.56 — below the cap, so tail contribution passes through.
+ mockInvoke.mockResolvedValueOnce([
+ { chunk_id: "P#0", page_id: "P", chunk_index: 0, chunk_text: "", heading_path: "", score: 0.5 },
+ { chunk_id: "P#1", page_id: "P", chunk_index: 1, chunk_text: "", heading_path: "", score: 0.1 },
+ { chunk_id: "P#2", page_id: "P", chunk_index: 2, chunk_text: "", heading_path: "", score: 0.1 },
+ ])
+ const out = await searchByEmbedding("/tmp/p", "q", cfg, 10)
+ expect(out[0].score).toBeCloseTo(0.56, 10)
+ })
+
+ it("over-fetches topK × 3 chunks with a floor of 30 so the page-grouping has enough candidates", async () => {
+ // mockImplementation returns a FRESH Response per call — Response
+ // bodies are single-use and mockResolvedValue would fail on the
+ // second searchByEmbedding call below.
+ mockHttpFetch.mockImplementation(async () => okResponse([0.1]))
+ mockInvoke.mockResolvedValueOnce([])
+ await searchByEmbedding("/tmp/p", "q", cfg, 3)
+ // topK=3 → max(9, 30) = 30
+ const searchCall = mockInvoke.mock.calls.find((c) => c[0] === "vector_search_chunks")!
+ expect((searchCall[1] as { topK: number }).topK).toBe(30)
+
+ mockInvoke.mockReset()
+ mockInvoke.mockResolvedValueOnce([])
+ await searchByEmbedding("/tmp/p", "q", cfg, 20)
+ // topK=20 → max(60, 30) = 60
+ const searchCall2 = mockInvoke.mock.calls.find((c) => c[0] === "vector_search_chunks")!
+ expect((searchCall2[1] as { topK: number }).topK).toBe(60)
+ })
+
+ it("returns [] when the LanceDB search command throws (doesn't leak the error)", async () => {
+ mockHttpFetch.mockResolvedValue(okResponse([0.1]))
+ mockInvoke.mockRejectedValueOnce(new Error("lancedb: could not open table"))
+ const out = await searchByEmbedding("/tmp/p", "q", cfg, 5)
+ expect(out).toEqual([])
+ })
+
+ it("sorts matchedChunks by score descending regardless of server return order", async () => {
+ mockHttpFetch.mockResolvedValue(okResponse([0.1]))
+ // Feed chunks in unsorted order; matchedChunks must still be sorted.
+ mockInvoke.mockResolvedValueOnce([
+ { chunk_id: "A#0", page_id: "A", chunk_index: 0, chunk_text: "low", heading_path: "", score: 0.3 },
+ { chunk_id: "A#1", page_id: "A", chunk_index: 1, chunk_text: "high", heading_path: "", score: 0.9 },
+ { chunk_id: "A#2", page_id: "A", chunk_index: 2, chunk_text: "mid", heading_path: "", score: 0.5 },
+ ])
+ const out = await searchByEmbedding("/tmp/p", "q", cfg, 5)
+ expect(out[0].matchedChunks!.map((c) => c.text)).toEqual(["high", "mid", "low"])
})
it("attaches up to 3 matched chunks with metadata", async () => {
@@ -208,33 +266,121 @@ describe("fetchEmbedding (via searchByEmbedding) — auto-halve", () => {
const out = await searchByEmbedding("/tmp/p", "hello", cfg, 5)
expect(out).toEqual([])
expect(mockHttpFetch).toHaveBeenCalledTimes(1)
- expect(getLastEmbeddingError()).toMatch(/401/)
+ // Pin the full "API <status> <statusText> — <body>" shape so a
+ // regression that dropped the statusText or body text is caught.
+ const err = getLastEmbeddingError()!
+ expect(err).toContain("API 401 Unauthorized")
+ expect(err).toContain("Invalid API key")
+ expect(err).toContain(cfg.endpoint)
})
- it("gives up after 3 halvings and surfaces a specific error", async () => {
+ it("gives up after 3 halvings and surfaces the 'rejected at N chars' message", async () => {
// A fresh Response instance per call — `mockResolvedValue` returns
// the same object repeatedly and Response bodies can only be
// consumed once, which would mask the real retry count.
mockHttpFetch.mockImplementation(async () => oversizeErrorResponse(400))
const out = await searchByEmbedding("/tmp/p", "a".repeat(2000), cfg, 5)
expect(out).toEqual([])
- // Initial call + 3 retries at halved sizes = 4 attempts.
+ // 2000 → 1000 → 500 → 250: 4 attempts (initial + 3 halvings).
expect(mockHttpFetch).toHaveBeenCalledTimes(4)
- // The final error message should name a concrete smallest size
- // attempted so the user knows how low the server's context is.
- expect(getLastEmbeddingError()).toMatch(/chars/)
+ // Pin the distinctive prefix — loosely matching /chars/ would pass
+ // for BOTH the exhausted-retry case and the 64-char-floor case,
+ // which are different bug signatures.
+ const err = getLastEmbeddingError()!
+ expect(err).toContain("Endpoint rejected input even at")
+ expect(err).toContain("250 chars")
+ expect(err).toContain("Lower Settings → Embedding → Max Chunk Chars")
})
- it("stops halving once text is short enough that retry is pointless", async () => {
- // With a 100-char input and the 64-char floor, only one retry at
- // 50 chars is possible before hitting the floor.
+ it("halving floor: 128-char input stops after 2 attempts (128 → 64; 64 is not > 64 so no further halving)", async () => {
mockHttpFetch.mockImplementation(async () => oversizeErrorResponse(400))
- await searchByEmbedding("/tmp/p", "a".repeat(100), cfg, 5)
- // Attempts: 100 → 50 (still > 64? no, 50 < 64 so no retry) → done.
- // Actually 100 is > 64, halved to 50, then 50 is not > 64, so no
- // further halving. But the current attempt still issues the
- // 50-char request, which also errors. So 2 calls total.
+ await searchByEmbedding("/tmp/p", "a".repeat(128), cfg, 5)
expect(mockHttpFetch).toHaveBeenCalledTimes(2)
+ const lens = mockHttpFetch.mock.calls.map(
+ (c) => JSON.parse((c[1] as RequestInit).body as string).input.length,
+ )
+ expect(lens).toEqual([128, 64])
+ })
+
+ it("halving floor: 130-char input produces 3 attempts (130 → 65 is > 64 so halves once more to 32)", async () => {
+ mockHttpFetch.mockImplementation(async () => oversizeErrorResponse(400))
+ await searchByEmbedding("/tmp/p", "a".repeat(130), cfg, 5)
+ expect(mockHttpFetch).toHaveBeenCalledTimes(3)
+ const lens = mockHttpFetch.mock.calls.map(
+ (c) => JSON.parse((c[1] as RequestInit).body as string).input.length,
+ )
+ expect(lens).toEqual([130, 65, 32])
+ })
+
+ it("recognizes a variety of oversize error phrases (not just 'exceeds maximum context')", async () => {
+ // Table-driven: every phrase that looksLikeOversizeError treats as
+ // oversize must trigger the halve path. If a regression changes
+ // the phrase list, the matching case stops halving (1 call instead
+ // of 2) and this test catches it.
+ const phrases = [
+ "this input is too long for the model",
+ "context length 512 surpassed",
+ "token limit hit",
+ "max_tokens exceeded for this request",
+ "max tokens 2048 is less than input",
+ "input length 3200 is over budget",
+ ]
+ for (const phrase of phrases) {
+ mockHttpFetch.mockReset()
+ mockHttpFetch
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ error: phrase }), { status: 400, statusText: "Bad Request" }),
+ )
+ .mockResolvedValueOnce(okResponse([0.1]))
+ mockInvoke.mockReset()
+ mockInvoke.mockResolvedValueOnce([
+ { chunk_id: "P#0", page_id: "P", chunk_index: 0, chunk_text: "", heading_path: "", score: 0.5 },
+ ])
+ await searchByEmbedding("/tmp/p", "a".repeat(500), cfg, 5)
+ // Exactly 2 fetches = initial rejected + halved succeeded.
+ expect(mockHttpFetch, `phrase="${phrase}"`).toHaveBeenCalledTimes(2)
+ }
+ })
+
+ it("surfaces a 'Network error' message when the fetch itself throws a TypeError", async () => {
+ mockHttpFetch.mockImplementationOnce(async () => {
+ throw new TypeError("Load failed")
+ })
+ const out = await searchByEmbedding("/tmp/p", "q", cfg, 5)
+ expect(out).toEqual([])
+ const err = getLastEmbeddingError()!
+ expect(err).toContain("Network error reaching")
+ expect(err).toContain(cfg.endpoint)
+ })
+
+ it("returns null + surfaces a descriptive error when 200 response is missing data[0].embedding", async () => {
+ mockHttpFetch.mockResolvedValueOnce(
+ new Response(JSON.stringify({ data: [{ wrong_field: [1, 2] }] }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ const out = await searchByEmbedding("/tmp/p", "q", cfg, 5)
+ expect(out).toEqual([])
+ const err = getLastEmbeddingError()!
+ expect(err).toContain("missing data[0].embedding")
+ })
+
+ it("clears lastEmbeddingError after a successful fetch following a failure", async () => {
+ // First call fails with 401 (sets lastEmbeddingError).
+ mockHttpFetch.mockResolvedValueOnce(
+ new Response(JSON.stringify({ error: "Invalid API key" }), { status: 401, statusText: "Unauthorized" }),
+ )
+ await searchByEmbedding("/tmp/p", "q", cfg, 5)
+ expect(getLastEmbeddingError()).toContain("API 401")
+
+ // Second call succeeds → last error must clear.
+ mockHttpFetch.mockResolvedValueOnce(okResponse([0.1]))
+ mockInvoke.mockResolvedValueOnce([
+ { chunk_id: "P#0", page_id: "P", chunk_index: 0, chunk_text: "", heading_path: "", score: 0.5 },
+ ])
+ await searchByEmbedding("/tmp/p", "q", cfg, 5)
+ expect(getLastEmbeddingError()).toBeNull()
})
})
@@ -246,7 +392,7 @@ describe("embedPage", () => {
// double-consumed.
mockHttpFetch.mockImplementation(async () => okResponse([0.1, 0.2, 0.3]))
- // Short page → likely one chunk under default opts.
+ // Short page (60 chars of body) → exactly one chunk under default opts.
await embedPage(
"/tmp/p",
"rope",
@@ -260,18 +406,51 @@ describe("embedPage", () => {
expect(cmd).toBe("vector_upsert_chunks")
// TS→Rust conversion happens at the Tauri boundary — from the TS
// side the arg object keeps its camelCase keys.
- const payload = args as { pageId: string; chunks: Array<{ chunk_index: number; embedding: number[] }> }
+ const payload = args as {
+ pageId: string
+ chunks: Array<{ chunk_index: number; chunk_text: string; heading_path: string; embedding: number[] }>
+ }
expect(payload.pageId).toBe("rope")
- expect(payload.chunks.length).toBeGreaterThan(0)
- // embedding.ts rounds every float to f32 via Math.fround before
- // sending to Rust, which drifts the IEEE-754 representation
- // slightly — compare element-wise with a tolerance instead of
- // strict equality.
+ // Exact count — short body should produce exactly one chunk.
+ expect(payload.chunks).toHaveLength(1)
+ expect(payload.chunks[0].chunk_index).toBe(0)
+ expect(payload.chunks[0].chunk_text).toContain("Rotary positional embeddings")
+ // Math.fround(0.1) / 0.2 / 0.3 are the exact f32 representations
+ // the Rust side will see. Assert the EXACT rounded value so a
+ // regression that removed Math.fround is caught.
const emb = payload.chunks[0].embedding
- expect(emb).toHaveLength(3)
- expect(emb[0]).toBeCloseTo(0.1, 5)
- expect(emb[1]).toBeCloseTo(0.2, 5)
- expect(emb[2]).toBeCloseTo(0.3, 5)
+ expect(emb).toEqual([Math.fround(0.1), Math.fround(0.2), Math.fround(0.3)])
+ // Also confirm f32 rounding actually drifted the representation
+ // (sanity check that we're not comparing to the f64 inputs).
+ expect(emb[0]).not.toBe(0.1)
+ })
+
+ it("keeps successful chunks even when some fail, preserving original chunk_index gaps", async () => {
+ // Two 1100-char paragraphs under default opts produce exactly 3
+ // chunks after packing + merging + overlap. Fail the middle embed
+ // (call index 1) — upsert must receive 2 rows at indexes 0 and 2,
+ // proving the failed chunk's index is preserved (NOT backfilled
+ // to [0, 1]) so a re-embed later can update the gap directly.
+ const para = "a".repeat(1100)
+ const content = `${para}\n\n${para}`
+ let call = 0
+ mockHttpFetch.mockImplementation(async () => {
+ const i = call++
+ // 404 Not Found — not an oversize phrase, so fetchEmbedding
+ // returns null immediately without halving/retrying.
+ if (i === 1) return new Response("not found", { status: 404, statusText: "Not Found" })
+ return okResponse([0.5])
+ })
+
+ await embedPage("/tmp/p", "page", "Page", content, cfg)
+
+ // Exactly 3 embed attempts (one per chunk), 2 successes, 1 upsert.
+ expect(mockHttpFetch).toHaveBeenCalledTimes(3)
+ expect(mockInvoke).toHaveBeenCalledTimes(1)
+ const payload = mockInvoke.mock.calls[0][1] as {
+ chunks: Array<{ chunk_index: number }>
+ }
+ expect(payload.chunks.map((c) => c.chunk_index)).toEqual([0, 2])
})
it("skips LanceDB call when all chunks fail to embed", async () => {
@@ -293,7 +472,7 @@ describe("embedPage", () => {
expect(mockInvoke).not.toHaveBeenCalled()
})
- it("passes page title + heading path + chunk text to the embed request", async () => {
+ it("passes page title + heading path + chunk text joined by blank lines to the embed request", async () => {
mockHttpFetch.mockResolvedValue(okResponse([0.5]))
await embedPage(
@@ -304,10 +483,292 @@ describe("embedPage", () => {
cfg,
)
- expect(mockHttpFetch).toHaveBeenCalled()
const body = JSON.parse((mockHttpFetch.mock.calls[0][1] as RequestInit).body as string)
- expect(body.input).toContain("Attention Mechanism")
- expect(body.input).toContain("## Intro")
- expect(body.input).toContain("Core concept")
+ // Exact shape: title + \n\n + heading path + \n\n + chunk text.
+ // A regression that drops the heading-path prefix (the most
+ // important context signal for short chunks) would be caught here.
+ expect(body.input).toBe(
+ "Attention Mechanism\n\n## Intro\n\n## Intro\n\nCore concept of Transformers.",
+ )
+ })
+
+ it("omits the heading-path prefix when the chunk is preamble (empty headingPath)", async () => {
+ mockHttpFetch.mockResolvedValue(okResponse([0.5]))
+ await embedPage(
+ "/tmp/p",
+ "rope",
+ "RoPE",
+ "Preamble sentence before any heading.",
+ cfg,
+ )
+ const body = JSON.parse((mockHttpFetch.mock.calls[0][1] as RequestInit).body as string)
+ // No empty blank line between title and body — enrichment must
+ // skip empty parts rather than emit `"RoPE\n\n\n\nPreamble..."`.
+ expect(body.input).toBe("RoPE\n\nPreamble sentence before any heading.")
+ })
+
+ it("omits the title prefix when pageTitle is empty/whitespace", async () => {
+ mockHttpFetch.mockResolvedValue(okResponse([0.5]))
+ await embedPage("/tmp/p", "rope", " ", "## H\n\nbody text.", cfg)
+ const body = JSON.parse((mockHttpFetch.mock.calls[0][1] as RequestInit).body as string)
+ // Must NOT start with "\n\n" (would indicate an empty title was
+ // joined in). Must start with the heading path.
+ expect(body.input.startsWith("## H")).toBe(true)
+ })
+
+ it("no-ops when cfg.model is empty (uninitialized embedding config)", async () => {
+ const noModel = { ...cfg, model: "" }
+ await embedPage("/tmp/p", "rope", "RoPE", "some body text", noModel)
+ expect(mockHttpFetch).not.toHaveBeenCalled()
+ expect(mockInvoke).not.toHaveBeenCalled()
+ })
+
+ it("honors cfg.maxChunkChars: smaller value produces more chunks", async () => {
+ // Wiring check for the Settings → Embedding chunk-size knob.
+ // Input is a single paragraph of exactly 2000 chars. With the
+ // default targetChars=1000 we expect ~2 chunks; with maxChunkChars
+ // forced to 400 we should see noticeably more (roughly 5 pieces
+ // before merging). If the draft → cfg → chunker plumbing breaks,
+ // BOTH calls would produce the same chunk count and this fires.
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+
+ const content = "a".repeat(2000)
+
+ mockInvoke.mockClear()
+ await embedPage("/tmp/p", "p", "P", content, { ...cfg })
+ const defaultChunks = (
+ mockInvoke.mock.calls[0][1] as { chunks: unknown[] }
+ ).chunks.length
+
+ mockInvoke.mockClear()
+ await embedPage("/tmp/p", "p", "P", content, {
+ ...cfg,
+ maxChunkChars: 400,
+ })
+ const smallChunks = (
+ mockInvoke.mock.calls[0][1] as { chunks: unknown[] }
+ ).chunks.length
+
+ expect(
+ smallChunks,
+ `expected more chunks at maxChunkChars=400 than at default 1000; got small=${smallChunks} default=${defaultChunks}`,
+ ).toBeGreaterThan(defaultChunks)
+ })
+
+ it("honors cfg.overlapChunkChars: larger overlap produces longer subsequent chunks", async () => {
+ // Wiring check for the overlap knob. Same input, only difference
+ // is overlapChunkChars. Non-first chunks under overlap=200 must
+ // be meaningfully longer than their overlap=0 counterparts —
+ // the overlap injection is literally prepended text.
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+ const content = `${"ab ".repeat(400)}\n\n${"cd ".repeat(400)}`
+
+ mockInvoke.mockClear()
+ await embedPage("/tmp/p", "p", "P", content, { ...cfg, overlapChunkChars: 0 })
+ const zeroOverlap = (
+ mockInvoke.mock.calls[0][1] as { chunks: Array<{ chunk_text: string }> }
+ ).chunks
+
+ mockInvoke.mockClear()
+ await embedPage("/tmp/p", "p", "P", content, { ...cfg, overlapChunkChars: 200 })
+ const bigOverlap = (
+ mockInvoke.mock.calls[0][1] as { chunks: Array<{ chunk_text: string }> }
+ ).chunks
+
+ expect(zeroOverlap.length).toBeGreaterThanOrEqual(2)
+ expect(bigOverlap).toHaveLength(zeroOverlap.length)
+
+ // The first chunk is identical (no prepending); chunks 1..N have
+ // the overlap prefix from the previous chunk's tail added.
+ expect(bigOverlap[0].chunk_text).toBe(zeroOverlap[0].chunk_text)
+ for (let i = 1; i < bigOverlap.length; i++) {
+ const delta = bigOverlap[i].chunk_text.length - zeroOverlap[i].chunk_text.length
+ expect(
+ delta,
+ `chunk[${i}] overlap delta=${delta} (zero=${zeroOverlap[i].chunk_text.length}, big=${bigOverlap[i].chunk_text.length}) — cfg.overlapChunkChars plumbing is probably broken`,
+ ).toBeGreaterThanOrEqual(100)
+ }
+ })
+})
+
+// ── embedAllPages — walk wiki tree, skip structural pages ───────────
+
+describe("embedAllPages", () => {
+ // Helpers to mock the fs commands that embedding.ts reads from.
+ // The mock factory created vi.fn() instances at module load (see the
+ // top-level vi.mock("@/commands/fs", ...)); we grab references here
+ // via dynamic import so per-test setup can script them.
+ let listDirectoryMock: ReturnType<typeof vi.fn>
+ let readFileMock: ReturnType<typeof vi.fn>
+ beforeEach(async () => {
+ const fs = await import("@/commands/fs")
+ listDirectoryMock = fs.listDirectory as ReturnType<typeof vi.fn>
+ readFileMock = fs.readFile as ReturnType<typeof vi.fn>
+ listDirectoryMock.mockReset()
+ readFileMock.mockReset()
+ // Default: every upsert succeeds. Each embed returns a shared
+ // vector via mockHttpFetch — set per-test.
+ mockInvoke.mockResolvedValue(undefined)
+ })
+
+ const makeTree = () => [
+ { name: "rope.md", path: "/proj/wiki/rope.md", is_dir: false },
+ { name: "index.md", path: "/proj/wiki/index.md", is_dir: false }, // skip
+ { name: "log.md", path: "/proj/wiki/log.md", is_dir: false }, // skip
+ { name: "overview.md", path: "/proj/wiki/overview.md", is_dir: false }, // skip
+ { name: "purpose.md", path: "/proj/wiki/purpose.md", is_dir: false }, // skip
+ { name: "schema.md", path: "/proj/wiki/schema.md", is_dir: false }, // skip
+ { name: "notes.txt", path: "/proj/wiki/notes.txt", is_dir: false }, // non-md
+ {
+ name: "sub",
+ path: "/proj/wiki/sub",
+ is_dir: true,
+ children: [
+ { name: "attention.md", path: "/proj/wiki/sub/attention.md", is_dir: false },
+ ],
+ },
+ ]
+
+ it("indexes every non-structural .md file, recursing into subdirs", async () => {
+ listDirectoryMock.mockResolvedValueOnce(makeTree())
+ readFileMock.mockResolvedValue("# Title\n\nBody.")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+
+ const count = await embedAllPages("/proj", cfg)
+
+ // 2 non-structural pages: rope.md and sub/attention.md.
+ expect(count).toBe(2)
+ // 2 upsert invokes, one per indexed page — other commands may
+ // appear if the production code adds helpers later, but this
+ // filter pins the exact pageIds.
+ const upsertCalls = mockInvoke.mock.calls.filter((c) => c[0] === "vector_upsert_chunks")
+ expect(upsertCalls).toHaveLength(2)
+ const pageIds = upsertCalls.map((c) => (c[1] as { pageId: string }).pageId).sort()
+ expect(pageIds).toEqual(["attention", "rope"])
+ })
+
+ it("extracts the title from YAML frontmatter when present", async () => {
+ listDirectoryMock.mockResolvedValueOnce([
+ { name: "rope.md", path: "/proj/wiki/rope.md", is_dir: false },
+ ])
+ readFileMock.mockResolvedValueOnce(
+ `---\ntitle: "RoPE 旋转位置编码"\ntype: concept\n---\n# RoPE\n\nBody.`,
+ )
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+ await embedAllPages("/proj", cfg)
+ const body = JSON.parse((mockHttpFetch.mock.calls[0][1] as RequestInit).body as string)
+ expect(body.input.startsWith("RoPE 旋转位置编码")).toBe(true)
+ })
+
+ it("falls back to the file id (without .md) when frontmatter has no title", async () => {
+ listDirectoryMock.mockResolvedValueOnce([
+ { name: "mystery.md", path: "/proj/wiki/mystery.md", is_dir: false },
+ ])
+ readFileMock.mockResolvedValueOnce("no frontmatter here, just body.")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+ await embedAllPages("/proj", cfg)
+ const body = JSON.parse((mockHttpFetch.mock.calls[0][1] as RequestInit).body as string)
+ expect(body.input.startsWith("mystery")).toBe(true)
+ })
+
+ it("invokes onProgress exactly once per indexed file with increasing done & constant total", async () => {
+ listDirectoryMock.mockResolvedValueOnce(makeTree())
+ readFileMock.mockResolvedValue("body.")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+
+ const progress: Array<[number, number]> = []
+ await embedAllPages("/proj", cfg, (done, total) => progress.push([done, total]))
+ expect(progress).toEqual([
+ [1, 2],
+ [2, 2],
+ ])
+ })
+
+ it("returns 0 and makes no network calls when embedding is disabled", async () => {
+ const disabled = { ...cfg, enabled: false }
+ const out = await embedAllPages("/proj", disabled)
+ expect(out).toBe(0)
+ // Guard runs before listDirectory, so nothing is called.
+ expect(listDirectoryMock).not.toHaveBeenCalled()
+ expect(mockHttpFetch).not.toHaveBeenCalled()
+ })
+
+ it("returns 0 when listDirectory throws (project has no wiki dir yet)", async () => {
+ listDirectoryMock.mockRejectedValueOnce(new Error("ENOENT: no such file"))
+ const out = await embedAllPages("/proj", cfg)
+ expect(out).toBe(0)
+ })
+
+ it("continues with remaining files when one file's readFile throws", async () => {
+ listDirectoryMock.mockResolvedValueOnce([
+ { name: "a.md", path: "/proj/wiki/a.md", is_dir: false },
+ { name: "b.md", path: "/proj/wiki/b.md", is_dir: false },
+ ])
+ // First file fails, second succeeds.
+ readFileMock
+ .mockRejectedValueOnce(new Error("permission denied"))
+ .mockResolvedValueOnce("body for b")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+
+ const count = await embedAllPages("/proj", cfg)
+ // `done` is incremented for every file attempted, even if embed fails.
+ expect(count).toBe(2)
+ const upserts = mockInvoke.mock.calls.filter((c) => c[0] === "vector_upsert_chunks")
+ expect(upserts).toHaveLength(1)
+ expect((upserts[0][1] as { pageId: string }).pageId).toBe("b")
+ })
+})
+
+// ── Legacy & misc helpers ───────────────────────────────────────────
+
+describe("legacyVectorRowCount / dropLegacyVectorTable / getEmbeddingCount / removePageEmbedding", () => {
+ it("legacyVectorRowCount: returns the Rust row count on success, 0 on error", async () => {
+ mockInvoke.mockResolvedValueOnce(42)
+ const n = await legacyVectorRowCount("/proj")
+ expect(n).toBe(42)
+ expect(mockInvoke).toHaveBeenCalledWith("vector_legacy_row_count", {
+ projectPath: "/proj",
+ })
+
+ mockInvoke.mockRejectedValueOnce(new Error("legacy table missing"))
+ const n2 = await legacyVectorRowCount("/proj")
+ expect(n2).toBe(0)
+ })
+
+ it("dropLegacyVectorTable: invokes the Rust command with normalized path, propagates throws", async () => {
+ mockInvoke.mockResolvedValueOnce(undefined)
+ await dropLegacyVectorTable("/proj")
+ expect(mockInvoke).toHaveBeenCalledWith("vector_drop_legacy", {
+ projectPath: "/proj",
+ })
+
+ // Unlike the read helpers, drop is destructive enough that a
+ // failure SHOULD propagate — callers can show the error in UI.
+ mockInvoke.mockRejectedValueOnce(new Error("lock contention"))
+ await expect(dropLegacyVectorTable("/proj")).rejects.toThrow("lock contention")
+ })
+
+ it("getEmbeddingCount: returns chunk count, swallows errors to 0", async () => {
+ mockInvoke.mockResolvedValueOnce(128)
+ expect(await getEmbeddingCount("/proj")).toBe(128)
+ expect(mockInvoke).toHaveBeenCalledWith("vector_count_chunks", {
+ projectPath: "/proj",
+ })
+
+ mockInvoke.mockRejectedValueOnce(new Error("table missing"))
+ expect(await getEmbeddingCount("/proj")).toBe(0)
+ })
+
+ it("removePageEmbedding: invokes vector_delete_page, swallows errors silently", async () => {
+ mockInvoke.mockResolvedValueOnce(undefined)
+ await removePageEmbedding("/proj", "rope")
+ expect(mockInvoke).toHaveBeenCalledWith("vector_delete_page", {
+ projectPath: "/proj",
+ pageId: "rope",
+ })
+
+ mockInvoke.mockRejectedValueOnce(new Error("table missing"))
+ // Must not throw — source-delete flow depends on silent failure.
+ await expect(removePageEmbedding("/proj", "rope")).resolves.toBeUndefined()
})
})
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
index 393562f2..8b12746b 100644
--- a/src/lib/embedding.ts
+++ b/src/lib/embedding.ts
@@ -52,7 +52,7 @@ export function getLastEmbeddingError(): string | null {
* positive just means a retry at half size, which will still succeed
* on a real auth/model-id error (it won't) or just log the same error.
*/
-function looksLikeOversizeError(httpStatus: number, body: string): boolean {
+export function looksLikeOversizeError(httpStatus: number, body: string): boolean {
if (httpStatus === 413) return true
const lower = body.toLowerCase()
return (
@@ -77,7 +77,7 @@ function looksLikeOversizeError(httpStatus: number, body: string): boolean {
* actually got through. Chunker config should be tuned to minimise
* truncation — this is a safety net, not the main line of defence.
*/
-async function fetchEmbedding(
+export async function fetchEmbedding(
text: string,
cfg: EmbeddingConfig,
maxRetries = 3,
diff --git a/src/lib/tauri-fetch.test.ts b/src/lib/tauri-fetch.test.ts
new file mode 100644
index 00000000..330188be
--- /dev/null
+++ b/src/lib/tauri-fetch.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Node-fallback contract for tauri-fetch.
+ *
+ * In production (Tauri webview) `getHttpFetch()` returns the
+ * `@tauri-apps/plugin-http` fetch so CORS-unfriendly endpoints work.
+ * In tests / SSR / storybook `window` is undefined and we must route
+ * through `globalThis.fetch` instead.
+ *
+ * A previous implementation `.catch()`ed the dynamic import — which
+ * never fires because the import SUCCEEDS under Node but the plugin's
+ * internals touch `window` later at call time. The fix is to detect
+ * the Node env BEFORE importing. This test pins that behavior so the
+ * fallback doesn't regress silently (you'd only notice via a vitest
+ * run crash with "window is not defined").
+ */
+import { describe, it, expect } from "vitest"
+import { getHttpFetch, isFetchNetworkError } from "./tauri-fetch"
+
+describe("getHttpFetch — Node fallback", () => {
+ it("returns a callable function under Node (typeof window === undefined)", async () => {
+ expect(typeof window).toBe("undefined")
+ const fn = await getHttpFetch()
+ expect(typeof fn).toBe("function")
+ })
+
+ it("does not throw 'window is not defined' when invoked under Node", async () => {
+ const fn = await getHttpFetch()
+ // Hit a guaranteed-fail address so we don't make a real network
+ // request — the point is to prove the fetch fn can be CALLED
+ // without the plugin's browser-only globals blowing up. A real
+ // network error or a fetch rejection is fine; a ReferenceError
+ // for `window` is the regression we're catching.
+ try {
+ await fn("http://127.0.0.1:1/", { method: "GET" })
+ } catch (err) {
+ if (err instanceof ReferenceError && /window/i.test(err.message)) {
+ throw new Error(
+ `Node fallback regressed — getHttpFetch() returned something that touches window: ${err.message}`,
+ )
+ }
+ // Any other error (ECONNREFUSED / TypeError) is expected and fine.
+ }
+ })
+
+ it("is cached: two calls return the same function reference", async () => {
+ const a = await getHttpFetch()
+ const b = await getHttpFetch()
+ expect(a).toBe(b)
+ })
+})
+
+describe("isFetchNetworkError", () => {
+ it("recognizes WebKit 'Load failed'", () => {
+ const err = new Error("Load failed")
+ expect(isFetchNetworkError(err)).toBe(true)
+ })
+
+ it("recognizes Chromium TypeError", () => {
+ const err = new TypeError("Failed to fetch")
+ expect(isFetchNetworkError(err)).toBe(true)
+ })
+
+ it("rejects AbortError (user cancel) — retries there would loop the cancellation", () => {
+ const err = new Error("The user aborted a request.")
+ err.name = "AbortError"
+ expect(isFetchNetworkError(err)).toBe(false)
+ })
+
+ it("rejects non-Error values (null / string / undefined)", () => {
+ expect(isFetchNetworkError(null)).toBe(false)
+ expect(isFetchNetworkError("oops")).toBe(false)
+ expect(isFetchNetworkError(undefined)).toBe(false)
+ })
+
+ it("matches generic 'network error' substring for less-common backends", () => {
+ const err = new Error("there was a network error while connecting")
+ expect(isFetchNetworkError(err)).toBe(true)
+ })
+})
diff --git a/src/lib/tauri-fetch.ts b/src/lib/tauri-fetch.ts
index a9313572..cd011315 100644
--- a/src/lib/tauri-fetch.ts
+++ b/src/lib/tauri-fetch.ts
@@ -19,6 +19,15 @@
let pluginFetchPromise: Promise<typeof globalThis.fetch> | null = null
+/**
+ * True when running outside a browser / webview (vitest, SSR, any
+ * Node-based tooling). The Tauri plugin is importable in Node
+ * (resolution succeeds) but its internals reach for `window` at call
+ * time, so we must avoid invoking it — guard BEFORE the dynamic
+ * import rather than trying to .catch() an error that happens later.
+ */
+const isNodeEnv = typeof window === "undefined"
+
/**
* Returns a fetch function that routes through Tauri's HTTP plugin in
* production, falling back to the platform's native fetch in non-Tauri
@@ -31,9 +40,14 @@ let pluginFetchPromise: Promise<typeof globalThis.fetch> | null = null
*/
export function getHttpFetch(): Promise<typeof globalThis.fetch> {
if (!pluginFetchPromise) {
- pluginFetchPromise = import("@tauri-apps/plugin-http")
- .then((m) => m.fetch as unknown as typeof globalThis.fetch)
- .catch(() => globalThis.fetch)
+ if (isNodeEnv) {
+ // Bind so `this === globalThis` — Node's fetch requires it.
+ pluginFetchPromise = Promise.resolve(globalThis.fetch.bind(globalThis))
+ } else {
+ pluginFetchPromise = import("@tauri-apps/plugin-http")
+ .then((m) => m.fetch as unknown as typeof globalThis.fetch)
+ .catch(() => globalThis.fetch.bind(globalThis))
+ }
}
return pluginFetchPromise
}
diff --git a/src/lib/text-chunker.test.ts b/src/lib/text-chunker.test.ts
index 556d5ab2..37346622 100644
--- a/src/lib/text-chunker.test.ts
+++ b/src/lib/text-chunker.test.ts
@@ -28,7 +28,9 @@ describe("stripFrontmatter", () => {
const input = "---\ntitle: RoPE\ntype: concept\n---\nBody content"
const { body, bodyOffset } = stripFrontmatter(input)
expect(body).toBe("Body content")
- expect(bodyOffset).toBeGreaterThan(0)
+ // Exact offset — the fence is 4 chars (`---\n`), the body 29 chars,
+ // the close fence 4 chars → body starts at index 33.
+ expect(bodyOffset).toBe("---\ntitle: RoPE\ntype: concept\n---\n".length)
expect(input.slice(bodyOffset)).toBe("Body content")
})
@@ -292,11 +294,24 @@ describe("chunkMarkdown — overlap between adjacent chunks", () => {
it("clamps overlap to half the target when misconfigured", () => {
// overlapChars >= targetChars would infinite-loop the packer; the
- // chunker must silently clamp and still terminate.
+ // chunker must silently clamp to floor(targetChars/2) and still
+ // terminate. A plain `rep("a", N)` input has no sentence/whitespace
+ // separators, so snapOverlapHead returns the tail unchanged → we
+ // can measure the exact overlap by comparing chunk[1] length to
+ // chunk[1]'s original size (= targetChars from the hard-slice).
const input = rep("a", 2000)
const result = chunkMarkdown(input, { targetChars: 200, maxChars: 500, minChars: 20, overlapChars: 500 })
- expect(result.length).toBeGreaterThan(0)
- expect(result.length).toBeLessThan(100) // sanity: terminates quickly
+ // Hard-slice at 200 chars → 10 pieces.
+ expect(result).toHaveLength(10)
+ // chunk[0] is the first slice, untouched.
+ expect(result[0].text).toHaveLength(200)
+ // chunk[1..] = clamp(500 → 100) chars of prev + 200 chars of own →
+ // 300 chars. If the clamp silently regressed to e.g. `overlapChars`
+ // unclamped, `slice(-500)` on a 200-char prev yields 200 chars of
+ // overlap and the second chunk would be 400 chars, not 300.
+ for (let i = 1; i < result.length; i++) {
+ expect(result[i].text).toHaveLength(300)
+ }
})
})
@@ -447,7 +462,10 @@ describe("chunkMarkdown — realistic wiki fixture", () => {
it("produces the expected number of chunks under default options", () => {
const result = chunkMarkdown(wikiPage)
- expect(result.length).toBeGreaterThan(0)
+ // Pin the exact count — regressions in chunking semantics (heading
+ // cuts, atom merging, overlap) all show up here. If the chunker is
+ // retuned intentionally, update this constant deliberately.
+ expect(result).toHaveLength(6)
})
it("each chunk is ≤ maxChars (or flagged oversized)", () => {
@@ -457,14 +475,22 @@ describe("chunkMarkdown — realistic wiki fixture", () => {
}
})
- it("every chunk either has a heading path or is the pre-heading preamble", () => {
+ it("only the preamble chunk has empty headingPath; every heading-scoped chunk has one", () => {
const result = chunkMarkdown(wikiPage)
- for (const c of result) {
- // Non-empty content should be discoverable under some heading,
- // except for preamble (before any `#`) which legitimately has "".
- if (!c.text.startsWith("Rotary")) {
- expect(c.headingPath.length).toBeGreaterThan(0)
- }
+ // Find the preamble chunk structurally (the one containing the
+ // first body paragraph that sits under the H1) — NOT by text
+ // prefix, so this test doesn't silently skip when chunks reorder.
+ const preamble = result.find((c) => c.text.includes("Rotary positional embeddings(RoPE)"))
+ expect(preamble).toBeDefined()
+ expect(preamble!.headingPath).toBe("# RoPE 旋转位置编码")
+
+ // Every OTHER chunk must have a heading path. Without the explicit
+ // split we used to silently skip the assertion when chunk ordering
+ // drifted.
+ const nonPreamble = result.filter((c) => c !== preamble)
+ expect(nonPreamble.length).toBeGreaterThanOrEqual(1)
+ for (const c of nonPreamble) {
+ expect(c.headingPath.length).toBeGreaterThan(0)
}
})
@@ -472,8 +498,12 @@ describe("chunkMarkdown — realistic wiki fixture", () => {
const result = chunkMarkdown(wikiPage)
const codeChunk = result.find((c) => c.text.includes("theta_i = base"))
expect(codeChunk).toBeDefined()
- const openers = codeChunk!.text.match(/```/g)?.length ?? 0
- expect(openers % 2).toBe(0)
+ // Must contain BOTH an opener and a closer (exactly 2 ``` markers),
+ // not just an even count — `0 % 2 === 0` passes trivially and would
+ // green an "opener escaped, closer stayed behind" regression.
+ const fenceMarkers = codeChunk!.text.match(/```/g) ?? []
+ expect(fenceMarkers).toHaveLength(2)
+ expect(codeChunk!.text).toContain("q' = q * e^(j * m * theta)")
})
it("list items about variants are captured", () => {
@@ -485,6 +515,83 @@ describe("chunkMarkdown — realistic wiki fixture", () => {
})
})
+// ── CRLF content body (Windows line endings) ───────────────────────
+
+describe("chunkMarkdown — CRLF in body", () => {
+ it("handles CRLF-delimited headings and fences correctly", () => {
+ // A Windows-authored markdown file uses \r\n, not \n. The chunker
+ // splits on \n and leaves \r attached to each line; the fence
+ // regex uses startsWith + trim() so \r shouldn't break fence
+ // detection. Headings use `\s+` which eats \r. If either regex
+ // regressed, the fence wouldn't close (everything becomes one
+ // oversized chunk) OR the heading wouldn't register (headingPath
+ // empty).
+ const input = "# Head\r\n\r\n```py\r\ncode line 1\r\ncode line 2\r\n```\r\n\r\nafter\r\n"
+ const result = chunkMarkdown(input, { targetChars: 2000 })
+ expect(result).toHaveLength(1)
+ expect(result[0].headingPath).toBe("# Head")
+ expect(result[0].text).toContain("code line 1")
+ expect(result[0].text).toContain("after")
+ expect(result[0].oversized).toBe(false)
+ })
+})
+
+// ── Nested fences (4-tick wrapping 3-tick) ─────────────────────────
+
+describe("chunkMarkdown — nested fences", () => {
+ it("a 4-backtick fence keeps a 3-backtick inner block intact", () => {
+ // CommonMark says a fence can only be closed by a run of the same
+ // character with length ≥ the opening run. So ```` should NOT be
+ // closed by ``` inside. The chunker records the opening marker's
+ // full length and must require the closer to match it exactly.
+ const input = [
+ "Intro.",
+ "",
+ "````markdown",
+ "Here is some embedded markdown with its own fence:",
+ "```python",
+ "print('inner')",
+ "```",
+ "End of embedded markdown.",
+ "````",
+ "",
+ "Outro.",
+ ].join("\n")
+ const result = chunkMarkdown(input, { targetChars: 2000 })
+ expect(result).toHaveLength(1)
+ // Inner ``` fence must remain captured inside the chunk — not
+ // treated as a closer that terminated the outer fence early.
+ expect(result[0].text).toContain("print('inner')")
+ expect(result[0].text).toContain("End of embedded markdown.")
+ expect(result[0].text).toContain("Outro.")
+ })
+})
+
+// ── Tables without a separator row ─────────────────────────────────
+
+describe("chunkMarkdown — table with no |---|---| separator", () => {
+ it("treats 2+ consecutive leading-pipe lines as a single indivisible table atom", () => {
+ // Some wikis omit the separator row (rendered as a two-row data
+ // table by many markdown engines). The chunker's rule is purely
+ // structural: ≥2 consecutive `|`-prefixed lines = one table atom.
+ const input = [
+ "Intro.",
+ "",
+ "| key1 | val1 |",
+ "| key2 | val2 |",
+ "",
+ "Outro.",
+ ].join("\n")
+ // Use targetChars small enough that a torn table WOULD produce
+ // multiple chunks — so we can assert "stayed intact" meaningfully.
+ const result = chunkMarkdown(input, { targetChars: 20, maxChars: 200, minChars: 5, overlapChars: 0 })
+ const tableChunks = result.filter((c) => c.text.includes("| key1"))
+ expect(tableChunks).toHaveLength(1)
+ expect(tableChunks[0].text).toContain("| key1 | val1 |")
+ expect(tableChunks[0].text).toContain("| key2 | val2 |")
+ })
+})
+
// ── Contract checks on the output shape ────────────────────────────
describe("Chunk shape contract", () => {
diff --git a/src/test-helpers/load-test-env.ts b/src/test-helpers/load-test-env.ts
new file mode 100644
index 00000000..ab34f549
--- /dev/null
+++ b/src/test-helpers/load-test-env.ts
@@ -0,0 +1,37 @@
+/**
+ * Vitest setup file — loads `.env.test.local` into process.env before
+ * any test module imports. Registered via `test.setupFiles` in
+ * vite.config.ts.
+ *
+ * Why a hand-rolled dotenv loader instead of the `dotenv` package:
+ * We intentionally avoid adding a prod dependency just for tests.
+ * The file format we support is a tiny subset — KEY=value lines,
+ * `#` comments, optional surrounding quotes. If the project ever
+ * outgrows this, swap in the real `dotenv` package.
+ *
+ * Precedence: variables already present in process.env (e.g. set by
+ * the npm script or the shell) are NOT overwritten, so CI can still
+ * override endpoints for special runs.
+ */
+import fs from "node:fs"
+import path from "node:path"
+
+const envPath = path.resolve(process.cwd(), ".env.test.local")
+if (fs.existsSync(envPath)) {
+ const content = fs.readFileSync(envPath, "utf-8")
+ for (const rawLine of content.split(/\r?\n/)) {
+ const line = rawLine.trim()
+ if (line.length === 0 || line.startsWith("#")) continue
+ const eqIdx = line.indexOf("=")
+ if (eqIdx < 0) continue
+ const key = line.slice(0, eqIdx).trim()
+ const rawValue = line.slice(eqIdx + 1).trim()
+ // Strip ONE layer of matching surrounding quotes (single or double).
+ const value =
+ (rawValue.startsWith('"') && rawValue.endsWith('"')) ||
+ (rawValue.startsWith("'") && rawValue.endsWith("'"))
+ ? rawValue.slice(1, -1)
+ : rawValue
+ if (!(key in process.env)) process.env[key] = value
+ }
+}
diff --git a/vite.config.ts b/vite.config.ts
index eea9db2f..7c0d58f5 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -46,5 +46,9 @@ export default defineConfig(async () => ({
test: {
environment: "node",
+ // Loads .env.test.local into process.env for real-LLM tests.
+ // The loader itself is a no-op if the file is absent, so this is
+ // safe to keep on for every test run.
+ setupFiles: ["./src/test-helpers/load-test-env.ts"],
},
}))