feat(M10.3): persist active profile selection

Test: cargo test -p fader_master --all-targets --all-features

Test: cargo clippy -p fader_master --all-targets --all-features -- -D warnings
This commit is contained in:
Dandaedre 2026-10-15 04:28:35 +02:00
parent 1129cc9730
commit d028cf26f0
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
11 changed files with 142 additions and 19 deletions

View File

@ -342,6 +342,12 @@ for retry after readback/reconciliation rather than publishing over in-flight
native work. The committed mapping generation advances the public mixer revision,
invalidating commands created from the prior profile.
The active pointer is a strict versioned TOML document containing one validated
profile ID. A successful runtime switch writes it atomically after activation.
Failure does not roll back the running generation, but marks the selection
unsaved; startup without `--config` accepts only this pointer and never guesses
another profile when it is absent or corrupt.
## CLI, IPC, and TUI
Plan `fader_master serve`, `tui`, `validate --config PATH`, `devices`, `status`, and `profile switch ID`. Run one server per user/runtime namespace with an owned Unix socket and lock; TUI disconnect must not stop MIDI control. No network listener. Bound IPC message size and queue sizes, enforce socket permissions/peer identity, negotiate protocol version, use request IDs and revisioned snapshots, and resnapshot after missed deltas. Length-prefixed UTF-8 TOML messages reuse Serde schemas initially; cap frames before allocation.

View File

