agentop 0.7.1

A TUI process inspector for Claude Code and OpenAI Codex CLI — like top for AI coding agents
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashMap, HashSet, VecDeque};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::widgets::TableState;

use crate::action::Action;
use crate::config::Config;
use crate::process::{
    build_forest, collect_expansion, flatten_visible, preserve_expansion, process_kind,
    toggle_expand, ActivityState, FlatEntry, ProcessInfo, ProcessKind, ProcessNode, SubtreeStats,
    SystemStats,
};
use crate::ui::styles::{GraphStyle, Palette, Theme};

/// Maximum number of historical CPU/memory samples retained per process.
///
/// At the default 2-second tick rate this is ~10 minutes of history,
/// enough to fill the sparkline chart on any realistic terminal width.
const HISTORY_LEN: usize = 300;

/// CPU usage percentage below which a root process is considered idle.
pub const IDLE_CPU_THRESHOLD: f32 = 0.5;

/// Minimum number of CPU samples required before classifying a process
/// as idle or active. Fewer samples yield [`ActivityState::Unknown`].
pub const IDLE_SAMPLE_WINDOW: usize = 5;

/// Columns that support sorting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortColumn {
    #[default]
    Pid,
    Name,
    Cpu,
    Memory,
    Status,
    Uptime,
}

impl SortColumn {
    const ALL: [SortColumn; 6] = [
        Self::Pid,
        Self::Name,
        Self::Cpu,
        Self::Memory,
        Self::Status,
        Self::Uptime,
    ];

    pub fn next(self) -> Self {
        let idx = Self::ALL
            .iter()
            .position(|&c| c == self)
            .expect("SortColumn variant missing from ALL array");
        Self::ALL[(idx + 1) % Self::ALL.len()]
    }

    pub fn prev(self) -> Self {
        let idx = Self::ALL
            .iter()
            .position(|&c| c == self)
            .expect("SortColumn variant missing from ALL array");
        Self::ALL[(idx + Self::ALL.len() - 1) % Self::ALL.len()]
    }
}

/// Sort direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortDirection {
    Ascending,
    #[default]
    Descending,
}

impl SortDirection {
    pub fn toggle(self) -> Self {
        match self {
            Self::Ascending => Self::Descending,
            Self::Descending => Self::Ascending,
        }
    }
}

/// Aggregated counts and resource usage across all detected agent processes.
///
/// Computed after every process refresh via [`App::compute_agent_summary`] and
/// displayed in the status bar to give an at-a-glance overview of active agents.
#[derive(Debug, Clone, Default)]
pub struct AgentSummary {
    /// Number of Claude Code root processes currently running.
    pub claude_count: usize,
    /// Number of Codex CLI root processes currently running.
    pub codex_count: usize,
    /// Total CPU usage (%) across all agent subtrees.
    pub total_cpu: f32,
    /// Total resident memory (bytes) across all agent subtrees.
    pub total_memory: u64,
}

/// Tracks which top-level panel is currently receiving input and being rendered.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ActiveView {
    /// The scrollable process tree list.
    #[default]
    Tree,
    /// The drill-down detail panel for a single selected process.
    Detail,
}

/// Transient state for the settings popup.
///
/// The popup exposes two categories of options — `Graph Style` and `Theme` —
/// as a single flat list so Up/Down navigation is trivial. [`Self::SECTIONS`]
/// describes the list layout used by both the handler and the renderer.
#[derive(Debug, Clone, Default)]
pub struct ConfigPopupState {
    /// Currently highlighted row in the flat option list.
    pub cursor: usize,
}

impl ConfigPopupState {
    /// Ordered sections and the option count for each.
    ///
    /// `(section label, option count)`. The flat cursor index maps into this
    /// layout so row 0 is the first option of the first section.
    pub const SECTIONS: &'static [(&'static str, usize)] = &[
        ("Graph Style", GraphStyle::ALL.len()),
        ("Theme", Theme::ALL.len()),
    ];

    /// Total number of selectable rows across all sections.
    pub fn total_rows() -> usize {
        Self::SECTIONS.iter().map(|(_, n)| n).sum()
    }

    /// Move the cursor up one row, wrapping at the top.
    pub fn move_up(&mut self) {
        let total = Self::total_rows();
        self.cursor = (self.cursor + total - 1) % total;
    }

    /// Move the cursor down one row, wrapping at the bottom.
    pub fn move_down(&mut self) {
        let total = Self::total_rows();
        self.cursor = (self.cursor + 1) % total;
    }
}

