This repository has been archived on 2026-10-08. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
maestro/crates/maestro-daemon/src/local_api.rs
T
Miguel Palhas c856333e4a
ci / rust (push) Successful in 2m40s
docs(maestro): describe the single-host architecture
Rewrites CLAUDE.md as the current-architecture reference, drops the
registry from INSTALL/PRODUCT/DESIGN and the web README, deletes the
registry Dockerfile, and marks the dated design specs superseded where
they describe the registry, JWT auth, or cross-host attach.

The installer loses its configure step — every config field now has a
default, so a daemon starts with no config file at all.
2026-08-22 10:26:49 +01:00

286 lines
9.6 KiB
Rust

//! 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::{
CatalogEvent, CreateSessionRequest, ErrorInfo, GitRoot, Session, PROTOCOL_VERSION,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::local_events::LocalEventBus;
use crate::session::SessionManager;
/// Daemon identity returned by `GET /api/info`. Clients render this in the
/// header ("you're connected to konishi"), plus the daemon's protocol version
/// and its spawn presets (#26).
#[derive(Debug, Clone, Serialize)]
pub struct DaemonInfo {
pub hostname: String,
pub version: String,
/// Home directory of the OS user this daemon runs as, so clients can
/// prefill a spawn form's working directory. Empty if unresolved.
pub home_dir: String,
/// Spawn-form command presets resolved from `[spawn].presets` (#22), with
/// the implicit `custom` tile appended. Clients render these as one-click
/// tiles; it rides this existing payload so opening the form needs no extra
/// round-trip (#26).
pub presets: Vec<SpawnPreset>,
}
#[derive(Debug, Clone)]
pub struct LocalApiState {
pub manager: SessionManager,
pub hostname: Arc<String>,
/// 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<String>,
/// Resolved spawn presets (#22/#26) advertised in `GET /api/info`.
pub presets: Arc<Vec<SpawnPreset>>,
/// Fan-out of session deltas (NAP-248). The `/api/events` WS subscribes
/// here; everything else just reads REST.
pub events: LocalEventBus,
}
pub fn router(state: LocalApiState) -> Router {
Router::new()
.route("/api/sessions", get(list_sessions).post(create_session))
.route("/api/sessions/:id", delete(kill_session))
.route("/api/dirs", get(list_dir))
.route("/api/recent-dirs", get(recent_dirs))
.route("/api/gitroot", get(git_root))
.route("/api/info", get(daemon_info))
.route("/api/events", any(events_ws))
.route("/api/attach/:id", any(attach_ws))
.with_state(state)
}
async fn list_sessions(State(s): State<LocalApiState>) -> Json<Vec<Session>> {
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<LocalApiState>, Query(q): Query<DirQuery>) -> 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,
}
}
/// Recent working dirs for the spawn form's recents picker (#26).
async fn recent_dirs(State(s): State<LocalApiState>) -> 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<LocalApiState>, Query(q): Query<DirQuery>) -> 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<LocalApiState>) -> Json<DaemonInfo> {
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<LocalApiState>,
Json(body): Json<CreateSessionRequest>,
) -> 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(
StatusCode::BAD_GATEWAY,
info.code.as_str(),
info.message.as_str(),
)
}
}
}
async fn kill_session(State(s): State<LocalApiState>, Path(id): Path<Uuid>) -> 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(
StatusCode::BAD_GATEWAY,
info.code.as_str(),
info.message.as_str(),
)
}
}
}
fn error_response(status: StatusCode, code: &str, message: &str) -> Response {
(
status,
Json(serde_json::json!({
"error": ErrorInfo {
code: code.into(),
message: message.into(),
},
})),
)
.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<String>,
home_dir: impl Into<String>,
presets: Vec<SpawnPreset>,
events: LocalEventBus,
) -> LocalApiState {
LocalApiState {
manager,
hostname: Arc::new(hostname.into()),
home_dir: Arc::new(home_dir.into()),
presets: Arc::new(presets),
events,
}
}
// ---------------------------------------------------------------------------
// WS /api/attach/:id — raw PTY bytes for one session
// ---------------------------------------------------------------------------
#[allow(clippy::result_large_err)]
async fn attach_ws(
Path(id): Path<Uuid>,
State(s): State<LocalApiState>,
ws: axum::extract::WebSocketUpgrade,
) -> Result<Response, Response> {
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<LocalApiState>,
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.events.subscribe();
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(())
}