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: prevent duplicate image extraction
nash_sue917373213ed
diff --git a/src-tauri/src/commands/claude_cli.rs b/src-tauri/src/commands/claude_cli.rsindex f89790fa..3a4de53c 100644--- a/src-tauri/src/commands/claude_cli.rs+++ b/src-tauri/src/commands/claude_cli.rs@@ -50,7 +50,67 @@ pub struct DetectResult {pub struct ClaudeMessage {/// "system" | "user" | "assistant"role: String,- content: String,+ content: ClaudeContent,+}++#[derive(Clone, Deserialize)]+#[serde(untagged)]+enum ClaudeContent {+ Text(String),+ Blocks(Vec<ClaudeContentBlock>),+}++#[derive(Clone, Deserialize)]+#[serde(tag = "type")]+enum ClaudeContentBlock {+ #[serde(rename = "text")]+ Text { text: String },+ #[serde(rename = "image")]+ Image {+ #[serde(rename = "mediaType")]+ media_type: String,+ #[serde(rename = "dataBase64")]+ data_base64: String,+ },+}++fn claude_content_text_only(content: &ClaudeContent) -> String {+ match content {+ ClaudeContent::Text(text) => text.clone(),+ ClaudeContent::Blocks(blocks) => blocks+ .iter()+ .filter_map(|block| match block {+ ClaudeContentBlock::Text { text } => Some(text.as_str()),+ ClaudeContentBlock::Image { .. } => None,+ })+ .collect::<Vec<_>>()+ .join(""),+ }+}++fn claude_content_blocks(content: &ClaudeContent) -> Vec<serde_json::Value> {+ match content {+ ClaudeContent::Text(text) => vec![serde_json::json!({ "type": "text", "text": text })],+ ClaudeContent::Blocks(blocks) => blocks+ .iter()+ .map(|block| match block {+ ClaudeContentBlock::Text { text } => {+ serde_json::json!({ "type": "text", "text": text })+ }+ ClaudeContentBlock::Image {+ media_type,+ data_base64,+ } => serde_json::json!({+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": media_type,+ "data": data_base64,+ },+ }),+ })+ .collect(),+ }}fn find_claude_command() -> Result<PathBuf, String> {@@ -159,7 +219,7 @@ pub async fn claude_cli_spawn(let system_preamble: String = messages.iter().filter(|m| m.role == "system")- .map(|m| m.content.clone())+ .map(|m| claude_content_text_only(&m.content)).collect::<Vec<_>>().join("\n\n");@@ -174,13 +234,16 @@ pub async fn claude_cli_spawn(// Synthesize turns with the preamble merged into the first user turn.let mut first_user_seen = false;- let turns: Vec<(String, String)> = conversation+ let turns: Vec<(String, Vec<serde_json::Value>)> = conversation.iter().map(|m| {let role = m.role.clone();- let mut content = m.content.clone();+ let mut content = claude_content_blocks(&m.content);if !first_user_seen && role == "user" && !system_preamble.is_empty() {- content = format!("{system_preamble}\n\n{content}");+ content.insert(+ 0,+ serde_json::json!({ "type": "text", "text": format!("{system_preamble}\n\n") }),+ );first_user_seen = true;}(role, content)@@ -235,7 +298,7 @@ pub async fn claude_cli_spawn("type": role,"message": {"role": role,- "content": [{ "type": "text", "text": content }],+ "content": content,}});let line = format!("{}\n", event);@@ -339,3 +402,45 @@ pub async fn claude_cli_kill(}Ok(())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn claude_content_blocks_maps_frontend_image_blocks_to_anthropic_shape() {+ let content: ClaudeContent = serde_json::from_value(serde_json::json!([+ { "type": "text", "text": "describe this" },+ { "type": "image", "mediaType": "image/png", "dataBase64": "abc123" }+ ]))+ .expect("content block payload should deserialize");++ let blocks = claude_content_blocks(&content);++ assert_eq!(+ blocks,+ vec![+ serde_json::json!({ "type": "text", "text": "describe this" }),+ serde_json::json!({+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/png",+ "data": "abc123",+ },+ }),+ ]+ );+ }++ #[test]+ fn system_text_drops_images_before_inlining_preamble() {+ let content: ClaudeContent = serde_json::from_value(serde_json::json!([+ { "type": "text", "text": "system rule" },+ { "type": "image", "mediaType": "image/png", "dataBase64": "abc123" }+ ]))+ .expect("content block payload should deserialize");++ assert_eq!(claude_content_text_only(&content), "system rule");+ }+}diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex e93fedab..2dff8d9a 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -23,7 +23,7 @@ const MEDIA_EXTS: &[&str] = &[const LEGACY_DOC_EXTS: &[&str] = &["ppt", "pages", "numbers", "key", "epub"];#[tauri::command]-pub async fn read_file(path: String) -> Result<String, String> {+pub async fn read_file(path: String, extract_images: Option<bool>) -> Result<String, String> {// `spawn_blocking` is REQUIRED, not a perf nicety. The body does// synchronous PDF/Office text extraction (pdfium FFI, calamine,// zip + image decode) that can take 10s+ on big files. Running@@ -46,8 +46,10 @@ pub async fn read_file(path: String) -> Result<String, String> {return Ok(cached);}+ let include_images = extract_images.unwrap_or(true);+match ext.as_str() {- "pdf" => extract_pdf_text(&path),+ "pdf" => extract_pdf_text(&path, include_images),e if OFFICE_EXTS.contains(&e) => extract_office_text(&path, e),e if IMAGE_EXTS.contains(&e) => {let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);@@ -98,7 +100,7 @@ pub async fn preprocess_file(path: String) -> Result<String, String> {.to_lowercase();let text = match ext.as_str() {- "pdf" => extract_pdf_text(&path)?,+ "pdf" => extract_pdf_text(&path, false)?,e if OFFICE_EXTS.contains(&e) => extract_office_text(&path, e)?,_ => return Ok("no preprocessing needed".to_string()),};@@ -317,69 +319,51 @@ pub(crate) fn pdfium() -> Result<&'static pdfium_render::prelude::Pdfium, String.map_err(|e| e.clone())}-/// Extract a PDF as markdown — text + per-page image references-/// when the file lives under a project's `raw/sources/` (the-/// layout the import pipeline produces). Falls back to text-only-/// when the PDF is opened from anywhere else.-///-/// Layout heuristic: a PDF at `<project>/raw/sources/<name>.pdf`-/// implies project root = `<project>` and image dest =-/// `<project>/wiki/media/<name>/`. We use absolute filesystem paths-/// in the emitted `` references so the markdown previews-/// (raw-source view AND wiki-summary view) both render via-/// `convertFileSrc` without anyone having to know which directory-/// they're rendering from.+/// Extract a PDF as markdown. When `include_images` is true and the PDF+/// is opened directly from `<project>/raw/sources`, this also writes+/// preview images to `<project>/wiki/media/<file-stem>/` and emits image+/// markdown. Ingest passes `include_images=false` and owns image+/// extraction through the canonical source-identity slug, preventing a+/// duplicate `<file-stem>` media folder for nested sources.////// Lock: delegates to `extract_pdf_markdown`, which acquires the/// pdfium lock internally. We must NOT take it here too —/// `std::sync::Mutex` is non-reentrant.-fn extract_pdf_text(path: &str) -> Result<String, String> {+fn extract_pdf_text(path: &str, include_images: bool) -> Result<String, String> {use crate::commands::extract_images::{extract_pdf_markdown, ExtractOptions};- let p = Path::new(path);- let parent = p.parent();- let stem = p- .file_stem()- .and_then(|s| s.to_str())- .unwrap_or("")- .to_string();-- // The path-component check uses `ends_with` on `Path` which- // matches the LAST component (not a string-suffix check), so- // `/foo/raw/sources/bar.pdf` correctly identifies as under- // `raw/sources/` while `/foo/braw/source-thing/bar.pdf` does- // not.- let parent_is_sources = parent.map(|d| d.ends_with("sources")).unwrap_or(false);- let raw_dir = parent.and_then(|d| d.parent());- let raw_is_raw = raw_dir.map(|d| d.ends_with("raw")).unwrap_or(false);- let project_root = if parent_is_sources && raw_is_raw {- raw_dir.and_then(|d| d.parent())- } else {- None- };+ if include_images {+ let p = Path::new(path);+ let parent = p.parent();+ let stem = p+ .file_stem()+ .and_then(|s| s.to_str())+ .unwrap_or("")+ .to_string();- if let Some(root) = project_root {- if !stem.is_empty() {- let media_dir = root.join("wiki").join("media").join(&stem);- // Forward-slash absolute path so we don't ship `\` into- // markdown that the JS-side resolver would then have to- // re-normalize. The resolver does handle backslashes,- // but emitting clean URLs in the first place avoids- // surprises in cache files we save to disk.- let url_prefix = media_dir.to_string_lossy().replace('\\', "/");- return extract_pdf_markdown(- path,- Some(&media_dir),- &url_prefix,- &ExtractOptions::default(),- );+ let parent_is_sources = parent.map(|d| d.ends_with("sources")).unwrap_or(false);+ let raw_dir = parent.and_then(|d| d.parent());+ let raw_is_raw = raw_dir.map(|d| d.ends_with("raw")).unwrap_or(false);+ let project_root = if parent_is_sources && raw_is_raw {+ raw_dir.and_then(|d| d.parent())+ } else {+ None+ };++ if let Some(root) = project_root {+ if !stem.is_empty() {+ let media_dir = root.join("wiki").join("media").join(&stem);+ let url_prefix = media_dir.to_string_lossy().replace('\\', "/");+ return extract_pdf_markdown(+ path,+ Some(&media_dir),+ &url_prefix,+ &ExtractOptions::default(),+ );+ }}}- // PDFs not under <project>/raw/sources/ — text-only fallback.- // Skip the image side of the extraction entirely (no media- // destination → extract_pdf_markdown only writes text + page- // headers, no pdfium image-object enumeration).extract_pdf_markdown(path, None, "", &ExtractOptions::default())}@@ -1568,7 +1552,7 @@ mod tests {for (name, bytes) in payloads {let path = tmp_pdf_with_bytes(bytes);- let result = read_file(path.clone()).await;+ let result = read_file(path.clone(), None).await;let _ = fs::remove_file(&path);eprintln!("[{name}] => {:?}",@@ -1583,7 +1567,11 @@ mod tests {/// through read_file's guarded path.#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn read_file_returns_err_on_missing_file_instead_of_panicking() {- let result = read_file("/nonexistent/path/that/does/not/exist.pdf".to_string()).await;+ let result = read_file(+ "/nonexistent/path/that/does/not/exist.pdf".to_string(),+ None,+ )+ .await;assert!(result.is_err() || result.is_ok()); // must at least return}@@ -1649,7 +1637,7 @@ mod tests {// Call extract_pdf_text directly (not read_file) so we bypass// the .cache sibling dir and always exercise the parser.let path_str = path.to_string_lossy().to_string();- let result = std::panic::catch_unwind(|| extract_pdf_text(&path_str));+ let result = std::panic::catch_unwind(|| extract_pdf_text(&path_str, true));match result {Ok(Ok(text)) => {ok += 1;diff --git a/src/commands/fs.ts b/src/commands/fs.tsindex 1a9a1432..91170f91 100644--- a/src/commands/fs.ts+++ b/src/commands/fs.ts@@ -8,8 +8,14 @@ interface RawProject {path: string}-export async function readFile(path: string): Promise<string> {- return invoke<string>("read_file", { path })+export async function readFile(+ path: string,+ options?: { extractImages?: boolean },+): Promise<string> {+ return invoke<string>("read_file", {+ path,+ extractImages: options?.extractImages,+ })}export async function writeFile(path: string, contents: string): Promise<void> {diff --git a/src/lib/image-caption-pipeline.test.ts b/src/lib/image-caption-pipeline.test.tsindex 0b6fbcd9..fccb4543 100644--- a/src/lib/image-caption-pipeline.test.ts+++ b/src/lib/image-caption-pipeline.test.ts@@ -220,6 +220,18 @@ describe("captionMarkdownImages", () => {expect(mockReadBase64).toHaveBeenCalledWith("/custom/anchor/media/foo/img-1.png")})+ it("skips Codex CLI captioning once before reading image bytes", async () => {+ const out = await captionMarkdownImages("/proj", "\n", {+ ...cfg,+ provider: "codex-cli",+ })++ expect(out.enrichedMarkdown).toBe("\n")+ expect(out.failed).toBe(2)+ expect(mockReadBase64).not.toHaveBeenCalled()+ expect(mockCaption).not.toHaveBeenCalled()+ })+it("forwards AbortSignal to captionImage", async () => {mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })mockCaption.mockResolvedValue("c")diff --git a/src/lib/image-caption-pipeline.ts b/src/lib/image-caption-pipeline.tsindex c32199fc..56b75f3b 100644--- a/src/lib/image-caption-pipeline.ts+++ b/src/lib/image-caption-pipeline.ts@@ -307,6 +307,18 @@ export async function captionMarkdownImages(}}+ if (llmConfig.provider === "codex-cli") {+ console.warn(+ "[caption-pipeline] skipped image captioning: Codex CLI transport does not support image input yet.",+ )+ return {+ enrichedMarkdown: markdown,+ freshCaptions: 0,+ cachedCaptions: 0,+ failed: targetRefs.length,+ }+ }+const cache = await readCache(projectPath)let freshCaptions = 0let cachedCaptions = 0diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex f1a00cf0..da4b2a99 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -1,4 +1,13 @@-import { createDirectory, deleteFile, fileExists, readFile, writeFile, listDirectory } from "@/commands/fs"+import {+ createDirectory,+ deleteFile,+ fileExists,+ getFileModifiedTime,+ getFileSize,+ readFile,+ writeFile,+ listDirectory,+} from "@/commands/fs"import { streamChat } from "@/lib/llm-client"import type { LlmConfig } from "@/stores/wiki-store"import { useWikiStore } from "@/stores/wiki-store"@@ -50,6 +59,69 @@ function appendSavedImageRefsForCaption(content: string, images: SavedImage[]):return `${content}\n\n## Referenced Local Images\n\n${refs.join("\n")}\n`}+const ingestImageExtractionPromises = new Map<string, Promise<SavedImage[]>>()++async function imageExtractionKey(+ projectPath: string,+ sourcePath: string,+ sourceSummarySlug: string,+): Promise<string> {+ const normalizedSource = normalizePath(sourcePath)+ let fingerprint: string+ try {+ const [size, mtime] = await Promise.all([+ getFileSize(normalizedSource),+ getFileModifiedTime(normalizedSource),+ ])+ fingerprint = `${size}:${mtime}`+ } catch {+ // If the source disappeared or stat fails, avoid reusing a stale+ // promise from a previous ingest of the same path.+ fingerprint = `unstable:${Date.now()}`+ }+ return `${normalizePath(projectPath)}\n${normalizedSource}\n${sourceSummarySlug}\n${fingerprint}`+}++function rememberImageExtractionByKey(+ key: string,+ promise: Promise<SavedImage[]>,+): Promise<SavedImage[]> {+ ingestImageExtractionPromises.set(key, promise)+ if (ingestImageExtractionPromises.size > 32) {+ const oldest = ingestImageExtractionPromises.keys().next().value+ if (oldest) ingestImageExtractionPromises.delete(oldest)+ }+ promise.catch(() => {+ if (ingestImageExtractionPromises.get(key) === promise) {+ ingestImageExtractionPromises.delete(key)+ }+ })+ return promise+}++function extractSourceImagesOnceByKey(+ key: string,+ projectPath: string,+ sourcePath: string,+ sourceSummarySlug: string,+): Promise<SavedImage[]> {+ const existing = ingestImageExtractionPromises.get(key)+ if (existing) return existing+ return rememberImageExtractionByKey(+ key,+ extractAndSaveSourceImages(projectPath, sourcePath, sourceSummarySlug),+ )+}++async function extractSourceImagesOnce(+ projectPath: string,+ sourcePath: string,+ sourceSummarySlug: string,+): Promise<SavedImage[]> {+ const key = await imageExtractionKey(projectPath, sourcePath, sourceSummarySlug)+ return extractSourceImagesOnceByKey(key, projectPath, sourcePath, sourceSummarySlug)+}+function isSavedImagePromptUrl(projectPath: string, sourceSummarySlug: string, url: string): boolean {return (url.startsWith(`${projectPath}/wiki/media/${sourceSummarySlug}/`) ||@@ -401,7 +473,7 @@ async function autoIngestImpl(})const [sourceContent, schema, purpose, index, overview] = await Promise.all([- tryReadFile(sp),+ tryReadSourceTextFile(sp),tryReadFile(`${pp}/schema.md`),tryReadFile(`${pp}/purpose.md`),tryReadFile(`${pp}/wiki/index.md`),@@ -567,7 +639,7 @@ async function autoIngestImpl(// "the curated wiki knowledge".let enrichedSourceContent = stripWikiMediaAbsPaths(pp,- appendSavedImageRefsForCaption(sourceContent, markdownImages),+ appendSavedImageRefsForCaption(sourceContent, savedImages),)const mmCfg = useWikiStore.getState().multimodalConfigconst captionLlm = resolveCaptionConfig(mmCfg, llmConfig)@@ -1588,6 +1660,14 @@ async function tryReadFile(path: string): Promise<string> {}}+async function tryReadSourceTextFile(path: string): Promise<string> {+ try {+ return await readFile(path, { extractImages: false })+ } catch {+ return ""+ }+}+function clampNumber(value: number, min: number, max: number): number {return Math.max(min, Math.min(max, value))}@@ -2258,7 +2338,7 @@ export async function startIngest(// Failure-tolerant — `extractAndSaveSourceImages` returns [] on// any error and logs internally; we never want image extraction// to break the ingest chat flow.- void extractAndSaveSourceImages(pp, sp, sourceSummarySlug).catch((err) => {+ void extractSourceImagesOnce(pp, sp, sourceSummarySlug).catch((err) => {console.warn(`[startIngest:images] eager extraction failed for "${getFileName(sp)}":`,err instanceof Error ? err.message : err,@@ -2266,7 +2346,7 @@ export async function startIngest(})const [sourceContent, schema, purpose, index] = await Promise.all([- tryReadFile(sp),+ tryReadSourceTextFile(sp),tryReadFile(`${pp}/wiki/schema.md`),tryReadFile(`${pp}/wiki/purpose.md`),tryReadFile(`${pp}/wiki/index.md`),@@ -2474,12 +2554,11 @@ export async function executeIngestWrites(// Image cascade: surface any embedded images on the source-summary// page. `startIngest` already kicked off extraction in parallel// with the chat stream — by now the images are sitting in- // `wiki/media/<slug>/`, but no markdown references them yet. We- // re-run extraction here to get back the SavedImage metadata- // (rel_path, page) needed to build the markdown section. The Rust- // command is idempotent (deterministic file paths, overwrite-safe- // writes), so repeating it is cheap on the second call where every- // file already exists.+ // `wiki/media/<slug>/`, but no markdown references them yet. Reuse+ // the eager extraction promise from `startIngest` to get back the+ // SavedImage metadata (rel_path, page) needed to build the markdown+ // section. If this write path is reached without a prior startIngest+ // call, the helper falls back to a single extraction.//// Read the source path from the chat store — `startIngest` set it// there at the beginning of the flow, and we don't have it as a@@ -2492,10 +2571,17 @@ export async function executeIngestWrites(// stays consistent with autoIngest.const mmCfgWrites = useWikiStore.getState().multimodalConfigif (ingestSource && mmCfgWrites.enabled) {+ let extractionKey: string | null = nulltry {const sourceIdentity = sourceIdentityForPath(pp, ingestSource)const sourceSummarySlug = sourceSummarySlugFromIdentity(sourceIdentity)- const savedImages = await extractAndSaveSourceImages(pp, ingestSource, sourceSummarySlug)+ extractionKey = await imageExtractionKey(pp, ingestSource, sourceSummarySlug)+ const savedImages = await extractSourceImagesOnceByKey(+ extractionKey,+ pp,+ ingestSource,+ sourceSummarySlug,+ )if (savedImages.length > 0) {await injectImagesIntoSourceSummary(pp, sourceIdentity, sourceSummarySlug, savedImages)}@@ -2504,6 +2590,8 @@ export async function executeIngestWrites(`[executeIngestWrites:images] post-write injection failed:`,err instanceof Error ? err.message : err,)+ } finally {+ if (extractionKey) ingestImageExtractionPromises.delete(extractionKey)}}diff --git a/src/lib/vision-caption.test.ts b/src/lib/vision-caption.test.tsindex 01438e9b..46ea9234 100644--- a/src/lib/vision-caption.test.ts+++ b/src/lib/vision-caption.test.ts@@ -103,7 +103,11 @@ describe("captionImage", () => {})const overrides = mockStreamChat.mock.calls[0][4]- expect(overrides).toEqual({ temperature: 0.3, max_tokens: 256 })+ expect(overrides).toEqual({+ temperature: 0.3,+ max_tokens: 256,+ reasoning: { mode: "off" },+ })})it("uses defaults (temp=0, max_tokens=4096) when no options passed", async () => {@@ -114,7 +118,38 @@ describe("captionImage", () => {await captionImage(TINY_B64, "image/png", cfg)const overrides = mockStreamChat.mock.calls[0][4]- expect(overrides).toEqual({ temperature: 0, max_tokens: 4096 })+ expect(overrides).toEqual({+ temperature: 0,+ max_tokens: 4096,+ reasoning: { mode: "off" },+ })+ })++ it("forces reasoning off so main reasoning models produce captions instead of thinking-only streams", async () => {+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {+ cb.onToken("caption")+ cb.onDone()+ })++ const reasoningCfg: LlmConfig = {+ ...cfg,+ reasoning: { mode: "high" },+ }+ await captionImage(TINY_B64, "image/png", reasoningCfg)++ expect(mockStreamChat.mock.calls[0][4]).toMatchObject({+ reasoning: { mode: "off" },+ })+ })++ it("rejects Codex CLI captioning because that transport omits image bytes", async () => {+ await expect(+ captionImage(TINY_B64, "image/png", {+ ...cfg,+ provider: "codex-cli",+ }),+ ).rejects.toThrow(/does not support image input/)+ expect(mockStreamChat).not.toHaveBeenCalled()})it("forwards the AbortSignal to streamChat (lets callers cancel batch captioning)", async () => {diff --git a/src/lib/vision-caption.ts b/src/lib/vision-caption.tsindex 9706c088..0b5b3763 100644--- a/src/lib/vision-caption.ts+++ b/src/lib/vision-caption.ts@@ -159,6 +159,10 @@ export async function captionImage(signal?: AbortSignal,options?: CaptionOptions,): Promise<string> {+ if (llmConfig.provider === "codex-cli") {+ throw new Error("Codex CLI transport does not support image input for captioning yet.")+ }+// Pick the context-aware prompt iff EITHER side has non-trivial// content. Whitespace-only context is treated as "no context" so a// caller passing untrimmed slices doesn't accidentally upgrade to@@ -198,6 +202,12 @@ export async function captionImage({temperature: options?.temperature ?? 0,max_tokens: options?.maxTokens ?? 4096,+ // Captioning is a short factual vision task. If the main LLM is+ // configured as a reasoning model, inheriting that setting here+ // often burns the small caption budget on thinking and produces+ // no usable alt text. Disable reasoning for caption calls unless+ // this helper grows an explicit caption-reasoning option.+ reasoning: { mode: "off" },},)