Two web spawn QoL improvements plus the wire support they need: - Command field now prefills `claude` instead of an empty box. - Working directory prefills the selected daemon's home dir, updating on daemon change unless the user has typed their own value. The daemon resolves its `$HOME` via `dirs::home_dir()` at startup and advertises it end-to-end: a new `home_dir` field on `DaemonOutbound::Hello` flows through the registry's `register` into `DaemonInfo` (served on `/api/daemons` and `/api/events`). The field is `#[serde(default)]`, so older daemons that omit it deserialize to an empty string — backward compatible, and the UI simply skips prefill when it's empty. Hierarchical `/`-separated labels in the web sidebar already worked (web/src/catalog.ts); no change there. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
197 lines
6.8 KiB
Rust
197 lines
6.8 KiB
Rust
//! Daemon-local mirror of the registry catalog (NAP-246).
|
|
//!
|
|
//! The registry fans out a stream of `RegistryEvent`s to each connected
|
|
//! daemon, filtered so each one only sees *peer* state. This module owns the
|
|
//! resulting in-memory copy and exposes read snapshots to the daemon's HTTP
|
|
//! handlers (`GET /api/sessions`, `GET /api/daemons`).
|
|
//!
|
|
//! The mirror does *not* include the daemon's own sessions — those come from
|
|
//! `SessionManager`. Combining the two for HTTP responses is the caller's
|
|
//! job (see `local_api.rs`).
|
|
|
|
use std::collections::{BTreeMap, HashMap};
|
|
use std::sync::Arc;
|
|
|
|
use maestro_protocol::{DaemonInfo, RegistryEvent, Session};
|
|
use tokio::sync::Mutex;
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Debug, Default)]
|
|
struct State {
|
|
daemons: HashMap<String, DaemonInfo>,
|
|
/// `(daemon_id, session_id) -> Session` — mirrors the registry's catalog
|
|
/// keying so removals (which arrive as `(daemon_id, id)`) are O(1).
|
|
sessions: BTreeMap<(String, Uuid), Session>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Default)]
|
|
pub struct CatalogMirror {
|
|
inner: Arc<Mutex<State>>,
|
|
/// Optional fan-out (NAP-248). When attached, every applied event is
|
|
/// re-published here so `WS /api/events` subscribers see peer state
|
|
/// changes the same way the registry's clients do.
|
|
bus: Option<crate::local_events::LocalEventBus>,
|
|
}
|
|
|
|
impl CatalogMirror {
|
|
pub fn new() -> Self {
|
|
Self::default()
|
|
}
|
|
|
|
/// Attach a [`LocalEventBus`](crate::local_events::LocalEventBus) so peer
|
|
/// catalog deltas reach the daemon's `/api/events` subscribers.
|
|
pub fn with_bus(mut self, bus: crate::local_events::LocalEventBus) -> Self {
|
|
self.bus = Some(bus);
|
|
self
|
|
}
|
|
|
|
/// Apply one delta. Snapshot events replace the mirror wholesale;
|
|
/// `Lagged` resets it on the assumption that the next full snapshot will
|
|
/// arrive later (today the registry doesn't re-send one — see follow-up
|
|
/// notes in `handler.rs`).
|
|
pub async fn apply(&self, event: RegistryEvent) {
|
|
{
|
|
let mut s = self.inner.lock().await;
|
|
match &event {
|
|
RegistryEvent::Snapshot { daemons, sessions } => {
|
|
s.daemons.clear();
|
|
s.sessions.clear();
|
|
for d in daemons {
|
|
s.daemons.insert(d.daemon_id.clone(), d.clone());
|
|
}
|
|
for sess in sessions {
|
|
s.sessions
|
|
.insert((sess.daemon_id.clone(), sess.id), sess.clone());
|
|
}
|
|
}
|
|
RegistryEvent::DaemonAdded { daemon } => {
|
|
s.daemons.insert(daemon.daemon_id.clone(), daemon.clone());
|
|
}
|
|
RegistryEvent::DaemonRemoved { daemon_id } => {
|
|
s.daemons.remove(daemon_id);
|
|
s.sessions.retain(|(d, _), _| d != daemon_id);
|
|
}
|
|
RegistryEvent::SessionAdded { session }
|
|
| RegistryEvent::SessionUpdated { session } => {
|
|
s.sessions
|
|
.insert((session.daemon_id.clone(), session.id), session.clone());
|
|
}
|
|
RegistryEvent::SessionRemoved { daemon_id, id } => {
|
|
s.sessions.remove(&(daemon_id.clone(), *id));
|
|
}
|
|
RegistryEvent::Lagged { skipped } => {
|
|
tracing::warn!(
|
|
skipped = *skipped,
|
|
"catalog mirror lagged — local view may be stale"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
// Re-publish AFTER releasing the lock so subscribers reading `daemons()`
|
|
// / `sessions()` in response observe the new state.
|
|
if let Some(bus) = &self.bus {
|
|
bus.publish(event);
|
|
}
|
|
}
|
|
|
|
/// Snapshot the peer daemons currently mirrored.
|
|
pub async fn daemons(&self) -> Vec<DaemonInfo> {
|
|
self.inner.lock().await.daemons.values().cloned().collect()
|
|
}
|
|
|
|
/// Snapshot every peer session currently mirrored.
|
|
pub async fn sessions(&self) -> Vec<Session> {
|
|
self.inner.lock().await.sessions.values().cloned().collect()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use chrono::Utc;
|
|
use maestro_protocol::SessionStatus;
|
|
use std::collections::HashMap as StdHashMap;
|
|
|
|
fn peer_session(daemon: &str, id_lo: u128) -> Session {
|
|
Session {
|
|
id: Uuid::from_u128(id_lo),
|
|
daemon_id: daemon.into(),
|
|
cwd: "/tmp".into(),
|
|
command: "bash".into(),
|
|
env: StdHashMap::new(),
|
|
metadata: StdHashMap::new(),
|
|
status: SessionStatus::Running,
|
|
created_at: Utc::now(),
|
|
}
|
|
}
|
|
|
|
fn peer_daemon(daemon_id: &str) -> DaemonInfo {
|
|
DaemonInfo {
|
|
daemon_id: daemon_id.into(),
|
|
hostname: format!("{daemon_id}-host"),
|
|
version: "0.1.0".into(),
|
|
daemon_url: format!("ws://{daemon_id}:7070"),
|
|
home_dir: String::new(),
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn snapshot_replaces_state() {
|
|
let m = CatalogMirror::new();
|
|
m.apply(RegistryEvent::DaemonAdded {
|
|
daemon: peer_daemon("old"),
|
|
})
|
|
.await;
|
|
m.apply(RegistryEvent::Snapshot {
|
|
daemons: vec![peer_daemon("new")],
|
|
sessions: vec![peer_session("new", 1)],
|
|
})
|
|
.await;
|
|
let ds = m.daemons().await;
|
|
assert_eq!(ds.len(), 1);
|
|
assert_eq!(ds[0].daemon_id, "new");
|
|
assert_eq!(m.sessions().await.len(), 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn daemon_removed_cascades_to_sessions() {
|
|
let m = CatalogMirror::new();
|
|
m.apply(RegistryEvent::DaemonAdded {
|
|
daemon: peer_daemon("konishi"),
|
|
})
|
|
.await;
|
|
m.apply(RegistryEvent::SessionAdded {
|
|
session: peer_session("konishi", 1),
|
|
})
|
|
.await;
|
|
m.apply(RegistryEvent::SessionAdded {
|
|
session: peer_session("konishi", 2),
|
|
})
|
|
.await;
|
|
assert_eq!(m.sessions().await.len(), 2);
|
|
|
|
m.apply(RegistryEvent::DaemonRemoved {
|
|
daemon_id: "konishi".into(),
|
|
})
|
|
.await;
|
|
assert!(m.daemons().await.is_empty());
|
|
assert!(m.sessions().await.is_empty());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn session_update_replaces_in_place() {
|
|
let m = CatalogMirror::new();
|
|
m.apply(RegistryEvent::SessionAdded {
|
|
session: peer_session("konishi", 1),
|
|
})
|
|
.await;
|
|
let mut updated = peer_session("konishi", 1);
|
|
updated.status = SessionStatus::Dead;
|
|
m.apply(RegistryEvent::SessionUpdated { session: updated })
|
|
.await;
|
|
let after = m.sessions().await;
|
|
assert_eq!(after.len(), 1);
|
|
assert_eq!(after[0].status, SessionStatus::Dead);
|
|
}
|
|
}
|