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(multimodal): vision pipeline, image search UI, and total-disable toggle

nash_su4fa67a000a26
diff --git a/src-tauri/src/commands/extract_images.rs b/src-tauri/src/commands/extract_images.rs
index b6f413f3..b2ed8be0 100644
--- a/src-tauri/src/commands/extract_images.rs
+++ b/src-tauri/src/commands/extract_images.rs
@@ -51,6 +51,7 @@ impl Default for ExtractOptions {
}
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct ExtractedImage {
/// 1-based index in document order. Stable across re-extractions.
/// Used as the filename suffix when the caller writes images to
@@ -77,6 +78,166 @@ pub struct ExtractedImage {
// ── PDF (pdfium) ────────────────────────────────────────────────────────
+/// Combined PDF text + image extraction in a single pdfium session.
+///
+/// Output is a markdown string with `## Page N` headers, the page's
+/// extracted text, and `![](url)` references to images embedded on
+/// that page — interleaved per-page so the document reads top-to-
+/// bottom the way the source did.
+///
+/// When `media_dest_dir` is `Some`, every embedded raster image
+/// passing the size filter is written to that directory as
+/// `img-<N>.png` (1-based across the whole document) and referenced
+/// in the markdown via `media_url_prefix + "/img-<N>.png"`. Pass an
+/// absolute path as the prefix when you want the markdown to render
+/// regardless of where the file is opened (this is what the raw-
+/// source preview wants — see `extract_pdf_text` in fs.rs).
+///
+/// When `media_dest_dir` is `None`, image objects are skipped
+/// entirely and the output is text + page headers only — useful for
+/// PDFs outside the project's `raw/sources/` layout where there's no
+/// stable place to land the image files.
+///
+/// Holds the global pdfium lock for its full duration. Callers MUST
+/// NOT acquire the lock themselves before calling this (would
+/// deadlock — `std::sync::Mutex` is non-reentrant).
+pub fn extract_pdf_markdown(
+ path: &str,
+ media_dest_dir: Option<&Path>,
+ media_url_prefix: &str,
+ options: &ExtractOptions,
+) -> Result<String, String> {
+ use pdfium_render::prelude::*;
+
+ let _guard = crate::commands::fs::lock_pdfium();
+ let pdfium = crate::commands::fs::pdfium()?;
+ let doc = pdfium
+ .load_pdf_from_file(path, None)
+ .map_err(|e| match e {
+ PdfiumError::PdfiumLibraryInternalError(
+ PdfiumInternalError::PasswordError,
+ ) => format!("PDF is password-protected and cannot be read: '{path}'"),
+ _ => format!("Failed to open PDF '{path}': {e}"),
+ })?;
+
+ let mut out = String::new();
+ let mut idx: u32 = 0;
+ let mut total_saved: u32 = 0;
+ // Strip a single trailing slash from the prefix so we can always
+ // emit `prefix + "/" + name` without producing `path//name`.
+ let prefix = media_url_prefix.trim_end_matches('/');
+
+ let page_count = doc.pages().len();
+ if media_dest_dir.is_some() {
+ eprintln!(
+ "[extract_pdf_markdown] '{path}': {page_count} page(s), images→{:?}",
+ media_dest_dir.map(|d| d.display().to_string())
+ );
+ }
+
+ for (page_idx, page) in doc.pages().iter().enumerate() {
+ let page_num = page_idx + 1;
+ if !out.is_empty() {
+ out.push_str("\n\n");
+ }
+ out.push_str(&format!("## Page {page_num}\n\n"));
+
+ let page_text = page
+ .text()
+ .map_err(|e| {
+ format!("Page {page_num} text extraction failed in '{path}': {e}")
+ })?;
+ out.push_str(&page_text.all());
+ // Single trailing newline so the next block starts on its own
+ // line; the `\n\n` separator before the next `## Page` heading
+ // gets prepended by the loop entry above.
+ out.push('\n');
+
+ // Skip image extraction when the caller didn't supply a
+ // destination — no point burning pdfium cycles to throw the
+ // pixels away.
+ let dest_dir = match media_dest_dir {
+ Some(d) => d,
+ None => continue,
+ };
+
+ let mut page_image_md: Vec<String> = Vec::new();
+ 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_pdf_markdown] page {page_num} image read failed: {e}"
+ );
+ 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_pdf_markdown] page {page_num} PNG encode failed: {e}"
+ );
+ continue;
+ }
+ idx += 1;
+ let file_name = format!("img-{idx}.png");
+ // `dest_dir_relative_to` is unused here (we don't need a
+ // rel_path return — the markdown uses media_url_prefix);
+ // pass dest_dir for both args so save_one_image's
+ // strip_prefix is a no-op.
+ if let Err(e) = save_one_image(&png_bytes, dest_dir, dest_dir, &file_name) {
+ eprintln!(
+ "[extract_pdf_markdown] page {page_num} save failed: {e}"
+ );
+ continue;
+ }
+ total_saved += 1;
+ // Empty alt-text on purpose: until the vision-caption
+ // helper lands (Phase 3a) we have nothing meaningful to
+ // put there, and a placeholder like "image" or the file
+ // name only adds noise to the LLM and to screen readers.
+ page_image_md.push(format!("![]({prefix}/{file_name})"));
+ if total_saved as usize >= options.max_images {
+ eprintln!(
+ "[extract_pdf_markdown] reached max_images={} cap; skipped rest",
+ options.max_images
+ );
+ break;
+ }
+ }
+ if !page_image_md.is_empty() {
+ out.push('\n');
+ for img_md in &page_image_md {
+ out.push_str(img_md);
+ out.push('\n');
+ }
+ }
+ if total_saved as usize >= options.max_images {
+ break;
+ }
+ }
+
+ if media_dest_dir.is_some() {
+ eprintln!(
+ "[extract_pdf_markdown] '{path}' DONE — pages={page_count}, saved={total_saved}"
+ );
+ }
+
+ Ok(out)
+}
+
/// Iterate every PDF page, extract every embedded raster image, and
/// re-encode each to PNG. Vector content (paths, glyph outlines) is
/// NOT extracted here — that's a Phase 1.5 follow-up if needed (would
@@ -87,6 +248,12 @@ pub fn extract_pdf_images(
) -> Result<Vec<ExtractedImage>, String> {
use pdfium_render::prelude::*;
+ // Hold the global PDFium lock for the entire call. The C library
+ // is NOT safe for concurrent access — see `lock_pdfium` in fs.rs
+ // for the full rationale. Held for the whole document lifetime so
+ // page iteration doesn't race a concurrent `load_pdf_from_file`
+ // on a different worker thread.
+ let _guard = crate::commands::fs::lock_pdfium();
let pdfium = crate::commands::fs::pdfium()?;
let doc = pdfium
.load_pdf_from_file(path, None)
@@ -405,7 +572,16 @@ fn build_pptx_media_slide_map(
/// 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 (`![alt](rel_path)`).
+///
+/// `rename_all = "camelCase"` is REQUIRED, not cosmetic. The TS layer
+/// validates the IPC payload by exact field names (`relPath`,
+/// `absPath`, `mimeType`) — without this attribute serde would emit
+/// `rel_path`/`abs_path`/`mime_type` and the validator drops every
+/// item, returning `[]` even when extraction succeeded and saved
+/// files to disk. Tauri's IPC auto-camelCase only applies to
+/// COMMAND PARAMETER names, never to serialized return values.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct SavedImage {
pub index: u32,
pub mime_type: String,
@@ -469,6 +645,8 @@ pub fn extract_and_save_pdf_images(
) -> Result<Vec<SavedImage>, String> {
use pdfium_render::prelude::*;
+ // See `extract_pdf_images` for why this lock is mandatory.
+ let _guard = crate::commands::fs::lock_pdfium();
let pdfium = crate::commands::fs::pdfium()?;
let doc = pdfium
.load_pdf_from_file(path, None)
@@ -476,16 +654,34 @@ pub fn extract_and_save_pdf_images(
let mut out: Vec<SavedImage> = Vec::new();
let mut idx: u32 = 0;
+ // Diagnostic counters — when extraction returns empty, the user's
+ // first question is "did the PDF actually have raster images?"
+ // These let us answer it from logs without having to crack open
+ // the PDF in a debugger.
+ let mut total_objects: u32 = 0;
+ let mut total_image_objects: u32 = 0;
+ let mut filtered_too_small: u32 = 0;
+ let mut filtered_decode_err: u32 = 0;
+ let mut filtered_encode_err: u32 = 0;
+
+ let page_count = doc.pages().len();
+ eprintln!(
+ "[extract_and_save_pdf_images] '{path}': {} page(s), filter=({}x{}) min, max={}",
+ page_count, options.min_width, options.min_height, options.max_images
+ );
'pages: for (page_idx, page) in doc.pages().iter().enumerate() {
for object in page.objects().iter() {
+ total_objects += 1;
let image = match object.as_image_object() {
Some(img) => img,
None => continue,
};
+ total_image_objects += 1;
let dyn_img = match image.get_raw_image() {
Ok(b) => b,
Err(e) => {
+ filtered_decode_err += 1;
eprintln!(
"[extract_and_save_pdf_images] page {} image read failed: {e}",
page_idx + 1
@@ -496,6 +692,11 @@ pub fn extract_and_save_pdf_images(
let width = dyn_img.width();
let height = dyn_img.height();
if width < options.min_width || height < options.min_height {
+ filtered_too_small += 1;
+ eprintln!(
+ "[extract_and_save_pdf_images] page {} image {}x{} < min ({}x{}) — skipped",
+ page_idx + 1, width, height, options.min_width, options.min_height
+ );
continue;
}
@@ -504,6 +705,7 @@ pub fn extract_and_save_pdf_images(
&mut std::io::Cursor::new(&mut png_bytes),
image::ImageFormat::Png,
) {
+ filtered_encode_err += 1;
eprintln!(
"[extract_and_save_pdf_images] page {} PNG encode failed: {e}",
page_idx + 1
@@ -537,6 +739,11 @@ pub fn extract_and_save_pdf_images(
}
}
+ eprintln!(
+ "[extract_and_save_pdf_images] '{path}' DONE — saved={}, total_objects={}, image_objects={}, too_small={}, decode_err={}, encode_err={}",
+ out.len(), total_objects, total_image_objects, filtered_too_small, filtered_decode_err, filtered_encode_err,
+ );
+
Ok(out)
}
@@ -639,18 +846,36 @@ pub fn extract_and_save_office_images(
// ── Tauri command bindings ─────────────────────────────────────────────
+// Why every cmd below is `spawn_blocking`:
+// PDFium FFI calls and zip+image-decode are all blocking. Running
+// them inside an `async fn` body (as we did before this fix) kept
+// them on a tokio worker thread, blocking other async tasks on
+// that worker for the full duration of the extraction. `spawn_
+// blocking` moves the work to tokio's blocking pool — that's the
+// pool's contract. (Combined with the PDFium mutex inside
+// `extract_pdf_images`, this also prevents the segfault that hit
+// when two PDF extractions raced on different workers.)
+
#[tauri::command]
pub async fn extract_pdf_images_cmd(path: String) -> Result<Vec<ExtractedImage>, String> {
- crate::panic_guard::run_guarded("extract_pdf_images", || {
- extract_pdf_images(&path, &ExtractOptions::default())
+ tauri::async_runtime::spawn_blocking(move || {
+ crate::panic_guard::run_guarded("extract_pdf_images", || {
+ extract_pdf_images(&path, &ExtractOptions::default())
+ })
})
+ .await
+ .map_err(|e| format!("extract_pdf_images blocking task join error: {e}"))?
}
#[tauri::command]
pub async fn extract_office_images_cmd(path: String) -> Result<Vec<ExtractedImage>, String> {
- crate::panic_guard::run_guarded("extract_office_images", || {
- extract_office_images(&path, &ExtractOptions::default())
+ tauri::async_runtime::spawn_blocking(move || {
+ crate::panic_guard::run_guarded("extract_office_images", || {
+ extract_office_images(&path, &ExtractOptions::default())
+ })
})
+ .await
+ .map_err(|e| format!("extract_office_images blocking task join error: {e}"))?
}
#[tauri::command]
@@ -659,14 +884,18 @@ pub async fn extract_and_save_pdf_images_cmd(
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::async_runtime::spawn_blocking(move || {
+ 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(),
+ )
+ })
})
+ .await
+ .map_err(|e| format!("extract_and_save_pdf_images blocking task join error: {e}"))?
}
#[tauri::command]
@@ -675,14 +904,18 @@ pub async fn extract_and_save_office_images_cmd(
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(),
- )
+ tauri::async_runtime::spawn_blocking(move || {
+ 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(),
+ )
+ })
})
+ .await
+ .map_err(|e| format!("extract_and_save_office_images blocking task join error: {e}"))?
}
// ── Tests ──────────────────────────────────────────────────────────────
diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rs
index 29e7eced..544efc18 100644
--- a/src-tauri/src/commands/fs.rs
+++ b/src-tauri/src/commands/fs.rs
@@ -20,85 +20,91 @@ const LEGACY_DOC_EXTS: &[&str] = &["doc", "xls", "ppt", "pages", "numbers", "key
#[tauri::command]
pub async fn read_file(path: String) -> Result<String, String> {
- run_guarded("read_file", || {
- let p = Path::new(&path);
- let ext = p
- .extension()
- .and_then(|e| e.to_str())
- .unwrap_or("")
- .to_lowercase();
-
- // Check cache first for any extractable format
- if let Some(cached) = read_cache(p) {
- return Ok(cached);
- }
-
- match ext.as_str() {
- "pdf" => extract_pdf_text(&path),
- 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);
- Ok(format!("[Image: {} ({:.1} KB)]", p.file_name().unwrap_or_default().to_string_lossy(), size as f64 / 1024.0))
+ // `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
+ // that directly inside an `async fn` body would block the tokio
+ // worker thread it's scheduled on, starving every other async
+ // task on that worker (notably re-rendering the import progress
+ // UI, which is what motivated the async conversion in the first
+ // place). `spawn_blocking` moves the work to tokio's blocking
+ // pool where blocking-for-seconds is the contract.
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("read_file", || {
+ let p = Path::new(&path);
+ let ext = p
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ if let Some(cached) = read_cache(p) {
+ return Ok(cached);
}
- e if MEDIA_EXTS.contains(&e) => {
- let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
- Ok(format!("[Media: {} ({:.1} MB)]", p.file_name().unwrap_or_default().to_string_lossy(), size as f64 / 1048576.0))
- }
- e if LEGACY_DOC_EXTS.contains(&e) => {
- Ok(format!("[Document: {} — text extraction not supported for .{} format]",
- p.file_name().unwrap_or_default().to_string_lossy(), e))
- }
- _ => {
- // Deliberate markers for IMAGE / MEDIA / LEGACY_DOC above
- // tell the UI "we know about this format, show a stub".
- // For everything else, a failed read_to_string is really
- // a problem: file missing, locked, corrupt encoding, etc.
- // Return Err so the caller can distinguish "no content"
- // from "successfully read stub text" — the latter used to
- // leak into the editor and overwrite the real file on
- // Milkdown's initial re-emit.
- match fs::read_to_string(&path) {
- Ok(content) => Ok(content),
- Err(e) => {
- let exists = p.exists();
- if !exists {
- Err(format!(
- "File does not exist: '{}'",
- path,
- ))
- } else {
- Err(format!(
- "Failed to read file '{}' as text: {} (likely binary, locked, or non-UTF-8)",
- path, e,
- ))
+
+ match ext.as_str() {
+ "pdf" => extract_pdf_text(&path),
+ 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);
+ Ok(format!("[Image: {} ({:.1} KB)]", p.file_name().unwrap_or_default().to_string_lossy(), size as f64 / 1024.0))
+ }
+ e if MEDIA_EXTS.contains(&e) => {
+ let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
+ Ok(format!("[Media: {} ({:.1} MB)]", p.file_name().unwrap_or_default().to_string_lossy(), size as f64 / 1048576.0))
+ }
+ e if LEGACY_DOC_EXTS.contains(&e) => {
+ Ok(format!("[Document: {} — text extraction not supported for .{} format]",
+ p.file_name().unwrap_or_default().to_string_lossy(), e))
+ }
+ _ => {
+ match fs::read_to_string(&path) {
+ Ok(content) => Ok(content),
+ Err(e) => {
+ let exists = p.exists();
+ if !exists {
+ Err(format!("File does not exist: '{}'", path))
+ } else {
+ Err(format!(
+ "Failed to read file '{}' as text: {} (likely binary, locked, or non-UTF-8)",
+ path, e,
+ ))
+ }
}
}
}
}
- }
+ })
})
+ .await
+ .map_err(|e| format!("read_file blocking task join error: {e}"))?
}
/// Pre-process a file and cache the extracted text.
#[tauri::command]
pub async fn preprocess_file(path: String) -> Result<String, String> {
- run_guarded("preprocess_file", || {
- let p = Path::new(&path);
- let ext = p
- .extension()
- .and_then(|e| e.to_str())
- .unwrap_or("")
- .to_lowercase();
-
- let text = match ext.as_str() {
- "pdf" => extract_pdf_text(&path)?,
- e if OFFICE_EXTS.contains(&e) => extract_office_text(&path, e)?,
- _ => return Ok("no preprocessing needed".to_string()),
- };
+ // See `read_file` above for why `spawn_blocking` is required.
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("preprocess_file", || {
+ let p = Path::new(&path);
+ let ext = p
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ let text = match ext.as_str() {
+ "pdf" => extract_pdf_text(&path)?,
+ e if OFFICE_EXTS.contains(&e) => extract_office_text(&path, e)?,
+ _ => return Ok("no preprocessing needed".to_string()),
+ };
- write_cache(p, &text)?;
- Ok(text)
+ write_cache(p, &text)?;
+ Ok(text)
+ })
})
+ .await
+ .map_err(|e| format!("preprocess_file blocking task join error: {e}"))?
}
fn cache_path_for(original: &Path) -> std::path::PathBuf {
@@ -136,6 +142,33 @@ fn write_cache(original: &Path, text: &str) -> Result<(), String> {
static PDFIUM: std::sync::OnceLock<Result<pdfium_render::prelude::Pdfium, String>> =
std::sync::OnceLock::new();
+/// Serializes every PDFium call. PDFium's C library is documented as
+/// safe across threads only when no PDFium object is touched from
+/// two threads simultaneously — interleaved calls are UB and have
+/// caused EXC_BAD_ACCESS segfaults on macOS ARM64 in production.
+///
+/// This mutex matters because our heavy fs commands are now `async
+/// fn`, so Tauri schedules them on the tokio multi-threaded runtime
+/// instead of running them on a single thread. Without this lock,
+/// two concurrent `read_file`/`extract_*_pdf` calls can land on
+/// different worker threads and interleave inside pdfium → crash.
+///
+/// We use `std::sync::Mutex` (not `tokio::sync::Mutex`) because the
+/// lock is acquired *inside* `spawn_blocking`, never held across
+/// `.await` — async-aware mutexes would just add overhead for no
+/// benefit here.
+static PDFIUM_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+/// Acquire the PDFium serialization lock. Auto-recovers from poison
+/// (a previous panic on a malformed PDF leaves the mutex poisoned,
+/// but pdfium has no shared state for that panic to have corrupted —
+/// the next caller can safely take the lock and proceed).
+pub(crate) fn lock_pdfium() -> std::sync::MutexGuard<'static, ()> {
+ PDFIUM_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
/// Additional resource directory hint, set by the Tauri setup() callback
/// once the AppHandle is available. Lets the pdfium resolver find the
/// bundled dylib without re-implementing Tauri's platform-specific
@@ -275,31 +308,70 @@ 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 `![](url)` 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.
+///
+/// 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> {
- use pdfium_render::prelude::*;
- let pdfium = pdfium()?;
-
- let doc = pdfium
- .load_pdf_from_file(path, None)
- .map_err(|e| match e {
- PdfiumError::PdfiumLibraryInternalError(
- PdfiumInternalError::PasswordError,
- ) => format!(
- "PDF is password-protected and cannot be read: '{}'",
- path
- ),
- _ => format!("Failed to open PDF '{}': {}", path, e),
- })?;
-
- let mut out = String::new();
- for (idx, page) in doc.pages().iter().enumerate() {
- let page_text = page
- .text()
- .map_err(|e| format!("Page {} text extraction failed in '{}': {}", idx + 1, path, e))?;
- out.push_str(&page_text.all());
- out.push('\n');
+ 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 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(),
+ );
+ }
}
- Ok(out)
+
+ // 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())
}
/// Extract text from Office Open XML formats, converting to Markdown.
@@ -820,30 +892,38 @@ fn extract_odf_text(archive: &mut zip::ZipArchive<fs::File>) -> Result<String, S
#[tauri::command]
pub async fn write_file(path: String, contents: String) -> Result<(), String> {
- run_guarded("write_file", || {
- let p = Path::new(&path);
- if let Some(parent) = p.parent() {
- fs::create_dir_all(parent)
- .map_err(|e| format!("Failed to create parent dirs for '{}': {}", path, e))?;
- }
- fs::write(&path, contents)
- .map_err(|e| format!("Failed to write file '{}': {}", path, e))
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("write_file", || {
+ let p = Path::new(&path);
+ if let Some(parent) = p.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create parent dirs for '{}': {}", path, e))?;
+ }
+ fs::write(&path, contents)
+ .map_err(|e| format!("Failed to write file '{}': {}", path, e))
+ })
})
+ .await
+ .map_err(|e| format!("write_file blocking task join error: {e}"))?
}
#[tauri::command]
pub async fn list_directory(path: String) -> Result<Vec<FileNode>, String> {
- run_guarded("list_directory", || {
- let p = Path::new(&path);
- if !p.exists() {
- return Err(format!("Path does not exist: '{}'", path));
- }
- if !p.is_dir() {
- return Err(format!("Path is not a directory: '{}'", path));
- }
- let nodes = build_tree(p, 0, 30)?;
- Ok(nodes)
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("list_directory", || {
+ let p = Path::new(&path);
+ if !p.exists() {
+ return Err(format!("Path does not exist: '{}'", path));
+ }
+ if !p.is_dir() {
+ return Err(format!("Path is not a directory: '{}'", path));
+ }
+ let nodes = build_tree(p, 0, 30)?;
+ Ok(nodes)
+ })
})
+ .await
+ .map_err(|e| format!("list_directory blocking task join error: {e}"))?
}
fn build_tree(dir: &Path, depth: usize, max_depth: usize) -> Result<Vec<FileNode>, String> {
@@ -915,101 +995,114 @@ fn build_tree(dir: &Path, depth: usize, max_depth: usize) -> Result<Vec<FileNode
#[tauri::command]
pub async fn copy_file(source: String, destination: String) -> Result<(), String> {
- run_guarded("copy_file", || {
- let dest = Path::new(&destination);
- if let Some(parent) = dest.parent() {
- fs::create_dir_all(parent)
- .map_err(|e| format!("Failed to create parent dirs: {}", e))?;
- }
- fs::copy(&source, &destination)
- .map_err(|e| format!("Failed to copy '{}' to '{}': {}", source, destination, e))?;
- Ok(())
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("copy_file", || {
+ let dest = Path::new(&destination);
+ if let Some(parent) = dest.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create parent dirs: {}", e))?;
+ }
+ fs::copy(&source, &destination)
+ .map_err(|e| format!("Failed to copy '{}' to '{}': {}", source, destination, e))?;
+ Ok(())
+ })
})
+ .await
+ .map_err(|e| format!("copy_file blocking task join error: {e}"))?
}
/// Recursively copy a directory, preserving structure.
/// Returns list of copied file paths (destination paths).
#[tauri::command]
pub async fn copy_directory(source: String, destination: String) -> Result<Vec<String>, String> {
- run_guarded("copy_directory", || {
- let src = Path::new(&source);
- let dest = Path::new(&destination);
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("copy_directory", || {
+ let src = Path::new(&source);
+ let dest = Path::new(&destination);
- if !src.is_dir() {
- return Err(format!("'{}' is not a directory", source));
- }
+ if !src.is_dir() {
+ return Err(format!("'{}' is not a directory", source));
+ }
- let mut copied_files = Vec::new();
+ let mut copied_files = Vec::new();
- fn copy_recursive(
- src: &Path,
- dest: &Path,
- files: &mut Vec<String>,
- ) -> Result<(), String> {
- fs::create_dir_all(dest)
- .map_err(|e| format!("Failed to create dir '{}': {}", dest.display(), e))?;
+ fn copy_recursive(
+ src: &Path,
+ dest: &Path,
+ files: &mut Vec<String>,
+ ) -> Result<(), String> {
+ fs::create_dir_all(dest)
+ .map_err(|e| format!("Failed to create dir '{}': {}", dest.display(), e))?;
- let entries = fs::read_dir(src)
- .map_err(|e| format!("Failed to read dir '{}': {}", src.display(), e))?;
+ let entries = fs::read_dir(src)
+ .map_err(|e| format!("Failed to read dir '{}': {}", src.display(), e))?;
- for entry in entries {
- let entry = entry.map_err(|e| format!("Dir entry error: {}", e))?;
- let path = entry.path();
- let name = entry.file_name();
- let dest_path = dest.join(&name);
+ for entry in entries {
+ let entry = entry.map_err(|e| format!("Dir entry error: {}", e))?;
+ let path = entry.path();
+ let name = entry.file_name();
+ let dest_path = dest.join(&name);
- // Skip hidden files/dirs
- if name.to_string_lossy().starts_with('.') {
- continue;
- }
+ if name.to_string_lossy().starts_with('.') {
+ continue;
+ }
- if path.is_dir() {
- copy_recursive(&path, &dest_path, files)?;
- } else {
- fs::copy(&path, &dest_path).map_err(|e| {
- format!("Failed to copy '{}': {}", path.display(), e)
- })?;
- // Normalize to forward slashes for consistent cross-
- // platform handling in the TS layer (see fs.rs build_tree).
- files.push(dest_path.to_string_lossy().replace('\\', "/"));
+ if path.is_dir() {
+ copy_recursive(&path, &dest_path, files)?;
+ } else {
+ fs::copy(&path, &dest_path).map_err(|e| {
+ format!("Failed to copy '{}': {}", path.display(), e)
+ })?;
+ files.push(dest_path.to_string_lossy().replace('\\', "/"));
+ }
}
+ Ok(())
}
- Ok(())
- }
- copy_recursive(src, dest, &mut copied_files)?;
- Ok(copied_files)
+ copy_recursive(src, dest, &mut copied_files)?;
+ Ok(copied_files)
+ })
})
+ .await
+ .map_err(|e| format!("copy_directory blocking task join error: {e}"))?
}
#[tauri::command]
pub async fn delete_file(path: String) -> Result<(), String> {
- run_guarded("delete_file", || {
- let p = Path::new(&path);
- if p.is_dir() {
- fs::remove_dir_all(&path)
- .map_err(|e| format!("Failed to delete directory '{}': {}", path, e))
- } else {
- fs::remove_file(&path)
- .map_err(|e| format!("Failed to delete file '{}': {}", path, e))
- }
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("delete_file", || {
+ let p = Path::new(&path);
+ if p.is_dir() {
+ fs::remove_dir_all(&path)
+ .map_err(|e| format!("Failed to delete directory '{}': {}", path, e))
+ } else {
+ fs::remove_file(&path)
+ .map_err(|e| format!("Failed to delete file '{}': {}", path, e))
+ }
+ })
})
+ .await
+ .map_err(|e| format!("delete_file blocking task join error: {e}"))?
}
/// Find wiki pages that reference a given source file name.
/// Scans all .md files under wiki/ for the source filename in frontmatter or content.
#[tauri::command]
pub async fn find_related_wiki_pages(project_path: String, source_name: String) -> Result<Vec<String>, String> {
- run_guarded("find_related_wiki_pages", || {
- let wiki_dir = Path::new(&project_path).join("wiki");
- if !wiki_dir.is_dir() {
- return Ok(vec![]);
- }
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("find_related_wiki_pages", || {
+ let wiki_dir = Path::new(&project_path).join("wiki");
+ if !wiki_dir.is_dir() {
+ return Ok(vec![]);
+ }
- let mut related = Vec::new();
- collect_related_pages(&wiki_dir, &source_name, &mut related)?;
- Ok(related)
+ let mut related = Vec::new();
+ collect_related_pages(&wiki_dir, &source_name, &mut related)?;
+ Ok(related)
+ })
})
+ .await
+ .map_err(|e| format!("find_related_wiki_pages blocking task join error: {e}"))?
}
fn collect_related_pages(dir: &Path, source_name: &str, results: &mut Vec<String>) -> Result<(), String> {
@@ -1129,17 +1222,83 @@ fn collect_related_pages(dir: &Path, source_name: &str, results: &mut Vec<String
#[tauri::command]
pub async fn create_directory(path: String) -> Result<(), String> {
- run_guarded("create_directory", || {
- fs::create_dir_all(&path)
- .map_err(|e| format!("Failed to create directory '{}': {}", path, e))
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("create_directory", || {
+ fs::create_dir_all(&path)
+ .map_err(|e| format!("Failed to create directory '{}': {}", path, e))
+ })
+ })
+ .await
+ .map_err(|e| format!("create_directory blocking task join error: {e}"))?
+}
+
+/// Read any file as base64 + a guessed mime type. Used by the
+/// vision-caption pipeline to slurp extracted image bytes off disk
+/// without round-tripping them through the JS string-as-UTF8 path
+/// (`read_file` would corrupt PNG bytes — they aren't valid UTF-8).
+///
+/// Mime detection is by extension only — the caption helper doesn't
+/// care about exact accuracy (vision models accept any common
+/// raster format), and the alternative (sniffing magic bytes via
+/// `infer` or similar) adds a dependency for marginal benefit.
+/// Unknown extensions fall back to `application/octet-stream`,
+/// which all major vision endpoints accept (Anthropic / OpenAI both
+/// also support that as a generic fallback).
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FileBase64 {
+ pub base64: String,
+ pub mime_type: String,
+}
+
+#[tauri::command]
+pub async fn read_file_as_base64(path: String) -> Result<FileBase64, String> {
+ use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("read_file_as_base64", || {
+ let bytes = fs::read(&path)
+ .map_err(|e| format!("Failed to read '{}': {}", path, e))?;
+ let p = Path::new(&path);
+ let ext = p
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or("")
+ .to_ascii_lowercase();
+ let mime_type = match ext.as_str() {
+ "png" => "image/png",
+ "jpg" | "jpeg" => "image/jpeg",
+ "gif" => "image/gif",
+ "webp" => "image/webp",
+ "bmp" => "image/bmp",
+ "tiff" | "tif" => "image/tiff",
+ "svg" => "image/svg+xml",
+ _ => "application/octet-stream",
+ }
+ .to_string();
+ Ok(FileBase64 {
+ base64: B64.encode(&bytes),
+ mime_type,
+ })
+ })
})
+ .await
+ .map_err(|e| format!("read_file_as_base64 blocking task join error: {e}"))?
}
/// Cheap existence check without reading or classifying the file.
/// Returns true iff `path` refers to something on disk right now.
#[tauri::command]
pub async fn file_exists(path: String) -> Result<bool, String> {
- run_guarded("file_exists", || Ok(Path::new(&path).exists()))
+ // `Path::exists()` does a `stat(2)` syscall — fast on a hot
+ // cache, but a blocking syscall nonetheless. Wrapping it keeps
+ // the rule "no sync IO on tokio worker threads" uniform across
+ // every fs command rather than carving out an exception that's
+ // easy to violate later.
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("file_exists", || Ok(Path::new(&path).exists()))
+ })
+ .await
+ .map_err(|e| format!("file_exists blocking task join error: {e}"))?
}
#[cfg(test)]
@@ -1167,8 +1326,15 @@ mod tests {
/// We try a handful of payloads that have historically caused
/// pdf-extract/lopdf panics — any process abort would fail the test
/// runner before it can report.
- #[test]
- fn read_file_survives_malformed_pdf_inputs() {
+ ///
+ /// `multi_thread` flavor: `read_file` now uses
+ /// `tauri::async_runtime::spawn_blocking`, which moves work onto
+ /// the tokio blocking pool. The blocking pool requires a multi-
+ /// threaded runtime — the default `#[tokio::test]` is single-
+ /// threaded current-thread, on which `.await` of a `spawn_blocking`
+ /// future deadlocks.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn read_file_survives_malformed_pdf_inputs() {
let payloads: &[(&str, &[u8])] = &[
("empty", b""),
("not_a_pdf", b"this is plainly not a PDF file"),
@@ -1185,9 +1351,7 @@ mod tests {
for (name, bytes) in payloads {
let path = tmp_pdf_with_bytes(bytes);
- // Either Ok(...) or Err(...) is acceptable — what matters is
- // that no panic reaches the test runner and aborts the process.
- let result = read_file(path.clone());
+ let result = read_file(path.clone()).await;
let _ = fs::remove_file(&path);
eprintln!("[{name}] => {:?}", result.as_ref().map(|s| &s[..s.len().min(80)]));
}
@@ -1197,11 +1361,9 @@ mod tests {
/// guarantee that any particular byte sequence above actually panics
/// pdf-extract across versions, so also trigger an explicit panic
/// through read_file's guarded path.
- #[test]
- fn read_file_returns_err_on_missing_file_instead_of_panicking() {
- // This won't panic, but confirms the error path is the Err path,
- // not a runtime abort.
- let result = read_file("/nonexistent/path/that/does/not/exist.pdf".to_string());
+ #[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;
assert!(result.is_err() || result.is_ok()); // must at least return
}
@@ -1484,4 +1646,162 @@ mod tests {
assert_eq!(got, vec!["concepts/rope.md"]);
let _ = fs::remove_dir_all(&wiki);
}
+
+ // ── copy_directory: folder import recursion + filtering ──────────
+ //
+ // The folder-import flow on the JS side calls this command and
+ // expects:
+ // 1. Recursion goes ALL the way down (no depth cap) — users
+ // drop trees with arbitrary nesting and every file inside
+ // should reach the wiki.
+ // 2. Dotfiles / dot-directories are skipped (`.git`, `.cache`,
+ // `.DS_Store`) — otherwise a folder with a `.git/` would
+ // import megabytes of git plumbing as "source files."
+ // 3. Returned paths are FLAT (one entry per file, regardless
+ // of depth) and use forward slashes (the JS layer normalizes
+ // everything to `/` before doing path comparisons).
+ //
+ // These are exactly the invariants `handleImportFolder` in
+ // sources-view.tsx assumes — pinning them here keeps a future
+ // refactor of the recursive copier from silently breaking the
+ // folder import button.
+
+ fn make_temp_dir(label: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "llmwiki-copydir-{label}-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ /// Pull the inner sync `copy_recursive` body out from
+ /// `copy_directory` so the test doesn't need to spin up a
+ /// tokio runtime just to exercise file-system recursion.
+ /// Mirrors the same logic the async command uses.
+ fn copy_dir_for_test(src: &Path, dest: &Path) -> Vec<String> {
+ std::fs::create_dir_all(dest).unwrap();
+ let mut out = Vec::new();
+ fn rec(src: &Path, dest: &Path, files: &mut Vec<String>) {
+ std::fs::create_dir_all(dest).unwrap();
+ for entry in std::fs::read_dir(src).unwrap().flatten() {
+ let path = entry.path();
+ let name = entry.file_name();
+ let dest_path = dest.join(&name);
+ if name.to_string_lossy().starts_with('.') {
+ continue;
+ }
+ if path.is_dir() {
+ rec(&path, &dest_path, files);
+ } else {
+ std::fs::copy(&path, &dest_path).unwrap();
+ files.push(dest_path.to_string_lossy().replace('\\', "/"));
+ }
+ }
+ }
+ rec(src, dest, &mut out);
+ out
+ }
+
+ #[test]
+ fn copy_directory_recurses_arbitrary_depth() {
+ let src = make_temp_dir("src-deep");
+ // Build /src/a/b/c/d/e/leaf.txt — five levels under root.
+ let leaf_dir = src.join("a/b/c/d/e");
+ std::fs::create_dir_all(&leaf_dir).unwrap();
+ std::fs::write(leaf_dir.join("leaf.txt"), b"deep content").unwrap();
+ // Plus a top-level file to ensure root files come along too.
+ std::fs::write(src.join("top.md"), b"# top").unwrap();
+
+ let dest = make_temp_dir("dest-deep");
+ let copied = copy_dir_for_test(&src, &dest);
+
+ assert_eq!(copied.len(), 2, "expected two files, got: {:?}", copied);
+ // Deep file made it across with full nesting preserved.
+ let leaf_dest = dest.join("a/b/c/d/e/leaf.txt");
+ assert!(leaf_dest.exists(), "deep leaf.txt missing at {:?}", leaf_dest);
+ assert_eq!(std::fs::read(&leaf_dest).unwrap(), b"deep content");
+ // Top-level file too.
+ assert!(dest.join("top.md").exists());
+ // Returned paths are forward-slashed and absolute.
+ for p in &copied {
+ assert!(!p.contains('\\'), "path should be /-normalized: {p}");
+ assert!(Path::new(p).is_absolute(), "path should be absolute: {p}");
+ }
+
+ let _ = std::fs::remove_dir_all(&src);
+ let _ = std::fs::remove_dir_all(&dest);
+ }
+
+ #[test]
+ fn copy_directory_skips_dotfiles_and_dot_directories() {
+ let src = make_temp_dir("src-dots");
+ // Visible content:
+ std::fs::write(src.join("keep.md"), b"keep me").unwrap();
+ std::fs::create_dir_all(src.join("subdir")).unwrap();
+ std::fs::write(src.join("subdir/keep2.md"), b"keep me too").unwrap();
+ // Things that must be skipped:
+ std::fs::write(src.join(".DS_Store"), b"junk").unwrap();
+ std::fs::create_dir_all(src.join(".git/objects")).unwrap();
+ std::fs::write(src.join(".git/HEAD"), b"ref: refs/heads/main").unwrap();
+ std::fs::write(src.join(".git/objects/abc"), b"\x78\x9c").unwrap();
+ std::fs::write(src.join(".env"), b"SECRET=foo").unwrap();
+ // Sneaky one: a dot-prefixed dir nested inside a normal dir
+ // should ALSO be skipped (the dotfile rule applies at every
+ // recursion level, not just the top).
+ std::fs::create_dir_all(src.join("subdir/.cache")).unwrap();
+ std::fs::write(src.join("subdir/.cache/blob"), b"cache").unwrap();
+
+ let dest = make_temp_dir("dest-dots");
+ let copied = copy_dir_for_test(&src, &dest);
+
+ assert_eq!(
+ copied.len(),
+ 2,
+ "should copy only the 2 visible files, got: {:?}",
+ copied,
+ );
+ assert!(dest.join("keep.md").exists());
+ assert!(dest.join("subdir/keep2.md").exists());
+ // Dot-stuff must NOT be on disk in the destination.
+ assert!(!dest.join(".DS_Store").exists());
+ assert!(!dest.join(".git").exists());
+ assert!(!dest.join(".env").exists());
+ assert!(!dest.join("subdir/.cache").exists());
+
+ let _ = std::fs::remove_dir_all(&src);
+ let _ = std::fs::remove_dir_all(&dest);
+ }
+
+ #[test]
+ fn copy_directory_returns_flat_list_with_forward_slashes() {
+ let src = make_temp_dir("src-flat");
+ std::fs::create_dir_all(src.join("year/2024/q3")).unwrap();
+ std::fs::write(src.join("year/2024/q3/report.pdf"), b"%PDF-fake").unwrap();
+ std::fs::write(src.join("year/2024/notes.md"), b"# notes").unwrap();
+
+ let dest = make_temp_dir("dest-flat");
+ let copied = copy_dir_for_test(&src, &dest);
+
+ // Both files in the flat list, ordered by file-system traversal
+ // (we don't care about exact order, but every entry must be
+ // forward-slashed and end with the expected filename).
+ let names: Vec<String> = copied
+ .iter()
+ .map(|p| Path::new(p).file_name().unwrap().to_string_lossy().to_string())
+ .collect();
+ assert!(names.contains(&"report.pdf".to_string()));
+ assert!(names.contains(&"notes.md".to_string()));
+ assert_eq!(copied.len(), 2);
+ for p in &copied {
+ assert!(p.contains('/'), "should contain at least one /: {p}");
+ assert!(!p.contains('\\'), "should NOT contain \\: {p}");
+ }
+
+ let _ = std::fs::remove_dir_all(&src);
+ let _ = std::fs::remove_dir_all(&dest);
+ }
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index f1b7d12e..c3e6393c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -50,6 +50,7 @@ pub fn run() {
commands::fs::find_related_wiki_pages,
commands::fs::create_directory,
commands::fs::file_exists,
+ commands::fs::read_file_as_base64,
commands::project::create_project,
commands::project::open_project,
clip_server_status,
diff --git a/src/App.tsx b/src/App.tsx
index 7069e1c7..82e9ba90 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,7 +5,7 @@ import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
import { useChatStore } from "@/stores/chat-store"
import { listDirectory, openProject } from "@/commands/fs"
-import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId } from "@/lib/project-store"
+import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId } from "@/lib/project-store"
import { loadReviewItems, loadChatHistory } from "@/lib/persist"
import { setupAutoSave } from "@/lib/auto-save"
import { startClipWatcher } from "@/lib/clip-watcher"
@@ -122,6 +122,10 @@ function App() {
if (savedEmbeddingConfig) {
useWikiStore.getState().setEmbeddingConfig(savedEmbeddingConfig)
}
+ const savedMultimodalConfig = await loadMultimodalConfig()
+ if (savedMultimodalConfig) {
+ useWikiStore.getState().setMultimodalConfig(savedMultimodalConfig)
+ }
const savedOutputLang = await loadOutputLanguage()
if (savedOutputLang) {
useWikiStore.getState().setOutputLanguage(savedOutputLang)
diff --git a/src/commands/fs.ts b/src/commands/fs.ts
index cb53b0e4..bc0ac9e5 100644
--- a/src/commands/fs.ts
+++ b/src/commands/fs.ts
@@ -50,6 +50,22 @@ export async function fileExists(path: string): Promise<boolean> {
return invoke<boolean>("file_exists", { path })
}
+/** Mirror of `commands::fs::FileBase64` (Rust side). */
+export interface FileBase64 {
+ base64: string
+ mimeType: string
+}
+
+/**
+ * Read any file off disk as base64 + a guessed mime type. The
+ * vision-caption pipeline uses this to pick up extracted images
+ * without having to read them as UTF-8 strings (PNG bytes aren't
+ * valid UTF-8 — `readFile` would corrupt them).
+ */
+export async function readFileAsBase64(path: string): Promise<FileBase64> {
+ return invoke<FileBase64>("read_file_as_base64", { path })
+}
+
export async function createProject(
name: string,
path: string,
diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsx
index 359474da..d84e1786 100644
--- a/src/components/chat/chat-message.tsx
+++ b/src/components/chat/chat-message.tsx
@@ -7,6 +7,7 @@ import "katex/dist/katex.min.css"
import {
Bot, User, FileText, BookmarkPlus, ChevronDown, ChevronRight, RefreshCw, Copy, Check,
Users, Lightbulb, BookOpen, HelpCircle, GitMerge, BarChart3, Layout, Globe,
+ Image as ImageIcon,
} from "lucide-react"
import { useWikiStore } from "@/stores/wiki-store"
import { readFile, writeFile, listDirectory } from "@/commands/fs"
@@ -18,6 +19,7 @@ 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"
+import { findRawSourceForImage, imageUrlToAbsolute } from "@/lib/raw-source-resolver"
// Module-level cache of source file names
let cachedSourceFiles: string[] = []
@@ -286,10 +288,41 @@ function getRefType(path: string): string {
return "source"
}
+/**
+ * Markdown image-reference regex used to count `![](url)` occurrences
+ * in cited pages AND extract the first URL (so the image-badge
+ * jump button knows where to send the user). Same shape as the
+ * search/pipeline regex elsewhere (kept duplicated to avoid
+ * coupling — this module never wants to pull caption-pipeline
+ * imports for a 3-character count).
+ *
+ * Group 1 captures the URL (everything inside `(...)` of the
+ * markdown image syntax, no whitespace).
+ */
+const CITED_IMAGE_RE = /!\[[^\]]*\]\(([^)\s]+)\)/g
+
+interface CitedImageInfo {
+ count: number
+ /** First image URL on the page — used as the scroll target when
+ * the badge button opens the raw source. Null when count===0. */
+ firstUrl: string | null
+}
+
function CitedReferencesPanel({ content, savedReferences }: { content: string; savedReferences?: CitedPage[] }) {
const project = useWikiStore((s) => s.project)
const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
+ const setFileContent = useWikiStore((s) => s.setFileContent)
+ const setPendingScrollImageSrc = useWikiStore((s) => s.setPendingScrollImageSrc)
const [expanded, setExpanded] = useState(false)
+ /**
+ * Per-cited-page image info: count + first image URL. We can't
+ * hang this off `CitedPage` directly because `extractCitedPages`
+ * is sync and works on the AI's text response, never seeing the
+ * underlying page. So we fetch the page contents lazily here.
+ * Same path → same info, so a tiny in-component map keyed by
+ * path is plenty.
+ */
+ const [imageInfos, setImageInfos] = useState<Record<string, CitedImageInfo>>({})
// Use saved references first (persisted with message), fall back to dynamic extraction
const citedPages = useMemo(() => {
@@ -297,6 +330,100 @@ function CitedReferencesPanel({ content, savedReferences }: { content: string; s
return extractCitedPages(content)
}, [content, savedReferences])
+ // Async-fetch each cited page's content once and extract image
+ // info: count + first URL. Done in parallel; failures are
+ // silently treated as { count: 0, firstUrl: null } (page may
+ // not exist on disk yet, e.g. a citation the LLM hallucinated).
+ useEffect(() => {
+ if (!project || citedPages.length === 0) return
+ const pp = normalizePath(project.path)
+ let cancelled = false
+ Promise.all(
+ citedPages.map(async (page) => {
+ // Try the path verbatim first, then the same fallback set
+ // the click-handler uses below — keeps "is the file on
+ // disk" check consistent across the panel.
+ const id = getFileName(page.path.replace(/^wiki\//, "").replace(/\.md$/, ""))
+ const candidates = [
+ `${pp}/${page.path}`,
+ `${pp}/wiki/entities/${id}.md`,
+ `${pp}/wiki/concepts/${id}.md`,
+ `${pp}/wiki/sources/${id}.md`,
+ `${pp}/wiki/queries/${id}.md`,
+ `${pp}/wiki/synthesis/${id}.md`,
+ `${pp}/wiki/comparisons/${id}.md`,
+ `${pp}/wiki/${id}.md`,
+ ]
+ for (const candidate of candidates) {
+ try {
+ const text = await readFile(candidate)
+ // Reset stateful regex.lastIndex by `new RegExp(...)` —
+ // module-level `g` regexes carry state across calls
+ // and would skip matches on the second invocation.
+ const re = new RegExp(CITED_IMAGE_RE.source, CITED_IMAGE_RE.flags)
+ const matches = [...text.matchAll(re)]
+ const info: CitedImageInfo = {
+ count: matches.length,
+ firstUrl: matches.length > 0 ? matches[0][1] : null,
+ }
+ return [page.path, info] as const
+ } catch {
+ // try next candidate
+ }
+ }
+ return [page.path, { count: 0, firstUrl: null }] as const
+ }),
+ ).then((entries) => {
+ if (cancelled) return
+ const next: Record<string, CitedImageInfo> = {}
+ for (const [path, info] of entries) next[path] = info
+ setImageInfos(next)
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [project, citedPages])
+
+ /**
+ * Open the raw source file for a page's first image and stage a
+ * scroll target so the markdown preview lands on that image.
+ * Mirrors the lightbox "Jump to source document" path in
+ * search-view — same `findRawSourceForImage` resolver, same
+ * `pendingScrollImageSrc` store handoff, same fallback to
+ * opening the wiki page when no raw source is found.
+ */
+ const handleJumpToImageSource = useCallback(
+ async (firstUrl: string, fallbackPath: string) => {
+ if (!project) return
+ const pp = normalizePath(project.path)
+ const rawPath = await findRawSourceForImage(firstUrl, pp)
+ if (rawPath) {
+ try {
+ const content = await readFile(rawPath)
+ setPendingScrollImageSrc(imageUrlToAbsolute(firstUrl, pp))
+ setSelectedFile(rawPath)
+ setFileContent(content)
+ console.log(`[refs:image-jump] ${firstUrl} → raw source ${rawPath}`)
+ return
+ } catch (err) {
+ console.warn(`[refs:image-jump] failed to read ${rawPath}:`, err)
+ }
+ }
+ // Fallback: open the wiki summary itself with same scroll
+ // target — at least the safety-net section will scroll into
+ // view there.
+ try {
+ const content = await readFile(`${pp}/${fallbackPath}`)
+ setPendingScrollImageSrc(firstUrl)
+ setSelectedFile(`${pp}/${fallbackPath}`)
+ setFileContent(content)
+ } catch (err) {
+ console.warn(`[refs:image-jump] fallback also failed:`, err)
+ }
+ },
+ [project, setPendingScrollImageSrc, setSelectedFile, setFileContent],
+ )
+
if (citedPages.length === 0) return null
const MAX_COLLAPSED = 3
@@ -323,44 +450,78 @@ function CitedReferencesPanel({ content, savedReferences }: { content: string; s
const refType = getRefType(page.path)
const config = REF_TYPE_CONFIG[refType] ?? REF_TYPE_CONFIG.source
const Icon = config.icon
+ const info = imageInfos[page.path]
+ const hasImages = (info?.count ?? 0) > 0
+ const openCitedPage = async () => {
+ if (!project) return
+ const pp = normalizePath(project.path)
+ const id = getFileName(page.path.replace(/^wiki\//, "").replace(/\.md$/, ""))
+ const candidates = [
+ `${pp}/${page.path}`,
+ `${pp}/wiki/entities/${id}.md`,
+ `${pp}/wiki/concepts/${id}.md`,
+ `${pp}/wiki/sources/${id}.md`,
+ `${pp}/wiki/queries/${id}.md`,
+ `${pp}/wiki/synthesis/${id}.md`,
+ `${pp}/wiki/comparisons/${id}.md`,
+ `${pp}/wiki/${id}.md`,
+ ]
+ for (const candidate of candidates) {
+ try {
+ await readFile(candidate)
+ setSelectedFile(candidate)
+ return
+ } catch {
+ // try next
+ }
+ }
+ setSelectedFile(`${pp}/${page.path}`)
+ }
return (
- <button
+ // Outer is a div, NOT a button — we have two click
+ // targets inside (image badge + main row) and nesting
+ // a button inside a button is invalid HTML and breaks
+ // event delegation. Hover effect shifts to the inner
+ // buttons individually so each gives feedback.
+ <div
key={page.path}
- type="button"
- onClick={async () => {
- if (!project) return
- const pp = normalizePath(project.path)
- // Try the given path first, then search all wiki subdirectories
- const id = getFileName(page.path.replace(/^wiki\//, "").replace(/\.md$/, ""))
- const candidates = [
- `${pp}/${page.path}`,
- `${pp}/wiki/entities/${id}.md`,
- `${pp}/wiki/concepts/${id}.md`,
- `${pp}/wiki/sources/${id}.md`,
- `${pp}/wiki/queries/${id}.md`,
- `${pp}/wiki/synthesis/${id}.md`,
- `${pp}/wiki/comparisons/${id}.md`,
- `${pp}/wiki/${id}.md`,
- ]
- for (const candidate of candidates) {
- try {
- await readFile(candidate)
- setSelectedFile(candidate)
- return
- } catch {
- // try next
- }
- }
- // Last resort: set the original path anyway
- setSelectedFile(`${pp}/${page.path}`)
- }}
- className="flex w-full items-center gap-1.5 rounded px-1 py-0.5 text-left hover:bg-accent/50 transition-colors"
+ className="flex w-full items-center gap-1.5 rounded text-left"
title={page.path}
>
<span className="text-[10px] text-muted-foreground/60 w-4 shrink-0 text-right">[{i + 1}]</span>
- <Icon className={`h-3 w-3 shrink-0 ${config.color}`} />
- <span className="truncate text-foreground/80">{page.title}</span>
- </button>
+ {/*
+ * Image badge — clickable, separately from the page
+ * row. Click → resolve the FIRST image's raw source
+ * (`raw/sources/<slug>.<ext>`) and open the FULL
+ * combined-extraction preview, scrolled to that
+ * image. This mirrors the search-view lightbox
+ * "Jump to source document" behavior so the two
+ * surfaces feel consistent.
+ *
+ * Icon: lucide `Image` (picture-frame outline with
+ * mountain + sun) — direct visual cue for "image",
+ * NOT `Camera` which reads as "take a photo".
+ */}
+ {hasImages && info?.firstUrl && (
+ <button
+ type="button"
+ onClick={() => handleJumpToImageSource(info.firstUrl!, page.path)}
+ className="flex shrink-0 items-center gap-0.5 rounded px-1 py-0.5 text-[10px] text-blue-600 hover:bg-blue-100/40 dark:text-blue-400 dark:hover:bg-blue-900/30 transition-colors"
+ title={`Open original document at first image (${info.count} image${info.count === 1 ? "" : "s"} on this page)`}
+ >
+ <ImageIcon className="h-3 w-3" />
+ {info.count}
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={openCitedPage}
+ className="flex min-w-0 flex-1 items-center gap-1.5 rounded px-1 py-0.5 text-left hover:bg-accent/50 transition-colors"
+ >
+ <Icon className={`h-3 w-3 shrink-0 ${config.color}`} />
+ <span className="truncate text-foreground/80">{page.title}</span>
+ </button>
+ </div>
)
})}
{hasMore && !expanded && (
diff --git a/src/components/editor/file-preview.tsx b/src/components/editor/file-preview.tsx
index 0b6ffe01..550a7764 100644
--- a/src/components/editor/file-preview.tsx
+++ b/src/components/editor/file-preview.tsx
@@ -1,3 +1,4 @@
+import { useEffect, useRef } from "react"
import { convertFileSrc } from "@tauri-apps/api/core"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
@@ -114,8 +115,66 @@ 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)
+ const pendingScrollImageSrc = useWikiStore((s) => s.pendingScrollImageSrc)
+ const setPendingScrollImageSrc = useWikiStore((s) => s.setPendingScrollImageSrc)
+ const scrollRootRef = useRef<HTMLDivElement | null>(null)
+
+ // Consume `pendingScrollImageSrc` once the file has rendered.
+ // We re-scan the DOM whenever:
+ // - file content changes (different page just loaded), OR
+ // - the pending target changes (user clicked a different image)
+ // Image loading is async, so we also subscribe to `load` events
+ // and rescroll once the actual layout settles — the first
+ // `scrollIntoView` lands on a 0-height placeholder otherwise.
+ useEffect(() => {
+ if (!pendingScrollImageSrc) return
+ const root = scrollRootRef.current
+ if (!root) return
+ // Match by `data-mdsrc` (literal markdown URL) — the post-
+ // resolver `src` is a tauri:// URL we don't want to bake into
+ // the search-result data.
+ // Inline-escape `"` and `\` for the attribute-VALUE position
+ // of a CSS selector (CSS.escape is for IDENTIFIER context and
+ // would over-escape here). Image URLs can in principle contain
+ // either, so doing this is correctness, not paranoia.
+ const escapedSrc = pendingScrollImageSrc
+ .replace(/\\/g, "\\\\")
+ .replace(/"/g, '\\"')
+ const target = root.querySelector<HTMLImageElement>(
+ `img[data-mdsrc="${escapedSrc}"]`,
+ )
+ if (!target) {
+ // Page may not actually contain this image — clear the
+ // pending so a future page-open doesn't get an unexpected
+ // scroll. Fail silently: the user navigated, we just don't
+ // know where to send them.
+ setPendingScrollImageSrc(null)
+ return
+ }
+ // Initial scroll. The image may not have loaded its bytes yet
+ // (lazy loading + remote PNG decode) so this lands on a
+ // 0-height box. After load, recompute.
+ target.scrollIntoView({ behavior: "auto", block: "center" })
+ if (!target.complete) {
+ const onLoad = () => {
+ target.scrollIntoView({ behavior: "smooth", block: "center" })
+ target.removeEventListener("load", onLoad)
+ }
+ target.addEventListener("load", onLoad)
+ }
+ // Briefly highlight the target so the user sees where they
+ // landed — the page might be long and the image might be in
+ // a section visually similar to its neighbors.
+ target.classList.add("ring-2", "ring-primary", "ring-offset-2")
+ const tHighlight = setTimeout(() => {
+ target.classList.remove("ring-2", "ring-primary", "ring-offset-2")
+ }, 1800)
+ setPendingScrollImageSrc(null)
+ return () => clearTimeout(tHighlight)
+ }, [pendingScrollImageSrc, content, setPendingScrollImageSrc])
+
return (
- <div className="h-full overflow-auto p-6">
+ <div ref={scrollRootRef} className="h-full overflow-auto p-6">
<div className="mb-2 flex items-center gap-2 text-xs text-muted-foreground">
<span>{filePath}</span>
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase">{label}</span>
@@ -129,11 +188,18 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:
// ingest image-extraction step. Without this, the
// browser tries to load `media/...` relative to the
// webview origin and silently 404s.
+ //
+ // `data-mdsrc` preserves the ORIGINAL markdown URL
+ // (pre-resolver) so the search-result jump-to-image
+ // path can find the rendered <img> by its source-of-
+ // truth identifier rather than the resolved tauri://
+ // URL (which differs per platform).
img: ({ src, alt, ...props }) => (
<img
src={typeof src === "string" ? resolveMarkdownImageSrc(src, projectPath) : undefined}
+ data-mdsrc={typeof src === "string" ? src : undefined}
alt={alt ?? ""}
- className="max-w-full rounded border border-border/40"
+ className="max-w-full rounded border border-border/40 transition-all"
loading="lazy"
{...props}
/>
diff --git a/src/components/search/search-view.tsx b/src/components/search/search-view.tsx
index bcdc3725..ddf2bd2f 100644
--- a/src/components/search/search-view.tsx
+++ b/src/components/search/search-view.tsx
@@ -1,10 +1,28 @@
-import { useState, useCallback } from "react"
-import { Search, FileText } from "lucide-react"
+import { useState, useCallback, useMemo, useEffect } from "react"
+import { Search, FileText, ImageIcon, X, ArrowUpRight } from "lucide-react"
import { useWikiStore } from "@/stores/wiki-store"
import { readFile } from "@/commands/fs"
-import { searchWiki, type SearchResult } from "@/lib/search"
+import { searchWiki, tokenizeQuery, type SearchResult, type ImageRef } from "@/lib/search"
import { useTranslation } from "react-i18next"
import { normalizePath } from "@/lib/path-utils"
+import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"
+import { findRawSourceForImage, imageUrlToAbsolute } from "@/lib/raw-source-resolver"
+
+/**
+ * One image hit displayed in the Images section.
+ *
+ * `sourcePath` is the wiki page that contains this image reference
+ * — clicking the card opens that page (and the page's markdown
+ * preview will scroll the user down to the image naturally).
+ *
+ * `altMatchesQuery` is whether the caption / alt text matches the
+ * query. Used only for ordering: caption matches sort first.
+ */
+interface ImageHit extends ImageRef {
+ sourcePath: string
+ sourceTitle: string
+ altMatchesQuery: boolean
+}
export function SearchView() {
const { t } = useTranslation()
@@ -12,11 +30,18 @@ export function SearchView() {
const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
const setFileContent = useWikiStore((s) => s.setFileContent)
const setActiveView = useWikiStore((s) => s.setActiveView)
+ const setPendingScrollImageSrc = useWikiStore((s) => s.setPendingScrollImageSrc)
const [query, setQuery] = useState("")
const [results, setResults] = useState<SearchResult[]>([])
const [searching, setSearching] = useState(false)
const [hasSearched, setHasSearched] = useState(false)
+ // Lightbox state — null when closed. Held inline rather than via
+ // a global store: nothing else needs to know which image is in
+ // the lightbox, and search-view-local state means the modal
+ // closes naturally when the user navigates away from search.
+ const [lightbox, setLightbox] = useState<ImageHit | null>(null)
+
const doSearch = useCallback(
async (q: string) => {
if (!project || !q.trim()) {
@@ -38,10 +63,61 @@ export function SearchView() {
[project],
)
- async function handleOpen(result: SearchResult) {
+ // Flatten + dedupe images across results. Two results referencing
+ // the same image (e.g. the source-summary AND a concept page that
+ // cited the figure) collapse to one card; we keep the FIRST
+ // result we saw it in as the click target since results are
+ // already sorted by RRF descending.
+ //
+ // Caption matching uses the SAME tokenizer the main search uses
+ // (`tokenizeQuery`), not raw substring containment. Without this
+ // a query like "总资产。" wouldn't match the caption "图:2023
+ // 年总资产合计" — the trailing 。 has no business in a substring
+ // test against alt text that doesn't end at that exact spot.
+ // Falls back to the raw lowercased query when tokenization
+ // returns nothing (e.g. user typed only punctuation), so the
+ // filter never silently goes empty when the user expected hits.
+ const imageHits = useMemo(() => {
+ if (!query.trim()) return [] as ImageHit[]
+ const tokens = tokenizeQuery(query)
+ const fallback = query.trim().toLowerCase()
+ const seen = new Set<string>()
+ const out: ImageHit[] = []
+ for (const r of results) {
+ for (const img of r.images) {
+ if (seen.has(img.url)) continue
+ seen.add(img.url)
+ const altLower = img.alt.toLowerCase()
+ const altMatchesQuery =
+ tokens.length > 0
+ ? tokens.some((t) => altLower.includes(t))
+ : altLower.includes(fallback)
+ out.push({
+ ...img,
+ sourcePath: r.path,
+ sourceTitle: r.title,
+ altMatchesQuery,
+ })
+ }
+ }
+ // Caption-matches first, then preserve RRF order.
+ return out.sort((a, b) => Number(b.altMatchesQuery) - Number(a.altMatchesQuery))
+ }, [results, query])
+
+ // Image hits whose CAPTION matches the query are the ones we
+ // confidently surface. Hits from matched pages whose alt text
+ // doesn't match the query are "supporting" (visible after a
+ // toggle) — showing them ALL by default would dilute the image
+ // grid with logos / page-corner decorations.
+ const [showSupportingImages, setShowSupportingImages] = useState(false)
+ const matchingImages = imageHits.filter((h) => h.altMatchesQuery)
+ const supportingImages = imageHits.filter((h) => !h.altMatchesQuery)
+ const visibleImages = showSupportingImages ? imageHits : matchingImages
+
+ async function handleOpen(path: string) {
try {
- const content = await readFile(result.path)
- setSelectedFile(result.path)
+ const content = await readFile(path)
+ setSelectedFile(path)
setFileContent(content)
setActiveView("wiki")
} catch (err) {
@@ -49,6 +125,65 @@ export function SearchView() {
}
}
+ /**
+ * Lightbox jump-to-source: open the ORIGINAL raw source file
+ * (the PDF / DOCX / PPTX in `raw/sources/`), not the LLM-
+ * summarized `wiki/sources/<slug>.md`. The wiki summary is
+ * abbreviated by design — the user's mental model when they
+ * click a search-result image is "show me where this came
+ * from in the actual document," and that's the raw file.
+ *
+ * Path derivation: image URLs always live under
+ * `<project>/wiki/media/<slug>/img-N.<ext>`. The slug matches
+ * the basename of the original raw source (we wrote it that
+ * way at extraction time in extract_pdf_markdown / fs.rs's
+ * raw-sources-layout heuristic). We list `raw/sources/` once
+ * and pick the file whose stem equals the slug.
+ *
+ * The raw file's preview goes through `read_file` → the
+ * combined-extraction path (text + per-page image refs with
+ * absolute URLs), which means the `<img data-mdsrc=...>` we
+ * scroll-target lives in the same DOM. To match what the
+ * preview emits, we normalize `hit.url` to its absolute form
+ * before staging the pending scroll — wiki-relative URLs
+ * (from the safety-net section) wouldn't otherwise match the
+ * absolute URLs the raw extractor uses.
+ *
+ * Fallback: if we can't find a raw source file (e.g. the user
+ * deleted it after ingest, leaving only the wiki summary), we
+ * open the wiki page so SOMETHING happens.
+ */
+ async function handleJumpFromLightbox(hit: ImageHit) {
+ const projectPath = project?.path
+ let openPath = hit.sourcePath
+ let scrollTarget = hit.url
+
+ if (projectPath) {
+ const pp = normalizePath(projectPath)
+ const rawPath = await findRawSourceForImage(hit.url, pp)
+ if (rawPath) {
+ console.log(`[search:jump] ${hit.url} → raw source ${rawPath}`)
+ openPath = rawPath
+ scrollTarget = imageUrlToAbsolute(scrollTarget, pp)
+ } else {
+ console.warn(
+ `[search:jump] no raw source found for image ${hit.url} — falling back to wiki page`,
+ )
+ }
+ }
+
+ try {
+ const content = await readFile(openPath)
+ setPendingScrollImageSrc(scrollTarget)
+ setSelectedFile(openPath)
+ setFileContent(content)
+ setActiveView("wiki")
+ setLightbox(null)
+ } catch (err) {
+ console.error("Failed to jump to source:", err)
+ }
+ }
+
return (
<div className="flex h-full flex-col overflow-hidden">
<div className="shrink-0 border-b px-4 py-3">
@@ -66,38 +201,305 @@ export function SearchView() {
</div>
</div>
- <div className="flex-1 overflow-y-auto">
- {searching ? (
- <div className="p-4 text-center text-sm text-muted-foreground">Searching...</div>
- ) : !hasSearched ? (
- <div className="flex flex-col items-center justify-center gap-2 p-8 text-center text-sm text-muted-foreground">
- <Search className="h-8 w-8 text-muted-foreground/30" />
- <p>Press Enter to search</p>
+ {/*
+ * Body. Two independently scrollable regions: images (capped
+ * height = 2 rows of thumbnails) and pages (fills the rest).
+ * Stacked, no outer scroll — the user asked for "image grid
+ * doesn't push the text list off-screen, both areas scroll
+ * inside themselves."
+ */}
+ {searching ? (
+ <div className="flex-1 p-4 text-center text-sm text-muted-foreground">
+ Searching...
+ </div>
+ ) : !hasSearched ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-2 p-8 text-center text-sm text-muted-foreground">
+ <Search className="h-8 w-8 text-muted-foreground/30" />
+ <p>Press Enter to search</p>
+ </div>
+ ) : results.length === 0 ? (
+ <div className="flex-1 p-4 text-center text-sm text-muted-foreground">
+ {t("search.noResults")} <span className="font-medium">"{query}"</span>
+ </div>
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="shrink-0 px-3 pt-3 pb-1 text-xs text-muted-foreground">
+ {results.length} page{results.length !== 1 ? "s" : ""}
+ {imageHits.length > 0 && (
+ <>
+ {" · "}
+ {matchingImages.length} image{matchingImages.length !== 1 ? "s" : ""} match
+ {supportingImages.length > 0 && ` · +${supportingImages.length} from matched pages`}
+ </>
+ )}
</div>
- ) : results.length === 0 ? (
- <div className="p-4 text-center text-sm text-muted-foreground">
- {t("search.noResults")} <span className="font-medium">"{query}"</span>
+
+ {/* ── Images: fixed-height thumbnails, 2 rows visible, scrolls inside ── */}
+ {visibleImages.length > 0 && (
+ <>
+ <div className="shrink-0 px-3 pt-1">
+ <SectionHeader
+ icon={<ImageIcon className="h-3.5 w-3.5" />}
+ label="Images"
+ count={visibleImages.length}
+ trailing={
+ supportingImages.length > 0 ? (
+ <button
+ type="button"
+ onClick={() => setShowSupportingImages((s) => !s)}
+ className="text-[11px] text-muted-foreground hover:text-foreground underline-offset-2 hover:underline"
+ >
+ {showSupportingImages
+ ? "Hide supporting"
+ : `Show all (+${supportingImages.length})`}
+ </button>
+ ) : null
+ }
+ />
+ </div>
+ {/*
+ * Cap height at 2-rows-worth of cards. Each `ImageHitCard`
+ * is fixed at ~176px tall (120px thumbnail + 2-line
+ * caption + source title + padding); with `gap-2` (8px)
+ * between rows that's ~360px for two rows. We pad to
+ * 23rem (368px) so the bottom edge of the second row
+ * isn't visually flush with the scrollbar / next
+ * section. Anything beyond 2 rows stays accessible via
+ * vertical scroll inside this container ONLY — the
+ * Pages list below keeps its own scroll independent.
+ */}
+ <div className="max-h-[23rem] shrink-0 overflow-y-auto px-3 pt-2 pb-3">
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4">
+ {visibleImages.map((img) => (
+ <ImageHitCard
+ key={img.url}
+ hit={img}
+ query={query}
+ onClick={() => setLightbox(img)}
+ />
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* ── Pages: takes remaining vertical space, scrolls inside ── */}
+ <div className="shrink-0 px-3 pt-1">
+ <SectionHeader
+ icon={<FileText className="h-3.5 w-3.5" />}
+ label="Pages"
+ count={results.length}
+ />
</div>
- ) : (
- <div className="flex flex-col gap-1 p-2">
- <div className="px-2 py-1 text-xs text-muted-foreground">
- {results.length} result{results.length !== 1 ? "s" : ""}
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 pt-2 pb-3">
+ <div className="flex flex-col gap-1">
+ {results.map((result) => (
+ <SearchResultCard
+ key={result.path}
+ result={result}
+ query={query}
+ onClick={() => handleOpen(result.path)}
+ />
+ ))}
</div>
- {results.map((result) => (
- <SearchResultCard
- key={result.path}
- result={result}
- query={query}
- onClick={() => handleOpen(result)}
- />
- ))}
</div>
- )}
+ </div>
+ )}
+
+ {/* Lightbox modal — only mounted when an image is selected.
+ * Sits at the SearchView root so it overlays everything inside
+ * this view but doesn't escape into other views' DOM. */}
+ {lightbox && (
+ <Lightbox
+ hit={lightbox}
+ projectPath={project?.path ?? null}
+ onClose={() => setLightbox(null)}
+ onJumpToSource={() => handleJumpFromLightbox(lightbox)}
+ />
+ )}
+ </div>
+ )
+}
+
+function Lightbox({
+ hit,
+ projectPath,
+ onClose,
+ onJumpToSource,
+}: {
+ hit: ImageHit
+ projectPath: string | null
+ onClose: () => void
+ onJumpToSource: () => void
+}) {
+ // Escape-to-close. Body-scroll-lock while open: a long search-
+ // results list scrolling underneath the modal is disorienting.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") onClose()
+ }
+ document.addEventListener("keydown", onKey)
+ const prev = document.body.style.overflow
+ document.body.style.overflow = "hidden"
+ return () => {
+ document.removeEventListener("keydown", onKey)
+ document.body.style.overflow = prev
+ }
+ }, [onClose])
+
+ const src = resolveMarkdownImageSrc(hit.url, projectPath)
+
+ return (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm"
+ onClick={onClose}
+ // Backdrop is the click target; the inner card stops
+ // propagation so clicks inside don't accidentally close.
+ role="dialog"
+ aria-modal="true"
+ >
+ <div
+ className="flex max-h-[90vh] w-[90vw] max-w-4xl flex-col overflow-hidden rounded-lg border bg-background shadow-xl"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {/* Header strip — caption + close button. */}
+ <div className="flex items-start justify-between gap-3 border-b px-4 py-2.5">
+ <div className="min-w-0 flex-1">
+ {hit.alt ? (
+ <div className="line-clamp-3 text-sm leading-snug">{hit.alt}</div>
+ ) : (
+ <div className="text-sm italic text-muted-foreground">No caption</div>
+ )}
+ <div className="mt-1 truncate text-[11px] text-muted-foreground">
+ From: {hit.sourceTitle}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="shrink-0 rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+
+ {/* Image area — flex-1 fills, object-contain preserves aspect. */}
+ <div className="flex min-h-0 flex-1 items-center justify-center bg-muted/30 p-4">
+ <img
+ src={src}
+ alt={hit.alt || ""}
+ className="max-h-full max-w-full object-contain"
+ />
+ </div>
+
+ {/* Action strip — single button to jump to source.
+ * Right-aligned so the eye lands on it after reading the
+ * caption (left-to-right). */}
+ <div className="flex items-center justify-end gap-2 border-t px-4 py-2.5">
+ <button
+ type="button"
+ onClick={onJumpToSource}
+ className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90"
+ >
+ <ArrowUpRight className="h-3.5 w-3.5" />
+ Jump to source document
+ </button>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+function SectionHeader({
+ icon,
+ label,
+ count,
+ trailing,
+}: {
+ icon: React.ReactNode
+ label: string
+ count: number
+ trailing?: React.ReactNode
+}) {
+ return (
+ <div className="flex items-center justify-between border-b pb-1">
+ <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ {icon}
+ {label}
+ <span className="text-muted-foreground/60">({count})</span>
</div>
+ {trailing}
</div>
)
}
+function ImageHitCard({
+ hit,
+ query,
+ onClick,
+}: {
+ hit: ImageHit
+ query: string
+ onClick: () => void
+}) {
+ const project = useWikiStore((s) => s.project)
+ const projectPath = project?.path ?? null
+ // Same resolver the markdown preview uses — handles absolute
+ // filesystem paths (which our extractor emits) AND wiki-relative
+ // paths (which the safety-net section emits).
+ const src = resolveMarkdownImageSrc(hit.url, projectPath)
+
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={hit.alt || hit.sourceTitle}
+ className="group flex h-44 flex-col overflow-hidden rounded-lg border bg-background text-left transition-colors hover:bg-accent"
+ >
+ {/*
+ * Fixed thumbnail height (h-30 = 120px). Width fills the grid
+ * cell. `object-cover` keeps the source's aspect ratio while
+ * cropping to fill — preferable to letterboxing for a thumb
+ * grid where users skim by visual identity rather than read
+ * the chart axes. Combined with the parent's fixed h-44 (176px)
+ * and the text block's `flex-1` cap, every card has the SAME
+ * total height regardless of caption length, which keeps the
+ * grid's row alignment clean.
+ */}
+ <div className="h-30 w-full shrink-0 overflow-hidden bg-muted" style={{ height: "7.5rem" }}>
+ {/* `loading="lazy"` matters: a project with hundreds of
+ * images would otherwise issue a request for every one
+ * on first render, even when most are scrolled offscreen. */}
+ <img
+ src={src}
+ alt={hit.alt || ""}
+ loading="lazy"
+ className="h-full w-full object-cover transition-transform group-hover:scale-105"
+ // Hide broken-image icon when convertFileSrc can't resolve
+ // (network image deleted, project moved, etc.) — leave the
+ // bg-muted placeholder visible instead of a sad 🖼️.
+ onError={(e) => {
+ ;(e.currentTarget as HTMLImageElement).style.opacity = "0"
+ }}
+ />
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col gap-0.5 p-2">
+ {hit.alt ? (
+ <div className="line-clamp-2 text-[11px] leading-snug">
+ <HighlightedText text={hit.alt} query={query} />
+ </div>
+ ) : (
+ <div className="text-[11px] italic text-muted-foreground">No caption</div>
+ )}
+ <div className="mt-auto truncate text-[10px] text-muted-foreground">
+ {hit.sourceTitle}
+ </div>
+ </div>
+ </button>
+ )
+}
+
function SearchResultCard({
result,
query,
@@ -134,7 +536,16 @@ function SearchResultCard({
function HighlightedText({ text, query }: { text: string; query: string }) {
if (!query.trim()) return <>{text}</>
- const regex = new RegExp(`(${escapeRegex(query)})`, "gi")
+ // Highlight EACH non-stopword token from the query, not the raw
+ // query string. Same rationale as the alt-text filter above:
+ // "总资产。" should still highlight "总资产" inside captions /
+ // titles even though the period prevents a literal substring
+ // match. Falls back to the raw query when the tokenizer returned
+ // nothing, so a query like "(?)" still attempts highlighting
+ // (and trivially finds nothing, which is fine).
+ const tokens = tokenizeQuery(query)
+ const patterns = tokens.length > 0 ? tokens : [query.trim()]
+ const regex = new RegExp(`(${patterns.map(escapeRegex).join("|")})`, "gi")
const parts = text.split(regex)
return (
diff --git a/src/components/settings/sections/multimodal-section.tsx b/src/components/settings/sections/multimodal-section.tsx
new file mode 100644
index 00000000..48c36385
--- /dev/null
+++ b/src/components/settings/sections/multimodal-section.tsx
@@ -0,0 +1,286 @@
+import { useTranslation } from "react-i18next"
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+import type { SettingsDraft, DraftSetter } from "../settings-types"
+
+interface Props {
+ draft: SettingsDraft
+ setDraft: DraftSetter
+}
+
+const PROVIDER_OPTIONS: Array<{ value: SettingsDraft["multimodalProvider"]; label: string }> = [
+ { value: "custom", label: "Custom (OpenAI-compat)" },
+ { value: "openai", label: "OpenAI" },
+ { value: "anthropic", label: "Anthropic" },
+ { value: "google", label: "Google (Gemini)" },
+ { value: "ollama", label: "Ollama" },
+]
+
+export function MultimodalSection({ draft, setDraft }: Props) {
+ const { t } = useTranslation()
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">{t("settings.sections.multimodal.title", "Image captioning")}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t(
+ "settings.sections.multimodal.description",
+ "Generate factual captions for images extracted from PDFs / DOCX / PPTX during ingest. Captions are inserted as alt text inside the source markdown — they're what semantic search matches when you search for image content. Cached by image hash so duplicate logos / charts only call the LLM once.",
+ )}
+ </p>
+ </div>
+
+ {/* Master toggle. Off by default — captioning is a non-trivial
+ token spend (one VLM call per image), and silently turning
+ it on for every user the first time they import a PDF
+ would surprise the budget.
+
+ Note: the toggle row deliberately uses a 2-tier border +
+ a textual ON/OFF state next to the pill switch. An earlier
+ version had only the small pill and several users missed
+ it entirely — pills are subtle when surrounded by long
+ help text. The textual ON/OFF and the matching colored
+ ring make the current state unambiguous at a glance. */}
+ <div
+ className={`flex items-center justify-between rounded-md border-2 p-3 transition-colors ${
+ draft.multimodalEnabled
+ ? "border-primary/40 bg-primary/5"
+ : "border-border bg-background"
+ }`}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium">
+ {t("settings.sections.multimodal.enableLabel", "Enable captioning at ingest")}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {t(
+ "settings.sections.multimodal.enableHint",
+ "Off: images still get extracted, just no captions. Search won't find them by visual content. On: each new image triggers one vision-LLM call (cached by hash).",
+ )}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => setDraft("multimodalEnabled", !draft.multimodalEnabled)}
+ role="switch"
+ aria-checked={draft.multimodalEnabled}
+ aria-label={t("settings.sections.multimodal.enableLabel", "Enable captioning at ingest")}
+ className="ml-3 flex shrink-0 items-center gap-2"
+ >
+ <span
+ className={`text-xs font-semibold ${
+ draft.multimodalEnabled ? "text-primary" : "text-muted-foreground"
+ }`}
+ >
+ {draft.multimodalEnabled
+ ? t("settings.sections.multimodal.stateOn", "ON")
+ : t("settings.sections.multimodal.stateOff", "OFF")}
+ </span>
+ <span
+ className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
+ draft.multimodalEnabled ? "bg-primary" : "bg-muted"
+ }`}
+ >
+ <span
+ className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${
+ draft.multimodalEnabled ? "translate-x-4.5" : "translate-x-0.5"
+ }`}
+ />
+ </span>
+ </button>
+ </div>
+
+ {draft.multimodalEnabled && (
+ <>
+ {/* "Use main LLM" toggle. Lets users with a single VL-capable
+ model in their main config save the trouble of typing
+ everything twice. The dedicated fields below show only
+ when this is OFF.
+
+ Layout: the text column needs `min-w-0 flex-1` so a
+ long help text wraps inside its column instead of
+ shoving the toggle off to the right (or worse,
+ forcing the row's intrinsic width past the parent).
+ Without this the row visibly broke in English where
+ the multi-clause hint sentence is much longer than
+ the equivalent CJK text. The toggle gets `shrink-0`
+ for the symmetric reason — never lose the toggle to
+ the text column. */}
+ <div className="flex items-center justify-between gap-3 rounded-md border p-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium">
+ {t("settings.sections.multimodal.useMainLabel", "Use main LLM for captions")}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {t(
+ "settings.sections.multimodal.useMainHint",
+ "Reuse the model picked under Settings → LLM provider. Only enable this if that model accepts image input — text-only models will return a 400.",
+ )}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => setDraft("multimodalUseMainLlm", !draft.multimodalUseMainLlm)}
+ role="switch"
+ aria-checked={draft.multimodalUseMainLlm}
+ aria-label={t(
+ "settings.sections.multimodal.useMainLabel",
+ "Use main LLM for captions",
+ )}
+ className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${
+ draft.multimodalUseMainLlm ? "bg-primary" : "bg-muted"
+ }`}
+ >
+ <span
+ className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${
+ draft.multimodalUseMainLlm ? "translate-x-4.5" : "translate-x-0.5"
+ }`}
+ />
+ </button>
+ </div>
+
+ {!draft.multimodalUseMainLlm && (
+ <div className="space-y-4 rounded-md border p-3">
+ <div className="text-sm font-medium">
+ {t("settings.sections.multimodal.dedicatedHeading", "Dedicated vision endpoint")}
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t("settings.sections.multimodal.provider", "Provider")}</Label>
+ <select
+ className="w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
+ value={draft.multimodalProvider}
+ onChange={(e) =>
+ setDraft("multimodalProvider", e.target.value as SettingsDraft["multimodalProvider"])
+ }
+ >
+ {PROVIDER_OPTIONS.map((p) => (
+ <option key={p.value} value={p.value}>
+ {p.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {draft.multimodalProvider === "ollama" && (
+ <div className="space-y-2">
+ <Label>{t("settings.sections.multimodal.ollamaUrl", "Ollama URL")}</Label>
+ <Input
+ value={draft.multimodalOllamaUrl}
+ onChange={(e) => setDraft("multimodalOllamaUrl", e.target.value)}
+ placeholder="http://localhost:11434"
+ />
+ </div>
+ )}
+
+ {draft.multimodalProvider === "custom" && (
+ <div className="space-y-2">
+ <Label>{t("settings.sections.multimodal.customEndpoint", "Endpoint URL")}</Label>
+ <Input
+ value={draft.multimodalCustomEndpoint}
+ onChange={(e) => setDraft("multimodalCustomEndpoint", e.target.value)}
+ placeholder="http://localhost:1234/v1"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t(
+ "settings.sections.multimodal.customEndpointHint",
+ "OpenAI-compatible /v1 base. LM Studio, llama.cpp server, vLLM, LocalAI all work.",
+ )}
+ </p>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Label>{t("settings.sections.multimodal.apiKey", "API key")}</Label>
+ <Input
+ type="password"
+ value={draft.multimodalApiKey}
+ onChange={(e) => setDraft("multimodalApiKey", e.target.value)}
+ placeholder={t(
+ "settings.sections.multimodal.apiKeyPlaceholder",
+ "Leave blank for local / no-auth endpoints",
+ )}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t("settings.sections.multimodal.model", "Model")}</Label>
+ <Input
+ value={draft.multimodalModel}
+ onChange={(e) => setDraft("multimodalModel", e.target.value)}
+ placeholder="e.g. Qwen2.5-VL-7B-Instruct, claude-3-5-sonnet-latest, gemini-2.5-flash"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t(
+ "settings.sections.multimodal.modelHint",
+ "Must be a vision-capable model. Text-only models will fail with a 400 / image-not-supported error at first ingest.",
+ )}
+ </p>
+ </div>
+ </div>
+ )}
+
+ {/* Concurrency knob — practical impact: a 30-image PDF at
+ concurrency=1 with a 10s/image VLM is 5 minutes of
+ ingest wall time; concurrency=4 makes it ~75s. Going
+ wider than ~8 is rarely a win on a single-GPU server
+ that batches under the hood anyway. */}
+ <div className="space-y-2 rounded-md border p-3">
+ <Label>{t("settings.sections.multimodal.concurrency", "Concurrent caption requests")}</Label>
+ <Input
+ type="number"
+ min={1}
+ max={16}
+ step={1}
+ value={draft.multimodalConcurrency}
+ onChange={(e) => {
+ const n = Number(e.target.value)
+ setDraft("multimodalConcurrency", Number.isFinite(n) ? n : 4)
+ }}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t(
+ "settings.sections.multimodal.concurrencyHint",
+ "How many caption requests run in parallel. 1 = strictly sequential. 4 is a good default for most setups; raise to 8+ only on a beefy GPU or hosted endpoint.",
+ )}
+ </p>
+ </div>
+
+ {/* Cost guardrail panel — mostly informational for now. */}
+ <div className="space-y-1 rounded-md border border-amber-500/40 bg-amber-500/5 p-3">
+ <div className="text-sm font-medium text-amber-700 dark:text-amber-400">
+ {t("settings.sections.multimodal.costHeading", "Cost guardrails")}
+ </div>
+ <ul className="ml-4 list-disc space-y-1 text-xs text-muted-foreground">
+ <li>
+ {t(
+ "settings.sections.multimodal.costPoint1",
+ "Each new image triggers one vision-LLM call (~500-2000 tokens depending on model + thinking mode).",
+ )}
+ </li>
+ <li>
+ {t(
+ "settings.sections.multimodal.costPoint2",
+ "Captions are cached by SHA-256 of image bytes. Duplicate logos / shared chart templates across documents only ever incur ONE call.",
+ )}
+ </li>
+ <li>
+ {t(
+ "settings.sections.multimodal.costPoint3",
+ "Rust-side filter drops images smaller than 100×100 px and caps at 500 images per source — pathological PDFs can't blow up the bill.",
+ )}
+ </li>
+ <li>
+ {t(
+ "settings.sections.multimodal.costPoint4",
+ "Prefer a local vision model (Qwen2.5-VL via LM Studio / Ollama) for bulk ingestion; reserve hosted vision APIs for one-off high-stakes documents.",
+ )}
+ </li>
+ </ul>
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.ts
index 4cb90e96..951f3b26 100644
--- a/src/components/settings/settings-types.ts
+++ b/src/components/settings/settings-types.ts
@@ -26,6 +26,17 @@ export interface SettingsDraft {
/** Overlap characters between adjacent chunks. Empty = default (200). */
embeddingOverlapChunkChars: number | undefined
+ // Multimodal (image captioning at ingest time)
+ multimodalEnabled: boolean
+ multimodalUseMainLlm: boolean
+ multimodalProvider: "openai" | "anthropic" | "google" | "ollama" | "custom" | "minimax" | "claude-code"
+ multimodalApiKey: string
+ multimodalModel: string
+ multimodalOllamaUrl: string
+ multimodalCustomEndpoint: string
+ multimodalApiMode: CustomApiMode | undefined
+ multimodalConcurrency: number
+
// Web search
searchProvider: "tavily" | "none"
searchApiKey: string
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index caa06a4c..f28b708d 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -6,6 +6,7 @@ import {
Languages,
Palette,
Info,
+ Image as ImageIcon,
} from "lucide-react"
import { useTranslation } from "react-i18next"
import i18n from "@/i18n"
@@ -16,6 +17,7 @@ import { saveLanguage } from "@/lib/project-store"
import type { SettingsDraft, DraftSetter } from "./settings-types"
import { LlmProviderSection } from "./sections/llm-provider-section"
import { EmbeddingSection } from "./sections/embedding-section"
+import { MultimodalSection } from "./sections/multimodal-section"
import { WebSearchSection } from "./sections/web-search-section"
import { OutputSection } from "./sections/output-section"
import { InterfaceSection } from "./sections/interface-section"
@@ -24,6 +26,7 @@ import { AboutSection } from "./sections/about-section"
type CategoryId =
| "llm"
| "embedding"
+ | "multimodal"
| "web-search"
| "output"
| "interface"
@@ -41,6 +44,7 @@ interface Category {
const CATEGORIES: Category[] = [
{ id: "llm", labelKey: "settings.categories.llm", icon: Bot },
{ id: "embedding", labelKey: "settings.categories.embedding", icon: Binary },
+ { id: "multimodal", labelKey: "settings.categories.multimodal", icon: ImageIcon },
{ id: "web-search", labelKey: "settings.categories.webSearch", icon: Globe },
{ id: "output", labelKey: "settings.categories.output", icon: Languages },
{ id: "interface", labelKey: "settings.categories.interface", icon: Palette },
@@ -51,6 +55,7 @@ function initialDraft(
llm: ReturnType<typeof useWikiStore.getState>["llmConfig"],
search: ReturnType<typeof useWikiStore.getState>["searchApiConfig"],
embed: ReturnType<typeof useWikiStore.getState>["embeddingConfig"],
+ multimodal: ReturnType<typeof useWikiStore.getState>["multimodalConfig"],
outputLanguage: ReturnType<typeof useWikiStore.getState>["outputLanguage"],
maxHistoryMessages: number,
uiLanguage: string,
@@ -69,6 +74,15 @@ function initialDraft(
embeddingModel: embed.model,
embeddingMaxChunkChars: embed.maxChunkChars,
embeddingOverlapChunkChars: embed.overlapChunkChars,
+ multimodalEnabled: multimodal.enabled,
+ multimodalUseMainLlm: multimodal.useMainLlm,
+ multimodalProvider: multimodal.provider,
+ multimodalApiKey: multimodal.apiKey,
+ multimodalModel: multimodal.model,
+ multimodalOllamaUrl: multimodal.ollamaUrl,
+ multimodalCustomEndpoint: multimodal.customEndpoint,
+ multimodalApiMode: multimodal.apiMode,
+ multimodalConcurrency: multimodal.concurrency,
searchProvider: search.provider,
searchApiKey: search.apiKey,
outputLanguage,
@@ -85,6 +99,8 @@ export function SettingsView() {
const setSearchApiConfig = useWikiStore((s) => s.setSearchApiConfig)
const embeddingConfig = useWikiStore((s) => s.embeddingConfig)
const setEmbeddingConfig = useWikiStore((s) => s.setEmbeddingConfig)
+ const multimodalConfig = useWikiStore((s) => s.multimodalConfig)
+ const setMultimodalConfig = useWikiStore((s) => s.setMultimodalConfig)
const outputLanguage = useWikiStore((s) => s.outputLanguage)
const setOutputLanguage = useWikiStore((s) => s.setOutputLanguage)
const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)
@@ -97,6 +113,7 @@ export function SettingsView() {
llmConfig,
searchApiConfig,
embeddingConfig,
+ multimodalConfig,
outputLanguage,
maxHistoryMessages,
i18n.language,
@@ -110,6 +127,7 @@ export function SettingsView() {
llmConfig,
searchApiConfig,
embeddingConfig,
+ multimodalConfig,
outputLanguage,
maxHistoryMessages,
i18n.language,
@@ -119,6 +137,7 @@ export function SettingsView() {
llmConfig,
searchApiConfig,
embeddingConfig,
+ multimodalConfig,
outputLanguage,
maxHistoryMessages,
])
@@ -132,6 +151,7 @@ export function SettingsView() {
saveLlmConfig,
saveSearchApiConfig,
saveEmbeddingConfig,
+ saveMultimodalConfig,
saveOutputLanguage,
} = await import("@/lib/project-store")
@@ -153,6 +173,23 @@ export function SettingsView() {
maxChunkChars: draft.embeddingMaxChunkChars,
overlapChunkChars: draft.embeddingOverlapChunkChars,
}
+ const newMultimodal = {
+ enabled: draft.multimodalEnabled,
+ useMainLlm: draft.multimodalUseMainLlm,
+ provider: draft.multimodalProvider,
+ apiKey: draft.multimodalApiKey,
+ model: draft.multimodalModel,
+ ollamaUrl: draft.multimodalOllamaUrl,
+ customEndpoint: draft.multimodalCustomEndpoint,
+ apiMode: draft.multimodalProvider === "custom" ? draft.multimodalApiMode : undefined,
+ // Clamp at save time so a hand-edited persisted store with a
+ // ridiculous concurrency value (e.g. someone setting 1000 in
+ // the JSON) doesn't blow up the captioning pipeline. Caption
+ // calls already share the LLM endpoint with everything else;
+ // going wider than ~16 just queues behind the server's batch
+ // slot.
+ concurrency: Math.max(1, Math.min(16, draft.multimodalConcurrency || 4)),
+ }
setLlmConfig(newLlm)
await saveLlmConfig(newLlm)
@@ -160,6 +197,8 @@ export function SettingsView() {
await saveSearchApiConfig(newSearch)
setEmbeddingConfig(newEmbed)
await saveEmbeddingConfig(newEmbed)
+ setMultimodalConfig(newMultimodal)
+ await saveMultimodalConfig(newMultimodal)
setOutputLanguage(draft.outputLanguage as typeof outputLanguage)
await saveOutputLanguage(draft.outputLanguage as typeof outputLanguage)
setMaxHistoryMessages(draft.maxHistoryMessages)
@@ -190,6 +229,8 @@ export function SettingsView() {
return <LlmProviderSection />
case "embedding":
return <EmbeddingSection draft={draft} setDraft={setDraft} />
+ case "multimodal":
+ return <MultimodalSection draft={draft} setDraft={setDraft} />
case "web-search":
return <WebSearchSection draft={draft} setDraft={setDraft} />
case "output":
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 92cd53c8..1304a6da 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -7,7 +7,6 @@ import { ScrollArea } from "@/components/ui/scroll-area"
import { useWikiStore } from "@/stores/wiki-store"
import { copyFile, listDirectory, readFile, writeFile, deleteFile, findRelatedWikiPages, preprocessFile } from "@/commands/fs"
import type { FileNode } from "@/types/wiki"
-import { startIngest } from "@/lib/ingest"
import { enqueueIngest, enqueueBatch } from "@/lib/ingest-queue"
import { useTranslation } from "react-i18next"
import { normalizePath, getFileName } from "@/lib/path-utils"
@@ -26,10 +25,8 @@ export function SourcesView() {
const project = useWikiStore((s) => s.project)
const selectedFile = useWikiStore((s) => s.selectedFile)
const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
- const setActiveView = useWikiStore((s) => s.setActiveView)
const setFileContent = useWikiStore((s) => s.setFileContent)
const setFileTree = useWikiStore((s) => s.setFileTree)
- const setChatExpanded = useWikiStore((s) => s.setChatExpanded)
const llmConfig = useWikiStore((s) => s.llmConfig)
const [sources, setSources] = useState<FileNode[]>([])
const [importing, setImporting] = useState(false)
@@ -351,13 +348,18 @@ export function SourcesView() {
async function handleIngest(node: FileNode) {
if (!project || ingestingPath) return
+ // Re-ingest goes through the same automated queue path as a fresh
+ // import (`handleImport` above). Earlier this used `startIngest`,
+ // which opens an interactive chat → user clicks "Save to Wiki" →
+ // `executeIngestWrites`. That had two problems: (a) it duplicated
+ // the auto-pipeline so features like image cascade had to be
+ // wired in twice, and (b) the interactive flow surprised users
+ // who expected a fresh-import re-run. One button, one path now.
setIngestingPath(node.path)
try {
- setChatExpanded(true)
- setActiveView("wiki")
- await startIngest(normalizePath(project.path), node.path, llmConfig)
+ await enqueueIngest(project.id, node.path)
} catch (err) {
- console.error("Failed to start ingest:", err)
+ console.error("Failed to enqueue ingest:", err)
} finally {
setIngestingPath(null)
}
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 1abed70d..75c869dc 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -100,6 +100,7 @@
"categories": {
"llm": "LLM Models",
"embedding": "Embeddings",
+ "multimodal": "Image Captioning",
"webSearch": "Web Search",
"output": "Output",
"interface": "Interface",
@@ -146,6 +147,32 @@
"dropLegacy": "Drop legacy index",
"dropLegacyDone": "Legacy index removed."
},
+ "multimodal": {
+ "title": "Image Captioning",
+ "description": "Generate factual captions for images extracted from PDFs / DOCX / PPTX during ingest. Captions are inserted as alt text inside the source markdown — they're what semantic search matches when you search for image content. Cached by image hash so duplicate logos / charts only call the LLM once.",
+ "enableLabel": "Enable captioning at ingest",
+ "enableHint": "Off: image references are stripped from ingested content — no images appear in wiki pages, search won't return them. (Files still extract to wiki/media/ for the raw-source preview.) On: each new image gets a factual caption from the vision LLM (cached by hash) and lands in the wiki page's alt text.",
+ "stateOn": "ON",
+ "stateOff": "OFF",
+ "useMainLabel": "Use main LLM for captions",
+ "useMainHint": "Reuse the model picked under Settings → LLM provider. Only enable this if that model accepts image input — text-only models will return a 400.",
+ "dedicatedHeading": "Dedicated vision endpoint",
+ "provider": "Provider",
+ "ollamaUrl": "Ollama URL",
+ "customEndpoint": "Endpoint URL",
+ "customEndpointHint": "OpenAI-compatible /v1 base. LM Studio, llama.cpp server, vLLM, LocalAI all work.",
+ "apiKey": "API key",
+ "apiKeyPlaceholder": "Leave blank for local / no-auth endpoints",
+ "model": "Model",
+ "modelHint": "Must be a vision-capable model. Text-only models will fail with a 400 / image-not-supported error at first ingest.",
+ "concurrency": "Concurrent caption requests",
+ "concurrencyHint": "How many caption requests run in parallel. 1 = strictly sequential. 4 is a good default for most setups; raise to 8+ only on a beefy GPU or hosted endpoint.",
+ "costHeading": "Cost guardrails",
+ "costPoint1": "Each new image triggers one vision-LLM call (~500-2000 tokens depending on model + thinking mode).",
+ "costPoint2": "Captions are cached by SHA-256 of image bytes. Duplicate logos / shared chart templates across documents only ever incur ONE call.",
+ "costPoint3": "Rust-side filter drops images smaller than 100×100 px and caps at 500 images per source — pathological PDFs can't blow up the bill.",
+ "costPoint4": "Prefer a local vision model (Qwen2.5-VL via LM Studio / Ollama) for bulk ingestion; reserve hosted vision APIs for one-off high-stakes documents."
+ },
"webSearch": {
"title": "Web Search",
"description": "Used by Deep Research to pull fresh external context."
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 153f9dc4..b24a5ab7 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -100,6 +100,7 @@
"categories": {
"llm": "LLM 模型",
"embedding": "向量嵌入",
+ "multimodal": "图片描述",
"webSearch": "网页搜索",
"output": "输出偏好",
"interface": "界面",
@@ -146,6 +147,32 @@
"dropLegacy": "删除旧版索引",
"dropLegacyDone": "旧版索引已删除。"
},
+ "multimodal": {
+ "title": "图片描述",
+ "description": "导入时调用视觉模型为 PDF / DOCX / PPTX 中提取的图片生成事实性描述。描述会写入源 markdown 的 alt 属性,语义搜索按图片内容查询时就靠它命中。按图片字节 SHA-256 缓存,跨文档重复出现的 logo / 图表模板只调用一次。",
+ "enableLabel": "导入时生成图片描述",
+ "enableHint": "关:ingest 时把图片引用从内容里剥掉 —— wiki 页面里不会出现图片,搜索也不会返回。(图片仍会落到 wiki/media/,原始文档预览能看到。)开:每张新图调用视觉模型生成事实性 caption(按 hash 缓存),写入 wiki 页面 alt 属性。",
+ "stateOn": "已开启",
+ "stateOff": "已关闭",
+ "useMainLabel": "使用主 LLM 生成 caption",
+ "useMainHint": "复用「设置 → LLM Provider」里选的模型。仅当主模型支持图像输入时打开 —— 纯文本模型会返回 400。",
+ "dedicatedHeading": "独立视觉端点",
+ "provider": "Provider",
+ "ollamaUrl": "Ollama URL",
+ "customEndpoint": "端点 URL",
+ "customEndpointHint": "OpenAI 兼容的 /v1 根地址。LM Studio、llama.cpp server、vLLM、LocalAI 都可以。",
+ "apiKey": "API Key",
+ "apiKeyPlaceholder": "本地 / 无鉴权端点留空",
+ "model": "模型",
+ "modelHint": "必须是支持视觉输入的模型。文本-only 模型会在首次 ingest 时报 400 / image-not-supported。",
+ "concurrency": "并发 caption 请求数",
+ "concurrencyHint": "并行多少个 caption 请求。1 = 严格串行。多数场景 4 合适;只有在高性能 GPU 或托管端点上才考虑 8+。",
+ "costHeading": "费用提示",
+ "costPoint1": "每张新图触发一次视觉模型调用(约 500-2000 token,取决于模型和 thinking 模式)。",
+ "costPoint2": "Caption 按图片字节 SHA-256 缓存。跨文档重复的 logo / 通用图表模板只调用 ONE 次。",
+ "costPoint3": "Rust 端过滤掉小于 100×100 像素的图,并限制每文档最多 500 张 —— 病态 PDF 不会无限放大费用。",
+ "costPoint4": "批量 ingest 推荐用本地视觉模型(LM Studio / Ollama 跑 Qwen2.5-VL);托管视觉 API 留给少量高价值文档。"
+ },
"webSearch": {
"title": "网页搜索",
"description": "Deep Research 会用它拉取最新的外部上下文。"
diff --git a/src/lib/extract-source-images.ts b/src/lib/extract-source-images.ts
index 2f118151..3928ea57 100644
--- a/src/lib/extract-source-images.ts
+++ b/src/lib/extract-source-images.ts
@@ -76,10 +76,13 @@ export async function extractAndSaveSourceImages(
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.
+ // Rust's `SavedImage` is `#[serde(rename_all = "camelCase")]`,
+ // so the wire format uses `relPath` / `absPath` / `mimeType`.
+ // (Note: Tauri's IPC auto-camelCase applies only to command
+ // PARAMETER names, never to return-value field names — without
+ // the explicit serde attribute on the Rust struct, this filter
+ // would drop every item and return `[]` even when extraction
+ // wrote images to disk. We had that bug.)
return images
.filter((it): it is SavedImage => {
if (!it || typeof it !== "object") return false
@@ -116,7 +119,10 @@ export async function extractAndSaveSourceImages(
* inline at page breaks; that requires the text extractor to emit
* page boundaries, which it doesn't yet.
*/
-export function buildImageMarkdownSection(images: SavedImage[]): string {
+export function buildImageMarkdownSection(
+ images: SavedImage[],
+ captionsBySha?: Map<string, string>,
+): string {
if (images.length === 0) return ""
const lines: string[] = ["", "", "## Embedded Images", ""]
@@ -140,14 +146,26 @@ export function buildImageMarkdownSection(images: SavedImage[]): string {
return numA - numB
})
+ // Sanitize a caption for safe inclusion as alt text — the same
+ // rules as the inline-rewrite path: no `]` (would close the alt
+ // bracket early), no embedded newlines (would break the markdown
+ // image syntax across lines).
+ const sanitize = (s: string): string =>
+ s.replace(/[\r\n]+/g, " ").replace(/]/g, ")").trim()
+
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(`![](${img.relPath})`)
+ // Caption lookup by SHA-256 — same key the caption pipeline
+ // uses to dedupe across documents. Falling back to empty alt
+ // text if no caption is available for this image (caption
+ // pipeline disabled / failed / didn't run yet on cache hit).
+ // Empty alt is still better than no image reference at all
+ // — the inline LLM-generated text might cite the image by
+ // page number anyway.
+ const caption = captionsBySha?.get(img.sha256)
+ const alt = caption ? sanitize(caption) : ""
+ lines.push(`![${alt}](${img.relPath})`)
}
lines.push("")
}
diff --git a/src/lib/image-caption-pipeline.test.ts b/src/lib/image-caption-pipeline.test.ts
new file mode 100644
index 00000000..0b6fbcd9
--- /dev/null
+++ b/src/lib/image-caption-pipeline.test.ts
@@ -0,0 +1,354 @@
+/**
+ * Unit coverage for the caption pipeline. Mocks `captionImage` and
+ * the fs commands so we can pin the cache + rewrite logic without
+ * touching either the LLM or the filesystem.
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+const { mockCaption, mockReadBase64, mockReadFile, mockWriteFile, mockFileExists, mockCreateDir } =
+ vi.hoisted(() => ({
+ mockCaption: vi.fn(),
+ mockReadBase64: vi.fn(),
+ mockReadFile: vi.fn(),
+ mockWriteFile: vi.fn(),
+ mockFileExists: vi.fn(),
+ mockCreateDir: vi.fn(),
+ }))
+
+vi.mock("@/lib/vision-caption", () => ({
+ captionImage: mockCaption,
+}))
+
+vi.mock("@/commands/fs", () => ({
+ readFile: (p: string) => mockReadFile(p),
+ writeFile: (p: string, c: string) => mockWriteFile(p, c),
+ fileExists: (p: string) => mockFileExists(p),
+ createDirectory: (p: string) => mockCreateDir(p),
+ readFileAsBase64: (p: string) => mockReadBase64(p),
+}))
+
+import { captionMarkdownImages, __test } from "./image-caption-pipeline"
+import type { LlmConfig } from "@/stores/wiki-store"
+
+const cfg: LlmConfig = {
+ provider: "custom",
+ apiKey: "",
+ model: "vl-test",
+ ollamaUrl: "",
+ customEndpoint: "http://example/v1",
+ apiMode: "chat_completions",
+ maxContextSize: 8192,
+}
+
+beforeEach(() => {
+ mockCaption.mockReset()
+ mockReadBase64.mockReset()
+ mockReadFile.mockReset()
+ mockWriteFile.mockReset()
+ mockFileExists.mockReset()
+ mockCreateDir.mockReset()
+ // Default: no cache file present, no images to read.
+ mockFileExists.mockResolvedValue(false)
+ mockCreateDir.mockResolvedValue(undefined)
+ mockWriteFile.mockResolvedValue(undefined)
+})
+
+describe("findImageReferences (helper)", () => {
+ it("captures markdown image syntax with position info", () => {
+ const refs = __test.findImageReferences("text\n![](a.png)\n![label](b.jpg) more")
+ expect(refs).toEqual([
+ { full: "![](a.png)", alt: "", url: "a.png", index: 5, length: 10 },
+ { full: "![label](b.jpg)", alt: "label", url: "b.jpg", index: 16, length: 15 },
+ ])
+ })
+
+ it("ignores links and HTML img", () => {
+ const refs = __test.findImageReferences("[link](url) <img src=foo.png /> ![real](z.png)")
+ expect(refs).toHaveLength(1)
+ expect(refs[0].url).toBe("z.png")
+ })
+})
+
+describe("captionMarkdownImages", () => {
+ it("returns input unchanged when there are no image references", async () => {
+ const out = await captionMarkdownImages("/proj", "no images here", cfg)
+ expect(out.enrichedMarkdown).toBe("no images here")
+ expect(out.freshCaptions).toBe(0)
+ expect(out.cachedCaptions).toBe(0)
+ expect(mockCaption).not.toHaveBeenCalled()
+ })
+
+ it("captions a fresh image, rewrites alt text, persists cache", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("a red square")
+
+ const md = "Before\n\n![](/abs/img-1.png)\n\nAfter"
+ const out = await captionMarkdownImages("/proj", md, cfg)
+
+ expect(out.freshCaptions).toBe(1)
+ expect(out.cachedCaptions).toBe(0)
+ expect(out.enrichedMarkdown).toBe(
+ "Before\n\n![a red square](/abs/img-1.png)\n\nAfter",
+ )
+
+ expect(mockCaption).toHaveBeenCalledTimes(1)
+ expect(mockCaption).toHaveBeenCalledWith(
+ "AAAA",
+ "image/png",
+ cfg,
+ undefined,
+ // Pipeline always passes a context options object, even when
+ // both sides are empty (image at start/end of doc).
+ expect.objectContaining({ contextBefore: expect.any(String), contextAfter: expect.any(String) }),
+ )
+
+ // Cache file written exactly once at the end of the batch.
+ expect(mockWriteFile).toHaveBeenCalledTimes(1)
+ const [cachePath, contents] = mockWriteFile.mock.calls[0] as [string, string]
+ expect(cachePath).toBe("/proj/.llm-wiki/image-caption-cache.json")
+ const written = JSON.parse(contents)
+ const entries = Object.values(written) as Array<Record<string, unknown>>
+ expect(entries).toHaveLength(1)
+ expect(entries[0]).toMatchObject({
+ caption: "a red square",
+ mimeType: "image/png",
+ model: "vl-test",
+ })
+ })
+
+ it("dedupes by SHA-256: two refs to the same bytes → one LLM call, both rewritten", async () => {
+ // Both URLs return the same base64 bytes — same hash → single
+ // caption call, both alt-texts populated.
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("the logo")
+
+ const md = "![](/a/logo.png) and ![](/b/logo-copy.png)"
+ const out = await captionMarkdownImages("/proj", md, cfg)
+
+ // Two reads, ONE caption call, both refs rewritten.
+ expect(mockReadBase64).toHaveBeenCalledTimes(2)
+ expect(mockCaption).toHaveBeenCalledTimes(1)
+ expect(out.freshCaptions).toBe(1)
+ expect(out.enrichedMarkdown).toBe(
+ "![the logo](/a/logo.png) and ![the logo](/b/logo-copy.png)",
+ )
+ })
+
+ it("uses cached caption when SHA-256 hash matches", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+
+ // Pre-populate the cache file. Hash of base64-decoded "AAAA"
+ // (bytes 0,0,0): we compute it via the same helper to keep
+ // the test deterministic and decoupled from a literal hash.
+ const knownHash = await __test.sha256OfBase64("AAAA")
+ const cacheJson = {
+ [knownHash]: {
+ caption: "previously captioned",
+ mimeType: "image/png",
+ model: "vl-old",
+ capturedAt: "2026-01-01T00:00:00Z",
+ },
+ }
+ mockFileExists.mockResolvedValue(true)
+ mockReadFile.mockResolvedValue(JSON.stringify(cacheJson))
+
+ const md = "![](/abs/x.png)"
+ const out = await captionMarkdownImages("/proj", md, cfg)
+
+ expect(out.cachedCaptions).toBe(1)
+ expect(out.freshCaptions).toBe(0)
+ expect(mockCaption).not.toHaveBeenCalled()
+ expect(out.enrichedMarkdown).toBe("![previously captioned](/abs/x.png)")
+ // Cache wasn't grown → no write.
+ expect(mockWriteFile).not.toHaveBeenCalled()
+ })
+
+ it("sanitizes captions: strips newlines and replaces ] with )", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("line1\nline2 with ] bracket")
+
+ const md = "![](/abs/x.png)"
+ const out = await captionMarkdownImages("/proj", md, cfg)
+
+ expect(out.enrichedMarkdown).toBe("![line1 line2 with ) bracket](/abs/x.png)")
+ })
+
+ it("continues batch when one caption call fails, reporting failed count", async () => {
+ mockReadBase64.mockImplementation(async (p: string) => {
+ if (p === "/abs/a.png") return { base64: "AAAA", mimeType: "image/png" }
+ return { base64: "BBBB", mimeType: "image/png" }
+ })
+ mockCaption.mockImplementation(async (b64: string) => {
+ if (b64 === "AAAA") return "first"
+ throw new Error("HTTP 500")
+ })
+
+ const md = "![](/abs/a.png) ![](/abs/b.png)"
+ const out = await captionMarkdownImages("/proj", md, cfg)
+
+ expect(out.freshCaptions).toBe(1)
+ expect(out.failed).toBe(1)
+ // Successful one rewritten, failing one keeps original empty alt.
+ expect(out.enrichedMarkdown).toBe("![first](/abs/a.png) ![](/abs/b.png)")
+ })
+
+ it("respects shouldCaption filter: skips URLs that don't match", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("c")
+
+ const md = "![](/wanted/img.png) ![](https://external.example/foo.png)"
+ const out = await captionMarkdownImages("/proj", md, cfg, {
+ shouldCaption: (url) => url.startsWith("/wanted/"),
+ })
+
+ expect(mockReadBase64).toHaveBeenCalledTimes(1)
+ expect(mockReadBase64).toHaveBeenCalledWith("/wanted/img.png")
+ expect(out.enrichedMarkdown).toBe(
+ "![c](/wanted/img.png) ![](https://external.example/foo.png)",
+ )
+ })
+
+ it("uses urlToAbsPath hook when provided", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("c")
+
+ const md = "![](media/foo/img-1.png)"
+ await captionMarkdownImages("/proj", md, cfg, {
+ urlToAbsPath: (url) => `/custom/anchor/${url}`,
+ })
+
+ expect(mockReadBase64).toHaveBeenCalledWith("/custom/anchor/media/foo/img-1.png")
+ })
+
+ it("forwards AbortSignal to captionImage", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("c")
+
+ const ctl = new AbortController()
+ await captionMarkdownImages("/proj", "![](/abs/x.png)", cfg, {
+ signal: ctl.signal,
+ })
+ expect(mockCaption).toHaveBeenCalledWith(
+ "AAAA",
+ "image/png",
+ cfg,
+ ctl.signal,
+ expect.objectContaining({ contextBefore: expect.any(String), contextAfter: expect.any(String) }),
+ )
+ })
+
+ it("recovers from corrupt cache JSON (logs and starts fresh)", async () => {
+ mockFileExists.mockResolvedValue(true)
+ mockReadFile.mockResolvedValue("{ this is not valid JSON")
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("ok")
+
+ const out = await captionMarkdownImages("/proj", "![](/abs/x.png)", cfg)
+ expect(out.enrichedMarkdown).toBe("![ok](/abs/x.png)")
+ expect(out.freshCaptions).toBe(1)
+ })
+
+ it("respects concurrency limit — three caption calls dispatch in parallel when concurrency=3", async () => {
+ // Need three distinct valid base64 strings so each image
+ // hashes to a unique cache key (otherwise dedupe collapses
+ // to one call). `atob` requires legal base64 — `AQ==` /
+ // `Ag==` / `Aw==` are bytes 0x01, 0x02, 0x03 respectively.
+ const b64ByPath: Record<string, string> = {
+ "/abs/a.png": "AQ==",
+ "/abs/b.png": "Ag==",
+ "/abs/c.png": "Aw==",
+ }
+ mockReadBase64.mockImplementation(async (p: string) => ({
+ base64: b64ByPath[p] ?? "AAAA",
+ mimeType: "image/png",
+ }))
+ let inFlight = 0
+ let peakInFlight = 0
+ mockCaption.mockImplementation(async (b64: string) => {
+ inFlight++
+ peakInFlight = Math.max(peakInFlight, inFlight)
+ // Yield one microtask boundary so the worker pool spins up
+ // additional tasks before this one resolves.
+ await Promise.resolve()
+ await new Promise((r) => setTimeout(r, 5))
+ inFlight--
+ return `cap-${b64}`
+ })
+
+ const md = "![](/abs/a.png) ![](/abs/b.png) ![](/abs/c.png)"
+ const out = await captionMarkdownImages("/proj", md, cfg, { concurrency: 3 })
+
+ expect(out.freshCaptions).toBe(3)
+ // With concurrency=3 and ALL three workers spawned before any
+ // resolve, the peak should reach 3. We assert >=2 to leave
+ // some slack for tight scheduler races but still detect
+ // strictly-sequential regressions (peak would be 1).
+ expect(peakInFlight).toBeGreaterThanOrEqual(2)
+ })
+
+ it("calls onProgress after each image with running counts", async () => {
+ const b64ByPath: Record<string, string> = {
+ "/abs/a.png": "AQ==",
+ "/abs/b.png": "Ag==",
+ }
+ mockReadBase64.mockImplementation(async (p: string) => ({
+ base64: b64ByPath[p] ?? "AAAA",
+ mimeType: "image/png",
+ }))
+ mockCaption.mockResolvedValue("c")
+ const progressCalls: Array<{ done: number; total: number }> = []
+
+ const md = "![](/abs/a.png) ![](/abs/b.png)"
+ await captionMarkdownImages("/proj", md, cfg, {
+ onProgress: (done, total) => progressCalls.push({ done, total }),
+ })
+
+ expect(progressCalls).toEqual([
+ { done: 1, total: 2 },
+ { done: 2, total: 2 },
+ ])
+ })
+
+ it("passes surrounding text as contextBefore / contextAfter to captionImage", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("c")
+
+ // Image is sandwiched between recognizable before / after
+ // markers so the slice content is easy to assert on.
+ const before = "Figure 3: Quarterly revenue 2024 — preceding text. ".repeat(2)
+ const after = " Following commentary about the chart. ".repeat(2)
+ const md = `${before}![](/abs/x.png)${after}`
+
+ await captionMarkdownImages("/proj", md, cfg)
+
+ const args = mockCaption.mock.calls[0]
+ const opts = args[4] as { contextBefore: string; contextAfter: string }
+ expect(opts.contextBefore).toContain("Figure 3: Quarterly revenue 2024")
+ expect(opts.contextAfter).toContain("Following commentary about the chart")
+ // The image's own `![](url)` must NOT leak into either side
+ // — slicing is by index/length, not by string match.
+ expect(opts.contextBefore).not.toContain("![](/abs/x.png)")
+ expect(opts.contextAfter).not.toContain("![](/abs/x.png)")
+ })
+
+ it("clamps context windows at document boundaries (no out-of-range read)", async () => {
+ mockReadBase64.mockResolvedValue({ base64: "AAAA", mimeType: "image/png" })
+ mockCaption.mockResolvedValue("c")
+
+ // Image at the very start: contextBefore must be empty string.
+ // Image at the very end: contextAfter must be empty string.
+ const md1 = "![](/abs/start.png) trailing text only"
+ await captionMarkdownImages("/proj", md1, cfg)
+ let opts = mockCaption.mock.calls[0][4] as { contextBefore: string; contextAfter: string }
+ expect(opts.contextBefore).toBe("")
+ expect(opts.contextAfter).toBe(" trailing text only")
+
+ mockCaption.mockClear()
+
+ const md2 = "leading text only ![](/abs/end.png)"
+ await captionMarkdownImages("/proj", md2, cfg)
+ opts = mockCaption.mock.calls[0][4] as { contextBefore: string; contextAfter: string }
+ expect(opts.contextBefore).toBe("leading text only ")
+ expect(opts.contextAfter).toBe("")
+ })
+})
diff --git a/src/lib/image-caption-pipeline.ts b/src/lib/image-caption-pipeline.ts
new file mode 100644
index 00000000..c32199fc
--- /dev/null
+++ b/src/lib/image-caption-pipeline.ts
@@ -0,0 +1,467 @@
+/**
+ * Caption-the-images pipeline + persistent cache.
+ *
+ * Sits between the Rust extractor (which lands images on disk under
+ * `wiki/media/<slug>/`) and the ingest LLM (which sees source
+ * markdown with `![](abs_path)` references). The job is twofold:
+ *
+ * 1. For each image referenced in the source markdown, get a
+ * factual caption from the vision model — using the cache if
+ * we've described those exact bytes before.
+ *
+ * 2. Rewrite the markdown so each `![](path)` becomes
+ * `![<caption>](path)`. The summarizer LLM stripping empty-alt
+ * images is the failure mode this exists to prevent: an alt-
+ * texted image carries enough semantic load that the model
+ * preserves it through paraphrasing.
+ *
+ * Cache key = SHA-256 of image bytes. This makes duplicate images
+ * across PDFs (logos, page headers, recurring chart templates) a
+ * single LLM call across the whole project — without it, a corpus
+ * of slide decks with shared brand assets would caption the same
+ * logo hundreds of times.
+ *
+ * Cache file lives at
+ * `<project>/.llm-wiki/image-caption-cache.json`
+ * keyed `{ "<sha256>": { caption, mimeType, model, capturedAt } }`.
+ * The model + capturedAt fields aren't read by anything yet but
+ * shipping the metadata now means we can implement Phase 4's
+ * "re-caption with new model" without a second cache version.
+ *
+ * Why JSON-on-disk and not LanceDB / sqlite: the cache is small
+ * (10s of KB on real corpora), human-readable for debugging
+ * ("why is this caption wrong?"), and survives `npm run dev`
+ * restarts — no migration story needed when the embedding-side
+ * schema changes. If we ever cache 100k+ images we'll revisit.
+ */
+import { writeFile, readFile, createDirectory, fileExists, readFileAsBase64 } from "@/commands/fs"
+import { captionImage } from "@/lib/vision-caption"
+import type { LlmConfig } from "@/stores/wiki-store"
+import { normalizePath } from "@/lib/path-utils"
+
+interface CaptionEntry {
+ caption: string
+ mimeType: string
+ model: string
+ capturedAt: string
+}
+
+type CaptionCache = Record<string, CaptionEntry>
+
+const CACHE_REL_PATH = ".llm-wiki/image-caption-cache.json"
+
+/**
+ * Compute SHA-256 of a base64 string by decoding to bytes first
+ * (the cache key is the hash of the IMAGE BYTES, not the base64
+ * string — same image encoded with different base64 line-wrap
+ * settings would otherwise miss the cache).
+ *
+ * Uses `crypto.subtle` which is available in both Tauri's webview
+ * and the Node test environment (since Node 19+ exposes the
+ * `webcrypto` shape on `globalThis.crypto`).
+ */
+async function sha256OfBase64(b64: string): Promise<string> {
+ const binary = atob(b64)
+ const bytes = new Uint8Array(binary.length)
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
+ const digest = await crypto.subtle.digest("SHA-256", bytes)
+ return Array.from(new Uint8Array(digest))
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("")
+}
+
+/**
+ * Public read of the on-disk caption cache. Returns the SHA-256 →
+ * caption map, or an empty map when the cache file doesn't exist
+ * yet / is corrupt. Callers (the source-summary safety-net
+ * injector, search result enrichment, etc.) use this to look up
+ * captions by image hash without re-running the LLM.
+ */
+export async function loadCaptionCache(
+ projectPath: string,
+): Promise<Map<string, string>> {
+ const cache = await readCache(projectPath)
+ const out = new Map<string, string>()
+ for (const [hash, entry] of Object.entries(cache)) {
+ out.set(hash, entry.caption)
+ }
+ return out
+}
+
+async function readCache(projectPath: string): Promise<CaptionCache> {
+ const cachePath = `${normalizePath(projectPath)}/${CACHE_REL_PATH}`
+ if (!(await fileExists(cachePath))) return {}
+ try {
+ const raw = await readFile(cachePath)
+ const parsed = JSON.parse(raw) as unknown
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ return parsed as CaptionCache
+ }
+ } catch (err) {
+ // Corrupt cache (e.g. truncated mid-write before we added
+ // atomic writes) — start fresh rather than wedging the whole
+ // ingest pipeline. Log so it's visible in the activity feed.
+ console.warn(
+ `[caption-cache] corrupt cache at ${cachePath}, starting empty:`,
+ err instanceof Error ? err.message : err,
+ )
+ }
+ return {}
+}
+
+async function writeCache(projectPath: string, cache: CaptionCache): Promise<void> {
+ const pp = normalizePath(projectPath)
+ const cachePath = `${pp}/${CACHE_REL_PATH}`
+ // `.llm-wiki/` may not exist on a fresh project — create_directory
+ // is idempotent and chains parents.
+ await createDirectory(`${pp}/.llm-wiki`)
+ // Pretty-print at 2 spaces. Cache files end up in user backups
+ // and source control sometimes; readability outweighs the small
+ // size penalty.
+ await writeFile(cachePath, JSON.stringify(cache, null, 2))
+}
+
+/**
+ * Discover every `![](path)` reference in markdown content.
+ * Returns the LITERAL strings (so we can string-replace later)
+ * along with the captured path.
+ *
+ * Scope:
+ * - Standard markdown image syntax: `![alt](url)` — alt is
+ * captured but ignored when deciding whether to caption (we
+ * re-caption even non-empty alt because user-typed alt text
+ * usually says "Figure 3" — useless to retrieval).
+ * - HTML `<img src="...">`: NOT captured by this regex; we
+ * don't generate those, and re-captioning hand-typed HTML
+ * would surprise the user.
+ * - Reference-style images (`![alt][ref]` + `[ref]: url`): NOT
+ * handled — we don't generate them either. Add support if
+ * it matters.
+ */
+const MD_IMAGE_RE = /(!\[)([^\]]*)(\]\()([^)\s]+)(\))/g
+
+interface ImageRef {
+ full: string // the entire `![alt](url)` substring
+ alt: string
+ url: string
+ /** 0-based offset of the match in the source markdown — used to
+ * slice the surrounding text for context-aware captioning. */
+ index: number
+ /** Length of the entire match including `!`, brackets, parens. */
+ length: number
+}
+
+/**
+ * Window size for context-aware captioning. 150 chars ≈ 30 English
+ * words ≈ 1-2 sentences ≈ 1 short paragraph in CJK. Sized to cover
+ * the typical "high-signal" zone around an image:
+ *
+ * - Figure captions ("Figure 3: Quarterly revenue 2024") sit
+ * immediately after the image and almost always fit in the
+ * first sentence — well under 150 chars.
+ * - Referring sentences ("as shown above", "the chart below
+ * illustrates ...") sit at the END of the preceding paragraph,
+ * also typically the last 1-2 sentences.
+ *
+ * We initially shipped 500 chars/side. Empirically that included
+ * too much unrelated body text on either side of the high-signal
+ * zone, which (a) bloated the LLM prompt with noise the model had
+ * to actively filter out, and (b) tripled the input-token cost
+ * for tiny upside. 150 keeps the figure-caption sweet spot while
+ * staying cheap.
+ *
+ * Tunable here, not in user settings — adding another knob hurts
+ * UX more than it helps the rare user with unusual document shape.
+ */
+const CONTEXT_CHARS = 150
+
+function findImageReferences(markdown: string): ImageRef[] {
+ const out: ImageRef[] = []
+ // Use exec() in a loop instead of matchAll() so we capture
+ // `m.index` (the position in the source) — needed for the
+ // context slicer below.
+ const re = new RegExp(MD_IMAGE_RE.source, MD_IMAGE_RE.flags)
+ let m: RegExpExecArray | null
+ while ((m = re.exec(markdown)) !== null) {
+ out.push({
+ full: m[0],
+ alt: m[2],
+ url: m[4],
+ index: m.index,
+ length: m[0].length,
+ })
+ }
+ return out
+}
+
+/**
+ * Slice the chars BEFORE and AFTER an image match in the source
+ * markdown. Bounds-safe (window clamps to document edges) and
+ * leaves the slices verbatim — no markdown stripping. Other
+ * `![](url)` references that fall inside the window remain in the
+ * raw text; the model handles them fine and removing them risks
+ * hiding "Figure 3 (above) shows ..." style cross-references.
+ */
+function sliceContext(
+ markdown: string,
+ ref: ImageRef,
+ windowChars: number,
+): { before: string; after: string } {
+ const beforeStart = Math.max(0, ref.index - windowChars)
+ const before = markdown.slice(beforeStart, ref.index)
+ const afterStart = ref.index + ref.length
+ const after = markdown.slice(afterStart, afterStart + windowChars)
+ return { before, after }
+}
+
+/**
+ * Caption every distinct image referenced in `markdown`, using the
+ * cache to skip ones we've already described, then rewrite the
+ * markdown to embed each caption as alt text.
+ *
+ * - Distinct = same SHA-256. Two different paths to the same
+ * image content (e.g. mirrored copies of a logo) caption ONCE
+ * and both refs get the same alt text.
+ *
+ * - Failures during a single caption call do NOT abort the batch.
+ * That image keeps its original (usually empty) alt text and
+ * the rest of the document still gets enriched. The error is
+ * logged so the activity feed surfaces "captioned 28/30 images
+ * — 2 failed" type info.
+ *
+ * Returns the rewritten markdown. The caption cache file at
+ * `<project>/.llm-wiki/image-caption-cache.json` is updated as a
+ * side-effect (atomically at the end, NOT per image — partial
+ * writes don't persist if the user cancels mid-batch).
+ *
+ * `urlToAbsPath` is a hook for path resolution: every image URL
+ * we see in the markdown needs to map to an absolute filesystem
+ * path so the Rust read_file_as_base64 command can pick up the
+ * bytes. The default treats non-absolute URLs as wiki-rooted
+ * (mirroring `markdown-image-resolver`), but autoIngest passes a
+ * stricter version that knows the source's media directory.
+ */
+export interface CaptionPipelineOptions {
+ /** Override the default URL→path resolution. */
+ urlToAbsPath?: (url: string) => string | null
+ /** AbortSignal forwarded to each captionImage call. */
+ signal?: AbortSignal
+ /**
+ * Skip URLs that don't pass this filter — used by autoIngest to
+ * caption ONLY the images extracted from the current source
+ * (not random user-typed `![](https://example.com/foo.png)`
+ * references that would otherwise fail with a bogus path).
+ */
+ shouldCaption?: (url: string) => boolean
+ /**
+ * Max parallel caption requests. 1 = strictly sequential.
+ * Defaults to 1 to keep the wire-format change non-breaking;
+ * the ingest pipeline reads this from `multimodalConfig` and
+ * passes the user's chosen value.
+ */
+ concurrency?: number
+ /**
+ * Progress hook fired after each image finishes (ok or failed),
+ * with running counts. Used by ingest to update the activity
+ * feed with "captioning N/M" messages — without it a long
+ * captioning run looks like the pipeline is stuck.
+ */
+ onProgress?: (done: number, total: number) => void
+}
+
+export interface CaptionPipelineResult {
+ /** Rewritten markdown with captions in alt text. */
+ enrichedMarkdown: string
+ /** Number of images we captioned via a fresh LLM call. */
+ freshCaptions: number
+ /** Number of images served from cache. */
+ cachedCaptions: number
+ /** Number of images we tried to caption but failed (logged). */
+ failed: number
+}
+
+export async function captionMarkdownImages(
+ projectPath: string,
+ markdown: string,
+ llmConfig: LlmConfig,
+ options?: CaptionPipelineOptions,
+): Promise<CaptionPipelineResult> {
+ const refs = findImageReferences(markdown)
+ if (refs.length === 0) {
+ return {
+ enrichedMarkdown: markdown,
+ freshCaptions: 0,
+ cachedCaptions: 0,
+ failed: 0,
+ }
+ }
+
+ const filter = options?.shouldCaption ?? (() => true)
+ const targetRefs = refs.filter((r) => filter(r.url))
+ if (targetRefs.length === 0) {
+ return {
+ enrichedMarkdown: markdown,
+ freshCaptions: 0,
+ cachedCaptions: 0,
+ failed: 0,
+ }
+ }
+
+ const cache = await readCache(projectPath)
+ let freshCaptions = 0
+ let cachedCaptions = 0
+ let failed = 0
+ const captionByUrl = new Map<string, string>()
+
+ // De-dupe target refs by URL up front. Two refs to the same URL
+ // (inline + safety-net section) should share one caption call —
+ // and we keep the FIRST occurrence so the context slice anchors
+ // to the inline reference (typically richer surrounding text)
+ // rather than the safety-net section (where every image is
+ // followed by another `![](path)` and very little prose).
+ const uniqueRefs: ImageRef[] = []
+ const seenUrls = new Set<string>()
+ for (const ref of targetRefs) {
+ if (seenUrls.has(ref.url)) continue
+ seenUrls.add(ref.url)
+ uniqueRefs.push(ref)
+ }
+
+ const concurrency = Math.max(1, options?.concurrency ?? 1)
+ const total = uniqueRefs.length
+ let completed = 0
+
+ /**
+ * Process one image: read bytes → check hash cache → call LLM
+ * if miss → record caption. Returns void; mutates the shared
+ * `cache` / `captionByUrl` / counters by closure. Errors are
+ * swallowed (per-image fault tolerance) — captioning ONE image
+ * shouldn't tank a 30-image batch.
+ *
+ * IMPORTANT: this function reads from and writes to `cache`
+ * concurrently when `concurrency > 1`. JS is single-threaded
+ * within a microtask boundary, so the reads/writes themselves
+ * don't race, but two concurrent tasks computing the SAME hash
+ * may both see "no entry" and both call the LLM. That's fine —
+ * we just spend an extra call. The LATER write wins; both
+ * captions are valid anyway.
+ */
+ async function processOne(ref: ImageRef): Promise<void> {
+ const absPath = options?.urlToAbsPath
+ ? options.urlToAbsPath(ref.url)
+ : ref.url.startsWith("/")
+ ? ref.url
+ : `${normalizePath(projectPath)}/wiki/${ref.url}`
+ if (!absPath) {
+ failed++
+ return
+ }
+
+ let bytes: { base64: string; mimeType: string }
+ try {
+ bytes = await readFileAsBase64(absPath)
+ } catch (err) {
+ console.warn(
+ `[caption-pipeline] failed to read ${absPath}:`,
+ err instanceof Error ? err.message : err,
+ )
+ failed++
+ return
+ }
+
+ const hash = await sha256OfBase64(bytes.base64)
+ const hit = cache[hash]
+ if (hit) {
+ captionByUrl.set(ref.url, hit.caption)
+ cachedCaptions++
+ return
+ }
+
+ // Slice surrounding text for context-aware captioning. We
+ // recompute here (rather than precompute alongside the ref)
+ // so the worker pool reads the up-to-date `markdown`
+ // closure; cheap (string slice + indexOf is microseconds).
+ const { before, after } = sliceContext(markdown, ref, CONTEXT_CHARS)
+
+ try {
+ const caption = await captionImage(
+ bytes.base64,
+ bytes.mimeType,
+ llmConfig,
+ options?.signal,
+ { contextBefore: before, contextAfter: after },
+ )
+ cache[hash] = {
+ caption,
+ mimeType: bytes.mimeType,
+ model: llmConfig.model,
+ capturedAt: new Date().toISOString(),
+ }
+ captionByUrl.set(ref.url, caption)
+ freshCaptions++
+ } catch (err) {
+ console.warn(
+ `[caption-pipeline] caption failed for ${absPath}:`,
+ err instanceof Error ? err.message : err,
+ )
+ failed++
+ }
+ }
+
+ // Concurrent worker pool. Each worker pulls from a shared index
+ // pointer — first worker free grabs the next ref, no fancy queue.
+ let nextIdx = 0
+ async function worker(): Promise<void> {
+ while (true) {
+ if (options?.signal?.aborted) return
+ const i = nextIdx++
+ if (i >= uniqueRefs.length) return
+ await processOne(uniqueRefs[i])
+ completed++
+ options?.onProgress?.(completed, total)
+ }
+ }
+
+ await Promise.all(
+ Array.from({ length: Math.min(concurrency, uniqueRefs.length) }, () => worker()),
+ )
+
+ // Persist the (possibly grown) cache. Per-image atomic writes
+ // would survive crashes mid-batch but every-image-disk-write
+ // adds N file syncs to a captioning loop that's already slow;
+ // one write at the end is the right trade.
+ if (freshCaptions > 0) {
+ try {
+ await writeCache(projectPath, cache)
+ } catch (err) {
+ console.warn(
+ `[caption-pipeline] failed to persist cache:`,
+ err instanceof Error ? err.message : err,
+ )
+ }
+ }
+
+ // Rewrite the markdown — replace every captured image ref's alt
+ // text with its caption. We use a callback-style replace rather
+ // than running findImageReferences twice so we can sanitize the
+ // alt text inline (no `]` characters or newlines, both of which
+ // would break the markdown).
+ const enrichedMarkdown = markdown.replace(
+ MD_IMAGE_RE,
+ (whole, openBang, _alt, closeBracket, url, closeParen) => {
+ const caption = captionByUrl.get(url)
+ if (!caption) return whole
+ const safe = caption
+ .replace(/[\r\n]+/g, " ") // collapse newlines
+ .replace(/]/g, ")") // ] would close the alt early
+ .trim()
+ return `${openBang}${safe}${closeBracket}${url}${closeParen}`
+ },
+ )
+
+ return { enrichedMarkdown, freshCaptions, cachedCaptions, failed }
+}
+
+// Exported for direct unit testing — keeps the module surface small
+// while letting the test file pin behavior on the helpers.
+export const __test = { findImageReferences, sha256OfBase64, MD_IMAGE_RE }
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index e0b02ecb..a30e3225 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -12,6 +12,37 @@ import {
extractAndSaveSourceImages,
buildImageMarkdownSection,
} from "@/lib/extract-source-images"
+import { captionMarkdownImages, loadCaptionCache } from "@/lib/image-caption-pipeline"
+import type { MultimodalConfig } from "@/stores/wiki-store"
+
+/**
+ * Resolve the LLM config that the caption pipeline should use.
+ * `null` = captioning is OFF, caller should skip the pipeline
+ * entirely. Otherwise either the main `llmConfig` (when
+ * `useMainLlm` is set) or the dedicated multimodal endpoint
+ * fields, projected into the same `LlmConfig` shape so callers
+ * pass it through to `streamChat` unchanged.
+ */
+function resolveCaptionConfig(
+ mm: MultimodalConfig,
+ mainLlm: LlmConfig,
+): LlmConfig | null {
+ if (!mm.enabled) return null
+ if (mm.useMainLlm) return mainLlm
+ return {
+ provider: mm.provider,
+ apiKey: mm.apiKey,
+ model: mm.model,
+ ollamaUrl: mm.ollamaUrl,
+ customEndpoint: mm.customEndpoint,
+ apiMode: mm.apiMode,
+ // The caption helper hits `streamChat` directly, which doesn't
+ // care about `maxContextSize` (that field is for the analysis
+ // / generation prompt-truncation logic). Keep it set so the
+ // shape matches LlmConfig.
+ maxContextSize: mainLlm.maxContextSize,
+ }
+}
import { buildLanguageDirective } from "@/lib/output-language"
import { detectLanguage } from "@/lib/detect-language"
@@ -250,6 +281,7 @@ async function autoIngestImpl(
const sp = normalizePath(sourcePath)
const activity = useActivityStore.getState()
const fileName = getFileName(sp)
+ console.log(`[ingest:diag] autoIngestImpl ENTRY for "${fileName}" (project="${pp}", source="${sp}")`)
const activityId = activity.addItem({
type: "ingest",
title: fileName,
@@ -267,8 +299,84 @@ async function autoIngestImpl(
])
// ── Cache check: skip re-ingest if source content hasn't changed ──
+ //
+ // Image cascade still runs on cache hits. Reason: a user may have
+ // ingested this source on a previous app version that didn't extract
+ // images yet, or the media dir may have been deleted out from under
+ // us. `extractAndSaveSourceImages` + injection are both idempotent
+ // (deterministic output paths, marker-bracketed replacement), so
+ // re-running them costs only the extraction time and converges the
+ // source-summary page on the current pipeline's contract regardless
+ // of when the file was first ingested.
const cachedFiles = await checkIngestCache(pp, fileName, sourceContent)
+ console.log(`[ingest:diag] cache check for "${fileName}":`, cachedFiles === null ? "MISS (full pipeline)" : `HIT (${cachedFiles.length} cached files)`)
if (cachedFiles !== null) {
+ try {
+ console.log(`[ingest:diag] cache-hit branch: starting image extraction for ${sp}`)
+ const savedImages = await extractAndSaveSourceImages(pp, sp)
+ console.log(`[ingest:diag] cache-hit branch: got ${savedImages.length} image(s)`)
+ if (savedImages.length > 0) {
+ // Caption first (populates the cache), THEN inject — the
+ // safety-net section uses the cache to populate alt text.
+ // Doing them in this order means cache-hit re-runs (e.g.
+ // user re-imports an old PDF after captioning was added)
+ // converge: first run grows the cache, second run uses it.
+ //
+ // Master-toggle gate: when multimodal is OFF the entire
+ // image-cascade is skipped here. This matches the
+ // full-pipeline branch's strip-and-skip behavior for the
+ // cache-hit path, so a user re-importing an old file
+ // after disabling captioning sees images disappear from
+ // the wiki side. (If a previous ingest had already written
+ // a `## Embedded Images` block, it stays — re-import
+ // doesn't proactively scrub old wiki content. The user
+ // would need to delete the wiki/sources/<slug>.md page
+ // to start clean.)
+ const mmCfg = useWikiStore.getState().multimodalConfig
+ if (!mmCfg.enabled) {
+ console.log(
+ `[ingest:caption] cache-hit + disabled — skipping caption + safety-net inject (${savedImages.length} image(s) untouched on disk)`,
+ )
+ } else {
+ const captionLlm = resolveCaptionConfig(mmCfg, llmConfig)
+ if (captionLlm) {
+ try {
+ await captionMarkdownImages(pp, sourceContent, captionLlm, {
+ signal,
+ shouldCaption: (url) =>
+ url.startsWith(`${pp}/wiki/media/${fileName.replace(/\.[^.]+$/, "")}/`),
+ urlToAbsPath: (url) => url,
+ concurrency: mmCfg.concurrency,
+ onProgress: (done, total) =>
+ activity.updateItem(activityId, {
+ detail: `Captioning images... ${done}/${total}`,
+ }),
+ })
+ } catch (err) {
+ console.warn(
+ `[ingest:caption] cache-hit caption pass failed:`,
+ err instanceof Error ? err.message : err,
+ )
+ }
+ }
+ await injectImagesIntoSourceSummary(pp, fileName, savedImages)
+ // Re-embed the source-summary page so caption text lands
+ // in the search index. Without this step, search by image
+ // content stays empty for files ingested before captioning
+ // was added — the safety-net section was just rewritten
+ // with captions, but the embeddings still reflect the old
+ // empty-alt content.
+ await reembedSourceSummary(pp, fileName)
+ }
+ } else {
+ console.log(`[ingest:diag] cache-hit branch: skipping injection (no images returned from extraction)`)
+ }
+ } catch (err) {
+ console.warn(
+ `[ingest:images] cache-hit injection failed for "${fileName}":`,
+ err instanceof Error ? err.message : err,
+ )
+ }
activity.updateItem(activityId, {
status: "done",
detail: `Skipped (unchanged) — ${cachedFiles.length} files from previous ingest`,
@@ -295,16 +403,109 @@ async function autoIngestImpl(
// Failure here is never fatal — extractAndSaveSourceImages logs
// and returns [] on any error.
activity.updateItem(activityId, { detail: "Extracting embedded images..." })
+ console.log(`[ingest:diag] full-pipeline branch: starting image extraction for ${sp}`)
const savedImages = await extractAndSaveSourceImages(pp, sp)
+ console.log(`[ingest:diag] full-pipeline branch: got ${savedImages.length} image(s)`)
if (savedImages.length > 0) {
console.log(
`[ingest:images] saved ${savedImages.length} image(s) for "${fileName}" → wiki/media/${fileName.replace(/\.[^.]+$/, "")}/`,
)
}
- const truncatedContent = sourceContent.length > 50000
- ? sourceContent.slice(0, 50000) + "\n\n[...truncated...]"
- : sourceContent
+ // ── Step 0.6: Caption embedded images ─────────────────────────
+ // Now that read_file's combined extraction has put `![](abs_path)`
+ // markers inline in `sourceContent`, walk them and replace the
+ // empty alt text with a vision-model-generated factual caption.
+ // SHA-256-keyed cache (`<project>/.llm-wiki/image-caption-cache.json`)
+ // dedupes across runs and across documents (shared logos / chart
+ // templates caption once, not once per document).
+ //
+ // Why this matters: an empty-alt image gets paraphrased away by
+ // text summarization. With a caption, the alt text carries enough
+ // semantic load that the generation LLM tends to preserve the
+ // image reference inline at the right paragraph.
+ //
+ // Scope: we only caption images whose absolute path lives under
+ // <project>/wiki/media/<source-slug>/ — i.e. images the current
+ // ingest produced. User-typed external URLs in markdown source
+ // documents are passed through untouched.
+ //
+ // Master-toggle behavior: when `multimodalConfig.enabled` is
+ // false, we don't just skip the caption LLM call — we ALSO
+ // strip `![](url)` references from sourceContent before the LLM
+ // sees it, AND skip the post-write safety-net injection further
+ // down. Net effect: the wiki-side pipeline never references
+ // images at all. Without the strip + skip, image references
+ // would leak via two paths:
+ // 1. The LLM-generation prompt sees them in sourceContent and
+ // can preserve them in the generated wiki pages
+ // 2. injectImagesIntoSourceSummary unconditionally appends a
+ // `## Embedded Images` section to wiki/sources/<slug>.md
+ // Both paths land image refs into wiki pages, which then get
+ // embedded → searchable → visible in the search image grid even
+ // though the user disabled captioning. This was the user-
+ // surprising behavior that prompted the fix.
+ //
+ // Rust extraction itself is untouched: images still land on disk
+ // under wiki/media/<slug>/ (cheap), and the raw-source preview
+ // (which renders read_file output directly) still shows them —
+ // that surface is "the source document as-is", separate from
+ // "the curated wiki knowledge".
+ let enrichedSourceContent = sourceContent
+ const mmCfg = useWikiStore.getState().multimodalConfig
+ const captionLlm = resolveCaptionConfig(mmCfg, llmConfig)
+ if (!mmCfg.enabled && savedImages.length > 0) {
+ // Strip `![alt](url)` references — match the same regex shape
+ // we use elsewhere for image refs. Preserve a single space
+ // where the ref used to sit so adjacent words don't fuse.
+ enrichedSourceContent = sourceContent.replace(
+ /!\[[^\]]*\]\([^)\s]+\)/g,
+ " ",
+ )
+ console.log(
+ `[ingest:caption] disabled — stripped image refs from sourceContent (${savedImages.length} image(s) won't appear in wiki pages)`,
+ )
+ } else if (
+ captionLlm &&
+ savedImages.length > 0 &&
+ /!\[\]\(/.test(sourceContent)
+ ) {
+ activity.updateItem(activityId, { detail: "Captioning images..." })
+ const sourceSlug = fileName.replace(/\.[^.]+$/, "")
+ const ourMediaPrefix = `${pp}/wiki/media/${sourceSlug}/`
+ try {
+ const result = await captionMarkdownImages(pp, sourceContent, captionLlm, {
+ signal,
+ // Strict filter: only caption images we know we just
+ // extracted into this source's media directory. Skips any
+ // pre-existing markdown image refs the user may have typed
+ // into the source content (e.g. for hand-authored .md
+ // sources).
+ shouldCaption: (url) => url.startsWith(ourMediaPrefix),
+ urlToAbsPath: (url) => url, // already absolute in our extraction output
+ concurrency: mmCfg.concurrency,
+ onProgress: (done, total) =>
+ activity.updateItem(activityId, {
+ detail: `Captioning images... ${done}/${total}`,
+ }),
+ })
+ enrichedSourceContent = result.enrichedMarkdown
+ console.log(
+ `[ingest:caption] images=${savedImages.length} fresh=${result.freshCaptions} cached=${result.cachedCaptions} failed=${result.failed}`,
+ )
+ } catch (err) {
+ console.warn(
+ `[ingest:caption] pipeline failed for "${fileName}":`,
+ err instanceof Error ? err.message : err,
+ )
+ // Fall through with original (empty-alt) source content —
+ // captioning failure must NEVER break ingest.
+ }
+ }
+
+ 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:
@@ -443,41 +644,12 @@ async function autoIngestImpl(
}
// ── Step 3.5: Append extracted images to the source-summary page ─
- // Reliable image surfacing: regardless of whether the LLM kept any
- // image references in its generated content, we directly append a
- // "## Embedded Images" section to wiki/sources/<slug>.md with the
- // saved image paths. The custom <img> resolver in the markdown
- // preview takes care of rendering them.
- //
- // Idempotent: if a previous ingest already appended this section,
- // we replace it rather than duplicating. The marker comment
- // <!-- llm-wiki:embedded-images --> identifies our injection.
- if (savedImages.length > 0 && !signal?.aborted) {
- try {
- const existing = await tryReadFile(sourceSummaryFullPath)
- if (existing) {
- const newSection = buildImageMarkdownSection(savedImages)
- const marker = "<!-- llm-wiki:embedded-images -->"
- // Wrap the section in marker comments for idempotent
- // replacement on re-ingest.
- const wrapped = `\n\n${marker}\n${newSection.trim()}\n${marker}\n`
- // Strip any prior injection (paired markers) so re-ingest
- // doesn't accumulate stale references when images change.
- const stripped = existing.replace(
- new RegExp(`\\n*${marker}[\\s\\S]*?${marker}\\n*`, "g"),
- "",
- )
- await writeFile(sourceSummaryFullPath, stripped.trimEnd() + wrapped)
- console.log(
- `[ingest:images] injected ${savedImages.length} image reference(s) into ${sourceSummaryPath}`,
- )
- }
- } catch (err) {
- console.warn(
- `[ingest:images] failed to append images to ${sourceSummaryPath}:`,
- err instanceof Error ? err.message : err,
- )
- }
+ // Skipped when the master toggle is off — see Step 0.6 above for
+ // the full rationale. With captioning disabled we also don't
+ // want the safety-net section to slip image refs into the wiki
+ // through the back door.
+ if (mmCfg.enabled && savedImages.length > 0 && !signal?.aborted) {
+ await injectImagesIntoSourceSummary(pp, fileName, savedImages)
}
if (writtenPaths.length > 0) {
@@ -922,6 +1094,121 @@ async function tryReadFile(path: string): Promise<string> {
}
}
+/**
+ * Append (or replace) the embedded-images section on the source-
+ * summary page. Idempotent — paired marker comments bracket our
+ * injection, so re-running this for the same source either:
+ * - replaces an existing injection in-place (image set changed), or
+ * - leaves an existing injection untouched (image set unchanged).
+ *
+ * Falls back to creating a minimal source-summary stub if the
+ * page doesn't exist yet (covers the cache-hit path where the
+ * original LLM-written page may have been deleted by the user but
+ * extracted images are still salvageable, and the rare case where
+ * the LLM wrote the source page under a slightly-different slug
+ * that didn't match `${sourceBaseName}.md`).
+ */
+async function injectImagesIntoSourceSummary(
+ pp: string,
+ fileName: string,
+ savedImages: { relPath: string; page: number | null; sha256?: string }[],
+): Promise<void> {
+ if (savedImages.length === 0) return
+ const sourceBaseName = fileName.replace(/\.[^.]+$/, "")
+ const sourceSummaryPath = `wiki/sources/${sourceBaseName}.md`
+ const sourceSummaryFullPath = `${pp}/${sourceSummaryPath}`
+ console.log(`[ingest:diag] injectImagesIntoSourceSummary: target=${sourceSummaryFullPath}, images=${savedImages.length}`)
+ try {
+ const existing = await tryReadFile(sourceSummaryFullPath)
+ console.log(`[ingest:diag] injectImagesIntoSourceSummary: existing file ${existing ? `read OK (${existing.length} chars)` : "MISSING (will write stub)"}`)
+ // Load captions from the on-disk cache so the safety-net
+ // section embeds caption text as alt — the embedding pipeline
+ // indexes whatever's in the wiki page, so without this, search
+ // by image content (e.g. "find the chart with revenue data")
+ // never matches because alt text was empty.
+ const captionsBySha = await loadCaptionCache(pp)
+ const newSection = buildImageMarkdownSection(savedImages as never, captionsBySha)
+ const marker = "<!-- llm-wiki:embedded-images -->"
+ const wrapped = `\n\n${marker}\n${newSection.trim()}\n${marker}\n`
+ if (existing) {
+ // Strip any prior injection (paired markers) so re-ingest
+ // doesn't accumulate stale references when images change.
+ const stripped = existing.replace(
+ new RegExp(`\\n*${marker}[\\s\\S]*?${marker}\\n*`, "g"),
+ "",
+ )
+ await writeFile(sourceSummaryFullPath, stripped.trimEnd() + wrapped)
+ } else {
+ // Page is missing — write a minimal stub so the user actually
+ // sees the images in the file tree. Without this fallback, the
+ // images sit in wiki/media/<slug>/ with no .md page referencing
+ // them, which means the lint view's orphan-page sweep eventually
+ // reaps the media directory (cascadeDeleteWikiPage triggered by
+ // a missing source page) — silent loss of extracted images.
+ const date = new Date().toISOString().slice(0, 10)
+ const stubFrontmatter = [
+ "---",
+ "type: source",
+ `title: "Source: ${fileName}"`,
+ `created: ${date}`,
+ `updated: ${date}`,
+ `sources: ["${fileName}"]`,
+ "tags: []",
+ "related: []",
+ "---",
+ "",
+ `# Source: ${fileName}`,
+ "",
+ ].join("\n")
+ await writeFile(sourceSummaryFullPath, stubFrontmatter + wrapped)
+ }
+ console.log(
+ `[ingest:images] injected ${savedImages.length} image reference(s) into ${sourceSummaryPath}`,
+ )
+ } catch (err) {
+ console.warn(
+ `[ingest:images] failed to append images to ${sourceSummaryPath}:`,
+ err instanceof Error ? err.message : err,
+ )
+ }
+}
+
+/**
+ * Re-embed the source-summary page after we've rewritten its
+ * `## Embedded Images` safety-net section with captions. The full
+ * autoIngest pipeline calls `embedPage` at step 6 unconditionally;
+ * this is the cache-hit equivalent (where step 6 is skipped) and
+ * exists specifically to keep the search index in sync after a
+ * caption refresh.
+ *
+ * Why not just call `embedPage` inline at the call site: the
+ * embedding store + config lookup, the readFile-then-parse-title
+ * dance, and the no-op behavior when embedding is disabled all
+ * already exist in the step-6 logic. Wrapping them once here
+ * avoids drift between the two paths if either side changes.
+ */
+async function reembedSourceSummary(pp: string, fileName: string): Promise<void> {
+ const embCfg = useWikiStore.getState().embeddingConfig
+ if (!embCfg.enabled || !embCfg.model) return
+ const sourceBaseName = fileName.replace(/\.[^.]+$/, "")
+ const sourceSummaryFullPath = `${pp}/wiki/sources/${sourceBaseName}.md`
+ try {
+ const content = await readFile(sourceSummaryFullPath)
+ const titleMatch = content.match(
+ /^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m,
+ )
+ const title = titleMatch ? titleMatch[1].trim() : sourceBaseName
+ const { embedPage } = await import("@/lib/embedding")
+ await embedPage(pp, sourceBaseName, title, content, embCfg)
+ console.log(`[ingest:caption] re-embedded ${sourceBaseName} with captioned alt text`)
+ } catch (err) {
+ console.warn(
+ `[ingest:caption] re-embed failed for ${sourceBaseName}:`,
+ err instanceof Error ? err.message : err,
+ )
+ }
+}
+
export async function startIngest(
projectPath: string,
sourcePath: string,
@@ -936,6 +1223,22 @@ export async function startIngest(
store.clearMessages()
store.setStreaming(false)
+ // Extract embedded images upfront — independent of the LLM call
+ // that follows. Done eagerly here (rather than in
+ // `executeIngestWrites`) so the images are on disk before the user
+ // even sees the analysis stream, and the cost is only paid once
+ // per source: a follow-up `executeIngestWrites` will reuse the
+ // already-extracted set rather than re-running pdfium.
+ // 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).catch((err) => {
+ console.warn(
+ `[startIngest:images] eager extraction failed for "${getFileName(sp)}":`,
+ err instanceof Error ? err.message : err,
+ )
+ })
+
const [sourceContent, schema, purpose, index] = await Promise.all([
tryReadFile(sp),
tryReadFile(`${pp}/wiki/schema.md`),
@@ -1112,5 +1415,41 @@ export async function executeIngestWrites(
getStore().addMessage("system", "No files were written. The LLM response did not contain valid FILE blocks.")
}
+ // 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.
+ //
+ // 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
+ // parameter (the chat-panel "Save to Wiki" button only passes
+ // projectPath). Skipped silently when there's no ingestSource
+ // (e.g. user manually entered chat mode and called this).
+ const ingestSource = getStore().ingestSource
+ // Master toggle gate — see autoIngestImpl Step 0.6 / 3.5 for
+ // the full rationale. When captioning is disabled, we skip the
+ // safety-net inject here too so the executeIngestWrites path
+ // stays consistent with autoIngest.
+ const mmCfgWrites = useWikiStore.getState().multimodalConfig
+ if (ingestSource && mmCfgWrites.enabled) {
+ try {
+ const savedImages = await extractAndSaveSourceImages(pp, ingestSource)
+ if (savedImages.length > 0) {
+ const fileName = getFileName(ingestSource)
+ await injectImagesIntoSourceSummary(pp, fileName, savedImages)
+ }
+ } catch (err) {
+ console.warn(
+ `[executeIngestWrites:images] post-write injection failed:`,
+ err instanceof Error ? err.message : err,
+ )
+ }
+ }
+
return writtenPaths
}
diff --git a/src/lib/llm-providers.test.ts b/src/lib/llm-providers.test.ts
new file mode 100644
index 00000000..4bfe6573
--- /dev/null
+++ b/src/lib/llm-providers.test.ts
@@ -0,0 +1,163 @@
+/**
+ * Wire-format coverage for `getProviderConfig().buildBody` —
+ * specifically the multimodal `ContentBlock[]` path added in Phase 2
+ * of the multimodal-images plan. The expectation we encode here:
+ *
+ * - Each provider's body produces the EXACT shape that wire
+ * accepts for vision input. Drift in any field name or nesting
+ * (e.g. OpenAI emitting `image: {url}` instead of
+ * `image_url: {url}`, or Anthropic emitting
+ * `mediaType` instead of `media_type`) breaks vision in prod
+ * silently — the wire returns 400 but only when an image is
+ * actually sent, which is rare in our test surface.
+ *
+ * - String content keeps emitting bytes byte-identical to the
+ * pre-Phase-2 shape. This is non-negotiable: regressing the
+ * text wire would break every existing call site.
+ */
+import { describe, it, expect } from "vitest"
+import { getProviderConfig, type ChatMessage, type ContentBlock } from "./llm-providers"
+import type { LlmConfig } from "@/stores/wiki-store"
+
+const TINY_PNG_B64 =
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABXvMqOgAAAABJRU5ErkJggg=="
+
+function mkConfig(over: Partial<LlmConfig>): LlmConfig {
+ return {
+ provider: "openai",
+ apiKey: "sk-test",
+ model: "gpt-4o",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 8192,
+ ...over,
+ }
+}
+
+function visionMessage(): ChatMessage {
+ const blocks: ContentBlock[] = [
+ { type: "text", text: "What's in this image?" },
+ { type: "image", mediaType: "image/png", dataBase64: TINY_PNG_B64 },
+ ]
+ return { role: "user", content: blocks }
+}
+
+describe("OpenAI buildBody — vision content", () => {
+ it("emits image_url block with data: URL framing", () => {
+ const cfg = mkConfig({ provider: "openai" })
+ const body = getProviderConfig(cfg).buildBody([visionMessage()]) as {
+ messages: Array<{ role: string; content: unknown }>
+ }
+ expect(body.messages).toHaveLength(1)
+ const content = body.messages[0].content as Array<{ type: string }>
+ expect(content).toHaveLength(2)
+ expect(content[0]).toEqual({ type: "text", text: "What's in this image?" })
+ expect(content[1]).toEqual({
+ type: "image_url",
+ image_url: { url: `data:image/png;base64,${TINY_PNG_B64}` },
+ })
+ })
+
+ it("flattens single-text-block array back to a string (avoids accidentally regressing text-only callers)", () => {
+ const cfg = mkConfig({ provider: "openai" })
+ const msg: ChatMessage = {
+ role: "user",
+ content: [{ type: "text", text: "hello world" }],
+ }
+ const body = getProviderConfig(cfg).buildBody([msg]) as {
+ messages: Array<{ content: unknown }>
+ }
+ expect(body.messages[0].content).toBe("hello world")
+ })
+
+ it("string content stays a string (byte-identical to pre-vision wire)", () => {
+ const cfg = mkConfig({ provider: "openai" })
+ const body = getProviderConfig(cfg).buildBody([
+ { role: "user", content: "hi" },
+ ]) as { messages: Array<{ content: unknown }> }
+ expect(body.messages[0].content).toBe("hi")
+ })
+})
+
+describe("Anthropic buildBody — vision content", () => {
+ it("emits image block with media_type/data inside source", () => {
+ const cfg = mkConfig({ provider: "anthropic", model: "claude-3-5-sonnet-latest" })
+ const body = getProviderConfig(cfg).buildBody([visionMessage()]) as {
+ messages: Array<{ role: string; content: unknown }>
+ }
+ const content = body.messages[0].content as Array<{ type: string }>
+ expect(content).toHaveLength(2)
+ expect(content[0]).toEqual({ type: "text", text: "What's in this image?" })
+ expect(content[1]).toEqual({
+ type: "image",
+ source: { type: "base64", media_type: "image/png", data: TINY_PNG_B64 },
+ })
+ })
+
+ it("flattens system content with images by dropping image blocks (anthropic doesn't accept system images)", () => {
+ const cfg = mkConfig({ provider: "anthropic", model: "claude-3-5-sonnet-latest" })
+ const sys: ChatMessage = {
+ role: "system",
+ content: [
+ { type: "text", text: "be terse" },
+ { type: "image", mediaType: "image/png", dataBase64: TINY_PNG_B64 },
+ ],
+ }
+ const body = getProviderConfig(cfg).buildBody([
+ sys,
+ { role: "user", content: "ok" },
+ ]) as { system?: string; messages: unknown[] }
+ expect(body.system).toBe("be terse")
+ })
+})
+
+describe("Google buildBody — vision content", () => {
+ it("emits parts with inline_data for images", () => {
+ const cfg = mkConfig({ provider: "google", model: "gemini-2.5-pro" })
+ const body = getProviderConfig(cfg).buildBody([visionMessage()]) as {
+ contents: Array<{ role: string; parts: unknown[] }>
+ }
+ const parts = body.contents[0].parts as Array<Record<string, unknown>>
+ expect(parts).toHaveLength(2)
+ expect(parts[0]).toEqual({ text: "What's in this image?" })
+ expect(parts[1]).toEqual({
+ inline_data: { mime_type: "image/png", data: TINY_PNG_B64 },
+ })
+ })
+})
+
+describe("Ollama / custom (chat_completions) — vision content", () => {
+ it("ollama uses OpenAI-shaped image_url block (works on /v1/chat/completions for vision-capable models)", () => {
+ const cfg = mkConfig({
+ provider: "ollama",
+ model: "qwen2.5vl",
+ ollamaUrl: "http://localhost:11434",
+ })
+ const body = getProviderConfig(cfg).buildBody([visionMessage()]) as {
+ messages: Array<{ content: unknown }>
+ }
+ const content = body.messages[0].content as Array<{ type: string }>
+ expect(content[1]).toMatchObject({
+ type: "image_url",
+ image_url: { url: `data:image/png;base64,${TINY_PNG_B64}` },
+ })
+ })
+
+ it("custom endpoint in chat_completions mode emits the same image_url block", () => {
+ const cfg = mkConfig({
+ provider: "custom",
+ model: "Qwen3.6-27B-Q4_K_M.gguf",
+ customEndpoint: "http://192.168.1.50:8000/v1",
+ apiMode: "chat_completions",
+ })
+ const body = getProviderConfig(cfg).buildBody([visionMessage()]) as {
+ messages: Array<{ content: unknown }>
+ }
+ const content = body.messages[0].content as Array<{ type: string }>
+ expect(content).toHaveLength(2)
+ expect(content[1]).toMatchObject({
+ type: "image_url",
+ image_url: { url: `data:image/png;base64,${TINY_PNG_B64}` },
+ })
+ })
+})
diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.ts
index 4d7be0ca..d6a06bb7 100644
--- a/src/lib/llm-providers.ts
+++ b/src/lib/llm-providers.ts
@@ -1,8 +1,37 @@
import type { LlmConfig } from "@/stores/wiki-store"
+/**
+ * One piece of a multimodal message body. Text + image is the only
+ * shape we use today; the discriminated union makes it cheap to
+ * extend (audio, file, tool_result …) without re-typing every
+ * call site.
+ *
+ * `dataBase64` holds the raw image bytes encoded as base64 — NOT a
+ * `data:` URL. The provider-specific translators below own the
+ * `data:image/png;base64,…` framing because each wire prefers a
+ * different shape (OpenAI puts it inside `image_url.url`, Anthropic
+ * splits the mime type out into `source.media_type`, Gemini uses
+ * `inline_data.mime_type`/`inline_data.data`). Putting the framing
+ * in the translators keeps the producer (image extractor) provider-
+ * agnostic.
+ */
+export type ContentBlock =
+ | { type: "text"; text: string }
+ | { type: "image"; mediaType: string; dataBase64: string }
+
export interface ChatMessage {
role: "system" | "user" | "assistant"
- content: string
+ /**
+ * `string` is the legacy shape — every existing call site uses it,
+ * and providers that don't speak vision (or callers that don't
+ * have images to send) keep working unchanged.
+ *
+ * `ContentBlock[]` unlocks vision input. Each provider's
+ * `buildBody` translates it into the native wire format; see
+ * `toOpenAiContent` / `toAnthropicContent` / `toGooglePart` /
+ * `extractOllamaImages` below.
+ */
+ content: string | ContentBlock[]
}
/**
@@ -132,6 +161,38 @@ export function parseGoogleLine(line: string): string | null {
}
}
+/**
+ * Translate a `ChatMessage.content` into the OpenAI Chat Completions
+ * `content` field. The wire accepts either a plain string or an
+ * array of `{type:"text"|"image_url", ...}` parts; we use the array
+ * form only when the message actually carries an image, so single-
+ * string requests stay byte-identical to what we sent before vision
+ * existed (avoids accidentally regressing endpoints that lag behind
+ * the spec — quite a few llama.cpp and vLLM builds in the wild
+ * still parse `content: string` faster than `content: [...]`).
+ *
+ * Image bytes are emitted as a `data:` URL inside `image_url.url`.
+ * `image_url` accepts both URLs and data URLs; data URL keeps every
+ * byte in the request (no follow-up GET from the model server),
+ * which is what we want for desktop-LLM endpoints that may not
+ * have outbound network access at all.
+ */
+function toOpenAiContent(content: string | ContentBlock[]): unknown {
+ if (typeof content === "string") return content
+ // Pure-text block array → flatten to a string so we don't force
+ // every provider proxy to handle parts. Same wire either way.
+ if (content.every((b) => b.type === "text")) {
+ return content.map((b) => (b.type === "text" ? b.text : "")).join("")
+ }
+ return content.map((b) => {
+ if (b.type === "text") return { type: "text", text: b.text }
+ return {
+ type: "image_url",
+ image_url: { url: `data:${b.mediaType};base64,${b.dataBase64}` },
+ }
+ })
+}
+
function buildOpenAiBody(
messages: ChatMessage[],
overrides?: RequestOverrides,
@@ -139,7 +200,55 @@ function buildOpenAiBody(
// OpenAI (and every /v1/chat/completions clone — DeepSeek, Groq,
// Ollama, Zhipu, Kimi, xAI, MiniMax OpenAI-compat, ...) accepts these
// knobs at the top level using the names clients already send.
- return { messages, stream: true, ...(overrides ?? {}) }
+ const translated = messages.map((m) => ({
+ role: m.role,
+ content: toOpenAiContent(m.content),
+ }))
+ return { messages: translated, stream: true, ...(overrides ?? {}) }
+}
+
+/**
+ * Translate `ChatMessage.content` into Anthropic Messages
+ * `content`. Anthropic requires the array form for any non-text
+ * block, and uses a different shape than OpenAI for images
+ * (`source.media_type` + `source.data` instead of a `data:` URL).
+ *
+ * For system messages, Anthropic accepts the top-level `system`
+ * field as a string OR as a content-block array. We always
+ * stringify system content here because every existing system-
+ * prompt call site sends a string and the round-trip through
+ * blocks is lossy.
+ */
+function toAnthropicContent(content: string | ContentBlock[]): unknown {
+ if (typeof content === "string") return content
+ if (content.every((b) => b.type === "text")) {
+ return content.map((b) => (b.type === "text" ? b.text : "")).join("")
+ }
+ return content.map((b) => {
+ if (b.type === "text") return { type: "text", text: b.text }
+ return {
+ type: "image",
+ source: {
+ type: "base64",
+ media_type: b.mediaType,
+ data: b.dataBase64,
+ },
+ }
+ })
+}
+
+/**
+ * Anthropic's top-level `system` field is a string, not blocks.
+ * If a caller puts images inside a system message we drop them —
+ * Anthropic doesn't accept system-level images today, and silently
+ * losing them is the lesser evil compared to the request 400ing
+ * out for "Unsupported content block in system".
+ */
+function flattenAnthropicSystem(content: string | ContentBlock[]): string {
+ if (typeof content === "string") return content
+ return content
+ .map((b) => (b.type === "text" ? b.text : ""))
+ .join("")
}
function buildAnthropicBody(
@@ -147,8 +256,12 @@ function buildAnthropicBody(
overrides?: RequestOverrides,
): Record<string, unknown> {
const systemMessages = messages.filter((m) => m.role === "system")
- const conversationMessages = messages.filter((m) => m.role !== "system")
- const system = systemMessages.map((m) => m.content).join("\n") || undefined
+ const conversationMessages = messages
+ .filter((m) => m.role !== "system")
+ .map((m) => ({ role: m.role, content: toAnthropicContent(m.content) }))
+ const system =
+ systemMessages.map((m) => flattenAnthropicSystem(m.content)).join("\n") ||
+ undefined
// Anthropic Messages uses top_p / top_k (Python-style snake_case), a
// mandatory `max_tokens`, and `stop_sequences` instead of `stop`.
@@ -225,6 +338,31 @@ function buildAnthropicHeaders(apiKey: string, url: string): Record<string, stri
return base
}
+/**
+ * Translate `ChatMessage.content` into Gemini `parts`. Gemini's
+ * native shape is already block-like (`parts: [{text}|{inline_data}]`)
+ * so the mapping is mostly cosmetic — we don't try to flatten
+ * single-text-block arrays because Gemini accepts the array form
+ * uniformly.
+ */
+function toGoogleParts(content: string | ContentBlock[]): unknown[] {
+ if (typeof content === "string") return [{ text: content }]
+ return content.map((b) => {
+ if (b.type === "text") return { text: b.text }
+ return {
+ inline_data: {
+ mime_type: b.mediaType,
+ data: b.dataBase64,
+ },
+ }
+ })
+}
+
+function flattenGoogleSystemParts(content: string | ContentBlock[]): string {
+ if (typeof content === "string") return content
+ return content.map((b) => (b.type === "text" ? b.text : "")).join("")
+}
+
function buildGoogleBody(
messages: ChatMessage[],
overrides?: RequestOverrides,
@@ -234,13 +372,17 @@ function buildGoogleBody(
const contents = conversationMessages.map((m) => ({
role: m.role === "assistant" ? "model" : "user",
- parts: [{ text: m.content }],
+ parts: toGoogleParts(m.content),
}))
+ // Gemini's `systemInstruction.parts` is a `parts` array but in
+ // practice every consumer flattens it to a string equivalent —
+ // images in a system instruction are not a documented use case.
+ // Keep it text-only.
const systemInstruction =
systemMessages.length > 0
? {
- parts: systemMessages.map((m) => ({ text: m.content })),
+ parts: systemMessages.map((m) => ({ text: flattenGoogleSystemParts(m.content) })),
}
: undefined
diff --git a/src/lib/project-store.ts b/src/lib/project-store.ts
index e0f268a3..dfc2aa25 100644
--- a/src/lib/project-store.ts
+++ b/src/lib/project-store.ts
@@ -1,6 +1,6 @@
import { load } from "@tauri-apps/plugin-store"
import type { WikiProject } from "@/types/wiki"
-import type { LlmConfig, SearchApiConfig, EmbeddingConfig, OutputLanguage, ProviderConfigs } from "@/stores/wiki-store"
+import type { LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProviderConfigs } from "@/stores/wiki-store"
const STORE_NAME = "app-state.json"
const RECENT_PROJECTS_KEY = "recentProjects"
@@ -96,6 +96,18 @@ export async function loadEmbeddingConfig(): Promise<EmbeddingConfig | null> {
return (await store.get<EmbeddingConfig>(EMBEDDING_KEY)) ?? null
}
+const MULTIMODAL_KEY = "multimodalConfig"
+
+export async function saveMultimodalConfig(config: MultimodalConfig): Promise<void> {
+ const store = await getStore()
+ await store.set(MULTIMODAL_KEY, config)
+}
+
+export async function loadMultimodalConfig(): Promise<MultimodalConfig | null> {
+ const store = await getStore()
+ return (await store.get<MultimodalConfig>(MULTIMODAL_KEY)) ?? null
+}
+
export async function removeFromRecentProjects(
path: string
): Promise<void> {
diff --git a/src/lib/raw-source-resolver.ts b/src/lib/raw-source-resolver.ts
new file mode 100644
index 00000000..924b8a69
--- /dev/null
+++ b/src/lib/raw-source-resolver.ts
@@ -0,0 +1,87 @@
+/**
+ * Map a wiki-side image reference back to its raw source file.
+ *
+ * Image URLs we generate always live under
+ * `<project>/wiki/media/<slug>/img-N.<ext>`
+ * — emitted either ABSOLUTE (from the unified Rust extractor that
+ * runs at `read_file` time) or WIKI-RELATIVE
+ * (`media/<slug>/img-N.png`, from the post-write safety-net section
+ * in `wiki/sources/<slug>.md`). The slug equals the basename of
+ * the original raw source file (we wrote it that way at extraction
+ * time in `extract_pdf_markdown` / fs.rs's raw-sources-layout
+ * heuristic), so finding the raw file is a stem match against
+ * `<project>/raw/sources/`.
+ *
+ * Used in two places that want to "open the original document
+ * around this image" rather than its LLM summary:
+ * - search-view's lightbox "Jump to source document" button
+ * - chat references panel's image badge (Phase 4 multimodal UI)
+ *
+ * Returns null when:
+ * - the URL doesn't match the expected media-directory shape, OR
+ * - no file with that stem exists under raw/sources/ (e.g. the
+ * user moved / deleted the original after ingest, leaving only
+ * the wiki summary). Callers fall back gracefully.
+ */
+import { listDirectory } from "@/commands/fs"
+import type { FileNode } from "@/types/wiki"
+
+export async function findRawSourceForImage(
+ imageUrl: string,
+ projectPath: string,
+): Promise<string | null> {
+ // Image URLs reach us in TWO shapes:
+ // 1. ABSOLUTE: `/Users/.../wiki/media/<slug>/img-N.png`
+ // 2. WIKI-RELATIVE: `media/<slug>/img-N.png`
+ // Match `media/<slug>/` either at the URL start or after any `/`.
+ const m = imageUrl.replace(/\\/g, "/").match(/(?:^|\/)media\/([^/]+)\//)
+ if (!m) return null
+ const slug = m[1]
+
+ let tree: FileNode[]
+ try {
+ tree = await listDirectory(`${projectPath}/raw/sources`)
+ } catch {
+ return null
+ }
+
+ const findByStem = (nodes: FileNode[]): string | null => {
+ for (const node of nodes) {
+ if (node.is_dir) {
+ if (node.children) {
+ const found = findByStem(node.children)
+ if (found) return found
+ }
+ continue
+ }
+ const stem = node.name.replace(/\.[^.]+$/, "")
+ if (stem === slug) return node.path
+ }
+ return null
+ }
+
+ return findByStem(tree)
+}
+
+/**
+ * Normalize a markdown image URL to the absolute-path form that
+ * the unified Rust extractor emits in raw-source previews. Used
+ * by jump-to-source code paths that want to set a `<img data-mdsrc>`
+ * scroll target on the raw-source preview — the raw side renders
+ * absolute URLs, so a wiki-relative URL we got from a wiki page's
+ * safety-net section needs to be promoted to absolute first.
+ *
+ * Idempotent: passing an already-absolute URL returns it unchanged.
+ */
+export function imageUrlToAbsolute(
+ imageUrl: string,
+ projectPath: string,
+): string {
+ const isAbsolute =
+ imageUrl.startsWith("/") ||
+ /^[a-zA-Z]:/.test(imageUrl) ||
+ imageUrl.startsWith("\\\\")
+ if (isAbsolute) return imageUrl
+ const cleaned = imageUrl.replace(/^\.\//, "")
+ return `${projectPath.replace(/\/+$/, "")}/wiki/${cleaned}`
+}
diff --git a/src/lib/search.ts b/src/lib/search.ts
index 947453e4..2223c910 100644
--- a/src/lib/search.ts
+++ b/src/lib/search.ts
@@ -2,12 +2,34 @@ import { readFile, listDirectory } from "@/commands/fs"
import type { FileNode } from "@/types/wiki"
import { normalizePath, getFileStem } from "@/lib/path-utils"
+/**
+ * One image reference extracted from a matched page's markdown.
+ *
+ * `url` is verbatim what was inside the `![](...)` parens — this is
+ * a forward-slash path that the markdown image resolver knows how
+ * to map to a renderable URL. We deliberately keep it pre-resolution
+ * so the search-result UI can filter by URL prefix (e.g. "only show
+ * images from this source's media dir") before paying the cost of
+ * `convertFileSrc`.
+ */
+export interface ImageRef {
+ url: string
+ alt: string
+}
+
export interface SearchResult {
path: string
title: string
snippet: string
titleMatch: boolean
score: number
+ /**
+ * Image references found inside this result's markdown. Populated
+ * even when the query doesn't match the alt text — the UI splits
+ * "alt-matches-query" from "image just lives on this matched
+ * page" itself, so both views need the full set. May be empty.
+ */
+ images: ImageRef[]
}
const MAX_RESULTS = 20
@@ -149,6 +171,36 @@ function extractTitle(content: string, fileName: string): string {
return fileName.replace(/\.md$/, "").replace(/-/g, " ")
}
+/**
+ * Markdown image-reference regex. Matches `![alt](url)` capturing
+ * groups 1=alt, 2=url. Identical to the regex in
+ * `image-caption-pipeline.ts` — kept duplicated rather than shared
+ * because the two modules have very different lifetimes (search
+ * runs every keystroke; the pipeline runs at ingest), and a shared
+ * symbol there would tie them together for no benefit.
+ *
+ * Excludes:
+ * - HTML `<img src=...>` (we don't generate these)
+ * - Reference-style `![alt][ref]` (we don't generate these either)
+ */
+const IMAGE_REF_RE = /!\[([^\]]*)\]\(([^)\s]+)\)/g
+
+function extractImageRefs(content: string): ImageRef[] {
+ const seen = new Set<string>()
+ const out: ImageRef[] = []
+ for (const m of content.matchAll(IMAGE_REF_RE)) {
+ const url = m[2]
+ // De-dupe within a single page: the same image may be
+ // referenced both inline (LLM-preserved) AND in the safety-net
+ // "## Embedded Images" section. Showing it twice in the
+ // results UI would just be visual noise.
+ if (seen.has(url)) continue
+ seen.add(url)
+ out.push({ url, alt: m[1] })
+ }
+ return out
+}
+
function buildSnippet(content: string, query: string): string {
const lower = content.toLowerCase()
const lowerQuery = query.toLowerCase()
@@ -175,24 +227,43 @@ export async function searchWiki(
const effectiveTokens = tokens.length > 0 ? tokens : [query.trim().toLowerCase()]
const results: SearchResult[] = []
- // Search wiki pages
+ const tSearchStart = performance.now()
+
+ // Search wiki pages.
+ //
+ // We deliberately do NOT also search `raw/sources/` here anymore.
+ // Previously this section walked every file under raw/sources/
+ // (including PDFs / DOCX / PPTX) and called `readFile` on each,
+ // which triggers the heavy pdfium / office text-extraction path
+ // — even on cache hits, that's an IPC round-trip per file plus
+ // a cache file read of the now-large combined-markdown output
+ // (text + per-page image refs after the unified extractor
+ // landed). On a project with ~50 PDFs this added 5-15s per
+ // search, which the user reported as "very, very slow."
+ //
+ // The content lost: nothing material. Each ingested raw source
+ // produces a `wiki/sources/<slug>.md` summary which is included
+ // in the wiki/ search below; the full extracted text lives in
+ // the embedding chunks and is reachable via vector search. The
+ // raw-files token pass added recall only for raw files that had
+ // never been ingested (and thus had no wiki summary), which is
+ // not a workflow we want to optimize at the cost of every other
+ // search call.
try {
+ const t0 = performance.now()
const wikiTree = await listDirectory(`${pp}/wiki`)
const wikiFiles = flattenMdFiles(wikiTree)
+ const tList = Math.round(performance.now() - t0)
+ const t1 = performance.now()
await searchFiles(wikiFiles, effectiveTokens, query, results)
+ const tRead = Math.round(performance.now() - t1)
+ console.log(
+ `[Search:token] wiki/ ${wikiFiles.length} files | list=${tList}ms read+match=${tRead}ms`,
+ )
} catch {
// no wiki directory
}
- // Also search raw sources (extracted text)
- try {
- const rawTree = await listDirectory(`${pp}/raw/sources`)
- const rawFiles = flattenAllFiles(rawTree)
- await searchFiles(rawFiles, effectiveTokens, query, results)
- } catch {
- // no raw sources
- }
-
// ── Build the token-side ranking (still based on the score field
// populated by searchFiles above). Snapshot it BEFORE the vector
// step, so adding vector-only pages doesn't shift token ranks.
@@ -248,6 +319,7 @@ export async function searchWiki(
snippet: buildSnippet(content, query),
titleMatch: false,
score: 0, // overwritten by RRF below
+ images: extractImageRefs(content),
})
knownIds.add(vr.id)
added++
@@ -297,86 +369,129 @@ export async function searchWiki(
return results.slice(0, MAX_RESULTS)
}
+/**
+ * Bound on concurrent `readFile` calls during search. Going wider
+ * than this saturates the Tauri IPC channel and starts QUEUING
+ * work behind the search request — the wider you go, the SLOWER
+ * a single search gets past about 16-32 in-flight reads (measured
+ * in dev against a 200-file project). 16 is a comfortable middle
+ * ground that gives near-linear speedup over sequential without
+ * choking the IPC layer.
+ */
+const SEARCH_READ_CONCURRENCY = 16
+
+/**
+ * Punctuation pattern shared between token splitting and the
+ * phrase-bonus normalization below. Matched at start AND end of
+ * the query — internal punctuation (`U.S.A.`, `2024-Q3`) stays
+ * because it might be load-bearing in legitimate phrase matches.
+ */
+const TRIM_PUNCT_RE =
+ /^[\s,,。!?、;:""''()()\-_/\\·~~…]+|[\s,,。!?、;:""''()()\-_/\\·~~…]+$/g
+
async function searchFiles(
files: FileNode[],
tokens: readonly string[],
query: string,
results: SearchResult[],
): Promise<void> {
- const queryPhrase = query.trim().toLowerCase()
-
- for (const file of files) {
- let content = ""
- try {
- content = await readFile(file.path)
- } catch {
- continue
- }
-
- const title = extractTitle(content, file.name)
- const titleText = `${title} ${file.name}`
- const titleLower = titleText.toLowerCase()
- const contentLower = content.toLowerCase()
- const fileStem = file.name.replace(/\.md$/, "").toLowerCase()
-
- // Exact-match signals (strongest)
- const filenameExact = fileStem === queryPhrase
- const titleHasPhrase =
- queryPhrase.length > 0 && titleLower.includes(queryPhrase)
- const contentPhraseOcc = Math.min(
- countOccurrences(contentLower, queryPhrase),
- MAX_PHRASE_OCC_COUNTED,
+ // Strip leading / trailing punctuation from the query before using
+ // it as a phrase-bonus probe. Without this, `query="总资产。"`
+ // tries to substring-match `总资产。` inside titles / content that
+ // never have the period at that spot — the phrase-bonus signal
+ // (worth +50 in titles, +20 per occurrence in content) silently
+ // goes to zero and the page's RRF rank slides. Same surface that
+ // bit the search-view image filter, fixed there in token space;
+ // here we apply the analog in phrase space.
+ //
+ // Internal punctuation is preserved on purpose: queries like
+ // "2024-Q3" or domain names should still phrase-match exactly.
+ const queryPhrase = query.trim().toLowerCase().replace(TRIM_PUNCT_RE, "")
+
+ // Process files in fixed-size concurrent batches. Promise.all over
+ // the entire list would work but spawns N IPC calls simultaneously
+ // — tested at N=200, that's where we saw the slowdown above.
+ for (let i = 0; i < files.length; i += SEARCH_READ_CONCURRENCY) {
+ const batch = files.slice(i, i + SEARCH_READ_CONCURRENCY)
+ const batchResults = await Promise.all(
+ batch.map(async (file) => {
+ let content: string
+ try {
+ content = await readFile(file.path)
+ } catch {
+ return null
+ }
+ return scoreFile(file, content, tokens, queryPhrase, query)
+ }),
)
-
- // Token-level signals (fallback / density)
- const titleTokenScore = tokenMatchScore(titleText, tokens)
- const contentTokenScore = tokenMatchScore(content, tokens)
-
- // Must have at least one signal to be included
- if (
- !filenameExact &&
- !titleHasPhrase &&
- contentPhraseOcc === 0 &&
- titleTokenScore === 0 &&
- contentTokenScore === 0
- ) {
- continue
+ for (const r of batchResults) {
+ if (r) results.push(r)
}
-
- const score =
- (filenameExact ? FILENAME_EXACT_BONUS : 0) +
- (titleHasPhrase ? PHRASE_IN_TITLE_BONUS : 0) +
- contentPhraseOcc * PHRASE_IN_CONTENT_PER_OCC +
- titleTokenScore * TITLE_TOKEN_WEIGHT +
- contentTokenScore * CONTENT_TOKEN_WEIGHT
-
- const isTitleMatch = titleTokenScore > 0 || titleHasPhrase
-
- // Prefer snipping around the full phrase when it exists; otherwise
- // pick the first matching token; otherwise the raw query.
- const snippetAnchor =
- contentPhraseOcc > 0
- ? queryPhrase
- : tokens.find((t) => contentLower.includes(t)) ?? query
-
- results.push({
- path: file.path,
- title,
- snippet: buildSnippet(content, snippetAnchor),
- titleMatch: isTitleMatch,
- score,
- })
}
}
-function flattenAllFiles(nodes: FileNode[]): FileNode[] {
- const files: FileNode[] = []
- for (const node of nodes) {
- if (node.is_dir && node.children) {
- files.push(...flattenAllFiles(node.children))
- } else if (!node.is_dir) {
- files.push(node)
- }
+/**
+ * Pure scoring pass — no IO. Extracted so `searchFiles` can run
+ * the IO and the matching independently and so this function can
+ * be unit-tested without mocking readFile.
+ */
+function scoreFile(
+ file: FileNode,
+ content: string,
+ tokens: readonly string[],
+ queryPhrase: string,
+ query: string,
+): SearchResult | null {
+ const title = extractTitle(content, file.name)
+ const titleText = `${title} ${file.name}`
+ const titleLower = titleText.toLowerCase()
+ const contentLower = content.toLowerCase()
+ const fileStem = file.name.replace(/\.md$/, "").toLowerCase()
+
+ // Exact-match signals (strongest)
+ const filenameExact = fileStem === queryPhrase
+ const titleHasPhrase =
+ queryPhrase.length > 0 && titleLower.includes(queryPhrase)
+ const contentPhraseOcc = Math.min(
+ countOccurrences(contentLower, queryPhrase),
+ MAX_PHRASE_OCC_COUNTED,
+ )
+
+ // Token-level signals (fallback / density)
+ const titleTokenScore = tokenMatchScore(titleText, tokens)
+ const contentTokenScore = tokenMatchScore(content, tokens)
+
+ if (
+ !filenameExact &&
+ !titleHasPhrase &&
+ contentPhraseOcc === 0 &&
+ titleTokenScore === 0 &&
+ contentTokenScore === 0
+ ) {
+ return null
+ }
+
+ const score =
+ (filenameExact ? FILENAME_EXACT_BONUS : 0) +
+ (titleHasPhrase ? PHRASE_IN_TITLE_BONUS : 0) +
+ contentPhraseOcc * PHRASE_IN_CONTENT_PER_OCC +
+ titleTokenScore * TITLE_TOKEN_WEIGHT +
+ contentTokenScore * CONTENT_TOKEN_WEIGHT
+
+ const isTitleMatch = titleTokenScore > 0 || titleHasPhrase
+
+ const snippetAnchor =
+ contentPhraseOcc > 0
+ ? queryPhrase
+ : tokens.find((t) => contentLower.includes(t)) ?? query
+
+ return {
+ path: file.path,
+ title,
+ snippet: buildSnippet(content, snippetAnchor),
+ titleMatch: isTitleMatch,
+ score,
+ images: extractImageRefs(content),
}
- return files
}
+
diff --git a/src/lib/vision-caption.real-llm.test.ts b/src/lib/vision-caption.real-llm.test.ts
new file mode 100644
index 00000000..480ac9f0
--- /dev/null
+++ b/src/lib/vision-caption.real-llm.test.ts
@@ -0,0 +1,97 @@
+/**
+ * Real-LLM probe: drive `captionImage` against a vision endpoint
+ * (defaults to LM Studio at 192.168.1.218:1234, override via
+ * VISION_ENDPOINT / VISION_MODEL env vars). Verifies the WHOLE
+ * captioning path end-to-end, not just the wire shape:
+ *
+ * ContentBlock[] → buildOpenAiBody → SSE stream
+ * → parseOpenAiLine → onToken → captionImage joins → trimmed string
+ *
+ * What the assertions actually check:
+ * - The returned string is non-empty (rules out the "thinking
+ * mode burns all max_tokens" failure mode that bit Phase 2).
+ * - The caption mentions "red" (case-insensitive) or 红色 — proves
+ * the model both received the image AND reasoned about it,
+ * not just ran a hard-coded "I see an image" reply.
+ *
+ * Skipped when the endpoint isn't reachable in <2s. Lives in
+ * `.real-llm.` so the fast suite ignores it.
+ */
+import { describe, it, expect, vi } from "vitest"
+
+vi.mock("@tauri-apps/api/core", () => ({
+ invoke: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock("@/commands/fs", () => ({
+ readFile: vi.fn(),
+ listDirectory: vi.fn(),
+}))
+
+import { captionImage } from "./vision-caption"
+import type { LlmConfig } from "@/stores/wiki-store"
+
+const DEFAULT_ENDPOINT = "http://192.168.1.218:1234/v1"
+const DEFAULT_MODEL = "qwen3.5-4b"
+const ENDPOINT = process.env.VISION_ENDPOINT ?? DEFAULT_ENDPOINT
+const MODEL = process.env.VISION_MODEL ?? DEFAULT_MODEL
+const REACHABILITY_TIMEOUT_MS = 2000
+const TEST_TIMEOUT_MS = 180_000
+
+// Same 64×64 solid-red PNG used in vision.real-llm.test.ts.
+// Pinned base64 of the raw bytes (NOT a data: URL — that framing
+// is added by the OpenAI provider translator).
+const RED_PNG_64_B64 =
+ "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAb0lEQVR4nO3PAQkAAAyEwO9feoshgnABdLep8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3IPanc8OLDQitxAAAAAElFTkSuQmCC"
+
+async function isEndpointReachable(url: string, timeoutMs: number): Promise<boolean> {
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
+ try {
+ await fetch(url.replace(/\/+$/, "") + "/models", { signal: controller.signal })
+ return true
+ } catch {
+ return false
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+describe("captionImage E2E (real LLM)", () => {
+ it(
+ "returns a non-empty caption mentioning 'red' for a solid-red image",
+ async () => {
+ const reachable = await isEndpointReachable(ENDPOINT, REACHABILITY_TIMEOUT_MS)
+ if (!reachable) {
+ console.warn(`[vision-caption.real-llm] ${ENDPOINT} not reachable — skipping`)
+ return
+ }
+
+ const cfg: LlmConfig = {
+ provider: "custom",
+ apiKey: "",
+ model: MODEL,
+ ollamaUrl: "",
+ customEndpoint: ENDPOINT,
+ apiMode: "chat_completions",
+ maxContextSize: 8192,
+ }
+
+ const caption = await captionImage(RED_PNG_64_B64, "image/png", cfg)
+ console.log(`[vision-caption.real-llm] caption: "${caption}"`)
+
+ expect(caption.length, "caption is non-empty").toBeGreaterThan(0)
+ const mentionsRed = /\bred\b/i.test(caption) || caption.includes("红")
+ expect(
+ mentionsRed,
+ `expected caption to mention "red" or "红"; got: "${caption}"`,
+ ).toBe(true)
+
+ // Plain text contract: no markdown structure leaking out.
+ // The pinned prompt explicitly bans this; this assertion
+ // catches drift in the model's instruction-following.
+ expect(caption).not.toMatch(/^#+\s/m) // no heading lines
+ expect(caption).not.toMatch(/```/) // no fenced code blocks
+ },
+ TEST_TIMEOUT_MS,
+ )
+})
diff --git a/src/lib/vision-caption.test.ts b/src/lib/vision-caption.test.ts
new file mode 100644
index 00000000..01438e9b
--- /dev/null
+++ b/src/lib/vision-caption.test.ts
@@ -0,0 +1,183 @@
+/**
+ * Unit coverage for `captionImage`. Mocks streamChat so we can
+ * pin the wire shape (one user message, text+image content blocks,
+ * exact prompt) without hitting the network.
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+// `vi.mock` is hoisted to the top of the file before imports run.
+// A plain `const mockStreamChat = vi.fn()` outside the factory
+// would be in a TDZ when the factory executes — `vi.hoisted`
+// hoists the declaration alongside the mock so the factory sees a
+// real fn.
+const { mockStreamChat } = vi.hoisted(() => ({ mockStreamChat: vi.fn() }))
+vi.mock("./llm-client", async () => {
+ const actual = await vi.importActual<typeof import("./llm-client")>("./llm-client")
+ return {
+ ...actual,
+ streamChat: mockStreamChat,
+ }
+})
+
+import { captionImage, CAPTION_PROMPT } from "./vision-caption"
+import type { LlmConfig } from "@/stores/wiki-store"
+import type { ChatMessage } from "./llm-providers"
+
+const cfg: LlmConfig = {
+ provider: "custom",
+ apiKey: "",
+ model: "vl-model",
+ ollamaUrl: "",
+ customEndpoint: "http://example/v1",
+ apiMode: "chat_completions",
+ maxContextSize: 8192,
+}
+
+const TINY_B64 = "iVBORw0KGgo="
+
+beforeEach(() => {
+ mockStreamChat.mockReset()
+})
+
+describe("captionImage", () => {
+ it("sends one user message with text+image blocks and the pinned prompt", async () => {
+ mockStreamChat.mockImplementation(
+ async (
+ _config: LlmConfig,
+ _messages: ChatMessage[],
+ callbacks: { onToken: (t: string) => void; onDone: () => void; onError: (e: Error) => void },
+ ) => {
+ callbacks.onToken("a red square")
+ callbacks.onDone()
+ },
+ )
+
+ const out = await captionImage(TINY_B64, "image/png", cfg)
+ expect(out).toBe("a red square")
+
+ expect(mockStreamChat).toHaveBeenCalledTimes(1)
+ const messages = mockStreamChat.mock.calls[0][1] as ChatMessage[]
+ expect(messages).toHaveLength(1)
+ expect(messages[0].role).toBe("user")
+ const blocks = messages[0].content as Array<{ type: string }>
+ expect(blocks).toHaveLength(2)
+ expect(blocks[0]).toEqual({ type: "text", text: CAPTION_PROMPT })
+ expect(blocks[1]).toEqual({
+ type: "image",
+ mediaType: "image/png",
+ dataBase64: TINY_B64,
+ })
+ })
+
+ it("joins multiple streamed tokens into one trimmed string", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onToken(" Red ")
+ cb.onToken("square ")
+ cb.onToken("on white ")
+ cb.onDone()
+ })
+
+ const out = await captionImage(TINY_B64, "image/png", cfg)
+ // Trailing/leading whitespace removed; INNER spaces preserved.
+ expect(out).toBe("Red square on white")
+ })
+
+ it("rethrows when streamChat reports an error (no silent empty caption)", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onError(new Error("HTTP 500: model unavailable"))
+ })
+
+ await expect(captionImage(TINY_B64, "image/png", cfg)).rejects.toThrow(
+ /HTTP 500: model unavailable/,
+ )
+ })
+
+ it("passes through temperature and maxTokens overrides to streamChat", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onDone()
+ })
+
+ await captionImage(TINY_B64, "image/png", cfg, undefined, {
+ temperature: 0.3,
+ maxTokens: 256,
+ })
+
+ const overrides = mockStreamChat.mock.calls[0][4]
+ expect(overrides).toEqual({ temperature: 0.3, max_tokens: 256 })
+ })
+
+ it("uses defaults (temp=0, max_tokens=4096) when no options passed", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onDone()
+ })
+
+ await captionImage(TINY_B64, "image/png", cfg)
+
+ const overrides = mockStreamChat.mock.calls[0][4]
+ expect(overrides).toEqual({ temperature: 0, max_tokens: 4096 })
+ })
+
+ it("forwards the AbortSignal to streamChat (lets callers cancel batch captioning)", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onDone()
+ })
+
+ const ctl = new AbortController()
+ await captionImage(TINY_B64, "image/png", cfg, ctl.signal)
+
+ const passedSignal = mockStreamChat.mock.calls[0][3]
+ expect(passedSignal).toBe(ctl.signal)
+ })
+
+ it("CAPTION_PROMPT contains the verbatim factual-description directive (regression guard)", () => {
+ // Plan-aligned wording — if these phrases drift, captions
+ // start hallucinating again. Check the load-bearing fragments.
+ expect(CAPTION_PROMPT).toMatch(/factually/)
+ expect(CAPTION_PROMPT).toMatch(/visible text verbatim/)
+ expect(CAPTION_PROMPT).toMatch(/Do NOT speculate/)
+ expect(CAPTION_PROMPT).toMatch(/no markdown/)
+ })
+
+ it("uses the no-context prompt when context is empty / whitespace-only", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onDone()
+ })
+
+ // Empty / whitespace-only counts as "no context" — should NOT
+ // upgrade to the longer context prompt with `(none)` blocks
+ // (that would just waste tokens telling the model nothing).
+ await captionImage(TINY_B64, "image/png", cfg, undefined, {
+ contextBefore: " \n ",
+ contextAfter: "",
+ })
+ const messages = mockStreamChat.mock.calls[0][1] as Array<{
+ content: Array<{ type: string; text?: string }>
+ }>
+ const promptText = messages[0].content[0].text ?? ""
+ expect(promptText).toBe(CAPTION_PROMPT)
+ })
+
+ it("switches to the context-aware prompt when EITHER side has content", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onDone()
+ })
+
+ await captionImage(TINY_B64, "image/png", cfg, undefined, {
+ contextBefore: "Figure 3: Q2 revenue chart",
+ contextAfter: "",
+ })
+ const messages = mockStreamChat.mock.calls[0][1] as Array<{
+ content: Array<{ type: string; text?: string }>
+ }>
+ const promptText = messages[0].content[0].text ?? ""
+ // Pinned framing sentences from the context-aware prompt:
+ expect(promptText).toMatch(/Text before image/)
+ expect(promptText).toMatch(/Text after image/)
+ expect(promptText).toMatch(/MAY help describe the image/)
+ expect(promptText).toMatch(/MAY ALSO be unrelated/)
+ // The actual context bytes round-trip through the prompt.
+ expect(promptText).toContain("Figure 3: Q2 revenue chart")
+ // Empty side becomes `(none)` so the structure is uniform.
+ expect(promptText).toMatch(/Text after image ---\s*\(none\)/)
+ })
+})
diff --git a/src/lib/vision-caption.ts b/src/lib/vision-caption.ts
new file mode 100644
index 00000000..9706c088
--- /dev/null
+++ b/src/lib/vision-caption.ts
@@ -0,0 +1,214 @@
+/**
+ * Vision-caption helper. Sends one image + a fixed factual prompt to a
+ * vision-capable LLM and returns the model's plain-text description.
+ *
+ * Why this exists:
+ *
+ * The image-extraction step (Phase 1) lands raster images on disk
+ * under `wiki/media/<source-slug>/`, but the text we hand to the
+ * ingest LLM contains those images as `![](...)` references with
+ * EMPTY alt text — meaningless to a text-only summarizer. Generation
+ * models silently strip empty-alt images when paraphrasing the
+ * source, so wiki pages that should reference figures end up with
+ * no figure at all. Worse: the embedding side has no semantic
+ * signal for those images, so chart-only PDF pages embed as their
+ * surrounding text only and rank far below where they should.
+ *
+ * captionImage solves both: a 2-4 sentence factual description per
+ * image gives the summarizer something to preserve, and (post-
+ * Phase 5) gives the embedding step token-bearing content to
+ * index alongside the image bytes.
+ *
+ * What this is NOT:
+ *
+ * This module knows nothing about ingest, caching, or where the
+ * image lives on disk. The caller passes raw base64 + mediaType,
+ * handles persistence (Phase 3b layers caching + ingest wiring on
+ * top), and decides whether to run captioning at all (Phase 4
+ * adds a settings toggle).
+ *
+ * Cost model (read this before you call this in a loop):
+ *
+ * Each call is one round-trip to the vision endpoint with the full
+ * image bytes inline. A 100-page paper with 30 figures = 30 vision
+ * calls. Caching by image SHA-256 (Phase 3b) lets duplicate logos
+ * / chart templates / academic-figure boilerplate dedupe to one
+ * call across an entire corpus — without it the cost scales
+ * linearly with figure count and we'll routinely 10x the budget
+ * on chart-heavy decks.
+ */
+import type { LlmConfig } from "@/stores/wiki-store"
+import { streamChat, type ChatMessage } from "./llm-client"
+
+/**
+ * The "no surrounding text" prompt — same factual / verbatim /
+ * no-speculation framing we've used since Phase 3a. Used when the
+ * caller has no context to supply (e.g. a captioning helper called
+ * directly without a document, or when context is intentionally
+ * disabled). Pinned, not parameterized.
+ *
+ * Reasons:
+ * - Factual / no-speculation framing reduces hallucination
+ * ("Describe ... factually" vs. "What is this?"). Ablation
+ * against an early "describe this image" prompt produced
+ * captions like "this appears to be a successful business
+ * metric" for a literal screenshot of a SQL query.
+ *
+ * - Verbatim text capture matters for diagrams, slide bullets,
+ * and figure callouts — a vision model will paraphrase OCR
+ * unless told not to.
+ *
+ * - 2-4 sentences is the sweet spot empirically: 1 sentence
+ * loses chart-axis detail; 6+ sentences burns tokens AND
+ * produces editorial filler that hurts retrieval relevance.
+ *
+ * - "no markdown, no preamble" prevents the caption from breaking
+ * when we splice it as alt text (`![CAPTION](path)` — newlines
+ * or markdown inside CAPTION corrupt the surrounding doc).
+ */
+export const CAPTION_PROMPT =
+ "Describe this image factually for a knowledge-base index. Include: any visible text verbatim, chart axes and values, diagram structure (boxes/arrows/labels), key visual elements. Do NOT speculate or editorialize. 2 to 4 sentences. Output plain text only — no markdown, no preamble."
+
+/**
+ * Build the prompt that gets used WHEN the caller supplies
+ * surrounding text. Wraps the no-context prompt with an explicit
+ * "here is the document text around this image — it may or may
+ * not be related, you decide" frame.
+ *
+ * Empty / whitespace-only sides collapse to "(none)" rather than
+ * leaving an empty delimited block, which some models try to
+ * interpret as silence-is-meaningful and produce odd captions
+ * about. The brackets stay so the structure is uniform.
+ */
+export function buildCaptionPromptWithContext(
+ before: string,
+ after: string,
+): string {
+ const fmt = (s: string) => {
+ const trimmed = s.trim()
+ return trimmed.length > 0 ? trimmed : "(none)"
+ }
+ return [
+ "The image is embedded in a longer document. Here is the text that appears IMMEDIATELY BEFORE and AFTER this image in the source:",
+ "",
+ "--- Text before image ---",
+ fmt(before),
+ "--- Text after image ---",
+ fmt(after),
+ "--- End surrounding text ---",
+ "",
+ "This surrounding text MAY help describe the image — for example, a sentence like \"Figure 3: Q2 revenue chart\" tells you what the chart actually plots. It MAY ALSO be unrelated body text that just happens to flank the image. Use your judgment: if a passage clearly identifies, references, or labels the image, anchor your caption to it; if not, ignore the surrounding text and describe what you see.",
+ "",
+ "Now describe the image factually for a knowledge-base index. Include: any visible text verbatim, chart axes and values, diagram structure (boxes/arrows/labels), key visual elements. If the surrounding text contains a relevant figure number / caption / referent, incorporate that specifically. Do NOT invent details that aren't visible in the image or directly stated in the surrounding text. 2 to 4 sentences. Output plain text only — no markdown, no preamble.",
+ ].join("\n")
+}
+
+export interface CaptionOptions {
+ /** Bound the model's output. Captions live inline in markdown
+ * alt text, so 200-400 tokens covers our pinned 2-4 sentences
+ * with margin for thinking-mode budgets. Default 4096 lets
+ * reasoning models (Qwen3, R1) think AND answer; bump higher
+ * if your model's `<think>` block reliably exceeds that. */
+ maxTokens?: number
+ /** Sampling. Caption-quality work wants determinism — we want
+ * the same image to caption the same way across runs (so the
+ * per-image hash cache from Phase 3b is meaningful). 0 makes
+ * the model greedy. */
+ temperature?: number
+ /**
+ * Document text immediately preceding/following the image in the
+ * source. When BOTH are present (or even one), we switch to the
+ * context-aware prompt that explicitly tells the model the text
+ * may or may not be relevant — the model decides. Without these
+ * the no-context prompt is used.
+ *
+ * Caller responsibility:
+ * - Trim/truncate to a sensible window (the caller knows the
+ * wider document; this helper just frames whatever it gets).
+ * - Don't include the image's own `![](url)` markdown in either
+ * side — the caller's slice should be the text BEFORE and
+ * AFTER the image's match in the source markdown.
+ * - Empty string is fine (treated as "no preceding/following
+ * text"); we'll mark it `(none)` in the prompt so the model
+ * sees the structure without an empty delimited block.
+ */
+ contextBefore?: string
+ contextAfter?: string
+}
+
+/**
+ * Caption a single image. Returns the joined caption text with
+ * surrounding whitespace stripped — newlines and trailing spaces
+ * inside the caption are PRESERVED (some captions legitimately
+ * contain line breaks for OCR'd multiline labels).
+ *
+ * `imageBase64` must be the raw base64 of the image bytes, NOT a
+ * `data:` URL. The provider translator owns the `data:image/png;
+ * base64,...` framing — passing an already-data-URL'd value would
+ * double-frame it and the wire would 400.
+ *
+ * Errors: any LLM error (network, HTTP non-2xx, timeout) propagates
+ * through `streamChat`'s `onError` and is rethrown here as a thrown
+ * Error. Callers wanting fault-tolerance (skip-on-fail in batch
+ * captioning) should `try/catch` and decide their own policy.
+ */
+export async function captionImage(
+ imageBase64: string,
+ mediaType: string,
+ llmConfig: LlmConfig,
+ signal?: AbortSignal,
+ options?: CaptionOptions,
+): Promise<string> {
+ // 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
+ // the longer prompt with `(none)`/`(none)` blocks — that just
+ // wastes tokens.
+ const before = options?.contextBefore?.trim() ?? ""
+ const after = options?.contextAfter?.trim() ?? ""
+ const promptText =
+ before.length > 0 || after.length > 0
+ ? buildCaptionPromptWithContext(before, after)
+ : CAPTION_PROMPT
+
+ const messages: ChatMessage[] = [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: promptText },
+ { type: "image", mediaType, dataBase64: imageBase64 },
+ ],
+ },
+ ]
+
+ const tokens: string[] = []
+ let streamError: Error | null = null
+
+ await streamChat(
+ llmConfig,
+ messages,
+ {
+ onToken: (t) => tokens.push(t),
+ onDone: () => {},
+ onError: (e) => {
+ streamError = e
+ },
+ },
+ signal,
+ {
+ temperature: options?.temperature ?? 0,
+ max_tokens: options?.maxTokens ?? 4096,
+ },
+ )
+
+ if (streamError) {
+ // streamChat reports HTTP / network errors via onError but
+ // resolves cleanly — re-throw so the caller can `try/catch`
+ // the caption call as a unit. Without this re-throw, a 500
+ // from the vision endpoint silently produces empty caption
+ // text and the ingest pipeline indexes images as untitled.
+ throw streamError as Error
+ }
+
+ return tokens.join("").trim()
+}
diff --git a/src/lib/vision.real-llm.test.ts b/src/lib/vision.real-llm.test.ts
new file mode 100644
index 00000000..76ea43d0
--- /dev/null
+++ b/src/lib/vision.real-llm.test.ts
@@ -0,0 +1,213 @@
+/**
+ * Real-LLM probe: drive `streamChat` against a vision-capable
+ * OpenAI-compatible endpoint (defaults to the user's Qwen3.6 box at
+ * 192.168.1.50:8000) with a `ContentBlock[]` carrying one image.
+ *
+ * What this verifies (end-to-end):
+ * - `buildOpenAiBody` → `toOpenAiContent` produces a body the
+ * vision model actually accepts (vs. the unit tests which just
+ * check the JSON shape against our expectation).
+ * - The streaming response is parsed by `parseOpenAiLine` and
+ * reaches our `onToken` callback.
+ * - The model "looked at" the image — we assert the response
+ * mentions either "red" / "color" / a non-trivial substring.
+ * A pure-text endpoint would just answer "I cannot see any
+ * image" or hallucinate, which the assertion catches.
+ *
+ * Lives in a `.real-llm.` file so the fast suite skips it (it hits
+ * a real network and a real GPU). Override the endpoint and model
+ * via env if your setup differs:
+ *
+ * VISION_ENDPOINT=http://localhost:8000/v1 \
+ * VISION_MODEL=Qwen2.5-VL-7B-Instruct \
+ * npx vitest run src/lib/vision.real-llm.test.ts
+ *
+ * Default skip path: when VISION_ENDPOINT is unset AND the default
+ * host (192.168.1.50:8000) isn't reachable in <2s, the test is
+ * skipped rather than failed. Lets contributors without the LAN
+ * box still run the rest of the .real-llm.* suite.
+ */
+import { describe, it, expect, vi } from "vitest"
+
+// Same module-graph stubs as llm-client.real-llm.test.ts — streamChat
+// transitively imports stores that touch Tauri commands during init.
+vi.mock("@tauri-apps/api/core", () => ({
+ invoke: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock("@/commands/fs", () => ({
+ readFile: vi.fn(),
+ listDirectory: vi.fn(),
+}))
+
+import { streamChat } from "./llm-client"
+import type { LlmConfig } from "@/stores/wiki-store"
+import type { ChatMessage } from "./llm-providers"
+
+const DEFAULT_ENDPOINT = "http://192.168.1.50:8000/v1"
+const DEFAULT_MODEL = "Qwen3.6-27B-Q4_K_M.gguf"
+const ENDPOINT = process.env.VISION_ENDPOINT ?? DEFAULT_ENDPOINT
+const MODEL = process.env.VISION_MODEL ?? DEFAULT_MODEL
+const REACHABILITY_TIMEOUT_MS = 2000
+const TEST_TIMEOUT_MS = 120_000
+
+/**
+ * Solid-red 64×64 PNG, deterministically generated and pinned as
+ * base64. We started with a 1×1 pixel which several vision-model
+ * loaders rejected with "Failed to load image" / "Invalid image
+ * detected" — too small for typical image preprocessing pipelines
+ * that downsample/normalize the input. 64×64 is enough to clear
+ * those guards while still keeping the request under 1KB.
+ *
+ * Pinned (not computed at runtime) so the test stays deterministic
+ * and works without a PNG encoder dependency in the test env.
+ */
+const RED_PNG_64_B64 = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAb0lEQVR4nO3PAQkAAAyEwO9feoshgnABdLep8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3IPanc8OLDQitxAAAAAElFTkSuQmCC"
+
+async function isEndpointReachable(url: string, timeoutMs: number): Promise<boolean> {
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
+ try {
+ // /v1/models is the canonical liveness probe for OpenAI-compat
+ // servers. We don't actually care about the response body — a
+ // socket-level success means the host is up, which is what the
+ // skip gate cares about.
+ const probe = url.replace(/\/+$/, "") + "/models"
+ await fetch(probe, { signal: controller.signal })
+ return true
+ } catch {
+ return false
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+describe("vision wire E2E (real LLM)", () => {
+ it(
+ "text-only baseline — endpoint is alive and our SSE parser sees its output",
+ async () => {
+ const reachable = await isEndpointReachable(ENDPOINT, REACHABILITY_TIMEOUT_MS)
+ if (!reachable) {
+ console.warn(`[vision.real-llm] ${ENDPOINT} not reachable — skipping`)
+ return
+ }
+ const cfg: LlmConfig = {
+ provider: "custom",
+ apiKey: "",
+ model: MODEL,
+ ollamaUrl: "",
+ customEndpoint: ENDPOINT,
+ apiMode: "chat_completions",
+ maxContextSize: 8192,
+ }
+ const tokens: string[] = []
+ const state: { done: boolean; error: Error | null } = { done: false, error: null }
+ await streamChat(
+ cfg,
+ [{ role: "user", content: "Say the single word: ready" }],
+ {
+ onToken: (t) => tokens.push(t),
+ onDone: () => {
+ state.done = true
+ },
+ onError: (e) => {
+ state.error = e
+ },
+ },
+ undefined,
+ // max_tokens is the budget for the *answer*, not just the
+ // visible content — Qwen3 / DeepSeek-R1-style models stream
+ // their internal reasoning in `delta.reasoning_content`
+ // FIRST, then the actual answer in `delta.content` after
+ // the </think> boundary. Our `parseOpenAiLine` only
+ // surfaces `delta.content`, so a small max_tokens like 16
+ // gets entirely consumed by reasoning and the visible
+ // stream stays empty. 4096 leaves room for both.
+ { temperature: 0, max_tokens: 4096 },
+ )
+ const body = tokens.join("").trim()
+ console.log(`[vision.real-llm:text-baseline] tokens=${tokens.length} body="${body}"`)
+ expect(state.error, `text-baseline error: ${state.error?.message}`).toBeNull()
+ expect(state.done).toBe(true)
+ expect(body.length, "text-only response is non-empty (proves the endpoint+parser pipeline works at all)").toBeGreaterThan(0)
+ },
+ TEST_TIMEOUT_MS,
+ )
+
+ it(
+ "OpenAI-compat endpoint accepts ContentBlock[] with image and produces a description",
+ async () => {
+ // Skip rather than fail when the LAN endpoint isn't reachable —
+ // contributors without that machine still get to run the rest
+ // of the .real-llm.* suite.
+ const reachable = await isEndpointReachable(ENDPOINT, REACHABILITY_TIMEOUT_MS)
+ if (!reachable) {
+ console.warn(`[vision.real-llm] ${ENDPOINT} not reachable in ${REACHABILITY_TIMEOUT_MS}ms — skipping`)
+ return
+ }
+
+ const cfg: LlmConfig = {
+ provider: "custom",
+ apiKey: "",
+ model: MODEL,
+ ollamaUrl: "",
+ customEndpoint: ENDPOINT,
+ apiMode: "chat_completions",
+ maxContextSize: 8192,
+ }
+
+ const messages: ChatMessage[] = [
+ {
+ role: "user",
+ content: [
+ {
+ type: "text",
+ text: "What single color fills this image? Reply with one English word.",
+ },
+ {
+ type: "image",
+ mediaType: "image/png",
+ dataBase64: RED_PNG_64_B64,
+ },
+ ],
+ },
+ ]
+
+ const tokens: string[] = []
+ const state: { done: boolean; error: Error | null } = { done: false, error: null }
+
+ await streamChat(
+ cfg,
+ messages,
+ {
+ onToken: (t) => tokens.push(t),
+ onDone: () => {
+ state.done = true
+ },
+ onError: (e) => {
+ state.error = e
+ },
+ },
+ undefined,
+ // See text-baseline test for max_tokens rationale (Qwen3
+ // thinking-mode tokens count against this budget).
+ { temperature: 0, max_tokens: 4096 },
+ )
+
+ const body = tokens.join("").trim()
+ console.log(`[vision.real-llm] model="${MODEL}" replied: "${body}"`)
+
+ expect(state.error, `streamChat error: ${state.error?.message}`).toBeNull()
+ expect(state.done, "stream finished cleanly").toBe(true)
+ expect(body.length, "response is non-empty").toBeGreaterThan(0)
+
+ // Behavioral assertion — the model should "see" red. We
+ // accept "red" in any case and tolerate trailing punctuation
+ // / Chinese 红色 (some Qwen builds prefer answering in the
+ // model's pretraining-dominant language regardless of the
+ // prompt language).
+ const matchesRed = /\bred\b/i.test(body) || body.includes("红")
+ expect(matchesRed, `expected "red" or "红" in response; got: "${body}"`).toBe(true)
+ },
+ TEST_TIMEOUT_MS,
+ )
+})
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index 04a004ce..049bdb94 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -46,6 +46,49 @@ interface EmbeddingConfig {
overlapChunkChars?: number
}
+/**
+ * Image-captioning settings (Phase 4 of the multimodal-images plan).
+ *
+ * Decoupled from `llmConfig` because vision-capable endpoints are
+ * usually NOT the same model the user picks for analysis/generation:
+ * - the analysis stage often goes to a strong text-only model (Claude
+ * Sonnet, DeepSeek, etc.) that doesn't speak vision at all;
+ * - captioning is happy with a small local VL model (Qwen2.5-VL-7B,
+ * LLaVA-1.6) that costs near-zero per call.
+ *
+ * `enabled` is the master gate. When false the caption pipeline is
+ * skipped entirely — `read_file`'s extracted images still appear
+ * inline (with empty alt text) and the safety-net `## Embedded
+ * Images` section still gets written, but we never touch the LLM.
+ *
+ * `useMainLlm`: when true (the default for first-time users we
+ * onboard), captioning calls go through the same `llmConfig`
+ * everything else uses. When false, the dedicated fields below are
+ * sent through the same provider machinery — same `streamChat`,
+ * same `getProviderConfig`, no duplicate code.
+ *
+ * `concurrency` bounds parallel caption requests during ingest.
+ * 30-image PDFs with sequential captioning at ~10s/image (a Qwen3
+ * thinking model on consumer GPU) take 5 minutes. At concurrency=4
+ * that drops to ~75s. Going wider than 8 typically just queues
+ * behind a single-GPU server's batch slot, so we cap the slider
+ * UI at a tasteful max in the settings view.
+ */
+interface MultimodalConfig {
+ enabled: boolean
+ /** Reuse `llmConfig` for caption calls. When true, the fields
+ * below are ignored. */
+ useMainLlm: boolean
+ provider: LlmConfig["provider"]
+ apiKey: string
+ model: string
+ ollamaUrl: string
+ customEndpoint: string
+ apiMode?: CustomApiMode
+ /** Max parallel caption requests during ingest. >=1. */
+ concurrency: number
+}
+
/**
* Output language for LLM-generated content (wiki pages, chat responses, research).
* "auto" = detect from user input / source document language.
@@ -94,6 +137,21 @@ interface WikiState {
fileTree: FileNode[]
selectedFile: string | null
fileContent: string
+ /**
+ * One-shot scroll target for the markdown preview. When the user
+ * clicks an image in search results and chooses "jump to source",
+ * we set this to the image URL alongside `selectedFile`. The
+ * markdown preview consumes it on its next render — finds the
+ * `<img data-mdsrc="..."/>` whose attribute matches and scrolls
+ * it into view, then clears this back to null so a stale target
+ * doesn't fire on the NEXT page open.
+ *
+ * Match by raw URL (the literal `src` from the markdown) rather
+ * than the resolved `convertFileSrc` URL — same image referenced
+ * across two pages with different URL conventions (one absolute,
+ * one wiki-relative) still works.
+ */
+ pendingScrollImageSrc: string | null
chatExpanded: boolean
activeView: "wiki" | "sources" | "search" | "graph" | "lint" | "review" | "settings"
llmConfig: LlmConfig
@@ -103,6 +161,7 @@ interface WikiState {
activePresetId: string | null
searchApiConfig: SearchApiConfig
embeddingConfig: EmbeddingConfig
+ multimodalConfig: MultimodalConfig
outputLanguage: OutputLanguage
dataVersion: number
@@ -110,6 +169,7 @@ interface WikiState {
setFileTree: (tree: FileNode[]) => void
setSelectedFile: (path: string | null) => void
setFileContent: (content: string) => void
+ setPendingScrollImageSrc: (src: string | null) => void
setChatExpanded: (expanded: boolean) => void
setActiveView: (view: WikiState["activeView"]) => void
setLlmConfig: (config: LlmConfig) => void
@@ -117,6 +177,7 @@ interface WikiState {
setActivePresetId: (id: string | null) => void
setSearchApiConfig: (config: SearchApiConfig) => void
setEmbeddingConfig: (config: EmbeddingConfig) => void
+ setMultimodalConfig: (config: MultimodalConfig) => void
setOutputLanguage: (lang: OutputLanguage) => void
bumpDataVersion: () => void
}
@@ -126,6 +187,7 @@ export const useWikiStore = create<WikiState>((set) => ({
fileTree: [],
selectedFile: null,
fileContent: "",
+ pendingScrollImageSrc: null,
chatExpanded: false,
activeView: "wiki",
llmConfig: {
@@ -145,6 +207,7 @@ export const useWikiStore = create<WikiState>((set) => ({
setFileTree: (fileTree) => set({ fileTree }),
setSelectedFile: (selectedFile) => set({ selectedFile }),
setFileContent: (fileContent) => set({ fileContent }),
+ setPendingScrollImageSrc: (pendingScrollImageSrc) => set({ pendingScrollImageSrc }),
setChatExpanded: (chatExpanded) => set({ chatExpanded }),
setActiveView: (activeView) => set({ activeView }),
searchApiConfig: {
@@ -159,6 +222,23 @@ export const useWikiStore = create<WikiState>((set) => ({
model: "",
},
+ multimodalConfig: {
+ // Off by default — captioning is a non-trivial token spend
+ // (one VLM call per extracted image), and silently turning it
+ // on for every user the first time they import a PDF would be
+ // a budget surprise. Users who want it flip the toggle in
+ // Settings → Image captioning.
+ enabled: false,
+ useMainLlm: true,
+ provider: "custom",
+ apiKey: "",
+ model: "",
+ ollamaUrl: "http://localhost:11434",
+ customEndpoint: "",
+ apiMode: "chat_completions",
+ concurrency: 4,
+ },
+
outputLanguage: "auto",
setLlmConfig: (llmConfig) => set({ llmConfig }),
@@ -166,8 +246,9 @@ export const useWikiStore = create<WikiState>((set) => ({
setActivePresetId: (activePresetId) => set({ activePresetId }),
setSearchApiConfig: (searchApiConfig) => set({ searchApiConfig }),
setEmbeddingConfig: (embeddingConfig) => set({ embeddingConfig }),
+ setMultimodalConfig: (multimodalConfig) => set({ multimodalConfig }),
setOutputLanguage: (outputLanguage) => set({ outputLanguage }),
bumpDataVersion: () => set((state) => ({ dataVersion: state.dataVersion + 1 })),
}))
-export type { WikiState, LlmConfig, SearchApiConfig, EmbeddingConfig, OutputLanguage }
+export type { WikiState, LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage }
diff --git a/src/test-helpers/scenarios/search-scenarios.ts b/src/test-helpers/scenarios/search-scenarios.ts
index 2910b36c..69f9800e 100644
--- a/src/test-helpers/scenarios/search-scenarios.ts
+++ b/src/test-helpers/scenarios/search-scenarios.ts
@@ -171,4 +171,39 @@ export const searchScenarios: SearchScenario[] = [
topResultPaths: ["wiki/phrase-page.md"],
},
},
+
+ // 8. trailing-punct-phrase-bonus — same query with a Chinese full stop
+ // appended must still apply the phrase-match bonus. Pre-fix,
+ // "总资产。" produced an exact-substring miss on titles / content
+ // (no trailing period there) and the phrase bonus silently went to
+ // zero, demoting the truly relevant page below tangentially-
+ // related ones in the chat-context priority order.
+ {
+ name: "trailing-punct-phrase-bonus",
+ description:
+ "Query '总资产。' (with trailing 。). Page with '总资产' in BOTH title " +
+ "and content should still rank first and titleMatch=true, the same " +
+ "as if the user had typed '总资产' without the period.",
+ initialWiki: {
+ "wiki/zong-zi-chan.md": page(
+ "总资产分析",
+ "公司 2023 年总资产合计 4.2 亿元;总资产同比增长 12%。",
+ ),
+ // Unrelated page must NOT contain "资" / "产" / "总" anywhere
+ // — the CJK tokenizer breaks "总资产" into bigrams + single
+ // chars, so a page mentioning even one of those characters
+ // would match via the partial token route, which is correct
+ // behavior we don't want to confuse this scenario with.
+ "wiki/unrelated.md": page(
+ "其他主题",
+ "本页讨论天气、足球与厨艺,跟当前查询完全无关。",
+ ),
+ },
+ query: "总资产。",
+ expected: {
+ topResultPaths: ["wiki/zong-zi-chan.md"],
+ titleMatchPaths: ["wiki/zong-zi-chan.md"],
+ excludedPaths: ["wiki/unrelated.md"],
+ },
+ },
]