From f01771568b035c20244bd53ef92cc092020fbb9e Mon Sep 17 00:00:00 2001 From: Miguel Palhas Date: Sat, 22 Aug 2026 13:08:08 +0100 Subject: [PATCH] refactor(maestro): make the TUI dispatch a reducer over effects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dispatch was `async fn -> ()` with reqwest calls and task spawns inlined, so it could not report intent and the spawn, kill and attach arms had no test. It now returns Vec and App::run performs them. Two bugs the old shape produced, both fixed and covered: - The toast overlay could not be dismissed. handle_overlay_input returned Pass for Toast(_) and nothing cleared it, so "spawn failed: ..." stayed until another overlay replaced it. It now clears and still returns Pass, so the keystroke does its normal job instead of being eaten. - Closing a tab leaked its emulator. Only submit_kill released one, so a closed tab's WebSocket task and vt100 parser outlived it forever. close_tab now reports the session it dropped — and holds onto it when another tab still shows the same one. AppState::overlay is private behind show_overlay/dismiss_overlay/toast. Four sites poked the field directly; that is why the toast bug existed. Co-Authored-By: Claude Opus 5 (1M context) --- crates/maestro-tui/src/app.rs | 355 ++++++++++++++++++++++--------- crates/maestro-tui/src/render.rs | 2 +- crates/maestro-tui/src/state.rs | 78 ++++++- 3 files changed, 332 insertions(+), 103 deletions(-) diff --git a/crates/maestro-tui/src/app.rs b/crates/maestro-tui/src/app.rs index 52e8c9b..3610387 100644 --- a/crates/maestro-tui/src/app.rs +++ b/crates/maestro-tui/src/app.rs @@ -66,6 +66,18 @@ impl std::fmt::Debug for App { } } +/// Something a keystroke decided to do that reaches outside `AppState`. +/// +/// `dispatch` returns these instead of performing them, so every arm is +/// assertable without a daemon on the other end. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Effect { + Attach(Uuid), + Spawn(CreateSessionRequest), + Kill(Uuid), + Forward { id: Uuid, bytes: Vec }, +} + impl App { pub fn new(cfg: TuiConfig, catalog: CatalogStore, daemon: DaemonClient) -> Self { let chord_timeout = cfg.chord_timeout; @@ -119,7 +131,9 @@ impl App { }; // Overlay intercept first. - if self.handle_overlay_input(&key).await == OverlayDecision::Consumed { + let (decision, effects) = self.handle_overlay_input(&key); + self.perform(effects).await; + if decision == OverlayDecision::Consumed { return Ok(false); } @@ -131,52 +145,87 @@ impl App { if matches!(act, Action::Quit) { return Ok(true); } - self.dispatch(act).await; + let effects = self.dispatch(act); + self.perform(effects).await; } else if self.state.mode == Mode::Insert && matches!(self.state.focus, Focus::Pane) { - self.forward_to_session(&key).await; + if let Some(effect) = self.forward_to_session(&key) { + self.perform(vec![effect]).await; + } } Ok(false) } } } - async fn handle_overlay_input(&mut self, key: &InputKey) -> OverlayDecision { - use crate::overlays::SpawnInputResult; - match self.state.overlay.clone() { - Some(OverlayKind::Spawn) => { - match self.spawn.on_input(key) { - SpawnInputResult::Consumed => {} - SpawnInputResult::Cancel => { - self.state.overlay = None; - } - SpawnInputResult::Submit => { - self.submit_spawn().await; + /// Carry out what `dispatch` decided. The only place in `App` that talks to + /// the daemon. + async fn perform(&mut self, effects: Vec) { + for effect in effects { + match effect { + Effect::Attach(id) => self.attach(id), + Effect::Spawn(req) => self.submit_spawn(req).await, + Effect::Kill(id) => self.submit_kill(id).await, + Effect::Forward { id, bytes } => { + if let Some(handle) = self.emulators.get(id) { + let _ = handle.tx.send(SessionInput::Bytes(bytes)).await; } } - OverlayDecision::Consumed } - Some(OverlayKind::KillConfirm(id)) => match key { - InputKey::Char { c: 'y', .. } => { - self.state.overlay = None; - self.submit_kill(id).await; - OverlayDecision::Consumed - } - InputKey::Char { c: 'n', .. } | InputKey::Esc => { - self.state.overlay = None; - OverlayDecision::Consumed - } - _ => OverlayDecision::Consumed, - }, - Some(OverlayKind::Help) => { - self.state.overlay = None; - OverlayDecision::Consumed - } - Some(OverlayKind::Toast(_)) | None => OverlayDecision::Pass, } } - async fn dispatch(&mut self, act: Action) { + fn handle_overlay_input(&mut self, key: &InputKey) -> (OverlayDecision, Vec) { + use crate::overlays::SpawnInputResult; + match self.state.overlay().cloned() { + Some(OverlayKind::Spawn) => { + let mut effects = Vec::new(); + match self.spawn.on_input(key) { + SpawnInputResult::Consumed => {} + SpawnInputResult::Cancel => { + self.state.dismiss_overlay(); + } + SpawnInputResult::Submit => { + effects.push(Effect::Spawn(CreateSessionRequest { + cwd: std::path::PathBuf::from(self.spawn.cwd.clone()), + command: self.spawn.command.clone(), + env: Default::default(), + metadata: Default::default(), + worktree: None, + })); + } + } + (OverlayDecision::Consumed, effects) + } + Some(OverlayKind::KillConfirm(id)) => match key { + InputKey::Char { c: 'y', .. } => { + self.state.dismiss_overlay(); + (OverlayDecision::Consumed, vec![Effect::Kill(id)]) + } + InputKey::Char { c: 'n', .. } | InputKey::Esc => { + self.state.dismiss_overlay(); + (OverlayDecision::Consumed, Vec::new()) + } + _ => (OverlayDecision::Consumed, Vec::new()), + }, + Some(OverlayKind::Help) => { + self.state.dismiss_overlay(); + (OverlayDecision::Consumed, Vec::new()) + } + // A toast is informational: clear it, but let the keystroke go on + // and do its normal job rather than being swallowed. + Some(OverlayKind::Toast(_)) => { + self.state.dismiss_overlay(); + (OverlayDecision::Pass, Vec::new()) + } + None => (OverlayDecision::Pass, Vec::new()), + } + } + + /// Fold a resolved action into `AppState` and report anything it wants done + /// outside it. Deliberately sync and side-effect-free. + fn dispatch(&mut self, act: Action) -> Vec { + let mut effects = Vec::new(); match act { Action::Noop | Action::Quit => {} Action::EnterInsert => self.state.mode = Mode::Insert, @@ -198,7 +247,11 @@ impl App { self.state.focus = Focus::Sidebar; } Action::NewTab => self.state.new_tab(), - Action::CloseTab => self.state.close_tab(), + Action::CloseTab => { + if let Some(sid) = self.state.close_tab() { + self.release_session(sid); + } + } Action::NextTab => self.state.next_tab(), Action::PrevTab => self.state.prev_tab(), Action::GotoTab(n) => self.state.goto_tab(n), @@ -207,7 +260,7 @@ impl App { self.help = HelpOverlay { lines: render_help_lines(&self.cfg), }; - self.state.overlay = Some(OverlayKind::Help); + self.state.show_overlay(OverlayKind::Help); } Action::OpenSpawnModal => { self.spawn = SpawnModal { @@ -215,31 +268,42 @@ impl App { command: String::new(), focused_field: Default::default(), }; - self.state.overlay = Some(OverlayKind::Spawn); + self.state.show_overlay(OverlayKind::Spawn); } Action::AttachHighlighted | Action::ToggleAttachHighlighted => { if let Some(sid) = self.pick_sidebar_target() { - if self.emulators.get(sid).is_none() { - match self.daemon.attach_url(sid) { - Ok(ws_url) => { - let handle = SessionTask::spawn(ws_url, 24, 80); - self.emulators.insert(sid, handle); - } - Err(e) => { - self.state.overlay = - Some(OverlayKind::Toast(format!("attach failed: {e}"))); - } - } - } + effects.push(Effect::Attach(sid)); self.state.attach_to_focused(sid); } } Action::KillHighlighted => { if let Some(sid) = self.pick_sidebar_target() { - self.state.overlay = Some(OverlayKind::KillConfirm(sid)); + self.state.show_overlay(OverlayKind::KillConfirm(sid)); } } } + effects + } + + /// Open a stream for `sid` if one isn't already running. + fn attach(&mut self, sid: Uuid) { + if self.emulators.get(sid).is_some() { + return; + } + match self.daemon.attach_url(sid) { + Ok(ws_url) => { + let handle = SessionTask::spawn(ws_url, 24, 80); + self.emulators.insert(sid, handle); + } + Err(e) => self.state.toast(format!("attach failed: {e}")), + } + } + + /// Tear down the emulator for `sid`, aborting its WebSocket task and + /// dropping its vt100 parser. + fn release_session(&mut self, sid: Uuid) { + self.emulators.remove(sid); + self.last_sent_size.remove(&sid); } /// Return the session under the sidebar highlight, falling back to the @@ -252,13 +316,11 @@ impl App { snap.sessions.first().map(|s| s.id) } - async fn forward_to_session(&mut self, key: &InputKey) { - let Some(sid) = self.state.active_tab().pane else { - return; - }; - let Some(handle) = self.emulators.get(sid) else { - return; - }; + /// Encode a keystroke for the focused pane. `None` when there is nothing + /// attached to send it to. + fn forward_to_session(&mut self, key: &InputKey) -> Option { + let sid = self.state.active_tab().pane?; + self.emulators.get(sid)?; let bytes = match key { InputKey::Char { c, ctrl, alt, .. } => { let mut out = Vec::with_capacity(8); @@ -282,37 +344,24 @@ impl App { InputKey::Down => b"\x1b[B".to_vec(), InputKey::Right => b"\x1b[C".to_vec(), InputKey::Left => b"\x1b[D".to_vec(), - InputKey::Mouse { .. } => return, + InputKey::Mouse { .. } => return None, }; - let _ = handle.tx.send(SessionInput::Bytes(bytes)).await; + Some(Effect::Forward { id: sid, bytes }) } - async fn submit_spawn(&mut self) { - let cwd = std::path::PathBuf::from(self.spawn.cwd.clone()); - let req = CreateSessionRequest { - cwd, - command: self.spawn.command.clone(), - env: Default::default(), - metadata: Default::default(), - worktree: None, - }; + async fn submit_spawn(&mut self, req: CreateSessionRequest) { match self.daemon.create_session(&req).await { - Ok(_) => self.state.overlay = None, - Err(e) => { - self.state.overlay = Some(OverlayKind::Toast(format!("spawn failed: {e}"))); + Ok(_) => { + self.state.dismiss_overlay(); } + Err(e) => self.state.toast(format!("spawn failed: {e}")), } } async fn submit_kill(&mut self, sid: Uuid) { match self.daemon.kill_session(sid).await { - Ok(()) => { - self.emulators.remove(sid); - self.last_sent_size.remove(&sid); - } - Err(e) => { - self.state.overlay = Some(OverlayKind::Toast(format!("kill failed: {e}"))); - } + Ok(()) => self.release_session(sid), + Err(e) => self.state.toast(format!("kill failed: {e}")), } } @@ -432,42 +481,152 @@ mod tests { ) } - #[tokio::test] - async fn enter_insert_then_leave() { + #[test] + fn enter_insert_then_leave() { let mut app = make_app(); assert_eq!(app.state.mode, Mode::Normal); - app.dispatch(Action::EnterInsert).await; + app.dispatch(Action::EnterInsert); assert_eq!(app.state.mode, Mode::Insert); - app.dispatch(Action::LeaveInsert).await; + app.dispatch(Action::LeaveInsert); assert_eq!(app.state.mode, Mode::Normal); } - #[tokio::test] - async fn new_tab_action_extends_tabs() { + #[test] + fn new_tab_action_extends_tabs() { let mut app = make_app(); - app.dispatch(Action::NewTab).await; - app.dispatch(Action::NewTab).await; + app.dispatch(Action::NewTab); + app.dispatch(Action::NewTab); assert_eq!(app.state.tabs.len(), 3); - app.dispatch(Action::CloseTab).await; + app.dispatch(Action::CloseTab); assert_eq!(app.state.tabs.len(), 2); } - #[tokio::test] - async fn show_help_opens_overlay() { + #[test] + fn show_help_opens_overlay() { let mut app = make_app(); - app.dispatch(Action::ShowHelp).await; - assert!(matches!(app.state.overlay, Some(OverlayKind::Help))); + app.dispatch(Action::ShowHelp); + assert!(matches!(app.state.overlay(), Some(OverlayKind::Help))); } - #[tokio::test] - async fn open_spawn_modal_sets_overlay() { + #[test] + fn open_spawn_modal_sets_overlay() { let mut app = make_app(); - app.dispatch(Action::OpenSpawnModal).await; - assert!(matches!(app.state.overlay, Some(OverlayKind::Spawn))); + app.dispatch(Action::OpenSpawnModal); + assert!(matches!(app.state.overlay(), Some(OverlayKind::Spawn))); } - #[tokio::test] - async fn kill_highlighted_opens_confirm() { + /// Seed the catalog with one session and highlight it. + fn app_with_highlighted_session(sid: Uuid) -> App { + use chrono::Utc; + use maestro_protocol::{CatalogEvent, Session, SessionStatus}; + let mut app = make_app(); + app.catalog.apply_event(CatalogEvent::Snapshot { + sessions: vec![Session { + id: sid, + command: "bash".into(), + cwd: std::path::PathBuf::from("/"), + env: Default::default(), + metadata: Default::default(), + status: SessionStatus::Running, + created_at: Utc::now(), + foreground: None, + activity: Default::default(), + last_activity_at: Utc::now(), + current_cwd: None, + }], + }); + app.dispatch(Action::SidebarNext); + app + } + + #[test] + fn attach_highlighted_asks_for_an_attach() { + let sid = Uuid::from_u128(11); + let mut app = app_with_highlighted_session(sid); + assert_eq!( + app.dispatch(Action::AttachHighlighted), + vec![Effect::Attach(sid)] + ); + assert_eq!(app.state.active_tab().pane, Some(sid)); + } + + #[test] + fn confirming_a_kill_asks_for_the_kill() { + let sid = Uuid::from_u128(12); + let mut app = app_with_highlighted_session(sid); + app.dispatch(Action::KillHighlighted); + + let (decision, effects) = app.handle_overlay_input(&InputKey::Char { + c: 'y', + ctrl: false, + alt: false, + shift: false, + }); + assert_eq!(decision, OverlayDecision::Consumed); + assert_eq!(effects, vec![Effect::Kill(sid)]); + assert!(app.state.overlay().is_none()); + } + + #[test] + fn declining_a_kill_asks_for_nothing() { + let sid = Uuid::from_u128(13); + let mut app = app_with_highlighted_session(sid); + app.dispatch(Action::KillHighlighted); + + let (decision, effects) = app.handle_overlay_input(&InputKey::Esc); + assert_eq!(decision, OverlayDecision::Consumed); + assert!(effects.is_empty()); + assert!(app.state.overlay().is_none()); + } + + #[test] + fn submitting_the_spawn_modal_carries_the_typed_fields() { + let mut app = make_app(); + app.dispatch(Action::OpenSpawnModal); + app.spawn.cwd = "/srv/work".into(); + app.spawn.command = "claude".into(); + app.spawn.focused_field = crate::overlays::SpawnField::Submit; + + let (_, effects) = app.handle_overlay_input(&InputKey::Enter); + match effects.as_slice() { + [Effect::Spawn(req)] => { + assert_eq!(req.cwd, std::path::PathBuf::from("/srv/work")); + assert_eq!(req.command, "claude"); + } + other => panic!("expected one Spawn effect, got {other:?}"), + } + } + + /// Regression: `Toast` returned `Pass` and nothing ever cleared it, so a + /// failure message stayed on screen until another overlay replaced it. + #[test] + fn a_toast_is_dismissed_by_the_next_key_without_eating_it() { + let mut app = make_app(); + app.state.toast("spawn failed: nope"); + + let (decision, effects) = app.handle_overlay_input(&InputKey::Char { + c: 'j', + ctrl: false, + alt: false, + shift: false, + }); + assert_eq!( + decision, + OverlayDecision::Pass, + "the keystroke should still reach the keymap" + ); + assert!(effects.is_empty()); + assert!(app.state.overlay().is_none(), "the toast must be gone"); + } + + #[test] + fn forwarding_is_a_no_op_without_an_attached_pane() { + let mut app = make_app(); + assert!(app.forward_to_session(&InputKey::Enter).is_none()); + } + + #[test] + fn kill_highlighted_opens_confirm() { use chrono::Utc; use maestro_protocol::{CatalogEvent, Session, SessionStatus}; let mut app = make_app(); @@ -488,7 +647,7 @@ mod tests { current_cwd: None, }], }); - app.dispatch(Action::KillHighlighted).await; - assert!(matches!(app.state.overlay, Some(OverlayKind::KillConfirm(s)) if s == sid)); + app.dispatch(Action::KillHighlighted); + assert!(matches!(app.state.overlay(), Some(OverlayKind::KillConfirm(s)) if *s == sid)); } } diff --git a/crates/maestro-tui/src/render.rs b/crates/maestro-tui/src/render.rs index 2f5e5a0..0bb2c75 100644 --- a/crates/maestro-tui/src/render.rs +++ b/crates/maestro-tui/src/render.rs @@ -137,7 +137,7 @@ pub fn draw(f: &mut Frame, inputs: RenderInputs<'_>) -> RegionMap { // always see the current mode + key hints. render_status_bar(f, status_area, inputs.state); - match &inputs.state.overlay { + match inputs.state.overlay() { Some(OverlayKind::Spawn) => { inputs.spawn.render(f, area); map.modal = Some(area); diff --git a/crates/maestro-tui/src/state.rs b/crates/maestro-tui/src/state.rs index bf19103..4e9e32f 100644 --- a/crates/maestro-tui/src/state.rs +++ b/crates/maestro-tui/src/state.rs @@ -39,7 +39,11 @@ pub struct AppState { pub mode: Mode, pub sidebar_visible: bool, pub sidebar_highlight: Option, - pub overlay: Option, + /// Private: every transition goes through [`AppState::show_overlay`], + /// [`AppState::dismiss_overlay`] or [`AppState::toast`]. Poking the field + /// from four call sites is what left a toast on screen with no way to + /// clear it. + overlay: Option, } impl Default for AppState { @@ -64,6 +68,24 @@ impl AppState { } } + pub fn overlay(&self) -> Option<&OverlayKind> { + self.overlay.as_ref() + } + + pub fn show_overlay(&mut self, kind: OverlayKind) { + self.overlay = Some(kind); + } + + /// Clear whatever overlay is up. Returns true if one was showing. + pub fn dismiss_overlay(&mut self) -> bool { + self.overlay.take().is_some() + } + + /// Surface a transient message. Replaces any overlay currently up. + pub fn toast(&mut self, message: impl Into) { + self.overlay = Some(OverlayKind::Toast(message.into())); + } + pub fn active_tab(&self) -> &Tab { &self.tabs[self.active_tab_idx] } @@ -83,14 +105,21 @@ impl AppState { /// Drop the active tab. No-op if it's the only one — there must always /// be at least one tab. - pub fn close_tab(&mut self) { + /// + /// Returns the session that tab was showing, if any, so the caller can + /// release its emulator. Without that the tab's WebSocket task and vt100 + /// parser outlive the tab forever. + pub fn close_tab(&mut self) -> Option { if self.tabs.len() <= 1 { - return; + return None; } - self.tabs.remove(self.active_tab_idx); + let closed = self.tabs.remove(self.active_tab_idx); if self.active_tab_idx >= self.tabs.len() { self.active_tab_idx = self.tabs.len() - 1; } + // Only release it if no other tab still shows the same session. + let still_shown = self.tabs.iter().any(|t| t.pane == closed.pane); + closed.pane.filter(|_| !still_shown) } pub fn next_tab(&mut self) { @@ -277,4 +306,45 @@ mod tests { // Doesn't force focus back; sidebar shown but focus stays where it was. assert_eq!(state.focus, Focus::Pane); } + + /// The emulator leak: a closed tab's session must come back so the caller + /// can abort its WebSocket task. + #[test] + fn close_tab_reports_the_session_it_dropped() { + let mut state = AppState::new(); + let sid = Uuid::from_u128(3); + state.new_tab(); + state.active_tab_mut().pane = Some(sid); + + assert_eq!(state.close_tab(), Some(sid)); + } + + /// ...but not while another tab still shows it. + #[test] + fn close_tab_keeps_a_session_another_tab_still_shows() { + let mut state = AppState::new(); + let sid = Uuid::from_u128(4); + state.active_tab_mut().pane = Some(sid); + state.new_tab(); + state.active_tab_mut().pane = Some(sid); + + assert_eq!(state.close_tab(), None); + } + + #[test] + fn close_tab_is_a_no_op_on_the_last_tab() { + let mut state = AppState::new(); + state.active_tab_mut().pane = Some(Uuid::from_u128(5)); + assert_eq!(state.close_tab(), None); + assert_eq!(state.tabs.len(), 1); + } + + #[test] + fn dismiss_overlay_reports_whether_one_was_showing() { + let mut state = AppState::new(); + assert!(!state.dismiss_overlay()); + state.toast("boom"); + assert!(state.dismiss_overlay()); + assert!(state.overlay().is_none()); + } }