/// Context passed to [`App::map_key_to_action`] describing the current UI mode.
///
/// Bundling these boolean flags into a struct avoids a long parameter list and
/// makes it straightforward to add new mode flags in the future without breaking
/// all call sites.
pub struct KeyContext<'a> {
    /// The panel that currently owns keyboard focus.
    pub active_view: &'a ActiveView,
    /// Whether a kill-confirmation popup is currently open.
    pub confirming_kill: bool,
    /// Whether the config popup is currently open.
    pub config_open: bool,
    /// Whether the search/filter bar is currently active.
    pub filter_active: bool,
}

/// Central application state. All mutations flow through [`App::handle_action`]
/// or [`App::update_processes`], keeping the state machine easy to reason about.
#[derive(Debug, Default)]
pub struct App {
    /// Set to `true` when the event loop should exit.
    pub should_quit: bool,
    /// Which panel currently owns keyboard focus.
    pub active_view: ActiveView,
    /// Live process tree, kept in sync with each refresh cycle.
    pub forest: Vec<ProcessNode>,
    /// Ordered, flattened projection of the visible forest rows.
    pub flat_list: Vec<FlatEntry>,
    /// Drives the ratatui `Table` cursor — holds the currently highlighted row index.
    pub table_state: TableState,
    /// Process snapshot shown in the detail panel; `None` until a row is selected.
    pub selected_detail: Option<ProcessInfo>,
    /// Subtree statistics for the selected process; `None` until a row is selected.
    pub selected_detail_subtree: Option<SubtreeStats>,
    /// Rolling CPU-usage history per PID (percentage, up to [`HISTORY_LEN`] samples).
    pub cpu_history: HashMap<u32, VecDeque<f32>>,
    /// Rolling resident-memory history per PID (bytes, up to [`HISTORY_LEN`] samples).
    pub mem_history: HashMap<u32, VecDeque<u64>>,
    /// Active sort column.
    pub sort_column: SortColumn,
    /// Active sort direction.
    pub sort_direction: SortDirection,
    /// PID pending kill confirmation.
    pub confirm_kill_pid: Option<u32>,
    /// Result message from the last kill attempt.
    pub kill_result: Option<String>,
    /// Latest system-wide resource snapshot.
    pub system_stats: SystemStats,
    /// Active visual theme. Changing this regenerates `palette`.
    pub theme: Theme,
    /// Cached style palette derived from `theme`, passed to every renderer.
    pub palette: Palette,
    /// Active graph style for the detail view (dots vs bars).
    pub graph_style: GraphStyle,
    /// Settings popup state; `None` when the popup is closed.
    pub config_popup: Option<ConfigPopupState>,
    /// Latest aggregated summary across all detected agent processes.
    pub agent_summary: AgentSummary,
    /// Per-root-PID activity classification (`Active` / `Idle` / `Unknown`).
    pub activity_state: HashMap<u32, ActivityState>,
    /// Per-root-PID aggregate CPU history used for idle/active classification.
    pub aggregate_cpu_history: HashMap<u32, VecDeque<f32>>,
    /// Whether the search/filter bar is currently accepting input.
    pub filter_active: bool,
    /// Current filter query text.
    pub filter_text: String,
}

impl App {
    /// Create a new [`App`] with sensible defaults and row 0 pre-selected.
    ///
    /// Persisted settings are loaded from
    /// `$XDG_CONFIG_HOME/agentop/config.toml` (or the platform equivalent)
    /// and applied to `theme` / `graph_style`. If no config file exists the
    /// defaults defined by the enum `Default` impls are used.
    pub fn new() -> Self {
        let mut table_state = TableState::default();
        // Pre-select the first row so the cursor is always visible from the start.
        table_state.select(Some(0));

        let config = Config::load();
        let palette = Palette::from_theme(config.theme);

        Self {
            table_state,
            theme: config.theme,
            graph_style: config.graph_style,
            palette,
            ..Default::default()
        }
    }

    /// Write the currently-applied settings to disk. Called whenever the
    /// user changes a setting via the config popup.
    fn persist_config(&self) {
        Config {
            theme: self.theme,
            graph_style: self.graph_style,
        }
        .save();
    }

