agent-top 0.15.1

htop for local coding agents: processes, subagents, MCP servers, tokens and cost in one terminal view.
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
//! UI state: selection, sort, toggles and short histories for sparklines.

use agent_top_core::{Agent, AgentState, Snapshot};
use ratatui::crossterm::event::KeyCode;
use std::collections::VecDeque;
use std::time::{Duration, Instant};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
    State,
    Name,
    Tokens,
    Cost,
    Cpu,
    Mem,
    Age,
}

impl SortKey {
    pub fn label(self) -> &'static str {
        match self {
            SortKey::State => "state",
            SortKey::Name => "name",
            SortKey::Tokens => "tokens",
            SortKey::Cost => "cost",
            SortKey::Cpu => "cpu",
            SortKey::Mem => "mem",
            SortKey::Age => "age",
        }
    }
    fn next(self) -> SortKey {
        match self {
            SortKey::State => SortKey::Name,
            SortKey::Name => SortKey::Tokens,
            SortKey::Tokens => SortKey::Cost,
            SortKey::Cost => SortKey::Cpu,
            SortKey::Cpu => SortKey::Mem,
            SortKey::Mem => SortKey::Age,
            SortKey::Age => SortKey::State,
        }
    }
}

/// Which panel the right half of the detail pane shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetailView {
    /// The live process tree, plus orphaned MCP servers.
    Tree,
    /// A waterfall of the agent's recent tool calls.
    Trace,
}

impl DetailView {
    pub fn label(self) -> &'static str {
        match self {
            DetailView::Tree => "tree",
            DetailView::Trace => "trace",
        }
    }

    fn next(self) -> DetailView {
        match self {
            DetailView::Tree => DetailView::Trace,
            DetailView::Trace => DetailView::Tree,
        }
    }
}

const HISTORY: usize = 120;

/// Output tokens per second are measured over this window rather than per
/// tick. A harness reports usage once per assistant message, so tick-to-tick
/// deltas are zeros with spikes between them; ten seconds smooths a turn into
/// a rate and still drops back to zero soon after the agents go quiet.
const RATE_WINDOW: Duration = Duration::from_secs(10);
/// Burn rate is smoothed over a longer window than the token rate, because
/// cost arrives in per-turn lumps that a short window would make jump around.
const BURN_WINDOW: Duration = Duration::from_secs(60);

/// Which full-screen popup, if any, is over the table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Overlay {
    None,
    Help,
    /// Tool calls ranked by how much time they took.
    SlowTools,
    /// Tool calls ranked by how often they failed.
    FailedTools,
    /// What looks like a bad deal right now, and what to do about it.
    Advice,
    /// A newer agent-top is available: upgrade now, or not now.
    Update,
}

pub struct App {
    pub snapshot: Snapshot,
    pub rows: Vec<Agent>,
    pub selected_id: Option<String>,
    pub selected: usize,
    pub sort: SortKey,
    pub sort_desc: bool,
    pub show_detail: bool,
    pub detail: DetailView,
    pub overlay: Overlay,
    pub show_stopped: bool,
    pub paused: bool,
    pub cpu_history: Vec<u64>,
    /// Output tokens per second across every agent, one entry per tick.
    pub output_rate: Vec<u64>,
    pub cost_history: Vec<u64>,
    /// (when, output tokens across every agent) for the last `RATE_WINDOW`.
    rate_samples: VecDeque<(Instant, u64)>,
    /// (when, cumulative cost in micro-dollars) for the last `BURN_WINDOW`.
    cost_samples: VecDeque<(Instant, u64)>,
    /// Current spend velocity across every agent, US dollars per hour.
    pub burn_per_hour: f64,
    /// The latest published version when it is newer than this build, filled by
    /// the update check; `None` otherwise. The footer reads it each frame.
    pub update: std::sync::Arc<std::sync::Mutex<Option<String>>>,
    /// The version the user has already said "not now" to, from the cache.
    pub update_dismissed: Option<String>,
    /// The upgrade question is asked at most once per run.
    update_prompted: bool,
    /// Which installer would run an upgrade; the popup shows its command.
    pub installer: crate::update::Installer,
    /// Set when the user pressed `u` in the update popup: the main loop
    /// leaves the TUI and runs the upgrade.
    pub upgrade_requested: Option<String>,
}

