crew-watch 0.2.2

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
575
576
577
578
579
580
581
//! TUI rendering: a htop-style system overview on top and an agent list below.
//!
//! Rendering itself is intentionally untested in v1; all the pure logic it
//! depends on (parsing, detection, aggregation, task resolution) is unit-tested
//! in the other modules.

use std::time::{SystemTime, UNIX_EPOCH};

use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block, Borders, Cell, Clear, Paragraph, Row, Table};
use ratatui::Frame;

use crate::about;
use crate::activity::fit_state;
use crate::agent_cols::{
    compressed_col_widths, fit_cpu, fit_elapsed, fit_header, fit_mem, fit_pid, task_width,
    AGENT_COL_SPACING,
};
use crate::app::{App, QuotaSelection};
use crate::detect::{AgentKind, AGENT_KINDS};
use crate::format_util::{format_age_compact, format_kib, format_uptime, make_bar};
use crate::procfs::{CpuLine, Snapshot};
use crate::quota::{has_usage_windows, ProviderQuota};
use crate::quota_row::build_quota_rows;
use crate::taskinfo::fit_task_line;
const MIN_CELL_WIDTH: usize = 18;
const MAX_COLS: usize = 8;
const MEM_BAR_WIDTH: usize = 20;

/// Right-aligned cell for the agent table's numeric columns (PID, ELAPSED,
/// CPU%, MEM): their magnitudes stack on the right edge so rows compare at a
/// glance. PID joins them — like htop and `ps`, and matching `--once` — even
/// though it is an identifier, not a magnitude; digits read as one numeric
/// block. Text columns (STATE, RUNTIME, MODEL, TASK) stay left-aligned, and
/// `--once` aligns the same columns the same way, so the two surfaces read
/// alike (the column *widths* differ by design; only alignment is shared).
///
/// Callers must pass content already fitted to the column's width via the
/// [`crate::agent_cols`] helpers: ratatui truncates an over-width
/// right-aligned line from the left, which would drop exactly the magnitude
/// digits this alignment exists to line up.
fn right_cell(text: String) -> Cell<'static> {
    Cell::from(Text::from(text).alignment(Alignment::Right))
}

pub fn draw(f: &mut Frame, app: &App) {
    let area = f.area();
    let top_h = top_height(app.snapshot(), area.width);
    let quota_h = app.quota_lines_count() as u16;
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(top_h),
            Constraint::Min(4),
            Constraint::Length(quota_h),
            Constraint::Length(1),
        ])
        .split(area);
    draw_top(f, chunks[0], app);
    draw_agents(f, chunks[1], app);
    draw_quota(f, chunks[2], app);
    draw_help(f, chunks[3], app);
    // The dialog overlays the agents area, rendered last so it sits on top.
    if let Some(dialog) = app.dialog.as_ref() {
        if let Some(rect) = centered_dialog(area, dialog.items.len()) {
            draw_dialog(f, rect, app);
        }
    }
    // The about overlay sits on top of everything. It is mutually exclusive
    // with the dialog by key routing: each opens only from the main view.
    if app.show_about {
        let inner = (about::panel_width(area).saturating_sub(2) as usize).max(1);
        let body = about::about_lines(inner);
        if let Some(rect) = about::centered_rect(area, body.len()) {
            draw_about(f, rect, &body);
        }
    }
}

/// Current UTC epoch seconds (for quota reset countdowns at render time).
fn current_epoch_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Height the top panel needs given terminal width (core grid is columnar).
fn top_height(curr: Option<&Snapshot>, width: u16) -> u16 {
    let Some(curr) = curr else {
        return 4;
    };
    let cores = num_cores(curr);
    let cols = cols_for_width(width as usize);
    let rows = cores.div_ceil(cols).max(1);
    // cpu grid rows + mem line + info line + 2 border rows.
    (rows + 2 + 2) as u16
}

fn num_cores(snap: &Snapshot) -> usize {
    snap.cpus
        .iter()
        .filter(|c| !c.is_aggregate())
        .count()
        .max(1)
}