    /// Dispatch an [`Action`] produced by the event loop, mutating state accordingly.
    pub fn handle_action(&mut self, action: Action) {
        // Clear the kill result message on any action that isn't part of the kill flow.
        if !matches!(
            action,
            Action::KillRequest | Action::ConfirmKill | Action::CancelKill
        ) {
            self.kill_result = None;
        }

        match action {
            Action::Quit => self.should_quit = true,
            Action::MoveUp => self.move_selection(-1),
            Action::MoveDown => self.move_selection(1),
            Action::ToggleExpand => {
                if let Some(idx) = self.table_state.selected() {
                    if let Some(entry) = self.flat_list.get(idx) {
                        let pid = entry.info.pid;
                        toggle_expand(&mut self.forest, pid);
                        self.rebuild_flat_list();
                    }
                }
            }
            Action::SelectProcess => {
                if let Some(idx) = self.table_state.selected() {
                    if let Some(entry) = self.flat_list.get(idx) {
                        self.selected_detail = Some(entry.info.clone());
                        self.selected_detail_subtree = Some(entry.subtree_stats);
                        self.active_view = ActiveView::Detail;
                    }
                }
            }
            Action::BackToTree => {
                self.active_view = ActiveView::Tree;
            }
            Action::SortNext => {
                self.sort_column = self.sort_column.next();
                self.rebuild_flat_list();
            }
            Action::SortPrev => {
                self.sort_column = self.sort_column.prev();
                self.rebuild_flat_list();
            }
            Action::SortToggleDirection => {
                self.sort_direction = self.sort_direction.toggle();
                self.rebuild_flat_list();
            }
            Action::KillRequest => {
                let pid = self.selected_pid();
                if pid.is_some() {
                    self.confirm_kill_pid = pid;
                    self.kill_result = None;
                }
            }
            Action::ConfirmKill => {
                if let Some(pid) = self.confirm_kill_pid.take() {
                    self.kill_result = Some(kill_process(pid));
                }
            }
            Action::CancelKill => {
                self.confirm_kill_pid = None;
            }
            Action::ToggleConfig => {
                if self.config_popup.is_some() {
                    self.config_popup = None;
                } else {
                    self.config_popup = Some(ConfigPopupState::default());
                }
            }
            Action::ConfigUp => {
                if let Some(popup) = self.config_popup.as_mut() {
                    popup.move_up();
                }
            }
            Action::ConfigDown => {
                if let Some(popup) = self.config_popup.as_mut() {
                    popup.move_down();
                }
            }
            Action::ConfigSelect => {
                if let Some(popup) = self.config_popup.as_ref() {
                    self.apply_config_selection(popup.cursor);
                }
            }
            Action::CloseConfig => {
                self.config_popup = None;
            }
            Action::EnterFilter => {
                self.filter_active = true;
            }
            Action::ClearFilter => {
                self.filter_active = false;
                self.filter_text.clear();
                self.rebuild_flat_list();
            }
            Action::FilterInput(c) => {
                self.filter_text.push(c);
                self.rebuild_flat_list();
            }
            Action::FilterBackspace => {
                self.filter_text.pop();
                if self.filter_text.is_empty() {
                    self.filter_active = false;
                }
                self.rebuild_flat_list();
            }
        }
    }

    /// Apply the option at the given flat cursor index to the live app state.
    ///
    /// The layout is driven by [`ConfigPopupState::SECTIONS`] so adding a new
    /// section or option does not require touching this function's arm order.
    ///
    /// Writes the updated settings to disk so they persist across restarts.
    fn apply_config_selection(&mut self, cursor: usize) {
        let mut offset = 0;
        // Section 0: graph style.
        let graph_count = GraphStyle::ALL.len();
        if cursor < offset + graph_count {
            self.graph_style = GraphStyle::ALL[cursor - offset];
            self.persist_config();
            return;
        }
        offset += graph_count;

        // Section 1: theme. Regenerate the palette so render functions
        // immediately pick up the new colors.
        let theme_count = Theme::ALL.len();
        if cursor < offset + theme_count {
            let theme = Theme::ALL[cursor - offset];
            self.theme = theme;
            self.palette = Palette::from_theme(theme);
            self.persist_config();
        }
    }

