The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
tech(#01): LU schreibt endlich ein Logfile — Bugs beim Nutzer werden diagnostizierbar
David8d13931f7b62
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 1831334c..55ccc85a 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2579,6 +2579,7 @@ dependencies = ["tokio-util","tower-http","tracing",+ "tracing-appender","tracing-subscriber","url","urlencoding",@@ -4823,6 +4824,12 @@ dependencies = ["serde_json",]+[[package]]+name = "symlink"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"+[[package]]name = "syn"version = "1.0.109"@@ -5662,6 +5669,19 @@ dependencies = ["tracing-core",]+[[package]]+name = "tracing-appender"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"+dependencies = [+ "crossbeam-channel",+ "symlink",+ "thiserror 2.0.18",+ "time",+ "tracing-subscriber",+]+[[package]]name = "tracing-attributes"version = "0.1.31"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex da73307d..3c28951c 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -66,6 +66,12 @@ socket2 = "0.5"chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }tracing = "0.1"tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }+# Audit #01 — the rolling log FILE. A shipped desktop app has no stdout, so+# until this crate arrived every line the app produced was thrown away and a+# user's crash left no artefact to ask for. 0.2 is the series that pairs with+# tracing-subscriber 0.3 (it re-exports `MakeWriter` from it); `max_log_files`+# needs >= 0.2.3.+tracing-appender = "0.2"[target.'cfg(windows)'.dependencies]windows-sys = { version = "0.59", features = ["Win32_System_JobObjects", "Win32_System_Threading", "Win32_Foundation", "Win32_Security"] }diff --git a/src-tauri/src/commands/logging.rs b/src-tauri/src/commands/logging.rsnew file mode 100644index 00000000..5cc42dc9--- /dev/null+++ b/src-tauri/src/commands/logging.rs@@ -0,0 +1,292 @@+//! The log file, as seen from the frontend.+//!+//! Audit finding #01: LU wrote no log file at all. `init_tracing` had a single+//! stdout layer, and a shipped desktop app has no stdout — on Windows the+//! release binary is built with `windows_subsystem = "windows"`, on macOS it is+//! launched from Finder. Any bug that could not be reproduced on a developer+//! machine was therefore unreachable: the user had nothing to send.+//!+//! main.rs now owns the Rust half (a rolling file writer next to the crash+//! log). This module is the part the WebView can reach:+//!+//! * `log_write` — the frontend mirrors its own warn/error lines into the+//! same file, so a support log holds BOTH halves of the app+//! in one chronological stream. Without it the file would+//! describe the backend of a bug whose visible half happened+//! in React.+//! * `log_file_path` — Settings → Troubleshoot shows the user where the file+//! is, which is the whole point of writing one.+//! * `log_reveal` — opens that folder in the file manager. `plugin:shell|open`+//! cannot do this: with no `plugins.shell.open` entry in+//! tauri.conf.json the plugin falls back to its built-in+//! validator, which only accepts `https?:` / `mailto:` /+//! `tel:` URLs and rejects a filesystem path.++use serde::Serialize;++/// Trusted callers only, but "trusted" here means "our own bundled frontend",+/// and a runaway loop in it must not be able to fill the user's disk through+/// a rolling file that is only pruned once a day. One line is capped here;+/// the daily rotation and `max_log_files` cap the rest.+const MAX_MESSAGE_CHARS: usize = 4000;++/// Filename parts of the rolling appender. Kept next to the command that+/// reports the path so the two cannot drift apart; main.rs builds the+/// appender from the same constants.+pub const LOG_FILE_PREFIX: &str = "lu";+pub const LOG_FILE_SUFFIX: &str = "log";++/// The five levels `tracing` knows, parsed from whatever the frontend sent.+///+/// Case-insensitive because the JS side uses lowercase names and a human+/// typing into a console will not. Anything else is rejected rather than+/// silently downgraded to `info`: a typo that logs at the wrong level is a+/// line nobody finds later, and the frontend's own logger only ever sends+/// `warn` / `error`, so a different value means a real bug on the caller side.+pub fn parse_level(raw: &str) -> Option<tracing::Level> {+ match raw.trim().to_ascii_lowercase().as_str() {+ "trace" => Some(tracing::Level::TRACE),+ "debug" => Some(tracing::Level::DEBUG),+ "info" => Some(tracing::Level::INFO),+ "warn" | "warning" => Some(tracing::Level::WARN),+ "error" => Some(tracing::Level::ERROR),+ _ => None,+ }+}++/// One event, one line. A JS stack trace arrives with embedded newlines and+/// would otherwise break the "one record per line" shape the file has for+/// every Rust-side event, which is what makes it greppable at all. Runs of+/// whitespace collapse the same way `crash_report::crash_line` folds a panic+/// payload, and an over-long line is cut with a visible marker so a truncated+/// record can never be mistaken for a complete one.+pub fn sanitize_message(raw: &str) -> String {+ let flat = raw.split_whitespace().collect::<Vec<_>>().join(" ");+ if flat.chars().count() <= MAX_MESSAGE_CHARS {+ return flat;+ }+ let head: String = flat.chars().take(MAX_MESSAGE_CHARS).collect();+ format!("{head}… [truncated]")+}++/// Where a caller-supplied `target` ends up. Empty / missing collapses to a+/// single known value so the field is always present and always searchable.+pub fn sanitize_target(raw: Option<&str>) -> String {+ let t = raw.unwrap_or("").trim();+ if t.is_empty() {+ "frontend".to_string()+ } else {+ sanitize_message(t)+ }+}++/// Name of the file the daily rotation is writing right now.+///+/// `tracing_appender::rolling` builds its suffix from the **UTC** date+/// (`Rotation::round_date` works on `OffsetDateTime::now_utc()`), so the+/// caller must pass a UTC date or the reported path will be wrong for the+/// hours where local and UTC dates disagree — which is most of the day for+/// anyone west of Greenwich.+pub fn log_file_name(utc_date: &str) -> String {+ format!("{LOG_FILE_PREFIX}.{utc_date}.{LOG_FILE_SUFFIX}")+}++#[derive(Debug, Serialize)]+pub struct LogLocation {+ /// Folder holding the rotated files. This is what the "Open folder"+ /// button opens — the user needs the whole set, not only today's.+ pub dir: String,+ /// Today's file. May not exist yet when nothing has been logged since+ /// midnight UTC, hence `exists`.+ pub file: String,+ pub exists: bool,+ /// Bytes of `file`, 0 when it does not exist. Cheap sanity check for a+ /// support request: "0 bytes" means the writer never got going.+ pub size_bytes: u64,+}++/// Mirror one frontend log line into the app log file.+///+/// Deliberately thin: no formatting, no context object, no batching. The+/// frontend already scrubs its own secrets (src/lib/logger.ts) and serialises+/// its context before it calls this, so everything that arrives is a finished+/// string. Validation is the only real work — an unknown level is an error so+/// the caller learns about it instead of losing lines into a level nobody+/// reads.+#[tauri::command]+pub fn log_write(level: String, target: Option<String>, message: String) -> Result<(), String> {+ let lvl = parse_level(&level).ok_or_else(|| {+ format!("unknown log level {level:?} (expected trace, debug, info, warn or error)")+ })?;+ let src = sanitize_target(target.as_deref());+ let msg = sanitize_message(&message);+ // `tracing`'s `target:` must be a `&'static str`, so the caller's target+ // travels as a field instead. The static target marks the whole stream as+ // coming from the WebView, which is what an `RUST_LOG=ui=warn` filter+ // would key on.+ match lvl {+ tracing::Level::TRACE => tracing::trace!(target: "ui", src = %src, "{msg}"),+ tracing::Level::DEBUG => tracing::debug!(target: "ui", src = %src, "{msg}"),+ tracing::Level::INFO => tracing::info!(target: "ui", src = %src, "{msg}"),+ tracing::Level::WARN => tracing::warn!(target: "ui", src = %src, "{msg}"),+ tracing::Level::ERROR => tracing::error!(target: "ui", src = %src, "{msg}"),+ }+ Ok(())+}++/// Where the log lives, for Settings → Troubleshoot.+#[tauri::command]+pub fn log_file_path() -> Result<LogLocation, String> {+ let dir = crate::os_paths::log_dir();+ let file = dir.join(log_file_name(&chrono::Utc::now().format("%Y-%m-%d").to_string()));+ let meta = std::fs::metadata(&file).ok();+ Ok(LogLocation {+ dir: dir.to_string_lossy().to_string(),+ file: file.to_string_lossy().to_string(),+ exists: meta.is_some(),+ size_bytes: meta.map(|m| m.len()).unwrap_or(0),+ })+}++/// Open the log folder in the platform file manager.+///+/// The directory is created first: a user who asks for the logs on a machine+/// where nothing has been logged yet should get an empty folder, not a file+/// manager error about a path that does not exist.+#[tauri::command]+pub fn log_reveal() -> Result<(), String> {+ let dir = crate::os_paths::log_dir();+ // House rule (os_error.rs drift guard): never hand the operating system's+ // own wording to the user — on a German Windows it is a German sentence in+ // an English app.+ std::fs::create_dir_all(&dir)+ .map_err(|e| format!("cannot create {}: {}", dir.display(), crate::os_error::english(&e)))?;++ #[cfg(target_os = "macos")]+ let mut cmd = {+ let mut c = std::process::Command::new("open");+ c.arg(&dir);+ c+ };+ #[cfg(target_os = "windows")]+ let mut cmd = {+ let mut c = std::process::Command::new("explorer");+ c.arg(&dir);+ c+ };+ #[cfg(all(unix, not(target_os = "macos")))]+ let mut cmd = {+ let mut c = std::process::Command::new("xdg-open");+ c.arg(&dir);+ c+ };++ crate::process_util::suppress_window(&mut cmd);+ // `explorer.exe` returns exit code 1 even on success, so only a spawn+ // failure (no such binary — a bare Linux container without xdg-utils) is+ // reported. Waiting for the file manager to close would hang the command.+ cmd.spawn()+ .map(|_| ())+ .map_err(|e| format!("cannot open the log folder: {}", crate::os_error::english(&e)))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_every_level_case_insensitively() {+ assert_eq!(parse_level("warn"), Some(tracing::Level::WARN));+ assert_eq!(parse_level("WARN"), Some(tracing::Level::WARN));+ assert_eq!(parse_level(" Error "), Some(tracing::Level::ERROR));+ assert_eq!(parse_level("info"), Some(tracing::Level::INFO));+ assert_eq!(parse_level("debug"), Some(tracing::Level::DEBUG));+ assert_eq!(parse_level("trace"), Some(tracing::Level::TRACE));+ // JS console vocabulary — `warning` is what a few callers say.+ assert_eq!(parse_level("warning"), Some(tracing::Level::WARN));+ }++ #[test]+ fn rejects_anything_that_is_not_a_level() {+ // A typo must not quietly become `info`: the line would be written at+ // a level the support filter does not read, which is the same as+ // losing it.+ assert_eq!(parse_level("fatal"), None);+ assert_eq!(parse_level(""), None);+ assert_eq!(parse_level("wa rn"), None);+ assert_eq!(parse_level("../../etc/passwd"), None);+ }++ #[test]+ fn log_write_refuses_an_unknown_level_and_names_it() {+ let err = log_write("fatal".into(), None, "boom".into()).unwrap_err();+ assert!(err.contains("fatal"), "the error should quote the bad level: {err}");+ }++ #[test]+ fn log_write_accepts_a_valid_level() {+ // No subscriber is installed in a unit test, so this only proves the+ // validation path and that the macros compile for every arm.+ assert!(log_write("warn".into(), Some("chat".into()), "hi".into()).is_ok());+ assert!(log_write("error".into(), None, "hi".into()).is_ok());+ }++ #[test]+ fn a_js_stack_trace_stays_on_one_line() {+ let stack = "TypeError: x is not a function\n at foo (app.js:1:2)\r\n at bar";+ let out = sanitize_message(stack);+ assert!(!out.contains('\n'), "got: {out}");+ assert!(!out.contains('\r'), "got: {out}");+ assert!(out.contains("TypeError: x is not a function at foo (app.js:1:2) at bar"));+ }++ #[test]+ fn an_enormous_message_is_cut_and_says_so() {+ let out = sanitize_message(&"a".repeat(MAX_MESSAGE_CHARS * 3));+ assert!(out.ends_with("… [truncated]"), "a cut line must be recognisable as cut");+ assert!(out.chars().count() < MAX_MESSAGE_CHARS + 40);+ }++ #[test]+ fn a_short_message_is_untouched_apart_from_whitespace() {+ assert_eq!(sanitize_message("model load failed"), "model load failed");+ assert_eq!(sanitize_message(" padded "), "padded");+ }++ #[test]+ fn a_missing_target_gets_a_searchable_default() {+ assert_eq!(sanitize_target(None), "frontend");+ assert_eq!(sanitize_target(Some(" ")), "frontend");+ assert_eq!(sanitize_target(Some("chatStore")), "chatStore");+ }++ #[test]+ fn the_reported_file_name_matches_the_appender_convention() {+ // tracing-appender builds `<prefix>.<date>.<suffix>`; if main.rs and+ // this command disagree, Settings shows a path that does not exist.+ assert_eq!(log_file_name("2026-08-31"), "lu.2026-08-31.log");+ }++ #[test]+ fn main_builds_the_appender_from_these_same_constants() {+ // The name is only right because both sides use the constants above.+ // A refactor that inlines "lu" in main.rs would break the Settings+ // path silently, so pin the wiring here.+ let src = include_str!("../main.rs");+ assert!(+ src.contains("commands::logging::LOG_FILE_PREFIX")+ && src.contains("commands::logging::LOG_FILE_SUFFIX"),+ "the rolling appender must be named from logging.rs's constants"+ );+ }++ #[test]+ fn log_file_path_points_into_the_log_dir() {+ let loc = log_file_path().expect("path lookup never fails");+ assert!(loc.file.starts_with(&loc.dir), "{loc:?}");+ assert!(loc.file.ends_with(".log"), "{loc:?}");+ assert!(loc.dir.ends_with("logs"), "{loc:?}");+ // Never reports a size for a file it just said does not exist.+ assert!(loc.exists || loc.size_bytes == 0, "{loc:?}");+ }+}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 5f7bf3b5..a1507163 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -9,6 +9,7 @@ pub mod gguf;pub mod gpu;pub mod health;pub mod install;+pub mod logging;pub mod media_cmds;pub mod mlx;pub mod oauth;diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 62116802..117021bb 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -62,6 +62,46 @@ fn should_offload_after_hide(visible_now: bool, hide_generation: u64, current_ge!visible_now && hide_generation == current_generation}+/// How many rotated log files survive. The appender prunes on every+/// rotation, so this is "roughly the last week" at one file per day.+///+/// The number is a support trade-off, not a storage one: a user reporting a+/// bug from Monday is usually asked for the log on Wednesday, and a file that+/// was already pruned cannot be sent. Seven days of a desktop app's log is a+/// few MB — small enough that nobody notices, long enough that a report which+/// took a weekend to write still has its evidence.+const LOG_FILES_KEPT: usize = 7;++/// Build the rolling-file writer for the app log.+///+/// Returns the non-blocking writer together with its `WorkerGuard`. The guard+/// is the classic `tracing-appender` trap: it owns the background thread that+/// actually performs the writes, and dropping it shuts that thread down and+/// flushes. Dropped at the end of the function that made it — the shape you+/// get from `let (w, _guard) = non_blocking(...)` inside a helper — the log+/// file ends up empty or nearly so, which looks exactly like "the logging+/// never worked". So it is handed back to `main`, which holds it for as long+/// as the process runs. See the caller.+///+/// Returns `None` rather than failing the launch when the directory cannot be+/// created (read-only home, full disk, a locked-down corporate profile): a+/// missing log file is a degraded app, an app that refuses to start because+/// it could not open its log file is a broken one.+fn file_log_writer() -> Option<(tracing_appender::non_blocking::NonBlocking, tracing_appender::non_blocking::WorkerGuard)> {+ let dir = os_paths::log_dir();+ std::fs::create_dir_all(&dir).ok()?;+ let appender = tracing_appender::rolling::Builder::new()+ .rotation(tracing_appender::rolling::Rotation::DAILY)+ // Same constants the `log_file_path` command reports from, so+ // Settings can never point at a name the appender does not write.+ .filename_prefix(commands::logging::LOG_FILE_PREFIX)+ .filename_suffix(commands::logging::LOG_FILE_SUFFIX)+ .max_log_files(LOG_FILES_KEPT)+ .build(&dir)+ .ok()?;+ Some(tracing_appender::non_blocking(appender))+}+/// Initialise tracing-subscriber once on app start. `LU_LOG_FORMAT=json`/// switches to single-line JSON output (one object per event) for users/// who pipe LU's stdout into Loki / Vector / a log file consumed by@@ -70,7 +110,26 @@ fn should_offload_after_hide(visible_now: bool, hide_generation: u64, current_ge////// `RUST_LOG` is honored as the filter — common values are `info`,/// `locally_uncensored=debug`, or a per-module spec.-fn init_tracing() {+///+/// Audit finding #01: until now this was the stdout layer and nothing else,+/// and a shipped desktop app has no stdout. On Windows the release binary is+/// built with `windows_subsystem = "windows"`; on macOS it is launched from+/// Finder; the DevTools console only opens under `debug_assertions`. Every+/// line the app produced went nowhere, so a crash on a user's machine left no+/// artefact at all and any bug that did not reproduce locally was unreachable.+/// A rolling file layer is added ALONGSIDE the console layer — the terminal+/// output a developer runs `cargo tauri dev` for is unchanged, there is simply+/// now also a file to ask a user for.+///+/// The file layer is always the plain text formatter, even under+/// `LU_LOG_FORMAT=json`: that switch exists for someone piping stdout into a+/// log processor, whereas the file's reader is a human reading a support+/// attachment. ANSI is off for the same reason — escape codes in a file the+/// user opens in Notepad are noise.+///+/// Returns the writer's `WorkerGuard`, which the caller MUST keep alive.+#[must_use = "the WorkerGuard must outlive the app or the log file stays empty"]+fn init_tracing() -> Option<tracing_appender::non_blocking::WorkerGuard> {use tracing_subscriber::{fmt, prelude::*, EnvFilter};// `try_init` instead of `init` so we never panic if something else// (a test harness, a re-import) already set the global subscriber.@@ -78,9 +137,22 @@ fn init_tracing() {let json_mode = std::env::var("LU_LOG_FORMAT").map(|v| v.eq_ignore_ascii_case("json")).unwrap_or(false);+ let (file_layer, guard) = match file_log_writer() {+ Some((writer, guard)) => (+ Some(+ fmt::layer()+ .with_writer(writer)+ .with_ansi(false)+ .fmt_fields(EnglishFields(fmt::format::DefaultFields::new())),+ ),+ Some(guard),+ ),+ None => (None, None),+ };if json_mode {let _ = tracing_subscriber::registry().with(filter)+ .with(file_layer).with(fmt::layer().json()@@ -92,9 +164,11 @@ fn init_tracing() {} else {let _ = tracing_subscriber::registry().with(filter)+ .with(file_layer).with(fmt::layer().compact().fmt_fields(EnglishFields(fmt::format::DefaultFields::new()))).try_init();}+ guard}/// A field formatter that runs the finished text through `os_error`.@@ -144,7 +218,11 @@ fn main() {// and dies on "No module named 'encodings'".python::sanitize_appimage_python_env();- init_tracing();+ // Bound to a named local, not `let _ = ...`: `_log_guard` lives until the+ // end of `main`, i.e. as long as the app runs, while `_` would drop the+ // guard on this very line and take the file writer's worker thread down+ // with it before the first line was written.+ let _log_guard = init_tracing();tracing::info!(version = env!("CARGO_PKG_VERSION"),"LU starting"@@ -350,6 +428,11 @@ fn main() {commands::waitlist::waitlist_submit,// B7 (uselu Phase 4 inspiration) — one-shot diagnostic probecommands::health::system_health,+ // Audit #01 — the app log file: the frontend mirrors its warn /+ // error lines into it, Settings shows and opens it.+ commands::logging::log_write,+ commands::logging::log_file_path,+ commands::logging::log_reveal,// Bug BB v2.5.0 — BobbyT GPU pickercommands::gpu::detect_gpus,commands::gpu::set_gpu_selection,@@ -752,17 +835,23 @@ mod log_english_tests {/// The test above builds its own subscriber, so on its own it would still/// pass if `init_tracing` stopped using the wrapper. This is the other- /// half: BOTH log modes have to go through it, or a user on JSON logs- /// keeps the German line the text mode no longer has.+ /// half: EVERY layer has to go through it, or a user on JSON logs keeps+ /// the German line the text mode no longer has — and since audit #01 the+ /// file layer is the one whose text actually reaches a support request.#[test]- fn both_log_modes_are_wired_through_the_wrapper() {+ fn every_log_layer_is_wired_through_the_wrapper() {const SRC: &str = include_str!("main.rs");let init = &SRC[SRC.find("fn init_tracing()").expect("init_tracing exists")..];let init = &init[..init.find("\n}\n").expect("the function ends")];+ let layers = init.matches("fmt::layer()").count();+ assert!(+ layers >= 3,+ "expected at least the file, text and json layers, found {layers}:\n{init}"+ );assert_eq!(init.matches("EnglishFields(").count(),- 2,- "text mode and json mode must both sanitise:\n{init}"+ layers,+ "every fmt layer must sanitise the operating system's wording:\n{init}");}@@ -775,3 +864,151 @@ mod log_english_tests {assert!(out.contains("version=\"2.6.7\""), "got: {out}");}}++/// The log FILE itself (audit finding #01).+///+/// Nothing here writes a real log — installing a global subscriber inside a+/// unit test would fight every other test in the binary for the process-wide+/// slot. What these pin is the part a refactor silently breaks: that the file+/// layer exists at all, that its guard is kept, and that the rotation cannot+/// quietly become unbounded.+#[cfg(test)]+mod log_file_tests {+ const SRC: &str = include_str!("main.rs");++ fn init_tracing_body() -> &'static str {+ let s = &SRC[SRC.find("fn init_tracing()").expect("init_tracing exists")..];+ &s[..s.find("\n}\n").expect("the function ends")]+ }++ #[test]+ fn the_worker_guard_is_held_by_main_and_not_dropped_on_the_spot() {+ // THE tracing-appender trap. `let _ = init_tracing();` compiles, runs,+ // and produces an empty log file, because `_` drops the guard+ // immediately and the writer thread dies with it. A named binding in+ // `main` lives until the process ends.+ // Bounded to main's own body — the negative assertion below matches+ // its own source text otherwise, and the test would fail on itself.+ let main_fn = &SRC[SRC.find("\nfn main() {").expect("main exists")..];+ let main_fn = &main_fn[..main_fn.find("\n}\n").expect("main ends")];+ assert!(+ main_fn.contains("let _log_guard = init_tracing();"),+ "main must bind the WorkerGuard to a named local for the app's lifetime"+ );+ assert!(+ !main_fn.contains("let _ = init_tracing();"),+ "`let _ =` drops the guard at once and empties the log file"+ );+ }++ #[test]+ fn the_file_layer_is_added_to_both_log_modes_and_replaces_neither() {+ // "Additionally, not instead of": a developer running `cargo tauri dev`+ // must keep the console output they read while working.+ let init = init_tracing_body();+ assert_eq!(+ init.matches(".with(file_layer)").count(),+ 2,+ "text mode and json mode both need the file layer:\n{init}"+ );+ assert!(+ init.contains("fmt::layer().compact()"),+ "the stdout layer must survive alongside the file:\n{init}"+ );+ }++ #[test]+ fn rotation_is_bounded_in_both_directions() {+ // 0 would keep nothing (a log that prunes itself is no log), and a+ // large number turns "the app writes a log" into "the app fills the+ // disk of anyone who leaves it running for a year".+ assert!(+ (2..=31).contains(&super::LOG_FILES_KEPT),+ "kept log files out of range: {}",+ super::LOG_FILES_KEPT+ );+ let init = SRC+ .find("fn file_log_writer()")+ .map(|i| &SRC[i..i + 1200])+ .expect("file_log_writer exists");+ assert!(init.contains("max_log_files"), "the appender must prune:\n{init}");+ assert!(init.contains("Rotation::DAILY"), "rotation must be configured:\n{init}");+ }++ #[test]+ fn a_home_that_cannot_be_written_to_does_not_stop_the_app() {+ // Read-only profile / full disk: a missing log file is a degraded app,+ // an app that will not launch without one is a broken app. The helper+ // must therefore be fallible-but-soft, i.e. return an Option.+ let src = SRC+ .find("fn file_log_writer()")+ .map(|i| &SRC[i..i + 400])+ .expect("file_log_writer exists");+ assert!(src.contains("-> Option<"), "must degrade rather than panic:\n{src}");+ }++ #[test]+ fn the_log_lives_next_to_the_crash_log() {+ // One folder per support request. If these two drift apart, half the+ // evidence gets left behind on every report.+ let logs = crate::os_paths::log_dir();+ let crash = crate::crash_report::crash_log_path();+ assert_eq!(+ logs.parent(),+ crash.parent(),+ "the rolling log and crash.log must share one directory"+ );+ }++ #[test]+ fn the_appender_really_writes_the_file_name_settings_reports() {+ // The only test here that runs the real crate. Everything else about+ // the path is our own arithmetic; this pins it against+ // tracing-appender's actual behaviour, including the detail that the+ // date in the name is UTC and not the local day. A subscriber scoped+ // to this thread keeps it out of the global slot the other tests share.+ use tracing_subscriber::layer::SubscriberExt;+ let dir = tempfile::tempdir().expect("tempdir");+ let appender = tracing_appender::rolling::Builder::new()+ .rotation(tracing_appender::rolling::Rotation::DAILY)+ .filename_prefix(crate::commands::logging::LOG_FILE_PREFIX)+ .filename_suffix(crate::commands::logging::LOG_FILE_SUFFIX)+ .max_log_files(super::LOG_FILES_KEPT)+ .build(dir.path())+ .expect("the appender builds");+ let (writer, guard) = tracing_appender::non_blocking(appender);+ let subscriber = tracing_subscriber::registry().with(+ tracing_subscriber::fmt::layer().with_writer(writer).with_ansi(false),+ );+ tracing::subscriber::with_default(subscriber, || {+ tracing::warn!("a line that has to reach the disk");+ });+ // Dropping the guard shuts the writer thread down AND flushes it —+ // which is exactly why main must not drop it early.+ drop(guard);++ let expected = crate::commands::logging::log_file_name(+ &chrono::Utc::now().format("%Y-%m-%d").to_string(),+ );+ let written = std::fs::read_to_string(dir.path().join(&expected))+ .unwrap_or_else(|e| panic!("expected {expected} in the log dir: {e}"));+ assert!(+ written.contains("a line that has to reach the disk"),+ "the file exists but is empty — the guard was dropped too early: {written:?}"+ );+ }++ #[test]+ fn the_frontend_can_actually_reach_the_log_commands() {+ // The commands exist in logging.rs whether or not they are registered;+ // an unregistered command is an invoke that rejects at runtime with+ // "not allowed by scope" and no compile error anywhere.+ for cmd in [+ "commands::logging::log_write",+ "commands::logging::log_file_path",+ "commands::logging::log_reveal",+ ] {+ assert!(SRC.contains(cmd), "{cmd} is not in generate_handler!");+ }+ }+}diff --git a/src-tauri/src/os_paths.rs b/src-tauri/src/os_paths.rsindex 89fef1d0..54d86a52 100644--- a/src-tauri/src/os_paths.rs+++ b/src-tauri/src/os_paths.rs@@ -21,6 +21,29 @@ pub fn cache_dir() -> PathBuf {.join("lu-labs")}+/// Where the rolling application log is written (`init_tracing` in main.rs,+/// read back by the `log_file_path` command).+///+/// Deliberately NOT Tauri's `app_log_dir()`, for two reasons:+///+/// 1. Lifetime. `app_log_dir()` needs an `AppHandle`, which only exists once+/// `tauri::Builder::build()` has run. Tracing is initialised before that —+/// it has to be, or every line the app emits while starting up (the very+/// window where the hard-to-reproduce failures live) would be written to a+/// subscriber that does not exist yet. The `WorkerGuard` for the file+/// writer has the same problem: it must be created before the first event.+/// 2. Support. `crash.log` already lives in `data_dir()` (crash_report.rs).+/// Putting the rolling log in a sibling folder means one directory holds+/// every artefact a support request needs, instead of the panic record and+/// the log being two unrelated places on three different operating systems.+///+/// macOS: ~/Library/Application Support/lu-labs/logs+/// Windows: %LOCALAPPDATA%\lu-labs\logs+/// Linux: ~/.local/share/lu-labs/logs+pub fn log_dir() -> PathBuf {+ data_dir().join("logs")+}+/// Locate a usable Python interpreter. Returns the absolute path to the/// binary, or `None` if no real Python is on the system.///diff --git a/src/components/settings/LogFileSettings.tsx b/src/components/settings/LogFileSettings.tsxnew file mode 100644index 00000000..9ba49cf8--- /dev/null+++ b/src/components/settings/LogFileSettings.tsx@@ -0,0 +1,137 @@+// Audit #01 — the app log file, surfaced to the user.+//+// The Rust side now writes a rolling log (one file per day, seven kept) and+// the frontend mirrors its warn/error lines into it. None of that helps a+// support request unless the user can find the file, so this block sits in+// Settings → Troubleshoot, right under the diagnostic probe that is already+// the "something is wrong, what do I send you" panel.+//+// Two actions, because both fail in different places: "Open folder" is the+// fast path but does nothing useful over a remote desktop or on a Linux box+// without xdg-utils, and "Copy path" always works and can be pasted into a+// bug report as text.++import { useEffect, useState } from 'react'+import { FileText, FolderOpen, Check, Copy } from 'lucide-react'+import { backendCall, isTauri } from '../../api/backend'++interface LogLocation {+ dir: string+ file: string+ exists: boolean+ size_bytes: number+}++function prettySize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`+}++export function LogFileSettings() {+ const [loc, setLoc] = useState<LogLocation | null>(null)+ const [error, setError] = useState<string | null>(null)+ // One flag for both buttons' "it worked" tick — they are never pressed in+ // the same 1.5 s, and two timers would be two things to clean up.+ const [done, setDone] = useState<'copied' | 'opened' | null>(null)++ useEffect(() => {+ // Browser dev mode has no Rust side and therefore no log file; asking+ // would only produce an "Unknown backend command" error to render.+ if (!isTauri()) return+ let alive = true+ backendCall<LogLocation>('log_file_path', {})+ .then((r) => alive && setLoc(r))+ .catch((e) => alive && setError(e instanceof Error ? e.message : String(e)))+ return () => {+ alive = false+ }+ }, [])++ useEffect(() => {+ if (!done) return+ const t = setTimeout(() => setDone(null), 1500)+ return () => clearTimeout(t)+ }, [done])++ if (!isTauri()) {+ return (+ <div className="rounded-lg border border-white/[0.06] p-2.5">+ <div className="text-[0.55rem] uppercase tracking-widest text-gray-500 mb-1.5">Log file</div>+ <p className="text-[0.6rem] text-gray-500">+ Written by the desktop app only. In the browser the console is the log.+ </p>+ </div>+ )+ }++ const copyPath = async () => {+ if (!loc) return+ try {+ await navigator.clipboard.writeText(loc.dir)+ setDone('copied')+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e))+ }+ }++ const openFolder = async () => {+ try {+ await backendCall('log_reveal', {})+ setDone('opened')+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e))+ }+ }++ return (+ <div className="rounded-lg border border-white/[0.06] p-2.5 space-y-2">+ <div className="text-[0.55rem] uppercase tracking-widest text-gray-500 flex items-center gap-1.5">+ <FileText size={10} /> Log file+ </div>++ <p className="text-[0.6rem] text-gray-500 leading-relaxed">+ LU writes a log every day and keeps the last seven. Attach today's file+ to a bug report — it holds what the app was doing right before the+ problem, which a screenshot cannot show.+ </p>++ {loc && (+ <>+ {/* Breaks anywhere: a Windows path under a long user name does not+ fit the panel, and truncating it would make it uncopyable by eye. */}+ <div className="text-[0.6rem] font-mono text-gray-300 break-all leading-relaxed">+ {loc.file}+ </div>+ <div className="text-[0.55rem] text-gray-500">+ {loc.exists+ ? `today's file: ${prettySize(loc.size_bytes)}`+ : 'nothing logged yet today'}+ </div>+ </>+ )}++ {error && (+ <div className="text-[0.6rem] text-red-400 break-all">{error}</div>+ )}++ <div className="flex gap-2">+ <button+ onClick={openFolder}+ className="flex-1 px-3 py-1.5 rounded-md text-[0.65rem] font-medium bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-800 dark:text-gray-200 transition-colors flex items-center justify-center gap-1.5"+ >+ {done === 'opened' ? <Check size={11} /> : <FolderOpen size={11} />}+ {done === 'opened' ? 'Opened' : 'Open folder'}+ </button>+ <button+ onClick={copyPath}+ disabled={!loc}+ className="flex-1 px-3 py-1.5 rounded-md text-[0.65rem] font-medium bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-800 dark:text-gray-200 transition-colors disabled:opacity-50 flex items-center justify-center gap-1.5"+ >+ {done === 'copied' ? <Check size={11} /> : <Copy size={11} />}+ {done === 'copied' ? 'Copied' : 'Copy path'}+ </button>+ </div>+ </div>+ )+}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 3f483917..45b54381 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -7,6 +7,7 @@ import { useSettingsStore } from '../../stores/settingsStore'import { usePermissionStore } from '../../stores/permissionStore'import { useUIStore } from '../../stores/uiStore'import { SliderControl } from './SliderControl'+import { LogFileSettings } from './LogFileSettings'import { PersonaPanel } from '../personas/PersonaPanel'import { AccountPanel } from '../auth/AccountPanel'import { useVoiceStore } from '../../stores/voiceStore'@@ -2058,6 +2059,10 @@ function TroubleshootSection() {</div>)}+ {/* Audit #01 — where the log file is. Above the probe result because+ "send us the log" is the most common outcome of opening this panel. */}+ <LogFileSettings />+{report && (<div className="space-y-2">{/* Backends */}diff --git a/src/lib/__tests__/logger.test.ts b/src/lib/__tests__/logger.test.tsindex 04870e19..38c9972e 100644--- a/src/lib/__tests__/logger.test.ts+++ b/src/lib/__tests__/logger.test.ts@@ -106,3 +106,148 @@ describe('log levels', () => {expect(console.log).toHaveBeenCalledWith('[info]', 'hello', { a: 1 })})})++// ── Audit #01 — mirroring warn/error into the Rust log file ──────────+//+// A shipped desktop app has no stdout and no open DevTools console, so+// everything above this line went nowhere on a user's machine. warn/error are+// additionally handed to the `log_write` Tauri command, which writes them into+// the same rolling file as the Rust side.++const invokeMock = vi.fn()+vi.mock('@tauri-apps/api/core', () => ({ invoke: (...a: unknown[]) => invokeMock(...a) }))++/** Pretend to be inside the Tauri WebView, the way isTauri() detects it. */+function enterTauri() {+ ;(globalThis as Record<string, unknown>).window = { __TAURI_INTERNALS__: {} }+}+function leaveTauri() {+ delete (globalThis as Record<string, unknown>).window+}++/**+ * Let the mirror's promise chain run. The mirror resolves the Tauri module+ * with a dynamic `import()`, so the first call in the file needs a real turn+ * of the event loop, not just a microtask.+ */+const flush = () => new Promise((r) => setTimeout(r, 0))++/** The args of the last log_write invoke, or null when nothing was mirrored. */+function lastMirror(): { level: string; target: string; message: string } | null {+ const call = invokeMock.mock.calls.filter((c) => c[0] === 'log_write').pop()+ return call ? (call[1] as { level: string; target: string; message: string }) : null+}++describe('mirroring to the app log file', () => {+ beforeEach(() => {+ invokeMock.mockReset()+ invokeMock.mockResolvedValue(undefined)+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ enterTauri()+ })++ afterEach(() => {+ leaveTauri()+ vi.restoreAllMocks()+ })++ it('mirrors warn and error', async () => {+ log.warn('disk nearly full')+ log.error('model load failed')+ await flush()+ const levels = invokeMock.mock.calls+ .filter((c) => c[0] === 'log_write')+ .map((c) => (c[1] as { level: string }).level)+ expect(levels).toEqual(['warn', 'error'])+ })++ it('loses nothing when two lines land in the same tick', async () => {+ // Regression: with the resolved invoke memoised instead of the import+ // PROMISE, the second call of a burst started its own dynamic import and+ // its line went missing — and a burst is exactly what an error cascade is.+ log.error('first')+ log.error('second')+ log.warn('third')+ await flush()+ const msgs = invokeMock.mock.calls+ .filter((c) => c[0] === 'log_write')+ .map((c) => (c[1] as { message: string }).message)+ expect(msgs).toEqual(['first', 'second', 'third'])+ })++ it('does NOT mirror debug or info — they are the noise levels', async () => {+ // Render loops, polling and token streams live at these levels. Mirroring+ // them would drown the two levels a support log is read for, and cost an+ // IPC round trip per line.+ log.debug('tick')+ log.info('rendered 60 frames')+ await flush()+ expect(invokeMock.mock.calls.filter((c) => c[0] === 'log_write')).toHaveLength(0)+ })++ it('stays silent outside Tauri — a browser has no log file to write to', async () => {+ leaveTauri()+ log.error('boom')+ await flush()+ expect(invokeMock).not.toHaveBeenCalled()+ })++ it('scrubs BEFORE mirroring, so no secret reaches the file', async () => {+ // The whole point of the file is that a user attaches it to a bug report.+ // A key that the console redacts but the file keeps would be a leak with+ // a delivery mechanism.+ log.error('provider call failed', { apiKey: 'sk-live-123', nested: { token: 'tok-abc' }, model: 'llama3' })+ await flush()+ const args = lastMirror()+ expect(args).not.toBeNull()+ expect(args!.message).not.toContain('sk-live-123')+ expect(args!.message).not.toContain('tok-abc')+ expect(args!.message).toContain('[REDACTED]')+ // …and the harmless context still makes it through, or the file is useless.+ expect(args!.message).toContain('llama3')+ expect(args!.message).toContain('provider call failed')+ })++ it('mirrors a serialised Error, not an empty object', async () => {+ log.error('crashed', { err: new Error('kapow') })+ await flush()+ expect(lastMirror()!.message).toContain('kapow')+ })++ it('never throws when the invoke rejects', async () => {+ // Logging is called from catch blocks. A logger that can fail turns a+ // handled error into an unhandled one.+ invokeMock.mockRejectedValue(new Error('command log_write not allowed by scope'))+ expect(() => log.error('boom')).not.toThrow()+ await flush()+ })++ it('never throws when the invoke throws synchronously', () => {+ invokeMock.mockImplementation(() => {+ throw new Error('IPC bridge gone')+ })+ expect(() => log.warn('bad')).not.toThrow()+ })++ it('never throws on a cyclic context and still logs the message', async () => {+ // scrub() caps recursion depth instead of tracking visited nodes, so a+ // cycle survives it and JSON.stringify would throw on the way to the file.+ const cyclic: Record<string, unknown> = { name: 'loop' }+ cyclic.self = cyclic+ expect(() => log.error('cycle', { cyclic })).not.toThrow()+ await flush()+ expect(lastMirror()!.message).toContain('cycle')+ })++ it('still writes to the console when it mirrors', async () => {+ // The mirror is additional, not a replacement: a developer with DevTools+ // open must keep seeing what they always saw.+ process.env.NODE_ENV = 'production'+ log.error('both places')+ await flush()+ expect(console.error).toHaveBeenCalled()+ expect(lastMirror()).not.toBeNull()+ process.env.NODE_ENV = 'test'+ })+})diff --git a/src/lib/logger.ts b/src/lib/logger.tsindex 6f9df48d..f58c866c 100644--- a/src/lib/logger.ts+++ b/src/lib/logger.ts@@ -12,6 +12,19 @@//// Why not pino: zero extra runtime dep, no transport setup, fits the// uselu-on-Vercel deploy where stdout IS the transport.+//+// Audit #01 — that last paragraph was written for a server. In the DESKTOP+// build there is no stdout: the WebView's console only exists while DevTools+// are open, which happens under `debug_assertions` and nowhere else. Every+// line below was therefore written to nothing on a user's machine. Since the+// Rust side gained a rolling log file, warn/error lines are additionally+// mirrored into it through the `log_write` command, so a support log holds+// both halves of the app in one chronological stream instead of only the+// backend half of a bug whose visible symptom happened in React.+//+// Only warn and error are mirrored. debug/info are the high-frequency levels+// (render loops, polling, token streams) and would drown the signal — and+// every mirrored line costs an IPC round trip. The console keeps all four.export type LogLevel = 'debug' | 'info' | 'warn' | 'error'@@ -58,6 +71,78 @@ function serializeError(err: unknown): Record<string, unknown> | unknown {return err}+/** Levels worth a round trip into the Rust log file. See the header. */+const MIRRORED_LEVELS: ReadonlySet<LogLevel> = new Set<LogLevel>(['warn', 'error'])++/**+ * Same detection as `isTauri()` in ../api/backend, deliberately duplicated+ * rather than imported: backend.ts imports THIS module, and importing it back+ * would close a cycle whose evaluation order decides whether `log` exists when+ * backend.ts's module body runs. Ten lines of duplication beat a TDZ crash on+ * startup that only reproduces under some bundler settings.+ */+function isTauriRuntime(): boolean {+ if (typeof window === 'undefined') return false+ const w = window as unknown as Record<string, unknown>+ return !!(w.__TAURI_INTERNALS__ || w.__TAURI__)+}++type InvokeFn = (cmd: string, args?: Record<string, unknown>) => Promise<unknown>++/**+ * The PROMISE is memoised, not the resolved function. Two warns in the same+ * tick both arrive before any `await` has completed, so a `cachedInvoke`+ * variable would still be null for the second one and it would start a second+ * dynamic import of the same module — measurably losing the second line under+ * some module runners. One promise, shared by every caller.+ */+let invokePromise: Promise<InvokeFn> | null = null++function getInvoke(): Promise<InvokeFn> {+ if (!invokePromise) {+ invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke as InvokeFn)+ }+ return invokePromise+}++/**+ * Mirror one line into the Rust rolling log file.+ *+ * `cleaned` is the ALREADY-SCRUBBED context — the redaction has to happen+ * before this, never inside it, or the secret that the console never shows+ * would be written to a file the user is then asked to attach to a bug report.+ * The single call site in `emit` passes the scrubbed value for that reason.+ *+ * Fire and forget, and it must never throw. Logging is called from catch+ * blocks and from error boundaries; a logger that can fail turns a handled+ * error into an unhandled one, and a failed mirror (no Tauri, command not+ * registered, IPC busy) is not worth a single pixel of user attention. Every+ * path is swallowed: the synchronous body, the dynamic import, the invoke.+ */+function mirrorToLogFile(level: LogLevel, msg: string, cleaned?: LogContext): void {+ if (!MIRRORED_LEVELS.has(level)) return+ if (!isTauriRuntime()) return+ try {+ let message = msg+ if (cleaned && Object.keys(cleaned).length > 0) {+ // scrub() caps its recursion rather than tracking visited nodes, so a+ // cyclic object survives it and JSON.stringify would throw on the cycle.+ try {+ message = `${msg} ${JSON.stringify(cleaned)}`+ } catch {+ message = `${msg} [context not serialisable]`+ }+ }+ void getInvoke()+ .then((invoke) => invoke('log_write', { level, target: 'frontend', message }))+ .catch(() => {+ /* the log file is a best effort; never surface its failure */+ })+ } catch {+ /* unreachable in practice — belt and braces, see the doc comment */+ }+}+function emit(level: LogLevel, msg: string, ctx?: LogContext): void {if (level === 'debug' && isProd()) return@@ -73,6 +158,13 @@ function emit(level: LogLevel, msg: string, ctx?: LogContext): void {: undefinedconst cleaned = scrub(safeCtx) as LogContext | undefined+ // After the scrub, before either console path: the file gets the redacted+ // context and nothing else, and it gets the line whether the build is a+ // production bundle or a dev server — the desktop app is a production+ // bundle, and a `npm run tauri dev` session is the case where somebody is+ // actually reading the file while it is written.+ mirrorToLogFile(level, msg, cleaned)+if (isProd()) {const line = JSON.stringify({ts: new Date().toISOString(),