crew-watch 0.3.0

Terminal monitor for firstmate fleets: htop-style system overview plus one row per running AI agent session, with subtree-aggregated CPU and memory, task and activity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! crew-watch entry point: argument parsing, terminal setup/teardown, and the
//! render/tick event loop.

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);

    // --- quota configuration (clamped cadence; see cli.rs for the floor) ---
    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;
    }
    // No config path (no $HOME) ⇒ auto mode, session-only; a notice surfaces if
    // the user later tries to persist a selection from the dialog.

    if cli.once {
        run_once(&mut app);
        return Ok(());
    }

    // Spawn the background poller (never on the /proc tick path).
    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)?;

    // Restore the terminal even on panic so the user is never left in raw mode.
    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(())
}

/// `--once`: two samples ~1s apart (so CPU% is real), with the quota fetch
/// running concurrently on a thread so its ~0.8s wall overlaps the sampling
/// sleep. Then print and exit.
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);
}

/// Render + input/tick loop. Polls with a timeout of the remaining time until
/// the next refresh, so input stays responsive while /proc is read at most once
/// per interval.
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()? {
                // Ctrl-C is the documented always-available escape hatch: it quits
                // even with the dialog open (where Esc/q close the dialog instead).
                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;
                    }
                    // Any non-quit key clears the transient notice.
                    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)
}

/// Open the provider-selection dialog. The item list is built from the latest
/// report (live + failing providers) plus any stored ids no longer reported, so
/// the list always reflects what quota-axi actually reports — never hardcoded.
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));
}

/// Route a key to the open dialog. `Save` persists the selection (best-effort;
/// failure surfaces as a notice, the in-memory selection still applies for the
/// session), `Cancel` discards. `Esc` closes the dialog without quitting.
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 => {}
    }
}

/// Route a key while the about overlay is open: the trigger key, `q` and
/// `Esc` close it (the same dismiss set as the quota dialog), everything else
/// is consumed so the overlay never leaks keys into the main view. `Ctrl-C`
/// still quits — it is checked before this runs, as for the dialog.
fn handle_about_key(app: &mut App, k: KeyEvent) {
    if about::handle_key(k.code) == about::Outcome::Close {
        app.show_about = false;
    }
}

/// Effective quota poll cadence for `--quota-interval`, clamped to 60..=3600s
/// (a non-finite argument falls back to the 600s default). The 60s floor is not
/// arbitrary — polling the quota tool faster than once a minute gets the account
/// rate-limited — so an under-floor value is raised, never honoured.
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")
}

/// Fixed-width prefix of an agent row in `--once` output: every column before
/// TASK plus the separating spaces.
const ONCE_TASK_PREFIX_WIDTH: usize = 77;
/// ELAPSED's column width in `--once` output: a surface-local width like the
/// others in [`once_agent_header`], not the TUI's. Nine cells hold `999:59:59`
/// and `41d16h`.
const ONCE_ELAPSED_WIDTH: usize = 9;

/// Header line of the agent table in `--once` output. Column *alignment*
/// mirrors the TUI table (src/ui.rs): numeric columns — PID, ELAPSED, CPU%,
/// MEM — right-align so magnitudes stack; text columns stay left-aligned. The
/// column widths are this surface's own: `--once` writes to a plain stream and
/// never reflows, so they need not match the TUI's. STATE is a word here, not
/// the TUI's emoji glyph: words grep better and keep char count equal to
/// display width (see [`crate::activity::Activity::once_label`]).
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
    )
}

/// One agent row in `--once` output, in the column geometry of
/// [`once_agent_header`] and sharing the TUI table's per-column alignment.
#[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
    )
}

/// Non-interactive text dump of one snapshot (the `--once` path).
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());
        // On a real terminal, fit the TASK column to the remaining width (id
        // dropped first, then title shortens under the protected project
        // prefix); when piped/redirected, print the full composed line —
        // `project: title` for fleet rows — unfitted. crossterm's size()
        // consults /dev/tty and would succeed even with stdout redirected,
        // hence the explicit is_terminal gate.
        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);
}

/// Print the quota lines for `--once`, after the agents table. Bar-free, one
/// line per effective provider in report order; a fetch-level failure with an
/// explicit selection prints a single greppable `quota: unavailable (...)` line.
/// Auto mode with no provider reporting windows (or `--no-quota`) prints nothing.
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)
        );
    }

    /// Column just past the end of `needle` in `line` (its right edge).
    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() {
        // The captain's example rows: same columns, different value widths.
        // 827115 pid, 3:38:41 elapsed, 2.0% cpu, 722.0MiB rss (739328 KiB).
        let short = once_agent_row(
            "busy",
            "opencode",
            "glm-5.3",
            827_115,
            3 * 3600 + 38 * 60 + 41,
            2.0,
            739_328,
            "task one",
        );
        // 483889 pid, 38:23:40 elapsed, 31.8% cpu, 687.8MiB rss (704307 KiB).
        let long = once_agent_row(
            "blocked",
            "claude",
            "-",
            483_889,
            38 * 3600 + 23 * 60 + 40,
            31.8,
            704_307,
            "task two",
        );

        // ELAPSED / CPU% / MEM: different widths, same right edge.
        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")
        );

        // PID: an identifier, but right-aligned with the rest of the numeric
        // block (the same convention as the TUI table; see src/ui.rs).
        assert_eq!(right_edge(&short, "827115"), right_edge(&long, "483889"));

        // Headers sit over the same right edges as their column's values.
        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();
        // 999:59:59 is the last H:MM:SS value; 1000 hours switches to days.
        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"));
        }
        // No duration, however large, pushes the row past its column.
        // A value wider than its slot would push TASK right, so TASK's start
        // column catches an over-wide ELAPSED that a prefix match would miss.
        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() {
        // `--model claude-opus-5-5[1m]`, provider prefix already stripped.
        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] "));
        // MODEL is left-aligned: the header and the value share a start column.
        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",
        );
        // STATE at column 0, then RUNTIME and MODEL, all left-aligned.
        assert!(row.starts_with("human   claude"));
        assert!(row.starts_with("human   claude     -"));
        // TASK begins right after the fixed prefix (the width-fit boundary).
        assert_eq!(
            row.char_indices().nth(ONCE_TASK_PREFIX_WIDTH).unwrap().1,
            'i'
        );
    }
}