diff --git a/docs/implementation-status.md b/docs/implementation-status.md index 171e8ad..8aa1679 100644 --- a/docs/implementation-status.md +++ b/docs/implementation-status.md @@ -39,6 +39,7 @@ - The Uploads screen shows recent upload history with retry buttons for failed uploads, refreshed from the backend on load and after uploads. - Screenshot capture is implemented: F9 takes a PNG screenshot via bundled FFmpeg into `~/Pictures/ClipForge`, the recording bar has a Screenshot button, and the Library shows recent screenshots with an Open-in-Explorer action. - Storage guardrails are wired: recording refuses to start below 2 GB free and a backend worker stops an active recording and flags `StorageLow` when available disk drops to critical; the recording bar shows free disk space and a low-disk warning. +- Panic reporting writes crash reports with stack traces to the logs folder (`library/logs`), prunes old entries, and the Settings screen can open the logs folder. - Vite TypeScript UI builds and has interactive Library, Recording, Auto Clip, Uploads, and Settings views. - Library search, event/upload filters, and grid/list switching are functional in the UI. - User-visible notices are shown for major actions and failures instead of relying only on console output. @@ -53,7 +54,7 @@ - Hotkeys are still hardcoded; editable hotkey registration is future work. - Capture source, quality, storage cap, excluded windows, and per-game override UI are still incomplete. - Recorder service still runs inside the Tauri process instead of a separate background service process. -- Installer onboarding, auto-update, and crash logging are still not implemented. +- Installer onboarding and auto-update are still not implemented. ## Next Engineering Steps diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 823bb9a..dcbb3b9 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1033,6 +1033,42 @@ fn list_screenshots() -> Result, String> { .collect()) } +#[tauri::command] +fn reveal_crash_logs(runtime: State<'_, AppRuntime>) -> Result<(), String> { + let logs_dir = runtime.library_root.join("logs"); + fs::create_dir_all(&logs_dir).map_err(|error| error.to_string())?; + Command::new("explorer") + .arg(logs_dir.display().to_string()) + .spawn() + .map_err(|error| error.to_string())?; + Ok(()) +} + +#[tauri::command] +fn list_crash_logs(runtime: State<'_, AppRuntime>) -> Result, String> { + let logs_dir = runtime.library_root.join("logs"); + let Ok(entries) = fs::read_dir(&logs_dir) else { + return Ok(Vec::new()); + }; + let mut files = entries + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .map(|name| name.starts_with("crash-")) + .unwrap_or(false) + }) + .collect::>(); + files.sort(); + Ok(files + .iter() + .rev() + .take(10) + .filter_map(|path| path.to_str().map(|s| s.to_string())) + .collect()) +} + fn upload_clip_with_settings( clip: &Clip, settings: &AppSettings, @@ -1371,6 +1407,8 @@ fn main() { let (library_root, recorder, database) = create_runtime().expect("could not initialize ClipForge runtime"); + clipforge::crashlog::install_panic_hook(library_root.join("logs")); + tauri::Builder::default() .manage(AppRuntime { library_root, @@ -1432,6 +1470,8 @@ fn main() { take_screenshot, list_screenshots, reveal_screenshot, + reveal_crash_logs, + list_crash_logs, set_hotkeys ]) .run(tauri::generate_context!()) diff --git a/src/crashlog.rs b/src/crashlog.rs new file mode 100644 index 0000000..09ef8fc --- /dev/null +++ b/src/crashlog.rs @@ -0,0 +1,126 @@ +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +const MAX_CRASH_FILES: u64 = 5; + +pub fn install_panic_hook(log_dir: impl Into) { + let log_dir = log_dir.into(); + let _ = fs::create_dir_all(&log_dir); + let guard_path = log_dir.join("latest-crash.txt"); + + std::panic::set_hook(Box::new(move |panic_info| { + let now = SystemTime::now(); + let timestamp = now + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let payload = panic_info + .payload() + .downcast_ref::<&str>() + .map(|value| value.to_string()) + .or_else(|| { + panic_info + .payload() + .downcast_ref::() + .map(Clone::clone) + }) + .unwrap_or_else(|| "unknown panic payload".to_string()); + let location = panic_info + .location() + .map(|location| format!("{}:{}", location.file(), location.line())) + .unwrap_or_else(|| "unknown location".to_string()); + + let mut body = String::new(); + body.push_str("ClipForge crash report\n"); + body.push_str(&format!("time: {timestamp}\n")); + body.push_str(&format!("thread: {}\n", thread_name())); + body.push_str(&format!("location: {location}\n")); + body.push_str(&format!("message: {payload}\n")); + body.push_str("\nBacktrace:\n"); + body.push_str(&backtrace()); + + let _ = fs::write(&guard_path, &body); + let file = log_dir.join(format!("crash-{timestamp}.log")); + let _ = fs::write(&file, &body); + prune_crash_files(&log_dir); + + eprint!("{body}"); + })); +} + +fn thread_name() -> String { + std::thread::current() + .name() + .map(ToString::to_string) + .unwrap_or_else(|| "".to_string()) +} + +fn backtrace() -> String { + let backtrace = std::backtrace::Backtrace::force_capture(); + format!("{backtrace}") +} + +fn prune_crash_files(log_dir: &Path) { + let Ok(entries) = fs::read_dir(log_dir) else { + return; + }; + let mut files = entries + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .map(|name| name.starts_with("crash-") && name.ends_with(".log")) + .unwrap_or(false) + }) + .collect::>(); + files.sort(); + while files.len() as u64 > MAX_CRASH_FILES { + let oldest = files.remove(0); + let _ = fs::remove_file(oldest); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn panic_hook_writes_crash_file() { + let log_dir = std::env::temp_dir().join(format!( + "clipforge-crashlog-{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + fs::create_dir_all(&log_dir).expect("log dir"); + install_panic_hook(&log_dir); + + let result = std::panic::catch_unwind(|| { + let before = fs::read_dir(&log_dir).expect("read").count(); + assert_eq!(before, 0); + panic!("intentional-test-panic"); + }); + assert!(result.is_err()); + drop(std::panic::take_hook()); + + let crash_files = fs::read_dir(&log_dir) + .expect("read") + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .map(|name| name.starts_with("crash-")) + .unwrap_or(false) + }) + .collect::>(); + assert!(!crash_files.is_empty(), "expected a crash log file"); + let body = fs::read_to_string(&crash_files[0]).expect("crash body"); + assert!(body.contains("intentional-test-panic")); + + let _ = fs::remove_dir_all(log_dir); + } +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index a0233b2..faae487 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ pub mod screenshot; pub mod audio; pub mod capture; +pub mod crashlog; pub mod database; pub mod game_detection; pub mod game_watcher; diff --git a/ui/src/main.ts b/ui/src/main.ts index 50f4d05..0509c18 100644 --- a/ui/src/main.ts +++ b/ui/src/main.ts @@ -640,6 +640,12 @@ function renderSettingsView() {

50 GB cap

Old temporary buffer segments are removed automatically; saved clips are kept.

+
+

Support

+

Crash logs

+

Panic details are written to the logs folder so issues can be investigated.

+ +

Hotkeys

Customizable

@@ -830,6 +836,10 @@ function bindEvents() { void saveHotkeys(); }); + appRoot.querySelector("[data-action='reveal-crash-logs']")?.addEventListener("click", () => { + void revealCrashLogs(); + }); + appRoot.querySelectorAll("[data-action='reveal-screenshot']").forEach((button) => { button.addEventListener("click", () => { const path = button.dataset.screenshotPath; @@ -1192,6 +1202,15 @@ async function revealScreenshot(path: string) { } } +async function revealCrashLogs() { + try { + await window.__TAURI__?.core?.invoke?.("reveal_crash_logs"); + } catch (error) { + console.error("Could not reveal crash logs", error); + showNotice(`Could not reveal crash logs: ${String(error)}`); + } +} + async function uploadSelectedClip() { if (!tauriInvoke || !state.selectedClipId) { return;