    /// Move the highlighted row by `delta` rows, clamping at the list boundaries.
    ///
    /// # Arguments
    ///
    /// * `delta` - Positive values move down; negative values move up.
    fn move_selection(&mut self, delta: i32) {
        let len = self.flat_list.len();
        if len == 0 {
            return;
        }
        // current defaults to 0 when nothing is selected yet.
        let current = self.table_state.selected().unwrap_or(0) as i32;
        // Clamp to [0, len - 1] to prevent out-of-bounds selection.
        let next = (current + delta).clamp(0, (len as i32) - 1) as usize;
        self.table_state.select(Some(next));
    }

    /// Ingest a fresh process snapshot, preserving expansion state and updating histories.
    ///
    /// This is the primary entry point called by the background scanner on each tick.
    ///
    /// # Arguments
    ///
    /// * `processes` - Complete flat list of process snapshots from the current refresh.
    pub fn update_processes(&mut self, processes: Vec<ProcessInfo>, stats: SystemStats) {
        self.system_stats = stats;
        // Snapshot expansion state before rebuilding so the user's open/close choices survive.
        let old_expansion = collect_expansion(&self.forest);

        self.update_history(&processes);

        // Prune history for processes that no longer exist, preventing unbounded growth.
        let live_pids: HashSet<u32> = processes.iter().map(|p| p.pid).collect();
        self.cpu_history.retain(|pid, _| live_pids.contains(pid));
        self.mem_history.retain(|pid, _| live_pids.contains(pid));

        self.forest = build_forest(&processes);
        preserve_expansion(&mut self.forest, &old_expansion);

        // Compute idle/active badges for root processes.
        self.update_activity_states();

        // Prune activity history for PIDs that have exited.
        self.aggregate_cpu_history
            .retain(|pid, _| live_pids.contains(pid));
        self.activity_state.retain(|pid, _| live_pids.contains(pid));

        // Keep the detail view in sync with live data.
        if let Some(ref mut detail) = self.selected_detail {
            if let Some(updated) = processes.iter().find(|p| p.pid == detail.pid) {
                *detail = updated.clone();
            }
        }

        self.rebuild_flat_list();

        // Refresh the subtree stats for the selected process from the newly
        // flattened list, so the detail view always shows current aggregate data.
        if let Some(ref detail) = self.selected_detail {
            let pid = detail.pid;
            self.selected_detail_subtree = self
                .flat_list
                .iter()
                .find(|e| e.info.pid == pid)
                .map(|e| e.subtree_stats);
        }

        self.agent_summary = self.compute_agent_summary();
    }

    /// Sort the forest in place, then flatten into `flat_list`.
    ///
    /// Sorting is done on the tree before flattening so sibling order at every
    /// depth level is correct and parent-child grouping is never violated.
    /// Root nodes are sorted by aggregate (subtree) stats; child nodes by self stats.
    fn sort_flat_list(&mut self) {
        sort_forest(
            &mut self.forest,
            self.sort_column,
            self.sort_direction,
            true,
        );
        self.flat_list = flatten_visible(&self.forest);
    }

    /// Compute the [`AgentSummary`] from the current forest.
    ///
    /// Iterates over root nodes only: each root's `subtree_stats` already
    /// carries the recursive aggregate, so no additional traversal is needed.
    pub fn compute_agent_summary(&self) -> AgentSummary {
        let mut summary = AgentSummary::default();
        for root in &self.forest {
            match process_kind(&root.info) {
                Some(ProcessKind::Claude) => summary.claude_count += 1,
                Some(ProcessKind::Codex) => summary.codex_count += 1,
                None => {}
            }
            summary.total_cpu += root.subtree_stats.total_cpu;
            summary.total_memory += root.subtree_stats.total_memory;
        }
        summary
    }

    /// Rebuild and sort `flat_list`, inject activity badges, apply the current
    /// filter, then clamp the selection cursor.
    ///
    /// Call this whenever the forest structure, sort parameters, or filter text changes.
    fn rebuild_flat_list(&mut self) {
        self.sort_flat_list();

        // Inject activity state into root FlatEntry values.
        for entry in &mut self.flat_list {
            if entry.is_root {
                entry.activity = self.activity_state.get(&entry.info.pid).copied();
            }
        }

        self.apply_filter();
        self.clamp_selection();
    }