impl App {
    pub fn new(snapshot: Snapshot) -> Self {
        let mut app = App {
            snapshot,
            rows: Vec::new(),
            selected_id: None,
            selected: 0,
            sort: SortKey::State,
            sort_desc: false,
            show_detail: true,
            detail: DetailView::Tree,
            overlay: Overlay::None,
            show_stopped: true,
            paused: false,
            cpu_history: Vec::new(),
            output_rate: Vec::new(),
            cost_history: Vec::new(),
            rate_samples: VecDeque::new(),
            cost_samples: VecDeque::new(),
            burn_per_hour: 0.0,
            update: std::sync::Arc::new(std::sync::Mutex::new(None)),
            update_dismissed: None,
            update_prompted: false,
            installer: crate::update::Installer::Unknown,
            upgrade_requested: None,
        };
        app.rebuild_rows();
        app
    }

    /// The newer version the update check knows of, if any.
    pub fn latest(&self) -> Option<String> {
        self.update.lock().ok().and_then(|g| g.clone())
    }

    /// Open the update question once a newer version is known, unless the
    /// user already declined that version or another popup is open. Called
    /// after the check starts and on every tick, since the answer can arrive
    /// from the network a moment after start.
    pub fn maybe_prompt_update(&mut self) {
        if self.update_prompted || self.overlay != Overlay::None {
            return;
        }
        let Some(latest) = self.latest() else { return };
        if self.update_dismissed.as_deref() == Some(latest.as_str()) {
            return;
        }
        self.update_prompted = true;
        self.overlay = Overlay::Update;
    }

    /// Close whatever popup is open. Closing the update question counts as
    /// "not now": that version is not asked about again.
    pub fn close_overlay(&mut self) {
        if self.overlay == Overlay::Update
            && let Some(latest) = self.latest()
        {
            self.update_dismissed = Some(latest.clone());
            crate::update::dismiss(&latest);
        }
        self.overlay = Overlay::None;
    }

    pub fn update(&mut self, snapshot: Snapshot) {
        self.update_at(snapshot, Instant::now());
    }

    /// `update` with the clock injected, so the rate can be tested.
    pub fn update_at(&mut self, snapshot: Snapshot, now: Instant) {
        push(&mut self.cpu_history, snapshot.host.cpu_percent.round() as u64);
        // Output only: cache reads and prompt tokens are the context being
        // re-sent, not work being produced, and they dwarf the output by a
        // hundred to one on a long session.
        let output: u64 = snapshot.agents.iter().map(|a| a.usage.output).sum();
        self.rate_samples.push_back((now, output));
        // Keep the newest sample that is at least a window old as the anchor,
        // so the rate always spans a full window once there is that much
        // history.
        while self.rate_samples.len() > 2 && self.rate_samples[1].0 + RATE_WINDOW <= now {
            self.rate_samples.pop_front();
        }
        push(&mut self.output_rate, output_per_second(&self.rate_samples));
        push(&mut self.cost_history, (snapshot.totals.cost_usd * 100.0) as u64);
        // Spend velocity: the cost added over the burn window, projected to an
        // hour. Cost only climbs, so an idle machine reads zero.
        let cost_micros = (snapshot.totals.cost_usd * 1_000_000.0) as u64;
        self.cost_samples.push_back((now, cost_micros));
        while self.cost_samples.len() > 2 && self.cost_samples[1].0 + BURN_WINDOW <= now {
            self.cost_samples.pop_front();
        }
        self.burn_per_hour = burn_per_hour(&self.cost_samples);
        self.snapshot = snapshot;
        self.rebuild_rows();
        self.maybe_prompt_update();
    }

