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).
This commit is contained in:
Dandaedre 2026-10-18 11:10:41 +02:00
parent a03c8c4d8d
commit 54149c3302
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
10 changed files with 309 additions and 8 deletions

View File

@ -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 `<profile>.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.

View File

@ -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 `<profile>.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

View File

@ -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<Self, ConfigError> {
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<Self, ConfigError> {
Profile::parse(input)?;

View File

@ -346,6 +346,34 @@ impl ConfigurationEditor {
self.dirty = false;
Ok(())
}
pub(crate) fn reset(&mut self, expected_revision: u64) -> Result<Profile, EditorError> {
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<fader_config::Action, ConfigError> {
@ -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());
}
}

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 = 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,

View File

@ -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(),

View File

@ -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();

View File

@ -335,6 +335,10 @@ impl MixerClient for IpcMixerClient {
self.send(RequestCommand::SaveConfiguration { expected_revision })
}
fn reset_configuration(&mut self, expected_revision: u64) -> io::Result<MixerSnapshot> {
self.send(RequestCommand::ResetConfiguration { expected_revision })
}
fn switch_profile(&mut self, id: String) -> io::Result<MixerSnapshot> {
self.send(RequestCommand::SwitchProfile { id, restore: false })
}

View File

@ -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.

View File

@ -500,6 +500,12 @@ pub trait MixerClient {
"configuration save is unavailable",
))
}
fn reset_configuration(&mut self, _expected_revision: u64) -> io::Result<MixerSnapshot> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"configuration reset is unavailable",
))
}
fn switch_profile(&mut self, _id: String) -> io::Result<MixerSnapshot> {
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<MixerSnapshot> {
self.queue_configuration_action(BufferedAction::ResetConfiguration)
}
fn switch_profile(&mut self, id: String) -> io::Result<MixerSnapshot> {
self.queue_configuration_action(BufferedAction::SwitchProfile { id })
}
@ -848,6 +859,7 @@ fn execute_action<C: MixerClient>(
} => 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<C: MixerClient>(
| 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<C> {
theme_override: bool,
exit: bool,
quit_confirmation: bool,
reset_confirmation: bool,
show_help: bool,
client_error: Option<String>,
tab: Tab,
@ -1057,6 +1072,7 @@ enum SettingsRow {
AddMasterFader,
CancelMidiLearn,
Save,
Reset,
MidiDevice { id: String },
DiscoveredMidiPort { backend_id: String },
}
@ -1323,6 +1339,7 @@ impl<C: MixerClient> LiveTui<C> {
theme_override,
exit: false,
quit_confirmation: false,
reset_confirmation: false,
show_help: false,
client_error: None,
tab: Tab::Mixer,
@ -1450,6 +1467,23 @@ impl<C: MixerClient> LiveTui<C> {
}
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<C: MixerClient> LiveTui<C> {
rows.push(SettingsRow::AddMasterFader);
}
rows.push(SettingsRow::Save);
rows.push(SettingsRow::Reset);
rows.extend(
self.snapshot
.devices
@ -1879,6 +1914,7 @@ impl<C: MixerClient> LiveTui<C> {
});
}
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<C: MixerClient> Widget for &LiveTui<C> {
)
.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 <profile>.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<C: MixerClient> LiveTui<C> {
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<C: MixerClient> LiveTui<C> {
"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<AtomicBool>,
}
impl MixerClient for ResetClient {
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
Ok(DemoClient::default().view())
}
fn set_volume(
&mut self,
_id: MixerObjectId,
_gain: f64,
_expected_revision: u64,
) -> io::Result<MixerSnapshot> {
unreachable!()
}
fn toggle_mute(
&mut self,
_id: MixerObjectId,
_expected_revision: u64,
) -> io::Result<MixerSnapshot> {
unreachable!()
}
fn reset_configuration(
&mut self,
_expected_revision: u64,
) -> io::Result<MixerSnapshot> {
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::<String>();
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);