feat(M9.1): edit server drafts from the TUI

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

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

Test: cargo clippy -p tui -p fader_master --all-targets --all-features -- -D warnings
This commit is contained in:
Dandaedre 2026-10-15 04:14:41 +02:00
parent 102f233980
commit 5daa06100b
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
3 changed files with 495 additions and 44 deletions

View File

@ -1,8 +1,8 @@
use std::{io, path::PathBuf};
use tui::{
MixerClient, MixerItem, MixerObjectId, MixerObjectKind, MixerSnapshot,
PickupStatus as TuiPickupStatus,
ConfigurationEdit as TuiConfigurationEdit, MixerClient, MixerItem, MixerObjectId,
MixerObjectKind, MixerSnapshot, PickupStatus as TuiPickupStatus,
};
use crate::{
@ -143,7 +143,9 @@ impl IpcMixerClient {
},
}),
ResponseResult::Error { message, .. } => {
let kind = if message.contains("stale revision") {
let kind = if message.contains("stale revision")
|| message.contains("stale configuration revision")
{
io::ErrorKind::InvalidData
} else {
io::ErrorKind::Other
@ -182,6 +184,91 @@ impl MixerClient for IpcMixerClient {
expected_revision,
})
}
fn edit_configuration(
&mut self,
edit: TuiConfigurationEdit,
expected_revision: u64,
) -> io::Result<MixerSnapshot> {
self.send(RequestCommand::EditConfiguration {
expected_revision,
edit: configuration_edit(edit),
})
}
}
fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEdit {
use crate::ipc::ConfigurationEdit as IpcEdit;
match edit {
TuiConfigurationEdit::Application {
existing,
id,
label,
field,
pattern,
regex,
} => {
if existing {
IpcEdit::SetApplication {
id,
label,
field,
pattern,
regex,
}
} else {
IpcEdit::AddApplication {
id,
label,
field,
pattern,
regex,
}
}
}
TuiConfigurationEdit::Group {
existing,
id,
label,
members,
} => {
if existing {
IpcEdit::SetGroup { id, label, members }
} else {
IpcEdit::AddGroup { id, label, members }
}
}
TuiConfigurationEdit::Fader {
existing,
id,
target,
pickup,
pickup_tolerance,
} => {
let target = key(target);
if existing {
IpcEdit::SetFader {
id,
target,
pickup,
pickup_tolerance,
}
} else {
IpcEdit::AddFader {
id,
target,
pickup,
pickup_tolerance,
}
}
}
TuiConfigurationEdit::Remove { kind, id } => match kind.as_str() {
"application" => IpcEdit::RemoveApplication { id },
"group" => IpcEdit::RemoveGroup { id },
"fader" => IpcEdit::RemoveFader { id },
_ => IpcEdit::RemoveApplication { id },
},
}
}
fn key(id: MixerObjectId) -> MixerObjectKey {

View File

@ -332,12 +332,14 @@ regression-tested profile fix then matched it into the two-stream media group.
Dependencies: M8, M2, M1.
- [ ] **M9.1 Editor drafts:** separate tab to create/edit/delete applications, groups and faders; target/member selection, matcher preview, validation errors and referenced-delete handling. Tests: invalid regex/dangling member rejected; Cancel has no side effects; creating a group/fader produces the expected semantic TOML.
- [x] **M9.1 Editor drafts:** separate tab to create/edit/delete applications, groups and faders; target/member selection, matcher preview, validation errors and referenced-delete handling. Tests: invalid regex/dangling member rejected; Cancel has no side effects; creating a group/fader produces the expected semantic TOML.
Transactional, comment-preserving draft primitives now create applications,
absolute groups and faders, and roll back invalid regexes or referenced
deletes. A separate Config tab now shows the server-owned applications, group
membership, logical fader targets, pickup policy, and MIDI assignments. The
selection controls, matcher preview, and full edit/delete surface remain.
keyboard editor accepts explicit target/member IDs, previews live matcher
results, and provides the full create/update/delete surface with inline
validation errors and cancellation.
The server now owns the validated draft and its independent revision; stale
or invalid edit requests are rejected without advancing or altering it, and
accepted edits are exposed as an unsaved draft in the Config tab.

View File

@ -113,6 +113,35 @@ pub struct ConfiguredBinding {
pub message: String,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConfigurationEdit {
Application {
existing: bool,
id: String,
label: String,
field: String,
pattern: String,
regex: bool,
},
Group {
existing: bool,
id: String,
label: String,
members: Vec<String>,
},
Fader {
existing: bool,
id: String,
target: MixerObjectId,
pickup: bool,
pickup_tolerance: f64,
},
Remove {
kind: String,
id: String,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct MixerSnapshot {
pub revision: u64,
@ -139,6 +168,16 @@ pub trait MixerClient {
id: MixerObjectId,
expected_revision: u64,
) -> io::Result<MixerSnapshot>;
fn edit_configuration(
&mut self,
_edit: ConfigurationEdit,
_expected_revision: u64,
) -> io::Result<MixerSnapshot> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"configuration editing is unavailable",
))
}
}
#[derive(Clone, Debug)]
@ -146,6 +185,7 @@ enum BufferedAction {
SetVolume { id: MixerObjectId, gain: f64 },
ToggleMute { id: MixerObjectId },
Refresh,
EditConfiguration { edit: ConfigurationEdit },
}
#[derive(Debug)]
@ -155,6 +195,7 @@ struct BufferedState {
desired_mutes: BTreeMap<MixerObjectId, bool>,
volume_work: BTreeMap<MixerObjectId, f64>,
mute_work: VecDeque<MixerObjectId>,
configuration_work: VecDeque<ConfigurationEdit>,
error: Option<String>,
shutdown: bool,
}
@ -186,6 +227,7 @@ impl BufferedMixerClient {
desired_mutes: BTreeMap::new(),
volume_work: BTreeMap::new(),
mute_work: VecDeque::new(),
configuration_work: VecDeque::new(),
error: None,
shutdown: false,
}),
@ -277,6 +319,25 @@ impl MixerClient for BufferedMixerClient {
wake.notify_one();
Ok(snapshot)
}
fn edit_configuration(
&mut self,
edit: ConfigurationEdit,
_expected_revision: u64,
) -> io::Result<MixerSnapshot> {
let (state, wake) = &*self.shared;
let mut state = state
.lock()
.map_err(|_| io::Error::other("buffered mixer client state is poisoned"))?;
if state.configuration_work.len() >= 64 {
return Err(io::Error::other("configuration edit buffer is full"));
}
state.configuration_work.push_back(edit);
state.error = None;
let snapshot = state.snapshot.clone();
wake.notify_one();
Ok(snapshot)
}
}
impl Drop for BufferedMixerClient {
@ -310,6 +371,7 @@ fn client_loop<C>(
&& !state.shutdown
&& state.mute_work.is_empty()
&& state.volume_work.is_empty()
&& state.configuration_work.is_empty()
{
let refresh = if state.desired_volumes.is_empty() && state.desired_mutes.is_empty()
{
@ -332,6 +394,8 @@ fn client_loop<C>(
BufferedAction::ToggleMute { id }
} else if let Some((id, gain)) = state.volume_work.pop_first() {
BufferedAction::SetVolume { id, gain }
} else if let Some(edit) = state.configuration_work.pop_front() {
BufferedAction::EditConfiguration { edit }
} else {
BufferedAction::Refresh
}
@ -362,22 +426,27 @@ fn execute_action<C: MixerClient>(
confirmed: &mut MixerSnapshot,
action: &BufferedAction,
) -> io::Result<MixerSnapshot> {
let execute = |client: &mut C, revision| match action {
let execute = |client: &mut C, revision, configuration_revision| match action {
BufferedAction::SetVolume { id, gain } => client.set_volume(id.clone(), *gain, revision),
BufferedAction::ToggleMute { id } => client.toggle_mute(id.clone(), revision),
BufferedAction::Refresh => client.snapshot(),
BufferedAction::EditConfiguration { edit } => {
client.edit_configuration(edit.clone(), configuration_revision)
}
};
match execute(client, confirmed.revision) {
match execute(client, confirmed.revision, confirmed.configuration.revision) {
Ok(snapshot) => Ok(snapshot),
Err(first)
if matches!(action, BufferedAction::SetVolume { .. })
|| (matches!(action, BufferedAction::EditConfiguration { .. })
&& first.kind() == io::ErrorKind::InvalidData)
|| (matches!(action, BufferedAction::ToggleMute { .. })
&& first.kind() == io::ErrorKind::InvalidData) =>
{
*confirmed = client.snapshot()?;
execute(client, confirmed.revision).map_err(|second| {
io::Error::other(format!("{first}; retry after resync failed: {second}"))
})
execute(client, confirmed.revision, confirmed.configuration.revision).map_err(
|second| io::Error::other(format!("{first}; retry after resync failed: {second}")),
)
}
Err(error) => Err(error),
}
@ -430,6 +499,7 @@ fn discard_failed_action(state: &mut BufferedState, action: &BufferedAction) {
}
}
BufferedAction::Refresh => {}
BufferedAction::EditConfiguration { .. } => {}
}
}
@ -481,6 +551,7 @@ pub struct LiveTui<C> {
exit: bool,
client_error: Option<String>,
tab: Tab,
editor: Option<EditorInput>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
@ -490,6 +561,20 @@ enum Tab {
Configuration,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum EditorOperation {
Application,
Group,
Fader,
Remove,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct EditorInput {
operation: EditorOperation,
value: String,
}
impl<C: MixerClient> LiveTui<C> {
pub fn new(client: C) -> io::Result<Self> {
Self::with_theme(client, ThemeName::Default)
@ -505,6 +590,7 @@ impl<C: MixerClient> LiveTui<C> {
exit: false,
client_error: None,
tab: Tab::Mixer,
editor: None,
})
}
@ -555,6 +641,10 @@ impl<C: MixerClient> LiveTui<C> {
}
fn handle_key_event(&mut self, key_event: KeyEvent) {
if self.editor.is_some() {
self.handle_editor_key(key_event.code);
return;
}
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
self.selected =
@ -579,11 +669,148 @@ impl<C: MixerClient> LiveTui<C> {
}
KeyCode::Char('1') => self.tab = Tab::Mixer,
KeyCode::Char('2') => self.tab = Tab::Configuration,
KeyCode::Char('a') if self.tab == Tab::Configuration => {
self.start_editor(EditorOperation::Application)
}
KeyCode::Char('g') if self.tab == Tab::Configuration => {
self.start_editor(EditorOperation::Group)
}
KeyCode::Char('f') if self.tab == Tab::Configuration => {
self.start_editor(EditorOperation::Fader)
}
KeyCode::Char('d') if self.tab == Tab::Configuration => {
self.start_editor(EditorOperation::Remove)
}
KeyCode::Esc | KeyCode::Char('q') => self.exit = true,
_ => {}
}
}
fn start_editor(&mut self, operation: EditorOperation) {
self.editor = Some(EditorInput {
operation,
value: String::new(),
});
self.client_error = None;
}
fn handle_editor_key(&mut self, code: KeyCode) {
match code {
KeyCode::Esc => self.editor = None,
KeyCode::Backspace => {
if let Some(editor) = &mut self.editor {
editor.value.pop();
}
}
KeyCode::Enter => self.submit_editor(),
KeyCode::Char(character) => {
if let Some(editor) = &mut self.editor {
editor.value.push(character);
}
}
_ => {}
}
}
fn submit_editor(&mut self) {
let Some(editor) = self.editor.take() else {
return;
};
let edit = match self.parse_editor(&editor) {
Ok(edit) => edit,
Err(error) => {
self.client_error = Some(error);
return;
}
};
match self
.client
.edit_configuration(edit, self.snapshot.configuration.revision)
{
Ok(snapshot) => self.replace_snapshot(snapshot),
Err(error) => self.client_error = Some(error.to_string()),
}
}
fn parse_editor(&self, editor: &EditorInput) -> Result<ConfigurationEdit, String> {
let fields = editor.value.split('|').map(str::trim).collect::<Vec<_>>();
match editor.operation {
EditorOperation::Application if fields.len() == 5 => {
Ok(ConfigurationEdit::Application {
existing: self
.snapshot
.configuration
.applications
.iter()
.any(|item| item.id == fields[0]),
id: fields[0].to_owned(),
label: fields[1].to_owned(),
field: fields[2].to_owned(),
regex: match fields[3] {
"exact" => false,
"regex" => true,
_ => return Err("matcher mode must be exact or regex".to_owned()),
},
pattern: fields[4].to_owned(),
})
}
EditorOperation::Group if fields.len() == 3 => Ok(ConfigurationEdit::Group {
existing: self
.snapshot
.configuration
.groups
.iter()
.any(|item| item.id == fields[0]),
id: fields[0].to_owned(),
label: fields[1].to_owned(),
members: fields[2]
.split(',')
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_owned)
.collect(),
}),
EditorOperation::Fader if fields.len() == 4 => Ok(ConfigurationEdit::Fader {
existing: self
.snapshot
.configuration
.faders
.iter()
.any(|item| item.id == fields[0]),
id: fields[0].to_owned(),
target: MixerObjectId {
kind: parse_kind(fields[1])?,
id: fields[2].to_owned(),
},
pickup: match fields[3] {
"yes" | "true" => true,
"no" | "false" => false,
_ => return Err("pickup must be yes/no or true/false".to_owned()),
},
pickup_tolerance: 0.02,
}),
EditorOperation::Remove
if fields.len() == 2 && matches!(fields[0], "application" | "group" | "fader") =>
{
Ok(ConfigurationEdit::Remove {
kind: fields[0].to_owned(),
id: fields[1].to_owned(),
})
}
EditorOperation::Remove if fields.len() == 2 => {
Err("delete kind must be application, group, or fader".to_owned())
}
EditorOperation::Application => {
Err("expected id|label|field|exact/regex|pattern".to_owned())
}
EditorOperation::Group => Err("expected id|label|member1,member2".to_owned()),
EditorOperation::Fader => {
Err("expected id|application/group/output|target|pickup".to_owned())
}
EditorOperation::Remove => Err("expected application/group/fader|id".to_owned()),
}
}
fn change_volume(&mut self, delta: f64) {
if let Some(item) = self.snapshot.items.get(self.selected) {
if let Some(gain) = item.gain {
@ -666,16 +893,22 @@ impl<C> Widget for &LiveTui<C> {
)
.render(header, buf);
let status_error = self.client_error.is_some()
|| self
.snapshot
.devices
.iter()
.any(|device| device.error.is_some() || device.status == "error");
let status = self.client_error.clone().unwrap_or_else(|| {
device_summary(&self.snapshot.devices)
.unwrap_or_else(|| "confirmed server state".to_owned())
});
let status_error = self.editor.is_none()
&& (self.client_error.is_some()
|| self
.snapshot
.devices
.iter()
.any(|device| device.error.is_some() || device.status == "error"));
let status = self.editor.as_ref().map_or_else(
|| {
self.client_error.clone().unwrap_or_else(|| {
device_summary(&self.snapshot.devices)
.unwrap_or_else(|| "confirmed server state".to_owned())
})
},
|editor| format!("{}: {}", editor_prompt(editor.operation), editor.value),
);
let mixer = Block::bordered()
.title(
match self.tab {
@ -699,29 +932,48 @@ impl<C> Widget for &LiveTui<C> {
Tab::Configuration => self.render_configuration(inner, buf),
}
Paragraph::new(Line::from(vec![
" ↑/↓ or j/k ".fg(theme.foreground),
"select".fg(theme.secondary),
" ←/→ ".fg(theme.foreground),
"volume".fg(theme.secondary),
" M ".fg(theme.foreground),
"mute".fg(theme.secondary),
" Home/End ".fg(theme.foreground),
"0/100%".fg(theme.secondary),
" T ".fg(theme.foreground),
"theme".fg(theme.secondary),
" Tab/1/2 ".fg(theme.foreground),
"view".fg(theme.secondary),
" Q/Esc ".fg(theme.foreground),
"quit".fg(theme.secondary),
]))
.alignment(Alignment::Center)
.block(
Block::bordered()
.border_set(border::ROUNDED)
.border_style(Style::default().fg(theme.muted)),
)
.render(footer, buf);
let footer_line = match self.tab {
Tab::Mixer => Line::from(vec![
" ↑↓/jk ".fg(theme.foreground),
"select".fg(theme.secondary),
" ←→ ".fg(theme.foreground),
"volume".fg(theme.secondary),
" M ".fg(theme.foreground),
"mute".fg(theme.secondary),
" Home/End ".fg(theme.foreground),
"0/100%".fg(theme.secondary),
" T ".fg(theme.foreground),
"theme".fg(theme.secondary),
" Tab ".fg(theme.foreground),
"config".fg(theme.secondary),
" Q/Esc ".fg(theme.foreground),
"quit".fg(theme.secondary),
]),
Tab::Configuration => Line::from(vec![
" A ".fg(theme.foreground),
"app".fg(theme.secondary),
" G ".fg(theme.foreground),
"group".fg(theme.secondary),
" F ".fg(theme.foreground),
"fader".fg(theme.secondary),
" D ".fg(theme.foreground),
"delete".fg(theme.secondary),
" Tab ".fg(theme.foreground),
"mixer".fg(theme.secondary),
" T ".fg(theme.foreground),
"theme".fg(theme.secondary),
" Q/Esc ".fg(theme.foreground),
"quit".fg(theme.secondary),
]),
};
Paragraph::new(footer_line)
.alignment(Alignment::Center)
.block(
Block::bordered()
.border_set(border::ROUNDED)
.border_style(Style::default().fg(theme.muted)),
)
.render(footer, buf);
}
}
@ -751,6 +1003,24 @@ fn device_summary(devices: &[MidiDevice]) -> Option<String> {
})
}
fn parse_kind(value: &str) -> Result<MixerObjectKind, String> {
match value {
"application" => Ok(MixerObjectKind::Application),
"group" => Ok(MixerObjectKind::Group),
"output" => Ok(MixerObjectKind::Output),
_ => Err("target kind must be application, group, or output".to_owned()),
}
}
const fn editor_prompt(operation: EditorOperation) -> &'static str {
match operation {
EditorOperation::Application => "app id|label|field|exact/regex|pattern",
EditorOperation::Group => "group id|label|member1,member2",
EditorOperation::Fader => "fader id|application/group/output|target|pickup",
EditorOperation::Remove => "delete application/group/fader|id",
}
}
impl<C> LiveTui<C> {
fn render_configuration(&self, area: Rect, buf: &mut Buffer) {
let theme = self.theme.palette();
@ -769,9 +1039,27 @@ impl<C> LiveTui<C> {
.bold(),
];
lines.push(Line::from(""));
lines.push(
Line::from(
"A app · G group · F fader · D delete · Enter submit · Esc cancel",
)
.fg(theme.muted),
);
lines.push(Line::from("Applications").fg(theme.accent).bold());
lines.extend(config.applications.iter().map(|application| {
Line::from(format!(" {} — {}", application.id, application.label))
let matched = self
.snapshot
.items
.iter()
.find(|item| {
item.id.kind == MixerObjectKind::Application && item.id.id == application.id
})
.map(|item| item.detail.as_str())
.unwrap_or("not in live snapshot");
Line::from(format!(
" {} — {} · matcher preview: {}",
application.id, application.label, matched
))
}));
lines.push(Line::from("Groups").fg(theme.accent).bold());
lines.extend(config.groups.iter().map(|group| {
@ -1162,6 +1450,80 @@ mod tests {
assert!(rendered.contains("desk-left · volume · cc ch1 #49"));
}
#[test]
fn configuration_editor_submits_valid_input_and_cancel_has_no_side_effect() {
struct EditingClient {
snapshot: MixerSnapshot,
edits: Arc<Mutex<Vec<ConfigurationEdit>>>,
}
impl MixerClient for EditingClient {
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
Ok(self.snapshot.clone())
}
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 edit_configuration(
&mut self,
edit: ConfigurationEdit,
expected_revision: u64,
) -> io::Result<MixerSnapshot> {
assert_eq!(expected_revision, 0);
self.edits.lock().unwrap().push(edit);
self.snapshot.configuration.revision += 1;
self.snapshot.configuration.dirty = true;
Ok(self.snapshot.clone())
}
}
let edits = Arc::new(Mutex::new(Vec::new()));
let mut app = LiveTui::new(EditingClient {
snapshot: DemoClient::default().view(),
edits: Arc::clone(&edits),
})
.unwrap();
app.handle_key_event(press(KeyCode::Char('2')));
app.handle_key_event(press(KeyCode::Char('g')));
for character in "comms|Communications|browser,music".chars() {
app.handle_key_event(press(KeyCode::Char(character)));
}
app.handle_key_event(press(KeyCode::Enter));
assert_eq!(app.snapshot.configuration.revision, 1);
assert_eq!(
edits.lock().unwrap().as_slice(),
&[ConfigurationEdit::Group {
existing: false,
id: "comms".into(),
label: "Communications".into(),
members: vec!["browser".into(), "music".into()],
}]
);
app.handle_key_event(press(KeyCode::Char('a')));
for character in "discarded".chars() {
app.handle_key_event(press(KeyCode::Char(character)));
}
app.handle_key_event(press(KeyCode::Esc));
assert_eq!(edits.lock().unwrap().len(), 1);
assert!(app.editor.is_none());
}
#[test]
fn device_status_summaries_include_recovery_actions_and_errors() {
let ambiguous = MidiDevice {