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(sources): folder delete + inline confirmation + ingest-cache cleanup
nash_su91a6bd051822
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsxindex 1304a6da..349f9c1c 100644--- a/src/components/sources/sources-view.tsx+++ b/src/components/sources/sources-view.tsx@@ -19,6 +19,11 @@ import {} from "@/lib/wiki-cleanup"import { parseSources, writeSources } from "@/lib/sources-merge"import { decidePageFate } from "@/lib/source-delete-decision"+import { removeFromIngestCache } from "@/lib/ingest-cache"+import {+ collectAllFilesIncludingDot,+ decideDeleteClick,+} from "@/lib/sources-tree-delete"export function SourcesView() {const { t } = useTranslation()@@ -31,6 +36,28 @@ export function SourcesView() {const [sources, setSources] = useState<FileNode[]>([])const [importing, setImporting] = useState(false)const [ingestingPath, setIngestingPath] = useState<string | null>(null)+ /**+ * Path of the source-tree node currently in "click again to+ * confirm delete" state. Lifted up here (rather than living+ * inside SourceTree) for two reasons:+ * 1. Only one button can be armed at a time across the whole+ * tree — clicking another delete disarms the prior one.+ * Lifting state to the common ancestor makes that natural.+ * 2. The auto-disarm timer (5s) needs to survive across re-+ * renders triggered by tree mutation; useEffect cleanup+ * anchored here is the right scope.+ */+ const [pendingDeletePath, setPendingDeletePath] = useState<string | null>(null)++ // Auto-disarm: 5 seconds without a second click resets the+ // pending state. Prevents a stale armed button from firing if+ // the user walked away and came back. Cleared whenever the+ // pending path changes (so a fresh arm restarts the clock).+ useEffect(() => {+ if (!pendingDeletePath) return+ const t = setTimeout(() => setPendingDeletePath(null), 5000)+ return () => clearTimeout(t)+ }, [pendingDeletePath])const loadSources = useCallback(async () => {if (!project) return@@ -202,25 +229,107 @@ export function SourcesView() {async function handleDelete(node: FileNode) {if (!project) returnconst pp = normalizePath(project.path)- const fileName = node.name- const confirmed = window.confirm(- t("sources.deleteConfirm", { name: fileName })- )- if (!confirmed) return-+ // Confirmation now lives in the SourceTree component as a+ // two-stage button (click once = "Confirm", click again =+ // delete). Reaching this handler means the user has already+ // confirmed via the inline UI, so we proceed unconditionally.try {- // Step 1: Find related wiki pages before deleting- const relatedPages = await findRelatedWikiPages(pp, fileName)-- // Step 2: Delete the source file- await deleteFile(node.path)+ const result = await deleteSourceWithCascade(pp, node)+ // Step 8: Refresh everything (UI side — must run with parent+ // context, hence kept here rather than inside the helper).+ await loadSources()+ const tree = await listDirectory(pp)+ setFileTree(tree)+ useWikiStore.getState().bumpDataVersion()+ if (+ selectedFile === node.path ||+ result.deletedWikiPaths.includes(selectedFile ?? "")+ ) {+ setSelectedFile(null)+ }+ } catch (err) {+ console.error("Failed to delete source:", err)+ window.alert(`Failed to delete: ${err}`)+ }+ }- // Step 3: Delete preprocessed cache+ /**+ * Recursive folder delete. Walks the folder tree, runs the+ * wiki-cascade for every individual file inside (so any+ * derived wiki pages, embeddings, log entries get cleaned up+ * the same way as a single-file delete), then removes the+ * folder itself with `deleteFile` — which dispatches to+ * `remove_dir_all` Rust-side, taking the now-empty (or near-+ * empty) directory tree with it including any leftover dotdir+ * cache files we didn't explicitly target.+ *+ * Errors on individual files are logged and skipped; the batch+ * keeps going so partial cleanup is preferred over an all-or-+ * nothing failure that leaves the tree half-deleted.+ */+ async function handleDeleteFolder(folder: FileNode) {+ if (!project) return+ const pp = normalizePath(project.path)+ try {+ const allFiles = collectAllFilesIncludingDot(folder)+ const allDeletedWikiPaths: string[] = []+ for (const file of allFiles) {+ try {+ const r = await deleteSourceWithCascade(pp, file)+ allDeletedWikiPaths.push(...r.deletedWikiPaths)+ } catch (err) {+ console.warn(`Failed to delete ${file.path} during folder delete:`, err)+ }+ }+ // Now remove the folder (and any leftover empty subdirs / dot+ // cache dirs) in one shot. Files we just deleted above are+ // gone; this call mostly tears down empty directories.try {- await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)- } catch {- // cache file may not exist+ await deleteFile(folder.path)+ } catch (err) {+ console.warn(`Failed to remove folder ${folder.path}:`, err)+ }+ await loadSources()+ const tree = await listDirectory(pp)+ setFileTree(tree)+ useWikiStore.getState().bumpDataVersion()+ if (+ selectedFile?.startsWith(folder.path + "/") ||+ allDeletedWikiPaths.includes(selectedFile ?? "")+ ) {+ setSelectedFile(null)}+ } catch (err) {+ console.error("Failed to delete folder:", err)+ window.alert(`Failed to delete folder: ${err}`)+ }+ }++ /**+ * Per-file deletion: the wiki cascade portion (steps 1-7 of the+ * old handleDelete), without the confirmation dialog or the+ * UI-state refresh (callers do those once at the end of a batch).+ *+ * Returns the wiki page paths we actually removed so the caller+ * can reset selectedFile if one of them was open.+ */+ async function deleteSourceWithCascade(+ pp: string,+ node: FileNode,+ ): Promise<{ deletedWikiPaths: string[] }> {+ const fileName = node.name+ // Step 1: Find related wiki pages before deleting+ const relatedPages = await findRelatedWikiPages(pp, fileName)++ // Step 2: Delete the source file+ await deleteFile(node.path)++ // Step 3: Delete preprocessed cache+ try {+ await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)+ } catch {+ // cache file may not exist+ }// Step 4: For each page that findRelatedWikiPages surfaced,// consult decidePageFate to pick one of three actions:@@ -318,32 +427,33 @@ export function SourcesView() {}}- // Step 7: Append deletion record to log.md- try {- const logPath = `${pp}/wiki/log.md`- const logContent = await readFile(logPath).catch(() => "# Wiki Log\n")- const date = new Date().toISOString().slice(0, 10)- const keptCount = relatedPages.length - actuallyDeleted.length- const logEntry = `\n## [${date}] delete | ${fileName}\n\nDeleted source file and ${actuallyDeleted.length} wiki pages.${keptCount > 0 ? ` ${keptCount} shared pages kept (have other sources).` : ""}\n`- await writeFile(logPath, logContent.trimEnd() + logEntry)- } catch {- // non-critical- }-- // Step 8: Refresh everything- await loadSources()- const tree = await listDirectory(pp)- setFileTree(tree)- useWikiStore.getState().bumpDataVersion()+ // Step 7: Append deletion record to log.md+ try {+ const logPath = `${pp}/wiki/log.md`+ const logContent = await readFile(logPath).catch(() => "# Wiki Log\n")+ const date = new Date().toISOString().slice(0, 10)+ const keptCount = relatedPages.length - actuallyDeleted.length+ const logEntry = `\n## [${date}] delete | ${fileName}\n\nDeleted source file and ${actuallyDeleted.length} wiki pages.${keptCount > 0 ? ` ${keptCount} shared pages kept (have other sources).` : ""}\n`+ await writeFile(logPath, logContent.trimEnd() + logEntry)+ } catch {+ // non-critical+ }- // Clear selected file if it was the deleted one- if (selectedFile === node.path || actuallyDeleted.includes(selectedFile ?? "")) {- setSelectedFile(null)- }- } catch (err) {- console.error("Failed to delete source:", err)- window.alert(`Failed to delete: ${err}`)+ // Step 8: Drop the source's ingest-cache entry so a future+ // re-import doesn't hit a stale "already ingested" record.+ // The cache's existence-check fallback would have caught this+ // anyway (it falls through to re-ingest when wiki/sources/<slug>.md+ // is gone), but removing the entry up front keeps the cache+ // file small and avoids confusing log lines like "cache miss+ // for foo.pdf: wiki/sources/foo.md no longer on disk" on+ // every search after a delete.+ try {+ await removeFromIngestCache(pp, fileName)+ } catch {+ // non-critical}++ return { deletedWikiPaths: actuallyDeleted }}async function handleIngest(node: FileNode) {@@ -407,6 +517,9 @@ export function SourcesView() {onOpen={handleOpenSource}onIngest={handleIngest}onDelete={handleDelete}+ onDeleteFolder={handleDeleteFolder}+ pendingDeletePath={pendingDeletePath}+ setPendingDeletePath={setPendingDeletePath}ingestingPath={ingestingPath}depth={0}/>@@ -488,11 +601,15 @@ function countFiles(nodes: FileNode[]): number {return count}+function SourceTree({nodes,onOpen,onIngest,onDelete,+ onDeleteFolder,+ pendingDeletePath,+ setPendingDeletePath,ingestingPath,depth,}: {@@ -500,6 +617,13 @@ function SourceTree({onOpen: (node: FileNode) => voidonIngest: (node: FileNode) => voidonDelete: (node: FileNode) => void+ onDeleteFolder: (node: FileNode) => void+ /** Path of the node currently in "click again to confirm" state.+ * Lifted to the parent so only ONE button is armed at a time+ * across the whole tree — clicking another delete arms that one+ * and disarms the previous. */+ pendingDeletePath: string | null+ setPendingDeletePath: (path: string | null) => voidingestingPath: string | nulldepth: number}) {@@ -509,6 +633,29 @@ function SourceTree({setCollapsed((prev) => ({ ...prev, [path]: !prev[path] }))}+ /**+ * Two-stage delete handler. Decision logic lives in+ * `decideDeleteClick` (pure, unit-tested in+ * `sources-tree-delete.test.ts`); this wrapper just dispatches+ * the resulting action onto the React state + handler props.+ */+ const handleDeleteClick = (node: FileNode) => {+ const action = decideDeleteClick(pendingDeletePath, node)+ switch (action.kind) {+ case "arm":+ setPendingDeletePath(action.path)+ return+ case "fire-file":+ setPendingDeletePath(null)+ onDelete(action.node)+ return+ case "fire-folder":+ setPendingDeletePath(null)+ onDeleteFolder(action.node)+ return+ }+ }+// Sort: folders first, then files, alphabetical within each groupconst sorted = [...nodes].sort((a, b) => {if (a.is_dir && !b.is_dir) return -1@@ -519,32 +666,49 @@ function SourceTree({return (<>{sorted.map((node) => {+ const isPendingDelete = pendingDeletePath === node.pathif (node.is_dir && node.children) {const isCollapsed = collapsed[node.path] ?? falsereturn (<div key={node.path}>- <button- onClick={() => toggle(node.path)}- className="flex w-full items-center gap-1.5 rounded-md px-1 py-1 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground"+ <div+ className="group flex w-full items-center gap-1 rounded-md text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground"style={{ paddingLeft: `${depth * 16 + 4}px` }}>- {isCollapsed ? (- <ChevronRight className="h-3.5 w-3.5 shrink-0" />- ) : (- <ChevronDown className="h-3.5 w-3.5 shrink-0" />- )}- <Folder className="h-4 w-4 shrink-0 text-amber-500" />- <span className="truncate font-medium">{node.name}</span>- <span className="ml-auto text-[10px] text-muted-foreground/60 shrink-0">- {countFiles(node.children)}- </span>- </button>+ <button+ onClick={() => toggle(node.path)}+ className="flex flex-1 items-center gap-1.5 px-1 py-1 text-left"+ >+ {isCollapsed ? (+ <ChevronRight className="h-3.5 w-3.5 shrink-0" />+ ) : (+ <ChevronDown className="h-3.5 w-3.5 shrink-0" />+ )}+ <Folder className="h-4 w-4 shrink-0 text-amber-500" />+ <span className="truncate font-medium">{node.name}</span>+ <span className="ml-auto text-[10px] text-muted-foreground/60 shrink-0">+ {countFiles(node.children)}+ </span>+ </button>+ <DeleteButton+ isPending={isPendingDelete}+ onClick={() => handleDeleteClick(node)}+ hint={+ isPendingDelete+ ? `Click again to delete folder ${node.name} and ALL its contents`+ : `Delete folder ${node.name} (recursive)`+ }+ />+ </div>{!isCollapsed && (<SourceTreenodes={node.children}onOpen={onOpen}onIngest={onIngest}onDelete={onDelete}+ onDeleteFolder={onDeleteFolder}+ pendingDeletePath={pendingDeletePath}+ setPendingDeletePath={setPendingDeletePath}ingestingPath={ingestingPath}depth={depth + 1}/>@@ -576,15 +740,15 @@ function SourceTree({><BookOpen className="h-4 w-4" /></Button>- <Button- variant="ghost"- size="icon"- className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"- title="Delete"- onClick={() => onDelete(node)}- >- <Trash2 className="h-3.5 w-3.5" />- </Button>+ <DeleteButton+ isPending={isPendingDelete}+ onClick={() => handleDeleteClick(node)}+ hint={+ isPendingDelete+ ? `Click again to delete ${node.name}`+ : `Delete ${node.name}`+ }+ /></div>)})}@@ -592,6 +756,52 @@ function SourceTree({)}+/**+ * Two-stage delete button. Default = ghost trash icon (subtle).+ * Armed = solid red "Confirm" pill with the icon — visually+ * unmistakable, so the user can't miss the second-click warning.+ *+ * Same component is used for both files and folders; the parent+ * decides which delete handler to call from the click. The pending+ * state is owned by SourceTree (lifted to its parent SourcesView)+ * so only one button is armed across the entire tree at a time.+ */+function DeleteButton({+ isPending,+ onClick,+ hint,+}: {+ isPending: boolean+ onClick: () => void+ hint: string+}) {+ if (isPending) {+ return (+ <Button+ variant="destructive"+ size="sm"+ className="h-7 shrink-0 px-2 text-[11px] font-semibold animate-pulse"+ title={hint}+ onClick={onClick}+ >+ <Trash2 className="mr-1 h-3.5 w-3.5" />+ Confirm+ </Button>+ )+ }+ return (+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"+ title={hint}+ onClick={onClick}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ )+}+function flattenMdFiles(nodes: FileNode[]): FileNode[] {const files: FileNode[] = []for (const node of nodes) {diff --git a/src/lib/sources-tree-delete.test.ts b/src/lib/sources-tree-delete.test.tsnew file mode 100644index 00000000..99ef381a--- /dev/null+++ b/src/lib/sources-tree-delete.test.ts@@ -0,0 +1,154 @@+/**+ * Unit tests for the pure helpers backing the SourcesView delete+ * flow. The React component (`SourceTree`) calls these and turns+ * their output into state updates / handler dispatches; testing+ * the helpers in isolation pins behavior without needing a DOM+ * test environment.+ */+import { describe, it, expect } from "vitest"+import {+ collectAllFilesIncludingDot,+ decideDeleteClick,+} from "./sources-tree-delete"+import type { FileNode } from "@/types/wiki"++function file(path: string): FileNode {+ const name = path.split("/").pop() ?? path+ return { name, path, is_dir: false }+}++function dir(path: string, children: FileNode[]): FileNode {+ const name = path.split("/").pop() ?? path+ return { name, path, is_dir: true, children }+}++describe("collectAllFilesIncludingDot", () => {+ it("returns empty list for an empty folder", () => {+ expect(collectAllFilesIncludingDot(dir("/p", []))).toEqual([])+ })++ it("returns all leaf files of a single-level folder", () => {+ const tree = dir("/p", [file("/p/a.pdf"), file("/p/b.docx")])+ const out = collectAllFilesIncludingDot(tree)+ expect(out.map((n) => n.path)).toEqual(["/p/a.pdf", "/p/b.docx"])+ })++ it("recurses into subdirectories of arbitrary depth", () => {+ // /p/a.pdf+ // /p/sub/b.docx+ // /p/sub/deep/c.md+ // /p/sub/deep/even-deeper/d.txt+ const tree = dir("/p", [+ file("/p/a.pdf"),+ dir("/p/sub", [+ file("/p/sub/b.docx"),+ dir("/p/sub/deep", [+ file("/p/sub/deep/c.md"),+ dir("/p/sub/deep/even-deeper", [file("/p/sub/deep/even-deeper/d.txt")]),+ ]),+ ]),+ ])+ const out = collectAllFilesIncludingDot(tree)+ expect(out.map((n) => n.path)).toEqual([+ "/p/a.pdf",+ "/p/sub/b.docx",+ "/p/sub/deep/c.md",+ "/p/sub/deep/even-deeper/d.txt",+ ])+ })++ it("does not include directory nodes themselves in the result", () => {+ const tree = dir("/p", [dir("/p/sub", [file("/p/sub/x.md")])])+ const out = collectAllFilesIncludingDot(tree)+ expect(out.every((n) => !n.is_dir)).toBe(true)+ expect(out).toHaveLength(1)+ expect(out[0].path).toBe("/p/sub/x.md")+ })++ it("handles a directory with no children property (defensive)", () => {+ // listDirectory normalizes empty dirs to children: [], but the+ // FileNode type allows `children?: FileNode[]` — make sure we+ // don't crash on undefined.+ const tree: FileNode = { name: "p", path: "/p", is_dir: true }+ expect(collectAllFilesIncludingDot(tree)).toEqual([])+ })++ it("walks deeply-nested folder containing a single file 10 levels down", () => {+ // Build /p/0/1/2/3/4/5/6/7/8/9/leaf.txt programmatically.+ let leaf: FileNode = file("/p/0/1/2/3/4/5/6/7/8/9/leaf.txt")+ for (let i = 9; i >= 0; i--) {+ const path = "/p/" + Array.from({ length: i + 1 }, (_, k) => k).join("/")+ leaf = dir(path, [leaf])+ }+ // `leaf` is now the outer /p/0 dir wrapping all of it.+ const root = dir("/p", [leaf])+ const out = collectAllFilesIncludingDot(root)+ expect(out).toHaveLength(1)+ expect(out[0].path).toBe("/p/0/1/2/3/4/5/6/7/8/9/leaf.txt")+ })+})++describe("decideDeleteClick", () => {+ const fileNode = file("/p/a.pdf")+ const folderNode = dir("/p/sub", [file("/p/sub/x.md")])++ it("arms the button on first click (no pending state)", () => {+ expect(decideDeleteClick(null, fileNode)).toEqual({+ kind: "arm",+ path: "/p/a.pdf",+ })+ })++ it("arms a different node when the pending path doesn't match", () => {+ // User had `/p/a.pdf` armed but now clicked `/p/b.pdf` — the+ // newer click wins and `b` becomes the armed one.+ const otherFile = file("/p/b.pdf")+ expect(decideDeleteClick("/p/a.pdf", otherFile)).toEqual({+ kind: "arm",+ path: "/p/b.pdf",+ })+ })++ it("fires file delete on second click of the same FILE node", () => {+ expect(decideDeleteClick("/p/a.pdf", fileNode)).toEqual({+ kind: "fire-file",+ node: fileNode,+ })+ })++ it("fires folder delete on second click of the same FOLDER node", () => {+ expect(decideDeleteClick("/p/sub", folderNode)).toEqual({+ kind: "fire-folder",+ node: folderNode,+ })+ })++ it("treats node identity by path, not object identity", () => {+ // Two FileNode objects with the same path should still match —+ // the file tree gets re-allocated on every loadSources() call,+ // so object-identity equality would break confirmation across+ // re-renders.+ const reAllocated = file("/p/a.pdf")+ expect(decideDeleteClick("/p/a.pdf", reAllocated)).toEqual({+ kind: "fire-file",+ node: reAllocated,+ })+ })++ it("never returns a no-op — every click produces an actionable result", () => {+ // Any combination of (pending, clicked) must produce one of+ // the three action kinds, never `undefined` or a "do nothing"+ // signal. Tested against the three meaningful scenarios above+ // — this is a regression guard for accidentally adding an+ // early-return path.+ const results = [+ decideDeleteClick(null, fileNode),+ decideDeleteClick("other", fileNode),+ decideDeleteClick(fileNode.path, fileNode),+ decideDeleteClick(folderNode.path, folderNode),+ ]+ for (const r of results) {+ expect(["arm", "fire-file", "fire-folder"]).toContain(r.kind)+ }+ })+})diff --git a/src/lib/sources-tree-delete.ts b/src/lib/sources-tree-delete.tsnew file mode 100644index 00000000..f4475c09--- /dev/null+++ b/src/lib/sources-tree-delete.ts@@ -0,0 +1,76 @@+/**+ * Pure helpers for the SourcesView delete flow.+ *+ * Extracted out of `sources-view.tsx` so they're testable without+ * spinning up React Testing Library / @testing-library/react —+ * neither of which is currently a project dependency. The actual+ * click handlers and state in the component are thin glue around+ * these functions; visual review covers the wiring, unit tests+ * cover the decision logic.+ */+import type { FileNode } from "@/types/wiki"++/**+ * Recursively collect every leaf (non-directory) file under+ * `folder`. Walks `folder.children` rather than re-reading the+ * file system — the parent already filtered dotfiles out via+ * `filterTree` before the tree reached the UI, so this preserves+ * the "delete exactly what the user saw" invariant.+ *+ * Skips empty folders (returns no entries for them) but recurses+ * into populated subdirectories regardless of nesting depth.+ */+export function collectAllFilesIncludingDot(folder: FileNode): FileNode[] {+ const out: FileNode[] = []+ function walk(node: FileNode) {+ if (node.is_dir) {+ if (node.children) {+ for (const c of node.children) walk(c)+ }+ } else {+ out.push(node)+ }+ }+ walk(folder)+ return out+}++/**+ * Decision returned by the two-stage delete-button click logic.+ * The component reads this and (a) calls the appropriate handler,+ * (b) updates `pendingDeletePath` to match.+ *+ * - "arm" : first click on this node — set pending,+ * visually flip the button to "Confirm"+ * - "fire-file" : second click on the same FILE node — call+ * onDelete + clear pending+ * - "fire-folder" : second click on the same FOLDER node — call+ * onDeleteFolder + clear pending+ */+export type DeleteClickAction =+ | { kind: "arm"; path: string }+ | { kind: "fire-file"; node: FileNode }+ | { kind: "fire-folder"; node: FileNode }++/**+ * Pure state-machine for the inline delete-confirm button.+ *+ * currentPending === clicked.path → second click → fire+ * else → first click → arm+ *+ * Folder vs file dispatch is on `clicked.is_dir` so the parent+ * doesn't need to branch explicitly — one button, one click+ * handler, the action shape tells the component which prop to+ * call.+ */+export function decideDeleteClick(+ currentPending: string | null,+ clicked: FileNode,+): DeleteClickAction {+ if (currentPending === clicked.path) {+ return clicked.is_dir+ ? { kind: "fire-folder", node: clicked }+ : { kind: "fire-file", node: clicked }+ }+ return { kind: "arm", path: clicked.path }+}