Replace the freeform `metadata.label` session grouping with nesting derived
from each session's working directory. The daemon's activity watcher already
polls each tmux pane every tick, so it now also captures
`#{pane_current_path}` and surfaces it as a new `Session.current_cwd`
(serde-default, back-compat); `cwd` stays the spawn dir for worktree
inference, spawn-similar, and recents.
Web catalog builds the tree from `current_cwd ?? cwd`, collapses the home
dir to `~`, and folds single-child folder chains so `~/git/maestro` reads as
one node. CLI swaps its LABEL column for an abbreviated DIR; the spawn forms
(web + TUI) and `--label` flag are removed.
The pane format stays space-delimited (parser splits the first three tokens
and keeps the remainder as the path) so a cwd containing spaces survives.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
298 lines
9.9 KiB
Rust
298 lines
9.9 KiB
Rust
//! `maestro list / spawn / kill` — registry HTTP calls + console formatting.
|
|
|
|
use std::collections::HashMap;
|
|
use std::io::Write;
|
|
|
|
use maestro_protocol::{
|
|
ActivityState, ConnectInfo, CreateSessionRequest, DaemonInfo, Session, SessionStatus,
|
|
WorktreeSpec,
|
|
};
|
|
use serde_json::Value;
|
|
use uuid::Uuid;
|
|
|
|
use crate::cli::{KillArgs, ListArgs, SpawnArgs};
|
|
use crate::http::{HttpError, RegistryClient};
|
|
|
|
/// `maestro list`
|
|
pub async fn run_list(
|
|
client: &RegistryClient,
|
|
args: &ListArgs,
|
|
out: &mut impl Write,
|
|
) -> Result<(), HttpError> {
|
|
let mut sessions: Vec<Session> = client.get_json("/api/sessions").await?;
|
|
let daemons: Vec<DaemonInfo> = client
|
|
.get_json::<Vec<DaemonInfo>>("/api/daemons")
|
|
.await
|
|
.unwrap_or_default();
|
|
if let Some(d) = &args.daemon {
|
|
sessions.retain(|s| &s.daemon_id == d);
|
|
}
|
|
|
|
if args.json {
|
|
let body = serde_json::json!({ "sessions": sessions, "daemons": daemons });
|
|
writeln!(out, "{}", serde_json::to_string_pretty(&body)?).ok();
|
|
return Ok(());
|
|
}
|
|
|
|
print_session_table(out, &sessions, &daemons);
|
|
Ok(())
|
|
}
|
|
|
|
/// `maestro spawn`
|
|
pub async fn run_spawn(client: &RegistryClient, args: SpawnArgs) -> Result<Session, HttpError> {
|
|
let mut env: HashMap<String, String> = HashMap::new();
|
|
for (k, v) in args.env.iter() {
|
|
env.insert(k.clone(), v.clone());
|
|
}
|
|
|
|
let metadata: HashMap<String, Value> = HashMap::new();
|
|
|
|
let worktree = match (args.worktree_from.as_ref(), args.branch.as_ref()) {
|
|
(Some(repo), Some(branch)) => Some(WorktreeSpec {
|
|
base_repo: repo.clone(),
|
|
branch: branch.clone(),
|
|
cleanup_on_kill: args.cleanup_on_kill,
|
|
}),
|
|
_ => None,
|
|
};
|
|
|
|
let body = CreateSessionRequest {
|
|
daemon_id: args.daemon.clone(),
|
|
cwd: args.cwd.clone(),
|
|
command: args.command.clone(),
|
|
env,
|
|
metadata,
|
|
worktree,
|
|
};
|
|
let session: Session = client.post_json("/api/sessions", &body).await?;
|
|
Ok(session)
|
|
}
|
|
|
|
/// `maestro kill`
|
|
pub async fn run_kill(client: &RegistryClient, args: &KillArgs) -> Result<(), HttpError> {
|
|
client
|
|
.delete(&format!("/api/sessions/{}", args.session_id))
|
|
.await
|
|
}
|
|
|
|
/// `GET /api/sessions/:id/connect-info`
|
|
pub async fn fetch_connect_info(
|
|
client: &RegistryClient,
|
|
session_id: Uuid,
|
|
) -> Result<ConnectInfo, HttpError> {
|
|
client
|
|
.get_json(&format!("/api/sessions/{session_id}/connect-info"))
|
|
.await
|
|
}
|
|
|
|
#[allow(clippy::write_literal)]
|
|
fn print_session_table(out: &mut impl Write, sessions: &[Session], daemons: &[DaemonInfo]) {
|
|
if sessions.is_empty() {
|
|
if daemons.is_empty() {
|
|
writeln!(out, "no sessions, no daemons connected").ok();
|
|
} else {
|
|
writeln!(
|
|
out,
|
|
"no sessions ({} daemon{} connected)",
|
|
daemons.len(),
|
|
if daemons.len() == 1 { "" } else { "s" }
|
|
)
|
|
.ok();
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Group by daemon, stable order.
|
|
let mut by_daemon: Vec<(String, Vec<&Session>)> = Vec::new();
|
|
for s in sessions {
|
|
if let Some(slot) = by_daemon.iter_mut().find(|(d, _)| d == &s.daemon_id) {
|
|
slot.1.push(s);
|
|
} else {
|
|
by_daemon.push((s.daemon_id.clone(), vec![s]));
|
|
}
|
|
}
|
|
for (_, group) in &mut by_daemon {
|
|
group.sort_by_key(|s| s.created_at);
|
|
}
|
|
|
|
for (daemon_id, group) in &by_daemon {
|
|
let daemon = daemons.iter().find(|d| &d.daemon_id == daemon_id);
|
|
let hostname = daemon.map(|d| d.hostname.as_str()).unwrap_or("?");
|
|
let home = daemon.map(|d| d.home_dir.as_str()).unwrap_or("");
|
|
writeln!(out, "\n{daemon_id} ({hostname})").ok();
|
|
writeln!(
|
|
out,
|
|
" {:<36} {:<8} {:<9} {:<28} {}",
|
|
"ID", "STATUS", "ACTIVITY", "DIR", "COMMAND"
|
|
)
|
|
.ok();
|
|
for s in group {
|
|
// The pane's live cwd if observed, else the spawn dir, home-abbreviated.
|
|
let dir = abbreviate_dir(s.current_cwd.as_deref().unwrap_or(&s.cwd), home);
|
|
let status = match s.status {
|
|
SessionStatus::Running => "running",
|
|
SessionStatus::Dead => "dead",
|
|
};
|
|
let activity = match s.activity {
|
|
ActivityState::Active => "active",
|
|
ActivityState::Idle => "idle",
|
|
ActivityState::AwaitingInput => "awaiting",
|
|
};
|
|
// Show the live foreground command alongside the spawn command when
|
|
// the daemon has observed one that differs (NAP-340).
|
|
let command = match &s.foreground {
|
|
Some(fg) if fg != &s.command => format!("{} [{}]", s.command, fg),
|
|
_ => s.command.clone(),
|
|
};
|
|
writeln!(
|
|
out,
|
|
" {:<36} {:<8} {:<9} {:<28} {command}",
|
|
s.id, status, activity, dir
|
|
)
|
|
.ok();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Render a path with the daemon's home dir collapsed to `~`. Mirrors the web
|
|
/// UI's abbreviation so CLI and browser show the same directory shorthand.
|
|
fn abbreviate_dir(path: &std::path::Path, home: &str) -> String {
|
|
let p = path.to_string_lossy();
|
|
if !home.is_empty() {
|
|
if p == home {
|
|
return "~".into();
|
|
}
|
|
if let Some(rest) = p.strip_prefix(&format!("{home}/")) {
|
|
return format!("~/{rest}");
|
|
}
|
|
}
|
|
p.into_owned()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::collections::HashMap;
|
|
use std::path::PathBuf;
|
|
|
|
use chrono::{TimeZone, Utc};
|
|
use maestro_protocol::{ActivityState, DaemonInfo, Session, SessionStatus};
|
|
use uuid::Uuid;
|
|
|
|
fn session(daemon: &str, cwd: &str, command: &str, id: u128) -> Session {
|
|
Session {
|
|
id: Uuid::from_u128(id),
|
|
daemon_id: daemon.into(),
|
|
cwd: PathBuf::from(cwd),
|
|
command: command.into(),
|
|
env: HashMap::new(),
|
|
metadata: HashMap::new(),
|
|
status: SessionStatus::Running,
|
|
created_at: Utc.with_ymd_and_hms(2026, 5, 25, 12, 0, 0).unwrap(),
|
|
foreground: None,
|
|
activity: Default::default(),
|
|
last_activity_at: chrono::Utc::now(),
|
|
current_cwd: None,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn formats_grouped_table() {
|
|
let sessions = vec![
|
|
session("laptop", "/home/naps/maestro", "claude", 1),
|
|
session("vm1", "/srv/work/api", "bash", 2),
|
|
session("laptop", "/home/naps/scratch", "nvim", 3),
|
|
];
|
|
let daemons = vec![
|
|
DaemonInfo {
|
|
daemon_id: "laptop".into(),
|
|
hostname: "naps-laptop".into(),
|
|
version: "0.1.0".into(),
|
|
daemon_url: "ws://10.0.0.1:7070".into(),
|
|
home_dir: "/home/naps".into(),
|
|
},
|
|
DaemonInfo {
|
|
daemon_id: "vm1".into(),
|
|
hostname: "vm1.lan".into(),
|
|
version: "0.1.0".into(),
|
|
daemon_url: "ws://10.0.0.2:7070".into(),
|
|
home_dir: String::new(),
|
|
},
|
|
];
|
|
let mut buf = Vec::new();
|
|
super::print_session_table(&mut buf, &sessions, &daemons);
|
|
let s = String::from_utf8(buf).unwrap();
|
|
assert!(s.contains("laptop (naps-laptop)"), "{s}");
|
|
assert!(s.contains("vm1 (vm1.lan)"), "{s}");
|
|
// Home dir collapses to ~ in the DIR column.
|
|
assert!(s.contains("~/maestro"), "{s}");
|
|
// No home dir → path shown verbatim.
|
|
assert!(s.contains("/srv/work/api"), "{s}");
|
|
assert!(s.contains("running"), "{s}");
|
|
assert!(s.contains("ACTIVITY"), "{s}");
|
|
assert!(s.contains("DIR"), "{s}");
|
|
assert!(s.contains("idle"), "{s}");
|
|
}
|
|
|
|
#[test]
|
|
fn live_cwd_overrides_spawn_dir_in_table() {
|
|
let mut s = session("laptop", "/home/naps/maestro", "bash", 1);
|
|
s.current_cwd = Some(PathBuf::from("/home/naps/maestro/crates/maestro-cli"));
|
|
let daemons = vec![DaemonInfo {
|
|
daemon_id: "laptop".into(),
|
|
hostname: "h".into(),
|
|
version: "0.1.0".into(),
|
|
daemon_url: "ws://x".into(),
|
|
home_dir: "/home/naps".into(),
|
|
}];
|
|
let mut buf = Vec::new();
|
|
super::print_session_table(&mut buf, &[s], &daemons);
|
|
let out = String::from_utf8(buf).unwrap();
|
|
assert!(out.contains("~/maestro/crates/maestro-cli"), "{out}");
|
|
}
|
|
|
|
#[test]
|
|
fn shows_activity_and_foreground() {
|
|
let mut s1 = session("laptop", "/tmp", "bash", 1);
|
|
s1.activity = ActivityState::AwaitingInput;
|
|
s1.foreground = Some("claude".into()); // differs from spawn command
|
|
let daemons = vec![DaemonInfo {
|
|
daemon_id: "laptop".into(),
|
|
hostname: "h".into(),
|
|
version: "0.1.0".into(),
|
|
daemon_url: "ws://x".into(),
|
|
home_dir: String::new(),
|
|
}];
|
|
let mut buf = Vec::new();
|
|
super::print_session_table(&mut buf, &[s1], &daemons);
|
|
let out = String::from_utf8(buf).unwrap();
|
|
assert!(out.contains("awaiting"), "{out}");
|
|
// Live foreground surfaces next to the spawn command.
|
|
assert!(out.contains("bash [claude]"), "{out}");
|
|
}
|
|
|
|
#[test]
|
|
fn empty_sessions_with_no_daemons() {
|
|
let mut buf = Vec::new();
|
|
super::print_session_table(&mut buf, &[], &[]);
|
|
assert_eq!(
|
|
String::from_utf8(buf).unwrap(),
|
|
"no sessions, no daemons connected\n"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn empty_sessions_with_daemons() {
|
|
let daemons = vec![DaemonInfo {
|
|
daemon_id: "laptop".into(),
|
|
hostname: "naps".into(),
|
|
version: "0.1.0".into(),
|
|
daemon_url: "ws://x".into(),
|
|
home_dir: String::new(),
|
|
}];
|
|
let mut buf = Vec::new();
|
|
super::print_session_table(&mut buf, &[], &daemons);
|
|
let s = String::from_utf8(buf).unwrap();
|
|
assert!(s.contains("1 daemon connected"), "{s}");
|
|
}
|
|
}
|