feat(M9.3): apply and atomically save editor drafts

Test: cargo fmt --all -- --check

Test: cargo check --workspace --all-targets --all-features

Test: cargo test --workspace --all-targets --all-features

Test: cargo test --workspace --doc --all-features

Test: cargo clippy --workspace --all-targets --all-features -- -D warnings

Test: cargo build --workspace --release --all-features

Test: default, no-default, Pulse-only, and MIDI-only feature matrix
This commit is contained in:
Dandaedre 2026-10-15 04:22:05 +02:00
parent fa45944b79
commit 8e1c504478
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
9 changed files with 340 additions and 15 deletions

View File

@ -314,6 +314,12 @@ armed, messages from that surface are withheld from normal routing; unrelated
surfaces continue normally. The first compatible CC or note press becomes a
validated draft binding, while cancellation restores routing immediately.
Apply and Save are separate editor actions. Apply rebuilds profile-derived
matching, groups, faders, pickup, and MIDI routing while retaining confirmed
audio observations and issuing no audio write. Save first compares the exact
on-disk bytes with the server's load/save baseline, then uses the atomic writer;
conflicts or persistence failures retain both the previous file and dirty draft.
The implemented atomic writer checks that its parent and any existing target
are owned by the effective user and are not symlinks. It creates mode-`0600`
temporary files in the destination directory, streams and syncs their content,

View File