fn cols_for_width(inner_width_px: usize) -> usize {
    let usable = inner_width_px.saturating_sub(2);
    let cols = usable / MIN_CELL_WIDTH;
    cols.clamp(1, MAX_COLS)
}

fn draw_top(f: &mut Frame, area: Rect, app: &App) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("System")
        .title_bottom(Line::from("crew-watch").right_aligned());
    let lines = match app.snapshot() {
        Some(snap) => build_top_lines(snap, app.prev.as_ref(), area.width as usize),
        None => vec![Line::from("collecting /proc ...")],
    };
    let p = Paragraph::new(lines).block(block);
    f.render_widget(p, area);
}

fn build_top_lines(curr: &Snapshot, prev: Option<&Snapshot>, width: usize) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = Vec::new();

    // Per-core usage grid.
    let cores: Vec<&CpuLine> = curr.cpus.iter().filter(|c| !c.is_aggregate()).collect();
    let pcts = core_pcts(curr, prev);
    if !cores.is_empty() {
        let n = cores.len();
        let cols = cols_for_width(width);
        let cell_w = (width.saturating_sub(2)) / cols;
        let bar_w = cell_w.saturating_sub(9).max(4);
        let rows = n.div_ceil(cols);
        for r in 0..rows {
            let mut spans: Vec<Span<'static>> = Vec::new();
            for c in 0..cols {
                let idx = c * rows + r;
                if idx < n {
                    let corenum = idx + 1;
                    let pct = pcts.get(idx).copied().unwrap_or(0.0);
                    let cell = format_cell(corenum, pct, bar_w, cell_w);
                    spans.push(Span::styled(cell, Style::default().fg(pct_color(pct))));
                } else {
                    spans.push(Span::raw(" ".repeat(cell_w)));
                }
            }
            lines.push(Line::from(spans));
        }
    }

    // Memory + swap.
    let mem = &curr.mem;
    let mem_used = mem.mem_total_kib.saturating_sub(mem.mem_avail_kib);
    let mem_pct = ratio(mem_used, mem.mem_total_kib);
    let swap_used = mem.swap_total_kib.saturating_sub(mem.swap_free_kib);
    let swap_pct = ratio(swap_used, mem.swap_total_kib);
    let mem_label = format!(
        "{} / {}",
        format_kib(mem_used),
        format_kib(mem.mem_total_kib)
    );
    let swap_label = format!(
        "{} / {}",
        format_kib(swap_used),
        format_kib(mem.swap_total_kib)
    );
    lines.push(Line::from(vec![
        Span::raw("Mem "),
        Span::styled(
            format!("{} ", make_bar(mem_pct, MEM_BAR_WIDTH)),
            Style::default().fg(pct_color(mem_pct)),
        ),
        Span::styled(
            format!("{:>5.0}% ", mem_pct),
            Style::default().fg(pct_color(mem_pct)),
        ),
        Span::raw(mem_label),
        Span::raw("   Swp "),
        Span::styled(
            format!("{} ", make_bar(swap_pct, MEM_BAR_WIDTH)),
            Style::default().fg(pct_color(swap_pct)),
        ),
        Span::styled(
            format!("{:>5.0}% ", swap_pct),
            Style::default().fg(pct_color(swap_pct)),
        ),
        Span::raw(swap_label),
    ]));

    // Tasks / load / uptime.
    let up_secs = curr.uptime.secs.max(0.0) as u64;
    lines.push(Line::from(format!(
        "Tasks: {} total, {} running    Load avg: {:.2} {:.2} {:.2}    Uptime: {}",
        curr.load.total,
        curr.load.running,
        curr.load.one,
        curr.load.five,
        curr.load.fifteen,
        format_uptime(up_secs)
    )));

    lines
}