@ -17,7 +17,7 @@ pub enum Command {
Serve {
/// Validated profile to activate.
#[arg(long)]
config: PathBuf,
config: Option<PathBuf>,
/// Session-only audio backend override.
#[arg(long, value_enum)]
audio: Option<AudioArgument>,

View File

@ -160,6 +160,7 @@ pub struct ConfigurationSnapshot {
pub revision: u64,
pub dirty: bool,
pub applied_revision: u64,
pub selection_saved: bool,
pub learning: Option<String>,
pub error: Option<String>,
pub profile_id: String,

View File

@ -108,6 +108,7 @@ pub(crate) fn configuration_snapshot(
revision,
dirty,
applied_revision,
selection_saved: true,
learning: None,
error: None,
profile_id: profile.id().to_string(),

View File

@ -180,6 +180,7 @@ pub struct LocalServer {
configuration: ConfigurationEditor,
applied_configuration_revision: u64,
profile_directory: PathBuf,
active_config_path: PathBuf,
}
impl LocalServer {
@ -188,6 +189,7 @@ impl LocalServer {
write_ceiling: Gain,
document: ProfileDocument,
profile_path: PathBuf,
active_config_path: PathBuf,
) -> Result<Self, LocalError> {
let profile = document.preview()?;
let midi =
@ -217,6 +219,7 @@ impl LocalServer {
configuration: ConfigurationEditor::new(document, profile_path),
applied_configuration_revision: 0,
profile_directory,
active_config_path,
})
}
@ -499,7 +502,29 @@ impl LocalServer {
self.midi = midi;
self.configuration = ConfigurationEditor::new(document, path);
self.applied_configuration_revision = 0;
self.publish_configuration(&profile, None);
let persistence_error = (|| {
let active = fader_config::ActiveConfig::new(profile.id().as_str())?;
let encoded = active.to_toml()?;
fader_config::AtomicFile::write(
&self.active_config_path,
encoded.as_bytes(),
)
.map_err(|error| {
fader_config::ConfigError::Validation {
path: "active_profile".to_owned(),
message: error.to_string(),
}
})?;
Ok::<(), fader_config::ConfigError>(())
})()
.err()
.map(|error| error.to_string());
self.publish_configuration(&profile, persistence_error.clone());
if persistence_error.is_some() {
let mut configuration = self.mixer.snapshot().configuration;
configuration.selection_saved = false;
self.mixer.set_configuration(configuration);
}
self.mixer.request(ClientRequest {
version: request.version,
request_id,
@ -644,7 +669,7 @@ fn remove_stale_socket(path: &Path) -> Result<(), LocalError> {
#[cfg(test)]
mod tests {
use std::{fs, time::Instant};
use std::{fs, os::unix::fs::PermissionsExt, time::Instant};
use super::*;
use crate::ipc::RequestCommand;
@ -688,6 +713,7 @@ mod tests {
Gain::UNITY,
ProfileDocument::parse(source).unwrap(),
active_path,
root.path().join("config.toml"),
)
.unwrap();
@ -721,6 +747,31 @@ mod tests {
assert_eq!(snapshot.configuration.profile_id, "secondary");
assert_eq!(snapshot.objects[0].label, "Listening");
assert!(snapshot.revision > old_revision);
let active = fader_config::ActiveConfig::parse(
&fs::read_to_string(root.path().join("config.toml")).unwrap(),
)
.unwrap();
assert_eq!(active.active_profile().as_str(), "secondary");
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o500)).unwrap();
let response = direct_request(
&mut server,
RequestCommand::SwitchProfile {
id: "desktop".into(),
},
);
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
let ResponseResult::Snapshot { snapshot } = response.result else {
panic!("runtime activation should survive pointer save failure");
};
assert_eq!(snapshot.configuration.profile_id, "desktop");
assert!(!snapshot.configuration.selection_saved);
assert!(snapshot.configuration.error.is_some());
let durable = fader_config::ActiveConfig::parse(
&fs::read_to_string(root.path().join("config.toml")).unwrap(),
)
.unwrap();
assert_eq!(durable.active_profile().as_str(), "secondary");
}
fn direct_request(

View File

@ -2,7 +2,7 @@ use std::{fs, os::unix::fs::PermissionsExt, path::Path};
use anyhow::{Context, Result, bail};
use clap::Parser;
use fader_config::{Profile, ProfileDocument, XdgEnvironment, XdgPaths};
use fader_config::{ActiveConfig, Profile, ProfileDocument, XdgEnvironment, XdgPaths};
use fader_core::Gain;
use fader_master::{
audio_selection_policy,
@ -31,7 +31,7 @@ fn main() -> Result<()> {
audio,
socket,
} => serve(
&config,
config.as_deref(),
audio.map(|value| value.choice()),
socket.as_deref(),
),
@ -56,11 +56,28 @@ fn load_profile_document(path: &Path) -> Result<ProfileDocument> {
}
fn serve(
config: &Path,
config: Option<&Path>,
override_choice: Option<volume_lib::AdapterChoice>,
socket_override: Option<&Path>,
) -> Result<()> {
let document = load_profile_document(config)?;
let environment = XdgEnvironment::from_process()?;
let paths = XdgPaths::resolve(&environment)?;
paths.create_layout()?;
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())?
}
};
let document = load_profile_document(&config)?;
let profile = document.preview()?;
let policy = audio_selection_policy(&profile, override_choice)?;
let selected = select_adapter(
@ -77,12 +94,7 @@ fn serve(
prepare_private_parent(path)?;
path.to_owned()
}
None => {
let environment = XdgEnvironment::from_process()?;
let paths = XdgPaths::resolve(&environment)?;
paths.create_layout()?;
default_socket_path()?
}
None => default_socket_path()?,
};
println!(
"serving profile={} backend={} poll={}ms socket={}",
@ -95,7 +107,8 @@ fn serve(
socket,
Gain::new(profile.max_gain())?,
document,
config.to_owned(),
config,
paths.config_file(),
)?
.run()?;
Ok(())

View File

@ -93,6 +93,7 @@ impl IpcMixerClient {
revision: snapshot.configuration.revision,
dirty: snapshot.configuration.dirty,
applied_revision: snapshot.configuration.applied_revision,
selection_saved: snapshot.configuration.selection_saved,
learning: snapshot.configuration.learning,
error: snapshot.configuration.error,
profile_id: snapshot.configuration.profile_id,

View File

@ -12,8 +12,17 @@ fn every_planned_command_is_present_in_help() {
}
#[test]
fn serve_requires_a_config_and_parses_session_override() {
assert!(Cli::try_parse_from(["fader_master", "serve"]).is_err());
fn serve_accepts_durable_selection_or_config_and_parses_session_override() {
assert_eq!(
Cli::try_parse_from(["fader_master", "serve"])
.unwrap()
.command,
Command::Serve {
config: None,
audio: None,
socket: None,
}
);
assert_eq!(
Cli::try_parse_from([
"fader_master",
@ -26,7 +35,7 @@ fn serve_requires_a_config_and_parses_session_override() {
.unwrap()
.command,
Command::Serve {
config: PathBuf::from("profile.toml"),
config: Some(PathBuf::from("profile.toml")),
audio: Some(AudioArgument::Pulse),
socket: None,
}

View File

@ -23,3 +23,33 @@ fn invalid_serve_profile_fails_before_socket_or_audio_side_effects() {
assert!(!socket.parent().unwrap().exists());
assert!(String::from_utf8_lossy(&output.stderr).contains("profile"));
}
#[test]
fn corrupt_active_selection_cannot_silently_choose_a_profile() {
let directory = tempfile::tempdir().unwrap();
let home = directory.path().join("home");
let config_home = directory.path().join("config");
let state_home = directory.path().join("state");
let runtime = directory.path().join("runtime");
let app_config = config_home.join("fader_master");
fs::create_dir_all(&app_config).unwrap();
fs::write(
app_config.join("config.toml"),
"active_profile = '../escape'",
)
.unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_fader_master"))
.arg("serve")
.env("HOME", home)
.env("XDG_CONFIG_HOME", config_home)
.env("XDG_STATE_HOME", state_home)
.env("XDG_RUNTIME_DIR", runtime)
.output()
.unwrap();
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr).contains("active profile selection is invalid")
);
}

View File

@ -362,7 +362,11 @@ Dependencies: M9, M6, M7.
then publishes matching, groups, faders, pickup, and MIDI together. Activation
advances the mixer view revision so pre-switch client commands are stale.
- [ ] **M10.2 Restore/adopt policy:** default switch adopts live state; explicit restore uses saved object intents and deterministic overlap ordering. Tests: no surprise startup/switch write, restore limits enforced, offline/new members follow configured policy, pickup/feedback resync happens on every surface.
- [ ] **M10.3 Durable selection:** save active pointer after successful activation and reconcile state namespaces. Tests: disk failure marks active runtime selection unsaved, restart selects last durably saved profile, and corruption cannot silently activate an unintended profile.
- [x] **M10.3 Durable selection:** save active pointer after successful activation and reconcile state namespaces. Tests: disk failure marks active runtime selection unsaved, restart selects last durably saved profile, and corruption cannot silently activate an unintended profile.
Successful activation atomically writes the strict XDG active-profile pointer.
`serve` without `--config` follows it; corrupt pointers fail before audio/socket
side effects, while pointer-write failure keeps the new runtime profile active
but visibly marks its selection unsaved.
## M11 — Native PipeWire and optional ALSA mixer

View File

@ -79,6 +79,7 @@ pub struct ConfigurationSnapshot {
pub revision: u64,
pub dirty: bool,
pub applied_revision: u64,
pub selection_saved: bool,
pub learning: Option<String>,
pub error: Option<String>,
pub profile_id: String,
@ -1182,8 +1183,13 @@ impl<C> LiveTui<C> {
let config = &self.snapshot.configuration;
let mut lines = vec![
Line::from(format!(
"Profile: {} · draft {} · live {}{}",
"Profile: {}{} · draft {} · live {}{}",
config.profile_id,
if config.selection_saved {
""
} else {
" · selection unsaved"
},
config.revision,
config.applied_revision,
if config.dirty {
@ -1571,6 +1577,7 @@ mod tests {
revision: 3,
dirty: true,
applied_revision: 2,
selection_saved: true,
learning: None,
error: None,
profile_id: "desktop".into(),