    pub fn rebuild_rows(&mut self) {
        let mut rows: Vec<Agent> =
            self.snapshot.agents.iter().filter(|a| self.show_stopped || a.state != AgentState::Stopped).cloned().collect();
        let key = self.sort;
        rows.sort_by(|a, b| {
            let ord = match key {
                SortKey::State => a.state.cmp(&b.state).then_with(|| b.usage.total().cmp(&a.usage.total())),
                SortKey::Name => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
                SortKey::Tokens => b.usage.total().cmp(&a.usage.total()),
                SortKey::Cost => b.cost_usd.partial_cmp(&a.cost_usd).unwrap_or(std::cmp::Ordering::Equal),
                SortKey::Cpu => b.cpu_percent.partial_cmp(&a.cpu_percent).unwrap_or(std::cmp::Ordering::Equal),
                SortKey::Mem => b.rss_bytes.cmp(&a.rss_bytes),
                SortKey::Age => b.age_secs.cmp(&a.age_secs),
            };
            if self.sort_desc { ord.reverse() } else { ord }
        });
        self.rows = rows;
        // Keep the cursor on the same agent across refreshes.
        if let Some(id) = &self.selected_id
            && let Some(i) = self.rows.iter().position(|a| &a.id == id)
        {
            self.selected = i;
        }
        if self.rows.is_empty() {
            self.selected = 0;
        } else if self.selected >= self.rows.len() {
            self.selected = self.rows.len() - 1;
        }
        self.selected_id = self.rows.get(self.selected).map(|a| a.id.clone());
    }

    pub fn selected_agent(&self) -> Option<&Agent> {
        self.rows.get(self.selected)
    }

    fn select(&mut self, i: usize) {
        if self.rows.is_empty() {
            return;
        }
        self.selected = i.min(self.rows.len() - 1);
        self.selected_id = Some(self.rows[self.selected].id.clone());
    }

    pub fn on_key(&mut self, code: KeyCode) {
        // The update question takes `u` and `n` for itself while it is open.
        if self.overlay == Overlay::Update {
            match code {
                KeyCode::Char('u') | KeyCode::Char('y') | KeyCode::Enter => {
                    if self.installer.steps().is_some() {
                        self.upgrade_requested = self.latest();
                    }
                    return;
                }
                KeyCode::Char('n') | KeyCode::Esc => {
                    self.close_overlay();
                    return;
                }
                _ => {}
            }
        }
        match code {
            KeyCode::Char('j') | KeyCode::Down => self.select(self.selected + 1),
            KeyCode::Char('k') | KeyCode::Up => self.select(self.selected.saturating_sub(1)),
            KeyCode::Char('g') | KeyCode::Home => self.select(0),
            KeyCode::Char('G') | KeyCode::End => self.select(usize::MAX),
            KeyCode::PageDown => self.select(self.selected + 10),
            KeyCode::PageUp => self.select(self.selected.saturating_sub(10)),
            KeyCode::Char('s') => {
                self.sort = self.sort.next();
                self.rebuild_rows();
            }
            KeyCode::Char('r') => {
                self.sort_desc = !self.sort_desc;
                self.rebuild_rows();
            }
            KeyCode::Char('t') | KeyCode::Enter => self.show_detail = !self.show_detail,
            // Cycling the view opens the pane rather than switching a panel
            // nobody can see.
            KeyCode::Tab | KeyCode::Char('v') => {
                if self.show_detail {
                    self.detail = self.detail.next();
                } else {
                    self.show_detail = true;
                }
            }
            KeyCode::Char('x') => {
                self.show_stopped = !self.show_stopped;
                self.rebuild_rows();
            }
            KeyCode::Char('p') | KeyCode::Char(' ') => self.paused = !self.paused,
            KeyCode::Char('h') | KeyCode::Char('?') | KeyCode::F(1) => self.toggle(Overlay::Help),
            KeyCode::Char('l') => self.toggle(Overlay::SlowTools),
            KeyCode::Char('f') => self.toggle(Overlay::FailedTools),
            KeyCode::Char('a') => self.toggle(Overlay::Advice),
            KeyCode::Esc => self.close_overlay(),
            _ => {}
        }
    }

