diff --git a/crates/maestro-cli/src/sessions.rs b/crates/maestro-cli/src/sessions.rs index 5a2af60..2e3729a 100644 --- a/crates/maestro-cli/src/sessions.rs +++ b/crates/maestro-cli/src/sessions.rs @@ -74,7 +74,17 @@ fn print_session_table(out: &mut impl Write, sessions: &[Session], info: &Daemon sorted.sort_by_key(|s| s.created_at); if !info.hostname.is_empty() { - writeln!(out, "\n{}", info.hostname).ok(); + let warn = if maestro_protocol::is_compatible(&info.version) { + "" + } else { + " (protocol mismatch)" + }; + let version = if info.version.is_empty() { + String::new() + } else { + format!(" maestro {}{warn}", info.version) + }; + writeln!(out, "\n{}{version}", info.hostname).ok(); } writeln!( out, diff --git a/crates/maestro-daemon/src/local_api.rs b/crates/maestro-daemon/src/local_api.rs index 926e048..7326f0c 100644 --- a/crates/maestro-daemon/src/local_api.rs +++ b/crates/maestro-daemon/src/local_api.rs @@ -83,6 +83,16 @@ fn dir_error_status(code: &str) -> StatusCode { } } +/// HTTP status for a [`crate::session::SessionError`] code. Everything used to +/// collapse to 502, which reports a client mistake as a daemon failure. +fn session_error_status(code: &str) -> StatusCode { + match code { + "not_found" => StatusCode::NOT_FOUND, + "invalid_env" => StatusCode::BAD_REQUEST, + _ => StatusCode::BAD_GATEWAY, + } +} + /// Recent working dirs for the spawn form's recents picker (#26). async fn recent_dirs(State(s): State) -> Response { Json(crate::spawn_history::to_wire(s.manager.recent_dirs())).into_response() @@ -117,7 +127,7 @@ async fn create_session( Err(e) => { let info = e.to_error_info(); error_response( - StatusCode::BAD_GATEWAY, + session_error_status(&info.code), info.code.as_str(), info.message.as_str(), ) @@ -138,7 +148,7 @@ async fn kill_session(State(s): State, Path(id): Path) -> R Err(e) => { let info = e.to_error_info(); error_response( - StatusCode::BAD_GATEWAY, + session_error_status(&info.code), info.code.as_str(), info.message.as_str(), ) diff --git a/crates/maestro-daemon/src/panes.rs b/crates/maestro-daemon/src/panes.rs index d1a522d..1769025 100644 --- a/crates/maestro-daemon/src/panes.rs +++ b/crates/maestro-daemon/src/panes.rs @@ -5,7 +5,7 @@ //! forking a tmux server. [`Tmux`] is the production adapter; [`FakePanes`] is //! the one tests drive. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::Path; use std::sync::Mutex; @@ -24,6 +24,7 @@ pub trait Panes: std::fmt::Debug + Send + Sync + 'static { id: Uuid, cwd: &Path, command: &str, + session_env: &BTreeMap, sink_command: &str, ) -> Result<(), TmuxError>; @@ -46,9 +47,10 @@ impl Panes for Tmux { id: Uuid, cwd: &Path, command: &str, + session_env: &BTreeMap, sink_command: &str, ) -> Result<(), TmuxError> { - Tmux::new_session_piped(self, id, cwd, command, sink_command) + Tmux::new_session_piped(self, id, cwd, command, session_env, sink_command) } fn kill_session(&self, id: Uuid) -> Result<(), TmuxError> { @@ -96,13 +98,24 @@ pub enum Op { /// sequence property, so the tests that matter assert on this. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Call { - NewSessionPiped { id: Uuid, command: String }, + NewSessionPiped { + id: Uuid, + command: String, + env: BTreeMap, + }, KillSession(Uuid), ListSessions, PaneInfo(Uuid), - SendKeys { id: Uuid, bytes: Vec }, + SendKeys { + id: Uuid, + bytes: Vec, + }, PipePane(Uuid), - ResizeWindow { id: Uuid, cols: u16, rows: u16 }, + ResizeWindow { + id: Uuid, + cols: u16, + rows: u16, + }, } /// In-memory [`Panes`] for tests. @@ -181,12 +194,14 @@ impl Panes for FakePanes { id: Uuid, _cwd: &Path, command: &str, + session_env: &BTreeMap, _sink_command: &str, ) -> Result<(), TmuxError> { self.record( Call::NewSessionPiped { id, command: command.to_owned(), + env: session_env.clone(), }, Op::NewSessionPiped, )?; @@ -238,7 +253,7 @@ mod tests { let fake = FakePanes::new(); let id = Uuid::new_v4(); - fake.new_session_piped(id, Path::new("/tmp"), "bash", "cat >> /x") + fake.new_session_piped(id, Path::new("/tmp"), "bash", &BTreeMap::new(), "cat >> /x") .unwrap(); assert!(fake.is_live(id)); fake.kill_session(id).unwrap(); @@ -249,7 +264,8 @@ mod tests { vec![ Call::NewSessionPiped { id, - command: "bash".into() + command: "bash".into(), + env: BTreeMap::new(), }, Call::KillSession(id), ] @@ -263,7 +279,7 @@ mod tests { fake.fail(Op::NewSessionPiped, "boom"); assert!(fake - .new_session_piped(id, Path::new("/tmp"), "bash", "cat") + .new_session_piped(id, Path::new("/tmp"), "bash", &BTreeMap::new(), "cat") .is_err()); assert!( !fake.is_live(id), diff --git a/crates/maestro-daemon/src/pty.rs b/crates/maestro-daemon/src/pty.rs index e29a47c..e903e84 100644 --- a/crates/maestro-daemon/src/pty.rs +++ b/crates/maestro-daemon/src/pty.rs @@ -58,7 +58,9 @@ const READ_BUF_BYTES: usize = 4096; #[derive(Debug)] pub struct PtyBridge { fifo_path: PathBuf, - sender: broadcast::Sender>, + /// `None` once [`Self::seal`] has run: live subscribers see the channel + /// close, but the replay buffer stays readable. + sender: Option>>, replay: ReplayBuffer, /// Monotonic timestamp of the last non-empty read off the FIFO, bumped by /// `run_reader`. The activity watcher reads it to gauge PTY quiescence @@ -100,7 +102,7 @@ impl PtyBridge { }); Ok(Self { fifo_path, - sender, + sender: Some(sender), replay, last_activity, task, @@ -123,7 +125,14 @@ impl PtyBridge { /// Subscribe to live PTY frames. Use [`Self::subscribe_with_replay`] for /// new attaches that want the buffered scrollback first. pub fn subscribe(&self) -> broadcast::Receiver> { - self.sender.subscribe() + match &self.sender { + Some(tx) => tx.subscribe(), + None => { + let (tx, rx) = broadcast::channel(1); + drop(tx); + rx + } + } } /// Atomically snapshot the replay buffer and return a fresh subscriber @@ -134,10 +143,30 @@ impl PtyBridge { pub fn subscribe_with_replay(&self) -> (Vec, broadcast::Receiver>) { let guard = self.replay.lock_for_snapshot(); let snapshot = guard.snapshot(); - let rx = self.sender.subscribe(); + let rx = match &self.sender { + Some(tx) => tx.subscribe(), + // Sealed: hand back the scrollback plus a receiver that is already + // closed, so the client renders the final output and then sees the + // stream end rather than hanging. + None => { + let (tx, rx) = broadcast::channel(1); + drop(tx); + rx + } + }; drop(guard); (snapshot, rx) } + + /// Stop reading and close the live stream, keeping the replay buffer. + /// + /// Attached clients see the channel close — without that a `maestro attach` + /// sits in raw mode against a shell that has exited (NAP-226) — while the + /// buffered output survives for anyone who attaches later. + pub fn seal(&mut self) { + self.task.abort(); + self.sender = None; + } } impl Drop for PtyBridge { diff --git a/crates/maestro-daemon/src/session.rs b/crates/maestro-daemon/src/session.rs index b07fc72..f57fbb8 100644 --- a/crates/maestro-daemon/src/session.rs +++ b/crates/maestro-daemon/src/session.rs @@ -62,6 +62,8 @@ pub enum SessionError { Io(#[from] std::io::Error), #[error("session not found: {0}")] NotFound(Uuid), + #[error("invalid environment variable name: {0:?}")] + InvalidEnv(String), } impl SessionError { @@ -72,6 +74,7 @@ impl SessionError { SessionError::Sidecar(_) => "sidecar_failed", SessionError::Io(_) => "io_failed", SessionError::NotFound(_) => "not_found", + SessionError::InvalidEnv(_) => "invalid_env", }; ErrorInfo { code: code.into(), @@ -201,6 +204,12 @@ impl SessionManager { self.inner.sessions.lock().await.contains_key(&id) } + /// Current status of a session, or `None` if we do not know it. + pub async fn status(&self, id: Uuid) -> Option { + let sessions = self.inner.sessions.lock().await; + sessions.get(&id).map(|r| r.session.status) + } + /// Spawn a new session. On success returns the freshly-created `Session`. pub async fn create(&self, req: CreateSessionRequest) -> Result { let (effective_cwd, worktree_path, worktree_base_repo) = match &req.worktree { @@ -240,12 +249,21 @@ impl SessionManager { return Err(e.into()); } }; + let session_env = match sanitize_env(&req.env) { + Ok(env) => env, + Err(e) => { + let _ = std::fs::remove_file(&fifo_path); + self.rollback_worktree(&worktree_base_repo, &worktree_path); + return Err(e); + } + }; let spawned = { let tmux = self.inner.tmux.clone(); let cwd = effective_cwd.clone(); let command = req.command.clone(); let sink = pipe_pane_command(&fifo_path); - tmux_blocking(move || tmux.new_session_piped(id, &cwd, &command, &sink)).await + let env = session_env.clone(); + tmux_blocking(move || tmux.new_session_piped(id, &cwd, &command, &env, &sink)).await }; if let Err(e) = spawned { // `bridge` drops at the end of this block, closing the FIFO reader. @@ -341,13 +359,18 @@ impl SessionManager { /// Kill a session and remove its on-disk artifacts. The worktree is only /// pruned if the create request set `cleanup_on_kill: true`. + /// + /// This is also how an already-dead session is dismissed. tmux is only + /// asked to kill something it still has — calling `kill-session` on a + /// session tmux already lost fails, and that failure is not interesting. pub async fn kill(&self, id: Uuid) -> Result<(), SessionError> { let removed = { let mut sessions = self.inner.sessions.lock().await; sessions.remove(&id) }; let record = removed.ok_or(SessionError::NotFound(id))?; - cleanup_record(&self.inner, id, record, true).await; + let alive = record.session.status == SessionStatus::Running; + cleanup_record(&self.inner, id, record, alive).await; Ok(()) } @@ -444,9 +467,14 @@ impl SessionManager { Ok(adopted) } + /// Forward keystrokes to a session's pane. A dead session is read-only — + /// its pane is gone, so this is a no-op rather than a tmux failure the + /// client would have to interpret. pub async fn send_keys(&self, id: Uuid, bytes: &[u8]) -> Result<(), SessionError> { - if !self.has(id).await { - return Err(SessionError::NotFound(id)); + match self.status(id).await { + None => return Err(SessionError::NotFound(id)), + Some(SessionStatus::Dead) => return Ok(()), + Some(SessionStatus::Running) => {} } let tmux = self.inner.tmux.clone(); let bytes = bytes.to_vec(); @@ -455,9 +483,13 @@ impl SessionManager { .map_err(SessionError::Tmux) } + /// Resize a session's window. No-op for a dead session, as with + /// [`Self::send_keys`]. pub async fn resize(&self, id: Uuid, cols: u16, rows: u16) -> Result<(), SessionError> { - if !self.has(id).await { - return Err(SessionError::NotFound(id)); + match self.status(id).await { + None => return Err(SessionError::NotFound(id)), + Some(SessionStatus::Dead) => return Ok(()), + Some(SessionStatus::Running) => {} } let tmux = self.inner.tmux.clone(); tmux_blocking(move || tmux.resize_window(id, cols, rows)) @@ -471,6 +503,24 @@ impl SessionManager { /// milliseconds on a loaded host, and `send_keys` rides the per-keystroke hot /// path — running it inline would starve HTTP handlers, the events WS, the /// liveness watcher, and PTY readers (NAP-256). +/// Turn a request's environment into tmux `-e KEY=VAL` material. +/// +/// A key containing `=` or NUL would be parsed by tmux as a different +/// assignment than the caller wrote, so it is rejected rather than silently +/// reinterpreted. `BTreeMap` so the resulting argv is deterministic. +fn sanitize_env( + env: &std::collections::HashMap, +) -> Result, SessionError> { + let mut out = std::collections::BTreeMap::new(); + for (k, v) in env { + if k.is_empty() || k.contains('=') || k.contains('\0') || v.contains('\0') { + return Err(SessionError::InvalidEnv(k.clone())); + } + out.insert(k.clone(), v.clone()); + } + Ok(out) +} + async fn tmux_blocking(f: F) -> T where F: FnOnce() -> T + Send + 'static, @@ -488,13 +538,22 @@ async fn run_liveness_pass(inner: &Arc) { // nothing to reap and no reason to spawn a tmux subprocess (this also // avoids racing with the very first `new-session` that would otherwise // be competing to start the tmux server). + // Only sessions we still believe are running can transition; a session + // already marked Dead must not re-emit an update on every 2s tick. let known: Vec = { let sessions = inner.sessions.lock().await; if sessions.is_empty() { return; } - sessions.keys().copied().collect() + sessions + .iter() + .filter(|(_, r)| r.session.status == SessionStatus::Running) + .map(|(id, _)| *id) + .collect() }; + if known.is_empty() { + return; + } let live_ids = { let tmux = inner.tmux.clone(); @@ -510,7 +569,7 @@ async fn run_liveness_pass(inner: &Arc) { for id in known { if !live.contains(&id) { - reap_dead_session(inner, id).await; + mark_session_dead(inner, id).await; } } } @@ -524,8 +583,17 @@ async fn run_activity_pass(inner: &Arc) { if sessions.is_empty() { return; } - sessions.keys().copied().collect() + // A dead session has no pane to inspect; its last observed activity is + // kept as-is so the UI can still show what it was doing when it died. + sessions + .iter() + .filter(|(_, r)| r.session.status == SessionStatus::Running) + .map(|(id, _)| *id) + .collect() }; + if ids.is_empty() { + return; + } for id in ids { // The tmux pane lookup is a subprocess — keep it off the runtime worker @@ -580,19 +648,36 @@ async fn run_activity_pass(inner: &Arc) { } } -/// Remove a session whose tmux session is already gone: drop the in-memory -/// record, delete the sidecar + FIFO, clean up its worktree if requested, and -/// fire `SessionEvent::Removed`. No tmux kill — there is nothing left to kill. -async fn reap_dead_session(inner: &Arc, id: Uuid) { - let record = { +/// Mark a session whose tmux session has disappeared as [`SessionStatus::Dead`] +/// and announce it, keeping everything else intact. +/// +/// The record, its [`PtyBridge`] and its sidecar all survive, so a client can +/// still attach and read the replay buffer — the last thing a crashed agent +/// printed. Artifacts are only released when the operator dismisses the session +/// via [`SessionManager::kill`]. +/// +/// Dead sessions do not survive a daemon restart: [`SessionManager::recover`] +/// adopts only what tmux still holds. +async fn mark_session_dead(inner: &Arc, id: Uuid) { + let updated = { let mut sessions = inner.sessions.lock().await; - sessions.remove(&id) + match sessions.get_mut(&id) { + Some(record) if record.session.status == SessionStatus::Running => { + record.session.status = SessionStatus::Dead; + // Release anyone attached; the scrollback survives for a later + // attach. + record.bridge.seal(); + Some(record.session.clone()) + } + _ => None, + } }; - let Some(record) = record else { + let Some(session) = updated else { return; }; - tracing::info!(%id, "session vanished from tmux — reaping"); - cleanup_record(inner, id, record, false).await; + tracing::info!(%id, "session vanished from tmux — marking dead"); + let _ = inner.sidecar.write(&session); + let _ = inner.events.send(CatalogEvent::SessionUpdated { session }); } /// Tear down a session's artifacts after it has already been removed from the diff --git a/crates/maestro-daemon/src/tmux.rs b/crates/maestro-daemon/src/tmux.rs index 89abed6..10030ef 100644 --- a/crates/maestro-daemon/src/tmux.rs +++ b/crates/maestro-daemon/src/tmux.rs @@ -3,6 +3,7 @@ //! All sessions managed through this wrapper are named `maestro-` so that //! the daemon can recover its own sessions on restart (and ignore foreign ones). +use std::collections::BTreeMap; use std::env; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::OsStrExt; @@ -96,7 +97,13 @@ impl Tmux { let command = login_shell_command(env::var_os("SHELL").as_deref(), command); let out = self .cmd() - .args(new_session_args(&name, cwd, &command, None)) + .args(new_session_args( + &name, + cwd, + &command, + &BTreeMap::new(), + None, + )) .output()?; check(out) } @@ -112,13 +119,20 @@ impl Tmux { id: Uuid, cwd: &Path, command: &str, + session_env: &BTreeMap, sink_command: &str, ) -> Result<(), TmuxError> { let name = session_name(id); let command = login_shell_command(env::var_os("SHELL").as_deref(), command); let out = self .cmd() - .args(new_session_args(&name, cwd, &command, Some(sink_command))) + .args(new_session_args( + &name, + cwd, + &command, + session_env, + Some(sink_command), + )) .output()?; check(out) } @@ -370,6 +384,7 @@ fn new_session_args( name: &str, cwd: &Path, command: &str, + env: &BTreeMap, pipe_sink: Option<&str>, ) -> Vec { let mut args = vec![ @@ -388,8 +403,14 @@ fn new_session_args( OsString::from(name), OsString::from("-c"), cwd.as_os_str().to_os_string(), - OsString::from(command), ]; + // Caller-supplied environment. Sorted so the argv is deterministic, and + // therefore assertable. + for (k, v) in env { + args.push(OsString::from("-e")); + args.push(OsString::from(format!("{k}={v}"))); + } + args.push(OsString::from(command)); if let Some(sink) = pipe_sink { args.extend([ OsString::from(";"), @@ -419,6 +440,29 @@ mod tests { /// Every phrasing must be recognised: an unmatched one makes /// `list_sessions` fail, and a failed pass reaps nothing. + #[test] + fn new_session_args_emit_sorted_env_flags_before_the_command() { + let env: BTreeMap = [ + ("ZED".to_string(), "9".to_string()), + ("ALPHA".to_string(), "1".to_string()), + ] + .into_iter() + .collect(); + let args = new_session_args("maestro-x", Path::new("/tmp"), "bash", &env, None); + let flat: Vec = args + .iter() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + + let alpha = flat.iter().position(|a| a == "ALPHA=1").expect("ALPHA"); + let zed = flat.iter().position(|a| a == "ZED=9").expect("ZED"); + let command = flat.iter().rposition(|a| a == "bash").expect("command"); + assert!(alpha < zed, "env flags must be sorted for a stable argv"); + assert!(zed < command, "env must precede the command argument"); + assert_eq!(flat[alpha - 1], "-e"); + assert_eq!(flat[zed - 1], "-e"); + } + #[test] fn is_no_server_error_matches_every_known_phrasing() { for phrase in NO_SERVER_PHRASES { @@ -470,7 +514,13 @@ mod tests { #[test] fn new_session_args_pass_256color_env_and_default_terminal() { - let args = new_session_args("maestro-abc", Path::new("/tmp/proj"), "sleep 30", None); + let args = new_session_args( + "maestro-abc", + Path::new("/tmp/proj"), + "sleep 30", + &BTreeMap::new(), + None, + ); let strs: Vec<&str> = args.iter().map(|s| s.to_str().unwrap()).collect(); assert_eq!( strs, @@ -526,6 +576,7 @@ mod tests { "maestro-abc", Path::new("/tmp/proj"), "sleep 30", + &BTreeMap::new(), Some("cat >> '/tmp/fifo'"), ); let strs: Vec<&str> = args.iter().map(|s| s.to_str().unwrap()).collect(); diff --git a/crates/maestro-daemon/tests/attach.rs b/crates/maestro-daemon/tests/attach.rs index bcfec11..d8c6b1f 100644 --- a/crates/maestro-daemon/tests/attach.rs +++ b/crates/maestro-daemon/tests/attach.rs @@ -325,3 +325,57 @@ async fn second_attach_sees_replay_buffer_of_prior_output() { "fresh attach did not receive replay containing prior output" ); } + +/// The point of keeping a dead session: attach afterwards and read what it +/// printed before it died. The stream then ends rather than hanging. +#[tokio::test] +async fn attaching_to_a_dead_session_replays_its_final_output() { + let h = spawn_daemon_ws().await; + let id = create_bash_session(&h).await; + + // Produce output, then let the session die out-of-band. + { + let mut ws = connect_attach(h.addr, id).await.unwrap(); + ws.send(WsMessage::Binary(b"echo last-words\n".to_vec())) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(300)).await; + } + h.manager.start_liveness_watcher(Duration::from_millis(50)); + h._fx.tmux.tmux.kill_session(id).expect("kill tmux"); + + // Wait for the daemon to notice. + let deadline = std::time::Instant::now() + Duration::from_secs(3); + while std::time::Instant::now() < deadline { + if h.manager.status(id).await == Some(maestro_protocol::SessionStatus::Dead) { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + assert_eq!( + h.manager.status(id).await, + Some(maestro_protocol::SessionStatus::Dead), + "session should be marked dead, not removed" + ); + + let mut ws = connect_attach(h.addr, id) + .await + .expect("a dead session must still accept an attach"); + + let mut seen = Vec::new(); + let deadline = std::time::Instant::now() + Duration::from_secs(3); + while std::time::Instant::now() < deadline { + match tokio::time::timeout(Duration::from_millis(200), ws.next()).await { + Ok(Some(Ok(WsMessage::Binary(b)))) => seen.extend_from_slice(&b), + Ok(Some(Ok(WsMessage::Close(_)))) | Ok(None) => break, + Ok(Some(Ok(_))) => continue, + Ok(Some(Err(_))) => break, + Err(_) => continue, + } + } + let text = String::from_utf8_lossy(&seen); + assert!( + text.contains("last-words"), + "replay of a dead session lost its final output: {text:?}" + ); +} diff --git a/crates/maestro-daemon/tests/session_decisions.rs b/crates/maestro-daemon/tests/session_decisions.rs index af4acc5..ed31a2e 100644 --- a/crates/maestro-daemon/tests/session_decisions.rs +++ b/crates/maestro-daemon/tests/session_decisions.rs @@ -4,7 +4,7 @@ //! spawn rollback ordering, liveness diffing, and activity change-detection. //! Nothing here spawns a process, so they run everywhere and in milliseconds. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -14,7 +14,7 @@ use maestro_daemon::session::{SessionError, SessionManager}; use maestro_daemon::sidecar::SidecarStore; use maestro_daemon::tmux::PaneInfo; use maestro_daemon::worktree::WorktreeManager; -use maestro_protocol::{ActivityState, CatalogEvent, CreateSessionRequest}; +use maestro_protocol::{ActivityState, CatalogEvent, CreateSessionRequest, SessionStatus}; use tempfile::TempDir; use tokio::sync::broadcast::error::TryRecvError; use uuid::Uuid; @@ -55,19 +55,16 @@ impl Fx { } } -/// Poll `manager.snapshot()` until it holds `n` sessions. -async fn wait_for_len(manager: &SessionManager, n: usize) { +/// Poll until `id` reaches `want`. +async fn wait_for_status(manager: &SessionManager, id: uuid::Uuid, want: SessionStatus) { let deadline = tokio::time::Instant::now() + Duration::from_secs(3); while tokio::time::Instant::now() < deadline { - if manager.snapshot().await.len() == n { + if manager.status(id).await == Some(want) { return; } tokio::time::sleep(Duration::from_millis(10)).await; } - panic!( - "timed out waiting for {n} sessions, have {}", - manager.snapshot().await.len() - ); + panic!("timed out waiting for {id} to become {want:?}"); } /// NAP-260 rollback, asserted as an *ordering* rather than an end state. @@ -152,22 +149,23 @@ async fn recover_adopts_live_sessions_and_repipes_them() { ); } +/// A session tmux lost is marked `Dead` and kept, so the operator can still see +/// it exited and read what it printed. It is not removed. #[tokio::test] -async fn liveness_reaps_only_the_session_tmux_lost() { +async fn liveness_marks_the_lost_session_dead_and_keeps_it() { let fx = Fx::new(); let keep = fx.manager.create(fx.request("keep")).await.expect("keep"); let lose = fx.manager.create(fx.request("lose")).await.expect("lose"); let mut events = fx.manager.events(); - // The command exited, or someone ran `tmux kill-session` behind our back. fx.fake.remove_live(lose.id); fx.manager.start_liveness_watcher(Duration::from_millis(25)); + wait_for_status(&fx.manager, lose.id, SessionStatus::Dead).await; - wait_for_len(&fx.manager, 1).await; - - let survivors = fx.manager.snapshot().await; - assert_eq!(survivors.len(), 1); - assert_eq!(survivors[0].id, keep.id); + let all = fx.manager.snapshot().await; + assert_eq!(all.len(), 2, "the dead session must stay in the catalog"); + let survivor = all.iter().find(|s| s.id == keep.id).expect("keep"); + assert_eq!(survivor.status, SessionStatus::Running); let mut removed = Vec::new(); while let Ok(ev) = events.try_recv() { @@ -175,10 +173,118 @@ async fn liveness_reaps_only_the_session_tmux_lost() { removed.push(id); } } - assert_eq!( - removed, - vec![lose.id], - "exactly one Removed, for the dead id" + assert!(removed.is_empty(), "nothing should be removed: {removed:?}"); +} + +/// The transition fires once. Without the Running filter the pass re-announces +/// the same dead session on every tick, forever. +#[tokio::test] +async fn a_dead_session_is_announced_only_once() { + let fx = Fx::new(); + let s = fx.manager.create(fx.request("bash")).await.expect("create"); + let mut events = fx.manager.events(); + + fx.fake.remove_live(s.id); + fx.manager.start_liveness_watcher(Duration::from_millis(25)); + wait_for_status(&fx.manager, s.id, SessionStatus::Dead).await; + + let mut dead_updates = 0; + let deadline = tokio::time::Instant::now() + Duration::from_millis(300); + while tokio::time::Instant::now() < deadline { + if let Ok(CatalogEvent::SessionUpdated { session }) = events.try_recv() { + if session.status == SessionStatus::Dead { + dead_updates += 1; + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!(dead_updates, 1, "expected exactly one Dead announcement"); +} + +/// Dismissing a dead session releases it — without asking tmux to kill +/// something tmux already lost. +#[tokio::test] +async fn killing_a_dead_session_dismisses_it_without_touching_tmux() { + let fx = Fx::new(); + let s = fx.manager.create(fx.request("bash")).await.expect("create"); + fx.fake.remove_live(s.id); + fx.manager.start_liveness_watcher(Duration::from_millis(25)); + wait_for_status(&fx.manager, s.id, SessionStatus::Dead).await; + + fx.manager.kill(s.id).await.expect("dismiss"); + + assert!(fx.manager.snapshot().await.is_empty()); + assert!( + !fx.fake + .calls() + .iter() + .any(|c| matches!(c, Call::KillSession(k) if *k == s.id)), + "kill-session was called on a session tmux had already lost: {:?}", + fx.fake.calls() + ); +} + +/// A dead session has no pane, so input is dropped rather than surfacing as a +/// tmux failure the client would have to interpret. +#[tokio::test] +async fn a_dead_session_is_read_only() { + let fx = Fx::new(); + let s = fx.manager.create(fx.request("bash")).await.expect("create"); + fx.fake.remove_live(s.id); + fx.manager.start_liveness_watcher(Duration::from_millis(25)); + wait_for_status(&fx.manager, s.id, SessionStatus::Dead).await; + + fx.manager + .send_keys(s.id, b"ls\n") + .await + .expect("send_keys"); + fx.manager.resize(s.id, 80, 24).await.expect("resize"); + + assert!( + !fx.fake + .calls() + .iter() + .any(|c| matches!(c, Call::SendKeys { .. } | Call::ResizeWindow { .. })), + "input reached tmux for a dead session: {:?}", + fx.fake.calls() + ); +} + +/// `CreateSessionRequest.env` was accepted, stored, echoed back to clients, and +/// then dropped: `new_session_piped` had no env parameter at all. +#[tokio::test] +async fn requested_env_reaches_tmux() { + let fx = Fx::new(); + let mut req = fx.request("bash"); + req.env.insert("FOO".into(), "bar".into()); + req.env.insert("EMPTY".into(), String::new()); + + fx.manager.create(req).await.expect("create"); + + let want: BTreeMap = [ + ("EMPTY".to_string(), String::new()), + ("FOO".to_string(), "bar".to_string()), + ] + .into_iter() + .collect(); + match fx.fake.calls().first() { + Some(Call::NewSessionPiped { env, .. }) => assert_eq!(env, &want), + other => panic!("expected a spawn call, got {other:?}"), + } +} + +#[tokio::test] +async fn an_env_key_tmux_would_misparse_is_rejected() { + let fx = Fx::new(); + let mut req = fx.request("bash"); + req.env.insert("A=B".into(), "x".into()); + + let err = fx.manager.create(req).await.expect_err("should reject"); + assert_eq!(err.to_error_info().code, "invalid_env"); + assert!( + fx.fake.calls().is_empty(), + "nothing should have been spawned: {:?}", + fx.fake.calls() ); } diff --git a/crates/maestro-daemon/tests/session_manager.rs b/crates/maestro-daemon/tests/session_manager.rs index 1411b08..6b1df55 100644 --- a/crates/maestro-daemon/tests/session_manager.rs +++ b/crates/maestro-daemon/tests/session_manager.rs @@ -8,8 +8,8 @@ use std::sync::Arc; use std::time::Duration; use common::{wait_for_async, DaemonFixture}; -use maestro_protocol::CatalogEvent; use maestro_protocol::CreateSessionRequest; +use maestro_protocol::{CatalogEvent, SessionStatus}; use tempfile::TempDir; #[tokio::test] @@ -305,7 +305,7 @@ async fn pty_broadcast_delivers_bytes_to_subscribers() { } #[tokio::test] -async fn liveness_watcher_reaps_dead_sessions_and_emits_removed() { +async fn liveness_watcher_marks_dead_sessions_and_keeps_them_until_dismissed() { let fx = DaemonFixture::new(); let cwd = TempDir::new().unwrap(); @@ -330,30 +330,39 @@ async fn liveness_watcher_reaps_dead_sessions_and_emits_removed() { // daemon never finds out through its normal channels. fx.tmux.tmux.kill_session(s.id).expect("kill tmux directly"); - // Within a few watcher ticks the daemon should drop the session. wait_for_async(Duration::from_secs(3), || async { - !fx.manager.has(s.id).await + fx.manager.status(s.id).await == Some(SessionStatus::Dead) }) .await; - // Sidecar + FIFO should be cleaned up too. - assert!(!fx.sidecar_dir().join(format!("{}.json", s.id)).exists()); - assert!(!fx.fifo_dir().join(format!("{}.fifo", s.id)).exists()); + // Marked, not removed — the operator still sees it exited, and its + // artifacts stay so the output can be replayed. + assert!(fx.manager.has(s.id).await); + assert!(fx.sidecar_dir().join(format!("{}.json", s.id)).exists()); - // And we should have seen a Removed event for this id. - let mut saw_removed = false; + let mut saw_dead = false; let deadline = std::time::Instant::now() + Duration::from_secs(1); - while std::time::Instant::now() < deadline && !saw_removed { + while std::time::Instant::now() < deadline && !saw_dead { match tokio::time::timeout(Duration::from_millis(50), events.recv()).await { - Ok(Ok(CatalogEvent::SessionRemoved { id })) if id == s.id => saw_removed = true, + Ok(Ok(CatalogEvent::SessionUpdated { session })) + if session.id == s.id && session.status == SessionStatus::Dead => + { + saw_dead = true + } Ok(Ok(_)) => continue, _ => break, } } assert!( - saw_removed, - "expected SessionEvent::Removed for dead session" + saw_dead, + "expected a SessionUpdated marking the session dead" ); + + // Dismissing it is what finally releases the artifacts. + fx.manager.kill(s.id).await.expect("dismiss"); + assert!(!fx.manager.has(s.id).await); + assert!(!fx.sidecar_dir().join(format!("{}.json", s.id)).exists()); + assert!(!fx.fifo_dir().join(format!("{}.fifo", s.id)).exists()); } #[tokio::test] diff --git a/crates/maestro-protocol/src/lib.rs b/crates/maestro-protocol/src/lib.rs index dcdf4e1..fe001b8 100644 --- a/crates/maestro-protocol/src/lib.rs +++ b/crates/maestro-protocol/src/lib.rs @@ -25,6 +25,24 @@ use uuid::Uuid; /// The protocol version this crate implements. Advertised in `GET /api/info`. pub const PROTOCOL_VERSION: &str = env!("CARGO_PKG_VERSION"); +/// True when a daemon advertising `daemon_version` speaks the same protocol as +/// this build. +/// +/// Compared on the major component only, per semver: within a major, added +/// fields are `#[serde(default)]` and so are forward-compatible. An empty or +/// unparseable version is treated as compatible — daemons that predate the +/// field should not trip a warning. +pub fn is_compatible(daemon_version: &str) -> bool { + fn major(v: &str) -> Option<&str> { + let m = v.split('.').next()?; + (!m.is_empty() && m.bytes().all(|b| b.is_ascii_digit())).then_some(m) + } + match (major(daemon_version), major(PROTOCOL_VERSION)) { + (Some(theirs), Some(ours)) => theirs == ours, + _ => true, + } +} + /// A live or recently-dead tmux session managed by the daemon. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Session { @@ -275,6 +293,22 @@ pub enum ClientControl { mod tests { use super::*; + #[test] + fn version_compatibility_is_major_only() { + assert!(is_compatible(PROTOCOL_VERSION)); + let ours_major = PROTOCOL_VERSION.split('.').next().unwrap(); + assert!(is_compatible(&format!("{ours_major}.99.99"))); + assert!(!is_compatible("99.0.0")); + } + + /// A daemon predating the field sends nothing; that must not read as a + /// mismatch. + #[test] + fn version_compatibility_tolerates_unknown_versions() { + assert!(is_compatible("")); + assert!(is_compatible("unknown")); + } + fn round_trip(value: &T) -> T where T: Serialize + for<'de> Deserialize<'de>, diff --git a/crates/maestro-tui/src/lib.rs b/crates/maestro-tui/src/lib.rs index c0f0783..4736fa5 100644 --- a/crates/maestro-tui/src/lib.rs +++ b/crates/maestro-tui/src/lib.rs @@ -117,7 +117,14 @@ const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); async fn health_check(daemon: &DaemonClient) -> Result<(), TuiError> { for _ in 0..3 { - if daemon.daemon_info().await.is_ok() { + if let Ok(info) = daemon.daemon_info().await { + if !maestro_protocol::is_compatible(&info.version) { + tracing::warn!( + daemon = %info.version, + client = %maestro_protocol::PROTOCOL_VERSION, + "daemon protocol version differs from this client's", + ); + } return Ok(()); } tokio::time::sleep(HEALTH_TIMEOUT).await;