From 54149c3302b79d740529446c1c814ac04eaf6375 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 18 Oct 2026 11:10:41 +0200 Subject: [PATCH] feat: add confirmed TUI profile reset Back up the active profile, atomically install safe defaults, and activate them through the server-owned IPC lifecycle after explicit TUI confirmation. Tests: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; default/no-default workspace tests; isolated Pulse and MIDI feature tests (all pass; real-daemon tests remain opt-in). --- README.md | 6 ++ architecture.md | 9 ++ config/src/document.rs | 15 ++++ fader_master/src/editor.rs | 55 ++++++++++++ fader_master/src/ipc.rs | 5 +- fader_master/src/live.rs | 3 +- fader_master/src/local.rs | 61 +++++++++++++ fader_master/src/tui_client.rs | 4 + task.md | 4 + tui/src/lib.rs | 155 +++++++++++++++++++++++++++++++-- 10 files changed, 309 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 7709c68..19d572f 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,9 @@ cards, including one-row Slim and Bordered slim faders: Malformed or conflicting edits never replace the active configuration. - Switch among valid managed profiles from a popup in the Config view; the default switch adopts live audio without writing saved volume state. +- Reset the active profile from Config after an explicit confirmation. The TUI + preserves the previous file as `.toml.reset.bak` before installing + and activating a safe Master-output profile. ## Quick start @@ -107,6 +110,9 @@ Use `Tab` to open Config, `T` to cycle the theme, and `Q` to open the quit confirmation. Fader editing exposes capture rules, group membership, separate controller/Learn/Unlearn actions for volume and mute, size, and visibility. Config → Active profile opens the profile switcher. +Config → Reset active profile provides an emergency return to safe defaults; +confirming it immediately saves and activates the reset and keeps a `.reset.bak` +copy beside the profile. Separator editing offers an optional name, size, and decoration; an empty name with Plain + Fill creates flexible blank space. Press Enter to accept popup edits, then use Config → Save to persist the draft. diff --git a/architecture.md b/architecture.md index 46050f4..b8c8f54 100644 --- a/architecture.md +++ b/architecture.md @@ -558,6 +558,15 @@ MIDI devices are selectable settings rows. Their details popup shows stable and backend identity, connection status, and errors, and sets or clears the same profile-backed default controller used by MIDI learn. +Config also exposes a confirmed emergency reset for the active profile. The +server, never the TUI process, preserves the current on-disk bytes beside the +profile as `.toml.reset.bak`, atomically replaces the profile with the +safe default-output configuration, and activates it without issuing audio writes. +The reset clears drafts, routing, MIDI assignments, and presentation settings, +while retaining process-level runtime timing that cannot change under a live +native worker. It does not delete sibling profiles, the active-profile pointer, +or checkpoint state. + Every value presented as configuration is read from the server-owned validated profile draft and every edit targets that same profile field. The TUI must not invent parallel configuration defaults or overwrite unrelated fields; local diff --git a/config/src/document.rs b/config/src/document.rs index 2d67d38..c8717e1 100644 --- a/config/src/document.rs +++ b/config/src/document.rs @@ -50,6 +50,21 @@ pickup_tolerance = 0.02 )) } + /// Builds a safe replacement for this profile while retaining runtime timing. + /// + /// Runtime timing cannot be changed while the native worker is running, so an + /// emergency reset clears user routing and presentation data but carries that + /// one process-level setting into the replacement document. + pub fn safe_defaults(&self) -> Result { + let profile = self.preview()?; + let mut replacement = Self::empty(profile.id().as_str())?; + if let Some(runtime) = self.document.get("runtime") { + replacement.document["runtime"] = runtime.clone(); + } + replacement.preview()?; + Ok(replacement) + } + /// Parses both the editable TOML representation and semantic profile. pub fn parse(input: &str) -> Result { Profile::parse(input)?; diff --git a/fader_master/src/editor.rs b/fader_master/src/editor.rs index 747830a..cfc9733 100644 --- a/fader_master/src/editor.rs +++ b/fader_master/src/editor.rs @@ -346,6 +346,34 @@ impl ConfigurationEditor { self.dirty = false; Ok(()) } + + pub(crate) fn reset(&mut self, expected_revision: u64) -> Result { + if expected_revision != self.revision { + return Err(EditorError::StaleRevision { + actual: expected_revision, + current: self.revision, + }); + } + let disk = fs::read(&self.path).map_err(|source| EditorError::Read { + path: self.path.clone(), + source, + })?; + let replacement = self.document.safe_defaults()?; + let source = replacement.source(); + let file_name = self + .path + .file_name() + .map(|name| name.to_string_lossy()) + .unwrap_or_default(); + let backup = self.path.with_file_name(format!("{file_name}.reset.bak")); + AtomicFile::write(&backup, &disk)?; + AtomicFile::write(&self.path, source.as_bytes())?; + self.document = replacement; + self.baseline_source = source; + self.revision = self.revision.saturating_add(1); + self.dirty = false; + self.profile() + } } fn binding_action(action: &str) -> Result { @@ -660,4 +688,31 @@ mod tests { assert!(editor.dirty()); assert_eq!(fs::read_to_string(path).unwrap(), PROFILE); } + + #[test] + fn reset_backs_up_the_profile_and_installs_safe_defaults() { + let root = tempdir().unwrap(); + let path = root.path().join("desktop.toml"); + fs::write(&path, PROFILE).unwrap(); + let document = ProfileDocument::parse(PROFILE).unwrap(); + let original_poll_interval = document.preview().unwrap().poll_interval(); + let mut editor = ConfigurationEditor::new(document, path.clone()); + fs::write(&path, "not = [valid").unwrap(); + + let profile = editor.reset(0).unwrap(); + + assert_eq!(profile.id().as_str(), "desktop"); + assert_eq!(profile.poll_interval(), original_poll_interval); + assert!(profile.applications().is_empty()); + assert!(profile.groups().is_empty()); + assert!(profile.surfaces().is_empty()); + assert_eq!(profile.faders()[0].id(), "master-fader"); + assert_eq!(editor.revision(), 1); + assert!(!editor.dirty()); + assert_eq!( + fs::read_to_string(root.path().join("desktop.toml.reset.bak")).unwrap(), + "not = [valid" + ); + assert!(ProfileDocument::parse(&fs::read_to_string(path).unwrap()).is_ok()); + } } diff --git a/fader_master/src/ipc.rs b/fader_master/src/ipc.rs index e18852f..96e8f24 100644 --- a/fader_master/src/ipc.rs +++ b/fader_master/src/ipc.rs @@ -3,7 +3,7 @@ use std::io::{self, Read, Write}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use thiserror::Error; -pub const PROTOCOL_VERSION: u16 = 19; +pub const PROTOCOL_VERSION: u16 = 20; pub const MAX_FRAME_BYTES: usize = 64 * 1024; /// Kind of mixer object addressed by a client. @@ -56,6 +56,9 @@ pub enum RequestCommand { SaveConfiguration { expected_revision: u64, }, + ResetConfiguration { + expected_revision: u64, + }, SwitchProfile { id: String, restore: bool, diff --git a/fader_master/src/live.rs b/fader_master/src/live.rs index 3fc3f66..6715fcd 100644 --- a/fader_master/src/live.rs +++ b/fader_master/src/live.rs @@ -818,7 +818,8 @@ impl LiveMixerState { "MIDI learn commands must be handled by the server owner".to_owned(), )); } - RequestCommand::SaveConfiguration { .. } => { + RequestCommand::SaveConfiguration { .. } + | RequestCommand::ResetConfiguration { .. } => { return Err(LiveMixerError::Profile( "configuration lifecycle commands must be handled by the server owner" .to_owned(), diff --git a/fader_master/src/local.rs b/fader_master/src/local.rs index 719f78d..4273763 100644 --- a/fader_master/src/local.rs +++ b/fader_master/src/local.rs @@ -452,6 +452,26 @@ impl LocalServer { command: crate::ipc::RequestCommand::Snapshot, }) } + crate::ipc::RequestCommand::ResetConfiguration { expected_revision } + if request.version == PROTOCOL_VERSION => + { + let profile = self + .configuration + .reset(expected_revision) + .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, Gain::new(profile.max_gain())?)?; + 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::SwitchProfile { id, restore } if request.version == PROTOCOL_VERSION => { @@ -955,6 +975,47 @@ mod tests { assert_eq!(durable.active_profile().as_str(), "secondary"); } + #[test] + fn reset_configuration_backs_up_persists_and_activates_safe_profile() { + let root = tempdir().unwrap(); + let source = include_str!("../../examples/profiles/desktop.toml"); + let profile_path = root.path().join("desktop.toml"); + fs::write(&profile_path, source).unwrap(); + let mut server = LocalServer::pulse( + root.path().join("control.sock"), + Gain::UNITY, + ProfileDocument::parse(source).unwrap(), + profile_path.clone(), + root.path().join("config.toml"), + root.path().join("state.toml"), + ) + .unwrap(); + + let response = direct_request( + &mut server, + RequestCommand::ResetConfiguration { + expected_revision: 0, + }, + ); + + let ResponseResult::Snapshot { snapshot } = response.result else { + panic!("reset must return the safe active snapshot"); + }; + assert_eq!(snapshot.configuration.profile_id, "desktop"); + assert_eq!(snapshot.configuration.revision, 1); + assert_eq!(snapshot.configuration.applied_revision, 1); + assert!(!snapshot.configuration.dirty); + assert!(snapshot.configuration.applications.is_empty()); + assert_eq!(snapshot.configuration.faders[0].id, "master-fader"); + assert_eq!( + fs::read_to_string(root.path().join("desktop.toml.reset.bak")).unwrap(), + source + ); + let saved = + fader_config::Profile::parse(&fs::read_to_string(profile_path).unwrap()).unwrap(); + assert_eq!(saved.faders()[0].id(), "master-fader"); + } + #[test] fn save_persists_and_activates_the_validated_draft() { let root = tempdir().unwrap(); diff --git a/fader_master/src/tui_client.rs b/fader_master/src/tui_client.rs index 2ee3391..217ca70 100644 --- a/fader_master/src/tui_client.rs +++ b/fader_master/src/tui_client.rs @@ -335,6 +335,10 @@ impl MixerClient for IpcMixerClient { self.send(RequestCommand::SaveConfiguration { expected_revision }) } + fn reset_configuration(&mut self, expected_revision: u64) -> io::Result { + self.send(RequestCommand::ResetConfiguration { expected_revision }) + } + fn switch_profile(&mut self, id: String) -> io::Result { self.send(RequestCommand::SwitchProfile { id, restore: false }) } diff --git a/task.md b/task.md index 1dca921..c6203db 100644 --- a/task.md +++ b/task.md @@ -457,6 +457,10 @@ Dependencies: M8, M2, M1. fader. MIDI-device status rows are selectable and open a details popup where the profile's default-controller assignment can be set or cleared. `h` and `?` open detailed keyboard help; Shift+H hides the selected mixer fader. + A confirmed Config action now resets only the active profile to the safe + Master-output default. The server backs up the prior bytes as `.reset.bak`, + atomically persists the replacement, and activates it without audio writes; + editor, IPC/server, and confirmation/cancellation paths are regression-tested. Keep this item open until any remaining required object-creation workflow is available from the mixer and its small-terminal acceptance passes. diff --git a/tui/src/lib.rs b/tui/src/lib.rs index c3b4436..9dc61aa 100644 --- a/tui/src/lib.rs +++ b/tui/src/lib.rs @@ -500,6 +500,12 @@ pub trait MixerClient { "configuration save is unavailable", )) } + fn reset_configuration(&mut self, _expected_revision: u64) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "configuration reset is unavailable", + )) + } fn switch_profile(&mut self, _id: String) -> io::Result { Err(io::Error::new( io::ErrorKind::Unsupported, @@ -528,6 +534,7 @@ enum BufferedAction { }, CancelMidiLearn, SaveConfiguration, + ResetConfiguration, SwitchProfile { id: String, }, @@ -715,6 +722,10 @@ impl MixerClient for BufferedMixerClient { self.queue_configuration_action(BufferedAction::SaveConfiguration) } + fn reset_configuration(&mut self, _expected_revision: u64) -> io::Result { + self.queue_configuration_action(BufferedAction::ResetConfiguration) + } + fn switch_profile(&mut self, id: String) -> io::Result { self.queue_configuration_action(BufferedAction::SwitchProfile { id }) } @@ -848,6 +859,7 @@ fn execute_action( } => client.start_midi_learn(surface.clone(), fader.clone(), action.clone()), BufferedAction::CancelMidiLearn => client.cancel_midi_learn(), BufferedAction::SaveConfiguration => client.save_configuration(configuration_revision), + BufferedAction::ResetConfiguration => client.reset_configuration(configuration_revision), BufferedAction::SwitchProfile { id } => client.switch_profile(id.clone()), }; let can_retry_stale = matches!( @@ -856,6 +868,7 @@ fn execute_action( | BufferedAction::ToggleMute { .. } | BufferedAction::EditConfiguration { .. } | BufferedAction::SaveConfiguration + | BufferedAction::ResetConfiguration ); let mut first_error = None; for attempt in 0..MAX_STALE_ATTEMPTS { @@ -957,6 +970,7 @@ fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) { BufferedAction::EditConfiguration { .. } => {} BufferedAction::StartMidiLearn { .. } | BufferedAction::CancelMidiLearn => {} BufferedAction::SaveConfiguration => {} + BufferedAction::ResetConfiguration => {} BufferedAction::SwitchProfile { .. } => {} } } @@ -1015,6 +1029,7 @@ pub struct LiveTui { theme_override: bool, exit: bool, quit_confirmation: bool, + reset_confirmation: bool, show_help: bool, client_error: Option, tab: Tab, @@ -1057,6 +1072,7 @@ enum SettingsRow { AddMasterFader, CancelMidiLearn, Save, + Reset, MidiDevice { id: String }, DiscoveredMidiPort { backend_id: String }, } @@ -1323,6 +1339,7 @@ impl LiveTui { theme_override, exit: false, quit_confirmation: false, + reset_confirmation: false, show_help: false, client_error: None, tab: Tab::Mixer, @@ -1450,6 +1467,23 @@ impl LiveTui { } fn handle_key_event(&mut self, key_event: KeyEvent) { + if self.reset_confirmation { + match key_event.code { + KeyCode::Char('y' | 'Y') => { + self.reset_confirmation = false; + match self + .client + .reset_configuration(self.snapshot.configuration.revision) + { + Ok(snapshot) => self.replace_snapshot(snapshot), + Err(error) => self.client_error = Some(error.to_string()), + } + } + KeyCode::Char('n' | 'N') | KeyCode::Esc => self.reset_confirmation = false, + _ => {} + } + return; + } if self.quit_confirmation { match key_event.code { KeyCode::Char('y' | 'Y') => self.exit = true, @@ -1759,6 +1793,7 @@ impl LiveTui { rows.push(SettingsRow::AddMasterFader); } rows.push(SettingsRow::Save); + rows.push(SettingsRow::Reset); rows.extend( self.snapshot .devices @@ -1879,6 +1914,7 @@ impl LiveTui { }); } SettingsRow::Save if forward => self.save_configuration(), + SettingsRow::Reset if forward => self.reset_confirmation = true, SettingsRow::MidiDevice { id } if forward => { self.midi_device_details = Some(id); } @@ -2891,6 +2927,37 @@ impl Widget for &LiveTui { ) .render(popup, buf); } + if self.reset_confirmation { + let width = area.width.min(60); + let height = area.height.min(7); + let popup = Rect::new( + area.x + area.width.saturating_sub(width) / 2, + area.y + area.height.saturating_sub(height) / 2, + width, + height, + ); + Clear.render(popup, buf); + Paragraph::new(Text::from(vec![ + Line::from("Reset the active profile to safe defaults?").bold(), + Line::from("The current file is preserved as .toml.reset.bak."), + Line::from(vec![ + " Y ".fg(theme.foreground).bold(), + "reset".fg(theme.secondary), + " N / Esc ".fg(theme.foreground).bold(), + "cancel".fg(theme.secondary), + ]), + ])) + .alignment(Alignment::Center) + .wrap(Wrap { trim: true }) + .block( + Block::bordered() + .title(" Confirm profile reset ".fg(theme.error).bold()) + .border_set(border::DOUBLE) + .border_style(Style::default().fg(theme.error)) + .style(Style::default().bg(theme.background)), + ) + .render(popup, buf); + } } } @@ -3634,6 +3701,7 @@ impl LiveTui { Line::from(" Up/Down or J/K Select a setting or MIDI device"), Line::from(" Left/Right/Enter Change a setting or open its popup"), Line::from(" S Save the configuration"), + Line::from(" Reset setting Restore safe defaults after confirmation"), Line::from(""), Line::from("Global").fg(theme.accent).bold(), Line::from(" 1 / 2 / Tab Switch Mixer and Config views"), @@ -3742,6 +3810,7 @@ impl LiveTui { "already saved" } ), + SettingsRow::Reset => "Reset active profile to safe defaults [Enter]".to_owned(), SettingsRow::MidiDevice { .. } | SettingsRow::DiscoveredMidiPort { .. } => { continue; } @@ -4641,6 +4710,76 @@ mod tests { assert!(app.exit); } + #[test] + fn profile_reset_requires_confirmation_and_can_be_cancelled() { + struct ResetClient { + reset: Arc, + } + + impl MixerClient for ResetClient { + fn snapshot(&mut self) -> io::Result { + Ok(DemoClient::default().view()) + } + + fn set_volume( + &mut self, + _id: MixerObjectId, + _gain: f64, + _expected_revision: u64, + ) -> io::Result { + unreachable!() + } + + fn toggle_mute( + &mut self, + _id: MixerObjectId, + _expected_revision: u64, + ) -> io::Result { + unreachable!() + } + + fn reset_configuration( + &mut self, + _expected_revision: u64, + ) -> io::Result { + self.reset.store(true, Ordering::SeqCst); + Ok(DemoClient::default().view()) + } + } + + let reset = Arc::new(AtomicBool::new(false)); + let mut app = LiveTui::new(ResetClient { + reset: Arc::clone(&reset), + }) + .unwrap(); + app.tab = Tab::Configuration; + app.settings_selected = app + .settings_rows() + .iter() + .position(|row| matches!(row, SettingsRow::Reset)) + .unwrap(); + + app.handle_key_event(press(KeyCode::Enter)); + let area = Rect::new(0, 0, 80, 20); + let mut buffer = Buffer::empty(area); + (&app).render(area, &mut buffer); + let rendered = buffer + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(rendered.contains("Reset the active profile to safe defaults?")); + assert!(!reset.load(Ordering::SeqCst)); + + app.handle_key_event(press(KeyCode::Esc)); + app.handle_key_event(press(KeyCode::Char('y'))); + assert!(!reset.load(Ordering::SeqCst)); + + app.handle_key_event(press(KeyCode::Enter)); + app.handle_key_event(press(KeyCode::Char('y'))); + assert!(reset.load(Ordering::SeqCst)); + } + #[test] fn help_keys_open_detailed_keyboard_help_without_hiding() { let mut app = LiveTui::new(DemoClient::default()).unwrap(); @@ -5891,9 +6030,11 @@ mod tests { }) .unwrap(); app.handle_key_event(press(KeyCode::Tab)); - for _ in 0..8 { - app.handle_key_event(press(KeyCode::Down)); - } + app.settings_selected = app + .settings_rows() + .iter() + .position(|row| matches!(row, SettingsRow::MidiDevice { id } if id == "desk-left")) + .unwrap(); app.handle_key_event(press(KeyCode::Enter)); let area = Rect::new(0, 0, 100, 24); @@ -5962,9 +6103,11 @@ mod tests { }) .unwrap(); app.handle_key_event(press(KeyCode::Tab)); - for _ in 0..8 { - app.handle_key_event(press(KeyCode::Down)); - } + app.settings_selected = app + .settings_rows() + .iter() + .position(|row| matches!(row, SettingsRow::DiscoveredMidiPort { backend_id } if backend_id == "36:0")) + .unwrap(); app.handle_key_event(press(KeyCode::Enter)); let area = Rect::new(0, 0, 100, 24);