    /// Open the given overlay, or close it if it is already the one showing.
    fn toggle(&mut self, o: Overlay) {
        self.overlay = if self.overlay == o { Overlay::None } else { o };
    }
}

/// Output tokens per second between the oldest and newest sample. An agent
/// leaving the snapshot can make the total fall; that reads as zero, not as
/// a negative rate.
fn output_per_second(samples: &VecDeque<(Instant, u64)>) -> u64 {
    let (Some((t0, n0)), Some((t1, n1))) = (samples.front(), samples.back()) else { return 0 };
    let secs = t1.duration_since(*t0).as_secs_f64();
    if secs <= 0.0 {
        return 0;
    }
    (n1.saturating_sub(*n0) as f64 / secs).round() as u64
}

/// US dollars per hour from cumulative-cost samples: the cost added across the
/// window, scaled to an hour. Needs a few seconds of history so a cold start
/// does not read a wild rate off a one-second window.
fn burn_per_hour(samples: &VecDeque<(Instant, u64)>) -> f64 {
    let (Some((t0, c0)), Some((t1, c1))) = (samples.front(), samples.back()) else { return 0.0 };
    let secs = t1.duration_since(*t0).as_secs_f64();
    if secs < 3.0 {
        return 0.0;
    }
    let micros = c1.saturating_sub(*c0) as f64;
    micros / 1_000_000.0 / secs * 3600.0
}

