LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
fix: catch panics in Tauri commands so one bad file can't kill the app
nash_su0a142d170f56
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 30760a66..7057857e 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -41,5 +41,8 @@ futures = "0.3"codegen-units = 1lto = trueopt-level = "s"-panic = "abort"+# Unwind (not abort) so third-party parser panics can be caught at the+# Tauri command boundary via panic_guard and turned into errors. Slightly+# larger binary, but prevents single-file corruption from killing the app.+panic = "unwind"strip = truediff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex 1537287a..f4f31d9b 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -4,6 +4,7 @@ use std::path::Path;use calamine::{Reader, open_workbook_auto, Data};+use crate::panic_guard::run_guarded;use crate::types::wiki::FileNode;/// Known binary formats that need special extraction@@ -19,65 +20,69 @@ const LEGACY_DOC_EXTS: &[&str] = &["doc", "xls", "ppt", "pages", "numbers", "key#[tauri::command]pub fn read_file(path: String) -> Result<String, String> {- 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);- }+ run_guarded("read_file", || {+ let p = Path::new(&path);+ let ext = p+ .extension()+ .and_then(|e| e.to_str())+ .unwrap_or("")+ .to_lowercase();- 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))+ // Check cache first for any extractable format+ if let Some(cached) = read_cache(p) {+ return Ok(cached);}- 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))- }- _ => {- // Try reading as text; if it fails (binary), return a friendly message- match fs::read_to_string(&path) {- Ok(content) => Ok(content),- Err(_) => {- let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);- Ok(format!("[Binary file: {} ({:.1} KB)]",- p.file_name().unwrap_or_default().to_string_lossy(), size as f64 / 1024.0))++ 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))+ }+ _ => {+ // Try reading as text; if it fails (binary), return a friendly message+ match fs::read_to_string(&path) {+ Ok(content) => Ok(content),+ Err(_) => {+ let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);+ Ok(format!("[Binary file: {} ({:.1} KB)]",+ p.file_name().unwrap_or_default().to_string_lossy(), size as f64 / 1024.0))+ }}}}- }+ })}/// Pre-process a file and cache the extracted text.#[tauri::command]pub fn preprocess_file(path: String) -> Result<String, String> {- 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)+ 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)+ })}fn cache_path_for(original: &Path) -> std::path::PathBuf {@@ -635,25 +640,30 @@ fn extract_odf_text(archive: &mut zip::ZipArchive<fs::File>) -> Result<String, S#[tauri::command]pub fn write_file(path: String, contents: String) -> Result<(), String> {- 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))+ 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::command]pub fn list_directory(path: String) -> Result<Vec<FileNode>, String> {- 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)+ 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)+ })}fn build_tree(dir: &Path, depth: usize, max_depth: usize) -> Result<Vec<FileNode>, String> {@@ -720,91 +730,99 @@ fn build_tree(dir: &Path, depth: usize, max_depth: usize) -> Result<Vec<FileNode#[tauri::command]pub fn copy_file(source: String, destination: String) -> Result<(), String> {- 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(())+ 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(())+ })}/// Recursively copy a directory, preserving structure./// Returns list of copied file paths (destination paths).#[tauri::command]pub fn copy_directory(source: String, destination: String) -> Result<Vec<String>, String> {- let src = Path::new(&source);- let dest = Path::new(&destination);+ 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;- }+ // Skip hidden files/dirs+ 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)- })?;- files.push(dest_path.to_string_lossy().to_string());+ 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().to_string());+ }}+ Ok(())}- Ok(())- }- copy_recursive(src, dest, &mut copied_files)?;- Ok(copied_files)+ copy_recursive(src, dest, &mut copied_files)?;+ Ok(copied_files)+ })}#[tauri::command]pub fn delete_file(path: String) -> Result<(), String> {- 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))- }+ 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))+ }+ })}/// 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 fn find_related_wiki_pages(project_path: String, source_name: String) -> Result<Vec<String>, String> {- let wiki_dir = Path::new(&project_path).join("wiki");- if !wiki_dir.is_dir() {- return Ok(vec![]);- }+ 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)+ })}fn collect_related_pages(dir: &Path, source_name: &str, results: &mut Vec<String>) -> Result<(), String> {@@ -880,6 +898,8 @@ fn collect_related_pages(dir: &Path, source_name: &str, results: &mut Vec<String#[tauri::command]pub fn create_directory(path: String) -> Result<(), String> {- fs::create_dir_all(&path)- .map_err(|e| format!("Failed to create directory '{}': {}", path, e))+ run_guarded("create_directory", || {+ fs::create_dir_all(&path)+ .map_err(|e| format!("Failed to create directory '{}': {}", path, e))+ })}diff --git a/src-tauri/src/commands/project.rs b/src-tauri/src/commands/project.rsindex 2f513343..270c00ec 100644--- a/src-tauri/src/commands/project.rs+++ b/src-tauri/src/commands/project.rs@@ -3,10 +3,15 @@ use std::path::Path;use chrono::Local;+use crate::panic_guard::run_guarded;use crate::types::wiki::WikiProject;#[tauri::command]pub fn create_project(name: String, path: String) -> Result<WikiProject, String> {+ run_guarded("create_project", || create_project_impl(name, path))+}++fn create_project_impl(name: String, path: String) -> Result<WikiProject, String> {let root = Path::new(&path).join(&name);if root.exists() {@@ -232,37 +237,39 @@ related: []#[tauri::command]pub fn open_project(path: String) -> Result<WikiProject, String> {- let root = Path::new(&path);-- if !root.exists() {- return Err(format!("Path does not exist: '{}'", path));- }- if !root.is_dir() {- return Err(format!("Path is not a directory: '{}'", path));- }-- // Validate that this looks like a wiki project- if !root.join("schema.md").exists() {- return Err(format!(- "Not a valid wiki project (missing schema.md): '{}'",- path- ));- }- if !root.join("wiki").is_dir() {- return Err(format!(- "Not a valid wiki project (missing wiki/ directory): '{}'",- path- ));- }-- // Derive project name from the directory name- let name = root- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("Unknown")- .to_string();-- Ok(WikiProject { name, path })+ run_guarded("open_project", || {+ let root = Path::new(&path);++ if !root.exists() {+ return Err(format!("Path does not exist: '{}'", path));+ }+ if !root.is_dir() {+ return Err(format!("Path is not a directory: '{}'", path));+ }++ // Validate that this looks like a wiki project+ if !root.join("schema.md").exists() {+ return Err(format!(+ "Not a valid wiki project (missing schema.md): '{}'",+ path+ ));+ }+ if !root.join("wiki").is_dir() {+ return Err(format!(+ "Not a valid wiki project (missing wiki/ directory): '{}'",+ path+ ));+ }++ // Derive project name from the directory name+ let name = root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("Unknown")+ .to_string();++ Ok(WikiProject { name, path })+ })}fn write_file_inner(path: std::path::PathBuf, contents: &str) -> Result<(), String> {diff --git a/src-tauri/src/commands/vectorstore.rs b/src-tauri/src/commands/vectorstore.rsindex 0dcd12a9..dd0eb195 100644--- a/src-tauri/src/commands/vectorstore.rs+++ b/src-tauri/src/commands/vectorstore.rs@@ -5,6 +5,8 @@ use arrow_schema::{DataType, Field, Schema};use serde::{Deserialize, Serialize};use std::sync::Arc;+use crate::panic_guard::run_guarded_async;+/// Result from vector search#[derive(Debug, Serialize, Deserialize, Clone)]pub struct VectorSearchResult {@@ -66,46 +68,49 @@ pub async fn vector_upsert(page_id: String,embedding: Vec<f32>,) -> Result<(), String> {- validate_page_id(&page_id)?;-- let db = connect(&db_path(&project_path))- .execute()- .await- .map_err(|e| format!("DB connect error: {e}"))?;-- let dim = embedding.len() as i32;- let schema = make_schema(dim);- let batch = make_batch(schema.clone(), &page_id, embedding, dim)?;- let data = vec![batch];-- let tables = db.table_names()- .execute()- .await- .map_err(|e| format!("List tables error: {e}"))?;+ run_guarded_async("vector_upsert", async move {+ validate_page_id(&page_id)?;- if tables.contains(&TABLE_NAME.to_string()) {- let table = db.open_table(TABLE_NAME)+ let db = connect(&db_path(&project_path)).execute().await- .map_err(|e| format!("Open table error: {e}"))?;+ .map_err(|e| format!("DB connect error: {e}"))?;- // Delete existing entry then add new one- if let Err(e) = table.delete(&format!("page_id = '{}'", page_id)).await {- eprintln!("[vectorstore] Warning: delete before upsert failed for '{}': {}", page_id, e);- }+ let dim = embedding.len() as i32;+ let schema = make_schema(dim);+ let batch = make_batch(schema.clone(), &page_id, embedding, dim)?;+ let data = vec![batch];- table.add(data)+ let tables = db.table_names().execute().await- .map_err(|e| format!("Add error: {e}"))?;- } else {- db.create_table(TABLE_NAME, data)- .execute()- .await- .map_err(|e| format!("Create table error: {e}"))?;- }+ .map_err(|e| format!("List tables error: {e}"))?;++ if tables.contains(&TABLE_NAME.to_string()) {+ let table = db.open_table(TABLE_NAME)+ .execute()+ .await+ .map_err(|e| format!("Open table error: {e}"))?;++ // Delete existing entry then add new one+ if let Err(e) = table.delete(&format!("page_id = '{}'", page_id)).await {+ eprintln!("[vectorstore] Warning: delete before upsert failed for '{}': {}", page_id, e);+ }++ table.add(data)+ .execute()+ .await+ .map_err(|e| format!("Add error: {e}"))?;+ } else {+ db.create_table(TABLE_NAME, data)+ .execute()+ .await+ .map_err(|e| format!("Create table error: {e}"))?;+ }- Ok(())+ Ok(())+ })+ .await}/// Search for similar pages by embedding vector@@ -115,61 +120,64 @@ pub async fn vector_search(query_embedding: Vec<f32>,top_k: usize,) -> Result<Vec<VectorSearchResult>, String> {- let db = connect(&db_path(&project_path))- .execute()- .await- .map_err(|e| format!("DB connect error: {e}"))?;-- let tables = db.table_names()- .execute()- .await- .map_err(|e| format!("List tables error: {e}"))?;-- if !tables.contains(&TABLE_NAME.to_string()) {- return Ok(vec![]);- }+ run_guarded_async("vector_search", async move {+ let db = connect(&db_path(&project_path))+ .execute()+ .await+ .map_err(|e| format!("DB connect error: {e}"))?;++ let tables = db.table_names()+ .execute()+ .await+ .map_err(|e| format!("List tables error: {e}"))?;- let table = db.open_table(TABLE_NAME)- .execute()- .await- .map_err(|e| format!("Open table error: {e}"))?;-- let results_stream = table- .vector_search(query_embedding)- .map_err(|e| format!("Search error: {e}"))?- .limit(top_k)- .execute()- .await- .map_err(|e| format!("Execute search error: {e}"))?;-- let mut search_results = Vec::new();-- use futures::TryStreamExt;- let batches: Vec<RecordBatch> = results_stream- .try_collect()- .await- .map_err(|e| format!("Collect error: {e}"))?;-- for batch in &batches {- let ids = batch- .column_by_name("page_id")- .and_then(|c| c.as_any().downcast_ref::<StringArray>())- .ok_or("Missing page_id column")?;-- let distances = batch- .column_by_name("_distance")- .and_then(|c| c.as_any().downcast_ref::<Float32Array>())- .ok_or("Missing _distance column")?;-- for i in 0..batch.num_rows() {- let page_id = ids.value(i).to_string();- let distance = distances.value(i);- let score = 1.0 / (1.0 + distance);- search_results.push(VectorSearchResult { page_id, score });+ if !tables.contains(&TABLE_NAME.to_string()) {+ return Ok(vec![]);}- }- Ok(search_results)+ let table = db.open_table(TABLE_NAME)+ .execute()+ .await+ .map_err(|e| format!("Open table error: {e}"))?;++ let results_stream = table+ .vector_search(query_embedding)+ .map_err(|e| format!("Search error: {e}"))?+ .limit(top_k)+ .execute()+ .await+ .map_err(|e| format!("Execute search error: {e}"))?;++ let mut search_results = Vec::new();++ use futures::TryStreamExt;+ let batches: Vec<RecordBatch> = results_stream+ .try_collect()+ .await+ .map_err(|e| format!("Collect error: {e}"))?;++ for batch in &batches {+ let ids = batch+ .column_by_name("page_id")+ .and_then(|c| c.as_any().downcast_ref::<StringArray>())+ .ok_or("Missing page_id column")?;++ let distances = batch+ .column_by_name("_distance")+ .and_then(|c| c.as_any().downcast_ref::<Float32Array>())+ .ok_or("Missing _distance column")?;++ for i in 0..batch.num_rows() {+ let page_id = ids.value(i).to_string();+ let distance = distances.value(i);+ let score = 1.0 / (1.0 + distance);+ search_results.push(VectorSearchResult { page_id, score });+ }+ }++ Ok(search_results)+ })+ .await}/// Delete a page from the vector index@@ -178,32 +186,35 @@ pub async fn vector_delete(project_path: String,page_id: String,) -> Result<(), String> {- validate_page_id(&page_id)?;+ run_guarded_async("vector_delete", async move {+ validate_page_id(&page_id)?;- let db = connect(&db_path(&project_path))- .execute()- .await- .map_err(|e| format!("DB connect error: {e}"))?;+ let db = connect(&db_path(&project_path))+ .execute()+ .await+ .map_err(|e| format!("DB connect error: {e}"))?;- let tables = db.table_names()- .execute()- .await- .map_err(|e| format!("List tables error: {e}"))?;+ let tables = db.table_names()+ .execute()+ .await+ .map_err(|e| format!("List tables error: {e}"))?;- if !tables.contains(&TABLE_NAME.to_string()) {- return Ok(());- }+ if !tables.contains(&TABLE_NAME.to_string()) {+ return Ok(());+ }- let table = db.open_table(TABLE_NAME)- .execute()- .await- .map_err(|e| format!("Open table error: {e}"))?;+ let table = db.open_table(TABLE_NAME)+ .execute()+ .await+ .map_err(|e| format!("Open table error: {e}"))?;- table.delete(&format!("page_id = '{}'", page_id))- .await- .map_err(|e| format!("Delete error: {e}"))?;+ table.delete(&format!("page_id = '{}'", page_id))+ .await+ .map_err(|e| format!("Delete error: {e}"))?;- Ok(())+ Ok(())+ })+ .await}/// Get count of indexed vectors@@ -211,28 +222,31 @@ pub async fn vector_delete(pub async fn vector_count(project_path: String,) -> Result<usize, String> {- let db = connect(&db_path(&project_path))- .execute()- .await- .map_err(|e| format!("DB connect error: {e}"))?;-- let tables = db.table_names()- .execute()- .await- .map_err(|e| format!("List tables error: {e}"))?;-- if !tables.contains(&TABLE_NAME.to_string()) {- return Ok(0);- }+ run_guarded_async("vector_count", async move {+ let db = connect(&db_path(&project_path))+ .execute()+ .await+ .map_err(|e| format!("DB connect error: {e}"))?;++ let tables = db.table_names()+ .execute()+ .await+ .map_err(|e| format!("List tables error: {e}"))?;- let table = db.open_table(TABLE_NAME)- .execute()- .await- .map_err(|e| format!("Open table error: {e}"))?;+ if !tables.contains(&TABLE_NAME.to_string()) {+ return Ok(0);+ }- let count = table.count_rows(None)- .await- .map_err(|e| format!("Count error: {e}"))?;+ let table = db.open_table(TABLE_NAME)+ .execute()+ .await+ .map_err(|e| format!("Open table error: {e}"))?;++ let count = table.count_rows(None)+ .await+ .map_err(|e| format!("Count error: {e}"))?;- Ok(count)+ Ok(count)+ })+ .await}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex b678aec5..7d94ca3f 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,10 +1,16 @@mod clip_server;mod commands;+mod panic_guard;mod types;+use panic_guard::run_guarded;+#[tauri::command]fn clip_server_status() -> String {- clip_server::get_daemon_status().to_string()+ run_guarded("clip_server_status", || {+ Ok(clip_server::get_daemon_status().to_string())+ })+ .unwrap_or_else(|e| format!("error: {e}"))}#[cfg_attr(mobile, tauri::mobile_entry_point)]diff --git a/src-tauri/src/panic_guard.rs b/src-tauri/src/panic_guard.rsnew file mode 100644index 00000000..5fa9f9db--- /dev/null+++ b/src-tauri/src/panic_guard.rs@@ -0,0 +1,46 @@+//! Panic-to-error boundary for Tauri commands.+//!+//! Third-party parsers (pdf-extract / lopdf, docx-rs, calamine, …) are+//! known to panic on malformed input instead of returning Err. Under+//! `panic = "abort"` that kills the whole app; even with `panic =+//! "unwind"`, letting a panic propagate through the `extern "C"` Tauri+//! command boundary is UB. These helpers catch panics at the command+//! boundary and convert them into a Tauri Err the frontend can display.++use std::any::Any;+use std::panic::{catch_unwind, AssertUnwindSafe};++/// Run a synchronous command body, converting any panic into an Err.+pub fn run_guarded<T, F>(label: &str, f: F) -> Result<T, String>+where+ F: FnOnce() -> Result<T, String>,+{+ match catch_unwind(AssertUnwindSafe(f)) {+ Ok(r) => r,+ Err(payload) => Err(report(label, payload)),+ }+}++/// Run an async command body, converting any panic into an Err.+pub async fn run_guarded_async<T, Fut>(label: &str, fut: Fut) -> Result<T, String>+where+ Fut: std::future::Future<Output = Result<T, String>>,+{+ use futures::FutureExt;+ match AssertUnwindSafe(fut).catch_unwind().await {+ Ok(r) => r,+ Err(payload) => Err(report(label, payload)),+ }+}++fn report(label: &str, payload: Box<dyn Any + Send>) -> String {+ let msg = if let Some(s) = payload.downcast_ref::<String>() {+ s.clone()+ } else if let Some(s) = payload.downcast_ref::<&str>() {+ (*s).to_string()+ } else {+ "(non-string panic payload)".to_string()+ };+ eprintln!("[panic_guard] command '{label}' panicked: {msg}");+ format!("Internal error in {label}: {msg}")+}