@ -1,6 +1,8 @@
use std::{fs, io, path::PathBuf};
use fader_config::{
ConfigError, Profile, ProfileDocument, SelectorDraft, SelectorField, SelectorPattern,
TargetKind,
AtomicFile, ConfigError, PersistenceError, Profile, ProfileDocument, SelectorDraft,
SelectorField, SelectorPattern, TargetKind,
};
use thiserror::Error;
@ -12,6 +14,16 @@ pub(crate) enum EditorError {
StaleRevision { actual: u64, current: u64 },
#[error(transparent)]
Config(#[from] ConfigError),
#[error("profile file changed outside fader_master; refusing to overwrite {0}")]
ExternalConflict(PathBuf),
#[error("could not read profile file {path}: {source}")]
Read {
path: PathBuf,
#[source]
source: io::Error,
},
#[error(transparent)]
Persistence(#[from] PersistenceError),
}
#[derive(Debug)]
@ -19,14 +31,19 @@ pub(crate) struct ConfigurationEditor {
document: ProfileDocument,
revision: u64,
dirty: bool,
path: PathBuf,
baseline_source: String,
}
impl ConfigurationEditor {
pub(crate) const fn new(document: ProfileDocument) -> Self {
pub(crate) fn new(document: ProfileDocument, path: PathBuf) -> Self {
let baseline_source = document.source();
Self {
document,
revision: 0,
dirty: false,
path,
baseline_source,
}
}
@ -149,6 +166,27 @@ impl ConfigurationEditor {
self.dirty = true;
self.profile()
}
pub(crate) fn save(&mut self, expected_revision: u64) -> Result<(), EditorError> {
if expected_revision != self.revision {
return Err(EditorError::StaleRevision {
actual: expected_revision,
current: self.revision,
});
}
let disk = fs::read_to_string(&self.path).map_err(|source| EditorError::Read {
path: self.path.clone(),
source,
})?;
if disk != self.baseline_source {
return Err(EditorError::ExternalConflict(self.path.clone()));
}
let source = self.document.source();
AtomicFile::write(&self.path, source.as_bytes())?;
self.baseline_source = source;
self.dirty = false;
Ok(())
}
}
fn selector(field: &str, pattern: String, regex: bool) -> Result<SelectorDraft, ConfigError> {
@ -184,15 +222,21 @@ const fn target_kind(kind: MixerObjectKind) -> TargetKind {
#[cfg(test)]
mod tests {
use std::{fs, os::unix::fs::PermissionsExt};
use super::*;
use crate::ipc::MixerObjectKey;
use tempfile::tempdir;
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
#[test]
fn accepted_edits_advance_revision_and_stale_or_invalid_edits_do_not() {
let root = tempdir().unwrap();
let path = root.path().join("desktop.toml");
fs::write(&path, PROFILE).unwrap();
let document = ProfileDocument::parse(PROFILE).unwrap();
let mut editor = ConfigurationEditor::new(document);
let mut editor = ConfigurationEditor::new(document, path);
let profile = editor
.apply(
0,
@ -231,4 +275,69 @@ mod tests {
assert_eq!(editor.revision(), 1);
assert_eq!(editor.profile().unwrap().faders().len(), 2);
}
#[test]
fn save_is_atomic_and_refuses_external_changes() {
let root = tempdir().unwrap();
let path = root.path().join("desktop.toml");
fs::write(&path, PROFILE).unwrap();
let document = ProfileDocument::parse(PROFILE).unwrap();
let mut editor = ConfigurationEditor::new(document, path.clone());
editor
.apply(
0,
ConfigurationEdit::SetGroup {
id: "media".into(),
label: "Players".into(),
members: vec!["music".into(), "browser".into()],
},
)
.unwrap();
editor.save(1).unwrap();
assert!(!editor.dirty());
assert!(fs::read_to_string(&path).unwrap().contains("Players"));
editor
.apply(
1,
ConfigurationEdit::SetGroup {
id: "media".into(),
label: "Media again".into(),
members: vec!["music".into(), "browser".into()],
},
)
.unwrap();
fs::write(&path, "external edit").unwrap();
assert!(matches!(
editor.save(2),
Err(EditorError::ExternalConflict(_))
));
assert!(editor.dirty());
assert_eq!(fs::read_to_string(path).unwrap(), "external edit");
}
#[test]
fn save_failure_keeps_previous_file_and_unsaved_draft() {
let root = tempdir().unwrap();
let path = root.path().join("desktop.toml");
fs::write(&path, PROFILE).unwrap();
let document = ProfileDocument::parse(PROFILE).unwrap();
let mut editor = ConfigurationEditor::new(document, path.clone());
editor
.apply(
0,
ConfigurationEdit::SetGroup {
id: "media".into(),
label: "Unsaved".into(),
members: vec!["music".into(), "browser".into()],
},
)
.unwrap();
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o500)).unwrap();
let result = editor.save(1);
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
assert!(matches!(result, Err(EditorError::Persistence(_))));
assert!(editor.dirty());
assert_eq!(fs::read_to_string(path).unwrap(), PROFILE);
}
}

View File

@ -3,7 +3,7 @@ use std::io::{self, Read, Write};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;
pub const PROTOCOL_VERSION: u16 = 7;
pub const PROTOCOL_VERSION: u16 = 8;
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
/// Kind of mixer object addressed by a client.
@ -53,6 +53,12 @@ pub enum RequestCommand {
action: String,
},
CancelMidiLearn,
ApplyConfiguration {
expected_revision: u64,
},
SaveConfiguration {
expected_revision: u64,
},
SetVolume {
object: MixerObjectKey,
gain: f64,
@ -150,6 +156,7 @@ pub struct MixerSnapshot {
pub struct ConfigurationSnapshot {
pub revision: u64,
pub dirty: bool,
pub applied_revision: u64,
pub learning: Option<String>,
pub error: Option<String>,
pub profile_id: String,

View File

@ -101,10 +101,12 @@ pub(crate) fn configuration_snapshot(
profile: &Profile,
revision: u64,
dirty: bool,
applied_revision: u64,
) -> ConfigurationSnapshot {
ConfigurationSnapshot {
revision,
dirty,
applied_revision,
learning: None,
error: None,
profile_id: profile.id().to_string(),
@ -259,7 +261,7 @@ impl LiveMixerState {
write_ceiling,
backend: backend.into(),
status: "connecting".to_owned(),
configuration: configuration_snapshot(profile, 0, false),
configuration: configuration_snapshot(profile, 0, false, 0),
})
}
@ -414,6 +416,21 @@ impl LiveMixerState {
self.configuration = configuration;
}
/// Replaces profile-derived routing while retaining confirmed backend state.
pub(crate) fn reconfigure(&mut self, profile: &Profile) -> Result<(), LiveMixerError> {
let mut replacement = Self::new(self.write_ceiling, self.backend.clone(), profile)?;
std::mem::swap(&mut replacement.reducer, &mut self.reducer);
std::mem::swap(&mut replacement.metadata, &mut self.metadata);
std::mem::swap(&mut replacement.output, &mut self.output);
std::mem::swap(&mut replacement.status, &mut self.status);
std::mem::swap(&mut replacement.devices, &mut self.devices);
replacement.configuration = self.configuration.clone();
*self = replacement;
let faders = self.faders.keys().cloned().collect::<Vec<_>>();
self.rearm_faders(&faders);
Ok(())
}
pub fn midi_intent(
&mut self,
intent: MidiIntent,
@ -577,6 +594,13 @@ impl LiveMixerState {
"MIDI learn commands must be handled by the server owner".to_owned(),
));
}
RequestCommand::ApplyConfiguration { .. }
| RequestCommand::SaveConfiguration { .. } => {
return Err(LiveMixerError::Profile(
"configuration lifecycle commands must be handled by the server owner"
.to_owned(),
));
}
RequestCommand::SetVolume {
object,
gain,
@ -817,3 +841,39 @@ impl LiveMixerState {
Ok(commands)
}
}
#[cfg(test)]
mod reconfigure_tests {
use super::*;
#[test]
fn reconfigure_retains_observations_without_issuing_audio_writes() {
let source = include_str!("../../examples/profiles/desktop.toml");
let profile = Profile::parse(source).unwrap();
let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
let stream = StreamHandle::new(fader_core::BackendEpoch::new(1), 7, 1);
state
.worker_event(WorkerEvent::StreamMetadata {
stream,
metadata: StreamMetadata::new().with_application_name("Music Player"),
volume_writable: true,
})
.unwrap();
state
.worker_event(WorkerEvent::Adapter(AdapterEvent::Observed {
stream,
channels: ChannelGains::new(vec![Gain::new(0.6).unwrap()]).unwrap(),
muted: Mute::Unmuted,
operation: None,
}))
.unwrap();
let edited = source.replace("label = \"Music\"", "label = \"Listening\"");
state
.reconfigure(&Profile::parse(&edited).unwrap())
.unwrap();
let snapshot = state.snapshot();
assert_eq!(snapshot.objects[0].label, "Listening");
assert_eq!(snapshot.objects[0].gain, Some(0.6));
}
}

View File

@ -178,6 +178,7 @@ pub struct LocalServer {
dispatch: AdapterQueue,
poll_interval: Duration,
configuration: ConfigurationEditor,
applied_configuration_revision: u64,
}
impl LocalServer {
@ -185,6 +186,7 @@ impl LocalServer {
socket: impl Into<PathBuf>,
write_ceiling: Gain,
document: ProfileDocument,
profile_path: PathBuf,
) -> Result<Self, LocalError> {
let profile = document.preview()?;
let midi =
@ -204,7 +206,8 @@ impl LocalServer {
midi_sequence: 1,
dispatch: AdapterQueue::new(256),
poll_interval: profile.poll_interval(),
configuration: ConfigurationEditor::new(document),
configuration: ConfigurationEditor::new(document, profile_path),
applied_configuration_revision: 0,
})
}
@ -306,6 +309,7 @@ impl LocalServer {
&profile,
self.configuration.revision(),
self.configuration.dirty(),
self.applied_configuration_revision,
));
self.mixer.request(ClientRequest {
version: request.version,
@ -363,6 +367,7 @@ impl LocalServer {
&profile,
self.configuration.revision(),
self.configuration.dirty(),
self.applied_configuration_revision,
);
configuration.learning = Some(format!("{surface} -> {fader} ({action:?})"));
self.mixer.set_configuration(configuration);
@ -385,6 +390,50 @@ impl LocalServer {
command: crate::ipc::RequestCommand::Snapshot,
})
}
crate::ipc::RequestCommand::ApplyConfiguration { expected_revision }
if request.version == PROTOCOL_VERSION =>
{
if expected_revision != self.configuration.revision() {
Err(crate::live::LiveMixerError::Profile(format!(
"stale configuration revision {expected_revision}; current revision is {}",
self.configuration.revision()
)))
} else {
let profile = self
.configuration
.profile()
.map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?;
let midi = crate::midi_runtime::MidiRuntime::new(&profile)
.map_err(crate::live::LiveMixerError::Profile)?;
self.mixer.reconfigure(&profile)?;
self.midi = midi;
self.applied_configuration_revision = self.configuration.revision();
self.publish_configuration(&profile, None);
self.mixer.request(ClientRequest {
version: request.version,
request_id,
command: crate::ipc::RequestCommand::Snapshot,
})
}
}
crate::ipc::RequestCommand::SaveConfiguration { expected_revision }
if request.version == PROTOCOL_VERSION =>
{
match self.configuration.save(expected_revision) {
Ok(()) => {
let profile = self.configuration.profile().map_err(|error| {
crate::live::LiveMixerError::Profile(error.to_string())
})?;
self.publish_configuration(&profile, None);
self.mixer.request(ClientRequest {
version: request.version,
request_id,
command: crate::ipc::RequestCommand::Snapshot,
})
}
Err(error) => Err(crate::live::LiveMixerError::Profile(error.to_string())),
}
}
command => self.mixer.request(ClientRequest {
version: request.version,
request_id,
@ -414,6 +463,7 @@ impl LocalServer {
profile,
self.configuration.revision(),
self.configuration.dirty(),
self.applied_configuration_revision,
);
configuration.error = error;
self.mixer.set_configuration(configuration);

View File

@ -89,7 +89,13 @@ fn serve(
profile.poll_interval().as_millis(),
socket.display()
);
LocalServer::pulse(socket, Gain::new(profile.max_gain())?, document)?.run()?;
LocalServer::pulse(
socket,
Gain::new(profile.max_gain())?,
document,
config.to_owned(),
)?
.run()?;
Ok(())
}

View File

@ -92,6 +92,7 @@ impl IpcMixerClient {
configuration: tui::ConfigurationSnapshot {
revision: snapshot.configuration.revision,
dirty: snapshot.configuration.dirty,
applied_revision: snapshot.configuration.applied_revision,
learning: snapshot.configuration.learning,
error: snapshot.configuration.error,
profile_id: snapshot.configuration.profile_id,
@ -214,6 +215,14 @@ impl MixerClient for IpcMixerClient {
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
self.send(RequestCommand::CancelMidiLearn)
}
fn apply_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
self.send(RequestCommand::ApplyConfiguration { expected_revision })
}
fn save_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
self.send(RequestCommand::SaveConfiguration { expected_revision })
}
}
fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit {

11
task.md
View File

@ -274,12 +274,12 @@ Dependencies: M7, M4 for real use.
checks including terminal resize passed on 2026-10-15. A later UI refinement
should add a denser row mode and/or horizontal fader layout for smaller
terminals.
- [ ] **M8.2 Devices/status:** show adapter selection/probe errors, device mappings, ambiguity and persistence problems. Tests: disconnected/unsupported states have useful actions; manual backend selection validates rather than silently applying incompatible mappings.
- [x] **M8.2 Devices/status:** show adapter selection/probe errors, device mappings, ambiguity and persistence problems. Tests: disconnected/unsupported states have useful actions; manual backend selection validates rather than silently applying incompatible mappings.
The live TUI now preserves server-published MIDI placeholders and shows
connected backend IDs, connection progress, missing-device guidance,
ambiguity selection guidance, and transport errors in its compact status
line. Keep this item open until editor-managed assignment persistence can
report save/conflict failures from M9.3.
line. Editor save/conflict failures now remain visible while the prior live
state and unsaved draft are retained.
- [x] **M8.3 Terminal lifecycle:** restoration on normal/error exit, nonblocking refresh, logging away from display. Tests: injected IO/client failure releases terminal guard; polling/refresh does not block server operation.
Blocking IPC runs on a joined worker and a delayed request cannot block redraw
access. The restoration guard is independently injected and proven to run
@ -347,7 +347,10 @@ Dependencies: M8, M2, M1.
The Config tab starts surface/fader/action-scoped learning with `L` and
cancels with `C`. Captured CC/note identity is added to the validated server
draft; conflicts are shown without changing the draft revision.
- [ ] **M9.3 Apply/save/conflict:** server-owned revisioned edits, separate live apply and persistence. Tests: stale edits conflict, external file edits are not overwritten, comments survive save, write failure is shown as unsaved and leaves previous disk config usable.
- [x] **M9.3 Apply/save/conflict:** server-owned revisioned edits, separate live apply and persistence. Tests: stale edits conflict, external file edits are not overwritten, comments survive save, write failure is shown as unsaved and leaves previous disk config usable.
`P` applies the validated draft without writing audio or disk; `S` atomically
saves it only when the on-disk bytes still match the server baseline. Draft,
live, and durable state remain separately visible after failures.
## M10 — Transactional profile swapping

View File

@ -78,6 +78,7 @@ pub struct MidiDevice {
pub struct ConfigurationSnapshot {
pub revision: u64,
pub dirty: bool,
pub applied_revision: u64,
pub learning: Option<String>,
pub error: Option<String>,
pub profile_id: String,
@ -197,6 +198,18 @@ pub trait MixerClient {
"MIDI learn is unavailable",
))
}
fn apply_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"configuration apply is unavailable",
))
}
fn save_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"configuration save is unavailable",
))
}
}
#[derive(Clone, Debug)]
@ -218,6 +231,8 @@ enum BufferedAction {
action: String,
},
CancelMidiLearn,
ApplyConfiguration,
SaveConfiguration,
}
#[derive(Debug)]
@ -389,6 +404,14 @@ impl MixerClient for BufferedMixerClient {
fn cancel_midi_learn(&mut self) -> io::Result<MixerSnapshot> {
self.queue_configuration_action(BufferedAction::CancelMidiLearn)
}
fn apply_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
self.queue_configuration_action(BufferedAction::ApplyConfiguration)
}
fn save_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
self.queue_configuration_action(BufferedAction::SaveConfiguration)
}
}
impl BufferedMixerClient {
@ -507,6 +530,8 @@ fn execute_action<C: MixerClient>(
action,
} => client.start_midi_learn(surface.clone(), fader.clone(), action.clone()),
BufferedAction::CancelMidiLearn => client.cancel_midi_learn(),
BufferedAction::ApplyConfiguration => client.apply_configuration(configuration_revision),
BufferedAction::SaveConfiguration => client.save_configuration(configuration_revision),
};
match execute(client, confirmed.revision, confirmed.configuration.revision) {
Ok(snapshot) => Ok(snapshot),
@ -514,6 +539,10 @@ fn execute_action<C: MixerClient>(
if matches!(action, BufferedAction::SetVolume { .. })
|| (matches!(action, BufferedAction::EditConfiguration { .. })
&& first.kind() == io::ErrorKind::InvalidData)
|| (matches!(
action,
BufferedAction::ApplyConfiguration | BufferedAction::SaveConfiguration
) && first.kind() == io::ErrorKind::InvalidData)
|| (matches!(action, BufferedAction::ToggleMute { .. })
&& first.kind() == io::ErrorKind::InvalidData) =>
{
@ -575,6 +604,7 @@ fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) {
BufferedAction::Refresh => {}
BufferedAction::EditConfiguration { .. } => {}
BufferedAction::StartMidiLearn { .. } | BufferedAction::CancelMidiLearn => {}
BufferedAction::ApplyConfiguration | BufferedAction::SaveConfiguration => {}
}
}
@ -766,6 +796,24 @@ impl<C: MixerClient> LiveTui<C> {
Err(error) => self.client_error = Some(error.to_string()),
}
}
KeyCode::Char('p') if self.tab == Tab::Configuration => {
match self
.client
.apply_configuration(self.snapshot.configuration.revision)
{
Ok(snapshot) => self.replace_snapshot(snapshot),
Err(error) => self.client_error = Some(error.to_string()),
}
}
KeyCode::Char('s') if self.tab == Tab::Configuration => {
match self
.client
.save_configuration(self.snapshot.configuration.revision)
{
Ok(snapshot) => self.replace_snapshot(snapshot),
Err(error) => self.client_error = Some(error.to_string()),
}
}
KeyCode::Esc | KeyCode::Char('q') => self.exit = true,
_ => {}
}
@ -1062,6 +1110,8 @@ impl<C> Widget for &LiveTui<C> {
"delete".fg(theme.secondary),
" L/C ".fg(theme.foreground),
"learn".fg(theme.secondary),
" P/S ".fg(theme.foreground),
"apply/save".fg(theme.secondary),
" Tab ".fg(theme.foreground),
"mixer".fg(theme.secondary),
" T ".fg(theme.foreground),
@ -1132,9 +1182,10 @@ impl<C> LiveTui<C> {
let config = &self.snapshot.configuration;
let mut lines = vec![
Line::from(format!(
"Profile: {} · config rev {}{}",
"Profile: {} · draft {} · live {}{}",
config.profile_id,
config.revision,
config.applied_revision,
if config.dirty {
" · unsaved draft"
} else {
@ -1157,7 +1208,7 @@ impl<C> LiveTui<C> {
}
lines.push(Line::from(""));
lines.push(
Line::from("A app · G group · F fader · D delete · L learn · C cancel learn")
Line::from("A app · G group · F fader · D delete · L/C learn · P apply · S save")
.fg(theme.muted),
);
lines.push(Line::from("Applications").fg(theme.accent).bold());
@ -1519,6 +1570,7 @@ mod tests {
snapshot.configuration = ConfigurationSnapshot {
revision: 3,
dirty: true,
applied_revision: 2,
learning: None,
error: None,
profile_id: "desktop".into(),
@ -1680,6 +1732,22 @@ mod tests {
self.snapshot.configuration.learning = None;
Ok(self.snapshot.clone())
}
fn apply_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
self.calls
.lock()
.unwrap()
.push(format!("apply:{expected_revision}"));
self.snapshot.configuration.applied_revision = expected_revision;
Ok(self.snapshot.clone())
}
fn save_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
self.calls
.lock()
.unwrap()
.push(format!("save:{expected_revision}"));
self.snapshot.configuration.dirty = false;
Ok(self.snapshot.clone())
}
}
let calls = Arc::new(Mutex::new(Vec::new()));
@ -1700,9 +1768,16 @@ mod tests {
);
app.handle_key_event(press(KeyCode::Char('c')));
assert!(app.snapshot.configuration.learning.is_none());
app.handle_key_event(press(KeyCode::Char('p')));
app.handle_key_event(press(KeyCode::Char('s')));
assert_eq!(
calls.lock().unwrap().as_slice(),
&["start:apc-mini:media-fader:volume", "cancel"]
&[
"start:apc-mini:media-fader:volume",
"cancel",
"apply:0",
"save:0"
]
);
}