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: preserve lazy tree and mineru images
nash_sub312074193d1
diff --git a/src/App.tsx b/src/App.tsxindex ab1a22be..892ebc6a 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -424,6 +424,7 @@ function App() {// Start project source watch if enabledimport("@/lib/project-file-sync").then(async ({ startProjectFileSync, stopProjectFileSync }) => {const config = await loadSourceWatchConfig(proj.id)+ if (!isCurrentProject(proj)) returnuseWikiStore.getState().setSourceWatchConfig(config)if (config.enabled) {startProjectFileSync(proj, config).catch((err) =>diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsxindex 558d766d..dc23b5e6 100644--- a/src/components/chat/chat-panel.tsx+++ b/src/components/chat/chat-panel.tsx@@ -360,7 +360,7 @@ export function ChatPanel() {const pp = normalizePath(project.path)try {await executeIngestWrites(pp, llmConfig, undefined, undefined)- await refreshProjectFileTree(pp)+ await refreshProjectFileTree(pp, { bumpDataVersion: true })} catch (err) {console.error("Failed to write to wiki:", err)}diff --git a/src/components/layout/file-tree.tsx b/src/components/layout/file-tree.tsxindex 6c3034d1..1a5de9b3 100644--- a/src/components/layout/file-tree.tsx+++ b/src/components/layout/file-tree.tsx@@ -93,10 +93,12 @@ export function FileTree() {const setFileTree = useWikiStore((s) => s.setFileTree)const project = useWikiStore((s) => s.project)const loadedPaths = useRef(new Set<string>())+ const loadingPaths = useRef(new Set<string>())useEffect(() => {loadedPaths.current.clear()- }, [project?.id, fileTree])+ loadingPaths.current.clear()+ }, [project?.id])const handleOpenProjectFolder = async () => {if (!project) return@@ -121,7 +123,8 @@ export function FileTree() {const handleLoadChildren = async (node: FileNode) => {if (!project) return- if (loadedPaths.current.has(node.path)) return+ if (loadedPaths.current.has(node.path) || loadingPaths.current.has(node.path)) return+ loadingPaths.current.add(node.path)const projectId = project.idtry {const children = await listDirectory(node.path, { maxDepth: 1 })@@ -135,6 +138,8 @@ export function FileTree() {})} catch (err) {console.error("[FileTree] load children failed:", err)+ } finally {+ loadingPaths.current.delete(node.path)}}diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.tsindex 493695ea..25b41fc6 100644--- a/src/lib/ingest-source-path-collision.test.ts+++ b/src/lib/ingest-source-path-collision.test.ts@@ -110,14 +110,15 @@ vi.mock("./llm-client", () => ({vi.mock("./mineru", () => ({parseWithMineru: vi.fn(),+ parseWithMineruResult: vi.fn(),}))import { autoIngest, executeIngestWrites, hasMineruImageRefs } from "./ingest"import { streamChat } from "./llm-client"-import { parseWithMineru } from "./mineru"+import { parseWithMineruResult } from "./mineru"const mockStreamChat = vi.mocked(streamChat)-const mockParseWithMineru = vi.mocked(parseWithMineru)+const mockParseWithMineru = vi.mocked(parseWithMineruResult)describe("autoIngest source summary paths", () => {let tmp: { path: string; cleanup: () => Promise<void> } | undefined@@ -506,7 +507,7 @@ describe("autoIngest source summary paths", () => {controller.signal,"project-a",),- ).rejects.toThrow("AbortError")+ ).rejects.toThrow("Ingest cancelled")})it("falls back to built-in PDF extraction when MinerU fails for a non-cancelled ingest", async () => {@@ -563,7 +564,7 @@ describe("autoIngest source summary paths", () => {controller.signal,"project-a",),- ).rejects.toThrow("MinerU parsing cancelled")+ ).rejects.toThrow("Ingest cancelled")expect(useActivityStore.getState().items.some((item) =>diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 47e1e9d5..26be69dc 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -5,13 +5,14 @@ import {getFileModifiedTime,getFileSize,readFile,+ readFileAsBase64,writeFile,listDirectory,} from "@/commands/fs"import { streamChat } from "@/lib/llm-client"import type { LlmConfig } from "@/stores/wiki-store"import { useWikiStore } from "@/stores/wiki-store"-import { parseWithMineru } from "@/lib/mineru"+import { parseWithMineruResult } from "@/lib/mineru"import { useChatStore } from "@/stores/chat-store"import { useActivityStore } from "@/stores/activity-store"import { useReviewStore, type ReviewItem } from "@/stores/review-store"@@ -139,6 +140,99 @@ function promptImageUrlToAbs(projectPath: string, url: string): string {return url.startsWith("media/") ? `${projectPath}/wiki/${url}` : url}+function imageMimeTypeFromPath(path: string): string {+ const ext = getFileName(path).split(".").pop()?.toLowerCase() ?? ""+ switch (ext) {+ case "jpg":+ case "jpeg":+ return "image/jpeg"+ case "png":+ return "image/png"+ case "gif":+ return "image/gif"+ case "webp":+ return "image/webp"+ case "bmp":+ return "image/bmp"+ case "svg":+ return "image/svg+xml"+ case "tif":+ case "tiff":+ return "image/tiff"+ default:+ return "application/octet-stream"+ }+}++async function sha256OfBase64(b64: string): Promise<string> {+ const binary = atob(b64)+ const bytes = new Uint8Array(binary.length)+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer+ const digest = await crypto.subtle.digest("SHA-256", buffer)+ return Array.from(new Uint8Array(digest))+ .map((b) => b.toString(16).padStart(2, "0"))+ .join("")+}++async function savedImagesFromMineruMarkdown(+ projectPath: string,+ sourceSummarySlug: string,+ markdown: string,+): Promise<SavedImage[]> {+ const pp = normalizePath(projectPath)+ const prefix = `media/${sourceSummarySlug}/mineru/`+ const encodedPrefix = `media/${encodeMarkdownPathSegment(sourceSummarySlug)}/mineru/`+ const refs: string[] = []+ const seen = new Set<string>()++ for (const match of markdown.matchAll(/!\[[^\]]*]\(((?:[^()]|\([^()]*\))*)\)/g)) {+ const rawTarget = (match[1] ?? "").trim()+ const url = rawTarget.startsWith("<") && rawTarget.includes(">")+ ? rawTarget.slice(1, rawTarget.indexOf(">"))+ : rawTarget.split(/\s+["']/)[0]+ if (!url) continue+ let decoded = url+ try {+ decoded = decodeURIComponent(url)+ } catch {+ // Keep the raw URL if it is not valid percent-encoding.+ }+ const normalized = normalizePath(decoded.replace(/^\.\//, ""))+ if (!normalized.startsWith(prefix) && !normalized.startsWith(encodedPrefix)) continue+ const relPath = normalized.startsWith(encodedPrefix)+ ? `media/${sourceSummarySlug}/mineru/${normalized.slice(encodedPrefix.length)}`+ : normalized+ if (seen.has(relPath)) continue+ seen.add(relPath)+ refs.push(relPath)+ }++ const images: SavedImage[] = []+ for (const relPath of refs) {+ const absPath = `${pp}/wiki/${relPath}`+ try {+ const { base64 } = await readFileAsBase64(absPath)+ images.push({+ index: images.length + 1,+ mimeType: imageMimeTypeFromPath(relPath),+ page: null,+ width: 0,+ height: 0,+ relPath,+ absPath,+ sha256: await sha256OfBase64(base64),+ })+ } catch (err) {+ console.warn(+ `[ingest:mineru] failed to read cached MinerU image "${relPath}":`,+ err instanceof Error ? err.message : err,+ )+ }+ }+ return images+}+function stripWikiMediaAbsPaths(projectPath: string, content: string): string {return content.split(`${projectPath}/wiki/media/`).join("media/")}@@ -524,22 +618,30 @@ async function autoIngestImpl(const isPdf = lowerExt === "pdf"const mineruCfg = useWikiStore.getState().mineruConfiglet mineruSucceeded = false+ let mineruSavedImages: SavedImage[] = []if (isPdf && mineruCfg.enabled && mineruCfg.token) {try {const cacheDir = sp.substring(0, sp.lastIndexOf("/"))const cachePath = `${cacheDir}/.cache/${fileName}.txt`activity.updateItem(activityId, { detail: "MinerU: parsing PDF..." })console.log(`[ingest:mineru] submitting "${fileName}" to MinerU API`)- const markdown = await parseWithMineru(mineruCfg, sp, undefined, (msg) => {+ const mineruResult = await parseWithMineruResult(mineruCfg, sp, undefined, (msg) => {activity.updateItem(activityId, { detail: `MinerU: ${msg}` })}, signal, {projectPath: pp,sourceSummarySlug,})await createDirectory(`${cacheDir}/.cache`)- await writeFile(cachePath, markdown)+ await writeFile(cachePath, mineruResult.markdown)+ mineruSavedImages = mineruResult.savedImages+ if (mineruSavedImages.length > 0) {+ const extractionKey = await imageExtractionKey(pp, sp, sourceSummarySlug)+ rememberImageExtractionByKey(extractionKey, Promise.resolve(mineruSavedImages))+ }mineruSucceeded = true- console.log(`[ingest:mineru] cached MinerU output for "${fileName}" (${markdown.length} chars)`)+ console.log(+ `[ingest:mineru] cached MinerU output for "${fileName}" (${mineruResult.markdown.length} chars, images=${mineruSavedImages.length})`,+ )} catch (err) {throwIfIngestAborted(signal, activityId)const msg = trimInlineStatus(err instanceof Error ? err.message : String(err))@@ -560,6 +662,13 @@ async function autoIngestImpl(tryReadFile(`${pp}/wiki/index.md`),tryReadFile(`${pp}/wiki/overview.md`),])+ if (isPdf && mineruSavedImages.length === 0 && hasMineruImageRefs(sourceContent, sourceSummarySlug)) {+ mineruSavedImages = await savedImagesFromMineruMarkdown(pp, sourceSummarySlug, sourceContent)+ if (mineruSavedImages.length > 0) {+ const extractionKey = await imageExtractionKey(pp, sp, sourceSummarySlug)+ rememberImageExtractionByKey(extractionKey, Promise.resolve(mineruSavedImages))+ }+ }// ── Cache check: skip re-ingest if source content hasn't changed ──//@@ -578,7 +687,7 @@ async function autoIngestImpl(console.log(`[ingest:diag] cache-hit branch: starting image extraction for ${sp}`)const skipNativePdfImageExtraction = isPdf && hasMineruImageRefs(sourceContent, sourceSummarySlug)let savedImages = skipNativePdfImageExtraction- ? []+ ? mineruSavedImages: await extractAndSaveSourceImages(pp, sp, sourceSummarySlug)const markdownImages = await extractAndSaveMarkdownImages(pp, sp, sourceContent, sourceSummarySlug)savedImages = [...savedImages, ...markdownImages]@@ -676,7 +785,7 @@ async function autoIngestImpl(hasMineruImageRefs(sourceContent, sourceSummarySlug))let savedImages = skipNativePdfImageExtraction- ? []+ ? mineruSavedImages: await extractAndSaveSourceImages(pp, sp, sourceSummarySlug)const markdownImages = await extractAndSaveMarkdownImages(pp, sp, sourceContent, sourceSummarySlug)savedImages = [...savedImages, ...markdownImages]diff --git a/src/lib/mineru.test.ts b/src/lib/mineru.test.tsindex e2f825e1..a9820505 100644--- a/src/lib/mineru.test.ts+++ b/src/lib/mineru.test.ts@@ -21,7 +21,7 @@ vi.mock("@/commands/fs", () => ({writeFileBase64: fsMocks.writeFileBase64,}))-import { __mineruTest, parseWithMineru, testMineruConnection } from "./mineru"+import { __mineruTest, parseWithMineru, parseWithMineruResult, testMineruConnection } from "./mineru"function jsonResponse(body: unknown, init?: ResponseInit): Response {return new Response(JSON.stringify(body), {@@ -193,6 +193,32 @@ describe("MinerU API helpers", () => {expect(markdown).toContain("")})+ it("returns SavedImage metadata for MinerU zip images", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": "",+ "images/chart.png": "chart-bytes",+ }))++ const result = await __mineruTest.downloadAndExtractMarkdownResult(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(result.markdown).toBe("")+ expect(result.savedImages).toHaveLength(1)+ expect(result.savedImages[0]).toMatchObject({+ index: 1,+ mimeType: "image/png",+ page: null,+ width: 0,+ height: 0,+ relPath: "media/paper/mineru/images/chart.png",+ absPath: "/project/wiki/media/paper/mineru/images/chart.png",+ })+ expect(result.savedImages[0].sha256).toMatch(/^[0-9a-f]{64}$/)+ })+it("rewrites Markdown image paths containing spaces", async () => {mockHttpFetch.mockResolvedValueOnce(await zipResponse({"full.md": "",@@ -444,6 +470,42 @@ describe("parseWithMineru", () => {)})+ it("returns saved MinerU images from local parsing result", async () => {+ mockHttpFetch+ .mockResolvedValueOnce(jsonResponse({+ code: 0,+ msg: "ok",+ data: { batch_id: "batch-1", file_urls: ["https://upload"] },+ }))+ .mockResolvedValueOnce(new Response("", { status: 200 }))+ .mockResolvedValueOnce(jsonResponse({+ code: 0,+ msg: "ok",+ data: {+ batch_id: "batch-1",+ extract_result: [{ file_name: "doc.pdf", state: "done", full_zip_url: "https://zip" }],+ },+ }))+ .mockResolvedValueOnce(await zipResponse({+ "full.md": "",+ "images/chart.png": "chart-bytes",+ }))++ const result = await parseWithMineruResult({+ enabled: true,+ token: "token",+ modelVersion: "vlm",+ }, "/tmp/doc.pdf", undefined, undefined, undefined, {+ projectPath: "/project",+ sourceSummarySlug: "doc",+ })++ expect(result.markdown).toBe("")+ expect(result.savedImages.map((image) => image.relPath)).toEqual([+ "media/doc/mineru/images/chart.png",+ ])+ })+it("submits URL tasks without reading or uploading a local file", async () => {mockHttpFetch.mockResolvedValueOnce(jsonResponse({diff --git a/src/lib/mineru.ts b/src/lib/mineru.tsindex 758720cf..242256c6 100644--- a/src/lib/mineru.ts+++ b/src/lib/mineru.ts@@ -3,6 +3,7 @@ import type { MineruConfig } from "@/stores/wiki-store"import { createDirectory, getFileSize, readFileAsBase64, writeFileBase64 } from "@/commands/fs"import { getHttpFetch } from "@/lib/tauri-fetch"import { getFileName, normalizePath } from "@/lib/path-utils"+import type { SavedImage } from "@/lib/extract-source-images"const API_BASE = "https://mineru.net/api/v4"const POLL_INTERVAL_MS = 3_000@@ -70,6 +71,11 @@ interface MineruAssetOptions {sourceSummarySlug: string}+interface MineruExtractedMarkdown {+ markdown: string+ savedImages: SavedImage[]+}+// ── API calls ──async function mineruHeaders(token: string): Promise<HeadersInit> {@@ -137,6 +143,37 @@ function bytesToBase64(bytes: Uint8Array): string {return btoa(binary)}+async function sha256OfBytes(bytes: Uint8Array): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", bytesToUploadBody(bytes))+ return Array.from(new Uint8Array(digest))+ .map((b) => b.toString(16).padStart(2, "0"))+ .join("")+}++function mineruImageMimeType(path: string): string {+ const ext = getFileName(path).split(".").pop()?.toLowerCase() ?? ""+ switch (ext) {+ case "jpg":+ case "jpeg":+ return "image/jpeg"+ case "png":+ return "image/png"+ case "gif":+ return "image/gif"+ case "webp":+ return "image/webp"+ case "bmp":+ return "image/bmp"+ case "svg":+ return "image/svg+xml"+ case "tif":+ case "tiff":+ return "image/tiff"+ default:+ return "application/octet-stream"+ }+}+function safeMineruAssetSegment(segment: string): string {const decoded = (() => {try {@@ -484,10 +521,11 @@ async function saveMineruZipImages(zip: JSZip,options: MineruAssetOptions,signal?: AbortSignal,-): Promise<Map<string, string>> {+): Promise<{ pathMap: Map<string, string>; savedImages: SavedImage[] }> {const pp = normalizePath(options.projectPath)const rootDir = `${pp}/wiki/media/${options.sourceSummarySlug}/mineru`const pathMap = new Map<string, string>()+ const savedImages: SavedImage[] = []const imageEntries: Array<[string, JSZip.JSZipObject]> = []const basenameCounts = new Map<string, number>()@@ -500,7 +538,7 @@ async function saveMineruZipImages(}})- if (imageEntries.length === 0) return pathMap+ if (imageEntries.length === 0) return { pathMap, savedImages }await createDirectory(rootDir)for (const [zipPath, file] of imageEntries) {@@ -516,16 +554,26 @@ async function saveMineruZipImages(pathMap.set(basename, relPath)pathMap.set(decodeMineruPath(basename), relPath)}+ savedImages.push({+ index: savedImages.length + 1,+ mimeType: mineruImageMimeType(relPath),+ page: null,+ width: 0,+ height: 0,+ relPath,+ absPath,+ sha256: await sha256OfBytes(bytes),+ })}- return pathMap+ return { pathMap, savedImages }}async function downloadAndExtractMarkdown(zipUrl: string,signal?: AbortSignal,assetOptions?: MineruAssetOptions,-): Promise<string> {+): Promise<MineruExtractedMarkdown> {const httpFetch = await getHttpFetch()throwIfAborted(signal)const res = await httpFetch(zipUrl, { signal })@@ -553,20 +601,23 @@ async function downloadAndExtractMarkdown()const markdown = await (fullMd ?? mdEntries[0])[1].async("string")const markdownWithTables = convertHtmlTablesToMarkdown(markdown)- if (!assetOptions) return markdownWithTables+ if (!assetOptions) return { markdown: markdownWithTables, savedImages: [] }try {- const pathMap = await saveMineruZipImages(zip, assetOptions, signal)- return pathMap.size > 0+ const { pathMap, savedImages } = await saveMineruZipImages(zip, assetOptions, signal)+ return {+ markdown: pathMap.size > 0? rewriteMineruMarkdownImages(markdownWithTables, pathMap)- : markdownWithTables+ : markdownWithTables,+ savedImages,+ }} catch (err) {if (signal?.aborted) throw errconsole.warn("[MinerU] failed to save extracted images; keeping parsed Markdown text:",err instanceof Error ? err.message : err,)- return markdownWithTables+ return { markdown: markdownWithTables, savedImages: [] }}}@@ -589,6 +640,17 @@ export async function parseWithMineru(signal?: AbortSignal,assetOptions?: MineruAssetOptions,): Promise<string> {+ return (await parseWithMineruResult(config, sourcePath, sourceUrl, onProgress, signal, assetOptions)).markdown+}++export async function parseWithMineruResult(+ config: MineruConfig,+ sourcePath: string,+ sourceUrl?: string,+ onProgress?: (msg: string) => void,+ signal?: AbortSignal,+ assetOptions?: MineruAssetOptions,+): Promise<MineruExtractedMarkdown> {throwIfAborted(signal)if (!config.token) throw new Error("MinerU API token not configured")if (config.modelVersion !== "pipeline" && config.modelVersion !== "vlm") {@@ -627,10 +689,10 @@ export async function parseWithMineru(}onProgress?.("Downloading parsed result...")- const markdown = await downloadAndExtractMarkdown(zipUrl, signal, assetOptions)+ const result = await downloadAndExtractMarkdown(zipUrl, signal, assetOptions)onProgress?.("Done")- return markdown+ return result}/**@@ -659,7 +721,12 @@ export async function testMineruConnection(token: string): Promise<void> {// Test-only hooks for MinerU's browser/Tauri boundary helpers.export const __mineruTest = {- downloadAndExtractMarkdown,+ downloadAndExtractMarkdown: async (+ zipUrl: string,+ signal?: AbortSignal,+ assetOptions?: MineruAssetOptions,+ ) => (await downloadAndExtractMarkdown(zipUrl, signal, assetOptions)).markdown,+ downloadAndExtractMarkdownResult: downloadAndExtractMarkdown,mineruApiErrorMessage,decodeBase64ToBytes,rewriteMineruMarkdownImages,diff --git a/src/lib/project-file-tree-refresh.test.ts b/src/lib/project-file-tree-refresh.test.tsindex 6b1d946b..f5e2b076 100644--- a/src/lib/project-file-tree-refresh.test.ts+++ b/src/lib/project-file-tree-refresh.test.ts@@ -133,6 +133,110 @@ describe("refreshProjectFileTree", () => {}})+ it("preserves already-loaded display children when refreshing the shallow tree", async () => {+ const loadedTree: FileNode[] = [+ {+ name: "wiki",+ path: "/tmp/project/wiki",+ is_dir: true,+ children: [+ {+ name: "entities",+ path: "/tmp/project/wiki/entities",+ is_dir: true,+ children: [+ {+ name: "alpha.md",+ path: "/tmp/project/wiki/entities/alpha.md",+ is_dir: false,+ },+ ],+ },+ ],+ },+ ]+ const refreshedShallowTree: FileNode[] = [+ {+ name: "wiki",+ path: "/tmp/project/wiki",+ is_dir: true,+ children: [+ {+ name: "entities",+ path: "/tmp/project/wiki/entities",+ is_dir: true,+ },+ {+ name: "concepts",+ path: "/tmp/project/wiki/concepts",+ is_dir: true,+ },+ ],+ },+ ]+ useWikiStore.getState().setFileTree(loadedTree, { syncPathIndex: false })+ mocks.listDirectory.mockImplementation(async (_path: string, options?: { maxDepth?: number }) =>+ options?.maxDepth === 2 ? refreshedShallowTree : fullTree+ )++ await refreshProjectFileTree(project.path, {+ projectId: project.id,+ refreshPathIndex: false,+ })++ expect(useWikiStore.getState().fileTree).toEqual([+ {+ name: "wiki",+ path: "/tmp/project/wiki",+ is_dir: true,+ children: [+ {+ name: "entities",+ path: "/tmp/project/wiki/entities",+ is_dir: true,+ children: [+ {+ name: "alpha.md",+ path: "/tmp/project/wiki/entities/alpha.md",+ is_dir: false,+ },+ ],+ },+ {+ name: "concepts",+ path: "/tmp/project/wiki/concepts",+ is_dir: true,+ },+ ],+ },+ ])+ })++ it("retries the shallow display tree refresh before showing an empty sidebar", async () => {+ vi.useFakeTimers()+ try {+ mocks.listDirectory+ .mockRejectedValueOnce(new Error("transient list failure"))+ .mockResolvedValueOnce(shallowTree)++ const pending = refreshProjectFileTree(project.path, {+ projectId: project.id,+ refreshPathIndex: false,+ })+ await flushMicrotasks()+ expect(useWikiStore.getState().fileTree).toEqual([])++ await vi.advanceTimersByTimeAsync(250)+ await pending++ expect(mocks.listDirectory).toHaveBeenNthCalledWith(1, project.path, { maxDepth: 2 })+ expect(mocks.listDirectory).toHaveBeenNthCalledWith(2, project.path, { maxDepth: 2 })+ expect(useWikiStore.getState().fileTree).toEqual(shallowTree)+ } finally {+ vi.useRealTimers()+ }+ })+it("does not start the background full scan once the shallow refresh reveals a stale project", async () => {mocks.listDirectory.mockImplementation(async (_path: string, options?: { maxDepth?: number }) => {if (options?.maxDepth === 2) {diff --git a/src/lib/project-file-tree-refresh.ts b/src/lib/project-file-tree-refresh.tsindex 35e8a545..0f42b8fd 100644--- a/src/lib/project-file-tree-refresh.ts+++ b/src/lib/project-file-tree-refresh.ts@@ -1,6 +1,7 @@import { listDirectory } from "@/commands/fs"import { useWikiStore } from "@/stores/wiki-store"import { normalizePath } from "@/lib/path-utils"+import type { FileNode } from "@/types/wiki"export interface RefreshProjectFileTreeOptions {projectId?: string@@ -36,6 +37,17 @@ function isStillCurrentProject(projectId: string | undefined, projectPath: strinreturn normalizePath(current.path) === projectPath}+function mergeLoadedDisplayTree(existing: FileNode[], refreshed: FileNode[]): FileNode[] {+ const existingByPath = new Map(existing.map((node) => [node.path, node]))++ return refreshed.map((node) => {+ const prior = existingByPath.get(node.path)+ if (!prior?.children) return node+ if (!node.children) return { ...node, children: prior.children }+ return { ...node, children: mergeLoadedDisplayTree(prior.children, node.children) }+ })+}+export async function refreshProjectFileTree(projectPath: string,options: RefreshProjectFileTreeOptions = {},@@ -51,9 +63,13 @@ export async function refreshProjectFileTree(if (refreshDisplayTree) {try {- const shallowTree = await listDirectory(normalizedProjectPath, { maxDepth: 2 })+ const shallowTree = await listDirectoryWithRetry(normalizedProjectPath, { maxDepth: 2 }, 3)if (isStillCurrentProject(currentProjectId, normalizedProjectPath)) {- useWikiStore.getState().setFileTree(shallowTree, { syncPathIndex: false })+ const currentTree = useWikiStore.getState().fileTree+ const displayTree = options.clearDisplayTreeFirst+ ? shallowTree+ : mergeLoadedDisplayTree(currentTree, shallowTree)+ useWikiStore.getState().setFileTree(displayTree, { syncPathIndex: false })}} catch (err) {console.error("Failed to refresh project file tree:", err)