From 564fca9001ce3282ecfc5ce7a7a959e76b5fb63a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 15 Oct 2026 23:03:24 +0200 Subject: [PATCH] feat: initialize missing managed profiles Create a valid empty default profile and active pointer on first managed launch, or recreate only the missing profile named by an existing valid pointer. Preserve explicit-path failures and existing malformed files. Tests: cargo test -p fader_master managed_startup_; cargo test -p fader-config --test schema --test persistence; cargo fmt --all -- --check --- README.md | 6 ++ architecture.md | 6 ++ config/src/document.rs | 16 +++++ fader_master/src/application.rs | 111 ++++++++++++++++++++++++++++---- task.md | 4 ++ 5 files changed, 129 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index ffeb3ac..2c3157b 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,12 @@ cargo run --locked -p fader_master --bin fader_master_client The compatible `fader_master serve` and `fader_master tui` subcommands remain available for scripts and existing workflows. +On the first combined or server launch without `--config`, fader_master creates +a valid empty `default` profile and active-profile selection. If an existing +active selection names a missing managed profile, that empty profile is created +with the selected ID. Explicit missing `--config` paths still fail, preventing a +mistyped path from silently creating a file. + The mixer arrow keys follow its orientation. In Vertical mode, use Up/Down to select a configured fader or separator and Left/Right to change its volume. In Horizontal mode, use Left/Right to select and Up/Down to change volume. J/K diff --git a/architecture.md b/architecture.md index 37c6792..b90a15d 100644 --- a/architecture.md +++ b/architecture.md @@ -222,6 +222,12 @@ All durable application data is TOML: profiles, device profiles/bindings, active - `~/.config/fader_master/devices/.toml`: reusable MIDI output/input protocol profiles when needed. - `~/.local/state/fader_master/state.toml`: schema version, per-profile confirmed object/channel state and separately validated desired object volume/mute, remembered assignments, last selected UI view. No ephemeral backend handles or pending operation IDs; cached observations are marked stale until refreshed. Desired values may include commands issued offline, but are applied after restart only under explicit restore policy. +When no explicit profile path is supplied, a missing active selection creates a +minimal `default` profile before atomically publishing its active pointer. A +missing profile named by an existing valid active pointer is initialized with +that stable ID. Existing files, malformed selections, and explicit missing +paths are never overwritten by this first-run recovery. + The following profile is parsed and semantically validated by an automated test and mirrored at `examples/profiles/desktop.toml`. Sample application and MIDI names must still be selected from actual discovery. CLI overrides apply for the diff --git a/config/src/document.rs b/config/src/document.rs index 25f9387..44094dc 100644 --- a/config/src/document.rs +++ b/config/src/document.rs @@ -28,6 +28,22 @@ pub struct ProfileDocument { } impl ProfileDocument { + /// Builds a valid profile with no configured objects or MIDI surfaces. + pub fn empty(id: &str) -> Result { + Self::parse(&format!( + r#"schema_version = 1 +id = {id:?} +startup = "adopt" +new_stream = "adopt" + +[audio] +adapter = "auto" +preference = ["pulse", "pipewire"] +max_gain = 1.0 +"# + )) + } + /// Parses both the editable TOML representation and semantic profile. pub fn parse(input: &str) -> Result { Profile::parse(input)?; diff --git a/fader_master/src/application.rs b/fader_master/src/application.rs index 07c5a44..376d24e 100644 --- a/fader_master/src/application.rs +++ b/fader_master/src/application.rs @@ -10,7 +10,7 @@ use std::{ }; use anyhow::{Context, Result, bail}; -use fader_config::{ActiveConfig, Profile, ProfileDocument, XdgEnvironment, XdgPaths}; +use fader_config::{ActiveConfig, AtomicFile, Profile, ProfileDocument, XdgEnvironment, XdgPaths}; use fader_core::Gain; use midi::{LinuxIdentityCatalog, MidiInputCatalog}; use volume_lib::{AudioBackend, CompiledAdapterProbe, TargetRequirements, select_adapter}; @@ -168,6 +168,52 @@ fn load_profile_document(path: &Path) -> Result { ProfileDocument::parse(&input).with_context(|| format!("profile {} is invalid", path.display())) } +fn resolve_managed_profile(paths: &XdgPaths) -> Result { + const DEFAULT_PROFILE: &str = "default"; + + paths + .create_layout() + .context("could not initialize the fader_master configuration directories")?; + let active = match fs::read_to_string(paths.config_file()) { + Ok(source) => { + ActiveConfig::parse(&source).context("active profile selection is invalid")? + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let active = ActiveConfig::new(DEFAULT_PROFILE)?; + let profile_path = paths.profile_file(DEFAULT_PROFILE)?; + initialize_missing_profile(&profile_path, DEFAULT_PROFILE)?; + AtomicFile::write(&paths.config_file(), active.to_toml()?.as_bytes()) + .context("could not initialize the active profile selection")?; + active + } + Err(error) => { + return Err(error).with_context(|| { + format!( + "--config was omitted and active selection {} could not be read", + paths.config_file().display() + ) + }); + } + }; + let profile_path = paths.profile_file(active.active_profile().as_str())?; + initialize_missing_profile(&profile_path, active.active_profile().as_str())?; + Ok(profile_path) +} + +fn initialize_missing_profile(path: &Path, id: &str) -> Result<()> { + match fs::symlink_metadata(path) { + Ok(_) => return Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error) + .with_context(|| format!("could not inspect profile {}", path.display())); + } + } + let source = ProfileDocument::empty(id)?.finish()?; + AtomicFile::write(path, source.as_bytes()) + .with_context(|| format!("could not initialize empty profile {}", path.display())) +} + fn build_server( config: Option<&Path>, override_choice: Option, @@ -177,17 +223,7 @@ fn build_server( let paths = XdgPaths::resolve(&environment)?; let config = match config { Some(path) => path.to_owned(), - None => { - let active_source = fs::read_to_string(paths.config_file()).with_context(|| { - format!( - "--config was omitted and active selection {} could not be read", - paths.config_file().display() - ) - })?; - let active = ActiveConfig::parse(&active_source) - .context("active profile selection is invalid")?; - paths.profile_file(active.active_profile().as_str())? - } + None => resolve_managed_profile(&paths)?, }; let document = load_profile_document(&config)?; let profile = document.preview()?; @@ -325,9 +361,12 @@ fn devices() -> Result<()> { #[cfg(test)] mod tests { - use std::cell::Cell; + use std::{cell::Cell, fs}; - use super::start_if_missing; + use fader_config::{ActiveConfig, ProfileDocument, XdgEnvironment, XdgPaths}; + use tempfile::tempdir; + + use super::{resolve_managed_profile, start_if_missing}; #[test] fn combined_mode_only_starts_a_server_when_probe_did_not_find_one() { @@ -348,4 +387,48 @@ mod tests { assert_eq!(started, Some("started")); assert_eq!(starts.get(), 1); } + + #[test] + fn managed_startup_initializes_missing_active_selection_and_profile() { + let root = tempdir().unwrap(); + let paths = XdgPaths::resolve(&XdgEnvironment { + home: root.path().join("home"), + config_home: Some(root.path().join("config")), + state_home: Some(root.path().join("state")), + runtime_dir: Some(root.path().join("runtime")), + }) + .unwrap(); + + let profile_path = resolve_managed_profile(&paths).unwrap(); + + assert_eq!(profile_path, paths.profile_file("default").unwrap()); + let active = + ActiveConfig::parse(&fs::read_to_string(paths.config_file()).unwrap()).unwrap(); + assert_eq!(active.active_profile().as_str(), "default"); + let document = ProfileDocument::parse(&fs::read_to_string(&profile_path).unwrap()).unwrap(); + let profile = document.preview().unwrap(); + assert_eq!(profile.id().as_str(), "default"); + assert!(profile.faders().is_empty()); + } + + #[test] + fn managed_startup_recreates_only_a_missing_selected_profile() { + let root = tempdir().unwrap(); + let paths = XdgPaths::resolve(&XdgEnvironment { + home: root.path().join("home"), + config_home: Some(root.path().join("config")), + state_home: Some(root.path().join("state")), + runtime_dir: Some(root.path().join("runtime")), + }) + .unwrap(); + paths.create_layout().unwrap(); + let active = ActiveConfig::new("arch-pipewire").unwrap(); + fs::write(paths.config_file(), active.to_toml().unwrap()).unwrap(); + + let profile_path = resolve_managed_profile(&paths).unwrap(); + + assert_eq!(profile_path, paths.profile_file("arch-pipewire").unwrap()); + let document = ProfileDocument::parse(&fs::read_to_string(&profile_path).unwrap()).unwrap(); + assert_eq!(document.preview().unwrap().id().as_str(), "arch-pipewire"); + } } diff --git a/task.md b/task.md index cf54b61..a9b6fe5 100644 --- a/task.md +++ b/task.md @@ -461,6 +461,10 @@ Dependencies: all required feature milestones; hardware-only ALSA remains an exp - [ ] **M12.1 Adversarial replay:** deterministic reconnect/churn/write-failure/echo/reordered-event/profile-switch scenarios. Property tests preserve domain invariants; command storms stay bounded and converge without starving mute or shutdown. - [ ] **M12.2 Integration matrix:** PulseAudio, pipewire-pulse, native PipeWire, two controllers, external desktop mixer, reload/restart, read-only/full state directory. Record fixtures, supported device profiles and known limitations; never run destructive audio tests on the user's current session by default. - [ ] **M12.3 Packaging:** example TOML profiles, schema/migration documentation, build/install guide, optional systemd user unit and troubleshooting. Acceptance: fresh user install can discover, bind, edit, save, restart and reconnect without root or manual state repair. + Managed startup now initializes a valid empty `default` profile and active + pointer on first run, and recreates only a missing profile referenced by a + valid existing pointer. Explicit paths and malformed existing files remain + errors rather than being overwritten. - [ ] **M12.4 Release gates:** all workspace/default/feature/MSRV checks, reproducible lockfile, license review and dependency advisory review using maintained tooling selected at implementation time. Measure/control latency under multi-surface load and publish the tested envelope. ## User requirement coverage