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: complete overview and review lifecycle

nash_suf64967398802
diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rs
index 91faba54..50e54067 100644
--- a/src-tauri/src/api_server.rs
+++ b/src-tauri/src/api_server.rs
@@ -346,7 +346,7 @@ fn handle_request(
if !is_authorized(app, query, headers) {
return err(401, "Unauthorized");
}
- if !matches!(method, &Method::Get | &Method::Post | &Method::Patch) {
+ if !matches!(method, &Method::Get | &Method::Post | &Method::Patch | &Method::Delete) {
return err(405, "Method not allowed");
}
@@ -369,6 +369,9 @@ fn handle_request(
(&Method::Patch, ["projects", project_id, "reviews", review_id]) => {
handle_patch_review(app, project_id, review_id, body)
}
+ (&Method::Delete, ["projects", project_id, "reviews", review_id]) => {
+ handle_delete_review(app, project_id, review_id)
+ }
(&Method::Post, ["projects", project_id, "search"]) => handle_search(app, project_id, body),
(&Method::Get, ["projects", project_id, "graph"]) => handle_graph(app, project_id, query),
(&Method::Post, ["projects", project_id, "sources", "rescan"]) => {
@@ -1601,11 +1604,47 @@ fn handle_patch_review(
#[serde(rename_all = "camelCase")]
struct BulkResolveRequest {
/// Review item ids to resolve. Required, non-empty.
+ #[serde(alias = "reviewIds")]
ids: Vec<String>,
/// Optional label applied to every resolved item.
action: Option<String>,
}
+fn handle_delete_review(app: &AppHandle, project_id: &str, review_id: &str) -> ApiResponse {
+ let project = match resolve_project(app, project_id) {
+ Ok(project) => project,
+ Err(e) => return err(404, e),
+ };
+ match delete_review_item(&project.path, review_id) {
+ Ok(true) => ok(json!({
+ "ok": true,
+ "projectId": project.id,
+ "reviewId": review_id,
+ "deleted": true,
+ })),
+ Ok(false) => err(404, format!("Review item '{review_id}' not found")),
+ Err(e) => err(500, e),
+ }
+}
+
+fn delete_review_item(project_path: &str, review_id: &str) -> Result<bool, String> {
+ let path = Path::new(project_path).join(".llm-wiki/review.json");
+ let mut parsed = match read_raw_review_array(&path)? {
+ Some(parsed) => parsed,
+ None => return Ok(false),
+ };
+ let items = parsed
+ .as_array_mut()
+ .ok_or_else(|| "Invalid review state JSON: expected an array".to_string())?;
+ let original_len = items.len();
+ items.retain(|item| !review_id_matches(item, review_id));
+ if items.len() == original_len {
+ return Ok(false);
+ }
+ write_raw_review_array(&path, &parsed)?;
+ Ok(true)
+}
+
/// `POST /projects/{id}/reviews/resolve` — bulk-resolve many review
/// items in one request. Body `{ ids, action? }`. Partial success is
/// normal, so this returns 200 with `{ resolved, notFound, count }`
@@ -3530,6 +3569,41 @@ mod tests {
let _ = fs::remove_dir_all(root);
}
+ #[test]
+ fn delete_review_item_removes_match_and_preserves_other_fields() {
+ let root = test_project_dir();
+ write_reviews(
+ &root,
+ json!([
+ { "id": "r1", "resolved": false, "internalSecret": "remove" },
+ { "id": "r2", "resolved": false, "internalSecret": "keep" }
+ ]),
+ );
+
+ assert!(delete_review_item(root.to_str().unwrap(), "r1").unwrap());
+ let parsed = read_reviews(&root);
+ let items = parsed.as_array().unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].get("id").and_then(Value::as_str), Some("r2"));
+ assert_eq!(
+ items[0].get("internalSecret").and_then(Value::as_str),
+ Some("keep")
+ );
+ assert!(!delete_review_item(root.to_str().unwrap(), "missing").unwrap());
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn bulk_resolve_request_accepts_documented_review_ids_alias() {
+ let request: BulkResolveRequest = serde_json::from_value(json!({
+ "reviewIds": ["r1", "r2"],
+ "action": "API"
+ }))
+ .unwrap();
+ assert_eq!(request.ids, vec!["r1", "r2"]);
+ assert_eq!(request.action.as_deref(), Some("API"));
+ }
+
#[test]
fn resolve_review_items_bulk_resolves_matching_and_reports_not_found() {
let root = test_project_dir();
diff --git a/src/App.tsx b/src/App.tsx
index 84446998..54837248 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -455,8 +455,11 @@ function App() {
projectLlmOverride,
llmState.customLlmPresets,
))
- const projectOutputLang = await loadOutputLanguage(proj.id)
- useWikiStore.getState().setOutputLanguage(projectOutputLang ?? "auto")
+ const [projectOutputLang, globalOutputLang] = await Promise.all([
+ loadOutputLanguage(proj.id),
+ loadOutputLanguage(),
+ ])
+ useWikiStore.getState().setOutputLanguage(projectOutputLang ?? globalOutputLang ?? "auto")
setSelectedFile(null)
setFileTree([])
setActiveView("wiki")
diff --git a/src/lib/ingest.prompt.test.ts b/src/lib/ingest.prompt.test.ts
index ce6cb32e..0e66d858 100644
--- a/src/lib/ingest.prompt.test.ts
+++ b/src/lib/ingest.prompt.test.ts
@@ -12,6 +12,7 @@ import {
computeIngestSourceBudget,
formatIngestWarningLogEntry,
splitSourceIntoSemanticChunks,
+ updateBoundedOverviewRecentSection,
} from "./ingest"
import { useWikiStore } from "@/stores/wiki-store"
@@ -357,3 +358,21 @@ describe("long-source ingest planning", () => {
expect(chunks[1].main.startsWith(chunks[0].main.slice(-200))).toBe(false)
})
})
+
+describe("overview maintenance", () => {
+ it("adds a bounded managed section without replacing user content", () => {
+ const original = "# Overview\n\nUser-maintained summary.\n"
+ const updated = updateBoundedOverviewRecentSection(original, ["- [[entities/a]] — A"])
+ expect(updated).toContain("User-maintained summary.")
+ expect(updated).toContain("<!-- llm-wiki:recent-start -->")
+ expect(updated).toContain("- [[entities/a]] — A")
+ })
+
+ it("updates the managed section idempotently and limits it to 50 entries", () => {
+ const additions = Array.from({ length: 60 }, (_, index) => `- [[p-${index}]] — P ${index}`)
+ const once = updateBoundedOverviewRecentSection("# Overview\n", additions)
+ const twice = updateBoundedOverviewRecentSection(once, [additions[0]])
+ expect(twice).toBe(once)
+ expect(twice.match(/^- \[\[/gm)).toHaveLength(50)
+ })
+})
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index c27b7cc4..25a3952c 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -1389,9 +1389,13 @@ async function autoIngestImpl(
writtenPaths.push("wiki/index.md")
onFileWritten?.("wiki/index.md")
}
+ if (await updateWikiOverviewDeterministically(pp, writtenPaths)) {
+ writtenPaths.push("wiki/overview.md")
+ onFileWritten?.("wiki/overview.md")
+ }
} catch (err) {
writeWarnings.push(
- `Deterministic index update failed: ${err instanceof Error ? err.message : String(err)}`,
+ `Deterministic aggregate update failed: ${err instanceof Error ? err.message : String(err)}`,
)
}
@@ -1727,6 +1731,72 @@ async function updateWikiIndexDeterministically(
return true
}
+const OVERVIEW_RECENT_START = "<!-- llm-wiki:recent-start -->"
+const OVERVIEW_RECENT_END = "<!-- llm-wiki:recent-end -->"
+
+async function updateWikiOverviewDeterministically(
+ projectPath: string,
+ writtenPaths: string[],
+): Promise<boolean> {
+ const candidates = Array.from(new Set(writtenPaths.map(normalizePath))).filter((path) =>
+ path.startsWith("wiki/")
+ && path.endsWith(".md")
+ && !AGGREGATE_WIKI_PATHS.includes(path as (typeof AGGREGATE_WIKI_PATHS)[number]),
+ )
+ if (candidates.length === 0) return false
+
+ const overviewPath = `${projectPath}/wiki/overview.md`
+ const overview = await readFile(overviewPath).catch(() => [
+ "---",
+ "type: overview",
+ "title: Project Overview",
+ "tags: []",
+ "related: []",
+ "---",
+ "",
+ "# Overview",
+ "",
+ ].join("\n"))
+ const additions: string[] = []
+ for (const path of candidates) {
+ const target = path.replace(/^wiki\//, "").replace(/\.md$/i, "")
+ const content = await readFile(`${projectPath}/${path}`).catch(() => "")
+ const parsed = parseFrontmatter(content)
+ const title = typeof parsed.frontmatter?.title === "string"
+ ? parsed.frontmatter.title.trim()
+ : getFileName(path).replace(/\.md$/i, "")
+ additions.push(`- [[${target}]] — ${title}`)
+ }
+ const updated = updateBoundedOverviewRecentSection(overview, additions)
+ if (updated === overview) return false
+ await writeFile(overviewPath, updated)
+ return true
+}
+
+export function updateBoundedOverviewRecentSection(
+ overview: string,
+ additions: string[],
+): string {
+ const start = overview.indexOf(OVERVIEW_RECENT_START)
+ const end = overview.indexOf(OVERVIEW_RECENT_END)
+ const existing = start >= 0 && end > start
+ ? overview.slice(start + OVERVIEW_RECENT_START.length, end)
+ .split("\n")
+ .filter((line) => /^-\s+/.test(line))
+ : []
+ const recent = Array.from(new Set([...additions, ...existing])).slice(0, 50)
+ const block = [
+ OVERVIEW_RECENT_START,
+ "## Recently Updated",
+ ...recent,
+ OVERVIEW_RECENT_END,
+ ].join("\n")
+ if (start >= 0 && end > start) {
+ return `${overview.slice(0, start)}${block}${overview.slice(end + OVERVIEW_RECENT_END.length)}`
+ }
+ return `${overview.trimEnd()}\n\n${block}\n`
+}
+
function normalizeIndexTarget(target: string): string {
return normalizePath(target)
.replace(/^wiki\//i, "")
diff --git a/src/lib/wiki-page-delete.test.ts b/src/lib/wiki-page-delete.test.ts
index a7735371..295446c5 100644
--- a/src/lib/wiki-page-delete.test.ts
+++ b/src/lib/wiki-page-delete.test.ts
@@ -11,6 +11,8 @@ const mockRemovePageEmbedding = vi.fn<(projectPath: string, slug: string) => Pro
const mockReadFile = vi.fn<(path: string) => Promise<string>>()
const mockWriteFile = vi.fn<(path: string, content: string) => Promise<void>>()
const mockListDirectory = vi.fn<(path: string) => Promise<unknown>>()
+const mockLoadReviewItems = vi.fn()
+const mockSaveReviewItems = vi.fn()
vi.mock("@/commands/fs", () => ({
deleteFile: (path: string) => mockDeleteFile(path),
@@ -25,6 +27,11 @@ vi.mock("@/lib/embedding", async (importOriginal) => ({
mockRemovePageEmbedding(projectPath, slug),
}))
+vi.mock("@/lib/persist", () => ({
+ loadReviewItems: (...args: unknown[]) => mockLoadReviewItems(...args),
+ saveReviewItems: (...args: unknown[]) => mockSaveReviewItems(...args),
+}))
+
import { cascadeDeleteWikiPage, cascadeDeleteWikiPagesWithRefs } from "./wiki-page-delete"
import type { FileNode } from "@/types/wiki"
@@ -34,10 +41,14 @@ beforeEach(() => {
mockReadFile.mockReset()
mockWriteFile.mockReset()
mockListDirectory.mockReset()
+ mockLoadReviewItems.mockReset()
+ mockSaveReviewItems.mockReset()
// Default: both succeed silently.
mockDeleteFile.mockResolvedValue(undefined)
mockRemovePageEmbedding.mockResolvedValue(undefined)
mockWriteFile.mockResolvedValue(undefined)
+ mockLoadReviewItems.mockResolvedValue([])
+ mockSaveReviewItems.mockResolvedValue(undefined)
})
describe("cascadeDeleteWikiPage", () => {
@@ -479,4 +490,25 @@ describe("cascadeDeleteWikiPagesWithRefs", () => {
expect(bobWrite[1]).not.toContain("[[alice-chen]]")
expect(bobWrite[1]).not.toContain("[[alice-chen-1]]")
})
+
+ it("removes deleted affected pages and drops reviews that become orphaned", async () => {
+ const target = `${PROJECT}/wiki/entities/a.md`
+ mockReadFile.mockImplementation(async (path: string) => {
+ if (path === target) return "---\ntitle: A\n---\n"
+ throw new Error(`unexpected read ${path}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([])
+ mockLoadReviewItems.mockResolvedValueOnce([
+ { id: "orphan", affectedPages: ["entities/a.md"] },
+ { id: "survivor", affectedPages: ["entities/a.md", "entities/b.md"] },
+ { id: "general" },
+ ])
+
+ await cascadeDeleteWikiPagesWithRefs(PROJECT, [target])
+
+ expect(mockSaveReviewItems).toHaveBeenCalledWith(PROJECT, [
+ { id: "survivor", affectedPages: ["entities/b.md"] },
+ { id: "general" },
+ ])
+ })
})
diff --git a/src/lib/wiki-page-delete.ts b/src/lib/wiki-page-delete.ts
index 98f829ed..d2244f94 100644
--- a/src/lib/wiki-page-delete.ts
+++ b/src/lib/wiki-page-delete.ts
@@ -35,6 +35,8 @@ import {
writeFrontmatterArray,
} from "@/lib/sources-merge"
import type { FileNode } from "@/types/wiki"
+import { loadReviewItems, saveReviewItems } from "@/lib/persist"
+import { useReviewStore } from "@/stores/review-store"
/**
* Detect whether a wiki page lives under `wiki/sources/`. We treat
@@ -128,6 +130,38 @@ export interface CascadeDeleteResult {
rewrittenFiles: number
}
+async function pruneDeletedPagesFromReviews(
+ projectPath: string,
+ deletedPaths: readonly string[],
+): Promise<void> {
+ const deleted = new Set(deletedPaths.map((path) => normalizePath(path).toLowerCase()))
+ const toAbsolute = (path: string) => {
+ const normalized = normalizePath(path)
+ if (normalized.startsWith(`${projectPath}/`)) return normalized.toLowerCase()
+ const relative = normalized.replace(/^wiki\//i, "")
+ return `${projectPath}/wiki/${relative}`.toLowerCase()
+ }
+ try {
+ const reviews = await loadReviewItems(projectPath)
+ let changed = false
+ const remaining = reviews.flatMap((item) => {
+ if (!item.affectedPages?.length) return [item]
+ const affectedPages = item.affectedPages.filter((path) => !deleted.has(toAbsolute(path)))
+ if (affectedPages.length === item.affectedPages.length) return [item]
+ changed = true
+ return affectedPages.length > 0 ? [{ ...item, affectedPages }] : []
+ })
+ if (!changed) return
+ await saveReviewItems(projectPath, remaining)
+ const activeProject = (await import("@/stores/wiki-store")).useWikiStore.getState().project
+ if (activeProject && normalizePath(activeProject.path) === projectPath) {
+ useReviewStore.getState().setItems(remaining)
+ }
+ } catch (err) {
+ console.warn("[wiki-delete] failed to prune orphaned reviews:", err)
+ }
+}
+
/**
* Delete one or more wiki pages and clean up every reference to them
* in the rest of the wiki: file delete, embedding drop, media-dir
@@ -241,5 +275,7 @@ export async function cascadeDeleteWikiPagesWithRefs(
}
}
+ await pruneDeletedPagesFromReviews(pp, result.deletedPaths)
+
return result
}