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: harden autosave during project open
nash_su052e54cd39ea
diff --git a/src/App.tsx b/src/App.tsxindex ce31aceb..509e7e9a 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -294,146 +294,150 @@ function App() {// auto-save before reset empties the stores — otherwise the debounced// writers would persist empty arrays back over the old project's pending// review / deep-research items.- const { flushAndSuspendAutoSave, resumeAutoSave } = await import("@/lib/auto-save")- await flushAndSuspendAutoSave()+ const { runWithSuspendedAutoSave } = await import("@/lib/auto-save")+ await runWithSuspendedAutoSave(async () => {+ // Clear all per-project state BEFORE loading new project data+ // to prevent cross-project contamination. MUST be awaited so the+ // ingest queue / graph cache are actually cleared before the new+ // project's state is populated.+ const { resetProjectState } = await import("@/lib/reset-project-state")+ await resetProjectState()- // Clear all per-project state BEFORE loading new project data- // to prevent cross-project contamination. MUST be awaited so the- // ingest queue / graph cache are actually cleared before the new- // project's state is populated.- const { resetProjectState } = await import("@/lib/reset-project-state")- await resetProjectState()+ setProject(proj)+ const projectOutputLang = await loadOutputLanguage(proj.id)+ useWikiStore.getState().setOutputLanguage(projectOutputLang ?? "auto")+ setSelectedFile(null)+ setActiveView("wiki")+ // Bump data version so any cached graphs/views invalidate+ useWikiStore.getState().bumpDataVersion()+ await saveLastProject(proj)- setProject(proj)- const projectOutputLang = await loadOutputLanguage(proj.id)- useWikiStore.getState().setOutputLanguage(projectOutputLang ?? "auto")- setSelectedFile(null)- setActiveView("wiki")- // Bump data version so any cached graphs/views invalidate- useWikiStore.getState().bumpDataVersion()- await saveLastProject(proj)-- // Restore ingest queue (resume interrupted tasks). Keyed by the- // project's stable UUID so the queue still finds the right project- // even if the filesystem path changed since the task was enqueued.- // Await this before starting file sync: watcher events for raw/sources- // may enqueue ingest tasks and require an active project queue.- try {- const { restoreQueue } = await import("@/lib/ingest-queue")- await restoreQueue(proj.id, proj.path)- } catch (err) {- console.error("Failed to restore ingest queue:", err)- }- // Same handshake for the dedup-merge queue.- import("@/lib/dedup-queue").then(({ restoreQueue }) => {- restoreQueue(proj.id, proj.path).catch((err) =>- console.error("Failed to restore dedup queue:", err)- )- })- // Load per-project scheduled import config- try {- const savedScheduledImport = await loadScheduledImportConfig(proj.path)- if (savedScheduledImport) {- // Migrate relative path to absolute (backward compatibility)- let path = savedScheduledImport.path- if (path && !path.startsWith("/") && !path.match(/^[a-zA-Z]:[/\\]/)) {- path = `${proj.path}/${path}`+ // Restore ingest queue (resume interrupted tasks). Keyed by the+ // project's stable UUID so the queue still finds the right project+ // even if the filesystem path changed since the task was enqueued.+ // Await this before starting file sync: watcher events for raw/sources+ // may enqueue ingest tasks and require an active project queue.+ try {+ const { restoreQueue } = await import("@/lib/ingest-queue")+ await restoreQueue(proj.id, proj.path)+ } catch (err) {+ console.error("Failed to restore ingest queue:", err)+ }+ // Same handshake for the dedup-merge queue.+ import("@/lib/dedup-queue").then(({ restoreQueue }) => {+ restoreQueue(proj.id, proj.path).catch((err) =>+ console.error("Failed to restore dedup queue:", err)+ )+ })+ // Load per-project scheduled import config+ try {+ const savedScheduledImport = await loadScheduledImportConfig(proj.path)+ if (savedScheduledImport) {+ // Migrate relative path to absolute (backward compatibility)+ let path = savedScheduledImport.path+ if (path && !path.startsWith("/") && !path.match(/^[a-zA-Z]:[/\\]/)) {+ path = `${proj.path}/${path}`+ }+ useWikiStore.getState().setScheduledImportConfig({+ ...savedScheduledImport,+ path,+ })+ } else {+ // Reset to default for new projects+ useWikiStore.getState().setScheduledImportConfig({+ enabled: false,+ path: `${proj.path}/raw/sources`,+ interval: 60,+ lastScan: null,+ })}- useWikiStore.getState().setScheduledImportConfig({- ...savedScheduledImport,- path,- })- } else {- // Reset to default for new projects- useWikiStore.getState().setScheduledImportConfig({- enabled: false,- path: `${proj.path}/raw/sources`,- interval: 60,- lastScan: null,- })+ } catch {+ // ignore}- } catch {- // ignore- }- // Start scheduled import if enabled- const scheduledImportConfig = useWikiStore.getState().scheduledImportConfig- if (scheduledImportConfig.enabled && scheduledImportConfig.path && scheduledImportConfig.interval > 0) {- import("@/lib/scheduled-import").then(({ startScheduledImport }) => {- startScheduledImport(proj, scheduledImportConfig)- }).catch((err) =>- console.error("Failed to start scheduled import:", err)- )- }-- // Start project source watch if enabled- import("@/lib/project-file-sync").then(async ({ startProjectFileSync, stopProjectFileSync }) => {- const config = await loadSourceWatchConfig(proj.id)- useWikiStore.getState().setSourceWatchConfig(config)- if (config.enabled) {- startProjectFileSync(proj, config).catch((err) =>- console.error("Failed to start project file sync:", err)+ // Start scheduled import if enabled+ const scheduledImportConfig = useWikiStore.getState().scheduledImportConfig+ if (scheduledImportConfig.enabled && scheduledImportConfig.path && scheduledImportConfig.interval > 0) {+ import("@/lib/scheduled-import").then(({ startScheduledImport }) => {+ startScheduledImport(proj, scheduledImportConfig)+ }).catch((err) =>+ console.error("Failed to start scheduled import:", err))- } else {- stopProjectFileSync().catch(() => {})}- }).catch((err) => console.error("Failed to configure project file sync:", err))- // Notify local clip server of the current project + all recent projects- fetch("http://127.0.0.1:19827/project", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ path: proj.path }),- }).catch(() => {})- // Send all recent projects to clip server for extension project picker- getRecentProjects().then((recents) => {- const projects = recents.map((p) => ({ name: p.name, path: p.path }))- fetch("http://127.0.0.1:19827/projects", {+ // Start project source watch if enabled+ import("@/lib/project-file-sync").then(async ({ startProjectFileSync, stopProjectFileSync }) => {+ const config = await loadSourceWatchConfig(proj.id)+ useWikiStore.getState().setSourceWatchConfig(config)+ if (config.enabled) {+ startProjectFileSync(proj, config).catch((err) =>+ console.error("Failed to start project file sync:", err)+ )+ } else {+ stopProjectFileSync().catch(() => {})+ }+ }).catch((err) => console.error("Failed to configure project file sync:", err))+ // Notify local clip server of the current project + all recent projects+ fetch("http://127.0.0.1:19827/project", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ projects }),+ body: JSON.stringify({ path: proj.path }),}).catch(() => {})- }).catch(() => {})- try {- const tree = await listDirectory(proj.path)- setFileTree(tree)- } catch (err) {- console.error("Failed to load file tree:", err)- }- // Load persisted review items- try {- const savedReview = await loadReviewItems(proj.path)- if (savedReview.length > 0) {- useReviewStore.getState().setItems(savedReview)++ // Send all recent projects to clip server for extension project picker+ getRecentProjects().then((recents) => {+ const projects = recents.map((p) => ({ name: p.name, path: p.path }))+ fetch("http://127.0.0.1:19827/projects", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ projects }),+ }).catch(() => {})+ }).catch(() => {})+ try {+ const tree = await listDirectory(proj.path)+ setFileTree(tree)+ } catch (err) {+ console.error("Failed to load file tree:", err)}- } catch {- // ignore, start fresh- }- // Load persisted lint items- useLintStore.getState().setItems([])- try {- const savedLint = await loadLintItems(proj.path)- useLintStore.getState().setItems(savedLint)- } catch {+ // Load persisted review items+ try {+ const savedReview = await loadReviewItems(proj.path)+ if (savedReview.length > 0) {+ useReviewStore.getState().setItems(savedReview)+ }+ } catch {+ // ignore, start fresh+ }+ // Load persisted lint itemsuseLintStore.getState().setItems([])- }- // Load persisted chat history- try {- const savedChat = await loadChatHistory(proj.path)- if (savedChat.conversations.length > 0) {- useChatStore.getState().setConversations(savedChat.conversations)- useChatStore.getState().setMessages(savedChat.messages)- // Set most recent conversation as active- const sorted = [...savedChat.conversations].sort((a, b) => b.updatedAt - a.updatedAt)- if (sorted[0]) {- useChatStore.getState().setActiveConversation(sorted[0].id)+ try {+ const savedLint = await loadLintItems(proj.path)+ useLintStore.getState().setItems(savedLint)+ } catch {+ useLintStore.getState().setItems([])+ }+ // Load persisted chat history+ try {+ const savedChat = await loadChatHistory(proj.path)+ if (savedChat.conversations.length > 0) {+ useChatStore.getState().setConversations(savedChat.conversations)+ useChatStore.getState().setMessages(savedChat.messages)+ // Set most recent conversation as active+ const sorted = [...savedChat.conversations].sort((a, b) => b.updatedAt - a.updatedAt)+ if (sorted[0]) {+ useChatStore.getState().setActiveConversation(sorted[0].id)+ }}+ } catch {+ // ignore, start fresh}- } catch {- // ignore, start fresh- }- // New project's persisted state is loaded — re-arm auto-save so further- // edits persist to THIS project.- resumeAutoSave()+ }, () => {+ // If project loading fails after resetProjectState() and before persisted+ // review/lint/chat state has been restored, do not leave auto-save armed+ // against a half-loaded project with empty stores.+ setProject(null)+ setFileTree([])+ setSelectedFile(null)+ })}async function handleSelectRecent(proj: WikiProject) {diff --git a/src/lib/auto-save.test.ts b/src/lib/auto-save.test.tsindex b8de752d..706a9299 100644--- a/src/lib/auto-save.test.ts+++ b/src/lib/auto-save.test.ts@@ -20,7 +20,12 @@ const { saveReviewItems, saveLintItems, saveChatHistory } = vi.hoisted(() => ({vi.mock("./persist", () => ({ saveReviewItems, saveLintItems, saveChatHistory }))-import { setupAutoSave, flushAndSuspendAutoSave, resumeAutoSave } from "./auto-save"+import {+ setupAutoSave,+ flushAndSuspendAutoSave,+ resumeAutoSave,+ runWithSuspendedAutoSave,+} from "./auto-save"import { useReviewStore } from "@/stores/review-store"import { useLintStore } from "@/stores/lint-store"import { useChatStore } from "@/stores/chat-store"@@ -91,6 +96,39 @@ describe("auto-save project-switch guard", () => {expect(saveReviewItems).toHaveBeenCalledWith("/proj/B", [review("b1")])})+ it("runs the failure cleanup before resuming auto-save", async () => {+ setProjectPath("/proj/A")+ useReviewStore.setState({ items: [review("a1")] })++ await expect(runWithSuspendedAutoSave(+ async () => {+ throw new Error("open failed")+ },+ () => {+ // This store mutation must still be suppressed. If the helper resumed+ // auto-save before running cleanup, it would schedule an empty write+ // using the old project path captured before setProjectPath(null).+ useReviewStore.setState({ items: [] })+ setProjectPath(null)+ },+ )).rejects.toThrow("open failed")++ saveReviewItems.mockClear()+ saveLintItems.mockClear()+ saveChatHistory.mockClear()++ // A post-failure store change should not write empty data to the half-opened+ // project because the cleanup cleared the active project before resume.+ useReviewStore.setState({ items: [] })+ useLintStore.setState({ items: [] })+ useChatStore.setState({ conversations: [], messages: [] })+ vi.runAllTimers()++ expect(saveReviewItems).not.toHaveBeenCalled()+ expect(saveLintItems).not.toHaveBeenCalled()+ expect(saveChatHistory).not.toHaveBeenCalled()+ })+it("skips chat flush while streaming", async () => {setProjectPath("/proj/A")useChatStore.setState({ isStreaming: true })diff --git a/src/lib/auto-save.ts b/src/lib/auto-save.tsindex fad75385..46e7cffc 100644--- a/src/lib/auto-save.ts+++ b/src/lib/auto-save.ts@@ -48,6 +48,30 @@ export function resumeAutoSave(): void {suspended = false}+/**+ * Run a project-switch/open operation while auto-save is suspended. If the+ * operation fails, onFailure runs before auto-save resumes so callers can clear+ * any half-loaded project path before store changes are allowed to persist.+ */+export async function runWithSuspendedAutoSave<T>(+ action: () => Promise<T>,+ onFailure?: () => void,+): Promise<T> {+ await flushAndSuspendAutoSave()+ try {+ return await action()+ } catch (err) {+ try {+ onFailure?.()+ } catch (cleanupErr) {+ console.warn("Failed to clean up after suspended auto-save operation:", cleanupErr)+ }+ throw err+ } finally {+ resumeAutoSave()+ }+}+export function setupAutoSave(): void {// Auto-save review items (debounced 1s)useReviewStore.subscribe((state) => {