    /// Update the idle/active classification for every root process in the forest.
    fn update_activity_states(&mut self) {
        for root in &self.forest {
            let pid = root.info.pid;
            let buf = self.aggregate_cpu_history.entry(pid).or_default();
            if buf.len() == HISTORY_LEN {
                buf.pop_front();
            }
            buf.push_back(root.info.cpu_usage);

            let state = if buf.len() < IDLE_SAMPLE_WINDOW {
                ActivityState::Unknown
            } else {
                let window_start = buf.len() - IDLE_SAMPLE_WINDOW;
                let all_idle = buf
                    .iter()
                    .skip(window_start)
                    .all(|&s| s < IDLE_CPU_THRESHOLD);
                if all_idle {
                    ActivityState::Idle
                } else {
                    ActivityState::Active
                }
            };
            self.activity_state.insert(pid, state);
        }
    }

    /// Filter `flat_list` in-place based on `filter_text`.
    fn apply_filter(&mut self) {
        if self.filter_text.is_empty() {
            return;
        }

        let query = self.filter_text.to_lowercase();
        let n = self.flat_list.len();

        // Pass 1: direct match flags.
        let mut keep = vec![false; n];
        for (i, entry) in self.flat_list.iter().enumerate() {
            keep[i] = entry_matches_filter(entry, &query);
        }

        // Pass 2: propagate keep upward through parent chains.
        for i in (0..n).rev() {
            if !keep[i] {
                continue;
            }
            let child_depth = self.flat_list[i].depth;
            if child_depth == 0 {
                continue;
            }
            for j in (0..i).rev() {
                if self.flat_list[j].depth == child_depth - 1 {
                    keep[j] = true;
                    break;
                }
            }
        }

        let mut idx = 0;
        self.flat_list.retain(|_| {
            let keep_entry = keep[idx];
            idx += 1;
            keep_entry
        });
    }

    /// Return the PID of the currently focused process, if any.
    fn selected_pid(&self) -> Option<u32> {
        match self.active_view {
            ActiveView::Tree => {
                let idx = self.table_state.selected()?;
                Some(self.flat_list.get(idx)?.info.pid)
            }
            ActiveView::Detail => self.selected_detail.as_ref().map(|d| d.pid),
        }
    }

    /// Clamp the selected row index to valid bounds.
    fn clamp_selection(&mut self) {
        let len = self.flat_list.len();
        if len == 0 {
            self.table_state.select(None);
            return;
        }
        let clamped = self.table_state.selected().unwrap_or(0).min(len - 1);
        self.table_state.select(Some(clamped));
    }

    /// Push the latest CPU and memory readings into the per-PID ring buffers.
    ///
    /// Called before the forest is rebuilt so it operates on the raw flat list,
    /// reaching every process regardless of tree depth.
    ///
    /// # Arguments
    ///
    /// * `processes` - The same flat snapshot slice passed to [`update_processes`].
    fn update_history(&mut self, processes: &[ProcessInfo]) {
        for proc in processes {
            // VecDeque as a fixed-size ring buffer: push to back, pop from front.
            let cpu_buf = self.cpu_history.entry(proc.pid).or_default();
            if cpu_buf.len() == HISTORY_LEN {
                cpu_buf.pop_front();
            }
            cpu_buf.push_back(proc.cpu_usage);

            let mem_buf = self.mem_history.entry(proc.pid).or_default();
            if mem_buf.len() == HISTORY_LEN {
                mem_buf.pop_front();
            }
            mem_buf.push_back(proc.memory_bytes);
        }
    }

    /// Translate a raw terminal key event into an [`Action`], if one is bound.
    ///
    /// Returns `None` for unbound keys so the caller can ignore them without matching
    /// exhaustively on every possible [`KeyCode`].
    ///
    /// # Arguments
    ///
    /// * `key`         - The raw key event from crossterm.
    /// * `active_view` - The panel currently in focus; some bindings are view-specific.
    pub fn map_key_to_action(key: KeyEvent, ctx: &KeyContext<'_>) -> Option<Action> {
        // Ctrl+C is a universal quit regardless of view or mode.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return Some(Action::Quit);
        }

        // Config popup captures all input when open.
        if ctx.config_open {
            return match key.code {
                KeyCode::Up | KeyCode::Char('k') => Some(Action::ConfigUp),
                KeyCode::Down | KeyCode::Char('j') => Some(Action::ConfigDown),
                KeyCode::Enter => Some(Action::ConfigSelect),
                KeyCode::Esc | KeyCode::Char('c') => Some(Action::CloseConfig),
                KeyCode::Char('q') => Some(Action::Quit),
                _ => None,
            };
        }

