From 7d58204ab1c957b23a53e9cfadf3ea6eb6601809 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 15 Oct 2026 03:38:00 +0200 Subject: [PATCH] fix(M7.3): tolerate disconnected clients and targets Treat MIDI input for offline or read-only mixer objects as a nonfatal no-op. Start the buffered TUI with a local disconnected snapshot, retain confirmed state across transport failures, and reconnect in the background. 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 MIDI and volume_lib feature matrix. --- architecture.md | 8 +- fader_master/src/live.rs | 25 ++++++- fader_master/src/tui_client.rs | 1 + fader_master/tests/live_mixer.rs | 30 ++++++++ task.md | 10 ++- tui/src/lib.rs | 122 ++++++++++++++++++++++++++++--- 6 files changed, 176 insertions(+), 20 deletions(-) diff --git a/architecture.md b/architecture.md index d0a7aaa..ffe24ce 100644 --- a/architecture.md +++ b/architecture.md @@ -149,7 +149,7 @@ use `volume_mode = "absolute"` only. Group dispatch is best effort because audio APIs do not offer a transaction across arbitrary streams. Track results per stream, keep successful changes, show failures, and refresh observations. Do not pretend to roll back atomically. Backend workers preserve server write ordering per stream and per property; volume and mute can be tracked independently. -Default startup, reconnect, profile switching, and new-stream discovery adopt live state without writes. A deliberate command while an application is offline stores pending intent for display but is not replayed on launch by default. An explicit `restore` policy may apply saved object intents to newly matched streams after full discovery, with validated bounds and visible status; conflicting restored targets use documented profile order, last matching target wins. Persist that order and test it. Never resurrect backend handles or pending operation IDs from disk. +Default startup, reconnect, profile switching, and new-stream discovery adopt live state without writes. Live MIDI/TUI input against an offline or read-only target is a visible, nonfatal no-op and is never replayed when the target appears. A future explicit saved-intent workflow may retain a deliberate offline command for display, but only an explicit `restore` policy may apply saved object intents to newly matched streams after full discovery, with validated bounds and visible status; conflicting restored targets use documented profile order, last matching target wins. Persist that order and test it. Never resurrect backend handles or pending operation IDs from disk. ## Server state transitions and concurrency @@ -306,7 +306,11 @@ queues work without waiting for a socket response. Pending volume work is latest-value-per-object; mute presses remain a bounded FIFO. Confirmed snapshots replace the local base and retain optimistic overlays until observation settles them. Poll quickly while writes are pending, slowly while idle, and resnapshot -then retry once after a stale edit. +then retry once after a stale edit. Start immediately with a disconnected +placeholder when the socket is absent, retain the last confirmed items across +transport failures, surface the connection error inside the terminal, and keep +retrying so starting or restarting the server reconnects without restarting the +TUI. Terminal colors come from semantic theme palettes rather than renderer-local literals. The built-ins are Default, Dracula, Nord, Gruvbox Dark, Catppuccin diff --git a/fader_master/src/live.rs b/fader_master/src/live.rs index 130f0cb..ba5199b 100644 --- a/fader_master/src/live.rs +++ b/fader_master/src/live.rs @@ -319,6 +319,9 @@ impl LiveMixerState { .get(&fader) .cloned() .ok_or_else(|| LiveMixerError::UnknownFader(fader.clone()))?; + if self.resolve(&configured.target)?.is_empty() { + return Ok(Vec::new()); + } let key = (surface, fader); let target = if configured.pickup { let needs_arming = self @@ -347,12 +350,21 @@ impl LiveMixerState { } else { gain }; - let commands = self.set_volume( + let commands = match self.set_volume( configured.target.clone(), target, self.reducer.revision().get(), sequence, - )?; + ) { + Ok(commands) => commands, + Err( + LiveMixerError::OfflineObject { .. } + | LiveMixerError::ReadOnlyObject { .. }, + ) => { + return Ok(Vec::new()); + } + Err(error) => return Err(error), + }; self.rearm_other_pickups(&key, &configured.target, target); Ok(commands) } @@ -362,7 +374,14 @@ impl LiveMixerState { .get(&fader) .cloned() .ok_or(LiveMixerError::UnknownFader(fader))?; - self.toggle_mute(configured.target, self.reducer.revision().get(), sequence) + match self.toggle_mute(configured.target, self.reducer.revision().get(), sequence) { + Ok(commands) => Ok(commands), + Err( + LiveMixerError::OfflineObject { .. } + | LiveMixerError::ReadOnlyObject { .. }, + ) => Ok(Vec::new()), + Err(error) => Err(error), + } } } } diff --git a/fader_master/src/tui_client.rs b/fader_master/src/tui_client.rs index 3267837..f17bfed 100644 --- a/fader_master/src/tui_client.rs +++ b/fader_master/src/tui_client.rs @@ -45,6 +45,7 @@ impl IpcMixerClient { revision: snapshot.revision, backend: snapshot.backend, status: snapshot.status, + error: None, items: snapshot .objects .into_iter() diff --git a/fader_master/tests/live_mixer.rs b/fader_master/tests/live_mixer.rs index 578d72c..ded4b2b 100644 --- a/fader_master/tests/live_mixer.rs +++ b/fader_master/tests/live_mixer.rs @@ -75,6 +75,36 @@ fn observations_publish_configured_objects_and_offline_state() { assert!(snapshot.revision > 0); } +#[test] +fn midi_input_for_an_offline_application_is_a_nonfatal_noop() { + let profile = + Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap(); + let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap(); + let surface = SurfaceId::new("apc-mini").unwrap(); + let fader = FaderId::new("browser-fader").unwrap(); + + assert!( + state + .midi_intent( + MidiIntent::AbsoluteVolume { + surface: surface.clone(), + fader: fader.clone(), + gain: gain(0.75), + }, + 1, + ) + .unwrap() + .is_empty() + ); + assert!( + state + .midi_intent(MidiIntent::ToggleMute { surface, fader }, 2) + .unwrap() + .is_empty() + ); + assert_eq!(state.snapshot().objects[1].detail, "offline"); +} + #[test] fn client_volume_is_pending_until_correlated_readback() { let mut state = ready_state(); diff --git a/task.md b/task.md index 091ab38..0f227f4 100644 --- a/task.md +++ b/task.md @@ -196,8 +196,10 @@ Dependencies: M3; M4 for full end-to-end acceptance. tolerance and crossing activation, external-change/reconnect resets, competing surfaces, and above-range endpoint pickup. The Arch profile routes APC MINI CC 48/49/50/56 and notes 64/65/66/98 to Music, Browser, Media, and - the default output master. Keep this item open until pickup state is - published to the TUI and profile-switch rearming is implemented. + the default output master. Input targeting an offline/read-only object is a + nonfatal no-op, leaving other targets and the server available. Keep this item + open until pickup state is published to the TUI and profile-switch rearming is + implemented. - [ ] **M5.5 Physical smoke test:** one controller -> server -> application audio; then two controllers with overlapping MIDI message numbers. Acceptance: correct applications respond, bindings persist, and USB loss leaves server running. Record controller/firmware and environment. M5.1 verification on 2026-10-14: nine decoder/router/transport tests pass with @@ -234,7 +236,9 @@ Dependencies: M3, M2; may proceed after the fake-adapter slice. - [x] **M7.3 Client resync:** full snapshot on attach/lag and revision checks for edits. Tests: TUI exit never stops the server; reconnect shows current observations; concurrent clients cannot overwrite each other's edits unnoticed. Each request receives a complete current snapshot; stale edit revisions trigger a background resnapshot and one retry. The TUI's IPC worker exits - independently of the server. Competing edits from one attached revision prove + independently of the server, starts with a disconnected placeholder when the + socket is absent, retains the last confirmed view during failures, and retries + until a server appears again. Competing edits from one attached revision prove that only the first is accepted and that a lagging client obtains the newer complete snapshot before retrying. - [x] **M7.4 Buffered interaction:** isolate blocking IPC and native audio diff --git a/tui/src/lib.rs b/tui/src/lib.rs index 9fe2901..8635f34 100644 --- a/tui/src/lib.rs +++ b/tui/src/lib.rs @@ -61,6 +61,8 @@ pub struct MixerSnapshot { pub revision: u64, pub backend: String, pub status: String, + /// Client/transport failure while the last confirmed items remain visible. + pub error: Option, pub items: Vec, } @@ -109,7 +111,13 @@ impl BufferedMixerClient { where C: MixerClient + Send + 'static, { - let initial = client.snapshot()?; + let initial = MixerSnapshot { + revision: 0, + backend: "local IPC".to_owned(), + status: "waiting for server".to_owned(), + error: None, + items: Vec::new(), + }; let shared = Arc::new(( Mutex::new(BufferedState { snapshot: initial.clone(), @@ -142,12 +150,10 @@ impl BufferedMixerClient { impl MixerClient for BufferedMixerClient { fn snapshot(&mut self) -> io::Result { self.with_state(|state| { - if let Some(error) = state.error.take() { - Err(io::Error::other(error)) - } else { - Ok(state.snapshot.clone()) - } - })? + let mut snapshot = state.snapshot.clone(); + snapshot.error.clone_from(&state.error); + snapshot + }) } fn set_volume( @@ -232,13 +238,18 @@ fn client_loop( ) where C: MixerClient, { + let mut first_refresh = true; loop { let action = { let (state, wake) = &**shared; let Ok(mut state) = state.lock() else { return; }; - if !state.shutdown && state.mute_work.is_empty() && state.volume_work.is_empty() { + if !first_refresh + && !state.shutdown + && state.mute_work.is_empty() + && state.volume_work.is_empty() + { let refresh = if state.desired_volumes.is_empty() && state.desired_mutes.is_empty() { CLIENT_IDLE_REFRESH @@ -253,7 +264,10 @@ fn client_loop( if state.shutdown { return; } - if let Some(id) = state.mute_work.pop_front() { + if first_refresh { + first_refresh = false; + BufferedAction::Refresh + } else if let Some(id) = state.mute_work.pop_front() { BufferedAction::ToggleMute { id } } else if let Some((id, gain)) = state.volume_work.pop_first() { BufferedAction::SetVolume { id, gain } @@ -445,6 +459,7 @@ impl LiveTui { .items .get(self.selected) .map(|item| item.id.clone()); + self.client_error.clone_from(&snapshot.error); self.snapshot = snapshot; self.selected = selected_id .and_then(|id| self.snapshot.items.iter().position(|item| item.id == id)) @@ -452,7 +467,6 @@ impl LiveTui { self.selected .min(self.snapshot.items.len().saturating_sub(1)) }); - self.client_error = None; } fn draw(&self, frame: &mut Frame) { @@ -702,6 +716,7 @@ impl DemoClient { revision: self.revision, backend: "demo".into(), status: "preview".into(), + error: None, items: vec![MixerItem { id: MixerObjectId { kind: MixerObjectKind::Application, @@ -899,6 +914,19 @@ mod tests { } } + fn wait_for_items(client: &mut impl MixerClient) -> MixerSnapshot { + let deadline = Instant::now() + Duration::from_secs(1); + loop { + if let Ok(snapshot) = client.snapshot() + && !snapshot.items.is_empty() + { + return snapshot; + } + assert!(Instant::now() < deadline, "client did not publish items"); + thread::sleep(Duration::from_millis(5)); + } + } + #[test] fn buffered_client_keeps_redraw_nonblocking_and_coalesces_volume() { let writes = Arc::new(Mutex::new(Vec::new())); @@ -908,7 +936,7 @@ mod tests { mutes: Arc::new(Mutex::new(Vec::new())), }) .unwrap(); - let id = client.snapshot().unwrap().items[0].id.clone(); + let id = wait_for_items(&mut client).items[0].id.clone(); client .set_volume(id.clone(), 0.1, 0) @@ -947,7 +975,7 @@ mod tests { mutes: Arc::clone(&mutes), }) .unwrap(); - let id = client.snapshot().unwrap().items[0].id.clone(); + let id = wait_for_items(&mut client).items[0].id.clone(); let first = client .toggle_mute(id.clone(), 0) @@ -963,6 +991,76 @@ mod tests { assert_eq!(mutes.lock().unwrap().as_slice(), &[true, false]); } + #[test] + fn buffered_client_starts_disconnected_and_recovers_in_the_background() { + struct RecoveringClient { + attempts: Arc>, + } + + impl MixerClient for RecoveringClient { + fn snapshot(&mut self) -> io::Result { + let mut attempts = self.attempts.lock().unwrap(); + *attempts += 1; + if *attempts == 1 { + thread::sleep(Duration::from_millis(100)); + return Err(io::Error::new( + io::ErrorKind::NotFound, + "server socket is not available", + )); + } + 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!() + } + } + + let attempts = Arc::new(Mutex::new(0)); + let started = Instant::now(); + let mut client = BufferedMixerClient::spawn(RecoveringClient { + attempts: Arc::clone(&attempts), + }) + .unwrap(); + assert!(started.elapsed() < Duration::from_millis(30)); + let initial = client.snapshot().unwrap(); + assert_eq!(initial.status, "waiting for server"); + assert!(initial.items.is_empty()); + + let deadline = Instant::now() + Duration::from_secs(2); + loop { + let snapshot = client.snapshot().unwrap(); + if snapshot.error.is_some() { + assert!(snapshot.items.is_empty()); + break; + } + assert!(Instant::now() < deadline, "client did not publish failure"); + thread::sleep(Duration::from_millis(10)); + } + loop { + let snapshot = client.snapshot().unwrap(); + if snapshot.error.is_none() && !snapshot.items.is_empty() { + break; + } + assert!(Instant::now() < deadline, "client did not reconnect"); + thread::sleep(Duration::from_millis(10)); + } + assert!(*attempts.lock().unwrap() >= 2); + } + #[test] fn buffered_action_resnapshots_and_retries_a_stale_revision() { struct RevisionClient {