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: close project-switch races in review sweep

nash_su420cc719947e
diff --git a/src/App.tsx b/src/App.tsx
index 14a5966b..f2fa3e02 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -73,9 +73,11 @@ function App() {
async function handleProjectOpened(proj: WikiProject) {
// Clear all per-project state BEFORE loading new project data
- // to prevent cross-project contamination
+ // 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")
- resetProjectState()
+ await resetProjectState()
setProject(proj)
setSelectedFile(null)
@@ -166,7 +168,7 @@ function App() {
// Clear all per-project state BEFORE flipping back to the welcome screen
// so old data cannot leak in via any async render pass.
const { resetProjectState } = await import("@/lib/reset-project-state")
- resetProjectState()
+ await resetProjectState()
setProject(null)
setFileTree([])
setSelectedFile(null)
diff --git a/src/lib/reset-project-state.ts b/src/lib/reset-project-state.ts
index fe12689d..49a93b9f 100644
--- a/src/lib/reset-project-state.ts
+++ b/src/lib/reset-project-state.ts
@@ -1,7 +1,11 @@
/**
* Centralized reset of all per-project state.
- * MUST be called both when leaving a project and when opening a new one,
- * to prevent cross-project data contamination.
+ * MUST be called (and AWAITED) both when leaving a project and when opening a
+ * new one, to prevent cross-project data contamination.
+ *
+ * Returns once every store/cache has actually been cleared — the caller can
+ * trust that downstream project-opening steps will not race with lingering
+ * cleanup.
*/
import { useChatStore } from "@/stores/chat-store"
@@ -9,8 +13,8 @@ import { useReviewStore } from "@/stores/review-store"
import { useActivityStore } from "@/stores/activity-store"
import { useResearchStore } from "@/stores/research-store"
-export function resetProjectState() {
- // Zustand stores — clear all per-project data
+export async function resetProjectState(): Promise<void> {
+ // Zustand stores — clear all per-project data (synchronous)
useChatStore.setState({
conversations: [],
messages: [],
@@ -34,18 +38,30 @@ export function resetProjectState() {
panelOpen: false,
})
- // Module-level caches
- // Ingest queue
- import("@/lib/ingest-queue").then(({ clearQueueState }) => {
- clearQueueState()
- }).catch((err) => {
- console.warn("[Reset Project State] Failed to clear ingest queue:", err)
- })
+ // Module-level caches — load in parallel and clear each, surfacing any
+ // failure instead of swallowing it.
+ const [queueMod, graphMod] = await Promise.allSettled([
+ import("@/lib/ingest-queue"),
+ import("@/lib/graph-relevance"),
+ ])
- // Graph relevance cache
- import("@/lib/graph-relevance").then(({ clearGraphCache }) => {
- clearGraphCache()
- }).catch((err) => {
- console.warn("[Reset Project State] Failed to clear graph cache:", err)
- })
+ if (queueMod.status === "fulfilled") {
+ try {
+ queueMod.value.clearQueueState()
+ } catch (err) {
+ console.warn("[Reset Project State] clearQueueState failed:", err)
+ }
+ } else {
+ console.warn("[Reset Project State] Failed to load ingest-queue:", queueMod.reason)
+ }
+
+ if (graphMod.status === "fulfilled") {
+ try {
+ graphMod.value.clearGraphCache()
+ } catch (err) {
+ console.warn("[Reset Project State] clearGraphCache failed:", err)
+ }
+ } else {
+ console.warn("[Reset Project State] Failed to load graph-relevance:", graphMod.reason)
+ }
}
diff --git a/src/lib/sweep-reviews.ts b/src/lib/sweep-reviews.ts
index 8b3122e2..f12fb8ce 100644
--- a/src/lib/sweep-reviews.ts
+++ b/src/lib/sweep-reviews.ts
@@ -315,14 +315,34 @@ async function llmJudgeReviews(
// ── Main ──────────────────────────────────────────────────────────────────
+/**
+ * Returns true if the given path still matches the currently-open project.
+ * Used to bail mid-sweep if the user has switched projects under us —
+ * the sweep's wiki index is for the old project and would falsely match
+ * the new project's reviews if we kept going.
+ */
+function matchesCurrentProject(projectPath: string): boolean {
+ const current = useWikiStore.getState().project?.path
+ if (!current) return false
+ return normalizePath(current) === normalizePath(projectPath)
+}
+
/**
* Scan pending review items and auto-resolve those whose condition
* no longer holds. Called when the ingest queue drains.
+ *
+ * Guards against two races:
+ * - `signal` aborted mid-flight (e.g. project switch triggered clearQueueState)
+ * - The current project changed while we were awaiting I/O — the wiki index
+ * we built is for the wrong project and must not be applied.
*/
export async function sweepResolvedReviews(
projectPath: string,
signal?: AbortSignal,
): Promise<number> {
+ if (signal?.aborted) return 0
+ if (!matchesCurrentProject(projectPath)) return 0
+
const store = useReviewStore.getState()
const pending = store.items.filter((i) => !i.resolved)
@@ -330,11 +350,19 @@ export async function sweepResolvedReviews(
const index = await buildWikiIndex(projectPath)
+ // Re-check after async I/O: user may have switched projects while we
+ // were reading the wiki directory.
+ if (signal?.aborted || !matchesCurrentProject(projectPath)) return 0
+
let ruleResolved = 0
const stillPending: ReviewItem[] = []
// Stage 1: rule-based matching
for (const item of pending) {
+ // Bail mid-loop on project switch / abort — applying rules to new
+ // project's reviews with old project's wiki index would corrupt state.
+ if (signal?.aborted || !matchesCurrentProject(projectPath)) return ruleResolved
+
let resolvedByRule = false
if (item.type === "missing-page") {
@@ -371,7 +399,7 @@ export async function sweepResolvedReviews(
const activity = useActivityStore.getState()
let activityId: string | null = null
- if (stillPending.length > 0 && !signal?.aborted) {
+ if (stillPending.length > 0 && !signal?.aborted && matchesCurrentProject(projectPath)) {
// Surface a running indicator so a multi-second LLM judgment doesn't
// feel like the app froze.
activityId = activity.addItem({
@@ -384,7 +412,9 @@ export async function sweepResolvedReviews(
try {
const resolvedIds = await llmJudgeReviews(stillPending, index, signal)
- if (!signal?.aborted) {
+ // Final guard: do not write results if the user switched projects
+ // or aborted between the LLM call starting and finishing.
+ if (!signal?.aborted && matchesCurrentProject(projectPath)) {
for (const id of resolvedIds) {
store.resolveItem(id, "llm-judged")
llmResolved++