        // When a kill confirmation is pending, only y/n/Esc are accepted.
        if ctx.confirming_kill {
            return match key.code {
                KeyCode::Char('y') => Some(Action::ConfirmKill),
                KeyCode::Char('n') | KeyCode::Esc => Some(Action::CancelKill),
                _ => None,
            };
        }

        // Filter bar intercepts most keystrokes when active.
        if ctx.filter_active {
            return match key.code {
                KeyCode::Esc => Some(Action::ClearFilter),
                KeyCode::Backspace => Some(Action::FilterBackspace),
                KeyCode::Up | KeyCode::Char('k') => Some(Action::MoveUp),
                KeyCode::Down | KeyCode::Char('j') => Some(Action::MoveDown),
                KeyCode::Enter => Some(Action::SelectProcess),
                KeyCode::Char(c) => Some(Action::FilterInput(c)),
                _ => None,
            };
        }

        match ctx.active_view {
            ActiveView::Tree => match key.code {
                KeyCode::Char('q') => Some(Action::Quit),
                KeyCode::Up | KeyCode::Char('k') => Some(Action::MoveUp),
                KeyCode::Down | KeyCode::Char('j') => Some(Action::MoveDown),
                KeyCode::Char(' ') => Some(Action::ToggleExpand),
                KeyCode::Enter => Some(Action::SelectProcess),
                KeyCode::Tab => Some(Action::SortNext),
                KeyCode::BackTab => Some(Action::SortPrev),
                KeyCode::Char('s') => Some(Action::SortToggleDirection),
                KeyCode::Char('x') => Some(Action::KillRequest),
                KeyCode::Char('c') => Some(Action::ToggleConfig),
                KeyCode::Char('/') => Some(Action::EnterFilter),
                _ => None,
            },
            ActiveView::Detail => match key.code {
                KeyCode::Char('q') => Some(Action::Quit),
                KeyCode::Esc => Some(Action::BackToTree),
                KeyCode::Char('x') => Some(Action::KillRequest),
                KeyCode::Char('c') => Some(Action::ToggleConfig),
                _ => None,
            },
        }
    }
}

/// Attempt to kill a process by PID using SIGTERM.
///
/// Uses `libc::kill` directly instead of sysinfo, which requires a
/// fully-refreshed `System` instance just to send a signal.
fn kill_process(pid: u32) -> String {
    let pid_i32 = pid as i32;
    // SAFETY: kill(2) with SIGTERM is a standard POSIX syscall.
    let result = unsafe { libc::kill(pid_i32, libc::SIGTERM) };
    if result == 0 {
        return format!("Sent SIGTERM to PID {}", pid);
    }

    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        Some(libc::ESRCH) => format!("PID {} not found", pid),
        Some(libc::EPERM) => format!("Permission denied for PID {}", pid),
        _ => format!("Failed to kill PID {}: {}", pid, err),
    }
}

/// Sort process nodes recursively: siblings at each level are sorted,
/// preserving the parent-child tree structure.
///
/// When `use_aggregate` is `true` the root-level siblings are sorted by their
/// subtree aggregate values for CPU and Memory columns, giving a more useful
/// ordering (e.g. a claude instance using 400 MB of child memory ranks higher
/// than one using 10 MB). Children are always sorted by their own `info` values.
///
/// # Arguments
///
/// * `nodes`         - Mutable slice of sibling nodes to sort at this level.
/// * `column`        - The column to compare on.
/// * `direction`     - Ascending or descending order.
/// * `use_aggregate` - When `true`, sort this level by subtree stats for
///   CPU/Memory columns. Set to `false` for recursive calls.
fn sort_forest(
    nodes: &mut [ProcessNode],
    column: SortColumn,
    direction: SortDirection,
    use_aggregate: bool,
) {
    nodes.sort_by(|a, b| {
        let cmp = compare_nodes(a, b, column, use_aggregate);
        match direction {
            SortDirection::Ascending => cmp,
            SortDirection::Descending => cmp.reverse(),
        }
    });
    // Children are always sorted by their own stats (use_aggregate = false).
    for node in nodes.iter_mut() {
        sort_forest(&mut node.children, column, direction, false);
    }
}