/// Per-core busy percentages (0..=100), matched core-by-core against the
/// previous snapshot. Cores without a previous sample read 0%.
fn core_pcts(curr: &Snapshot, prev: Option<&Snapshot>) -> Vec<f64> {
    let cores: Vec<&CpuLine> = curr.cpus.iter().filter(|c| !c.is_aggregate()).collect();
    let prev_map: std::collections::HashMap<&str, &CpuLine> = prev
        .map(|p| {
            p.cpus
                .iter()
                .filter(|c| !c.is_aggregate())
                .map(|c| (c.name.as_str(), c))
                .collect()
        })
        .unwrap_or_default();
    cores
        .iter()
        .map(|c| {
            let Some(p) = prev_map.get(c.name.as_str()) else {
                return 0.0;
            };
            let total_d = c.total().saturating_sub(p.total());
            if total_d == 0 {
                return 0.0;
            }
            let idle_d = c.idle().saturating_sub(p.idle());
            let busy_d = total_d.saturating_sub(idle_d);
            (busy_d as f64 / total_d as f64) * 100.0
        })
        .collect()
}

fn format_cell(corenum: usize, pct: f64, bar_w: usize, cell_w: usize) -> String {
    let mut s = format!("{:>2} {:>3.0}% {}", corenum, pct, make_bar(pct, bar_w));
    if s.chars().count() < cell_w {
        let pad = cell_w - s.chars().count();
        s.push_str(&" ".repeat(pad));
    } else if s.chars().count() > cell_w {
        s = s.chars().take(cell_w).collect();
    }
    s
}

fn ratio(used: u64, total: u64) -> f64 {
    if total == 0 {
        0.0
    } else {
        (used as f64 / total as f64) * 100.0
    }
}

fn pct_color(pct: f64) -> Color {
    if pct >= 90.0 {
        Color::Red
    } else if pct >= 60.0 {
        Color::Yellow
    } else if pct >= 30.0 {
        Color::Green
    } else {
        Color::Cyan
    }
}

fn draw_agents(f: &mut Frame, area: Rect, app: &App) {
    let block = Block::default().borders(Borders::ALL).title(format!(
        "Agents ({} sessions) [sorted by CPU% desc]",
        app.sessions.len()
    ));

    if app.sessions.is_empty() {
        let p = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(
                "  No agent runtimes detected.",
                Style::default().fg(Color::DarkGray),
            )),
            Line::from(Span::styled(
                "  crew-watch scans /proc for: claude, opencode, codex, grok, kimi, muse, pi.",
                Style::default().fg(Color::DarkGray),
            )),
        ])
        .block(block);
        f.render_widget(p, area);
        return;
    }

    // The widths the fixed columns actually get at this terminal width: the
    // nominal ones when they fit, a proportional shrink when they do not.
    // They serve as both the table constraints and every numeric cell's
    // fitting budget, so ratatui never has to shrink a column itself and the
    // right-aligned cells are never truncated from the left.
    let cols = compressed_col_widths(area.width);
    let (state_w, pid_w, elapsed_w, cpu_w, mem_w) = (
        cols[0] as usize,
        cols[3] as usize,
        cols[4] as usize,
        cols[5] as usize,
        cols[6] as usize,
    );
    let task_w = task_width(area.width, &cols);

    let header = Row::new(vec![
        Cell::from(fit_header("S", state_w)),
        Cell::from("RUNTIME"),
        Cell::from("MODEL"),
        right_cell(fit_header("PID", pid_w)),
        right_cell(fit_header("ELAPSED", elapsed_w)),
        right_cell(fit_header("CPU%", cpu_w)),
        right_cell(fit_header("MEM", mem_w)),
        Cell::from("TASK"),
    ])
    .style(Style::default().add_modifier(Modifier::BOLD));

    let rows = app.sessions.iter().map(|s| {
        Row::new(vec![
            Cell::from(fit_state(s.activity, state_w)),
            Cell::from(s.kind.display.to_string()).style(Style::default().fg(kind_color(s.kind))),
            Cell::from(if s.model.is_empty() {
                "-".to_string()
            } else {
                s.model.clone()
            }),
            right_cell(fit_pid(s.pid, pid_w)),
            right_cell(fit_elapsed(s.elapsed_secs, elapsed_w)),
            right_cell(fit_cpu(s.cpu_percent, cpu_w))
                .style(Style::default().fg(pct_color(s.cpu_percent))),
            right_cell(fit_mem(s.rss_kib, mem_w)),
            Cell::from(fit_task_line(s.task_project.as_deref(), &s.task, task_w)),
        ])
    });

    let mut constraints: Vec<Constraint> = cols.iter().map(|w| Constraint::Length(*w)).collect();
    constraints.push(Constraint::Min(1));
    let table = Table::new(rows, constraints)
        .column_spacing(AGENT_COL_SPACING)
        .header(header)
        .block(block);
    f.render_widget(table, area);
}

