From 8a1baef44db530293d985b85864a01252b194e52 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:22:12 +0200 Subject: [PATCH 1/5] Desktop: the panic log is kept in the settings folder, never the shared temp folder (#2572) By default the desktop app appended panics to lightcraft-panics.log in the system temp folder, a fixed name that every user shares on Linux and FreeBSD, so another user could create the file first to read the panic messages or plant a link that made LightCraft append to one of the victim's files. The emergency crash log now lives in the settings folder next to logs/, where an isolated LIGHTCRAFT_CONFIG_DIR profile already kept it. A --memory session, LIGHTCRAFT_NO_PREFS and an empty LIGHTCRAFT_CONFIG_DIR keep no crash file, like every other settings-folder file, and report panics on standard error only. The panic hooks are now installed once the arguments are read, so --version, --help and a usage error never create a portable LightCraftData folder for the crash log. --- README.md | 3 +- README.zh-hans.md | 3 +- README.zh-hant.md | 3 +- apps/lightcraft/src/logging.rs | 4 +- apps/lightcraft/src/main.rs | 99 +++++++++++++++++++++++++++++----- docs/control-protocol.md | 3 +- docs/whats-new.md | 9 ++++ 7 files changed, 105 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index c8db5a50ac..e7d1dbfb8c 100644 --- a/README.md +++ b/README.md @@ -474,7 +474,8 @@ at `warn`. `LIGHTCRAFT_LOG=info` or `debug` works as before (that level for Ligh errors from the rest; any other value: warnings and errors only) and wins over `RUST_LOG`, which otherwise replaces the default with env_logger-style directives such as `RUST_LOG=debug` or `RUST_LOG=warn,lightcraft_pipeline=trace` (a directive ending in `*` covers every target starting with it, as in `lightcraft*=debug`). Panics are recorded there -too, and still in `lightcraft-panics.log` in the temp folder. The logger is `apps/lightcraft/src/logging.rs`. +too, and in `lightcraft-panics.log` in the settings folder; runs with `--memory` or `LIGHTCRAFT_NO_PREFS` report +them on standard error only. The logger is `apps/lightcraft/src/logging.rs`. The web build needs the `wasm32-unknown-unknown` target and the matching `wasm-bindgen` CLI (`cargo xtask web` prints the exact install command); see [docs/web.md](docs/web.md). diff --git a/README.zh-hans.md b/README.zh-hans.md index 824913f140..0b3ebb77c1 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -409,7 +409,8 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft 错误;其他值:只记警告和错误),并且优先于 `RUST_LOG`,后者会把默认值替换为 env_logger 风格的指令,例如 `RUST_LOG=debug` 或 `RUST_LOG=warn,lightcraft_pipeline=trace`(以 `*` 结尾的指令覆盖所有以它开头的目标,如 `lightcraft*=debug`)。panic 也会记录在那里, -并且仍然写在临时文件夹里的 `lightcraft-panics.log`。日志器是 `apps/lightcraft/src/logging.rs`。 +并且写在设置文件夹里的 `lightcraft-panics.log`;带 `--memory` 或 +`LIGHTCRAFT_NO_PREFS` 运行时只写到标准错误。日志器是 `apps/lightcraft/src/logging.rs`。 网页版需要 `wasm32-unknown-unknown` target 和匹配的 `wasm-bindgen` CLI (`cargo xtask web` 会打印确切的安装命令);见 [docs/web.md](docs/web.md)。 diff --git a/README.zh-hant.md b/README.zh-hant.md index a17505f3f4..d5665dfb2f 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -435,7 +435,8 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft 用該層級,其餘只記警告與錯誤;其他值:只記警告與錯誤),並且優先於 `RUST_LOG`;未設定 `LIGHTCRAFT_LOG` 時,`RUST_LOG` 會把預設值換成 env_logger 風格的指令,例如 `RUST_LOG=debug` 或 `RUST_LOG=warn,lightcraft_pipeline=trace`(以 `*` 結尾的指令會涵蓋所有以它開頭的目標,如 `lightcraft*=debug`)。panic 一樣會記錄在那裡, -並且仍然會寫在暫存資料夾裡的 `lightcraft-panics.log`。記錄器程式碼位於 `apps/lightcraft/src/logging.rs`。 +並且會寫在設定資料夾裡的 `lightcraft-panics.log`;帶 `--memory` 或 +`LIGHTCRAFT_NO_PREFS` 執行時只會寫到標準錯誤輸出。記錄器程式碼位於 `apps/lightcraft/src/logging.rs`。 網頁版需要 `wasm32-unknown-unknown` target 以及對應版本的 `wasm-bindgen` CLI (`cargo xtask web` 會印出確切的安裝指令);詳見 [docs/web.md](docs/web.md)。 diff --git a/apps/lightcraft/src/logging.rs b/apps/lightcraft/src/logging.rs index 6239aded67..0873614179 100644 --- a/apps/lightcraft/src/logging.rs +++ b/apps/lightcraft/src/logging.rs @@ -329,8 +329,8 @@ pub fn install() -> Option<&'static AppLogger> { Some(logger) } -/// Chain a panic hook after the current one (the engine guard's: standard error plus -/// `lightcraft-panics.log` in the temp folder) that also puts the panic in the log file. +/// Chain a panic hook after the current one (the engine guard's when there is a crash log: standard +/// error plus `lightcraft-panics.log` in the settings folder) that also puts the panic in the log file. pub fn record_panics(logger: &'static AppLogger) { let previous = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 95739b3e97..db4c9cdc9e 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -834,19 +834,38 @@ fn control_port_from(what: &str, value: Option) -> Option { port } -/// An isolated profile keeps the emergency crash log with its other app data. With no -/// override (or an empty override), retain the historical system-temp location. -fn panic_log_path_with(env: impl Fn(&str) -> Option, temp: std::path::PathBuf) -> std::path::PathBuf { - env("LIGHTCRAFT_CONFIG_DIR").filter(|value| !value.is_empty()).map(std::path::PathBuf::from).unwrap_or(temp).join("lightcraft-panics.log") +/// The emergency crash log: `lightcraft-panics.log` in the settings folder, next to `ui.json` (an +/// isolated profile's with `LIGHTCRAFT_CONFIG_DIR`). Never the system temp folder: on Linux and +/// FreeBSD every user shares it, so another could create the file first or put a link there (issue +/// #2572). None (panics then go to standard error, and to the log file when there is one) for a +/// `--memory` session, which writes nothing (issue #164), with `LIGHTCRAFT_NO_PREFS` or with no +/// settings folder. +fn panic_log_path(in_memory: bool) -> Option { + panic_log_path_with(in_memory, std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some(), config_dir) +} + +/// `config` (the settings folder) is looked up only when the crash log is kept. +fn panic_log_path_with(in_memory: bool, no_prefs: bool, config: impl FnOnce() -> Option) -> Option { + if in_memory || no_prefs { + return None; + } + config().map(|d| d.join("lightcraft-panics.log")) +} + +/// The panic hooks: the engine guard's (standard error, and the crash log when there is one), then +/// the log file's. +fn install_panic_hooks(logger: Option<&'static logging::AppLogger>, in_memory: bool) { + if let Some(path) = panic_log_path(in_memory) { + lightcraft_engine::guard::install_hook(path); + } + if let Some(logger) = logger { + logging::record_panics(logger); + } } fn main() -> eframe::Result { // First, so every start-up record is kept for the log file (`logging`). let logger = logging::install(); - lightcraft_engine::guard::install_hook(panic_log_path_with(|name| std::env::var_os(name), std::env::temp_dir())); - if let Some(logger) = logger { - logging::record_panics(logger); - } alloc_release::install(); let mut control_port = control_port_from("LIGHTCRAFT_CONTROL_PORT", std::env::var("LIGHTCRAFT_CONTROL_PORT").ok().filter(|v| !v.is_empty())); let mut files = Vec::new(); @@ -875,6 +894,10 @@ fn main() -> eframe::Result { _ => files.push(a), } } + // Like the log file, after the arguments: `--version`, `--help` and a usage error create no + // portable `LightCraftData` folder for the crash log (a panic until here still reaches + // standard error). + install_panic_hooks(logger, in_memory); // The log file: opened after the arguments, so `--version`, `--help` and a usage error leave // no file behind. Records logged until now are written to it first. let mut log_file = None; @@ -1557,11 +1580,61 @@ mod tests { mod config_path_tests { use super::*; + /// #2572: the crash log is in the settings folder (an isolated profile's too: `config_dir` honours + /// `LIGHTCRAFT_CONFIG_DIR`); without one (an empty override, no home folder), with + /// `LIGHTCRAFT_NO_PREFS` or in a `--memory` session there is none, and the last two never look the + /// folder up. #[test] - fn config_override_keeps_panic_log_in_isolated_profile() { - let temp = std::path::PathBuf::from("temp"); - assert_eq!(panic_log_path_with(|_| Some("isolated".into()), temp.clone()), std::path::PathBuf::from("isolated/lightcraft-panics.log")); - assert_eq!(panic_log_path_with(|_| None, temp.clone()), temp.join("lightcraft-panics.log")); - assert_eq!(panic_log_path_with(|_| Some("".into()), temp.clone()), temp.join("lightcraft-panics.log")); + fn panic_log_lives_in_the_settings_folder() { + let settings = || Some(std::path::PathBuf::from("settings")); + assert_eq!(panic_log_path_with(false, false, settings), Some(std::path::Path::new("settings").join("lightcraft-panics.log"))); + assert_eq!(panic_log_path_with(false, false, || None), None); + let unasked = || -> Option { panic!("the settings folder was looked up") }; + assert_eq!(panic_log_path_with(false, true, unasked), None); + assert_eq!(panic_log_path_with(true, false, unasked), None); + } + + /// #2572: a panic is kept in `lightcraft-panics.log` in the settings folder, never in the system + /// temp folder (shared by every user on Linux and FreeBSD), and a `--memory` session keeps it + /// nowhere. The hook is process-wide, so the panic happens in a child (this test binary again) + /// with its own temp and home folders and no `LIGHTCRAFT_CONFIG_DIR`. + #[test] + fn a_panic_is_kept_in_the_settings_folder_not_the_temp_folder() { + if let Some(mode) = std::env::var_os("LIGHTCRAFT_TEST_PANIC_LOG") { + let settings = config_dir().unwrap(); + std::fs::create_dir_all(&settings).unwrap(); + println!("settings folder {}", settings.display()); + install_panic_hooks(None, mode == "memory"); + assert!(std::thread::spawn(|| panic!("lc-2572 probe")).join().is_err()); + return; + } + let scratch = std::env::temp_dir().join(format!("lightcraft-panic-log-{}", std::process::id())); + for memory in [false, true] { + let _ = std::fs::remove_dir_all(&scratch); + let (temp, home) = (scratch.join("temp"), scratch.join("home")); + std::fs::create_dir_all(&temp).unwrap(); + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "config_path_tests::a_panic_is_kept_in_the_settings_folder_not_the_temp_folder", "--nocapture"]) + .env("LIGHTCRAFT_TEST_PANIC_LOG", if memory { "memory" } else { "1" }) + .env_remove("LIGHTCRAFT_CONFIG_DIR") + .env_remove("LIGHTCRAFT_NO_PREFS") + .env("TMPDIR", &temp) + .env("TMP", &temp) + .env("TEMP", &temp) + .env("HOME", &home) + .env("XDG_CONFIG_HOME", home.join(".config")) + .env("APPDATA", home.join("AppData")) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "{stdout}{}", String::from_utf8_lossy(&out.stderr)); + // Anywhere in a line: with one test thread (`RUST_TEST_THREADS=1`, as `xtask ci` sets on a + // small machine) libtest prints the test's name first, on the same line. + let settings = stdout.lines().find_map(|l| l.split_once("settings folder ").map(|(_, p)| p)).expect("the child didn't run the test"); + let kept = std::fs::read_to_string(std::path::Path::new(settings).join("lightcraft-panics.log")).unwrap_or_default(); + assert_eq!(kept.contains("lc-2572 probe"), !memory, "--memory {memory}: {kept:?} in {settings}"); + assert!(!temp.join("lightcraft-panics.log").exists(), "--memory {memory}: the panic was kept in the temp folder"); + } + let _ = std::fs::remove_dir_all(&scratch); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dd41bcdb81..673e82da48 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -45,7 +45,8 @@ mode ([mcp.md](mcp.md)) is a thin layer over this channel. Implementation: Set `LIGHTCRAFT_CONFIG_DIR` to a fresh directory to isolate UI preferences, app logs, the emergency panic log, the GPU initialization marker, camera profiles and default model folders. The nonempty value is used as the complete settings directory. Unset retains the normal platform paths; an explicit -empty value disables the settings directory, while the emergency panic log retains its system-temp path. +empty value disables the settings directory, and with it the emergency panic log (panics then go to +standard error only). Explicit model-directory environment variables still take precedence over their defaults. Also pass `--library DIR` with a separate scratch library: the configuration override does not change the default photo-library location. Do not use `--memory` or `LIGHTCRAFT_NO_PREFS` when testing persistence. diff --git a/docs/whats-new.md b/docs/whats-new.md index cffff83e2b..4da20ae1bd 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,14 @@ # What's new in LightCraft +## 2026-10-22 + +### The crash log moved to the settings folder +- The desktop app keeps `lightcraft-panics.log` in its settings folder now, next to `logs/`, instead of the system + temp folder (issue #2572). On Linux and FreeBSD every user shares that folder, so someone else could create the + file first to read what LightCraft wrote there, or plant a link that made it write into another file. A `--memory` + session, `LIGHTCRAFT_NO_PREFS` and an empty `LIGHTCRAFT_CONFIG_DIR` keep no crash log; panics still go to standard + error. + ## 2026-10-21 ### Sharper resampling in HDR and panorama merges From bb6864066459c0fa56d9dba05e328e5611f2c721 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:40:17 +0100 Subject: [PATCH 2/5] Review: ignore an empty or relative HOME, APPDATA or XDG_CONFIG_HOME for the settings folder (#2572) --- crates/engine/src/config.rs | 50 ++++++++++++++++++++++++++++++++----- docs/whats-new.md | 3 +++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index b3ded1fbd7..efdd4afa2a 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -8,7 +8,9 @@ //! `%APPDATA%`. If that folder can't be written (read-only medium, Program Files), a warning is logged //! and the platform folder is used. //! 3. The platform convention: macOS `~/Library/Application Support/LightCraft`, Windows -//! `%APPDATA%\LightCraft`, Linux `$XDG_CONFIG_HOME/lightcraft` or `~/.config/lightcraft`. +//! `%APPDATA%\LightCraft`, Linux `$XDG_CONFIG_HOME/lightcraft` or `~/.config/lightcraft`. An empty or +//! relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` is ignored, so the folder is never under the launch +//! directory; with no usable one there is no settings folder. //! //! Hosts that have a file system (the desktop app, the CLI, the MCP server) share these defaults so a model //! installed from one is there for the others. Nothing here is applied automatically: a [`Session`] has no @@ -48,6 +50,9 @@ pub fn config_dir() -> Option { } /// `portable` is asked only without an override, so an isolated run never probes beside the executable. +/// An empty or relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` is ignored (an unusable `XDG_CONFIG_HOME` +/// gives way to `HOME`): it would put the settings folder, and the logs and crash log in it, under +/// whatever directory LightCraft was started in (issue #2572). fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, portable: impl FnOnce() -> Option) -> Option { if let Some(dir) = env("LIGHTCRAFT_CONFIG_DIR") { return (!dir.is_empty()).then(|| PathBuf::from(dir)); @@ -55,12 +60,12 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, p if let Some(dir) = portable() { return Some(dir); } + // Only a rooted folder: an empty or relative one would be under the launch directory (#2572). + let folder = |name: &str| env(name).map(PathBuf::from).filter(|dir| dir.has_root()); match platform { - Platform::Mac => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/LightCraft")), - Platform::Windows => env("APPDATA").map(|a| PathBuf::from(a).join("LightCraft")), - Platform::Other => { - env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("lightcraft")) - } + Platform::Mac => folder("HOME").map(|h| h.join("Library/Application Support/LightCraft")), + Platform::Windows => folder("APPDATA").map(|a| a.join("LightCraft")), + Platform::Other => folder("XDG_CONFIG_HOME").or_else(|| folder("HOME").map(|h| h.join(".config"))).map(|c| c.join("lightcraft")), } } @@ -253,6 +258,39 @@ mod config_tests { } } + /// #2572 review: an empty or relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` would put the settings + /// folder (and the crash log and logs in it) under the launch directory, where another user could + /// have planted the folder and a link. Such a value is ignored: an unusable `XDG_CONFIG_HOME` falls + /// back to `HOME`, and with neither usable there is no settings folder. + #[test] + fn config_ignores_empty_or_relative_platform_folders() { + for bad in ["", "relative", "./here", "../up"] { + assert_eq!(resolve(Platform::Mac, &[("HOME", bad)]), None, "HOME={bad:?}"); + assert_eq!(resolve(Platform::Other, &[("HOME", bad)]), None, "HOME={bad:?}"); + assert_eq!(resolve(Platform::Windows, &[("APPDATA", bad), ("HOME", "/user")]), None, "APPDATA={bad:?}"); + assert_eq!(resolve(Platform::Other, &[("XDG_CONFIG_HOME", bad)]), None, "XDG_CONFIG_HOME={bad:?}"); + assert_eq!(resolve(Platform::Other, &[("XDG_CONFIG_HOME", bad), ("HOME", bad)]), None, "both {bad:?}"); + assert_eq!( + resolve(Platform::Other, &[("XDG_CONFIG_HOME", bad), ("HOME", "/user")]), + Some(PathBuf::from("/user/.config/lightcraft")), + "XDG_CONFIG_HOME={bad:?} falls back to HOME" + ); + assert_eq!( + resolve(Platform::Other, &[("XDG_CONFIG_HOME", "/xdg"), ("HOME", bad)]), + Some(PathBuf::from("/xdg/lightcraft")), + "a usable XDG_CONFIG_HOME doesn't need HOME" + ); + } + } + + /// The explicit profile keeps its own policy: a relative `LIGHTCRAFT_CONFIG_DIR` is the user's choice. + #[test] + fn config_override_may_still_be_relative() { + for platform in [Platform::Mac, Platform::Windows, Platform::Other] { + assert_eq!(resolve(platform, &[("LIGHTCRAFT_CONFIG_DIR", "isolated"), ("HOME", "")]), Some(PathBuf::from("isolated"))); + } + } + #[cfg(unix)] #[test] fn config_override_preserves_non_unicode_paths() { diff --git a/docs/whats-new.md b/docs/whats-new.md index f7eaf1f436..dd71269062 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -90,6 +90,9 @@ file first to read what LightCraft wrote there, or plant a link that made it write into another file. A `--memory` session, `LIGHTCRAFT_NO_PREFS` and an empty `LIGHTCRAFT_CONFIG_DIR` keep no crash log; panics still go to standard error. +- An empty or relative `HOME`, `APPDATA` or `XDG_CONFIG_HOME` no longer puts the settings folder (and the crash log + and logs in it) under the folder LightCraft was started from: it is ignored (`XDG_CONFIG_HOME` then gives way to + `HOME`), and with no usable one there is no settings folder: panics then go to standard error only. ### Reliability - Opening a library no longer writes through a link left at the lock's owner note (`catalog.lock.owner`): the link From d1d55c4a2d18c1abc45a613af0ac84aa7dea388d Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:26:19 +0100 Subject: [PATCH 3/5] Review: on Windows the settings folder needs a fully qualified APPDATA (#2572) A rooted but drive-relative APPDATA such as \foo or /foo, or C:foo, follows the current drive or its current folder, so the launch drive could still choose where the settings folder and crash log go. APPDATA must now be a drive path like C:\... or a UNC or device path; HOME and XDG_CONFIG_HOME must start with /. The check follows each platform's rules rather than the host's, and the Windows tests use real Windows paths. --- crates/engine/src/config.rs | 43 +++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index efdd4afa2a..116a886824 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -17,7 +17,7 @@ //! face-, denoise- or SAM 3 model folder until a host asks for one ([`Session::with_default_face_models`], //! [`Session::with_default_denoise_models`], [`Session::with_default_sam3_model`]), so tests stay hermetic. -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::sync::OnceLock; @@ -60,8 +60,9 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, p if let Some(dir) = portable() { return Some(dir); } - // Only a rooted folder: an empty or relative one would be under the launch directory (#2572). - let folder = |name: &str| env(name).map(PathBuf::from).filter(|dir| dir.has_root()); + // Only a fully qualified folder: an empty or relative one would be under the launch directory, + // and on Windows `\foo` or `C:foo` would follow the current drive or its folder (#2572). + let folder = |name: &str| env(name).filter(|dir| fully_qualified(platform, dir)).map(PathBuf::from); match platform { Platform::Mac => folder("HOME").map(|h| h.join("Library/Application Support/LightCraft")), Platform::Windows => folder("APPDATA").map(|a| a.join("LightCraft")), @@ -69,6 +70,23 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, p } } +/// Whether `dir` names one folder whatever the current drive and directory, by `platform`'s rules +/// rather than the host's, so each arm is tested the same on every host: on Windows a drive path +/// (`C:\…`) or a UNC or device path (`\\server\share`, `\\?\…`), elsewhere a path from `/`. +fn fully_qualified(platform: Platform, dir: &OsStr) -> bool { + let text = dir.to_string_lossy(); + let b = text.as_bytes(); + let sep = |c: &u8| *c == b'\\' || *c == b'/'; + match platform { + Platform::Windows => match (b.first(), b.get(1), b.get(2)) { + (Some(drive), Some(b':'), Some(c)) => drive.is_ascii_alphabetic() && sep(c), + (Some(a), Some(c), Some(d)) => sep(a) && sep(c) && !sep(d), + _ => false, + }, + Platform::Mac | Platform::Other => b.first() == Some(&b'/'), + } +} + /// This process's portable data folder, if a marker sits beside its executable and the folder can be /// written. Resolved once: the check creates the folder and writes a probe file. fn portable_dir() -> Option { @@ -197,7 +215,8 @@ mod config_tests { assert!(data.is_dir()); assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0, "the write probe is removed"); let found = portable_dir_in(&exe).unwrap(); - let actual = config_dir_with(Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from("/roaming")), || found); + let actual = + config_dir_with(Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from(r"C:\Users\me\AppData\Roaming")), || found); assert_eq!(actual, Some(data)); let _ = std::fs::remove_dir_all(&exe); } @@ -248,9 +267,9 @@ mod config_tests { #[test] fn config_unset_override_keeps_platform_defaults() { - let vars = [("HOME", "/user"), ("APPDATA", "/roaming"), ("XDG_CONFIG_HOME", "/xdg")]; + let vars = [("HOME", "/user"), ("APPDATA", r"C:\Users\me\AppData\Roaming"), ("XDG_CONFIG_HOME", "/xdg")]; assert_eq!(resolve(Platform::Mac, &vars), Some(PathBuf::from("/user/Library/Application Support/LightCraft"))); - assert_eq!(resolve(Platform::Windows, &vars), Some(PathBuf::from("/roaming/LightCraft"))); + assert_eq!(resolve(Platform::Windows, &vars), Some(PathBuf::from(r"C:\Users\me\AppData\Roaming").join("LightCraft"))); assert_eq!(resolve(Platform::Other, &vars), Some(PathBuf::from("/xdg/lightcraft"))); assert_eq!(resolve(Platform::Other, &[("HOME", "/user")]), Some(PathBuf::from("/user/.config/lightcraft"))); for platform in [Platform::Mac, Platform::Windows, Platform::Other] { @@ -283,6 +302,18 @@ mod config_tests { } } + /// #2572 review: on Windows `APPDATA` must be fully qualified. `\foo` and `/foo` follow the current + /// drive and `C:foo` that drive's current folder, so the launch drive could choose the folder. + #[test] + fn windows_appdata_must_be_fully_qualified() { + for good in [r"C:\Users\me\AppData\Roaming", "D:/Data", r"\\server\share\Roaming", r"\\?\C:\Users\me\AppData\Roaming"] { + assert_eq!(resolve(Platform::Windows, &[("APPDATA", good)]), Some(PathBuf::from(good).join("LightCraft")), "APPDATA={good:?}"); + } + for bad in [r"\foo", "/roaming", "C:foo", "C:", "c", r"\\"] { + assert_eq!(resolve(Platform::Windows, &[("APPDATA", bad)]), None, "APPDATA={bad:?}"); + } + } + /// The explicit profile keeps its own policy: a relative `LIGHTCRAFT_CONFIG_DIR` is the user's choice. #[test] fn config_override_may_still_be_relative() { From c28824a72be96495ae8f674cf28c7127ebc34b49 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:51:37 +0100 Subject: [PATCH 4/5] Crash log: main's Nightly profile comes through the settings folder; a Windows test path is fully qualified --- crates/engine/src/config.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index 57bfe99ef2..c5ed4c6ad4 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -331,8 +331,8 @@ mod config_tests { assert_eq!(actual, Some(root.join("Settings"))); } assert_eq!( - config_dir_from(None, Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from("/roaming")), || None), - Some(PathBuf::from("/roaming/LightCraft")) + config_dir_from(None, Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from(r"C:\Roaming")), || None), + Some(PathBuf::from(r"C:\Roaming").join("LightCraft")) ); } From 0f1cc4fdc79af02fa84d60db88e5019e5fadb4c5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:20:26 +0100 Subject: [PATCH 5/5] Prepare the selected settings directory before crash logging --- apps/lightcraft/src/launch.rs | 118 +++++++++++++++++++++++++--------- 1 file changed, 88 insertions(+), 30 deletions(-) diff --git a/apps/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index b5dfed3fc5..81f3dca90b 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -123,10 +123,24 @@ fn panic_log_path_with(in_memory: bool, no_prefs: bool, config: impl FnOnce() -> config().map(|d| d.join("lightcraft-panics.log")) } +/// Prepare only the selected settings directory before installing the emergency hook. A new profile +/// may not have reached the normal logger yet; if preparation fails, keep the stderr fallback. +fn prepare_panic_log(path: std::path::PathBuf) -> Option { + let mut dirs = std::fs::DirBuilder::new(); + dirs.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + dirs.mode(0o700); + } + dirs.create(path.parent()?).ok()?; + Some(path) +} + /// The panic hooks: the engine guard's (standard error, and the crash log when there is one), then /// the log file's. pub(crate) fn install_panic_hooks(logger: Option<&'static super::logging::AppLogger>, in_memory: bool) { - if let Some(path) = panic_log_path(in_memory) { + if let Some(path) = panic_log_path(in_memory).and_then(prepare_panic_log) { lightcraft_engine::guard::install_hook(path); } if let Some(logger) = logger { @@ -197,47 +211,91 @@ mod config_path_tests { assert_eq!(panic_log_path_with(true, false, unasked), None); } - /// #2572: a panic is kept in `lightcraft-panics.log` in the settings folder, never in the system - /// temp folder (shared by every user on Linux and FreeBSD), and a `--memory` session keeps it - /// nowhere. The hook is process-wide, so the panic happens in a child (this test binary again) - /// with its own temp and home folders and no `LIGHTCRAFT_CONFIG_DIR`. + /// The emergency hook works before the logger creates a new profile's directory, but leaves + /// no files or settings directory in no-persistence modes. A child isolates the panic hook + /// and active profile; both possible settings paths and the temp directory are synthetic. #[test] fn a_panic_is_kept_in_the_settings_folder_not_the_temp_folder() { - if let Some(mode) = std::env::var_os("LIGHTCRAFT_TEST_PANIC_LOG") { - let settings = config_dir().unwrap(); - std::fs::create_dir_all(&settings).unwrap(); - println!("settings folder {}", settings.display()); + if let Ok(mode) = std::env::var("LIGHTCRAFT_TEST_PANIC_LOG") { + let root = std::path::PathBuf::from(std::env::var_os("LIGHTCRAFT_TEST_PANIC_ROOT").unwrap()); + let settings = if mode == "nightly" { + let profile = root.join("nightly"); + let settings = profile.join("Settings"); + lightcraft_engine::config::set_profile_root(profile).unwrap(); + settings + } else { + root.join("settings") + }; + assert_eq!(config_dir(), Some(settings.clone())); + assert!(!settings.exists(), "the logger has not initialized these settings"); + if mode == "existing" { + std::fs::create_dir(&settings).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&settings, std::fs::Permissions::from_mode(0o750)).unwrap(); + } + } + #[cfg(unix)] + let before = if mode == "existing" { + use std::os::unix::fs::PermissionsExt; + Some(std::fs::metadata(&settings).unwrap().permissions().mode()) + } else { + None + }; + install_panic_hooks(None, mode == "memory"); + let persists = mode != "memory" && mode != "no-prefs"; + if persists { + assert!(settings.is_dir(), "{mode}: settings directory was not prepared"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let after = std::fs::metadata(&settings).unwrap().permissions().mode(); + if let Some(before) = before { + assert_eq!(after, before, "existing settings permissions were changed"); + } else { + assert_eq!(after & 0o077, 0, "{mode}: fresh settings directory is not private"); + } + } + } else { + assert!(!settings.exists(), "{mode}: settings directory was created by startup"); + } assert!(std::thread::spawn(|| panic!("lc-2572 probe")).join().is_err()); + let kept = std::fs::read_to_string(settings.join("lightcraft-panics.log")).unwrap_or_default(); + assert_eq!(kept.contains("lc-2572 probe"), persists, "{mode}: {kept:?}"); + if !persists { + assert!(!settings.exists(), "{mode}: the hook created a settings directory"); + } + assert!(!root.join("temp/lightcraft-panics.log").exists(), "{mode}: crash log fell back to temp"); + if mode == "nightly" { + assert!(!root.join("settings").exists(), "Nightly did not initialize the other profile"); + } return; } + let scratch = std::env::temp_dir().join(format!("lightcraft-panic-log-{}", std::process::id())); - for memory in [false, true] { - let _ = std::fs::remove_dir_all(&scratch); - let (temp, home) = (scratch.join("temp"), scratch.join("home")); + std::fs::create_dir(&scratch).unwrap(); + for mode in ["first-run", "nightly", "existing", "memory", "no-prefs"] { + let root = scratch.join(mode); + let temp = root.join("temp"); std::fs::create_dir_all(&temp).unwrap(); - let out = std::process::Command::new(std::env::current_exe().unwrap()) + let mut child = std::process::Command::new(std::env::current_exe().unwrap()); + child .args(["--exact", "launch::config_path_tests::a_panic_is_kept_in_the_settings_folder_not_the_temp_folder", "--nocapture"]) - .env("LIGHTCRAFT_TEST_PANIC_LOG", if memory { "memory" } else { "1" }) - .env_remove("LIGHTCRAFT_CONFIG_DIR") + .env("LIGHTCRAFT_TEST_PANIC_LOG", mode) + .env("LIGHTCRAFT_TEST_PANIC_ROOT", &root) + .env("LIGHTCRAFT_CONFIG_DIR", root.join("settings")) .env_remove("LIGHTCRAFT_NO_PREFS") .env("TMPDIR", &temp) .env("TMP", &temp) - .env("TEMP", &temp) - .env("HOME", &home) - .env("XDG_CONFIG_HOME", home.join(".config")) - .env("APPDATA", home.join("AppData")) - .output() - .unwrap(); - let stdout = String::from_utf8_lossy(&out.stdout); - assert!(out.status.success(), "{stdout}{}", String::from_utf8_lossy(&out.stderr)); - // Anywhere in a line: with one test thread (`RUST_TEST_THREADS=1`, as `xtask ci` sets on a - // small machine) libtest prints the test's name first, on the same line. - let settings = stdout.lines().find_map(|l| l.split_once("settings folder ").map(|(_, p)| p)).expect("the child didn't run the test"); - let kept = std::fs::read_to_string(std::path::Path::new(settings).join("lightcraft-panics.log")).unwrap_or_default(); - assert_eq!(kept.contains("lc-2572 probe"), !memory, "--memory {memory}: {kept:?} in {settings}"); - assert!(!temp.join("lightcraft-panics.log").exists(), "--memory {memory}: the panic was kept in the temp folder"); + .env("TEMP", &temp); + if mode == "no-prefs" { + child.env("LIGHTCRAFT_NO_PREFS", "1"); + } + let out = child.output().unwrap(); + assert!(out.status.success(), "{mode}: {}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); } - let _ = std::fs::remove_dir_all(&scratch); + std::fs::remove_dir_all(&scratch).unwrap(); } }