feat(maestro): spawn protocol types + relay + daemon HTTP for recents/gitroot/presets (#26)

Expose the daemon-side spawn data (#24 recents, #25 gitroot, #22 presets) to
the web, mirroring the NAP-329 ListDir broker plumbing end to end so it works
across federated hosts.

Wire (maestro-protocol): `RecentDir`/`RecentDirs`/`GitRoot` payloads;
`DaemonInbound::RecentDirs`/`GitRoot` requests + `ForwardRecentDirs`/
`ForwardGitRoot` relay pairs + their `*Result` replies on both enums. All
forward-compatible via the existing `RpcResult` + `#[serde(other)] Unknown`.

Relay (broker + registry + registry_client): home daemon → registry → owning
daemon → back, with the same fail-fast-while-disconnected + RAII pending-entry
cleanup discipline as ListDir. The owning daemon answers RecentDirs from its
spawn history and GitRoot by resolving the path against its home dir
(shared `dirlist::resolve`) then walking up via `gitroot::find_root`.

Daemon HTTP (maestro-daemon):
- GET /api/daemons/:id/recent-dirs → RecentDirs
- GET /api/daemons/:id/gitroot?path= → GitRoot
- Presets ride GET /api/web/info (the documented DaemonInfo sibling) so the
  form needs no extra round-trip; resolved once at startup from [spawn].presets
  (a bad preset list now refuses startup).

Tests: protocol round-trip + forward-compat for the new variants; broker
forward round-trips + fail-fast; HTTP handler tests (self recents/gitroot,
presets advertisement, peer 503 without a registry link).

Closes #26

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-20 21:09:18 +00:00
co-authored by Claude Opus 4.8
parent ac11997f58
commit cc8412ca59
11 changed files with 776 additions and 5 deletions
+221 -1
View File
@@ -19,7 +19,8 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use maestro_protocol::{
AttachCandidates, CreateSessionRequest, DaemonOutbound, DirListing, ReplyTo, RpcResult, Session,
AttachCandidates, CreateSessionRequest, DaemonOutbound, DirListing, GitRoot, RecentDirs,
ReplyTo, RpcResult, Session,
};
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;
@@ -73,6 +74,10 @@ pub struct BrokerHandle {
pending_kill: Arc<Mutex<HashMap<ReplyTo, oneshot::Sender<RpcResult<()>>>>>,
/// Pending `ForwardListDir` replies, keyed by `reply_to` (NAP-329).
pending_list_dir: Arc<Mutex<HashMap<ReplyTo, oneshot::Sender<RpcResult<DirListing>>>>>,
/// Pending `ForwardRecentDirs` replies, keyed by `reply_to` (#26).
pending_recent_dirs: Arc<Mutex<HashMap<ReplyTo, oneshot::Sender<RpcResult<RecentDirs>>>>>,
/// Pending `ForwardGitRoot` replies, keyed by `reply_to` (#26).
pending_git_root: Arc<Mutex<HashMap<ReplyTo, oneshot::Sender<RpcResult<GitRoot>>>>>,
/// Whether the registry control link is currently up. Flipped by the
/// registry-client task via [`BrokerHandle::set_connected`]. When down,
/// `resolve_attach` fails fast instead of queueing onto an undrained
@@ -95,6 +100,8 @@ impl BrokerHandle {
pending_create: Arc::new(Mutex::new(HashMap::new())),
pending_kill: Arc::new(Mutex::new(HashMap::new())),
pending_list_dir: Arc::new(Mutex::new(HashMap::new())),
pending_recent_dirs: Arc::new(Mutex::new(HashMap::new())),
pending_git_root: Arc::new(Mutex::new(HashMap::new())),
connected: Arc::new(AtomicBool::new(false)),
};
(handle, out_rx)
@@ -292,6 +299,117 @@ impl BrokerHandle {
}
}
/// Broker a cross-daemon recent-dirs query: ask the registry to relay a
/// `RecentDirs` request to the daemon named by `daemon_id` (which may be a
/// peer) and return its recents. Same discipline as the other broker calls
/// (#26).
pub async fn forward_recent_dirs(&self, daemon_id: String) -> Result<RecentDirs, BrokerError> {
if !self.connected.load(Ordering::Acquire) {
return Err(BrokerError::NoControlLink);
}
let reply_to = Uuid::new_v4();
let (tx, rx) = oneshot::channel();
self.pending_recent_dirs
.lock()
.unwrap()
.insert(reply_to, tx);
let _guard = PendingGuard {
map: &*self.pending_recent_dirs,
key: reply_to,
};
if self
.out_tx
.try_send(DaemonOutbound::ForwardRecentDirs {
reply_to,
daemon_id,
})
.is_err()
{
return Err(BrokerError::NoControlLink);
}
match tokio::time::timeout(RESOLVE_TIMEOUT, rx).await {
Ok(Ok(RpcResult::Ok { value })) => Ok(value),
Ok(Ok(RpcResult::Err { error })) => {
Err(BrokerError::Registry(error.code, error.message))
}
Ok(Err(_)) => Err(BrokerError::ReplyClosed),
Err(_) => Err(BrokerError::Timeout(RESOLVE_TIMEOUT)),
}
}
/// Resolve a waiting [`forward_recent_dirs`](Self::forward_recent_dirs);
/// called by the registry-client task on a `ForwardRecentDirsResult` frame.
pub async fn complete_forward_recent_dirs(
&self,
reply_to: ReplyTo,
result: RpcResult<RecentDirs>,
) -> bool {
let entry = self.pending_recent_dirs.lock().unwrap().remove(&reply_to);
match entry {
Some(tx) => tx.send(result).is_ok(),
None => {
tracing::debug!(?reply_to, "no waiter for ForwardRecentDirsResult");
false
}
}
}
/// Broker a cross-daemon gitroot probe: ask the registry to relay a
/// `GitRoot` request for `path` to the daemon named by `daemon_id` (which
/// may be a peer) and return its result (#26).
pub async fn forward_git_root(
&self,
daemon_id: String,
path: String,
) -> Result<GitRoot, BrokerError> {
if !self.connected.load(Ordering::Acquire) {
return Err(BrokerError::NoControlLink);
}
let reply_to = Uuid::new_v4();
let (tx, rx) = oneshot::channel();
self.pending_git_root.lock().unwrap().insert(reply_to, tx);
let _guard = PendingGuard {
map: &*self.pending_git_root,
key: reply_to,
};
if self
.out_tx
.try_send(DaemonOutbound::ForwardGitRoot {
reply_to,
daemon_id,
path,
})
.is_err()
{
return Err(BrokerError::NoControlLink);
}
match tokio::time::timeout(RESOLVE_TIMEOUT, rx).await {
Ok(Ok(RpcResult::Ok { value })) => Ok(value),
Ok(Ok(RpcResult::Err { error })) => {
Err(BrokerError::Registry(error.code, error.message))
}
Ok(Err(_)) => Err(BrokerError::ReplyClosed),
Err(_) => Err(BrokerError::Timeout(RESOLVE_TIMEOUT)),
}
}
/// Resolve a waiting [`forward_git_root`](Self::forward_git_root); called by
/// the registry-client task on a `ForwardGitRootResult` frame.
pub async fn complete_forward_git_root(
&self,
reply_to: ReplyTo,
result: RpcResult<GitRoot>,
) -> bool {
let entry = self.pending_git_root.lock().unwrap().remove(&reply_to);
match entry {
Some(tx) => tx.send(result).is_ok(),
None => {
tracing::debug!(?reply_to, "no waiter for ForwardGitRootResult");
false
}
}
}
/// Resolve a waiting [`forward_create`](Self::forward_create); called by the
/// registry-client task on a `ForwardCreateResult` frame.
pub async fn complete_forward_create(
@@ -573,6 +691,108 @@ mod tests {
assert_eq!(handle.pending_list_dir.lock().unwrap().len(), 0);
}
// ----- #26: forward_recent_dirs / forward_git_root -----
/// `forward_recent_dirs` issues a `ForwardRecentDirs` frame and resolves
/// with the recents once the registry's `ForwardRecentDirsResult` lands.
#[tokio::test]
async fn forward_recent_dirs_round_trips() {
use maestro_protocol::{RecentDir, RecentDirs};
let (handle, mut out_rx) = BrokerHandle::new();
handle.set_connected(true);
let h = handle.clone();
let task = tokio::spawn(async move { h.forward_recent_dirs("konishi".into()).await });
let reply_to = match out_rx.recv().await.expect("ForwardRecentDirs went out") {
DaemonOutbound::ForwardRecentDirs {
reply_to,
daemon_id,
} => {
assert_eq!(daemon_id, "konishi");
reply_to
}
other => panic!("expected ForwardRecentDirs, got {other:?}"),
};
handle
.complete_forward_recent_dirs(
reply_to,
RpcResult::Ok {
value: RecentDirs {
dirs: vec![RecentDir {
cwd: std::path::PathBuf::from("/work"),
last_command: "claude".into(),
last_used: chrono::Utc::now(),
}],
truncated: false,
},
},
)
.await;
let got = task.await.unwrap().expect("recents ok");
assert_eq!(got.dirs.len(), 1);
assert_eq!(got.dirs[0].cwd, std::path::PathBuf::from("/work"));
}
/// `forward_git_root` issues a `ForwardGitRoot` frame carrying the path and
/// resolves with the probe result.
#[tokio::test]
async fn forward_git_root_round_trips() {
use maestro_protocol::GitRoot;
let (handle, mut out_rx) = BrokerHandle::new();
handle.set_connected(true);
let h = handle.clone();
let task = tokio::spawn(async move {
h.forward_git_root("konishi".into(), "/work/sub".into())
.await
});
let reply_to = match out_rx.recv().await.expect("ForwardGitRoot went out") {
DaemonOutbound::ForwardGitRoot {
reply_to,
daemon_id,
path,
} => {
assert_eq!(daemon_id, "konishi");
assert_eq!(path, "/work/sub");
reply_to
}
other => panic!("expected ForwardGitRoot, got {other:?}"),
};
handle
.complete_forward_git_root(
reply_to,
RpcResult::Ok {
value: GitRoot {
root: Some(std::path::PathBuf::from("/work")),
},
},
)
.await;
let got = task.await.unwrap().expect("gitroot ok");
assert_eq!(got.root, Some(std::path::PathBuf::from("/work")));
}
/// While disconnected, both new broker calls fail fast and leave no pending
/// entry (NAP-263 / NAP-259).
#[tokio::test]
async fn forward_recents_and_gitroot_fail_fast_while_disconnected() {
let (handle, _out_rx) = BrokerHandle::new(); // starts disconnected
assert!(matches!(
handle.forward_recent_dirs("konishi".into()).await,
Err(BrokerError::NoControlLink)
));
assert!(matches!(
handle.forward_git_root("konishi".into(), "/x".into()).await,
Err(BrokerError::NoControlLink)
));
assert_eq!(handle.pending_recent_dirs.lock().unwrap().len(), 0);
assert_eq!(handle.pending_git_root.lock().unwrap().len(), 0);
}
/// NAP-270: if the registry never replies, `resolve_attach` resolves to
/// `BrokerError::Timeout` after `RESOLVE_TIMEOUT` (driven here with a paused
/// clock so the test is instant).
+1
View File
@@ -140,6 +140,7 @@ async fn run(config_override: Option<PathBuf>) -> Result<(), Box<dyn Error>> {
config.hostname.clone(),
config.daemon_url.clone(),
config.home_dir.clone(),
config.spawn_presets.clone(),
catalog.clone(),
events,
client.broker(),
+11
View File
@@ -63,6 +63,8 @@ pub enum ConfigError {
env: &'static str,
path: PathBuf,
},
#[error("invalid [spawn].presets: {0}")]
SpawnPresets(#[from] maestro_config::SpawnConfigError),
}
/// Resolved, validated daemon configuration ready to drive the binary.
@@ -101,6 +103,10 @@ pub struct DaemonConfig {
/// form's "recent dirs" picker (#24). `0` disables history. Default
/// [`DEFAULT_SPAWN_HISTORY_DAYS`].
pub spawn_history_days: u32,
/// Resolved spawn-form command presets (#22/#26): `[spawn].presets` (or the
/// built-ins) with the implicit `custom` tile appended. Advertised to the
/// web in `GET /api/web/info`.
pub spawn_presets: Vec<maestro_config::SpawnPreset>,
}
impl DaemonConfig {
@@ -195,6 +201,10 @@ pub fn load_config(path: &Path, env: EnvOverrides) -> Result<DaemonConfig, Confi
let shared = file.shared;
let daemon = file.daemon;
// Resolve spawn presets up front so a bad `[spawn].presets` (empty/dup id,
// empty command) refuses startup with a clear error, like other config
// validation (#22/#26).
let spawn_presets = file.spawn.resolve()?;
let hostname = daemon.hostname.unwrap_or_else(system_hostname);
let home_dir = dirs::home_dir()
@@ -269,6 +279,7 @@ pub fn load_config(path: &Path, env: EnvOverrides) -> Result<DaemonConfig, Confi
pty_replay_bytes,
tmux_tmpdir,
spawn_history_days,
spawn_presets,
})
}
+5 -1
View File
@@ -61,7 +61,11 @@ pub fn list_dir(home_dir: &str, requested: &str) -> Result<DirListing, ErrorInfo
}
/// Expand an abbreviated client path against the daemon's home dir.
fn resolve(home_dir: &str, requested: &str) -> PathBuf {
///
/// Shared with the gitroot probe (#26) so a `~`/relative/empty path the client
/// sends is resolved against the daemon's `$HOME` the same way before walking
/// up for the enclosing repo.
pub fn resolve(home_dir: &str, requested: &str) -> PathBuf {
let home = PathBuf::from(home_dir);
let trimmed = requested.trim();
if trimmed.is_empty() {
+53 -2
View File
@@ -30,8 +30,10 @@ 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::{
CreateSessionRequest, DaemonInfo, DirListing, ErrorInfo, Session, PROTOCOL_VERSION,
CreateSessionRequest, DaemonInfo, DirListing, ErrorInfo, GitRoot, RecentDirs, Session,
PROTOCOL_VERSION,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -42,13 +44,18 @@ use crate::session::SessionManager;
/// Daemon identity returned by `GET /api/web/info`. Browsers render this in the
/// header ("you're connected to konishi"); the field set mirrors `DaemonInfo`
/// plus the running daemon's protocol version.
/// plus the running daemon's protocol version and its spawn presets (#26).
#[derive(Debug, Clone, Serialize)]
pub struct WebInfo {
pub daemon_id: String,
pub hostname: String,
pub version: String,
pub daemon_url: String,
/// Spawn-form command presets resolved from `[spawn].presets` (#22), with
/// the implicit `custom` tile appended. The web renders 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)]
@@ -59,6 +66,8 @@ pub struct LocalApiState {
/// 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/web/info`.
pub presets: Arc<Vec<SpawnPreset>>,
/// Peer-only mirror of the global catalog. Empty until the daemon's
/// registry client connects and receives the snapshot.
pub catalog: CatalogMirror,
@@ -76,6 +85,8 @@ pub fn router(state: LocalApiState) -> Router {
.route("/api/sessions/:id", delete(kill_session))
.route("/api/daemons", get(list_daemons))
.route("/api/daemons/:id/dirs", get(list_dir))
.route("/api/daemons/:id/recent-dirs", get(recent_dirs))
.route("/api/daemons/:id/gitroot", get(git_root))
.route("/api/web/info", get(web_info))
.route("/api/events", any(events_ws))
.with_state(state)
@@ -140,12 +151,49 @@ fn dir_error_status(code: &str) -> StatusCode {
}
}
/// Recent working dirs on `daemon_id`'s host for the spawn form's recents
/// picker (#26). Reads locally when the target is this daemon; otherwise brokers
/// a `RecentDirs` query to the owning daemon over the registry control link.
async fn recent_dirs(State(s): State<LocalApiState>, Path(daemon_id): Path<String>) -> Response {
if daemon_id == s.manager.daemon_id() {
let value = crate::spawn_history::to_wire(s.manager.recent_dirs());
return Json(value).into_response();
}
match s.broker.forward_recent_dirs(daemon_id).await {
Ok(recents) => Json::<RecentDirs>(recents).into_response(),
Err(e) => broker_error_response(&e),
}
}
/// Probe the enclosing git repo of `path` on `daemon_id`'s host, to infer the
/// worktree `base_repo` for the spawn form (#26). Local when the target is this
/// daemon; otherwise brokered to the owning daemon. `path` is resolved against
/// the target daemon's home dir (empty/`~`/relative), like [`list_dir`].
async fn git_root(
State(s): State<LocalApiState>,
Path(daemon_id): Path<String>,
Query(q): Query<DirQuery>,
) -> Response {
if daemon_id == s.manager.daemon_id() {
let dir = crate::dirlist::resolve(&s.home_dir, &q.path);
let value = GitRoot {
root: crate::gitroot::find_root(&dir),
};
return Json(value).into_response();
}
match s.broker.forward_git_root(daemon_id, q.path).await {
Ok(root) => Json::<GitRoot>(root).into_response(),
Err(e) => broker_error_response(&e),
}
}
async fn web_info(State(s): State<LocalApiState>) -> Json<WebInfo> {
Json(WebInfo {
daemon_id: s.manager.daemon_id().to_string(),
hostname: (*s.hostname).clone(),
version: PROTOCOL_VERSION.into(),
daemon_url: (*s.daemon_url).clone(),
presets: (*s.presets).clone(),
})
}
@@ -249,11 +297,13 @@ fn error_response(status: StatusCode, code: &str, message: &str) -> Response {
/// Convenience constructor — pulls the bits `LocalApiState` needs from
/// `DaemonConfig` so callers don't have to assemble it by hand.
#[allow(clippy::too_many_arguments)]
pub fn state_for(
manager: SessionManager,
hostname: impl Into<String>,
daemon_url: impl Into<String>,
home_dir: impl Into<String>,
presets: Vec<SpawnPreset>,
catalog: CatalogMirror,
events: LocalEventBus,
broker: BrokerHandle,
@@ -263,6 +313,7 @@ pub fn state_for(
hostname: Arc::new(hostname.into()),
daemon_url: Arc::new(daemon_url.into()),
home_dir: Arc::new(home_dir.into()),
presets: Arc::new(presets),
catalog,
events,
broker,
@@ -379,6 +379,44 @@ impl RegistryClient {
.complete_forward_list_dir(reply_to, result)
.await;
}
DaemonInbound::RecentDirs { reply_to } => {
// Answer a peer's recent-dirs query from this host's spawn
// history (#26). Daemon-wide, so no path to resolve.
let value = crate::spawn_history::to_wire(self.manager.recent_dirs());
sink.send(Message::Text(serde_json::to_string(
&DaemonOutbound::RecentDirsResult {
reply_to,
result: RpcResult::Ok { value },
},
)?))
.await?;
}
DaemonInbound::ForwardRecentDirsResult { reply_to, result } => {
self.broker
.complete_forward_recent_dirs(reply_to, result)
.await;
}
DaemonInbound::GitRoot { reply_to, path } => {
// Probe the enclosing repo of `path` on this host (#26),
// resolving the abbreviated path against this daemon's home the
// same way `ListDir` does.
let dir = crate::dirlist::resolve(&self.home_dir, &path);
let value = maestro_protocol::GitRoot {
root: crate::gitroot::find_root(&dir),
};
sink.send(Message::Text(serde_json::to_string(
&DaemonOutbound::GitRootResult {
reply_to,
result: RpcResult::Ok { value },
},
)?))
.await?;
}
DaemonInbound::ForwardGitRootResult { reply_to, result } => {
self.broker
.complete_forward_git_root(reply_to, result)
.await;
}
DaemonInbound::RelaySetup { .. } => {
// T3 (relay) is gated on NAP-238. Lands here only so newer
// registries sending it don't crash this daemon on parse.
@@ -61,6 +61,23 @@ pub struct RecentDir {
pub last_used: DateTime<Utc>,
}
/// Map daemon-local recents to the wire payload (#26). `recent_dirs` already
/// caps and dedups, so `truncated` is always false here — the field exists for
/// wire symmetry with [`maestro_protocol::DirListing`].
pub fn to_wire(dirs: Vec<RecentDir>) -> maestro_protocol::RecentDirs {
maestro_protocol::RecentDirs {
dirs: dirs
.into_iter()
.map(|d| maestro_protocol::RecentDir {
cwd: d.cwd,
last_command: d.last_command,
last_used: d.last_used,
})
.collect(),
truncated: false,
}
}
/// Append-only JSONL spawn log rooted at a file path, with a recency cap.
/// Cheap to clone — just the path + caps.
#[derive(Debug, Clone)]