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: stop ghost "[Binary file: …]" outputs from overwriting real files
nash_sudaacc4200619
diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex f60fe694..8d239a63 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -49,13 +49,29 @@ pub fn read_file(path: String) -> Result<String, String> {p.file_name().unwrap_or_default().to_string_lossy(), e))}_ => {- // Try reading as text; if it fails (binary), return a friendly message+ // Deliberate markers for IMAGE / MEDIA / LEGACY_DOC above+ // tell the UI "we know about this format, show a stub".+ // For everything else, a failed read_to_string is really+ // a problem: file missing, locked, corrupt encoding, etc.+ // Return Err so the caller can distinguish "no content"+ // from "successfully read stub text" — the latter used to+ // leak into the editor and overwrite the real file on+ // Milkdown's initial re-emit.match fs::read_to_string(&path) {Ok(content) => Ok(content),- Err(_) => {- let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);- Ok(format!("[Binary file: {} ({:.1} KB)]",- p.file_name().unwrap_or_default().to_string_lossy(), size as f64 / 1024.0))+ Err(e) => {+ let exists = p.exists();+ if !exists {+ Err(format!(+ "File does not exist: '{}'",+ path,+ ))+ } else {+ Err(format!(+ "Failed to read file '{}' as text: {} (likely binary, locked, or non-UTF-8)",+ path, e,+ ))+ }}}}@@ -1066,6 +1082,13 @@ pub fn create_directory(path: String) -> Result<(), String> {})}+/// Cheap existence check without reading or classifying the file.+/// Returns true iff `path` refers to something on disk right now.+#[tauri::command]+pub fn file_exists(path: String) -> Result<bool, String> {+ run_guarded("file_exists", || Ok(Path::new(&path).exists()))+}+#[cfg(test)]mod tests {use super::*;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 8a1e1978..4e70879a 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -40,6 +40,7 @@ pub fn run() {commands::fs::delete_file,commands::fs::find_related_wiki_pages,commands::fs::create_directory,+ commands::fs::file_exists,commands::project::create_project,commands::project::open_project,clip_server_status,diff --git a/src/components/editor/wiki-editor.tsx b/src/components/editor/wiki-editor.tsxindex 6df456c1..f4bd2105 100644--- a/src/components/editor/wiki-editor.tsx+++ b/src/components/editor/wiki-editor.tsx@@ -1,4 +1,4 @@-import { useMemo } from "react"+import { useMemo, useRef } from "react"import { Editor, rootCtx, defaultValueCtx } from "@milkdown/kit/core"import { commonmark } from "@milkdown/kit/preset/commonmark"import { gfm } from "@milkdown/kit/preset/gfm"@@ -17,6 +17,13 @@ interface WikiEditorInnerProps {}function WikiEditorInner({ content, onSave }: WikiEditorInnerProps) {+ // Milkdown fires `markdownUpdated` once on initial parse before any+ // user interaction. That one emit must not be forwarded as a save,+ // otherwise just opening a file can overwrite its content with+ // Milkdown's normalized-but-equivalent re-emit (or, worse, with a+ // placeholder string that came back from a failed read).+ const initialEmitConsumedRef = useRef(false)+useEditor((root) =>Editor.make()@@ -24,7 +31,12 @@ function WikiEditorInner({ content, onSave }: WikiEditorInnerProps) {.config((ctx) => {ctx.set(rootCtx, root)ctx.set(defaultValueCtx, content)+ initialEmitConsumedRef.current = falsectx.get(listenerCtx).markdownUpdated((_ctx, markdown) => {+ if (!initialEmitConsumedRef.current) {+ initialEmitConsumedRef.current = true+ return+ }onSave(markdown)})})diff --git a/src/components/layout/preview-panel.tsx b/src/components/layout/preview-panel.tsxindex b3b5bc2a..d14ea95d 100644--- a/src/components/layout/preview-panel.tsx+++ b/src/components/layout/preview-panel.tsx@@ -13,10 +13,17 @@ export function PreviewPanel() {const setFileContent = useWikiStore((s) => s.setFileContent)const setSelectedFile = useWikiStore((s) => s.setSelectedFile)const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ // Snapshot of what was most recently loaded from disk. Milkdown re-emits+ // `markdownUpdated` on initial parse (before the user types anything),+ // which used to trigger an auto-save that could write back a placeholder+ // marker if read_file had returned one for a missing/locked file. We+ // skip save when the incoming markdown equals the last-loaded content.+ const lastLoadedRef = useRef<string>("")useEffect(() => {if (!selectedFile) {setFileContent("")+ lastLoadedRef.current = ""return}@@ -24,22 +31,38 @@ export function PreviewPanel() {if (isBinary(category)) {setFileContent("")+ lastLoadedRef.current = ""return}readFile(selectedFile)- .then(setFileContent)- .catch((err) => setFileContent(`Error loading file: ${err}`))+ .then((content) => {+ lastLoadedRef.current = content+ setFileContent(content)+ })+ .catch((err) => {+ lastLoadedRef.current = ""+ setFileContent(`Error loading file: ${err}`)+ })}, [selectedFile, setFileContent])const handleSave = useCallback((markdown: string) => {if (!selectedFile) return+ // Ignore no-op saves from the editor's initial re-emit. Only write+ // when the user has actually changed the content relative to the+ // last disk read.+ if (markdown === lastLoadedRef.current) returnif (saveTimerRef.current) clearTimeout(saveTimerRef.current)saveTimerRef.current = setTimeout(() => {- writeFile(selectedFile, markdown).catch((err) =>- console.error("Failed to save:", err)- )+ writeFile(selectedFile, markdown)+ .then(() => {+ // Our own write becomes the new "last loaded" — subsequent+ // re-emits from Milkdown that match this content must not+ // trigger another save.+ lastLoadedRef.current = markdown+ })+ .catch((err) => console.error("Failed to save:", err))}, 1000)},[selectedFile]diff --git a/src/lib/ingest-cache.test.ts b/src/lib/ingest-cache.test.tsnew file mode 100644index 00000000..ed949cd6--- /dev/null+++ b/src/lib/ingest-cache.test.ts@@ -0,0 +1,96 @@+import { describe, it, expect, beforeEach, vi } from "vitest"++// Mock fs so the tests don't touch real disk.+vi.mock("@/commands/fs", () => ({+ readFile: vi.fn(),+ writeFile: vi.fn(),+ fileExists: vi.fn(),+}))++import { checkIngestCache, saveIngestCache } from "./ingest-cache"+import { readFile, writeFile, fileExists } from "@/commands/fs"++const mockReadFile = vi.mocked(readFile)+const mockWriteFile = vi.mocked(writeFile)+const mockFileExists = vi.mocked(fileExists)++beforeEach(() => {+ mockReadFile.mockReset()+ mockWriteFile.mockReset()+ mockFileExists.mockReset()+ mockWriteFile.mockResolvedValue(undefined as unknown as void)+})++describe("ingest-cache — checkIngestCache", () => {+ it("returns null when no entry exists", async () => {+ mockReadFile.mockResolvedValue(JSON.stringify({ entries: {} }))+ const result = await checkIngestCache("/project", "foo.pdf", "content")+ expect(result).toBeNull()+ })++ it("returns cached filesWritten when hash matches AND all files exist", async () => {+ // Pre-seed cache with a hash matching "hello".+ // We compute the expected hash by running saveIngestCache first in+ // a controlled round-trip, then feeding the same JSON back in.+ let persisted = ""+ mockReadFile.mockImplementation(async () => persisted || JSON.stringify({ entries: {} }))+ mockWriteFile.mockImplementation(async (_p: string, c: string) => {+ persisted = c+ })+ await saveIngestCache("/project", "foo.pdf", "hello", [+ "wiki/sources/foo.md",+ "wiki/entities/bar.md",+ ])++ mockFileExists.mockResolvedValue(true)+ const result = await checkIngestCache("/project", "foo.pdf", "hello")+ expect(result).toEqual(["wiki/sources/foo.md", "wiki/entities/bar.md"])+ })++ it("returns null when hash matches but a cached file no longer exists on disk", async () => {+ // Prime cache, then simulate user deleting one of the written files.+ let persisted = ""+ mockReadFile.mockImplementation(async () => persisted || JSON.stringify({ entries: {} }))+ mockWriteFile.mockImplementation(async (_p: string, c: string) => {+ persisted = c+ })+ await saveIngestCache("/project", "foo.pdf", "hello", [+ "wiki/sources/foo.md",+ "wiki/entities/bar.md",+ ])++ // wiki/entities/bar.md has been deleted since the cache was written.+ mockFileExists.mockImplementation(async (p: string) => {+ return !p.includes("entities/bar.md")+ })++ const result = await checkIngestCache("/project", "foo.pdf", "hello")+ expect(result).toBeNull()+ })++ it("returns null when the content hash no longer matches (cache stale on content change)", async () => {+ let persisted = ""+ mockReadFile.mockImplementation(async () => persisted || JSON.stringify({ entries: {} }))+ mockWriteFile.mockImplementation(async (_p: string, c: string) => {+ persisted = c+ })+ await saveIngestCache("/project", "foo.pdf", "hello", ["wiki/sources/foo.md"])++ const result = await checkIngestCache("/project", "foo.pdf", "different content")+ expect(result).toBeNull()+ })++ it("returns null if fileExists itself throws (safer to re-ingest than to trust)", async () => {+ let persisted = ""+ mockReadFile.mockImplementation(async () => persisted || JSON.stringify({ entries: {} }))+ mockWriteFile.mockImplementation(async (_p: string, c: string) => {+ persisted = c+ })+ await saveIngestCache("/project", "foo.pdf", "hello", ["wiki/sources/foo.md"])++ mockFileExists.mockRejectedValue(new Error("stat failed"))++ const result = await checkIngestCache("/project", "foo.pdf", "hello")+ expect(result).toBeNull()+ })+})diff --git a/src/lib/ingest-cache.ts b/src/lib/ingest-cache.tsindex de9bcf91..5e59cdf4 100644--- a/src/lib/ingest-cache.ts+++ b/src/lib/ingest-cache.ts@@ -1,5 +1,5 @@-import { readFile, writeFile } from "@/commands/fs"-import { normalizePath } from "@/lib/path-utils"+import { readFile, writeFile, fileExists } from "@/commands/fs"+import { normalizePath, isAbsolutePath } from "@/lib/path-utils"/*** SHA256-based ingest cache.@@ -48,7 +48,15 @@ async function saveCache(projectPath: string, cache: CacheData): Promise<void> {/*** Check if a source file has already been ingested with the same content.- * Returns the list of previously written files if cached, or null if ingest is needed.+ * Returns the list of previously written files if cached, or null if ingest+ * is needed.+ *+ * IMPORTANT: a cache hit is only returned if every previously-written file+ * still exists on disk. Otherwise we treat the cache as stale and fall+ * through to a full re-ingest. Historically we returned the cached list+ * blindly, which surfaced ghost entries in the activity panel — clicking+ * them gave the preview panel a missing file, and the auto-save path then+ * materialized a `[Binary file: ...]` stub at the now-empty location.*/export async function checkIngestCache(projectPath: string,@@ -60,10 +68,28 @@ export async function checkIngestCache(if (!entry) return nullconst currentHash = await sha256(sourceContent)- if (entry.hash === currentHash) {- return entry.filesWritten+ if (entry.hash !== currentHash) return null++ const pp = normalizePath(projectPath)+ for (const filePath of entry.filesWritten) {+ const fullPath = isAbsolutePath(filePath)+ ? normalizePath(filePath)+ : `${pp}/${filePath}`+ try {+ if (!(await fileExists(fullPath))) {+ console.log(+ `[ingest-cache] cache miss for ${sourceFileName}: ${filePath} no longer on disk`,+ )+ return null+ }+ } catch {+ // If the existence check itself fails, fall back to re-ingest —+ // safer than trusting a stale cache entry.+ return null+ }}- return null++ return entry.filesWritten}/**