mod about;
mod activity;
mod agent_cols;
mod app;
mod cli;
mod config;
mod detect;
mod format_util;
mod macos;
mod meta;
mod model;
mod procfs;
mod project;
mod quota;
mod quota_dialog;
mod quota_row;
mod taskinfo;
mod titles;
mod ui;
use std::io;
use std::path::PathBuf;
use std::sync::mpsc::channel;
use std::time::{Duration, Instant};
use clap::Parser;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::Backend;
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use crate::agent_cols::fit_elapsed;
use crate::app::App;
use crate::cli::Cli;
use crate::quota::{spawn_poller, QuotaFetch};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
let interval_secs = if cli.interval.is_finite() {
cli.interval.clamp(0.1, 3600.0)
} else {
2.0
};
let interval = Duration::from_secs_f64(interval_secs);
let fm_home = resolve_fm_home(cli.fm_home);
let mut app = App::new(interval, fm_home);
app.quota_enabled = !cli.no_quota;
app.quota_interval = resolve_quota_interval(cli.quota_interval);
if let Some(path) = config::config_path() {
let cfg = config::load(&path);
app.quota_selected = cfg.quota_providers;
}
if cli.once {
run_once(&mut app);
return Ok(());
}
if app.quota_enabled {
let (tx, rx) = channel::<QuotaFetch>();
app.quota_rx = Some(rx);
spawn_poller(app.quota_interval, tx);
}
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let original_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), LeaveAlternateScreen);
original_hook(info);
}));
app.tick();
let result = run(&mut terminal, &mut app);
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
terminal.show_cursor()?;
result?;
Ok(())
}
fn run_once(app: &mut App) {
let quota_handle = if app.quota_enabled {
Some(std::thread::spawn(|| {
crate::quota::fetch_once(Duration::from_secs(10))
}))
} else {
None
};
app.tick();
std::thread::sleep(Duration::from_millis(1000));
app.tick();
if let Some(h) = quota_handle {
if let Ok(fetch) = h.join() {
match fetch {
QuotaFetch::Report(r) => app.quota.report = Some(r),
QuotaFetch::Failed(e) => app.quota.last_error = Some(e),
}
}
}
print_once(app);
}
fn run<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> io::Result<()> {
let mut last_tick = Instant::now();
loop {
app.drain_quota();
terminal.draw(|f| ui::draw(f, app))?;
let timeout = app.interval.saturating_sub(last_tick.elapsed());
if event::poll(timeout)? {
if let Event::Key(k) = event::read()? {
if is_ctrl_c(&k) {
return Ok(());
}
if app.dialog.is_some() {
handle_dialog_key(app, k);
} else if app.show_about {
handle_about_key(app, k);
} else {
if is_quit(&k) {
return Ok(());
}
if matches!(k.code, KeyCode::Char('p')) && app.quota_enabled {
open_dialog(app);
}
if matches!(k.code, KeyCode::Char('a')) {
app.show_about = true;
}
app.notice = None;
}
}
}
if last_tick.elapsed() >= app.interval {
app.tick();
last_tick = Instant::now();
}
}
}
fn is_quit(k: &KeyEvent) -> bool {
match k.code {
KeyCode::Char('q') | KeyCode::Esc => true,
_ => is_ctrl_c(k),
}
}
fn is_ctrl_c(k: &KeyEvent) -> bool {
matches!(k.code, KeyCode::Char('c')) && k.modifiers.contains(KeyModifiers::CONTROL)
}
fn open_dialog(app: &mut App) {
let report = app.quota.report.as_ref();
let stored = app.quota_selected.as_deref();
let auto = quota_dialog::auto_ids(report);
app.dialog = Some(quota_dialog::open(report, stored, &auto));
}
fn handle_dialog_key(app: &mut App, k: KeyEvent) {
use quota_dialog::Outcome;
let Some(dialog) = app.dialog.as_mut() else {
return;
};
match dialog.handle_key(k.code) {
Outcome::Save(ids) => {
match config::config_path() {
Some(path) => {
if let Err(e) = config::save_quota_providers(&path, &ids) {
app.notice = Some(format!("config save failed: {e}"));
}
}
None => app.notice = Some("selection not persisted (no $HOME)".to_string()),
}
app.quota_selected = Some(ids);
app.dialog = None;
}
Outcome::Cancel => {
app.dialog = None;
}
Outcome::Pending => {}
}
}
fn handle_about_key(app: &mut App, k: KeyEvent) {
if about::handle_key(k.code) == about::Outcome::Close {
app.show_about = false;
}
}
fn resolve_quota_interval(arg_secs: f64) -> Duration {
let secs = if arg_secs.is_finite() {
arg_secs.clamp(60.0, 3600.0)
} else {
600.0
};
Duration::from_secs_f64(secs)
}
fn resolve_fm_home(arg: Option<PathBuf>) -> PathBuf {
if let Some(p) = arg {
return p;
}
if let Ok(home) = std::env::var("HOME") {
return PathBuf::from(home).join("agents").join("firstmate");
}
PathBuf::from("agents/firstmate")
}
const ONCE_TASK_PREFIX_WIDTH: usize = 77;
const ONCE_ELAPSED_WIDTH: usize = 9;
fn once_agent_header() -> String {
format!(
"{:<7} {:<10} {:<20} {:>7} {:>elapsed$} {:>7} {:>9} TASK",
"STATE",
"RUNTIME",
"MODEL",
"PID",
"ELAPSED",
"CPU%",
"MEM",
elapsed = ONCE_ELAPSED_WIDTH
)
}
#[allow(clippy::too_many_arguments)]
fn once_agent_row(
state: &str,
kind: &str,
model: &str,
pid: i32,
elapsed_secs: u64,
cpu_percent: f64,
rss_kib: u64,
task: &str,
) -> String {
use crate::format_util::{format_kib, format_percent};
format!(
"{:<7} {:<10} {:<20.20} {:>7} {:>elapsed$} {:>7} {:>9} {}",
state,
kind,
model,
pid,
fit_elapsed(elapsed_secs, ONCE_ELAPSED_WIDTH),
format_percent(cpu_percent),
format_kib(rss_kib),
task,
elapsed = ONCE_ELAPSED_WIDTH
)
}
fn print_once(app: &App) {
use crate::format_util::{format_kib, format_uptime};
use crate::procfs::CpuLine;
use crate::taskinfo::{compose_task_line, fit_task_line};
use std::io::IsTerminal;
let Some(snap) = app.snapshot() else {
println!("no snapshot");
return;
};
let cores: Vec<&CpuLine> = snap.cpus.iter().filter(|c| !c.is_aggregate()).collect();
let mem_used = snap
.mem
.mem_total_kib
.saturating_sub(snap.mem.mem_avail_kib);
let swap_used = snap
.mem
.swap_total_kib
.saturating_sub(snap.mem.swap_free_kib);
println!(
"cores={} mem={}/{} swap={}/{} tasks={} load={:.2} {:.2} {:.2} up={}",
cores.len(),
format_kib(mem_used),
format_kib(snap.mem.mem_total_kib),
format_kib(swap_used),
format_kib(snap.mem.swap_total_kib),
snap.load.total,
snap.load.one,
snap.load.five,
snap.load.fifteen,
format_uptime(snap.uptime.secs.max(0.0) as u64)
);
if app.sessions.is_empty() {
println!("agents: (none detected)");
} else {
println!("{}", once_agent_header());
let task_width = if io::stdout().is_terminal() {
crossterm::terminal::size()
.ok()
.map(|(w, _)| (w as usize).saturating_sub(ONCE_TASK_PREFIX_WIDTH).max(1))
} else {
None
};
for s in &app.sessions {
let model = if s.model.is_empty() {
"-".to_string()
} else {
s.model.clone()
};
let task = match task_width {
Some(w) => fit_task_line(s.task_project.as_deref(), &s.task, w),
None => compose_task_line(s.task_project.as_deref(), &s.task),
};
println!(
"{}",
once_agent_row(
s.activity.once_label(),
s.kind.display,
&model,
s.pid,
s.elapsed_secs,
s.cpu_percent,
s.rss_kib,
&task
)
);
}
}
print_once_quota(app);
}
fn print_once_quota(app: &App) {
use std::time::{SystemTime, UNIX_EPOCH};
if !app.quota_enabled {
return;
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
match app.effective_selection() {
crate::app::QuotaSelection::Auto => {
if let Some(r) = &app.quota.report {
for p in &r.providers {
if crate::quota::has_usage_windows(p) {
let suffix = if p.stale { " (stale)" } else { "" };
println!("quota {}{}", crate::quota_row::once_line(p, now), suffix);
}
}
}
}
crate::app::QuotaSelection::Explicit(ids) => {
if ids.is_empty() {
return;
}
match &app.quota.report {
Some(r) => {
for p in &r.providers {
if ids.contains(&p.id) {
let suffix = if p.stale { " (stale)" } else { "" };
println!("quota {}{}", crate::quota_row::once_line(p, now), suffix);
}
}
}
None => {
let err = app.quota.last_error.as_deref().unwrap_or("unavailable");
println!("quota: unavailable ({})", err);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quota_interval_default_and_in_range_values_pass_through() {
assert_eq!(resolve_quota_interval(600.0), Duration::from_secs(600));
assert_eq!(resolve_quota_interval(90.0), Duration::from_secs(90));
}
#[test]
fn quota_interval_below_floor_is_raised_to_60s() {
assert_eq!(resolve_quota_interval(5.0), Duration::from_secs(60));
assert_eq!(resolve_quota_interval(0.0), Duration::from_secs(60));
assert_eq!(resolve_quota_interval(-30.0), Duration::from_secs(60));
}
#[test]
fn quota_interval_above_ceiling_and_non_finite_are_bounded() {
assert_eq!(resolve_quota_interval(99_999.0), Duration::from_secs(3600));
assert_eq!(resolve_quota_interval(f64::NAN), Duration::from_secs(600));
assert_eq!(
resolve_quota_interval(f64::INFINITY),
Duration::from_secs(600)
);
}
fn right_edge(line: &str, needle: &str) -> usize {
line.find(needle).expect(needle) + needle.len()
}
#[test]
fn once_numeric_columns_right_align_so_magnitudes_stack() {
let short = once_agent_row(
"busy",
"opencode",
"glm-5.3",
827_115,
3 * 3600 + 38 * 60 + 41,
2.0,
739_328,
"task one",
);
let long = once_agent_row(
"blocked",
"claude",
"-",
483_889,
38 * 3600 + 23 * 60 + 40,
31.8,
704_307,
"task two",
);
assert_eq!(right_edge(&short, "3:38:41"), right_edge(&long, "38:23:40"));
assert_eq!(right_edge(&short, "2.0%"), right_edge(&long, "31.8%"));
assert_eq!(
right_edge(&short, "722.0MiB"),
right_edge(&long, "687.8MiB")
);
assert_eq!(right_edge(&short, "827115"), right_edge(&long, "483889"));
let header = once_agent_header();
assert_eq!(right_edge(&header, "PID"), right_edge(&long, "483889"));
assert_eq!(
right_edge(&header, "ELAPSED"),
right_edge(&long, "38:23:40")
);
assert_eq!(right_edge(&header, "CPU%"), right_edge(&long, "31.8%"));
assert_eq!(right_edge(&header, "MEM"), right_edge(&long, "687.8MiB"));
}
#[test]
fn once_elapsed_column_stays_within_its_width_at_every_duration() {
let header = once_agent_header();
for (secs, shown) in [
(999 * 3600 + 59 * 60 + 59, "999:59:59"),
(1000 * 3600, "41d16h"),
(1007 * 3600, "41d23h"),
] {
let row = once_agent_row("busy", "claude", "-", 1, secs, 0.0, 0, "task");
assert!(row.contains(shown), "{row}");
assert_eq!(right_edge(&row, shown), right_edge(&header, "ELAPSED"));
}
let row = once_agent_row("busy", "claude", "-", 1, u64::MAX, 0.0, 0, "task");
assert_eq!(row.find("task"), Some(ONCE_TASK_PREFIX_WIDTH));
}
#[test]
fn once_model_column_keeps_the_longest_common_model_whole() {
let row = once_agent_row(
"busy",
"claude",
"claude-opus-5-5[1m]",
1,
0,
0.0,
0,
"task",
);
assert!(row.starts_with("busy claude claude-opus-5-5[1m] "));
assert_eq!(once_agent_header().find("MODEL"), row.find("claude-opus"));
}
#[test]
fn once_text_columns_stay_left_and_task_follows_the_fixed_prefix() {
let row = once_agent_row(
"human",
"claude",
"-",
5463,
10_231,
0.0,
573_440,
"interactive",
);
assert!(row.starts_with("human claude"));
assert!(row.starts_with("human claude -"));
assert_eq!(
row.char_indices().nth(ONCE_TASK_PREFIX_WIDTH).unwrap().1,
'i'
);
}
}