/// Compare two [`ProcessNode`] values by the given sort column.
///
/// When `use_aggregate` is `true` and the column is `Cpu` or `Memory`, the
/// comparison uses `subtree_stats` totals so root nodes are ranked by their
/// full resource footprint rather than just the top-level process.
fn compare_nodes(
    a: &ProcessNode,
    b: &ProcessNode,
    column: SortColumn,
    use_aggregate: bool,
) -> std::cmp::Ordering {
    if use_aggregate {
        match column {
            SortColumn::Cpu => {
                return a
                    .subtree_stats
                    .total_cpu
                    .partial_cmp(&b.subtree_stats.total_cpu)
                    .unwrap_or(std::cmp::Ordering::Equal);
            }
            SortColumn::Memory => {
                return a
                    .subtree_stats
                    .total_memory
                    .cmp(&b.subtree_stats.total_memory);
            }
            _ => {}
        }
    }
    compare_by_column(&a.info, &b.info, column)
}

/// Returns `true` when `entry` matches the given lower-cased `query`.
///
/// Checked fields (all compared case-insensitively):
/// - Display name (`filter::display_name`)
/// - PID as a decimal string
/// - The basename of the working directory path
/// - The full command line (argv joined with spaces)
pub fn entry_matches_filter(entry: &FlatEntry, query: &str) -> bool {
    use crate::process::display_name;

    if display_name(&entry.info).to_lowercase().contains(query) {
        return true;
    }

    if entry.info.pid.to_string().contains(query) {
        return true;
    }

    if let Some(ref cwd) = entry.info.cwd {
        let basename = cwd.rsplit('/').next().unwrap_or(cwd.as_str());
        if basename.to_lowercase().contains(query) {
            return true;
        }
    }

    let cmd = entry.info.cmd.join(" ");
    cmd.to_lowercase().contains(query)
}