fn push(v: &mut Vec<u64>, x: u64) {
    v.push(x);
    if v.len() > HISTORY {
        let drop = v.len() - HISTORY;
        v.drain(..drop);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use agent_top_core::{Activity, Attribution, Harness, HostStats, TokenUsage, Totals};
    use std::time::SystemTime;

    fn snapshot(output: u64) -> Snapshot {
        let agent = Agent {
            id: "pid:1".into(),
            name: "claude".into(),
            harness: Harness::Claude,
            state: AgentState::Running,
            activity: Activity::Working,
            pid: Some(1),
            session_id: None,
            session_path: None,
            cwd: None,
            model: None,
            harness_version: None,
            usage: TokenUsage { input: 10, cache_write_5m: 0, cache_write_1h: 0, cache_read: 500_000, output },
            cost_usd: 0.0,
            cost_breakdown: Default::default(),
            price_source: None,
            unpriced_tokens: 0,
            turns: 1,
            subagent_turns: 0,
            tool_calls: 0,
            web_searches: 0,
            spans: Vec::new(),
            age_secs: 0,
            idle_secs: None,
            cpu_percent: 0.0,
            rss_bytes: 0,
            process_count: 1,
            mcp_count: 0,
            mcp_servers: Vec::new(),
            context: Vec::new(),
            tree: None,
            attribution: Attribution::HarnessRegistry,
            shares_process: false,
            parse_warning: None,
            rate_limit: None,
        };
        let mut s = Snapshot {
            schema_version: agent_top_core::SNAPSHOT_SCHEMA_VERSION,
            taken_at: SystemTime::UNIX_EPOCH,
            host: HostStats::default(),
            agents: vec![agent],
            orphans: Vec::new(),
            orphan_origins: Vec::new(),
            advice: Vec::new(),
            totals: Totals::default(),
        };
        s.compute_totals();
        s
    }

    /// The question opens once when a newer version is known, not when that
    /// version was already declined, and not over another popup; `n` declines
    /// and `u` asks the main loop to upgrade.
    #[test]
    fn the_upgrade_question_is_asked_once_and_remembers_no() {
        let mut app = App::new(snapshot(0));
        app.maybe_prompt_update();
        assert_eq!(app.overlay, Overlay::None, "nothing known yet");
        *app.update.lock().unwrap() = Some("9.9.9".into());
        app.overlay = Overlay::Help;
        app.maybe_prompt_update();
        assert_eq!(app.overlay, Overlay::Help, "never over another popup");
        app.overlay = Overlay::None;
        app.update_at(snapshot(0), Instant::now());
        assert_eq!(app.overlay, Overlay::Update, "a tick asks");
        // `u` with an unknown installer does nothing: there is no command to run.
        app.on_key(KeyCode::Char('u'));
        assert_eq!(app.upgrade_requested, None);
        app.installer = crate::update::Installer::CargoInstall;
        app.on_key(KeyCode::Char('u'));
        assert_eq!(app.upgrade_requested.as_deref(), Some("9.9.9"));

        // Declining closes it and is remembered in memory for this version.
        let mut app = App::new(snapshot(0));
        *app.update.lock().unwrap() = Some("9.9.9".into());
        app.maybe_prompt_update();
        assert_eq!(app.overlay, Overlay::Update);
        app.update_dismissed = None;
        app.overlay = Overlay::Update;
        // Simulate the decline without touching the real cache file.
        app.update_dismissed = Some("9.9.9".into());
        app.overlay = Overlay::None;
        app.update_prompted = false;
        app.maybe_prompt_update();
        assert_eq!(app.overlay, Overlay::None, "a declined version is not asked again");
        // A newer release than the declined one is asked about.
        *app.update.lock().unwrap() = Some("10.0.0".into());
        app.maybe_prompt_update();
        assert_eq!(app.overlay, Overlay::Update);
    }

    #[test]
    fn burn_rate_is_dollars_per_hour_over_the_window() {
        use std::collections::VecDeque;
        let t0 = Instant::now();
        // $0.60 spent over 60 seconds → $36/hour.
        let mut s: VecDeque<(Instant, u64)> = VecDeque::new();
        s.push_back((t0, 1_000_000)); // $1.00
        s.push_back((t0 + Duration::from_secs(60), 1_600_000)); // $1.60
        assert!((burn_per_hour(&s) - 36.0).abs() < 1e-6, "{}", burn_per_hour(&s));
        // Too little history reads zero rather than a wild number.
        let mut s: VecDeque<(Instant, u64)> = VecDeque::new();
        s.push_back((t0, 1_000_000));
        s.push_back((t0 + Duration::from_secs(1), 2_000_000));
        assert_eq!(burn_per_hour(&s), 0.0);
    }

    #[test]
    fn output_rate_is_per_second_over_the_window_not_per_tick() {
        let t0 = Instant::now();
        let mut app = App::new(snapshot(0));
        // 1000 output tokens landing in one tick, at a one second interval.
        app.update_at(snapshot(0), t0);
        app.update_at(snapshot(1000), t0 + Duration::from_secs(1));
        assert_eq!(app.output_rate.last(), Some(&1000), "one second, one thousand tokens");
        // Nine quiet ticks: the burst is spread over the window, not forgotten.
        for i in 2..=10 {
            app.update_at(snapshot(1000), t0 + Duration::from_secs(i));
        }
        assert_eq!(app.output_rate.last(), Some(&100), "1000 tokens over the 10 s window");
        // Past the window the burst has aged out and the rate is zero again.
        for i in 11..=21 {
            app.update_at(snapshot(1000), t0 + Duration::from_secs(i));
        }
        assert_eq!(app.output_rate.last(), Some(&0));
        assert!(app.rate_samples.len() <= 12, "samples outside the window are dropped");
    }

    #[test]
    fn a_falling_total_reads_as_zero_and_a_half_second_tick_is_scaled() {
        let t0 = Instant::now();
        let mut app = App::new(snapshot(0));
        app.update_at(snapshot(500), t0);
        app.update_at(snapshot(0), t0 + Duration::from_secs(1));
        assert_eq!(app.output_rate.last(), Some(&0));
        let mut app = App::new(snapshot(0));
        app.update_at(snapshot(0), t0);
        app.update_at(snapshot(50), t0 + Duration::from_millis(500));
        assert_eq!(app.output_rate.last(), Some(&100), "50 tokens in half a second");
    }
}