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: support EPUB and MOBI sources
nash_su9d95f79bb378
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 1b8f287d..cc91b651 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2219,7 +2219,7 @@ dependencies = ["bit-set","cssparser","foldhash 0.2.0",- "html5ever",+ "html5ever 0.38.0","precomputed-hash","selectors","tendril",@@ -2308,6 +2308,70 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"+[[package]]+name = "encoding"+version = "0.2.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b0d943856b990d12d3b55b359144ff341533e516d94098b1d3fc1ac666d36ec"+dependencies = [+ "encoding-index-japanese",+ "encoding-index-korean",+ "encoding-index-simpchinese",+ "encoding-index-singlebyte",+ "encoding-index-tradchinese",+]++[[package]]+name = "encoding-index-japanese"+version = "1.20141219.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04e8b2ff42e9a05335dbf8b5c6f7567e5591d0d916ccef4e0b1710d32a0d0c91"+dependencies = [+ "encoding_index_tests",+]++[[package]]+name = "encoding-index-korean"+version = "1.20141219.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4dc33fb8e6bcba213fe2f14275f0963fd16f0a02c878e3095ecfdf5bee529d81"+dependencies = [+ "encoding_index_tests",+]++[[package]]+name = "encoding-index-simpchinese"+version = "1.20141219.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87a7194909b9118fc707194baa434a4e3b0fb6a5a757c73c3adb07aa25031f7"+dependencies = [+ "encoding_index_tests",+]++[[package]]+name = "encoding-index-singlebyte"+version = "1.20141219.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3351d5acffb224af9ca265f435b859c7c01537c0849754d3db3fdf2bfe2ae84a"+dependencies = [+ "encoding_index_tests",+]++[[package]]+name = "encoding-index-tradchinese"+version = "1.20141219.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd0e20d5688ce3cab59eb3ef3a2083a5c77bf496cb798dc6fcdb75f323890c18"+dependencies = [+ "encoding_index_tests",+]++[[package]]+name = "encoding_index_tests"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a246d82be1c9d791c5dfde9a2bd045fc3cbba3fa2b11ad558f27d01712f00569"+[[package]]name = "encoding_rs"version = "0.8.35"@@ -2350,6 +2414,19 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"+[[package]]+name = "epub"+version = "2.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95518004c0a638e03a17589d2d336b7c936d92184d81bf1e66d3b1555de89f2d"+dependencies = [+ "percent-encoding",+ "regex",+ "thiserror 2.0.18",+ "xml-rs",+ "zip 3.0.0",+]+[[package]]name = "equivalent"version = "1.0.2"@@ -3105,6 +3182,19 @@ dependencies = ["digest",]+[[package]]+name = "html2text"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1c97eea9d3e6524d8d2a4643ce0e3135500c4c7ca1d02393a485f871bef69d8"+dependencies = [+ "html5ever 0.39.0",+ "tendril",+ "thiserror 2.0.18",+ "unicode-width",+ "xml5ever",+]+[[package]]name = "html5ever"version = "0.38.0"@@ -3112,7 +3202,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2"dependencies = ["log",- "markup5ever",+ "markup5ever 0.38.0",+]++[[package]]+name = "html5ever"+version = "0.39.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"+dependencies = [+ "log",+ "markup5ever 0.39.0",][[package]]@@ -4469,10 +4569,13 @@ dependencies = ["calamine","chrono","docx-rs",+ "epub","futures",+ "html2text","image","lancedb","md-5",+ "mobi","notify","office_oxide","pdfium-render",@@ -4604,6 +4707,17 @@ dependencies = ["web_atoms",]+[[package]]+name = "markup5ever"+version = "0.39.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"+dependencies = [+ "log",+ "tendril",+ "web_atoms",+]+[[package]]name = "matchers"version = "0.2.0"@@ -4719,6 +4833,17 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "mobi"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f3f8e34216126be00a189105bda27462e1743d59cd4e15d6b99ff4af051b1b4"+dependencies = [+ "encoding",+ "indexmap 1.9.3",+ "thiserror 1.0.69",+]+[[package]]name = "mock_instant"version = "0.6.0"@@ -9270,6 +9395,31 @@ dependencies = ["pkg-config",]+[[package]]+name = "xml"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "636f85e5ca6488e96401b61eb7de54f4e44755c988af0f52cf90230c312a1a89"++[[package]]+name = "xml-rs"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3a56132a0d6ecbe77352edc10232f788fc4ceefefff4cab784a98e0e16b6b51"+dependencies = [+ "xml",+]++[[package]]+name = "xml5ever"+version = "0.39.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ab627f34ff61b80d756180d556f9c68801d836d271b3b8c094504ceca69d221"+dependencies = [+ "log",+ "markup5ever 0.39.0",+]+[[package]]name = "xxhash-rust"version = "0.8.15"@@ -9505,6 +9655,20 @@ dependencies = ["zstd",]+[[package]]+name = "zip"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"+dependencies = [+ "arbitrary",+ "crc32fast",+ "flate2",+ "indexmap 2.14.0",+ "memchr",+ "zopfli",+]+[[package]]name = "zip"version = "7.2.0"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 3d7c35c9..be44b154 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -62,6 +62,9 @@ sha2 = "0.10"md-5 = "0.10"notify = "8"walkdir = "2"+epub = "2.1.5"+mobi = "0.8"+html2text = { version = "0.17.1", default-features = false, features = ["xml"] }[dev-dependencies]tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread"] }diff --git a/src-tauri/src/commands/ebook.rs b/src-tauri/src/commands/ebook.rsnew file mode 100644index 00000000..51c5668f--- /dev/null+++ b/src-tauri/src/commands/ebook.rs@@ -0,0 +1,350 @@+//! Safe, cross-platform text extraction for ebook source files.+//!+//! The extractor returns one Markdown-shaped document so the existing ingest,+//! chunking, embedding, and preview pipelines do not need ebook-specific+//! branches. EPUB spine order is authoritative. MOBI support is intentionally+//! limited to DRM-free files accepted by the pure-Rust parser; encrypted Kindle+//! books are rejected instead of producing misleading partial text.++use std::fs;+use std::path::Path;++use epub::doc::EpubDoc;+use mobi::headers::Encryption;++const MAX_EBOOK_BYTES: u64 = 100 * 1024 * 1024;+const MAX_EPUB_ENTRIES: usize = 10_000;+const MAX_EPUB_EXPANDED_BYTES: u64 = 512 * 1024 * 1024;+const MAX_EPUB_COMPRESSION_RATIO: u64 = 200;+const MAX_EXTRACTED_TEXT_BYTES: usize = 32 * 1024 * 1024;+const MAX_CHAPTERS: usize = 10_000;++pub fn extract_ebook_text(path: &str, extension: &str) -> Result<String, String> {+ validate_source_file(path)?;+ match extension {+ "epub" => extract_epub(path),+ "mobi" => extract_mobi(path),+ _ => Err(format!("Unsupported ebook format: .{extension}")),+ }+}++fn validate_source_file(path: &str) -> Result<(), String> {+ let metadata = fs::metadata(path)+ .map_err(|error| format!("Failed to inspect ebook '{}': {error}", path))?;+ if !metadata.is_file() {+ return Err(format!("Ebook path is not a file: '{path}'"));+ }+ if metadata.len() > MAX_EBOOK_BYTES {+ return Err(format!(+ "Ebook exceeds the {} MB extraction limit",+ MAX_EBOOK_BYTES / 1024 / 1024+ ));+ }+ Ok(())+}++fn validate_epub_archive(path: &str) -> Result<(), String> {+ let file =+ fs::File::open(path).map_err(|error| format!("Failed to open EPUB '{}': {error}", path))?;+ let mut archive = zip::ZipArchive::new(file)+ .map_err(|error| format!("Invalid EPUB ZIP container: {error}"))?;+ if archive.len() > MAX_EPUB_ENTRIES {+ return Err(format!(+ "EPUB contains too many archive entries ({} > {MAX_EPUB_ENTRIES})",+ archive.len()+ ));+ }++ let mut expanded = 0_u64;+ for index in 0..archive.len() {+ let entry = archive+ .by_index(index)+ .map_err(|error| format!("Failed to inspect EPUB entry {index}: {error}"))?;+ if entry.enclosed_name().is_none() {+ return Err(format!(+ "EPUB contains an unsafe archive path: {}",+ entry.name()+ ));+ }+ expanded = expanded.saturating_add(entry.size());+ if expanded > MAX_EPUB_EXPANDED_BYTES {+ return Err(format!(+ "EPUB expanded content exceeds the {} MB safety limit",+ MAX_EPUB_EXPANDED_BYTES / 1024 / 1024+ ));+ }+ let compressed = entry.compressed_size();+ if entry.size() > 1024 * 1024+ && compressed > 0+ && entry.size() / compressed > MAX_EPUB_COMPRESSION_RATIO+ {+ return Err(format!(+ "EPUB entry has an unsafe compression ratio: {}",+ entry.name()+ ));+ }+ }+ Ok(())+}++fn extract_epub(path: &str) -> Result<String, String> {+ validate_epub_archive(path)?;+ let mut document =+ EpubDoc::new(path).map_err(|error| format!("Failed to parse EPUB '{}': {error}", path))?;+ let title = document+ .mdata("title")+ .map(|item| item.value.trim().to_string())+ .filter(|value| !value.is_empty())+ .unwrap_or_else(|| file_stem(path));+ let author = document+ .mdata("creator")+ .map(|item| item.value.trim().to_string());+ let language = document+ .mdata("language")+ .map(|item| item.value.trim().to_string());+ let publisher = document+ .mdata("publisher")+ .map(|item| item.value.trim().to_string());++ let mut output = ebook_header(+ &title,+ author.as_deref(),+ language.as_deref(),+ publisher.as_deref(),+ "epub",+ );+ let chapter_count = document.spine.len().min(MAX_CHAPTERS);+ let mut extracted_chapters = 0_usize;+ for index in 0..chapter_count {+ if !document.set_current_chapter(index) {+ continue;+ }+ let chapter_path = document+ .get_current_path()+ .map(|value| value.to_string_lossy().into_owned())+ .unwrap_or_else(|| format!("chapter-{}", index + 1));+ let Some((bytes, mime)) = document.get_current() else {+ continue;+ };+ if !mime.contains("html") && !mime.contains("xml") {+ continue;+ }+ let text = html_to_text(&bytes)?;+ if text.trim().is_empty() {+ continue;+ }+ let chapter_path = safe_heading_text(&chapter_path);+ push_bounded(+ &mut output,+ &format!(+ "\n\n## Chapter {} · {}\n\n{}",+ index + 1,+ chapter_path,+ text.trim()+ ),+ )?;+ extracted_chapters += 1;+ }++ if extracted_chapters == 0 {+ return Err("EPUB contains no extractable chapter text".to_string());+ }+ Ok(output)+}++fn extract_mobi(path: &str) -> Result<String, String> {+ let document = mobi::Mobi::from_path(path)+ .map_err(|error| format!("Failed to parse MOBI '{}': {error}", path))?;+ if document.encryption() != Encryption::No {+ return Err("Encrypted/DRM-protected MOBI files are not supported".to_string());+ }+ if document.metadata.palmdoc.text_length as usize > MAX_EXTRACTED_TEXT_BYTES {+ return Err(format!(+ "MOBI declares more than {} MB of text",+ MAX_EXTRACTED_TEXT_BYTES / 1024 / 1024+ ));+ }++ let title = document.title().trim().to_string();+ let title = if title.is_empty() {+ file_stem(path)+ } else {+ title+ };+ let author = document.author();+ let publisher = document.publisher();+ let language = Some(format!("{:?}", document.language()));+ let raw = document+ .content_as_string()+ .unwrap_or_else(|_| document.content_as_string_lossy());+ let text = if raw.contains('<') {+ html_to_text(raw.as_bytes())?+ } else {+ raw+ };+ if text.trim().is_empty() {+ return Err("MOBI contains no extractable text".to_string());+ }++ let mut output = ebook_header(+ &title,+ author.as_deref(),+ language.as_deref(),+ publisher.as_deref(),+ "mobi",+ );+ push_bounded(&mut output, &format!("\n\n{}", text.trim()))?;+ Ok(output)+}++fn ebook_header(+ title: &str,+ author: Option<&str>,+ language: Option<&str>,+ publisher: Option<&str>,+ format: &str,+) -> String {+ let mut output = format!("# {}\n\n", safe_inline_text(title, 500));+ output.push_str("## Book metadata\n\n");+ output.push_str(&format!("- Format: {}\n", format.to_uppercase()));+ if let Some(author) = non_empty(author) {+ output.push_str(&format!("- Author: {}\n", safe_inline_text(author, 1_000)));+ }+ if let Some(language) = non_empty(language) {+ output.push_str(&format!(+ "- Language: {}\n",+ safe_inline_text(language, 100)+ ));+ }+ if let Some(publisher) = non_empty(publisher) {+ output.push_str(&format!(+ "- Publisher: {}\n",+ safe_inline_text(publisher, 1_000)+ ));+ }+ output.push_str("\n## Contents");+ output+}++fn html_to_text(bytes: &[u8]) -> Result<String, String> {+ html2text::from_read(bytes, 120)+ .map(|text| text.replace("\r\n", "\n"))+ .map_err(|error| format!("Failed to convert ebook HTML to text: {error}"))+}++fn push_bounded(output: &mut String, value: &str) -> Result<(), String> {+ if output.len().saturating_add(value.len()) > MAX_EXTRACTED_TEXT_BYTES {+ return Err(format!(+ "Extracted ebook text exceeds the {} MB safety limit",+ MAX_EXTRACTED_TEXT_BYTES / 1024 / 1024+ ));+ }+ output.push_str(value);+ Ok(())+}++fn file_stem(path: &str) -> String {+ Path::new(path)+ .file_stem()+ .and_then(|value| value.to_str())+ .unwrap_or("Untitled ebook")+ .to_string()+}++fn non_empty(value: Option<&str>) -> Option<&str> {+ value.map(str::trim).filter(|value| !value.is_empty())+}++fn safe_heading_text(value: &str) -> String {+ safe_inline_text(value, 240)+}++fn safe_inline_text(value: &str, max_chars: usize) -> String {+ value+ .chars()+ .map(|character| {+ if character.is_control() {+ ' '+ } else {+ character+ }+ })+ .take(max_chars)+ .collect::<String>()+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+ .trim()+ .to_string()+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ #[test]+ fn converts_html_without_executing_markup() {+ let text = html_to_text(b"<h1>Chapter</h1><script>alert(1)</script><p>Hello</p>").unwrap();+ assert!(text.contains("Chapter"));+ assert!(text.contains("Hello"));+ assert!(!text.contains("alert(1)"));+ }++ #[test]+ fn rejects_epub_archive_traversal_paths() {+ let path = std::env::temp_dir().join(format!("unsafe-{}.epub", uuid::Uuid::new_v4()));+ let file = fs::File::create(&path).unwrap();+ let mut archive = zip::ZipWriter::new(file);+ archive+ .start_file("../outside.xhtml", zip::write::SimpleFileOptions::default())+ .unwrap();+ archive.write_all(b"<p>unsafe</p>").unwrap();+ archive.finish().unwrap();++ let error = validate_epub_archive(path.to_str().unwrap()).unwrap_err();+ assert!(error.contains("unsafe archive path"));+ let _ = fs::remove_file(path);+ }++ #[test]+ fn extracts_epub_metadata_and_spine_content() {+ let path = std::env::temp_dir().join(format!("book-{}.epub", uuid::Uuid::new_v4()));+ let file = fs::File::create(&path).unwrap();+ let mut archive = zip::ZipWriter::new(file);+ let options = zip::write::SimpleFileOptions::default();+ archive.start_file("mimetype", options).unwrap();+ archive.write_all(b"application/epub+zip").unwrap();+ archive+ .start_file("META-INF/container.xml", options)+ .unwrap();+ archive.write_all(br#"<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>"#).unwrap();+ archive.start_file("OEBPS/content.opf", options).unwrap();+ archive.write_all(br#"<?xml version="1.0"?><package version="3.0" xmlns="http://www.idpf.org/2007/opf" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">test</dc:identifier><dc:title>Test Book</dc:title><dc:creator>Test Author</dc:creator><dc:language>en</dc:language></metadata><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>"#).unwrap();+ archive.start_file("OEBPS/chapter.xhtml", options).unwrap();+ archive.write_all(br#"<html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Opening</h1><p>Hello ebook.</p></body></html>"#).unwrap();+ archive.finish().unwrap();++ let output = extract_ebook_text(path.to_str().unwrap(), "epub").unwrap();+ assert!(output.contains("# Test Book"));+ assert!(output.contains("Author: Test Author"));+ assert!(output.contains("Opening"));+ assert!(output.contains("Hello ebook."));+ let _ = fs::remove_file(path);+ }++ #[test]+ fn output_limit_is_enforced_before_append() {+ let mut output = "x".repeat(MAX_EXTRACTED_TEXT_BYTES);+ assert!(push_bounded(&mut output, "y").is_err());+ assert_eq!(output.len(), MAX_EXTRACTED_TEXT_BYTES);+ }++ #[test]+ fn metadata_is_single_line_and_bounded() {+ let value = format!("Book\r\nTitle {}", "x".repeat(600));+ let sanitized = safe_inline_text(&value, 20);+ assert_eq!(sanitized, "Book Title xxxxxxxx");+ assert!(!sanitized.contains('\n'));+ }+}diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex 195690b4..421ee4c6 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -20,7 +20,8 @@ const MEDIA_EXTS: &[&str] = &["mp4", "webm", "mov", "avi", "mkv", "flv", "wmv", "m4v", "mp3", "wav", "ogg", "flac", "aac","m4a", "wma",];-const LEGACY_DOC_EXTS: &[&str] = &["ppt", "pages", "numbers", "key", "epub"];+const EBOOK_EXTS: &[&str] = &["epub", "mobi"];+const LEGACY_DOC_EXTS: &[&str] = &["ppt", "pages", "numbers", "key"];fn require_absolute_path(operation: &str, path: &str) -> Result<(), String> {if is_absolute_path_cross_platform(path) {@@ -82,6 +83,7 @@ pub async fn read_file(path: String, extract_images: Option<bool>) -> Result<Strmatch ext.as_str() {"pdf" => extract_pdf_text(&path, include_images),e if OFFICE_EXTS.contains(&e) => extract_office_text(&path, e),+ e if EBOOK_EXTS.contains(&e) => crate::commands::ebook::extract_ebook_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))@@ -133,6 +135,9 @@ pub async fn preprocess_file(path: String) -> Result<String, String> {let text = match ext.as_str() {"pdf" => extract_pdf_text(&path, false)?,e if OFFICE_EXTS.contains(&e) => extract_office_text(&path, e)?,+ e if EBOOK_EXTS.contains(&e) => {+ crate::commands::ebook::extract_ebook_text(&path, e)?+ }_ => return Ok("no preprocessing needed".to_string()),};diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex bad19e3b..e2d9e24e 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -1,6 +1,7 @@pub mod claude_cli;mod cli_resolver;pub mod codex_cli;+pub mod ebook;pub mod external_search;pub mod extract_images;pub mod file_history;diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsxindex 177d69df..2e54889b 100644--- a/src/components/sources/sources-view.tsx+++ b/src/components/sources/sources-view.tsx@@ -107,7 +107,7 @@ export function SourcesView() {"md", "mdx", "txt", "rtf", "pdf","html", "htm", "xml","doc", "docx", "xls", "xlsx", "ppt", "pptx",- "odt", "ods", "odp", "epub", "pages", "numbers", "key",+ "odt", "ods", "odp", "epub", "mobi", "pages", "numbers", "key",],},{diff --git a/src/lib/file-types.test.ts b/src/lib/file-types.test.tsindex 9003b948..c65ff8ce 100644--- a/src/lib/file-types.test.ts+++ b/src/lib/file-types.test.ts@@ -12,9 +12,16 @@ describe("file types", () => {expect(isExtractedTextPreviewFile("/project/raw/sources/report.docx")).toBe(true)expect(isExtractedTextPreviewFile("/project/raw/sources/slides.pptx")).toBe(true)expect(isExtractedTextPreviewFile("/project/raw/sources/sheet.xlsx")).toBe(true)+ expect(isExtractedTextPreviewFile("/project/raw/sources/book.epub")).toBe(true)+ expect(isExtractedTextPreviewFile("C:\\books\\book.MOBI")).toBe(true)expect(isExtractedTextPreviewFile("/project/raw/sources/archive.zip")).toBe(false)})+ it("classifies EPUB and MOBI as extracted documents", () => {+ expect(getFileCategory("/project/book.epub")).toBe("document")+ expect(getFileCategory("C:\\books\\book.MOBI")).toBe("document")+ })+it("extracts extensions from windows and unix paths", () => {expect(getFileExtension("C:\\Users\\me\\report.DOC")).toBe("doc")expect(getFileExtension("/Users/me/report.docx")).toBe("docx")diff --git a/src/lib/file-types.ts b/src/lib/file-types.tsindex e798d7ce..10aee65a 100644--- a/src/lib/file-types.ts+++ b/src/lib/file-types.ts@@ -116,6 +116,7 @@ const EXT_MAP: Record<string, FileCategory> = {numbers: "document",key: "document",epub: "document",+ mobi: "document",// Datajson: "data",@@ -146,6 +147,8 @@ export const EXTRACTED_TEXT_PREVIEW_EXTENSIONS = new Set(["odt","ods","odp",+ "epub",+ "mobi",])export function getFileExtension(filePath: string): string {diff --git a/src/lib/source-lifecycle.test.ts b/src/lib/source-lifecycle.test.tsindex 072aa556..1450179f 100644--- a/src/lib/source-lifecycle.test.ts+++ b/src/lib/source-lifecycle.test.ts@@ -55,6 +55,11 @@ describe("source-lifecycle path helpers", () => {expect(isIngestableSourcePath("/project/raw/sources/.cache/report.pdf.txt")).toBe(false)})+ it("accepts supported ebook source formats", () => {+ expect(isIngestableSourcePath("raw/sources/book.epub")).toBe(true)+ expect(isIngestableSourcePath("C:\\project\\raw\\sources\\book.MOBI")).toBe(true)+ })+it("derives folder context from absolute raw/sources paths without leaking the project prefix", () => {expect(folderContextForSourcePath("/tmp/project/raw/sources/reports/2026/report.pdf"),@@ -236,6 +241,36 @@ describe("source-lifecycle path helpers", () => {])})+ it("allows an explicitly selected ebook with an older watch include-list", async () => {+ const copied = await importSourceFiles(+ { id: "p1", name: "Project", path: "/project" },+ ["/external/book.epub"],+ {+ provider: "openai",+ endpoint: "https://api.example.com/v1",+ apiKey: "key",+ model: "model",+ customModel: "",+ reasoning: { enabled: false, effort: "low" },+ } as never,+ {+ enabled: true,+ autoIngest: true,+ includeExtensions: ["md", "pdf"],+ excludeExtensions: [],+ excludeDirs: [],+ excludeGlobs: [],+ maxFileSizeMb: 100,+ },+ )++ expect(copied).toEqual(["/project/raw/sources/book.epub"])+ expect(mocks.copyFile).toHaveBeenCalledWith(+ "/external/book.epub",+ "/project/raw/sources/book.epub",+ )+ })+it("skips sensitive tool config files at the shared ingest enqueue boundary", async () => {const queued = await enqueueSourceIngest({ id: "p1", name: "Project", path: "/project" },diff --git a/src/lib/source-lifecycle.ts b/src/lib/source-lifecycle.tsindex 243bd4ca..2d0f8d65 100644--- a/src/lib/source-lifecycle.ts+++ b/src/lib/source-lifecycle.ts@@ -60,6 +60,8 @@ export const INGESTABLE_SOURCE_EXTENSIONS = new Set(["xml","yaml","yml",+ "epub",+ "mobi",])function flattenFiles(nodes: FileNode[]): FileNode[] {@@ -264,6 +266,11 @@ export async function importSourceFiles(const pp = normalizePath(project.path)const importedPaths: string[] = []const cfg = normalizeSourceWatchConfig(sourceWatchConfig)+ // Explicit file selection is user intent, so the watcher's allow-list must+ // not silently reject a newly supported format from an older persisted+ // configuration. Exclusions and the size ceiling still apply. Folder/watch+ // imports continue to honor includeExtensions to prevent surprise ingestion.+ const explicitImportConfig = { ...cfg, includeExtensions: [] }const maxBytes = cfg.maxFileSizeMb * 1024 * 1024for (const sourcePath of sourcePaths) {@@ -271,7 +278,8 @@ export async function importSourceFiles(if (isSensitiveConfigSourceFile(sourcePath)) {continue}- let allowed = isPathAllowedBySourceWatch(sourcePath, cfg)+ let allowed = isIngestableSourcePath(sourcePath)+ && isPathAllowedBySourceWatch(sourcePath, explicitImportConfig)if (allowed) {try {allowed = await getFileSize(sourcePath) <= maxBytesdiff --git a/src/lib/source-watch-config.ts b/src/lib/source-watch-config.tsindex 8ad3cd6d..31003be3 100644--- a/src/lib/source-watch-config.ts+++ b/src/lib/source-watch-config.ts@@ -7,7 +7,7 @@ export const DEFAULT_SOURCE_WATCH_CONFIG: SourceWatchConfig = sourceWatchDefaultexport const SOURCE_WATCH_FILE_TYPE_GROUPS = [{id: "documents",- extensions: ["md", "mdx", "txt", "pdf", "doc", "docx", "odt", "rtf"],+ extensions: ["md", "mdx", "txt", "pdf", "doc", "docx", "odt", "rtf", "epub", "mobi"],},{id: "presentations",