//! Integration tests for the daemon's HTTP + WS API (NAP-243). mod common; use std::collections::HashMap; use std::net::{Ipv4Addr, SocketAddr}; use std::time::Duration; use common::DaemonFixture; use futures_util::{SinkExt, StreamExt}; use maestro_daemon::{local_api, LocalEventBus}; use maestro_protocol::{CreateSessionRequest, Session}; use tokio::net::TcpListener; use tokio::sync::oneshot; use tokio_tungstenite::tungstenite::Message as WsMessage; use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; use uuid::Uuid; type WsClient = WebSocketStream>; struct Harness { addr: SocketAddr, manager: maestro_daemon::SessionManager, _shutdown: oneshot::Sender<()>, _fx: DaemonFixture, } async fn spawn(hostname: &str) -> Harness { let fx = DaemonFixture::new(); let manager = fx.manager.clone(); let events = LocalEventBus::new(); // Built-in presets (claude/opencode/zsh + custom) so `/api/info` advertises // a known set (#26). let presets = maestro_config::SpawnSection::default().resolve().unwrap(); let router = local_api::router(local_api::state_for( manager.clone(), hostname, "/home/test", presets, events, )); let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))) .await .unwrap(); let addr = listener.local_addr().unwrap(); let (tx, rx) = oneshot::channel::<()>(); tokio::spawn(async move { let _ = axum::serve(listener, router) .with_graceful_shutdown(async move { let _ = rx.await; }) .await; }); Harness { addr, manager, _shutdown: tx, _fx: fx, } } fn url(addr: SocketAddr, path: &str) -> String { format!("http://{addr}{path}") } #[tokio::test] async fn info_returns_daemon_identity() { let h = spawn("naps-laptop").await; let resp: serde_json::Value = reqwest::get(url(h.addr, "/api/info")) .await .unwrap() .json() .await .unwrap(); assert_eq!(resp["hostname"], "naps-laptop"); assert_eq!(resp["home_dir"], "/home/test"); assert!(resp["version"].is_string()); } #[tokio::test] async fn list_sessions_starts_empty_and_reflects_creates() { let h = spawn("naps-laptop").await; let empty: Vec = reqwest::get(url(h.addr, "/api/sessions")) .await .unwrap() .json() .await .unwrap(); assert!(empty.is_empty()); let req = CreateSessionRequest { cwd: "/tmp".into(), command: "sleep 60".into(), env: HashMap::new(), metadata: HashMap::new(), worktree: None, }; let created: Session = reqwest::Client::new() .post(url(h.addr, "/api/sessions")) .json(&req) .send() .await .unwrap() .json() .await .unwrap(); let after: Vec = reqwest::get(url(h.addr, "/api/sessions")) .await .unwrap() .json() .await .unwrap(); assert_eq!(after.len(), 1); assert_eq!(after[0].id, created.id); } #[tokio::test] async fn info_advertises_spawn_presets() { // #26: the daemon's presets ride the info payload so the spawn form needs // no extra round-trip. Built-ins + the implicit custom. let h = spawn("naps-laptop").await; let resp: serde_json::Value = reqwest::get(url(h.addr, "/api/info")) .await .unwrap() .json() .await .unwrap(); let ids: Vec<&str> = resp["presets"] .as_array() .unwrap() .iter() .map(|p| p["id"].as_str().unwrap()) .collect(); assert_eq!(ids, ["claude", "opencode", "zsh", "custom"]); } #[tokio::test] async fn recent_dirs_returns_empty_without_history() { // #26: reads this daemon's spawn history. The test fixture wires no // history, so the list is empty but the endpoint is well-formed. let h = spawn("naps-laptop").await; let resp: serde_json::Value = reqwest::get(url(h.addr, "/api/recent-dirs")) .await .unwrap() .json() .await .unwrap(); assert_eq!(resp["dirs"].as_array().unwrap().len(), 0); assert_eq!(resp["truncated"], false); } #[tokio::test] async fn gitroot_probes_path() { // #26: resolves the query against the daemon home dir and walks up for a // `.git`. A `/tmp`-rooted temp dir is not in a repo, so the root is null. let h = spawn("naps-laptop").await; let tmp = tempfile::tempdir().unwrap(); let resp: serde_json::Value = reqwest::get(url( h.addr, &format!( "/api/gitroot?path={}", urlencoding::encode(&tmp.path().to_string_lossy()) ), )) .await .unwrap() .json() .await .unwrap(); assert!(resp.get("root").is_none() || resp["root"].is_null()); } #[tokio::test] async fn delete_unknown_session_returns_404() { let h = spawn("naps-laptop").await; let resp = reqwest::Client::new() .delete(url(h.addr, &format!("/api/sessions/{}", Uuid::new_v4()))) .send() .await .unwrap(); assert_eq!(resp.status(), reqwest::StatusCode::NOT_FOUND); } #[tokio::test] async fn delete_owned_session_kills_it() { let h = spawn("naps-laptop").await; let session = h .manager .create(CreateSessionRequest { cwd: "/tmp".into(), command: "sleep 60".into(), env: HashMap::new(), metadata: HashMap::new(), worktree: None, }) .await .unwrap(); let resp = reqwest::Client::new() .delete(url(h.addr, &format!("/api/sessions/{}", session.id))) .send() .await .unwrap(); assert_eq!(resp.status(), reqwest::StatusCode::NO_CONTENT); assert!(!h.manager.has(session.id).await); } #[tokio::test] async fn attach_ws_streams_pty_bytes() { let h = spawn("naps-laptop").await; let session = h .manager .create(CreateSessionRequest { cwd: "/tmp".into(), command: "bash --noprofile --norc".into(), env: HashMap::new(), metadata: HashMap::new(), worktree: None, }) .await .unwrap(); let ws_url = format!("ws://{}/api/attach/{}", h.addr, session.id); let (mut ws, _): (WsClient, _) = connect_async(ws_url).await.unwrap(); // Provoke output. The bash process should echo this back via the PTY. ws.send(WsMessage::Binary(b"echo hello-attach\n".to_vec())) .await .unwrap(); let saw_hello = tokio::time::timeout(Duration::from_secs(2), async { loop { match ws.next().await { Some(Ok(WsMessage::Binary(bytes))) => { if String::from_utf8_lossy(&bytes).contains("hello-attach") { return true; } } Some(Ok(_)) => continue, Some(Err(_)) | None => return false, } } }) .await .unwrap_or(false); assert!(saw_hello, "PTY did not echo through the attach WS"); } #[tokio::test] async fn attach_ws_for_unknown_session_returns_404() { let h = spawn("naps-laptop").await; let ws_url = format!("ws://{}/api/attach/{}", h.addr, Uuid::new_v4()); let err = connect_async(ws_url) .await .expect_err("expected handshake fail"); let msg = err.to_string(); assert!( msg.contains("404") || msg.to_lowercase().contains("not found"), "{msg}" ); }