fn kind_color(kind: &AgentKind) -> Color {
    match kind.id {
        "claude" => Color::Magenta,
        "opencode" => Color::Cyan,
        "codex" => Color::Blue,
        "grok" => Color::LightGreen,
        "kimi" => Color::LightBlue,
        "muse" => Color::LightYellow,
        "pi" => Color::LightRed,
        _ => Color::Green,
    }
}

fn draw_help(f: &mut Frame, area: Rect, app: &App) {
    let interval = app.interval.as_secs_f64();
    let agent_ids: Vec<&str> = AGENT_KINDS.iter().map(|k| k.id).collect();
    // A transient notice (e.g. config save failed) takes over the help line
    // until the next keypress clears it; otherwise show the normal bindings,
    // with `p providers` present only when the quota row is enabled.
    if let Some(notice) = &app.notice {
        let line = Line::from(Span::styled(
            format!(" {notice}"),
            Style::default().fg(Color::Yellow),
        ));
        f.render_widget(Paragraph::new(line), area);
        return;
    }
    let providers_binding = if app.quota_enabled {
        "  |  p providers"
    } else {
        ""
    };
    let line = Line::from(format!(
        " q/Esc/Ctrl-C quit  |  a about{providers_binding}  |  refresh {:.1}s  |  detecting: {}",
        interval,
        agent_ids.join(", "),
    ));
    f.render_widget(Paragraph::new(line), area);
}

// ---------------------------------------------------------------------------
// Quota row
// ---------------------------------------------------------------------------

fn draw_quota(f: &mut Frame, area: Rect, app: &App) {
    if area.height == 0 {
        return;
    }
    let now = current_epoch_secs();
    let row_age = app.quota_fetch_age();
    let age_suffix = row_age.map(|d| format!(" ({} old)", format_age_compact(d.as_secs())));

    // Collect the providers to display, in display order, then build the whole
    // block through `build_quota_rows` so live rows share aligned columns.
    let mut providers: Vec<&ProviderQuota> = Vec::new();
    let mut have_report = true;
    match app.effective_selection() {
        QuotaSelection::Auto => {
            if let Some(r) = &app.quota.report {
                for p in r.providers.iter().filter(|p| has_usage_windows(p)) {
                    providers.push(p);
                }
            }
        }
        QuotaSelection::Explicit(ids) => {
            if !ids.is_empty() {
                match &app.quota.report {
                    Some(r) => {
                        for p in r.providers.iter().filter(|p| ids.contains(&p.id)) {
                            providers.push(p);
                        }
                    }
                    None => have_report = false,
                }
            }
        }
    }

    let mut lines: Vec<Line<'static>> = Vec::new();

    // D9: explicit selection with no report ⇒ one dim failure line (no rows).
    if !have_report {
        let err = app.quota.last_error.as_deref().unwrap_or("unavailable");
        lines.push(Line::from(Span::styled(
            format!(" quota: unavailable ({err})"),
            Style::default().fg(Color::DarkGray),
        )));
    } else {
        let block = build_quota_rows(&providers, now, area.width as usize);
        for (p, segs) in providers.iter().zip(block.iter()) {
            let dim = row_age.is_some() || p.stale;
            let live = has_usage_windows(p);
            let spans: Vec<Span<'static>> = segs
                .iter()
                .enumerate()
                .map(|(i, seg)| {
                    if dim || !live {
                        Span::styled(seg.text.clone(), Style::default().fg(Color::DarkGray))
                    } else if i == 0 {
                        Span::styled(seg.text.clone(), Style::default().fg(runtime_color(&p.id)))
                    } else if let Some(pct) = seg.pct {
                        Span::styled(seg.text.clone(), Style::default().fg(pct_color(pct)))
                    } else {
                        Span::raw(seg.text.clone())
                    }
                })
                .collect();
            let mut line = Line::from(spans);
            if p.stale {
                line.spans
                    .push(Span::styled(" stale", Style::default().fg(Color::DarkGray)));
            }
            lines.push(line);
        }
    }

    // Whole-row fetch staleness: append the age suffix to the first line.
    if let Some(suffix) = &age_suffix {
        if let Some(line) = lines.first_mut() {
            line.spans.push(Span::styled(
                suffix.clone(),
                Style::default().fg(Color::DarkGray),
            ));
        }
    }

    if !lines.is_empty() {
        f.render_widget(Paragraph::new(lines), area);
    }
}

