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

fix: cascade-delete embedding chunks when wiki pages are deleted

nash_su0f9f6b739211
diff --git a/src/components/lint/lint-view.tsx b/src/components/lint/lint-view.tsx
index 50bba4b5..ebcb0360 100644
--- a/src/components/lint/lint-view.tsx
+++ b/src/components/lint/lint-view.tsx
@@ -15,7 +15,7 @@ import { Button } from "@/components/ui/button"
import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
import { runStructuralLint, runSemanticLint, type LintResult } from "@/lib/lint"
-import { readFile, writeFile, deleteFile, listDirectory } from "@/commands/fs"
+import { readFile, writeFile, listDirectory } from "@/commands/fs"
import { normalizePath } from "@/lib/path-utils"
const typeConfig: Record<string, { icon: typeof AlertTriangle; label: string }> = {
@@ -180,7 +180,10 @@ export function LintView() {
if (!confirmed) return
try {
- await deleteFile(pagePath)
+ // Cascade = deleteFile(...) + drop the orphan page's embedding
+ // chunks so it stops showing up as a phantom vector hit.
+ const { cascadeDeleteWikiPage } = await import("@/lib/wiki-page-delete")
+ await cascadeDeleteWikiPage(pp, pagePath)
setResults((prev) => prev.filter((_, i) => i !== index))
const tree = await listDirectory(pp)
setFileTree(tree)
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 59b9a5aa..92cd53c8 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -268,7 +268,11 @@ export function SourcesView() {
const slug = getFileName(pagePath).replace(/\.md$/, "")
const title = extractFrontmatterTitle(content)
deletedInfos.push({ slug, title })
- await deleteFile(pagePath)
+ // cascadeDeleteWikiPage = deleteFile(...) + drop the page's
+ // embedding chunks so future searches don't return phantom
+ // hits pointing at a file that no longer exists.
+ const { cascadeDeleteWikiPage } = await import("@/lib/wiki-page-delete")
+ await cascadeDeleteWikiPage(pp, pagePath)
actuallyDeleted.push(pagePath)
} catch (err) {
console.error(`Failed to process wiki page ${pagePath}:`, err)
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index f17003b3..78a80dd3 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -20,6 +20,18 @@ vi.mock("./sweep-reviews", () => ({
sweepResolvedReviews: vi.fn().mockResolvedValue(0),
}))
+// Mock embedding so cleanupWrittenFiles' cascade-delete to LanceDB is
+// observable. The real module is over in `./embedding` but
+// cleanupWrittenFiles dynamically imports it via `@/lib/embedding`,
+// hence the absolute mock target.
+const removePageEmbeddingMock = vi.fn<(projectPath: string, slug: string) => Promise<void>>(
+ async () => {},
+)
+vi.mock("@/lib/embedding", () => ({
+ removePageEmbedding: (projectPath: string, slug: string) =>
+ removePageEmbeddingMock(projectPath, slug),
+}))
+
// Mock project-identity — tests don't hit Tauri plugin-store. Maps the
// test UUIDs defined below back to their assigned paths.
const TEST_ID = "test-project-uuid"
@@ -46,6 +58,7 @@ import {
cancelAllTasks,
clearCompletedTasks,
clearQueueState,
+ cleanupWrittenFiles,
getQueue,
getQueueSummary,
restoreQueue,
@@ -75,6 +88,7 @@ beforeEach(async () => {
mockWriteFile.mockReset()
mockSweep.mockReset()
mockSweep.mockResolvedValue(0)
+ removePageEmbeddingMock.mockReset()
// Default: persisted queue file doesn't exist
mockReadFile.mockRejectedValue(new Error("ENOENT"))
@@ -519,3 +533,99 @@ describe("ingest-queue — pauseQueue & switch-project survival", () => {
}
})
})
+
+// ── cleanupWrittenFiles — file delete + LanceDB chunk cascade ──────
+describe("cleanupWrittenFiles — embedding cascade", () => {
+ it("deletes each file AND drops its embedding chunks (relative paths)", async () => {
+ const { deleteFile } = await import("@/commands/fs")
+ const mockDeleteFile = vi.mocked(deleteFile)
+ mockDeleteFile.mockReset()
+ mockDeleteFile.mockResolvedValue(undefined)
+
+ await cleanupWrittenFiles("/proj", [
+ "wiki/concepts/rope.md",
+ "wiki/entities/transformer.md",
+ ])
+
+ // File deletes use joined absolute paths.
+ expect(mockDeleteFile).toHaveBeenCalledTimes(2)
+ expect(mockDeleteFile).toHaveBeenNthCalledWith(1, "/proj/wiki/concepts/rope.md")
+ expect(mockDeleteFile).toHaveBeenNthCalledWith(2, "/proj/wiki/entities/transformer.md")
+
+ // Embedding cascade uses page slugs (basename minus .md).
+ expect(removePageEmbeddingMock).toHaveBeenCalledTimes(2)
+ expect(removePageEmbeddingMock).toHaveBeenNthCalledWith(1, "/proj", "rope")
+ expect(removePageEmbeddingMock).toHaveBeenNthCalledWith(2, "/proj", "transformer")
+ })
+
+ it("uses absolute paths verbatim (doesn't double-prefix the project path)", async () => {
+ const { deleteFile } = await import("@/commands/fs")
+ const mockDeleteFile = vi.mocked(deleteFile)
+ mockDeleteFile.mockReset()
+ mockDeleteFile.mockResolvedValue(undefined)
+
+ await cleanupWrittenFiles("/proj", ["/abs/elsewhere/wiki/concepts/foo.md"])
+
+ expect(mockDeleteFile).toHaveBeenCalledWith("/abs/elsewhere/wiki/concepts/foo.md")
+ // Slug derivation still works on absolute paths.
+ expect(removePageEmbeddingMock).toHaveBeenCalledWith("/proj", "foo")
+ })
+
+ it("continues to subsequent files when one delete throws", async () => {
+ const { deleteFile } = await import("@/commands/fs")
+ const mockDeleteFile = vi.mocked(deleteFile)
+ mockDeleteFile.mockReset()
+ // First file fails (e.g. already gone), second succeeds.
+ mockDeleteFile
+ .mockRejectedValueOnce(new Error("ENOENT"))
+ .mockResolvedValueOnce(undefined)
+
+ await cleanupWrittenFiles("/proj", [
+ "wiki/concepts/missing.md",
+ "wiki/concepts/present.md",
+ ])
+
+ // Both deleteFile attempts happened — the helper kept going.
+ expect(mockDeleteFile).toHaveBeenCalledTimes(2)
+ // First file's embedding cascade was skipped (deleteFile threw),
+ // second file's cascade still ran.
+ expect(removePageEmbeddingMock).toHaveBeenCalledTimes(1)
+ expect(removePageEmbeddingMock).toHaveBeenCalledWith("/proj", "present")
+ })
+
+ it("swallows removePageEmbedding errors so a LanceDB issue doesn't abort cleanup", async () => {
+ const { deleteFile } = await import("@/commands/fs")
+ const mockDeleteFile = vi.mocked(deleteFile)
+ mockDeleteFile.mockReset()
+ mockDeleteFile.mockResolvedValue(undefined)
+
+ // First page's embedding cascade throws; second succeeds.
+ removePageEmbeddingMock
+ .mockRejectedValueOnce(new Error("lancedb unavailable"))
+ .mockResolvedValueOnce(undefined)
+
+ await cleanupWrittenFiles("/proj", [
+ "wiki/concepts/a.md",
+ "wiki/concepts/b.md",
+ ])
+
+ // Both file deletes still happened.
+ expect(mockDeleteFile).toHaveBeenCalledTimes(2)
+ // Second cascade still attempted despite first throwing.
+ expect(removePageEmbeddingMock).toHaveBeenCalledTimes(2)
+ })
+
+ it("handles Windows backslash paths via getFileStem", async () => {
+ const { deleteFile } = await import("@/commands/fs")
+ const mockDeleteFile = vi.mocked(deleteFile)
+ mockDeleteFile.mockReset()
+ mockDeleteFile.mockResolvedValue(undefined)
+
+ // A path that's been rewritten with backslashes (Windows ingest
+ // pipeline output before normalize). getFileStem must still
+ // pull "rope" out cleanly so the cascade hits the right page.
+ await cleanupWrittenFiles("C:/proj", ["wiki\\concepts\\rope.md"])
+
+ expect(removePageEmbeddingMock).toHaveBeenCalledWith("C:/proj", "rope")
+ })
+})
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index 455d7bae..0d83c9c0 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -79,6 +79,33 @@ function generateId(): string {
return `ingest-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
}
+/**
+ * Delete files written by a cancelled / failed ingest, AND drop the
+ * matching pages' chunks from LanceDB. Called from the cancel paths
+ * (cancelTask, cancelAllTasks).
+ *
+ * Per-file errors are swallowed (best-effort cleanup) — a missing
+ * file or LanceDB unavailable shouldn't abort the cancel flow.
+ * Structural pages (index/log/overview) aren't embedded, so the
+ * cascade no-ops for them.
+ */
+export async function cleanupWrittenFiles(
+ projectPath: string,
+ filePaths: string[],
+): Promise<void> {
+ const { cascadeDeleteWikiPage } = await import("@/lib/wiki-page-delete")
+ for (const filePath of filePaths) {
+ const fullPath = isAbsolutePath(filePath)
+ ? normalizePath(filePath)
+ : `${projectPath}/${filePath}`
+ try {
+ await cascadeDeleteWikiPage(projectPath, fullPath)
+ } catch {
+ // file may not exist / lancedb unavailable — non-critical
+ }
+ }
+}
+
/**
* Add a file to the ingest queue. The project MUST be the currently-
* active project — switching first is a prerequisite. Returns the new
@@ -184,17 +211,7 @@ export async function cancelTask(taskId: string): Promise<void> {
// Clean up any files written by the interrupted ingest
if (lastWrittenFiles.length > 0) {
- const { deleteFile } = await import("@/commands/fs")
- for (const filePath of lastWrittenFiles) {
- try {
- const fullPath = isAbsolutePath(filePath)
- ? normalizePath(filePath)
- : `${currentProjectPath}/${filePath}`
- await deleteFile(fullPath)
- } catch {
- // file may not exist
- }
- }
+ await cleanupWrittenFiles(currentProjectPath, lastWrittenFiles)
console.log(`[Ingest Queue] Cleaned up ${lastWrittenFiles.length} files from cancelled task`)
lastWrittenFiles = []
}
@@ -233,17 +250,7 @@ export async function cancelAllTasks(): Promise<number> {
processing = false
if (lastWrittenFiles.length > 0) {
- const { deleteFile } = await import("@/commands/fs")
- for (const filePath of lastWrittenFiles) {
- try {
- const fullPath = isAbsolutePath(filePath)
- ? normalizePath(filePath)
- : `${currentProjectPath}/${filePath}`
- await deleteFile(fullPath)
- } catch {
- // file may not exist
- }
- }
+ await cleanupWrittenFiles(currentProjectPath, lastWrittenFiles)
lastWrittenFiles = []
}
diff --git a/src/lib/wiki-page-delete.test.ts b/src/lib/wiki-page-delete.test.ts
new file mode 100644
index 00000000..548ce96f
--- /dev/null
+++ b/src/lib/wiki-page-delete.test.ts
@@ -0,0 +1,125 @@
+/**
+ * Unit tests for cascadeDeleteWikiPage — the one helper that every
+ * wiki-page delete flow goes through. By centralizing the cascade
+ * here we get test coverage for slug derivation + ordering once,
+ * instead of having to test it at every React-component call site.
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+const mockDeleteFile = vi.fn<(path: string) => Promise<void>>()
+const mockRemovePageEmbedding = vi.fn<(projectPath: string, slug: string) => Promise<void>>()
+
+vi.mock("@/commands/fs", () => ({
+ deleteFile: (path: string) => mockDeleteFile(path),
+ // The other fs functions aren't called by this helper, but the
+ // mock factory has to declare them so dynamic imports elsewhere
+ // in transitive deps don't break.
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+ listDirectory: vi.fn(),
+}))
+
+vi.mock("@/lib/embedding", () => ({
+ removePageEmbedding: (projectPath: string, slug: string) =>
+ mockRemovePageEmbedding(projectPath, slug),
+}))
+
+import { cascadeDeleteWikiPage } from "./wiki-page-delete"
+
+beforeEach(() => {
+ mockDeleteFile.mockReset()
+ mockRemovePageEmbedding.mockReset()
+ // Default: both succeed silently.
+ mockDeleteFile.mockResolvedValue(undefined)
+ mockRemovePageEmbedding.mockResolvedValue(undefined)
+})
+
+describe("cascadeDeleteWikiPage", () => {
+ it("deletes the file, then drops the matching page's embedding chunks", async () => {
+ await cascadeDeleteWikiPage("/proj", "/proj/wiki/concepts/rope.md")
+
+ expect(mockDeleteFile).toHaveBeenCalledTimes(1)
+ expect(mockDeleteFile).toHaveBeenCalledWith("/proj/wiki/concepts/rope.md")
+
+ expect(mockRemovePageEmbedding).toHaveBeenCalledTimes(1)
+ expect(mockRemovePageEmbedding).toHaveBeenCalledWith("/proj", "rope")
+ })
+
+ it("calls deleteFile BEFORE removePageEmbedding (file is the source of truth)", async () => {
+ // Order matters: if removePageEmbedding ran first and the disk
+ // delete then failed, we'd be left with a page on disk with no
+ // chunks — every search hit would skip it because vector search
+ // returned no chunks for it. Disk delete first means a partial
+ // failure leaves stale chunks (acceptable, fixed on next
+ // re-index) rather than a stale page (bad UX).
+ const order: string[] = []
+ mockDeleteFile.mockImplementation(async () => {
+ order.push("deleteFile")
+ })
+ mockRemovePageEmbedding.mockImplementation(async () => {
+ order.push("removePageEmbedding")
+ })
+
+ await cascadeDeleteWikiPage("/proj", "/proj/wiki/concepts/foo.md")
+ expect(order).toEqual(["deleteFile", "removePageEmbedding"])
+ })
+
+ it("does NOT call removePageEmbedding when deleteFile throws", async () => {
+ // If the file isn't actually gone, dropping its chunks is wrong:
+ // the page still exists (e.g. permission-denied) and would lose
+ // its searchability while staying on disk.
+ mockDeleteFile.mockRejectedValueOnce(new Error("EACCES"))
+
+ await expect(cascadeDeleteWikiPage("/proj", "/proj/wiki/foo.md")).rejects.toThrow("EACCES")
+
+ expect(mockRemovePageEmbedding).not.toHaveBeenCalled()
+ })
+
+ it("propagates removePageEmbedding errors to the caller (not silently swallowed)", async () => {
+ // Caller decides fault-tolerance policy. Some callers
+ // (ingest-queue cleanup, source-delete batches) want to
+ // continue past LanceDB hiccups; others (single-page delete
+ // from lint view) might want to surface the error.
+ mockRemovePageEmbedding.mockRejectedValueOnce(new Error("lancedb table missing"))
+
+ await expect(cascadeDeleteWikiPage("/proj", "/proj/wiki/foo.md")).rejects.toThrow(
+ "lancedb table missing",
+ )
+ // File delete still happened — leaving the cascade half-done
+ // is the lesser evil compared to never deleting the file.
+ expect(mockDeleteFile).toHaveBeenCalled()
+ })
+
+ it("derives slug from the path's basename, ignoring directory segments", async () => {
+ await cascadeDeleteWikiPage("/proj", "/proj/wiki/concepts/some-deep/nested/page.md")
+ expect(mockRemovePageEmbedding).toHaveBeenCalledWith("/proj", "page")
+ })
+
+ it("handles Windows backslash paths (project path normalization happens elsewhere)", async () => {
+ // The desktop ingest pipeline can produce backslash-laden paths
+ // before path-utils normalizes them. cascadeDeleteWikiPage's
+ // slug derivation MUST cope with both separators in one string.
+ await cascadeDeleteWikiPage("C:/proj", "C:\\proj\\wiki\\entities\\transformer.md")
+
+ expect(mockDeleteFile).toHaveBeenCalledWith("C:\\proj\\wiki\\entities\\transformer.md")
+ expect(mockRemovePageEmbedding).toHaveBeenCalledWith("C:/proj", "transformer")
+ })
+
+ it("preserves dotted page names (e.g. foo.bar.md) in the slug", async () => {
+ // getFileStem strips only the LAST extension, so "foo.bar.md" → "foo.bar".
+ // Pin it: a regression that strips ALL dots would turn this slug
+ // into "foo" and orphan the LanceDB chunks for "foo.bar".
+ await cascadeDeleteWikiPage("/proj", "/proj/wiki/concepts/foo.bar.md")
+ expect(mockRemovePageEmbedding).toHaveBeenCalledWith("/proj", "foo.bar")
+ })
+
+ it("skips removePageEmbedding when slug derivation yields empty (defensive)", async () => {
+ // Edge case: a path that's just "/" or empty would yield ""
+ // slug. Calling removePageEmbedding("") could match every page
+ // in some LanceDB filter implementations, which would be
+ // catastrophic. The helper guards against this.
+ await cascadeDeleteWikiPage("/proj", "/")
+ expect(mockDeleteFile).toHaveBeenCalled()
+ expect(mockRemovePageEmbedding).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/wiki-page-delete.ts b/src/lib/wiki-page-delete.ts
new file mode 100644
index 00000000..98ea38bd
--- /dev/null
+++ b/src/lib/wiki-page-delete.ts
@@ -0,0 +1,46 @@
+/**
+ * Cascade delete for wiki pages.
+ *
+ * Whenever a wiki page is removed from disk we ALSO need to drop its
+ * vector chunks from LanceDB; otherwise the chunks become "phantom"
+ * search hits — `searchByEmbedding` returns the orphaned `page_id`
+ * but `search.ts` then can't find a matching .md file and silently
+ * discards the result, wasting topK slots.
+ *
+ * This helper consolidates that two-step cleanup so every wiki-page
+ * delete path (source-delete cascade in sources-view, orphan-page
+ * delete in lint-view, cancelled-ingest cleanup in ingest-queue)
+ * uses the SAME slug derivation and order of operations. Without
+ * this, each call site reinvented the slug regex slightly
+ * differently (`getFileName().replace(/\.md$/, "")` vs
+ * `getFileStem()`), which would drift over time.
+ *
+ * Errors are propagated, NOT swallowed — callers wrap in try/catch
+ * to apply their own fault-tolerance policy (e.g. continue with the
+ * next file in a batch, or surface to the user via toast).
+ */
+import { deleteFile } from "@/commands/fs"
+import { getFileStem } from "@/lib/path-utils"
+import { removePageEmbedding } from "@/lib/embedding"
+
+/**
+ * Delete a wiki page from disk and drop its embedding chunks.
+ *
+ * `projectPath` is the project root (used to scope the embedding
+ * cascade to the right LanceDB instance).
+ *
+ * `pagePath` may be absolute or relative; only its basename is used
+ * for the page-id lookup, so callers don't need to normalize before
+ * calling. The disk delete uses the path verbatim — pass an
+ * absolute path if your caller has one (most do).
+ */
+export async function cascadeDeleteWikiPage(
+ projectPath: string,
+ pagePath: string,
+): Promise<void> {
+ await deleteFile(pagePath)
+ const slug = getFileStem(pagePath)
+ if (slug.length > 0) {
+ await removePageEmbedding(projectPath, slug)
+ }
+}