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(multimodal): save extracted images, inject into pages, render in preview
nash_su4b0af6b79138
diff --git a/src-tauri/src/commands/extract_images.rs b/src-tauri/src/commands/extract_images.rsindex 15533789..fcae1e11 100644--- a/src-tauri/src/commands/extract_images.rs+++ b/src-tauri/src/commands/extract_images.rs@@ -393,6 +393,250 @@ fn build_pptx_media_slide_map(out}+// ── Extract-and-save: write to disk, skip the base64 round-trip ────────+//+// The base64-returning commands above are useful for future+// captioning paths that need bytes in-memory. The ingest pipeline+// just wants to land images on disk and reference them from+// markdown — the round-trip via JS is wasteful (5 MB image → 6.7 MB+// base64 string → JS allocates → JS calls back to Rust → decode →+// write). The functions below short-circuit by writing directly.++/// Metadata for an image that's already been written to disk.+/// Mirrors `ExtractedImage` but swaps `data_base64` for `rel_path` —+/// the path the caller can embed in markdown (``).+#[derive(Debug, Serialize)]+pub struct SavedImage {+ pub index: u32,+ pub mime_type: String,+ pub page: Option<u32>,+ pub width: u32,+ pub height: u32,+ /// Path of the written file, relative to `dest_dir_relative_to`.+ /// E.g. when `dest_dir` is `<project>/wiki/media/foo` and+ /// `dest_dir_relative_to` is `<project>/wiki`, this is+ /// `media/foo/img-1.png`. The caller-provided base lets us+ /// generate paths that work inside markdown rendered from+ /// anywhere under the wiki root.+ pub rel_path: String,+ /// Absolute path on disk — the chat / file-preview UI uses this+ /// (via `convertFileSrc`) to actually load the image.+ pub abs_path: String,+ pub sha256: String,+}++fn save_one_image(+ bytes: &[u8],+ dest_dir: &Path,+ dest_dir_relative_to: &Path,+ file_name: &str,+) -> Result<(String, String), String> {+ if !dest_dir.exists() {+ std::fs::create_dir_all(dest_dir)+ .map_err(|e| format!("create_dir_all '{}': {e}", dest_dir.display()))?;+ }+ let abs = dest_dir.join(file_name);+ std::fs::write(&abs, bytes).map_err(|e| format!("write '{}': {e}", abs.display()))?;++ let rel = abs+ .strip_prefix(dest_dir_relative_to)+ .map(|p| p.to_string_lossy().replace('\\', "/"))+ .unwrap_or_else(|_| file_name.to_string());+ Ok((rel, abs.to_string_lossy().to_string()))+}++fn ext_for_mime(mime: &str) -> &'static str {+ match mime {+ "image/png" => "png",+ "image/jpeg" => "jpg",+ "image/gif" => "gif",+ "image/webp" => "webp",+ "image/bmp" => "bmp",+ _ => "bin",+ }+}++/// PDF: extract every embedded image AND write each to+/// `dest_dir / img-<index>.<ext>`. `rel_to` is the directory the+/// returned `rel_path` is anchored at (typically the wiki root).+/// PNG re-encoding is unconditional (pdfium hands us decoded bitmaps+/// regardless of source codec).+pub fn extract_and_save_pdf_images(+ path: &str,+ dest_dir: &Path,+ rel_to: &Path,+ options: &ExtractOptions,+) -> Result<Vec<SavedImage>, String> {+ use pdfium_render::prelude::*;++ let pdfium = crate::commands::fs::pdfium()?;+ let doc = pdfium+ .load_pdf_from_file(path, None)+ .map_err(|e| format!("Failed to open PDF '{path}': {e}"))?;++ let mut out: Vec<SavedImage> = Vec::new();+ let mut idx: u32 = 0;++ 'pages: for (page_idx, page) in doc.pages().iter().enumerate() {+ for object in page.objects().iter() {+ let image = match object.as_image_object() {+ Some(img) => img,+ None => continue,+ };+ let dyn_img = match image.get_raw_image() {+ Ok(b) => b,+ Err(e) => {+ eprintln!(+ "[extract_and_save_pdf_images] page {} image read failed: {e}",+ page_idx + 1+ );+ continue;+ }+ };+ let width = dyn_img.width();+ let height = dyn_img.height();+ if width < options.min_width || height < options.min_height {+ continue;+ }++ let mut png_bytes: Vec<u8> = Vec::new();+ if let Err(e) = dyn_img.write_to(+ &mut std::io::Cursor::new(&mut png_bytes),+ image::ImageFormat::Png,+ ) {+ eprintln!(+ "[extract_and_save_pdf_images] page {} PNG encode failed: {e}",+ page_idx + 1+ );+ continue;+ }++ idx += 1;+ let file_name = format!("img-{idx}.png");+ let (rel_path, abs_path) = save_one_image(&png_bytes, dest_dir, rel_to, &file_name)?;+ let sha256 = sha256_hex(&png_bytes);++ out.push(SavedImage {+ index: idx,+ mime_type: "image/png".to_string(),+ page: Some((page_idx + 1) as u32),+ width,+ height,+ rel_path,+ abs_path,+ sha256,+ });++ if out.len() >= options.max_images {+ eprintln!(+ "[extract_and_save_pdf_images] reached max_images={} cap; skipped rest",+ options.max_images+ );+ break 'pages;+ }+ }+ }++ Ok(out)+}++/// PPTX/DOCX: pull embedded images directly from the zip media/+/// directory and write each to `dest_dir`. Source format is+/// preserved (PNG stays PNG, JPEG stays JPEG) since pulling the raw+/// bytes is cheap and there's no compositing happening.+pub fn extract_and_save_office_images(+ path: &str,+ dest_dir: &Path,+ rel_to: &Path,+ options: &ExtractOptions,+) -> Result<Vec<SavedImage>, String> {+ let file = File::open(path).map_err(|e| format!("Failed to open '{path}': {e}"))?;+ let mut archive =+ zip::ZipArchive::new(file).map_err(|e| format!("Failed to read zip '{path}': {e}"))?;++ let is_pptx = archive+ .file_names()+ .any(|n| n == "ppt/presentation.xml" || n.starts_with("ppt/slides/slide"));+ let media_to_slide = if is_pptx {+ build_pptx_media_slide_map(&mut archive)+ } else {+ std::collections::HashMap::new()+ };++ let media_indices: Vec<usize> = (0..archive.len())+ .filter(|i| {+ archive+ .by_index_raw(*i)+ .ok()+ .map(|f| is_media_path(f.name()))+ .unwrap_or(false)+ })+ .collect();++ let mut out: Vec<SavedImage> = Vec::new();+ let mut idx: u32 = 0;++ for archive_idx in media_indices {+ let mut entry = match archive.by_index(archive_idx) {+ Ok(e) => e,+ Err(e) => {+ eprintln!("[extract_and_save_office_images] zip entry read failed: {e}");+ continue;+ }+ };+ let entry_name = entry.name().to_string();+ let mime_type = match guess_mime_from_name(&entry_name) {+ Some(m) => m,+ None => continue,+ };++ let mut bytes = Vec::with_capacity(entry.size() as usize);+ if let Err(e) = entry.read_to_end(&mut bytes) {+ eprintln!("[extract_and_save_office_images] read '{entry_name}' failed: {e}");+ continue;+ }++ let (width, height) = match image::load_from_memory(&bytes) {+ Ok(img) => (img.width(), img.height()),+ Err(e) => {+ eprintln!("[extract_and_save_office_images] decode '{entry_name}' failed: {e}");+ continue;+ }+ };+ if width < options.min_width || height < options.min_height {+ continue;+ }++ idx += 1;+ let ext = ext_for_mime(&mime_type);+ let file_name = format!("img-{idx}.{ext}");+ let (rel_path, abs_path) = save_one_image(&bytes, dest_dir, rel_to, &file_name)?;+ let sha256 = sha256_hex(&bytes);+ let page = media_to_slide.get(&entry_name).copied().flatten();++ out.push(SavedImage {+ index: idx,+ mime_type,+ page,+ width,+ height,+ rel_path,+ abs_path,+ sha256,+ });++ if out.len() >= options.max_images {+ eprintln!(+ "[extract_and_save_office_images] reached max_images={} cap; skipped rest",+ options.max_images+ );+ break;+ }+ }++ Ok(out)+}+// ── Tauri command bindings ─────────────────────────────────────────────#[tauri::command]@@ -409,6 +653,38 @@ pub fn extract_office_images_cmd(path: String) -> Result<Vec<ExtractedImage>, St})}+#[tauri::command]+pub fn extract_and_save_pdf_images_cmd(+ source_path: String,+ dest_dir: String,+ rel_to: String,+) -> Result<Vec<SavedImage>, String> {+ crate::panic_guard::run_guarded("extract_and_save_pdf_images", || {+ extract_and_save_pdf_images(+ &source_path,+ Path::new(&dest_dir),+ Path::new(&rel_to),+ &ExtractOptions::default(),+ )+ })+}++#[tauri::command]+pub fn extract_and_save_office_images_cmd(+ source_path: String,+ dest_dir: String,+ rel_to: String,+) -> Result<Vec<SavedImage>, String> {+ crate::panic_guard::run_guarded("extract_and_save_office_images", || {+ extract_and_save_office_images(+ &source_path,+ Path::new(&dest_dir),+ Path::new(&rel_to),+ &ExtractOptions::default(),+ )+ })+}+// ── Tests ──────────────────────────────────────────────────────────────#[cfg(test)]diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 0001989b..f1b7d12e 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -68,6 +68,8 @@ pub fn run() {commands::claude_cli::claude_cli_kill,commands::extract_images::extract_pdf_images_cmd,commands::extract_images::extract_office_images_cmd,+ commands::extract_images::extract_and_save_pdf_images_cmd,+ commands::extract_images::extract_and_save_office_images_cmd,]).on_window_event(|window, event| {if let tauri::WindowEvent::CloseRequested { api, .. } = event {diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsxindex 7ec28856..359474da 100644--- a/src/components/chat/chat-message.tsx+++ b/src/components/chat/chat-message.tsx@@ -17,6 +17,7 @@ import type { FileNode } from "@/types/wiki"import { convertLatexToUnicode } from "@/lib/latex-to-unicode"import { normalizePath, getFileName } from "@/lib/path-utils"import { makeQueryFileName } from "@/lib/wiki-filename"+import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"// Module-level cache of source file nameslet cachedSourceFiles: string[] = []@@ -481,6 +482,12 @@ function MarkdownContent({ content }: { content: string }) {// Strip hidden commentsconst cleaned = content.replace(/<!--.*?-->/gs, "").trimEnd()+ // Project path for resolving wiki-relative image src in chat+ // replies (LLM may surface images that came in via retrieved+ // chunks, e.g. when the chat answer cites a diagram from a wiki+ // page). Same convention the file-preview uses.+ const projectPath = useWikiStore((s) => s.project?.path ?? null)+// Separate thinking blocks from main contentconst { thinking, answer } = useMemo(() => separateThinking(cleaned), [cleaned])const processed = useMemo(() => processContent(answer), [answer])@@ -504,6 +511,15 @@ function MarkdownContent({ content }: { content: string }) {</span>)},+ img: ({ src, alt, ...props }) => (+ <img+ src={typeof src === "string" ? resolveMarkdownImageSrc(src, projectPath) : undefined}+ alt={alt ?? ""}+ className="my-2 max-w-full rounded border border-border/40"+ loading="lazy"+ {...props}+ />+ ),table: ({ children, ...props }) => (<div className="my-2 overflow-x-auto rounded border border-border"><table className="w-full border-collapse text-xs" {...props}>{children}</table>diff --git a/src/components/editor/file-preview.tsx b/src/components/editor/file-preview.tsxindex 4325864a..0b6ffe01 100644--- a/src/components/editor/file-preview.tsx+++ b/src/components/editor/file-preview.tsx@@ -15,6 +15,8 @@ import {import { getFileCategory, getCodeLanguage } from "@/lib/file-types"import type { FileCategory } from "@/lib/file-types"import { getFileName } from "@/lib/path-utils"+import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"+import { useWikiStore } from "@/stores/wiki-store"interface FilePreviewProps {filePath: string@@ -111,6 +113,7 @@ function CodePreview({ filePath, content }: { filePath: string; content: string}function TextPreview({ filePath, content, label }: { filePath: string; content: string; label: string }) {+ const projectPath = useWikiStore((s) => s.project?.path ?? null)return (<div className="h-full overflow-auto p-6"><div className="mb-2 flex items-center gap-2 text-xs text-muted-foreground">@@ -122,6 +125,19 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}components={{+ // Resolve `` references generated by the+ // ingest image-extraction step. Without this, the+ // browser tries to load `media/...` relative to the+ // webview origin and silently 404s.+ img: ({ src, alt, ...props }) => (+ <img+ src={typeof src === "string" ? resolveMarkdownImageSrc(src, projectPath) : undefined}+ alt={alt ?? ""}+ className="max-w-full rounded border border-border/40"+ loading="lazy"+ {...props}+ />+ ),table: ({ children, ...props }) => (<div className="my-2 overflow-x-auto rounded border border-border"><table className="w-full border-collapse text-xs" {...props}>{children}</table>diff --git a/src/lib/extract-source-images.ts b/src/lib/extract-source-images.tsnew file mode 100644index 00000000..2f118151--- /dev/null+++ b/src/lib/extract-source-images.ts@@ -0,0 +1,156 @@+/**+ * Image extraction orchestration for the ingest pipeline.+ *+ * Pure dispatch + path-shaping layer over the Rust commands+ * `extract_and_save_pdf_images_cmd` / `extract_and_save_office_images_cmd`.+ * Decides which command to call based on file extension, computes the+ * destination directory (`wiki/media/<source-slug>/`), and gives back+ * a small markdown snippet ready to paste into the LLM's source+ * context.+ *+ * NOTE: this layer does NOT call any LLM (no captions yet — that's+ * Phase 3a). The alt text on each image is a placeholder; once+ * captioning lands, the same helper grows a `caption` field per+ * image and the markdown line uses that instead.+ */+import { invoke } from "@tauri-apps/api/core"+import { getFileName, normalizePath } from "@/lib/path-utils"++/** Mirrors `commands::extract_images::SavedImage` on the Rust side. */+export interface SavedImage {+ index: number+ mimeType: string+ /** PDF page or PPTX slide number (1-based). DOCX always null. */+ page: number | null+ width: number+ height: number+ /** Path relative to the wiki/ root, e.g. `media/rope-paper/img-1.png`. */+ relPath: string+ /** Absolute filesystem path — used by `convertFileSrc` for preview. */+ absPath: string+ sha256: string+}++/** File extensions we currently extract images from. Excludes XLS/XLSX+ * because spreadsheets generally don't have charts as images (charts+ * are XML-rendered shapes, not embedded raster). Adding them later is+ * a one-line change here. */+const SUPPORTED_PDF_EXTS = ["pdf"] as const+const SUPPORTED_OFFICE_EXTS = ["pptx", "docx", "ppt", "doc"] as const+// Note: ppt / doc (legacy binary formats) won't actually work — they+// aren't ZIP. Listed for completeness; Rust side will return Err which+// the caller treats as "no images" gracefully.++/**+ * Extract every embedded image from `sourcePath` and save them to+ * `<projectPath>/wiki/media/<slug>/`. Returns metadata only — image+ * bytes never traverse JS (the Rust command writes directly).+ *+ * Returns `[]` for unsupported file types or when the source has no+ * extractable images. Errors during extraction are logged and returned+ * as an empty array — image extraction failure must NEVER abort the+ * ingest pipeline (which is why this isn't `throws`).+ *+ * `slug` is the basename of the source file without extension. Same+ * convention the rest of ingest uses (see `wiki/sources/<slug>.md`).+ */+export async function extractAndSaveSourceImages(+ projectPath: string,+ sourcePath: string,+): Promise<SavedImage[]> {+ const pp = normalizePath(projectPath)+ const sp = normalizePath(sourcePath)+ const fileName = getFileName(sp)+ const ext = fileName.split(".").pop()?.toLowerCase() ?? ""++ const isPdf = (SUPPORTED_PDF_EXTS as readonly string[]).includes(ext)+ const isOffice = (SUPPORTED_OFFICE_EXTS as readonly string[]).includes(ext)+ if (!isPdf && !isOffice) return []++ const slug = fileName.replace(/\.[^.]+$/, "")+ const destDir = `${pp}/wiki/media/${slug}`+ const relTo = `${pp}/wiki`++ try {+ const images = await invoke<unknown[]>(+ isPdf ? "extract_and_save_pdf_images_cmd" : "extract_and_save_office_images_cmd",+ { sourcePath: sp, destDir, relTo },+ )+ // Rust serializes with snake_case-ish field names per the struct+ // shape. Tauri's IPC layer with serde converts to camelCase+ // automatically. Validate the shape defensively in case the+ // contract drifts.+ return images+ .filter((it): it is SavedImage => {+ if (!it || typeof it !== "object") return false+ const obj = it as Record<string, unknown>+ return (+ typeof obj.index === "number" &&+ typeof obj.relPath === "string" &&+ typeof obj.absPath === "string"+ )+ })+ } catch (err) {+ console.warn(+ `[ingest:images] extraction failed for "${fileName}":`,+ err instanceof Error ? err.message : err,+ )+ return []+ }+}++/**+ * Build the markdown section to splice into `sourceContent` so the+ * generation LLM sees the available images. Each image is referenced+ * once by its rel_path with a placeholder alt-text (Phase 3a will+ * replace this with VLM-generated captions).+ *+ * Returns an empty string when there are no images — no leading+ * separator gets inserted, which keeps the prompt size unchanged for+ * pure-text documents.+ *+ * Placement: caller appends this AFTER the source's text content so+ * the LLM still reads the document linearly, then sees images at the+ * end with their page numbers as positional anchors. A future+ * refinement (per the plan) is to insert per-page image listings+ * inline at page breaks; that requires the text extractor to emit+ * page boundaries, which it doesn't yet.+ */+export function buildImageMarkdownSection(images: SavedImage[]): string {+ if (images.length === 0) return ""++ const lines: string[] = ["", "", "## Embedded Images", ""]+ // Group by page so the LLM can correlate "Figure 3 mentioned on+ // page 5" with the right image. DOCX images have page=null; they+ // get grouped under "Document":+ const byPage = new Map<string, SavedImage[]>()+ for (const img of images) {+ const key = img.page == null ? "Document" : `Page ${img.page}`+ const bucket = byPage.get(key)+ if (bucket) bucket.push(img)+ else byPage.set(key, [img])+ }++ // Page-keyed order, with "Document" (DOCX) last when present.+ const ordered = [...byPage.keys()].sort((a, b) => {+ if (a === "Document") return 1+ if (b === "Document") return -1+ const numA = parseInt(a.replace(/\D/g, ""), 10) || 0+ const numB = parseInt(b.replace(/\D/g, ""), 10) || 0+ return numA - numB+ })++ for (const key of ordered) {+ lines.push(`### ${key}`, "")+ for (const img of byPage.get(key) ?? []) {+ // Empty alt text on purpose — we don't have a caption yet, and+ // making one up here would just feed the LLM noise. The image+ // SOURCE (rel_path) carries enough information for the LLM to+ // refer to it by page number.+ lines.push(``)+ }+ lines.push("")+ }++ return lines.join("\n")+}diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 81e48b07..9be45184 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -8,6 +8,10 @@ import { useReviewStore, type ReviewItem } from "@/stores/review-store"import { getFileName, normalizePath } from "@/lib/path-utils"import { checkIngestCache, saveIngestCache } from "@/lib/ingest-cache"import { withProjectLock } from "@/lib/project-mutex"+import {+ extractAndSaveSourceImages,+ buildImageMarkdownSection,+} from "@/lib/extract-source-images"import { buildLanguageDirective } from "@/lib/output-language"import { detectLanguage } from "@/lib/detect-language"@@ -273,9 +277,27 @@ async function autoIngestImpl(return cachedFiles}- const truncatedContent = sourceContent.length > 50000- ? sourceContent.slice(0, 50000) + "\n\n[...truncated...]"- : sourceContent+ // ── Step 0.5: Extract embedded images ─────────────────────────+ // Pulls every embedded image out of PDF / PPTX / DOCX into+ // `wiki/media/<source-slug>/`, returns metadata. Markdown image+ // references get appended to the source content the LLM sees, so+ // generated wiki pages can reference figures by page number even+ // though we don't have captions yet (Phase 3a). Failure here is+ // never fatal — extractAndSaveSourceImages logs + returns [] on+ // any error.+ activity.updateItem(activityId, { detail: "Extracting embedded images..." })+ const savedImages = await extractAndSaveSourceImages(pp, sp)+ const imageSection = buildImageMarkdownSection(savedImages)+ const enrichedSourceContent = sourceContent + imageSection+ if (savedImages.length > 0) {+ console.log(+ `[ingest:images] saved ${savedImages.length} image(s) for "${fileName}" → wiki/media/${fileName.replace(/\.[^.]+$/, "")}/`,+ )+ }++ const truncatedContent = enrichedSourceContent.length > 50000+ ? enrichedSourceContent.slice(0, 50000) + "\n\n[...truncated...]"+ : enrichedSourceContent// ── Step 1: Analysis ──────────────────────────────────────────// LLM reads the source and produces a structured analysis:diff --git a/src/lib/markdown-image-resolver.test.ts b/src/lib/markdown-image-resolver.test.tsnew file mode 100644index 00000000..5fb09d40--- /dev/null+++ b/src/lib/markdown-image-resolver.test.ts@@ -0,0 +1,108 @@+/**+ * Tests for `resolveMarkdownImageSrc`.+ *+ * Tauri's `convertFileSrc` is mocked to a deterministic identity+ * wrapper so we can assert the path that goes IN, not the actual+ * Tauri-side URL shape (which differs across platforms — `asset://`+ * on macOS, `https://asset.localhost/` on Windows, etc.).+ */+import { describe, it, expect, vi } from "vitest"++// Hoisted mock — all calls to convertFileSrc return `tauri-asset:<path>`+// so tests can assert the input path was assembled correctly without+// caring about Tauri's per-platform URL scheme.+vi.mock("@tauri-apps/api/core", () => ({+ convertFileSrc: (path: string) => `tauri-asset:${path}`,+}))++import { resolveMarkdownImageSrc } from "./markdown-image-resolver"++describe("resolveMarkdownImageSrc", () => {+ const PROJECT = "/Users/me/MyWiki"++ it("passes http(s) URLs through unchanged", () => {+ expect(resolveMarkdownImageSrc("https://example.com/img.png", PROJECT)).toBe(+ "https://example.com/img.png",+ )+ expect(resolveMarkdownImageSrc("http://insecure.test/x.png", PROJECT)).toBe(+ "http://insecure.test/x.png",+ )+ })++ it("passes data: URIs through unchanged (inline base64)", () => {+ const src = "data:image/png;base64,iVBORw0K..."+ expect(resolveMarkdownImageSrc(src, PROJECT)).toBe(src)+ })++ it("passes blob: and tauri: URIs through unchanged", () => {+ expect(resolveMarkdownImageSrc("blob:abc-123", PROJECT)).toBe("blob:abc-123")+ expect(resolveMarkdownImageSrc("tauri://asset/foo.png", PROJECT)).toBe(+ "tauri://asset/foo.png",+ )+ })++ it("treats a wiki-rooted relative path as media under <project>/wiki/", () => {+ // This is the canonical case — ingest emits exactly this shape:+ // + expect(+ resolveMarkdownImageSrc("media/rope-paper/img-1.png", PROJECT),+ ).toBe("tauri-asset:/Users/me/MyWiki/wiki/media/rope-paper/img-1.png")+ })++ it("strips a leading ./ for cleanliness", () => {+ expect(+ resolveMarkdownImageSrc("./media/foo/img-2.png", PROJECT),+ ).toBe("tauri-asset:/Users/me/MyWiki/wiki/media/foo/img-2.png")+ })++ it("resolves nested paths (e.g. user-organized subfolders) under wiki/ root", () => {+ expect(+ resolveMarkdownImageSrc("entities/transformer/diagram.png", PROJECT),+ ).toBe("tauri-asset:/Users/me/MyWiki/wiki/entities/transformer/diagram.png")+ })++ it("treats an absolute POSIX path as a literal filesystem path", () => {+ // Some user content may legitimately reference an image outside+ // the wiki root (a system-wide asset, a mounted drive). Don't+ // re-anchor — just convert.+ expect(+ resolveMarkdownImageSrc("/var/data/screenshot.png", PROJECT),+ ).toBe("tauri-asset:/var/data/screenshot.png")+ })++ it("treats a Windows drive-letter path as absolute", () => {+ expect(+ resolveMarkdownImageSrc("C:/Users/me/Pictures/x.png", PROJECT),+ ).toBe("tauri-asset:C:/Users/me/Pictures/x.png")+ })++ it("treats a UNC path as absolute", () => {+ expect(+ resolveMarkdownImageSrc("\\\\share\\folder\\img.png", PROJECT),+ ).toBe("tauri-asset:\\\\share\\folder\\img.png")+ })++ it("returns the raw src unchanged when no project is loaded", () => {+ // Resolver is intentionally safe to call before a project is+ // open — preview surfaces (welcome screen, settings) might+ // render markdown without a project context.+ expect(resolveMarkdownImageSrc("media/foo/img.png", null)).toBe(+ "media/foo/img.png",+ )+ })++ it("normalizes Windows backslashes in projectPath via path-utils", () => {+ // normalizePath flips backslashes, so the assembled abs path+ // uses forward slashes regardless of OS.+ expect(+ resolveMarkdownImageSrc(+ "media/x/y.png",+ "C:\\Users\\me\\MyWiki",+ ),+ ).toBe("tauri-asset:C:/Users/me/MyWiki/wiki/media/x/y.png")+ })++ it("returns empty string verbatim for empty src", () => {+ expect(resolveMarkdownImageSrc("", PROJECT)).toBe("")+ })+})diff --git a/src/lib/markdown-image-resolver.ts b/src/lib/markdown-image-resolver.tsnew file mode 100644index 00000000..3e0429cf--- /dev/null+++ b/src/lib/markdown-image-resolver.ts@@ -0,0 +1,65 @@+/**+ * Resolve markdown image `src` attributes so they actually load in+ * the Tauri webview.+ *+ * The problem: ingest writes images to `<project>/wiki/media/<slug>/`+ * and embeds them in generated wiki pages as+ * ``. A markdown renderer interprets that+ * relative to the rendering page's URL — but in Tauri there IS no+ * URL context for arbitrary file paths, AND the wiki page may be+ * located deeper than `wiki/concepts/foo.md` so naive `../media/...`+ * fixups don't generalize.+ *+ * Convention we settle on:+ *+ * - Any src starting with `http://`, `https://`, `data:`, `blob:`,+ * `file:`, `tauri://` is passed through unchanged.+ * - Any src starting with `/` (absolute) is wrapped with+ * `convertFileSrc` directly — the path is the filesystem+ * absolute path.+ * - **Anything else is treated as relative to the project's+ * `wiki/` root.** Generated content uses this form+ * (`media/foo/img-1.png`); user-written content can use it too.+ *+ * The resolver returns a string that React's <img src=...> can load:+ * the appropriate `convertFileSrc(...)` URL or the original src+ * verbatim.+ */+import { convertFileSrc } from "@tauri-apps/api/core"+import { normalizePath } from "@/lib/path-utils"++const PASSTHROUGH_RE = /^(https?:|data:|blob:|file:|tauri:)/i++/**+ * `projectPath` is the wiki project's root directory. When null+ * (no project loaded), the resolver passes srcs through unchanged+ * so it remains safe to call before a project is open.+ */+export function resolveMarkdownImageSrc(+ rawSrc: string,+ projectPath: string | null,+): string {+ if (!rawSrc) return rawSrc+ if (PASSTHROUGH_RE.test(rawSrc)) return rawSrc++ if (!projectPath) return rawSrc++ const pp = normalizePath(projectPath)+ const isAbsolute =+ rawSrc.startsWith("/") || /^[a-zA-Z]:/.test(rawSrc) || rawSrc.startsWith("\\\\")++ // Absolute paths get fed straight to convertFileSrc — the user (or+ // some plugin) explicitly chose that path; we don't second-guess.+ if (isAbsolute) return convertFileSrc(rawSrc)++ // Strip a leading `./` for cleanliness; treat `media/foo.png` and+ // `./media/foo.png` identically.+ const cleaned = rawSrc.replace(/^\.\//, "")++ // Resolve as wiki-root-relative. The markdown lives somewhere+ // under wiki/ but we ignore its location — image references in+ // generated content always use this convention so the path is+ // stable regardless of page depth.+ const absolute = `${pp}/wiki/${cleaned}`+ return convertFileSrc(absolute)+}