//! Cross-process end-to-end tests for the headless Maestro slice. //! //! Each test brings up a real daemon subprocess, isolated in temp dirs, and //! drives it through the public HTTP+WS surface using the same client APIs a //! real CLI/web client would. //! //! These tests require `tmux` and `git` on `$PATH`. #![allow(clippy::result_large_err)] use std::collections::HashMap; use std::process::Command; use std::time::{Duration, Instant}; use futures_util::{SinkExt, StreamExt}; use maestro_e2e::util::wait_for_async; use maestro_e2e::{Daemon, TestClient}; use maestro_protocol::{CreateSessionRequest, WorktreeSpec}; use tempfile::TempDir; use tokio_tungstenite::tungstenite::Message as WsMessage; async fn bring_up() -> (Daemon, TestClient) { let daemon = Daemon::spawn().await; let client = TestClient::new(&daemon.http_base()); (daemon, client) } fn create_req(cwd: &std::path::Path, command: &str) -> CreateSessionRequest { CreateSessionRequest { cwd: cwd.to_path_buf(), command: command.into(), env: HashMap::new(), metadata: HashMap::new(), worktree: None, } } #[tokio::test(flavor = "multi_thread")] async fn lists_spawned_sessions() { let (_daemon, client) = bring_up().await; let cwd = TempDir::new().unwrap(); let a = client .spawn_session(&create_req(cwd.path(), "sleep 30")) .await .expect("spawn a"); let b = client .spawn_session(&create_req(cwd.path(), "sleep 30")) .await .expect("spawn b"); let sessions = client.list_sessions().await.expect("list"); assert!(sessions.iter().any(|s| s.id == a.id)); assert!(sessions.iter().any(|s| s.id == b.id)); client.kill_session(a.id).await.expect("kill a"); client.kill_session(b.id).await.expect("kill b"); } #[tokio::test(flavor = "multi_thread")] async fn multi_attach_sees_same_output() { let (_daemon, client) = bring_up().await; let cwd = TempDir::new().unwrap(); let s = client .spawn_session(&create_req(cwd.path(), "bash --noprofile --norc")) .await .expect("spawn"); let mut a = client.attach(s.id).await.expect("attach a"); let mut b = client.attach(s.id).await.expect("attach b"); // Drive input through client A; both attachments should observe it via // the daemon's PTY broadcast. let send = b"echo MAESTRO_E2E_SHARED\n".to_vec(); a.send(WsMessage::Binary(send)).await.expect("send keys"); let want = b"MAESTRO_E2E_SHARED"; let deadline = Instant::now() + Duration::from_secs(5); let mut buf_a = Vec::new(); let mut buf_b = Vec::new(); while Instant::now() < deadline { tokio::select! { msg = a.next() => match msg { Some(Ok(WsMessage::Binary(bytes))) => buf_a.extend(bytes), Some(Ok(_)) => {} _ => break, }, msg = b.next() => match msg { Some(Ok(WsMessage::Binary(bytes))) => buf_b.extend(bytes), Some(Ok(_)) => {} _ => break, }, _ = tokio::time::sleep(Duration::from_millis(50)) => {} } if buf_a.windows(want.len()).any(|w| w == want) && buf_b.windows(want.len()).any(|w| w == want) { break; } } assert!( buf_a.windows(want.len()).any(|w| w == want), "client A never saw the echo" ); assert!( buf_b.windows(want.len()).any(|w| w == want), "client B never saw the echo" ); let _ = a.close(None).await; let _ = b.close(None).await; client.kill_session(s.id).await.expect("kill"); } #[tokio::test(flavor = "multi_thread")] async fn cleanup_on_kill_removes_worktree() { let (_daemon, client) = bring_up().await; let base = TempDir::new().unwrap(); init_repo(base.path()); let req = CreateSessionRequest { cwd: base.path().to_path_buf(), command: "sleep 30".into(), env: HashMap::new(), metadata: HashMap::new(), worktree: Some(WorktreeSpec { base_repo: base.path().to_path_buf(), branch: "feature/e2e".into(), cleanup_on_kill: true, }), }; let s = client.spawn_session(&req).await.expect("spawn worktree"); // The daemon's WorktreeManager puts new worktrees under // `/worktrees/`. We can't peek the daemon's state dir // directly from here, but we can verify by asking git: a worktree must // exist that lives outside the original repo. let worktrees = git_worktree_list(base.path()); assert!( worktrees.iter().any(|w| w.contains("feature/e2e")), "expected a worktree for feature/e2e branch, got: {worktrees:?}" ); client.kill_session(s.id).await.expect("kill"); // Give the daemon a moment to remove the worktree, then verify. let deadline = Instant::now() + Duration::from_secs(5); while Instant::now() < deadline { let after = git_worktree_list(base.path()); if !after.iter().any(|w| w.contains("feature/e2e")) { return; } tokio::time::sleep(Duration::from_millis(100)).await; } panic!( "worktree feature/e2e still present after kill: {:?}", git_worktree_list(base.path()) ); } #[tokio::test(flavor = "multi_thread")] async fn daemon_restart_recovers_session() { let (mut daemon, client) = bring_up().await; let cwd = TempDir::new().unwrap(); let s = client .spawn_session(&create_req(cwd.path(), "sleep 300")) .await .expect("spawn"); // Restart against the same tmux server + state dir: the daemon must adopt // the still-running tmux session on boot. daemon.restart().await; wait_for_async( "session reappears after restart", Duration::from_secs(10), || { let client = client.clone(); let id = s.id; async move { client .list_sessions() .await .map(|ss| ss.iter().any(|x| x.id == id)) .unwrap_or(false) } }, ) .await; client.kill_session(s.id).await.expect("kill"); } #[tokio::test(flavor = "multi_thread")] async fn concurrent_spawns_each_get_unique_ids() { let (_daemon, client) = bring_up().await; let cwd = TempDir::new().unwrap(); let mut handles = Vec::new(); for _ in 0..5 { let client = client.clone(); let path = cwd.path().to_path_buf(); handles.push(tokio::spawn(async move { client .spawn_session(&create_req(&path, "sleep 30")) .await .expect("spawn") })); } let mut ids = Vec::new(); for h in handles { ids.push(h.await.unwrap().id); } ids.sort(); ids.dedup(); assert_eq!(ids.len(), 5, "expected 5 distinct session ids"); for id in ids { client.kill_session(id).await.expect("kill"); } } #[tokio::test(flavor = "multi_thread")] async fn spawn_records_history_and_infers_gitroot_for_form() { // #24/#25/#26/#28: a real spawn writes a durable spawn-history record, which // the daemon's recent-dirs endpoint surfaces on the spawn form's next open // (#27's recents picker), and gitroot infers the worktree base_repo from the // same dir. Exercised end to end against real tmux + git. let (daemon, client) = bring_up().await; // A git repo as the working dir, so gitroot has a repo to infer. let repo = TempDir::new().unwrap(); init_repo(repo.path()); let cwd = repo.path().to_string_lossy().to_string(); // Spawn in that dir (the command stands in for a preset tile selection). let s = client .spawn_session(&create_req(repo.path(), "sleep 30")) .await .expect("spawn"); // The recents picker reads GET /recent-dirs on open: the just-spawned dir // must surface, tagged with the command it was last used with. The history // write is best-effort right after the spawn, so poll briefly. wait_for_async( "recent-dirs surfaces the spawned cwd", Duration::from_secs(5), || { let client = daemon.client(); let want = cwd.clone(); async move { let Ok(recents) = client.recent_dirs().await else { return false; }; recents .dirs .iter() .any(|d| d.cwd.to_string_lossy() == want && d.last_command == "sleep 30") } }, ) .await; // gitroot infers the worktree base_repo from the same dir (#25/#26): the dir // is itself the repo toplevel (it holds `.git`). let gr = daemon.client().git_root(&cwd).await.expect("gitroot"); assert_eq!( gr.root.as_deref().map(|p| p.to_string_lossy().to_string()), Some(cwd.clone()), "gitroot should infer the enclosing repo" ); client.kill_session(s.id).await.expect("kill"); } #[tokio::test(flavor = "multi_thread")] async fn activity_reflects_foreground_and_input_blocking() { // NAP-340 (#18): the watcher infers each session's foreground command and // activity from structured tmux/proc state. `cat` parks in read() on the // pty → AwaitingInput; `sleep` is quiescent but not reading the tty → Idle // (the distinction the /proc//syscall check buys us). Both report the // right foreground. Exercised against real tmux. use maestro_protocol::ActivityState; let (_daemon, client) = bring_up().await; let cwd = TempDir::new().unwrap(); let cat = client .spawn_session(&create_req(cwd.path(), "cat")) .await .expect("spawn cat"); let slp = client .spawn_session(&create_req(cwd.path(), "sleep 300")) .await .expect("spawn sleep"); // Initial state is Active; the watcher needs a couple ticks past the // quiescence window (3s) to settle into the steady states. wait_for_async( "cat → AwaitingInput, sleep → Idle, with correct foreground", Duration::from_secs(20), || { let client = client.clone(); let (cat_id, sleep_id) = (cat.id, slp.id); async move { let sessions = match client.list_sessions().await { Ok(s) => s, Err(_) => return false, }; let cat_ok = sessions .iter() .find(|s| s.id == cat_id) .map(|s| { s.activity == ActivityState::AwaitingInput && s.foreground.as_deref() == Some("cat") }) .unwrap_or(false); let sleep_ok = sessions .iter() .find(|s| s.id == sleep_id) .map(|s| { s.activity == ActivityState::Idle && s.foreground.as_deref() == Some("sleep") }) .unwrap_or(false); cat_ok && sleep_ok } }, ) .await; client.kill_session(cat.id).await.expect("kill cat"); client.kill_session(slp.id).await.expect("kill sleep"); } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- fn init_repo(dir: &std::path::Path) { run_git(&["init", "-q", "-b", "main"], dir); run_git(&["config", "user.email", "e2e@example.com"], dir); run_git(&["config", "user.name", "E2E"], dir); std::fs::write(dir.join("README"), b"hello\n").unwrap(); run_git(&["add", "."], dir); run_git(&["commit", "-q", "-m", "initial"], dir); } fn run_git(args: &[&str], cwd: &std::path::Path) { let out = Command::new("git") .arg("-C") .arg(cwd) .args(args) .output() .expect("git spawn"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); } fn git_worktree_list(dir: &std::path::Path) -> Vec { let out = Command::new("git") .arg("-C") .arg(dir) .args(["worktree", "list", "--porcelain"]) .output() .expect("git worktree list"); String::from_utf8_lossy(&out.stdout) .lines() .map(str::to_string) .collect() } #[tokio::test(flavor = "multi_thread")] async fn daemon_events_ws_streams_snapshot_then_session_added() { // NAP-248: subscribe to the daemon's WS /api/events, expect an initial // Snapshot, then a SessionAdded after we spawn a session via REST. let (daemon, client) = bring_up().await; let cwd = TempDir::new().unwrap(); let ws_url = daemon.client().events_url().unwrap(); let (mut ws, _) = tokio_tungstenite::connect_async(ws_url) .await .expect("events WS handshake"); // First frame must be a Snapshot (the WS sends it eagerly on connect). let snapshot = next_event(&mut ws).await; match &snapshot { maestro_protocol::CatalogEvent::Snapshot { sessions } => { assert!(sessions.is_empty()); } other => panic!("expected initial Snapshot, got {other:?}"), } let session = client .spawn_session(&create_req(cwd.path(), "sleep 30")) .await .expect("spawn"); // SessionAdded must show up on the WS within a reasonable window. let saw_added = tokio::time::timeout(Duration::from_secs(5), async { loop { match next_event(&mut ws).await { maestro_protocol::CatalogEvent::SessionAdded { session: s } if s.id == session.id => { return true; } _ => continue, } } }) .await .unwrap_or(false); assert!( saw_added, "events WS never delivered SessionAdded for own session" ); client.kill_session(session.id).await.expect("kill"); } // --------------------------------------------------------------------------- // CLI against the local daemon // --------------------------------------------------------------------------- /// Run the real `maestro` binary with an isolated env and capture its output. fn run_cli(args: &[&str], envs: &[(&str, &str)]) -> std::process::Output { let bin = maestro_e2e::workspace_target_bin("maestro", "maestro"); let mut cmd = Command::new(&bin); cmd.args(args); cmd.env_clear().env( "PATH", std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".into()), ); for (k, v) in envs { cmd.env(k, v); } cmd.output().expect("run maestro cli") } #[tokio::test(flavor = "multi_thread")] async fn cli_list_reads_from_daemon() { // The subject is the shipped `maestro` binary — arg parsing, config // precedence, output. It needs a daemon to talk to, not tmux, so this runs // against an in-memory one. let mock = maestro_testing::MockDaemon::start().await; let id = uuid::Uuid::new_v4(); mock.add_session(maestro_testing::session(id, "/home/mock/work", "sleep 30")); let home = TempDir::new().unwrap(); let cfg_path = home.path().join("config.toml"); let out = run_cli( &["list", "--json"], &[ ("HOME", home.path().to_str().unwrap()), ("MAESTRO_CONFIG", cfg_path.to_str().unwrap()), ("MAESTRO_DAEMON_URL", &mock.http_base()), ], ); let stdout = String::from_utf8_lossy(&out.stdout); let stderr = String::from_utf8_lossy(&out.stderr); assert!(out.status.success(), "list failed: {stderr}\n{stdout}"); assert!( stdout.contains(&id.to_string()), "session not listed: {stdout}" ); } #[tokio::test(flavor = "multi_thread")] async fn cli_list_fails_when_daemon_is_down() { let dead_daemon = format!("http://127.0.0.1:{}", maestro_e2e::util::free_port()); let home = TempDir::new().unwrap(); let cfg_path = home.path().join("config.toml"); let out = run_cli( &["list"], &[ ("HOME", home.path().to_str().unwrap()), ("MAESTRO_CONFIG", cfg_path.to_str().unwrap()), ("MAESTRO_DAEMON_URL", &dead_daemon), ], ); assert!(!out.status.success(), "expected a failure with no daemon"); } async fn next_event(ws: &mut S) -> maestro_protocol::CatalogEvent where S: StreamExt> + Unpin, { loop { match ws.next().await { Some(Ok(WsMessage::Text(t))) => return serde_json::from_str(&t).expect("CatalogEvent"), Some(Ok(_)) => continue, other => panic!("WS closed waiting for event: {other:?}"), } } }