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

feat: project UUID + registry; queue survives project switch

nash_su76215846e606
diff --git a/src/App.tsx b/src/App.tsx
index f2fa3e02..ad999129 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -86,9 +86,11 @@ function App() {
useWikiStore.getState().bumpDataVersion()
await saveLastProject(proj)
- // Restore ingest queue (resume interrupted tasks)
+ // 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.
import("@/lib/ingest-queue").then(({ restoreQueue }) => {
- restoreQueue(proj.path).catch((err) =>
+ restoreQueue(proj.id, proj.path).catch((err) =>
console.error("Failed to restore ingest queue:", err)
)
})
diff --git a/src/commands/fs.ts b/src/commands/fs.ts
index a8d31027..cb53b0e4 100644
--- a/src/commands/fs.ts
+++ b/src/commands/fs.ts
@@ -1,5 +1,12 @@
import { invoke } from "@tauri-apps/api/core"
import type { FileNode, WikiProject } from "@/types/wiki"
+import { ensureProjectId, upsertProjectInfo } from "@/lib/project-identity"
+
+/** Raw shape returned by the Rust commands — id is attached client-side. */
+interface RawProject {
+ name: string
+ path: string
+}
export async function readFile(path: string): Promise<string> {
return invoke<string>("read_file", { path })
@@ -39,15 +46,25 @@ export async function createDirectory(path: string): Promise<void> {
return invoke<void>("create_directory", { path })
}
+export async function fileExists(path: string): Promise<boolean> {
+ return invoke<boolean>("file_exists", { path })
+}
+
export async function createProject(
name: string,
path: string,
): Promise<WikiProject> {
- return invoke<WikiProject>("create_project", { name, path })
+ const raw = await invoke<RawProject>("create_project", { name, path })
+ const id = await ensureProjectId(raw.path)
+ await upsertProjectInfo(id, raw.path, raw.name)
+ return { id, name: raw.name, path: raw.path }
}
export async function openProject(path: string): Promise<WikiProject> {
- return invoke<WikiProject>("open_project", { path })
+ const raw = await invoke<RawProject>("open_project", { path })
+ const id = await ensureProjectId(raw.path)
+ await upsertProjectInfo(id, raw.path, raw.name)
+ return { id, name: raw.name, path: raw.path }
}
export async function clipServerStatus(): Promise<string> {
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 1087ebc8..5b8d418c 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -108,7 +108,7 @@ export function SourcesView() {
// Enqueue for serial ingest (runs in background via ingest queue)
if (llmConfig.apiKey || llmConfig.provider === "ollama" || llmConfig.provider === "custom") {
for (const destPath of importedPaths) {
- enqueueIngest(pp, destPath).catch((err) =>
+ enqueueIngest(project.id, destPath).catch((err) =>
console.error(`Failed to enqueue ingest:`, err)
)
}
@@ -173,7 +173,7 @@ export function SourcesView() {
})
if (tasks.length > 0) {
- await enqueueBatch(pp, tasks)
+ await enqueueBatch(project.id, tasks)
console.log(`[Folder Import] Enqueued ${tasks.length} files for ingest`)
}
}
diff --git a/src/lib/clip-watcher.ts b/src/lib/clip-watcher.ts
index d644062c..bada1b00 100644
--- a/src/lib/clip-watcher.ts
+++ b/src/lib/clip-watcher.ts
@@ -38,13 +38,15 @@ export function startClipWatcher() {
// Enqueue (not auto-ingest directly) so the task lands in the
// persisted queue, shows up in the activity panel, and survives
// a UI refresh. Same path used by file imports from sources-view.
+ // Pass the project's stable UUID — the queue looks up the
+ // current filesystem path from the registry at run time.
const llmConfig = store.llmConfig
const hasLlm =
!!llmConfig.apiKey ||
llmConfig.provider === "ollama" ||
llmConfig.provider === "custom"
if (hasLlm) {
- enqueueIngest(clipProjectPath, clipFilePath).catch((err) => {
+ enqueueIngest(project.id, clipFilePath).catch((err) => {
console.error("Failed to enqueue web clip:", err)
})
}
diff --git a/src/lib/ingest-queue.integration.test.ts b/src/lib/ingest-queue.integration.test.ts
index 374cc0b6..2b155033 100644
--- a/src/lib/ingest-queue.integration.test.ts
+++ b/src/lib/ingest-queue.integration.test.ts
@@ -22,6 +22,21 @@ vi.mock("./sweep-reviews", () => ({
sweepResolvedReviews: vi.fn().mockResolvedValue(0),
}))
+// Tests use real filesystem tmp dirs. Each test's `tmp.path` maps from
+// the test's UUID back to that dir via a mutable pointer the setup
+// updates in beforeEach — so getProjectPathById stays in sync with the
+// currently-active test project.
+const TEST_ID_A = "test-id-a"
+const TEST_ID_B = "test-id-b"
+const pathByIdRef: { map: Record<string, string> } = { map: {} }
+vi.mock("@/lib/project-identity", () => ({
+ ensureProjectId: vi.fn(),
+ upsertProjectInfo: vi.fn(),
+ getProjectPathById: vi.fn(async (id: string) => pathByIdRef.map[id] ?? null),
+ getProjectIdByPath: vi.fn(),
+ loadRegistry: vi.fn(),
+}))
+
import {
enqueueIngest,
enqueueBatch,
@@ -44,6 +59,7 @@ beforeEach(async () => {
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
tmp = await createTempProject("ingestqueue")
+ pathByIdRef.map = { [TEST_ID_A]: tmp.path }
useWikiStore.getState().setLlmConfig({
provider: "openai",
@@ -53,6 +69,9 @@ beforeEach(async () => {
customEndpoint: "",
maxContextSize: 128000,
})
+
+ // Activate the test project so enqueue / restore guards pass.
+ await restoreQueue(TEST_ID_A, tmp.path)
})
afterEach(async () => {
@@ -66,7 +85,7 @@ async function readQueueFile(): Promise<string> {
describe("ingest-queue persistence — write", () => {
it("writes .llm-wiki/ingest-queue.json after enqueue", async () => {
- await enqueueIngest(tmp.path, "raw/sources/a.md")
+ await enqueueIngest(TEST_ID_A, "raw/sources/a.md")
await waitFor(async () => {
try {
const c = await readQueueFile()
@@ -80,7 +99,7 @@ describe("ingest-queue persistence — write", () => {
})
it("persists Unicode source paths without corruption", async () => {
- await enqueueBatch(tmp.path, [
+ await enqueueBatch(TEST_ID_A, [
{ sourcePath: "raw/sources/注意力机制.pdf", folderContext: "AI研究 > 论文" },
{ sourcePath: "raw/日本語.md", folderContext: "" },
])
@@ -101,12 +120,12 @@ describe("ingest-queue persistence — write", () => {
it("auto-creates .llm-wiki/ directory when it doesn't exist", async () => {
expect(await fileExists(`${tmp.path}/.llm-wiki`)).toBe(false)
- await enqueueIngest(tmp.path, "x.md")
+ await enqueueIngest(TEST_ID_A, "x.md")
await waitFor(() => fileExists(`${tmp.path}/.llm-wiki/ingest-queue.json`))
})
it("each enqueue updates the persisted JSON in-place", async () => {
- await enqueueIngest(tmp.path, "first.md")
+ await enqueueIngest(TEST_ID_A, "first.md")
await waitFor(async () => {
try {
return JSON.parse(await readQueueFile()).length === 1
@@ -115,7 +134,7 @@ describe("ingest-queue persistence — write", () => {
}
})
- await enqueueIngest(tmp.path, "second.md")
+ await enqueueIngest(TEST_ID_A, "second.md")
await waitFor(async () => {
try {
return JSON.parse(await readQueueFile()).length === 2
@@ -133,7 +152,7 @@ describe("ingest-queue persistence — write", () => {
describe("ingest-queue persistence — restore round-trip", () => {
it("restoreQueue reads back exactly what enqueue wrote", async () => {
- await enqueueBatch(tmp.path, [
+ await enqueueBatch(TEST_ID_A, [
{ sourcePath: "a.md", folderContext: "ctx-a" },
{ sourcePath: "b.md", folderContext: "ctx-b" },
])
@@ -150,7 +169,7 @@ describe("ingest-queue persistence — restore round-trip", () => {
clearQueueState()
expect(getQueue()).toHaveLength(0)
- await restoreQueue(tmp.path)
+ await restoreQueue(TEST_ID_A, tmp.path)
const restored = getQueue()
expect(restored).toHaveLength(2)
expect(restored.map((t) => t.sourcePath).sort()).toEqual(["a.md", "b.md"])
@@ -173,7 +192,7 @@ describe("ingest-queue persistence — restore round-trip", () => {
JSON.stringify(saved, null, 2),
)
- await restoreQueue(tmp.path)
+ await restoreQueue(TEST_ID_A, tmp.path)
await flushIO(2)
const restored = getQueue()
@@ -200,7 +219,7 @@ describe("ingest-queue persistence — restore round-trip", () => {
JSON.stringify(saved, null, 2),
)
- await restoreQueue(tmp.path)
+ await restoreQueue(TEST_ID_A, tmp.path)
const restored = getQueue()
expect(restored[0].status).toBe("failed")
expect(restored[0].error).toBe("LLM hit its rate limit")
@@ -208,7 +227,7 @@ describe("ingest-queue persistence — restore round-trip", () => {
})
it("returns empty queue when the file doesn't exist", async () => {
- await restoreQueue(tmp.path)
+ await restoreQueue(TEST_ID_A, tmp.path)
expect(getQueue()).toEqual([])
})
@@ -217,12 +236,12 @@ describe("ingest-queue persistence — restore round-trip", () => {
`${tmp.path}/.llm-wiki/ingest-queue.json`,
"{not valid json at all",
)
- await restoreQueue(tmp.path)
+ await restoreQueue(TEST_ID_A, tmp.path)
expect(getQueue()).toEqual([])
})
it("round-trips Unicode + folder context correctly", async () => {
- await enqueueBatch(tmp.path, [
+ await enqueueBatch(TEST_ID_A, [
{ sourcePath: "raw/sources/注意力.pdf", folderContext: "研究 > 深度学习" },
])
await waitFor(async () => {
@@ -238,7 +257,7 @@ describe("ingest-queue persistence — restore round-trip", () => {
expect(onDisk[0].folderContext).toBe("研究 > 深度学习")
clearQueueState()
- await restoreQueue(tmp.path)
+ await restoreQueue(TEST_ID_A, tmp.path)
const restored = getQueue()
expect(restored).toHaveLength(1)
@@ -250,9 +269,10 @@ describe("ingest-queue persistence — restore round-trip", () => {
describe("ingest-queue persistence — cross-project isolation", () => {
it("restoreQueue from project A does not leak into project B", async () => {
const other = await createTempProject("ingestqueue-other")
+ pathByIdRef.map[TEST_ID_B] = other.path
try {
// Populate project A
- await enqueueIngest(tmp.path, "a.md")
+ await enqueueIngest(TEST_ID_A, "a.md")
await waitFor(async () => {
try {
return JSON.parse(await readQueueFile()).length === 1
@@ -263,7 +283,7 @@ describe("ingest-queue persistence — cross-project isolation", () => {
expect(getQueue()).toHaveLength(1)
// Restore project B (empty) — should see empty queue, not A's
- await restoreQueue(other.path)
+ await restoreQueue(TEST_ID_B, other.path)
expect(getQueue()).toEqual([])
} finally {
await other.cleanup()
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index a6d15f70..f17003b3 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -20,6 +20,24 @@ vi.mock("./sweep-reviews", () => ({
sweepResolvedReviews: vi.fn().mockResolvedValue(0),
}))
+// Mock project-identity — tests don't hit Tauri plugin-store. Maps the
+// test UUIDs defined below back to their assigned paths.
+const TEST_ID = "test-project-uuid"
+const TEST_PATH = "/project"
+const TEST_ID_B = "test-project-uuid-b"
+const TEST_PATH_B = "/project-b"
+const idToPath: Record<string, string> = {
+ [TEST_ID]: TEST_PATH,
+ [TEST_ID_B]: TEST_PATH_B,
+}
+vi.mock("@/lib/project-identity", () => ({
+ ensureProjectId: vi.fn(),
+ upsertProjectInfo: vi.fn(),
+ getProjectPathById: vi.fn(async (id: string) => idToPath[id] ?? null),
+ getProjectIdByPath: vi.fn(),
+ loadRegistry: vi.fn(),
+}))
+
import {
enqueueIngest,
enqueueBatch,
@@ -42,7 +60,15 @@ const mockReadFile = vi.mocked(readFile)
const mockWriteFile = vi.mocked(writeFile)
const mockSweep = vi.mocked(sweepResolvedReviews)
-beforeEach(() => {
+/** Simulate the app having opened `TEST_ID` at `TEST_PATH` so the queue
+ * module's `currentProjectId` / `currentProjectPath` are set. Most
+ * tests need this — enqueue / retry / cancel guard against inactive
+ * projects. */
+async function activateProject(id: string = TEST_ID): Promise<void> {
+ await restoreQueue(id, idToPath[id])
+}
+
+beforeEach(async () => {
clearQueueState()
mockAutoIngest.mockReset()
mockReadFile.mockReset()
@@ -63,13 +89,15 @@ beforeEach(() => {
customEndpoint: "",
maxContextSize: 128000,
})
+
+ await activateProject()
})
describe("ingest-queue — enqueue & basic processing", () => {
it("enqueueIngest adds a pending task and triggers processing", async () => {
- mockAutoIngest.mockResolvedValue([])
+ mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
- const id = await enqueueIngest("/project", "raw/sources/a.md")
+ const id = await enqueueIngest(TEST_ID, "raw/sources/a.md")
expect(id).toMatch(/^ingest-/)
// Let the async processing loop run
@@ -82,7 +110,7 @@ describe("ingest-queue — enqueue & basic processing", () => {
it("persists queue to disk on enqueue", async () => {
mockAutoIngest.mockImplementation(() => new Promise(() => {})) // never resolves
- await enqueueIngest("/project", "a.md")
+ await enqueueIngest(TEST_ID, "a.md")
await flushMicrotasks(2)
// writeFile should have been called to save the queue
@@ -93,9 +121,9 @@ describe("ingest-queue — enqueue & basic processing", () => {
})
it("enqueueBatch queues multiple tasks and processes them serially", async () => {
- mockAutoIngest.mockResolvedValue([])
+ mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
- await enqueueBatch("/project", [
+ await enqueueBatch(TEST_ID, [
{ sourcePath: "a.md", folderContext: "" },
{ sourcePath: "b.md", folderContext: "" },
{ sourcePath: "c.md", folderContext: "" },
@@ -112,7 +140,7 @@ describe("ingest-queue — retry & failure", () => {
it("retries a failing task up to MAX_RETRIES=3 then marks failed", async () => {
mockAutoIngest.mockRejectedValue(new Error("LLM error"))
- await enqueueIngest("/project", "bad.md")
+ await enqueueIngest(TEST_ID, "bad.md")
await flushMicrotasks(30)
expect(mockAutoIngest).toHaveBeenCalledTimes(3)
@@ -127,25 +155,45 @@ describe("ingest-queue — retry & failure", () => {
mockAutoIngest
.mockRejectedValueOnce(new Error("transient"))
.mockRejectedValueOnce(new Error("transient"))
- .mockResolvedValueOnce([])
+ .mockResolvedValueOnce(["wiki/sources/foo.md"])
- await enqueueIngest("/project", "flaky.md")
+ await enqueueIngest(TEST_ID, "flaky.md")
await flushMicrotasks(30)
expect(mockAutoIngest).toHaveBeenCalledTimes(3)
expect(getQueue()).toHaveLength(0)
})
+ it("treats autoIngest resolving to an empty array as a failure (not silent success)", async () => {
+ // Regression: a webview refresh could abort the LLM fetch, making
+ // streamChat's error path fire, which historically caused autoIngest
+ // to `return []` — processNext then removed the task from the queue
+ // as if it had succeeded. The safety net in processNext now rejects
+ // zero-output completions and keeps the task around to retry.
+ mockAutoIngest.mockResolvedValue([])
+
+ await enqueueIngest(TEST_ID, "refresh-abort.md")
+ await flushMicrotasks(30)
+
+ // Three retries were attempted — the task didn't just vanish.
+ expect(mockAutoIngest).toHaveBeenCalledTimes(3)
+ const queue = getQueue()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].status).toBe("failed")
+ expect(queue[0].error).toContain("no output files")
+ expect(queue[0].retryCount).toBe(3)
+ })
+
it("retryTask resets a failed task to pending and reprocesses it", async () => {
mockAutoIngest.mockRejectedValue(new Error("always fails"))
- await enqueueIngest("/project", "x.md")
+ await enqueueIngest(TEST_ID, "x.md")
await flushMicrotasks(20)
expect(getQueue()[0].status).toBe("failed")
const taskId = getQueue()[0].id
- mockAutoIngest.mockResolvedValueOnce([])
- await retryTask("/project", taskId)
+ mockAutoIngest.mockResolvedValueOnce(["wiki/sources/foo.md"])
+ await retryTask(taskId)
await flushMicrotasks(10)
expect(getQueue()).toHaveLength(0)
@@ -156,7 +204,7 @@ describe("ingest-queue — cancel", () => {
it("cancelTask removes a pending task without calling autoIngest", async () => {
mockAutoIngest.mockImplementation(() => new Promise(() => {})) // block first task
- await enqueueBatch("/project", [
+ await enqueueBatch(TEST_ID, [
{ sourcePath: "first.md", folderContext: "" },
{ sourcePath: "second.md", folderContext: "" },
])
@@ -165,7 +213,7 @@ describe("ingest-queue — cancel", () => {
// first.md is processing; cancel second.md (still pending)
const queue = getQueue()
const second = queue.find((t) => t.sourcePath === "second.md")!
- await cancelTask("/project", second.id)
+ await cancelTask(second.id)
expect(getQueue().find((t) => t.sourcePath === "second.md")).toBeUndefined()
expect(getQueue().find((t) => t.sourcePath === "first.md")).toBeDefined()
@@ -177,7 +225,7 @@ describe("ingest-queue — cancelAllTasks", () => {
// Block the processing task so it doesn't finish on its own.
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
- await enqueueBatch("/project", [
+ await enqueueBatch(TEST_ID, [
{ sourcePath: "a.md", folderContext: "" },
{ sourcePath: "b.md", folderContext: "" },
{ sourcePath: "c.md", folderContext: "" },
@@ -188,7 +236,7 @@ describe("ingest-queue — cancelAllTasks", () => {
const failedTask = getQueue()[2]
;(failedTask as { status: string }).status = "failed"
- const removed = await cancelAllTasks("/project")
+ const removed = await cancelAllTasks()
expect(removed).toBe(2) // a (processing) + b (pending) gone
expect(getQueue()).toHaveLength(1)
@@ -197,18 +245,18 @@ describe("ingest-queue — cancelAllTasks", () => {
})
it("returns 0 when the queue is empty", async () => {
- const removed = await cancelAllTasks("/project")
+ const removed = await cancelAllTasks()
expect(removed).toBe(0)
expect(getQueue()).toHaveLength(0)
})
it("is safe to call after it has already cleared the queue", async () => {
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
- await enqueueIngest("/project", "only.md")
+ await enqueueIngest(TEST_ID, "only.md")
await flushMicrotasks(2)
- await cancelAllTasks("/project")
- const secondCall = await cancelAllTasks("/project")
+ await cancelAllTasks()
+ const secondCall = await cancelAllTasks()
expect(secondCall).toBe(0)
})
})
@@ -216,7 +264,7 @@ describe("ingest-queue — cancelAllTasks", () => {
describe("ingest-queue — clearCompletedTasks & summary", () => {
it("getQueueSummary returns accurate counts", async () => {
mockAutoIngest.mockRejectedValue(new Error("fail"))
- await enqueueIngest("/project", "fail.md")
+ await enqueueIngest(TEST_ID, "fail.md")
await flushMicrotasks(20)
const summary = getQueueSummary()
@@ -227,20 +275,20 @@ describe("ingest-queue — clearCompletedTasks & summary", () => {
it("clearCompletedTasks drops failed tasks", async () => {
mockAutoIngest.mockRejectedValue(new Error("fail"))
- await enqueueIngest("/project", "f.md")
+ await enqueueIngest(TEST_ID, "f.md")
await flushMicrotasks(20)
expect(getQueue()).toHaveLength(1)
- await clearCompletedTasks("/project")
+ await clearCompletedTasks()
expect(getQueue()).toHaveLength(0)
})
})
describe("ingest-queue — queue-drain triggers review sweep", () => {
it("calls sweepResolvedReviews once after a successful task drains the queue", async () => {
- mockAutoIngest.mockResolvedValue([])
+ mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
- await enqueueIngest("/project", "ok.md")
+ await enqueueIngest(TEST_ID, "ok.md")
await flushMicrotasks(30)
expect(mockSweep).toHaveBeenCalledOnce()
@@ -250,15 +298,15 @@ describe("ingest-queue — queue-drain triggers review sweep", () => {
it("does NOT trigger sweep when no task has been processed since the last drain", async () => {
// No tasks enqueued — processedSinceDrain flag stays false
// (We simulate an idle condition by enqueueing, processing, draining once)
- mockAutoIngest.mockResolvedValue([])
- await enqueueIngest("/project", "a.md")
+ mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
+ await enqueueIngest(TEST_ID, "a.md")
await flushMicrotasks(20)
expect(mockSweep).toHaveBeenCalledTimes(1)
// Now the queue is empty. Calling cancelTask on a nonexistent id is a
// no-op but internally may call processNext → no drain fire (nothing
// was processed since the last drain).
- await cancelTask("/project", "nonexistent")
+ await cancelTask("nonexistent")
await flushMicrotasks(5)
expect(mockSweep).toHaveBeenCalledTimes(1)
})
@@ -266,7 +314,7 @@ describe("ingest-queue — queue-drain triggers review sweep", () => {
it("does NOT trigger sweep when all tasks fail (nothing was successfully ingested)", async () => {
mockAutoIngest.mockRejectedValue(new Error("always fails"))
- await enqueueIngest("/project", "bad.md")
+ await enqueueIngest(TEST_ID, "bad.md")
await flushMicrotasks(30)
expect(mockSweep).not.toHaveBeenCalled()
@@ -276,7 +324,7 @@ describe("ingest-queue — queue-drain triggers review sweep", () => {
describe("ingest-queue — clearQueueState", () => {
it("clears pending tasks and resets processing flag", async () => {
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
- await enqueueBatch("/project", [
+ await enqueueBatch(TEST_ID, [
{ sourcePath: "a.md", folderContext: "" },
{ sourcePath: "b.md", folderContext: "" },
])
@@ -289,8 +337,8 @@ describe("ingest-queue — clearQueueState", () => {
})
it("processedSinceDrain flag resets so a post-switch no-op won't trigger sweep", async () => {
- mockAutoIngest.mockResolvedValue([])
- await enqueueIngest("/project", "x.md")
+ mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
+ await enqueueIngest(TEST_ID, "x.md")
await flushMicrotasks(20)
mockSweep.mockClear()
@@ -305,13 +353,13 @@ describe("ingest-queue — restoreQueue", () => {
it("resets in-memory state before loading, preventing cross-project bleed", async () => {
// Seed in-memory state from project A
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
- await enqueueIngest("/project-A", "a.md")
+ await enqueueIngest(TEST_ID, "a.md")
await flushMicrotasks(2)
expect(getQueue().length).toBeGreaterThan(0)
// Now restore project B — should reset and load B's saved queue (empty)
mockReadFile.mockRejectedValue(new Error("ENOENT"))
- await restoreQueue("/project-B")
+ await restoreQueue(TEST_ID_B, TEST_PATH_B)
expect(getQueue()).toHaveLength(0)
})
@@ -331,7 +379,7 @@ describe("ingest-queue — restoreQueue", () => {
// Prevent the reprocessing kickoff from completing forever:
mockAutoIngest.mockImplementation(() => new Promise(() => {}))
- await restoreQueue("/project")
+ await restoreQueue(TEST_ID, TEST_PATH)
await flushMicrotasks(2)
const queue = getQueue()
@@ -356,10 +404,118 @@ describe("ingest-queue — restoreQueue", () => {
]
mockReadFile.mockResolvedValue(JSON.stringify(saved))
- await restoreQueue("/project")
+ await restoreQueue(TEST_ID, TEST_PATH)
const queue = getQueue()
expect(queue).toHaveLength(1)
expect(queue[0].status).toBe("failed")
expect(queue[0].error).toBe("prior failure")
})
+
+ it("backfills projectId on older task files that predate the field", async () => {
+ // Disk written before projectId was part of the schema.
+ const savedLegacy = [
+ {
+ id: "ingest-legacy",
+ sourcePath: "legacy.md",
+ folderContext: "",
+ status: "pending",
+ addedAt: 0,
+ error: null,
+ retryCount: 0,
+ },
+ ]
+ mockReadFile.mockResolvedValue(JSON.stringify(savedLegacy))
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ const queue = getQueue()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].projectId).toBe(TEST_ID)
+ })
+})
+
+import { pauseQueue } from "./ingest-queue"
+
+describe("ingest-queue — pauseQueue & switch-project survival", () => {
+ it("pauseQueue persists pending/processing tasks to the paused project's disk", async () => {
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
+ await enqueueBatch(TEST_ID, [
+ { sourcePath: "a.md", folderContext: "" },
+ { sourcePath: "b.md", folderContext: "" },
+ ])
+ await flushMicrotasks(2)
+ mockWriteFile.mockClear()
+
+ await pauseQueue()
+
+ // The last write call should contain BOTH tasks, with the processing
+ // one demoted back to pending for resume-on-return.
+ const writes = mockWriteFile.mock.calls
+ expect(writes.length).toBeGreaterThan(0)
+ const [pathArg, contentArg] = writes[writes.length - 1]
+ expect(String(pathArg)).toContain("/project/.llm-wiki/ingest-queue.json")
+ const persisted = JSON.parse(String(contentArg)) as Array<{ status: string }>
+ expect(persisted).toHaveLength(2)
+ for (const t of persisted) expect(t.status).toBe("pending")
+ })
+
+ it("pauseQueue then restoreQueue of SAME project brings tasks back", async () => {
+ mockAutoIngest.mockImplementation(() => new Promise(() => {}))
+ await enqueueIngest(TEST_ID, "first.md")
+ await flushMicrotasks(2)
+
+ // Capture what pauseQueue writes so restore can read it back.
+ let lastWrittenContent = ""
+ mockWriteFile.mockImplementation(async (_path: string, content: string) => {
+ lastWrittenContent = content
+ })
+ await pauseQueue()
+
+ // Simulate reloading that same project: disk returns what we just wrote.
+ mockReadFile.mockResolvedValue(lastWrittenContent)
+ await restoreQueue(TEST_ID, TEST_PATH)
+
+ const queue = getQueue()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].sourcePath).toBe("first.md")
+ })
+
+ it("processNext bails if currentProjectId changes mid-ingest (no cross-project writes)", async () => {
+ // Block autoIngest so we can pause mid-flight. Then resolve it
+ // AFTER pauseQueue completes to simulate the delayed return.
+ let resolveAutoIngest: (files: string[]) => void = () => {}
+ mockAutoIngest.mockImplementation(
+ () => new Promise<string[]>((resolve) => { resolveAutoIngest = resolve }),
+ )
+
+ await enqueueIngest(TEST_ID, "long-running.md")
+ await flushMicrotasks(2)
+ // Ensure the task is processing
+ expect(getQueue().find((t) => t.status === "processing")).toBeTruthy()
+
+ // Switch projects: pause then restore a different one.
+ mockWriteFile.mockClear()
+ await pauseQueue()
+ await restoreQueue(TEST_ID_B, TEST_PATH_B)
+
+ // Now the orphaned autoIngest for TEST_ID returns late.
+ resolveAutoIngest(["wiki/sources/foo.md"])
+ await flushMicrotasks(10)
+
+ // The orphan must not have written to the ACTIVE (B) project's file.
+ // Inspect every post-pause write — the path should never contain the
+ // project-B queue file getting mutated by the orphan's filter result.
+ const writes = mockWriteFile.mock.calls
+ // Confirm no write touched project B's queue from orphan completion.
+ // (The only writes should be pauseQueue's flush to /project and
+ // restoreQueue's initial save of B's empty queue.)
+ const bWrites = writes.filter(([p]) => String(p).includes("/project-b/"))
+ // B's queue should only have been written once (during restore), and
+ // that write should show an empty array — not the orphan's filtered
+ // result leaking in.
+ for (const [, content] of bWrites) {
+ const parsed = JSON.parse(String(content))
+ expect(parsed).toEqual([])
+ }
+ })
})
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index 478925c7..455d7bae 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -2,11 +2,16 @@ import { readFile, writeFile } from "@/commands/fs"
import { autoIngest } from "./ingest"
import { useWikiStore } from "@/stores/wiki-store"
import { normalizePath, isAbsolutePath } from "@/lib/path-utils"
+import { getProjectPathById } from "@/lib/project-identity"
// ── Types ─────────────────────────────────────────────────────────────────
export interface IngestTask {
id: string
+ /** Stable project UUID (see project-identity.ts). Prefer this to
+ * `projectPath` because the filesystem location can change — tasks
+ * look up the current path via the registry at run time. */
+ projectId: string
sourcePath: string // relative to project: "raw/sources/folder/file.pdf"
folderContext: string // e.g. "AI-Research > papers" or ""
status: "pending" | "processing" | "done" | "failed"
@@ -19,6 +24,13 @@ export interface IngestTask {
let queue: IngestTask[] = []
let processing = false
+/** UUID of the currently-active project. Used as a stale-context guard
+ * in processNext: if this changes mid-ingest (user switched projects),
+ * the orphaned runner bails instead of writing to the old project. */
+let currentProjectId = ""
+/** Cached filesystem path of the currently-active project. Kept in lock-
+ * step with `currentProjectId` by pauseQueue / restoreQueue so sync
+ * callers (saveQueue, cancelTask, etc.) don't need a registry lookup. */
let currentProjectPath = ""
let currentAbortController: AbortController | null = null
let lastWrittenFiles: string[] = [] // track files written by current ingest for cleanup
@@ -45,10 +57,17 @@ async function saveQueue(projectPath: string): Promise<void> {
}
}
-async function loadQueue(projectPath: string): Promise<IngestTask[]> {
+async function loadQueue(projectPath: string, projectId: string): Promise<IngestTask[]> {
try {
const raw = await readFile(queueFilePath(projectPath))
- return JSON.parse(raw) as IngestTask[]
+ const tasks = JSON.parse(raw) as IngestTask[]
+ // Backfill projectId for tasks persisted before the field existed.
+ // Files live inside a specific project, so every task in this file
+ // belongs to `projectId` regardless of what's on disk.
+ return tasks.map((t) => ({
+ ...t,
+ projectId: t.projectId ?? projectId,
+ }))
} catch {
return []
}
@@ -61,18 +80,24 @@ function generateId(): string {
}
/**
- * Add a file to the ingest queue.
+ * Add a file to the ingest queue. The project MUST be the currently-
+ * active project — switching first is a prerequisite. Returns the new
+ * task's id.
*/
export async function enqueueIngest(
- projectPath: string,
+ projectId: string,
sourcePath: string,
folderContext: string = "",
): Promise<string> {
- const pp = normalizePath(projectPath)
- currentProjectPath = pp
+ if (!currentProjectId || currentProjectId !== projectId) {
+ throw new Error(
+ `enqueueIngest: project ${projectId} is not the active project (current: ${currentProjectId || "<none>"})`,
+ )
+ }
const task: IngestTask = {
id: generateId(),
+ projectId,
sourcePath,
folderContext,
status: "pending",
@@ -82,28 +107,32 @@ export async function enqueueIngest(
}
queue.push(task)
- await saveQueue(pp)
+ await saveQueue(currentProjectPath)
- // Start processing if not already running
- processNext(pp)
+ processNext(currentProjectId)
return task.id
}
/**
- * Add multiple files to the queue at once.
+ * Add multiple files to the queue at once. Same active-project
+ * requirement as enqueueIngest.
*/
export async function enqueueBatch(
- projectPath: string,
+ projectId: string,
files: Array<{ sourcePath: string; folderContext: string }>,
): Promise<string[]> {
- const pp = normalizePath(projectPath)
- currentProjectPath = pp
- const ids: string[] = []
+ if (!currentProjectId || currentProjectId !== projectId) {
+ throw new Error(
+ `enqueueBatch: project ${projectId} is not the active project (current: ${currentProjectId || "<none>"})`,
+ )
+ }
+ const ids: string[] = []
for (const file of files) {
const task: IngestTask = {
id: generateId(),
+ projectId,
sourcePath: file.sourcePath,
folderContext: file.folderContext,
status: "pending",
@@ -115,33 +144,36 @@ export async function enqueueBatch(
ids.push(task.id)
}
- await saveQueue(pp)
+ await saveQueue(currentProjectPath)
console.log(`[Ingest Queue] Enqueued ${files.length} files`)
- processNext(pp)
+ processNext(currentProjectId)
return ids
}
/**
- * Retry a failed task.
+ * Retry a failed task. Only valid for tasks in the active project's
+ * queue.
*/
-export async function retryTask(projectPath: string, taskId: string): Promise<void> {
+export async function retryTask(taskId: string): Promise<void> {
const task = queue.find((t) => t.id === taskId)
if (!task) return
+ if (task.projectId !== currentProjectId) return
task.status = "pending"
task.error = null
- await saveQueue(projectPath)
- processNext(normalizePath(projectPath))
+ await saveQueue(currentProjectPath)
+ processNext(currentProjectId)
}
/**
* Cancel a pending or processing task.
* If processing, aborts the LLM call and cleans up generated files.
*/
-export async function cancelTask(projectPath: string, taskId: string): Promise<void> {
+export async function cancelTask(taskId: string): Promise<void> {
const task = queue.find((t) => t.id === taskId)
if (!task) return
+ if (task.projectId !== currentProjectId) return
if (task.status === "processing") {
// Abort the in-progress LLM call
@@ -157,7 +189,7 @@ export async function cancelTask(projectPath: string, taskId: string): Promise<v
try {
const fullPath = isAbsolutePath(filePath)
? normalizePath(filePath)
- : `${normalizePath(projectPath)}/${filePath}`
+ : `${currentProjectPath}/${filePath}`
await deleteFile(fullPath)
} catch {
// file may not exist
@@ -171,46 +203,42 @@ export async function cancelTask(projectPath: string, taskId: string): Promise<v
}
queue = queue.filter((t) => t.id !== taskId)
- await saveQueue(projectPath)
+ await saveQueue(currentProjectPath)
console.log(`[Ingest Queue] Cancelled: ${task.sourcePath}`)
- // Continue with next task
- processNext(normalizePath(projectPath))
+ processNext(currentProjectId)
}
/**
- * Clear all done/failed tasks from the queue.
+ * Clear all done/failed tasks from the active project's queue.
*/
-export async function clearCompletedTasks(projectPath: string): Promise<void> {
+export async function clearCompletedTasks(): Promise<void> {
queue = queue.filter((t) => t.status === "pending" || t.status === "processing")
- await saveQueue(projectPath)
+ await saveQueue(currentProjectPath)
}
/**
- * Cancel everything that's not finished: aborts the running task (if any),
- * cleans up its partial output, and drops every pending + processing item.
+ * Cancel everything that's not finished in the active project's queue:
+ * aborts the running task (if any), cleans up its partial output, and
+ * drops every pending + processing item.
*
* Failed tasks are retained so the user can still see / retry them.
* Returns the number of tasks removed from the queue.
*/
-export async function cancelAllTasks(projectPath: string): Promise<number> {
- const pp = normalizePath(projectPath)
-
- // Abort any in-progress LLM call first so it stops burning tokens.
+export async function cancelAllTasks(): Promise<number> {
if (currentAbortController) {
currentAbortController.abort()
currentAbortController = null
}
processing = false
- // Clean up partial files from the task that was processing, if any.
if (lastWrittenFiles.length > 0) {
const { deleteFile } = await import("@/commands/fs")
for (const filePath of lastWrittenFiles) {
try {
const fullPath = isAbsolutePath(filePath)
? normalizePath(filePath)
- : `${pp}/${filePath}`
+ : `${currentProjectPath}/${filePath}`
await deleteFile(fullPath)
} catch {
// file may not exist
@@ -223,7 +251,7 @@ export async function cancelAllTasks(projectPath: string): Promise<number> {
queue = queue.filter((t) => t.status === "failed")
const removed = before - queue.length
- await saveQueue(pp)
+ await saveQueue(currentProjectPath)
console.log(`[Ingest Queue] Cancelled all: ${removed} tasks removed`)
return removed
}
@@ -248,20 +276,21 @@ export function getQueueSummary(): { pending: number; processing: number; failed
}
/**
- * Clear all in-memory queue state without touching disk.
- * Called when switching projects to prevent cross-project contamination.
+ * Clear all in-memory queue state without touching disk. Used by tests
+ * that want a clean slate between cases. **Production code should use
+ * `pauseQueue()` on project switch**, which flushes pending state to
+ * disk before clearing memory.
*/
export function clearQueueState(): void {
- // Abort any in-progress ingest
if (currentAbortController) {
currentAbortController.abort()
}
- // Abort any in-progress review sweep LLM call
if (sweepAbortController) {
sweepAbortController.abort()
}
queue = []
processing = false
+ currentProjectId = ""
currentProjectPath = ""
currentAbortController = null
sweepAbortController = null
@@ -269,35 +298,96 @@ export function clearQueueState(): void {
processedSinceDrain = false
}
+/**
+ * Project-switch handshake. Flushes the active project's current queue
+ * state to its disk file (so pending/failed tasks survive the switch),
+ * reverts any processing task to pending, then clears in-memory state
+ * so the next `restoreQueue()` can safely load a different project.
+ *
+ * Must be called before opening or switching to a different project.
+ * Must be `await`ed — the disk flush is async.
+ */
+export async function pauseQueue(): Promise<void> {
+ if (!currentProjectId || !currentProjectPath) {
+ // Nothing to pause (no active project)
+ return
+ }
+
+ const pausedProjectPath = currentProjectPath
+
+ if (currentAbortController) {
+ currentAbortController.abort()
+ currentAbortController = null
+ }
+ if (sweepAbortController) {
+ sweepAbortController.abort()
+ sweepAbortController = null
+ }
+ processing = false
+
+ // Revert any in-flight processing task back to pending so when the
+ // user returns to this project, the task is re-tried from scratch.
+ for (const task of queue) {
+ if (task.status === "processing") {
+ task.status = "pending"
+ }
+ }
+
+ // Flush the paused state to THIS project's disk before wiping memory.
+ await saveQueue(pausedProjectPath)
+
+ queue = []
+ currentProjectId = ""
+ currentProjectPath = ""
+ lastWrittenFiles = []
+ processedSinceDrain = false
+}
+
// ── Restore on startup ───────────────────────────────────────────────────
/**
- * Load queue from disk and resume processing.
- * Called on app startup.
+ * Load queue from disk and resume processing. Called on app startup
+ * and when opening / switching to a project. `pauseQueue()` must have
+ * been called first (or the active project already cleared) so that
+ * in-memory state is not contaminated from the previous project.
*/
-export async function restoreQueue(projectPath: string): Promise<void> {
+export async function restoreQueue(
+ projectId: string,
+ projectPath: string,
+): Promise<void> {
const pp = normalizePath(projectPath)
- // Always reset in-memory state FIRST to prevent cross-project contamination
+ // Defensive: reset in-memory state (should already be empty via
+ // pauseQueue, but clearing again costs nothing).
queue = []
processing = false
currentAbortController = null
lastWrittenFiles = []
+ currentProjectId = projectId
currentProjectPath = pp
- const saved = await loadQueue(pp)
+ const saved = await loadQueue(pp, projectId)
if (saved.length === 0) return
+ // Drop any cross-project contamination (shouldn't happen in practice
+ // but defends against a corrupt queue file).
+ const mine = saved.filter((t) => t.projectId === projectId)
+ if (mine.length !== saved.length) {
+ console.warn(
+ `[Ingest Queue] Dropped ${saved.length - mine.length} cross-project tasks during restore`,
+ )
+ }
+
// Reset any "processing" tasks back to "pending" (interrupted by app close)
let restored = 0
- for (const task of saved) {
+ for (const task of mine) {
if (task.status === "processing") {
task.status = "pending"
restored++
}
}
- queue = saved
+ queue = mine
await saveQueue(pp)
const pending = queue.filter((t) => t.status === "pending").length
@@ -305,7 +395,7 @@ export async function restoreQueue(projectPath: string): Promise<void> {
if (pending > 0 || restored > 0) {
console.log(`[Ingest Queue] Restored: ${pending} pending, ${failed} failed, ${restored} resumed from interrupted`)
- processNext(pp)
+ processNext(projectId)
}
}
@@ -313,8 +403,11 @@ export async function restoreQueue(projectPath: string): Promise<void> {
const MAX_RETRIES = 3
-async function onQueueDrained(projectPath: string): Promise<void> {
+async function onQueueDrained(projectId: string, projectPath: string): Promise<void> {
if (!processedSinceDrain) return
+ // Stale-context guard — if we switched projects mid-drain, the sweep
+ // would burn tokens analyzing the wrong project.
+ if (currentProjectId !== projectId) return
processedSinceDrain = false
sweepAbortController = new AbortController()
@@ -332,23 +425,44 @@ async function onQueueDrained(projectPath: string): Promise<void> {
}
}
-async function processNext(projectPath: string): Promise<void> {
+async function processNext(projectId: string): Promise<void> {
if (processing) return
+ // Stale-context guard: processNext may be invoked by an orphaned
+ // recursion from a previous project. If we're no longer active, bail.
+ if (currentProjectId !== projectId) return
- const next = queue.find((t) => t.status === "pending")
+ const next = queue.find((t) => t.projectId === projectId && t.status === "pending")
if (!next) {
// Queue drained — trigger review cleanup (auto-resolve stale items)
- onQueueDrained(projectPath).catch((err) =>
+ const pathAtDrain = currentProjectPath
+ onQueueDrained(projectId, pathAtDrain).catch((err) =>
console.error("[Ingest Queue] sweep failed:", err)
)
return
}
+ // Look up the project's current filesystem path from the registry —
+ // it may have moved since the task was enqueued. If the project isn't
+ // in the registry (was deleted or never registered), mark as failed.
+ const registryPath = await getProjectPathById(projectId)
+ const pp = registryPath ? normalizePath(registryPath) : ""
+
+ // Check we're still active after the registry await.
+ if (currentProjectId !== projectId) return
+
+ if (!pp) {
+ next.status = "failed"
+ next.error = "Project not found in registry (was it deleted?)"
+ await saveQueue(currentProjectPath)
+ processNext(projectId)
+ return
+ }
+
processing = true
next.status = "processing"
- await saveQueue(projectPath)
+ await saveQueue(pp)
+ if (currentProjectId !== projectId) return
- const pp = normalizePath(projectPath)
const llmConfig = useWikiStore.getState().llmConfig
// Check if LLM is configured
@@ -357,7 +471,7 @@ async function processNext(projectPath: string): Promise<void> {
next.error = "LLM not configured — set API key in Settings"
processing = false
await saveQueue(pp)
- processNext(pp)
+ processNext(projectId)
return
}
@@ -365,16 +479,28 @@ async function processNext(projectPath: string): Promise<void> {
? normalizePath(next.sourcePath)
: `${pp}/${next.sourcePath}`
- console.log(`[Ingest Queue] Processing: ${next.sourcePath} (${queue.filter((t) => t.status === "pending").length} remaining)`)
+ console.log(`[Ingest Queue] Processing: ${next.sourcePath} (${queue.filter((t) => t.projectId === projectId && t.status === "pending").length} remaining)`)
- // Create abort controller for this task
currentAbortController = new AbortController()
lastWrittenFiles = []
try {
const writtenFiles = await autoIngest(pp, fullSourcePath, llmConfig, currentAbortController.signal, next.folderContext)
+ // Stale-context guard: project switched during the long LLM call.
+ // Bail without mutating queue or writing to disk — pauseQueue has
+ // already persisted the correct state to the old project's file,
+ // and the new project's queue must not be touched by this orphan.
+ if (currentProjectId !== projectId) return
lastWrittenFiles = writtenFiles
+ // Safety net: autoIngest resolving with zero files means nothing
+ // was really ingested (e.g. abort during webview refresh where the
+ // historical `return []` error path masqueraded as success). Treat
+ // as failure so the task stays in the queue and retries.
+ if (writtenFiles.length === 0) {
+ throw new Error("Ingest produced no output files")
+ }
+
// Success: remove from queue
currentAbortController = null
lastWrittenFiles = []
@@ -384,6 +510,7 @@ async function processNext(projectPath: string): Promise<void> {
console.log(`[Ingest Queue] Done: ${next.sourcePath}`)
} catch (err) {
+ if (currentProjectId !== projectId) return
currentAbortController = null
const message = err instanceof Error ? err.message : String(err)
next.retryCount++
@@ -401,5 +528,5 @@ async function processNext(projectPath: string): Promise<void> {
}
processing = false
- processNext(pp)
+ processNext(projectId)
}
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index d9729bd4..db5eac1c 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -93,8 +93,12 @@ export async function autoIngest(
{ temperature: 0.1 },
)
- if (useActivityStore.getState().items.find((i) => i.id === activityId)?.status === "error") {
- return []
+ // A silent `return []` here would look like success to the queue
+ // runner and cause the task to be filter()'d out. Throw instead so
+ // processNext's catch-block path (retry / mark failed) engages.
+ const analysisActivity = useActivityStore.getState().items.find((i) => i.id === activityId)
+ if (analysisActivity?.status === "error") {
+ throw new Error(analysisActivity.detail || "Analysis stream failed")
}
// ── Step 2: Generation ────────────────────────────────────────
@@ -143,8 +147,9 @@ export async function autoIngest(
{ temperature: 0.1 },
)
- if (useActivityStore.getState().items.find((i) => i.id === activityId)?.status === "error") {
- return []
+ const generationActivity = useActivityStore.getState().items.find((i) => i.id === activityId)
+ if (generationActivity?.status === "error") {
+ throw new Error(generationActivity.detail || "Generation stream failed")
}
// ── Step 3: Write files ───────────────────────────────────────
@@ -157,7 +162,13 @@ export async function autoIngest(
const sourceSummaryFullPath = `${pp}/${sourceSummaryPath}`
const hasSourceSummary = writtenPaths.some((p) => p.startsWith("wiki/sources/"))
- if (!hasSourceSummary) {
+ // If the signal was aborted (e.g. user switched projects / cancelled),
+ // skip the fallback summary write — the LLM streams returned empty
+ // via the abort fast-path (onDone), and writing a stub file into the
+ // old project's wiki would both be noise and mask the error.
+ // Returning no files lets processNext's length-0 safety net mark the
+ // task for retry rather than "success".
+ if (!hasSourceSummary && !signal?.aborted) {
const date = new Date().toISOString().slice(0, 10)
const fallbackContent = [
"---",
diff --git a/src/lib/project-identity.ts b/src/lib/project-identity.ts
new file mode 100644
index 00000000..43e129b0
--- /dev/null
+++ b/src/lib/project-identity.ts
@@ -0,0 +1,131 @@
+/**
+ * Project identity: stable UUID per project + global registry mapping
+ * `UUID → current filesystem path`.
+ *
+ * Why: absolute paths are unstable (users move / rename project folders).
+ * Queue tasks reference projects by UUID and look up the current path
+ * via the registry at run time, so a moved folder doesn't orphan tasks.
+ *
+ * Storage:
+ * - Per-project identity: `{project}/.llm-wiki/project.json`
+ * `{ "id": "<uuid>", "createdAt": <ms> }`
+ * - Global registry: Tauri plugin-store `app-state.json` key `projectRegistry`
+ * `{ [id]: { id, path, name, lastOpened } }`
+ */
+
+import { load } from "@tauri-apps/plugin-store"
+import { readFile, writeFile } from "@/commands/fs"
+import { normalizePath } from "@/lib/path-utils"
+
+const STORE_NAME = "app-state.json"
+const REGISTRY_KEY = "projectRegistry"
+
+export interface ProjectIdentity {
+ id: string
+ createdAt: number
+}
+
+export interface ProjectRegistryEntry {
+ id: string
+ path: string // latest known filesystem path (normalized forward slashes)
+ name: string
+ lastOpened: number
+}
+
+export type ProjectRegistry = Record<string, ProjectRegistryEntry>
+
+// ── Per-project identity (reads/creates `.llm-wiki/project.json`) ─────────
+
+function identityPath(projectPath: string): string {
+ return `${normalizePath(projectPath)}/.llm-wiki/project.json`
+}
+
+/**
+ * Return the project's stable UUID. Generates + writes one on first call
+ * for a project that doesn't have `.llm-wiki/project.json` yet.
+ */
+export async function ensureProjectId(projectPath: string): Promise<string> {
+ const path = identityPath(projectPath)
+ try {
+ const raw = await readFile(path)
+ const parsed = JSON.parse(raw) as ProjectIdentity
+ if (parsed?.id && typeof parsed.id === "string") {
+ return parsed.id
+ }
+ } catch {
+ // missing or corrupt — fall through to create
+ }
+ const identity: ProjectIdentity = {
+ id: crypto.randomUUID(),
+ createdAt: Date.now(),
+ }
+ try {
+ await writeFile(path, JSON.stringify(identity, null, 2))
+ } catch (err) {
+ console.warn("[project-identity] failed to write identity file:", err)
+ }
+ return identity.id
+}
+
+// ── Global registry (Tauri plugin-store) ──────────────────────────────────
+
+async function getStore() {
+ return load(STORE_NAME, { autoSave: true })
+}
+
+export async function loadRegistry(): Promise<ProjectRegistry> {
+ try {
+ const store = await getStore()
+ const registry = await store.get<ProjectRegistry>(REGISTRY_KEY)
+ return registry ?? {}
+ } catch {
+ return {}
+ }
+}
+
+async function saveRegistry(registry: ProjectRegistry): Promise<void> {
+ const store = await getStore()
+ await store.set(REGISTRY_KEY, registry)
+}
+
+/**
+ * Create or update the registry entry for this project. Call on open /
+ * create / switch so the path always reflects the latest known location.
+ */
+export async function upsertProjectInfo(
+ id: string,
+ path: string,
+ name: string,
+): Promise<void> {
+ const registry = await loadRegistry()
+ registry[id] = {
+ id,
+ path: normalizePath(path),
+ name,
+ lastOpened: Date.now(),
+ }
+ await saveRegistry(registry)
+}
+
+/**
+ * Look up the current filesystem path by UUID. Returns null if the
+ * project isn't in the registry (e.g. was deleted or never opened).
+ */
+export async function getProjectPathById(id: string): Promise<string | null> {
+ const registry = await loadRegistry()
+ return registry[id]?.path ?? null
+}
+
+/**
+ * Reverse lookup: given a path, find the UUID of a known project at
+ * that exact location. Used by the clip watcher to translate
+ * clip-server-supplied paths back to stable project ids.
+ */
+export async function getProjectIdByPath(path: string): Promise<string | null> {
+ const normalized = normalizePath(path)
+ const registry = await loadRegistry()
+ for (const entry of Object.values(registry)) {
+ if (entry.path === normalized) return entry.id
+ }
+ return null
+}
diff --git a/src/lib/reset-project-state.test.ts b/src/lib/reset-project-state.test.ts
index e70a4e9a..f02b52fb 100644
--- a/src/lib/reset-project-state.test.ts
+++ b/src/lib/reset-project-state.test.ts
@@ -4,7 +4,7 @@ import { useChatStore } from "@/stores/chat-store"
import { useReviewStore } from "@/stores/review-store"
import { useActivityStore } from "@/stores/activity-store"
import { useResearchStore } from "@/stores/research-store"
-import { getQueue, clearQueueState } from "./ingest-queue"
+import { getQueue, pauseQueue } from "./ingest-queue"
// Dynamic-import mocks: resetProjectState uses `import("@/lib/ingest-queue")`
// and `import("@/lib/graph-relevance")` at runtime. vi.mock hoists these
@@ -13,7 +13,7 @@ vi.mock("./ingest-queue", async () => {
const actual = await vi.importActual<typeof import("./ingest-queue")>("./ingest-queue")
return {
...actual,
- clearQueueState: vi.fn(),
+ pauseQueue: vi.fn(async () => {}),
}
})
@@ -23,11 +23,12 @@ vi.mock("./graph-relevance", () => ({
import { clearGraphCache } from "./graph-relevance"
-const mockClearQueueState = vi.mocked(clearQueueState)
+const mockPauseQueue = vi.mocked(pauseQueue)
const mockClearGraphCache = vi.mocked(clearGraphCache)
beforeEach(() => {
- mockClearQueueState.mockReset()
+ mockPauseQueue.mockReset()
+ mockPauseQueue.mockImplementation(async () => {})
mockClearGraphCache.mockReset()
})
@@ -117,9 +118,9 @@ describe("resetProjectState — Zustand stores", () => {
})
describe("resetProjectState — module-level caches are awaited", () => {
- it("calls clearQueueState before the returned promise resolves", async () => {
+ it("calls pauseQueue before the returned promise resolves", async () => {
await resetProjectState()
- expect(mockClearQueueState).toHaveBeenCalledOnce()
+ expect(mockPauseQueue).toHaveBeenCalledOnce()
})
it("calls clearGraphCache before the returned promise resolves", async () => {
@@ -131,12 +132,12 @@ describe("resetProjectState — module-level caches are awaited", () => {
// This is the regression guard against fire-and-forget resets.
// By the time the outer await returns, BOTH clears must be done.
await resetProjectState()
- expect(mockClearQueueState).toHaveBeenCalledOnce()
+ expect(mockPauseQueue).toHaveBeenCalledOnce()
expect(mockClearGraphCache).toHaveBeenCalledOnce()
})
- it("does not throw when clearQueueState itself throws — logs and continues", async () => {
- mockClearQueueState.mockImplementationOnce(() => {
+ it("does not throw when pauseQueue itself throws — logs and continues", async () => {
+ mockPauseQueue.mockImplementationOnce(async () => {
throw new Error("boom")
})
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
diff --git a/src/lib/reset-project-state.ts b/src/lib/reset-project-state.ts
index 49a93b9f..a20b159a 100644
--- a/src/lib/reset-project-state.ts
+++ b/src/lib/reset-project-state.ts
@@ -47,9 +47,13 @@ export async function resetProjectState(): Promise<void> {
if (queueMod.status === "fulfilled") {
try {
- queueMod.value.clearQueueState()
+ // pauseQueue flushes the active project's state to disk (reverting
+ // any processing task to pending) before clearing in-memory state.
+ // Awaiting is required — the disk write must complete before the
+ // new project's restoreQueue reads its own file.
+ await queueMod.value.pauseQueue()
} catch (err) {
- console.warn("[Reset Project State] clearQueueState failed:", err)
+ console.warn("[Reset Project State] pauseQueue failed:", err)
}
} else {
console.warn("[Reset Project State] Failed to load ingest-queue:", queueMod.reason)
diff --git a/src/types/wiki.ts b/src/types/wiki.ts
index 9ecbf1f2..3760b10f 100644
--- a/src/types/wiki.ts
+++ b/src/types/wiki.ts
@@ -1,4 +1,7 @@
export interface WikiProject {
+ /** Stable UUID, persisted inside the project at .llm-wiki/project.json.
+ * Survives the user moving or renaming the project folder. */
+ id: string
name: string
path: string
}