/// Compare two [`ProcessInfo`] values by the given sort column.
fn compare_by_column(a: &ProcessInfo, b: &ProcessInfo, column: SortColumn) -> std::cmp::Ordering {
    match column {
        SortColumn::Pid => a.pid.cmp(&b.pid),
        SortColumn::Name => a.name.cmp(&b.name),
        SortColumn::Cpu => a
            .cpu_usage
            .partial_cmp(&b.cpu_usage)
            .unwrap_or(std::cmp::Ordering::Equal),
        SortColumn::Memory => a.memory_bytes.cmp(&b.memory_bytes),
        SortColumn::Status => a.status.cmp(&b.status),
        SortColumn::Uptime => a.run_time.cmp(&b.run_time),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::process::{build_forest, flatten_visible, ProcessInfo};

    fn make_proc(pid: u32, parent: Option<u32>, name: &str, cpu: f32, mem: u64) -> ProcessInfo {
        ProcessInfo {
            pid,
            parent_pid: parent,
            name: name.to_string(),
            cmd: vec![name.to_string()],
            exe_path: None,
            cwd: None,
            cpu_usage: cpu,
            memory_bytes: mem,
            status: "Run".to_string(),
            environ_count: 0,
            start_time: 0,
            run_time: 0,
        }
    }

    #[test]
    fn test_agent_summary_empty() {
        // An empty forest should produce a zeroed AgentSummary.
        let app = App {
            forest: build_forest(&[]),
            ..Default::default()
        };
        let summary = app.compute_agent_summary();
        assert_eq!(summary.claude_count, 0);
        assert_eq!(summary.codex_count, 0);
        assert_eq!(summary.total_memory, 0);
        assert!((summary.total_cpu - 0.0).abs() < 1e-4);
    }

    #[test]
    fn test_agent_summary_mixed() {
        // 2 claude roots + 1 codex root, each with one child.
        // subtree_stats should be aggregated (self + child).
        let procs = vec![
            make_proc(1, None, "claude", 1.0, 100),
            make_proc(2, Some(1), "node", 1.0, 100), // child of claude 1
            make_proc(3, None, "claude", 2.0, 200),
            make_proc(4, Some(3), "node", 2.0, 200), // child of claude 3
            make_proc(5, None, "codex", 3.0, 300),
            make_proc(6, Some(5), "node", 3.0, 300), // child of codex
        ];
        let app = App {
            forest: build_forest(&procs),
            ..Default::default()
        };
        let summary = app.compute_agent_summary();
        assert_eq!(summary.claude_count, 2);
        assert_eq!(summary.codex_count, 1);
        // Each root's subtree_stats covers self + one child, so:
        // claude1: cpu=2.0, mem=200; claude3: cpu=4.0, mem=400; codex5: cpu=6.0, mem=600
        assert!(
            (summary.total_cpu - 12.0).abs() < 1e-3,
            "total cpu: {}",
            summary.total_cpu
        );
        assert_eq!(summary.total_memory, 1200);
    }

    // ── Activity state tests ────────────────────────────────────────────────

    fn app_with_procs(procs: Vec<ProcessInfo>) -> App {
        let mut app = App::new();
        app.forest = build_forest(&procs);
        app.flat_list = flatten_visible(&app.forest);
        app
    }

    fn make_proc_simple(pid: u32, parent: Option<u32>, name: &str, cpu: f32) -> ProcessInfo {
        make_proc(pid, parent, name, cpu, 0)
    }

    #[test]
    fn test_activity_unknown_fewer_than_window() {
        let mut app = App::new();
        let pid = 1u32;
        let procs = vec![make_proc_simple(pid, None, "claude", 0.0)];
        app.forest = build_forest(&procs);
        let buf = app.aggregate_cpu_history.entry(pid).or_default();
        for _ in 0..(IDLE_SAMPLE_WINDOW - 2) {
            buf.push_back(0.0);
        }
        app.update_activity_states();
        assert_eq!(app.activity_state.get(&pid), Some(&ActivityState::Unknown));
    }

    #[test]
    fn test_activity_idle() {
        let mut app = App::new();
        let pid = 1u32;
        let procs = vec![make_proc_simple(pid, None, "claude", 0.1)];
        app.forest = build_forest(&procs);
        let buf = app.aggregate_cpu_history.entry(pid).or_default();
        for _ in 0..(IDLE_SAMPLE_WINDOW - 1) {
            buf.push_back(0.1);
        }
        app.update_activity_states();
        assert_eq!(app.activity_state.get(&pid), Some(&ActivityState::Idle));
    }

    #[test]
    fn test_activity_active() {
        let mut app = App::new();
        let pid = 1u32;
        let procs = vec![make_proc_simple(pid, None, "claude", 50.0)];
        app.forest = build_forest(&procs);
        let buf = app.aggregate_cpu_history.entry(pid).or_default();
        for _ in 0..(IDLE_SAMPLE_WINDOW - 1) {
            buf.push_back(0.1);
        }
        app.update_activity_states();
        assert_eq!(app.activity_state.get(&pid), Some(&ActivityState::Active));
    }

    // ── Filter tests ────────────────────────────────────────────────────────

    #[test]
    fn test_filter_matches_name() {
        let procs = vec![
            make_proc_simple(1, None, "claude", 0.0),
            make_proc_simple(2, None, "codex", 0.0),
        ];
        let mut app = app_with_procs(procs);
        app.filter_text = "claude".to_string();
        app.apply_filter();
        assert_eq!(app.flat_list.len(), 1);
        assert_eq!(app.flat_list[0].info.name, "claude");
    }

    #[test]
    fn test_filter_preserves_parents() {
        let procs = vec![
            make_proc_simple(1, None, "claude", 0.0),
            make_proc_simple(2, Some(1), "node", 0.0),
        ];
        let mut app = app_with_procs(procs);
        app.filter_text = "node".to_string();
        app.apply_filter();
        assert_eq!(app.flat_list.len(), 2);
        assert!(app.flat_list.iter().any(|e| e.info.pid == 1));
        assert!(app.flat_list.iter().any(|e| e.info.pid == 2));
    }

    #[test]
    fn test_filter_case_insensitive() {
        let procs = vec![make_proc_simple(1, None, "claude", 0.0)];
        let mut app = app_with_procs(procs);
        app.filter_text = "CLAUDE".to_string();
        app.apply_filter();
        assert_eq!(app.flat_list.len(), 1);
    }

    #[test]
    fn test_filter_clears() {
        let procs = vec![
            make_proc_simple(1, None, "claude", 0.0),
            make_proc_simple(2, None, "codex", 0.0),
        ];
        let mut app = app_with_procs(procs);
        app.filter_text = "claude".to_string();
        app.apply_filter();
        assert_eq!(app.flat_list.len(), 1);
        app.handle_action(Action::ClearFilter);
        assert_eq!(app.flat_list.len(), 2);
    }
}