/// Color for a provider/runtime id, reusing the agents-table palette. Unknown
/// ids default to `Color::White` so a future provider (e.g. z.ai) is visible.
fn runtime_color(id: &str) -> Color {
    match id {
        "claude" => Color::Magenta,
        "opencode" => Color::Cyan,
        "codex" => Color::Blue,
        "grok" => Color::LightGreen,
        "kimi" => Color::LightBlue,
        "muse" => Color::LightYellow,
        "pi" => Color::LightRed,
        _ => Color::White,
    }
}

// ---------------------------------------------------------------------------
// Quota provider-selection dialog overlay
// ---------------------------------------------------------------------------

/// Centered rect for the dialog: width `min(50, area.width-4)`, height
/// `items+4` (border + header gap + footer + items). Returns `None` when there
/// is no room.
fn centered_dialog(area: Rect, item_count: usize) -> Option<Rect> {
    let h = (item_count as u16 + 4).min(area.height);
    let w = (50u16).min(area.width.saturating_sub(4));
    if h == 0 || w == 0 {
        return None;
    }
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    Some(Rect::new(x, y, w, h))
}

fn draw_dialog(f: &mut Frame, area: Rect, app: &App) {
    let dialog = app.dialog.as_ref().expect("dialog present");
    // Clear the background under the overlay so the agents table doesn't show
    // through.
    f.render_widget(Clear, area);
    let block = Block::default()
        .borders(Borders::ALL)
        .title("Quota providers");

    let mut lines: Vec<Line<'static>> = Vec::new();
    for (i, item) in dialog.items.iter().enumerate() {
        let mark = if item.selected { "[x]" } else { "[ ]" };
        let cursor = if i == dialog.cursor { "▶" } else { " " };
        let checkbox = format!(" {cursor}{mark} {:<10} {}", item.id, item.note);
        let style = if i == dialog.cursor {
            Style::default().add_modifier(Modifier::REVERSED)
        } else if !item.reported {
            Style::default().fg(Color::DarkGray)
        } else {
            Style::default()
        };
        lines.push(Line::from(Span::styled(checkbox, style)));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        " space toggle · enter save · esc cancel",
        Style::default().fg(Color::DarkGray),
    )));
    f.render_widget(Paragraph::new(lines).block(block), area);
}

// ---------------------------------------------------------------------------
// About overlay
// ---------------------------------------------------------------------------

/// The about overlay: the app's identity (name+version, description,
/// repository link, MIT notice) in a centered panel. Content and geometry
/// come from [`crate::about`]; this is just the ratatui mapping, in the same
/// shape as the quota dialog (clear underlay, bordered block, dim footer).
fn draw_about(f: &mut Frame, area: Rect, body: &[String]) {
    // Clear the background so the UI underneath doesn't show through.
    f.render_widget(Clear, area);
    let block = Block::default()
        .borders(Borders::ALL)
        .title("About crew-watch");

    let mut lines: Vec<Line<'static>> = body
        .iter()
        .enumerate()
        .map(|(i, l)| {
            // First body line is the name+version heading.
            if i == 0 {
                Line::from(Span::styled(
                    l.clone(),
                    Style::default().add_modifier(Modifier::BOLD),
                ))
            } else {
                Line::from(l.clone())
            }
        })
        .collect();
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        " a/q/Esc close",
        Style::default().fg(Color::DarkGray),
    )));
    f.render_widget(Paragraph::new(lines).block(block), area);
}