//! Daemon-side HTTP API for clients (NAP-243). //! //! These routes live on the daemon's `bind_addr` (default `127.0.0.1:7070`). //! They're the contract `maestro-web`, the TUI, and the CLI call against. //! //! ## Trust model //! //! Whoever can reach `bind_addr` can use these routes. No JWT, no cookie. The //! default `127.0.0.1` bind makes this same-trust as tmux (one-user-wide). //! Operators who bind a LAN/VPN address opt into one-segment-wide trust — the //! perimeter is theirs to choose, Maestro does not police it. use std::sync::Arc; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::routing::{any, delete, get}; use axum::{Json, Router}; use maestro_config::SpawnPreset; use maestro_protocol::{ routes, ApiError, CatalogEvent, CreateSessionRequest, DaemonInfo, GitRoot, Session, PROTOCOL_VERSION, }; use serde::Deserialize; use uuid::Uuid; use crate::session::SessionManager; #[derive(Debug, Clone)] pub struct LocalApiState { pub manager: SessionManager, pub hostname: Arc, /// Home directory of the OS user this daemon runs as, advertised so clients /// can prefill a spawn form's working directory. Empty if unresolved. pub home_dir: Arc, /// Resolved spawn presets (#22/#26) advertised in `GET /api/info`. pub presets: Arc>, } pub fn router(state: LocalApiState) -> Router { Router::new() .route(routes::SESSIONS, get(list_sessions).post(create_session)) .route(routes::patterns::SESSION, delete(kill_session)) .route(routes::DIRS, get(list_dir)) .route(routes::RECENT_DIRS, get(recent_dirs)) .route(routes::GITROOT, get(git_root)) .route(routes::INFO, get(daemon_info)) .route(routes::EVENTS, any(events_ws)) .route(routes::patterns::ATTACH, any(attach_ws)) .with_state(state) } async fn list_sessions(State(s): State) -> Json> { Json(s.manager.snapshot().await) } /// Query string for `GET /api/dirs`. `path` is the directory to list (the /// parent of what the user is typing); empty/`~`/relative are resolved against /// the daemon's home dir. #[derive(Debug, Deserialize)] struct DirQuery { #[serde(default)] path: String, } /// List one directory's immediate subdirectories, for the spawn form's /// working-directory autocomplete (NAP-329). async fn list_dir(State(s): State, Query(q): Query) -> Response { match crate::dirlist::list_dir(&s.home_dir, &q.path) { Ok(listing) => Json(listing).into_response(), Err(info) => error_response(dir_error_status(&info.code), &info.code, &info.message), } } /// HTTP status for a local [`crate::dirlist`] error code. fn dir_error_status(code: &str) -> StatusCode { match code { "not_found" => StatusCode::NOT_FOUND, "permission_denied" => StatusCode::FORBIDDEN, "not_a_directory" => StatusCode::BAD_REQUEST, _ => StatusCode::BAD_GATEWAY, } } /// 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() } /// Probe the enclosing git repo of `path`, to infer the worktree `base_repo` /// for the spawn form (#26). `path` is resolved against the daemon's home dir /// (empty/`~`/relative), like [`list_dir`]. async fn git_root(State(s): State, Query(q): Query) -> Response { let dir = crate::dirlist::resolve(&s.home_dir, &q.path); Json(GitRoot { root: crate::gitroot::find_root(&dir), }) .into_response() } async fn daemon_info(State(s): State) -> Json { Json(DaemonInfo { hostname: (*s.hostname).clone(), version: PROTOCOL_VERSION.into(), home_dir: (*s.home_dir).clone(), presets: (*s.presets).clone(), }) } async fn create_session( State(s): State, Json(body): Json, ) -> Response { match s.manager.create(body).await { Ok(session) => (StatusCode::CREATED, Json(session)).into_response(), Err(e) => { let info = e.to_error_info(); error_response( session_error_status(&info.code), info.code.as_str(), info.message.as_str(), ) } } } async fn kill_session(State(s): State, Path(id): Path) -> Response { if !s.manager.has(id).await { return error_response( StatusCode::NOT_FOUND, "unknown_session", "no such session on this daemon", ); } match s.manager.kill(id).await { Ok(()) => StatusCode::NO_CONTENT.into_response(), Err(e) => { let info = e.to_error_info(); error_response( session_error_status(&info.code), info.code.as_str(), info.message.as_str(), ) } } } fn error_response(status: StatusCode, code: &str, message: &str) -> Response { (status, Json(ApiError::new(code, message))).into_response() } /// Convenience constructor — pulls the bits `LocalApiState` needs from /// `DaemonConfig` so callers don't have to assemble it by hand. pub fn state_for( manager: SessionManager, hostname: impl Into, home_dir: impl Into, presets: Vec, ) -> LocalApiState { LocalApiState { manager, hostname: Arc::new(hostname.into()), home_dir: Arc::new(home_dir.into()), presets: Arc::new(presets), } } // --------------------------------------------------------------------------- // WS /api/attach/:id — raw PTY bytes for one session // --------------------------------------------------------------------------- #[allow(clippy::result_large_err)] async fn attach_ws( Path(id): Path, State(s): State, ws: axum::extract::WebSocketUpgrade, ) -> Result { if !s.manager.has(id).await { return Err(error_response( StatusCode::NOT_FOUND, "unknown_session", "no such session on this daemon", )); } let manager = s.manager.clone(); Ok(ws.on_upgrade(move |socket| async move { let _ = crate::attach::serve(socket, manager, id).await; })) } // --------------------------------------------------------------------------- // WS /api/events — live catalog deltas for browser/TUI subscribers (NAP-248) // --------------------------------------------------------------------------- async fn events_ws( State(s): State, ws: axum::extract::WebSocketUpgrade, ) -> Response { ws.on_upgrade(move |socket| async move { let _ = pump_events(socket, s).await; }) } async fn pump_events( socket: axum::extract::ws::WebSocket, s: LocalApiState, ) -> Result<(), axum::Error> { use axum::extract::ws::Message; use futures_util::{SinkExt, StreamExt}; use tokio::sync::broadcast::error::RecvError; let (mut sink, mut stream) = socket.split(); // Subscribe BEFORE building the snapshot so deltas applied while we're // marshaling can't slip between the two and disappear. The UI is // idempotent for repeated *Added events, so any overlap is harmless. let mut rx = s.manager.events(); let snapshot = CatalogEvent::Snapshot { sessions: s.manager.snapshot().await, }; let text = serde_json::to_string(&snapshot).expect("snapshot encode"); if sink.send(Message::Text(text)).await.is_err() { return Ok(()); } loop { tokio::select! { ev = rx.recv() => { let event = match ev { Ok(e) => e, Err(RecvError::Lagged(n)) => CatalogEvent::Lagged { skipped: n }, Err(RecvError::Closed) => break, }; let text = serde_json::to_string(&event).expect("event encode"); if sink.send(Message::Text(text)).await.is_err() { break; } } frame = stream.next() => { // Server-push only. Anything from the client either closes or // is ignored. match frame { None => break, Some(Err(_)) => break, Some(Ok(Message::Close(_))) => break, Some(Ok(_)) => {} } } } } Ok(()) }