cctop 0.23.2

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, Gemini CLI, OpenCode, Pi, Windsurf)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
//! The tree view: sessions grouped by repository, then by checkout — and,
//! when root is watching more than one user, by user above both.
//!
//! htop's `F5` for agents. A flat table answers "what is running"; with a dozen
//! agents across three repositories and their worktrees, the question is as
//! often "what is running *in this repository*", and the flat table makes that
//! a matter of reading every PROJECT cell.
//!
//! Drawn inside the existing table rather than with `tui-tree-widget`. That
//! crate renders a tree of one-line labels; the rows here are the table's own,
//! with a dozen aligned columns, per-cell colour, click-to-sort headers, query
//! highlighting and a cursor that everything from the bottom panels to the row
//! menu already follows through [`App::visible`]. Adopting the widget would mean
//! either giving all that up or rebuilding it inside a widget that owns its own
//! selection state — two cursors to keep in agreement. The tree only needs a
//! few more rows in `visible` and a prefix of `├─` glyphs on the label, so that
//! is all it adds.
//!
//! Only what is known is nested. A repository is known from its git common
//! directory, which is what makes every worktree of one repository land under
//! one heading; a checkout is the directory holding the `.git`. Subagents nest
//! under their session exactly as they do in the flat table. No harness records
//! that one *session* started another — a Claude resume or a Codex fork keeps
//! only the id it came from, not a live parent — so sessions are never nested
//! under each other.
//!
//! The user level exists for root's view of a shared machine, where the first
//! question is whose agents these are. It is added only when the rows on screen
//! belong to more than one user, the same way a repository seen through one
//! checkout gets no checkout level: a heading that every row sits under says
//! nothing. Two users in one repository get a heading each, and fold
//! separately, because to them it is two pieces of work rather than one.

use super::*;
use crate::session::ActivityState;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex, PoisonError};

/// One heading in the tree: a repository, or one checkout of it.
///
/// The aggregates are over the sessions *shown* beneath it, after filtering, so
/// the heading always adds up to the rows it folds — a total that included
/// sessions the filter had hidden would be a number with nothing on screen to
/// check it against.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Group {
    /// Stable across refreshes, and what the fold state is remembered under.
    pub key: String,
    pub label: String,
    /// 0 for the outermost level shown and one more for each level in: a
    /// repository and its checkouts, under a user when there is a user level.
    pub depth: usize,
    pub collapsed: bool,
    pub sessions: usize,
    pub running: usize,
    /// Running and waiting on you, whether for a reply or an answer.
    pub waiting: usize,
    /// Blocked on a question, the loudest of the waiting states.
    pub asking: usize,
    /// Sum of the priced sessions; `None` when not one of them has a price.
    pub cost: Option<f64>,
    /// The most recent activity among the members.
    pub last_active: String,
    /// The branch a checkout has out, for its heading's BRANCH cell. A
    /// repository has several, so it has none.
    pub branch: Option<String>,
}

impl Group {
    fn add(&mut self, s: &Session) {
        self.sessions += 1;
        if s.is_running() {
            self.running += 1;
            match s.activity_state {
                ActivityState::Asking => {
                    self.waiting += 1;
                    self.asking += 1;
                }
                ActivityState::WaitingForInput => self.waiting += 1,
                _ => {}
            }
        }
        if s.cost_available
            && !s.cost_is_free
            && let Some(c) = s.total_cost
        {
            self.cost = Some(self.cost.unwrap_or(0.0) + c);
        }
        let newer = match (
            crate::util::parse_ts(&s.last_active),
            crate::util::parse_ts(&self.last_active),
        ) {
            (Some(a), Some(b)) => a > b,
            (Some(_), None) => true,
            _ => false,
        };
        if newer {
            self.last_active = s.last_active.clone();
        }
    }
}

/// The table's rows in tree order, the headings they reference, and the glyphs
/// leading each row's label.
pub(super) struct Tree {
    pub groups: Vec<Group>,
    pub rows: Vec<Row>,
    pub indent: Vec<String>,
}

/// Where a session's directory sits: a repository and a checkout of it.
#[derive(Debug, Clone, PartialEq)]
struct Place {
    repo: String,
    repo_label: String,
    /// `None` outside a repository, where there is no second level to show.
    checkout: Option<(String, String)>,
}

/// How long a directory's place is trusted; the same bargain as the branch
/// cache in [`columns`], since a checkout moves about as often as a branch.
const PLACE_TTL: Duration = Duration::from_secs(60);

type Located = Option<(PathBuf, PathBuf)>;

static PLACES: LazyLock<Mutex<HashMap<String, (Located, Instant)>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

/// The repository's common git directory and the checkout root, for a
/// directory inside one. Cached, since the tree is rebuilt on every refresh.
fn locate_cached(dir: &str) -> Located {
    let mut cache = PLACES.lock().unwrap_or_else(PoisonError::into_inner);
    if let Some((found, at)) = cache.get(dir)
        && at.elapsed() < PLACE_TTL
    {
        return found.clone();
    }
    let found = locate(Path::new(dir));
    cache.insert(dir.to_string(), (found.clone(), Instant::now()));
    found
}

/// Resolve `dir` to `(common git dir, checkout root)`.
///
/// The common directory is what every worktree of a repository shares, which
/// is why it and not the checkout root is the repository's identity: two
/// worktrees have two roots and one common directory. A linked worktree's `.git`
/// is a file naming its private git dir, and that dir's `commondir` names the
/// shared one. A submodule's git dir has no `commondir` — it is a repository of
/// its own, and is grouped as one.
///
/// Relative paths are refused: they would resolve against cctop's own working
/// directory, and group a session under whatever repository cctop was started
/// in.
fn locate(dir: &Path) -> Located {
    if !dir.is_absolute() {
        return None;
    }
    let root = dir.ancestors().find(|d| d.join(".git").exists())?;
    let git = root.join(".git");
    if git.is_dir() {
        return Some((git, root.to_path_buf()));
    }
    let pointer = std::fs::read_to_string(&git).ok()?;
    let target = PathBuf::from(pointer.trim().strip_prefix("gitdir:")?.trim());
    let target = if target.is_absolute() {
        target
    } else {
        root.join(target)
    };
    let common = match std::fs::read_to_string(target.join("commondir")) {
        Ok(rel) => {
            let joined = target.join(rel.trim());
            PathBuf::from(crate::collide::normalise(&joined.to_string_lossy(), "/"))
        }
        Err(_) => target,
    };
    Some((common, root.to_path_buf()))
}

/// The directory a repository is known by: the one holding its `.git`, or the
/// common directory itself for a bare repository, which has no other.
fn repo_dir(common: &Path) -> PathBuf {
    match common.file_name() {
        Some(name) if name == ".git" => common.parent().unwrap_or(common).to_path_buf(),
        _ => common.to_path_buf(),
    }
}

fn place(s: &Session) -> Place {
    let dir = s.label_source.as_str();
    // A remote row's directory is a path on another machine, so looking it up
    // here would read whatever lives at the same path locally. It is grouped by
    // host and directory, which is all this side can say about it.
    if let Some(r) = &s.remote {
        return Place {
            repo: format!("host:{}:{dir}", r.host),
            repo_label: format!("{}:{dir}", r.host),
            checkout: None,
        };
    }
    match locate_cached(dir) {
        Some((common, root)) => {
            let home = repo_dir(&common);
            let checkout_label = if root == home {
                // The main checkout is the one the repository is named after,
                // so its heading says which of the checkouts that is.
                format!("{} (main)", file_name(&root))
            } else {
                match root.strip_prefix(&home) {
                    Ok(inside) => inside.to_string_lossy().into_owned(),
                    Err(_) => crate::util::tildify(&root.to_string_lossy()),
                }
            };
            Place {
                repo: format!("repo:{}", common.display()),
                repo_label: crate::util::tildify(&home.to_string_lossy()),
                checkout: Some((format!("wt:{}", root.display()), checkout_label)),
            }
        }
        // Outside a repository the directory is its own group, the same
        // fallback the conflict check makes: one shared "no repository" bucket
        // would put every such session under one heading that means nothing.
        None if dir.is_empty() => Place {
            repo: "dir:".into(),
            repo_label: "(no directory)".into(),
            checkout: None,
        },
        None => Place {
            repo: format!("dir:{dir}"),
            repo_label: crate::util::tildify(dir),
            checkout: None,
        },
    }
}

fn file_name(p: &Path) -> String {
    p.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| p.to_string_lossy().into_owned())
}

/// A checkout's `(key, label)`, or `None` outside a repository, with the
/// sessions in it.
type Checkout = (Option<(String, String)>, Vec<usize>);

/// The fold key of a user's heading, and the prefix of every heading under it.
fn user_key(s: &Session) -> String {
    format!("user:{}", crate::config::user_label(s.owner.as_deref()))
}

/// A heading's fold key under `scope` — empty without a user level, so a
/// single-user tree remembers its folds under the keys it always had.
fn scoped(scope: &str, key: String) -> String {
    match scope.is_empty() {
        true => key,
        false => format!("{scope}/{key}"),
    }
}

/// Lay `ordered` out as a tree.
///
/// `ordered` is the filtered sessions already sorted, and the tree keeps that
/// order for the sessions within a checkout. Groups are ranked by what the
/// sort column says about the group as a whole. For a column that adds up
/// ([`summand`]) that is the group's total, so a cost sort leads with the
/// repository that has cost the most rather than the one holding the single
/// dearest session: ten $5 agents outrank one $20 one, which is the answer to
/// "where is the money going". For every other column a group's aggregate
/// *is* its best-placed member (the newest activity, the fullest context; a
/// model name has no sum), so first-seen order already ranks it. Either way a
/// group is never split to honour the sort.
///
/// `sort` is the column and direction `ordered` was sorted by.
///
/// `children` is how many subagent rows follow a session, which is the flat
/// table's business (whether it is expanded) and is asked rather than decided
/// here.
pub(super) fn build(
    sessions: &[Session],
    ordered: &[usize],
    collapsed: &HashSet<String>,
    sort: (ColumnId, bool),
    children: impl Fn(usize) -> usize,
) -> Tree {
    let mut tree = Tree {
        groups: Vec::new(),
        rows: Vec::new(),
        indent: Vec::new(),
    };
    let ordered_sessions = ordered.iter().map(|&i| &sessions[i]);
    if columns::users_in_view(ordered_sessions) < 2 {
        repos(
            &mut tree, sessions, ordered, collapsed, sort, &children, None,
        );
        return tree;
    }

    // (user key, members), in first-seen order, for the same reason the
    // repositories below are.
    let mut users: Vec<(String, Vec<usize>)> = Vec::new();
    for &i in ordered {
        let key = user_key(&sessions[i]);
        match users.iter_mut().find(|(k, _)| *k == key) {
            Some((_, members)) => members.push(i),
            None => users.push((key, vec![i])),
        }
    }
    rank(&mut users, |(_, m)| m.clone(), sessions, sort);
    for (key, members) in users {
        let label = crate::config::user_label(sessions[members[0]].owner.as_deref()).to_string();
        tree.indent.push(String::new());
        let mut g = Group {
            collapsed: collapsed.contains(&key),
            key: key.clone(),
            label,
            depth: 0,
            ..Group::default()
        };
        for &i in &members {
            g.add(&sessions[i]);
        }
        let folded = g.collapsed;
        tree.groups.push(g);
        tree.rows.push(Row::Group(tree.groups.len() - 1));
        if !folded {
            repos(
                &mut tree,
                sessions,
                &members,
                collapsed,
                sort,
                &children,
                Some(&key),
            );
        }
    }
    tree
}

/// Whether sort column `col` adds up across sessions, so that a group can be
/// ranked by its total.
///
/// Only what sums to something meaningful: the money, the burn rates, the
/// tokens, the tool calls and the machine the agents hold between them. A
/// context percentage or an error *rate* summed over unrelated agents is a
/// number that describes none of them, so a group sorted by one is ranked by
/// its best member instead.
fn adds_up(col: ColumnId) -> bool {
    matches!(
        col,
        ColumnId::Cost
            | ColumnId::CostHour
            | ColumnId::CostToday
            | ColumnId::TokenTotal
            | ColumnId::TokenRate
            | ColumnId::Tools
            | ColumnId::Cpu
            | ColumnId::Memory
    )
}

/// One session's share of its group's total under a column that [`adds_up`].
fn summand(col: ColumnId, s: &Session) -> f64 {
    let cpu = s.process.as_ref().map_or(0.0, |p| p.cpu as f64);
    let memory = s.process.as_ref().map_or(0.0, |p| p.memory as f64);
    match col {
        // An unpriced session adds nothing here, as it adds nothing to the
        // heading's cost.
        ColumnId::Cost if s.cost_available && !s.cost_is_free => s.total_cost.unwrap_or(0.0),
        ColumnId::CostHour => s.cost_hour,
        ColumnId::CostToday => s.cost_today,
        ColumnId::TokenTotal => (s.input_tokens + s.output_tokens) as f64,
        ColumnId::TokenRate => s.tokens_per_min,
        ColumnId::Tools => s.tool_count as f64,
        ColumnId::Cpu => cpu,
        ColumnId::Memory => memory,
        _ => 0.0,
    }
}

/// Reorder `groups` by the total of their members under `sort` when the
/// column [`adds_up`], and otherwise leave them in first-seen order, which is
/// already the order of their best-placed members.
///
/// Stable, so groups that tie keep the order the session sort gave them.
fn rank<T>(
    groups: &mut Vec<T>,
    members: impl Fn(&T) -> Vec<usize>,
    sessions: &[Session],
    (col, asc): (ColumnId, bool),
) {
    if !adds_up(col) {
        return;
    }
    let mut keyed: Vec<(f64, T)> = std::mem::take(groups)
        .into_iter()
        .map(|g| {
            let total = members(&g)
                .iter()
                .map(|&i| summand(col, &sessions[i]))
                .sum();
            (total, g)
        })
        .collect();
    keyed.sort_by(|a, b| {
        let ord = a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal);
        if asc { ord } else { ord.reverse() }
    });
    groups.extend(keyed.into_iter().map(|(_, g)| g));
}

/// Lay out `ordered` as repositories and their checkouts.
///
/// `user` is the heading these hang under, when there is a user level: the
/// repositories then become its children, drawn with the same `├─` rails a
/// checkout is, and every key is scoped to it.
fn repos(
    tree: &mut Tree,
    sessions: &[Session],
    ordered: &[usize],
    collapsed: &HashSet<String>,
    sort: (ColumnId, bool),
    children: &impl Fn(usize) -> usize,
    user: Option<&str>,
) {
    let scope = user.unwrap_or_default();
    let depth = usize::from(user.is_some());
    // (repo place, [(checkout, members)]), in first-seen order. Linear lookup:
    // a table holds tens of repositories, not thousands.
    let mut repos: Vec<(Place, Vec<Checkout>)> = Vec::new();
    for &i in ordered {
        let p = place(&sessions[i]);
        let at = match repos.iter().position(|(r, _)| r.repo == p.repo) {
            Some(at) => at,
            None => {
                repos.push((p.clone(), Vec::new()));
                repos.len() - 1
            }
        };
        let checkouts = &mut repos[at].1;
        match checkouts.iter_mut().find(|(c, _)| *c == p.checkout) {
            Some((_, members)) => members.push(i),
            None => checkouts.push((p.checkout.clone(), vec![i])),
        }
    }
    // A repository is ranked by the same total its heading shows, which is
    // its checkouts' together.
    rank(
        &mut repos,
        |(_, checkouts)| checkouts.iter().flat_map(|(_, m)| m.clone()).collect(),
        sessions,
        sort,
    );
    for (_, checkouts) in &mut repos {
        rank(checkouts, |(_, m)| m.clone(), sessions, sort);
    }

    let heading = |tree: &mut Tree, key: String, label: String, depth, members: &[usize]| {
        let key = scoped(scope, key);
        let mut g = Group {
            collapsed: collapsed.contains(&key),
            key,
            label,
            depth,
            ..Group::default()
        };
        for &i in members {
            g.add(&sessions[i]);
        }
        let folded = g.collapsed;
        tree.groups.push(g);
        tree.rows.push(Row::Group(tree.groups.len() - 1));
        folded
    };
    let leaves = |tree: &mut Tree, members: &[usize], cont: &str| {
        for (k, &i) in members.iter().enumerate() {
            let last = k + 1 == members.len();
            tree.rows.push(Row::Session(i));
            tree.indent
                .push(format!("{cont}{}", if last { "└─ " } else { "├─ " }));
            // A subagent's own cell already draws its `├─`; it only needs the
            // rails of everything above it.
            let rail = format!("{cont}{}", if last { "   " } else { "│  " });
            for index in 0..children(i) {
                tree.rows.push(Row::Subagent { parent: i, index });
                tree.indent.push(rail.clone());
            }
        }
    };

    let r_count = repos.len();
    for (r, (repo, checkouts)) in repos.into_iter().enumerate() {
        // Under a user, a repository is a child like any other and carries the
        // rails for everything beneath it; at the top it needs none.
        let (glyph, rail) = match (user.is_some(), r + 1 == r_count) {
            (false, _) => ("", ""),
            (true, false) => ("├─ ", "│  "),
            (true, true) => ("└─ ", "   "),
        };
        let all: Vec<usize> = checkouts.iter().flat_map(|(_, m)| m.clone()).collect();
        tree.indent.push(glyph.to_string());
        if heading(tree, repo.repo, repo.repo_label, depth, &all) {
            continue;
        }
        // A repository seen through one checkout has nothing for a second level
        // to distinguish, and a heading per level would only push the sessions
        // further right.
        if checkouts.len() == 1 {
            leaves(tree, &all, rail);
            continue;
        }
        let n = checkouts.len();
        for (c, (checkout, members)) in checkouts.into_iter().enumerate() {
            let last = c + 1 == n;
            let (key, label) = checkout.unwrap_or_default();
            tree.indent
                .push(format!("{rail}{}", if last { "└─ " } else { "├─ " }));
            let folded = heading(tree, key, label, depth + 1, &members);
            if let Some(g) = tree.groups.last_mut() {
                g.branch = columns::branch_of(&sessions[members[0]]);
            }
            if !folded {
                leaves(
                    tree,
                    &members,
                    &format!("{rail}{}", if last { "   " } else { "│  " }),
                );
            }
        }
    }
}

impl App {
    /// The heading under the cursor, when it is on one.
    pub fn selected_group(&self) -> Option<&Group> {
        match self.selected_row()? {
            Row::Group(g) => self.groups.get(g),
            _ => None,
        }
    }

    pub fn on_group(&self) -> bool {
        self.selected_group().is_some()
    }

    /// Where `F` would fork from: the checkout root the new branch starts at,
    /// and the main repository whose `.claude/worktrees/` it goes in.
    ///
    /// A heading is read back from its fold key rather than from one of its
    /// sessions, because a repository heading stands for the main checkout
    /// even when every session under it is in some other worktree. Forking
    /// from a linked worktree still lands beside the others, under the main
    /// one — a worktree nested in a worktree is one nobody finds again.
    pub(super) fn fork_point(&self) -> Result<(PathBuf, PathBuf), &'static str> {
        let dir = match self.selected_row() {
            Some(Row::Group(g)) => {
                let key = self.groups.get(g).map_or("", |g| g.key.as_str());
                // Under a user level every key is `user:<name>/<key>`.
                let key = key
                    .strip_prefix("user:")
                    .and_then(|rest| rest.split_once('/'))
                    .map_or(key, |(_, key)| key);
                if let Some(common) = key.strip_prefix("repo:") {
                    repo_dir(Path::new(common))
                } else if let Some(root) = key.strip_prefix("wt:") {
                    PathBuf::from(root)
                } else if key.starts_with("host:") {
                    return Err("That repository is on another machine");
                } else {
                    return Err("Not in a git repository");
                }
            }
            _ => {
                let s = self.selected_session().ok_or("Nothing selected")?;
                if s.remote.is_some() {
                    return Err("That session is on another machine");
                }
                PathBuf::from(&s.label_source)
            }
        };
        let (common, root) =
            locate_cached(&dir.to_string_lossy()).ok_or("Not in a git repository")?;
        Ok((root, repo_dir(&common)))
    }

    /// Switch between the flat table and the tree.
    ///
    /// The cursor keeps its session across the switch, the way it keeps it
    /// across a resort: `refilter` anchors on the row's key.
    pub(super) fn toggle_tree(&mut self) {
        self.tree = !self.tree;
        self.refilter();
        self.save_prefs();
        self.set_status(if self.tree {
            "Tree view: grouped by repository and checkout"
        } else {
            "Flat view"
        });
    }

    /// Fold or unfold the heading under the cursor. The cursor stays on the
    /// heading either way, since it is the one row certain to still be there.
    pub(super) fn toggle_group(&mut self) {
        let Some(key) = self.selected_group().map(|g| g.key.clone()) else {
            return;
        };
        if !self.collapsed.remove(&key) {
            self.collapsed.insert(key);
        }
        self.refilter();
        self.save_prefs();
    }

    /// Unfold whatever is hiding a session, so a jump to it has a row to land
    /// on. A bell from a folded repository is still a bell.
    pub(super) fn reveal(&mut self, key: &str) {
        if !self.tree {
            return;
        }
        let Some(s) = self.sessions.iter().find(|s| s.key() == key) else {
            return;
        };
        let p = place(s);
        // Every key the session could be folded under, with a user level and
        // without: whether there is one depends on who else is on screen, which
        // is not this session's to say.
        let user = user_key(s);
        let mut changed = self.collapsed.remove(&user);
        let mut keys = vec![p.repo];
        keys.extend(p.checkout.map(|(checkout, _)| checkout));
        for key in keys {
            changed |= self.collapsed.remove(&scoped(&user, key.clone()));
            changed |= self.collapsed.remove(&key);
        }
        if changed {
            self.refilter();
            self.save_prefs();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::tests::{session, test_app};

    /// A scratch tree of directories, removed when the test ends.
    struct Scratch(PathBuf);

    impl Scratch {
        fn new(name: &str) -> Scratch {
            let root = std::env::temp_dir().join(format!(
                "cctop-tree-{}-{name}-{:?}",
                std::process::id(),
                std::thread::current().id()
            ));
            let _ = std::fs::remove_dir_all(&root);
            std::fs::create_dir_all(&root).expect("scratch directory");
            Scratch(root)
        }

        /// A repository with its main checkout at `rel`.
        fn repo(&self, rel: &str) -> String {
            let dir = self.0.join(rel);
            std::fs::create_dir_all(dir.join(".git")).expect("repo");
            std::fs::write(dir.join(".git/HEAD"), "ref: refs/heads/main\n").expect("HEAD");
            dir.to_string_lossy().into_owned()
        }

        /// A linked worktree of the repository at `repo`, laid out as `git
        /// worktree add` does it: a `.git` file, and a private git dir whose
        /// `commondir` points back at the shared one.
        fn worktree(&self, repo: &str, rel: &str, name: &str) -> String {
            let gitdir = Path::new(repo).join(".git/worktrees").join(name);
            std::fs::create_dir_all(&gitdir).expect("gitdir");
            std::fs::write(gitdir.join("commondir"), "../..\n").expect("commondir");
            std::fs::write(gitdir.join("HEAD"), format!("ref: refs/heads/{name}\n")).expect("HEAD");
            let dir = self.0.join(rel);
            std::fs::create_dir_all(&dir).expect("worktree");
            std::fs::write(dir.join(".git"), format!("gitdir: {}\n", gitdir.display()))
                .expect(".git file");
            dir.to_string_lossy().into_owned()
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            std::fs::remove_dir_all(&self.0).ok();
        }
    }

    fn groups_of(app: &App) -> Vec<(usize, String)> {
        app.visible
            .iter()
            .filter_map(|r| match r {
                Row::Group(g) => Some((app.groups[*g].depth, app.groups[*g].label.clone())),
                _ => None,
            })
            .collect()
    }

    fn position(app: &App, id: &str) -> usize {
        app.visible
            .iter()
            .position(|r| {
                matches!(r, Row::Session(_))
                    && r.session().map(|i| app.sessions[i].session_id.as_str()) == Some(id)
            })
            .expect("session row")
    }

    /// The point of grouping by the common directory rather than the checkout
    /// root: every worktree of one repository lands under one heading, each
    /// worktree its own checkout beneath it.
    #[test]
    fn worktrees_of_one_repository_share_a_heading() {
        let fx = Scratch::new("worktrees");
        let repo = fx.repo("cctop");
        let wt = fx.worktree(&repo, "cctop/.claude/worktrees/agent-1", "agent-1");
        let deep = format!("{repo}/src");
        std::fs::create_dir_all(&deep).unwrap();
        let other = fx.repo("elsewhere");

        let mut app = test_app();
        app.tree = true;
        app.sessions = vec![
            session("main", true, &repo),
            session("sub", true, &deep),
            session("wt", true, &wt),
            session("other", false, &other),
        ];
        app.refilter();

        let groups = groups_of(&app);
        let repos: Vec<_> = groups.iter().filter(|g| g.0 == 0).collect();
        assert_eq!(repos.len(), 2, "two repositories: {groups:?}");
        let checkouts: Vec<&str> = groups
            .iter()
            .filter(|g| g.0 == 1)
            .map(|g| g.1.as_str())
            .collect();
        assert_eq!(checkouts.len(), 2, "cctop has two checkouts: {groups:?}");
        assert!(checkouts.contains(&"cctop (main)"));
        assert!(checkouts.contains(&".claude/worktrees/agent-1"));

        // A subdirectory is the same checkout as its root.
        let cctop = app
            .groups
            .iter()
            .find(|g| g.depth == 0 && g.label.ends_with("cctop"))
            .expect("cctop heading");
        assert_eq!(cctop.sessions, 3);
        let main = app
            .groups
            .iter()
            .find(|g| g.label == "cctop (main)")
            .unwrap();
        assert_eq!(main.sessions, 2);
        assert_eq!(main.branch.as_deref(), Some("main"));

        // A repository seen through one checkout gets no second level.
        let at = app
            .visible
            .iter()
            .position(|r| matches!(r, Row::Group(g) if app.groups[*g].label.ends_with("elsewhere")))
            .unwrap();
        assert_eq!(app.visible[at + 1], Row::Session(3));
        assert_eq!(app.indent[at + 1], "└─ ");
    }

    /// The heading adds up exactly the rows beneath it.
    #[test]
    fn a_heading_totals_its_sessions() {
        let fx = Scratch::new("totals");
        let repo = fx.repo("r");
        let mut app = test_app();
        app.tree = true;
        let mut a = session("a", true, &repo);
        a.cost_available = true;
        a.total_cost = Some(1.5);
        a.activity_state = ActivityState::WaitingForInput;
        let mut b = session("b", true, &repo);
        b.cost_available = true;
        b.total_cost = Some(2.0);
        b.activity_state = ActivityState::Asking;
        let mut c = session("c", false, &repo);
        // Waiting on nobody: a stopped session's last state is history.
        c.activity_state = ActivityState::WaitingForInput;
        app.sessions = vec![a, b, c];
        app.refilter();

        let g = &app.groups[0];
        assert_eq!(g.sessions, 3);
        assert_eq!(g.running, 2);
        assert_eq!(g.waiting, 2);
        assert_eq!(g.asking, 1);
        assert_eq!(g.cost, Some(3.5));
        assert_eq!(app.matched, 3);
    }

    /// Folding hides the members and keeps the cursor on the heading; unfolding
    /// brings them back. The fold outlives a refresh, since it is keyed.
    #[test]
    fn folding_a_heading_hides_its_sessions() {
        let fx = Scratch::new("fold");
        let repo = fx.repo("r");
        let mut app = test_app();
        app.tree = true;
        app.sessions = vec![session("a", true, &repo), session("b", true, &repo)];
        app.refilter();
        assert_eq!(app.visible.len(), 3);
        app.selected = 0;
        assert!(app.on_group());
        assert!(app.selected_session().is_none(), "a heading is no session");

        app.toggle_group();
        assert_eq!(app.visible, vec![Row::Group(0)]);
        assert!(app.groups[0].collapsed);
        assert_eq!(app.groups[0].sessions, 2, "the folded total still counts");
        app.refilter();
        assert_eq!(app.visible.len(), 1, "the fold survives a refresh");

        app.toggle_group();
        assert_eq!(app.visible.len(), 3);
        assert_eq!(app.selected, 0);
    }

    /// Sorting reorders inside a group and orders groups by their best member,
    /// but never splits one.
    #[test]
    fn the_sort_applies_within_each_group() {
        let fx = Scratch::new("sort");
        let (x, y) = (fx.repo("x"), fx.repo("y"));
        let mut app = test_app();
        app.tree = true;
        let priced = |id: &str, dir: &str, cost: f64| {
            let mut s = session(id, true, dir);
            s.cost_available = true;
            s.total_cost = Some(cost);
            s
        };
        app.sessions = vec![
            priced("x-cheap", &x, 1.0),
            priced("y-mid", &y, 5.0),
            priced("x-dear", &x, 9.0),
        ];
        app.sort_col = ColumnId::Cost;
        app.sort_asc = false;
        app.refilter();

        // x holds the dearest session, so it leads, with both of its own
        // sessions beneath it before y begins.
        assert!(position(&app, "x-dear") < position(&app, "x-cheap"));
        assert!(position(&app, "x-cheap") < position(&app, "y-mid"));
        assert_eq!(app.indent[position(&app, "x-dear")], "├─ ");
        assert_eq!(app.indent[position(&app, "x-cheap")], "└─ ");
    }

    /// Under a column that adds up, a group is ranked by its total, not its
    /// best member: three $4 agents have cost more than one $9 one. Under one
    /// that does not, the best member still decides, and ascending turns
    /// either order around.
    #[test]
    fn groups_rank_by_their_total_when_the_column_adds_up() {
        let fx = Scratch::new("rank");
        let (many, one) = (fx.repo("many"), fx.repo("one"));
        let mut app = test_app();
        app.tree = true;
        let priced = |id: &str, dir: &str, cost: f64| {
            let mut s = session(id, true, dir);
            s.cost_available = true;
            s.total_cost = Some(cost);
            s
        };
        app.sessions = vec![
            priced("m1", &many, 4.0),
            priced("m2", &many, 4.0),
            priced("m3", &many, 4.0),
            priced("o1", &one, 9.0),
        ];
        let first_repo = |app: &App| {
            app.groups
                .iter()
                .find(|g| g.depth == 0)
                .map(|g| g.label.clone())
                .unwrap()
        };

        app.sort_col = ColumnId::Cost;
        app.sort_asc = false;
        app.refilter();
        assert!(first_repo(&app).ends_with("many"), "{:?}", groups_of(&app));
        // The group is still whole: every one of its sessions before `one`.
        assert!(position(&app, "m3") < position(&app, "o1"));
        assert!(position(&app, "m1") < position(&app, "o1"));

        app.sort_asc = true;
        app.refilter();
        assert!(first_repo(&app).ends_with("one"), "{:?}", groups_of(&app));

        // Context does not add up, so the fullest session's group leads.
        app.sessions[3].context = Some(crate::session::ContextUsage {
            used: 150_000,
            max: 200_000,
            compacted: false,
        });
        app.sort_col = ColumnId::Context;
        app.sort_asc = false;
        app.refilter();
        assert!(first_repo(&app).ends_with("one"), "{:?}", groups_of(&app));
    }

    /// A filtered tree shows the matches with the headings they sit under, and
    /// nothing else — a heading with no match beneath it is gone.
    #[test]
    fn filtering_keeps_a_match_and_its_ancestors() {
        let fx = Scratch::new("filter");
        let (x, y) = (fx.repo("x"), fx.repo("y"));
        let mut app = test_app();
        app.tree = true;
        let mut hit = session("hit", true, &x);
        hit.title = Some("kingfisher".into());
        app.sessions = vec![hit, session("miss", true, &x), session("far", true, &y)];
        app.search = "kingfisher".into();
        app.refilter();

        assert_eq!(app.visible.len(), 2, "{:?}", app.visible);
        assert!(matches!(app.visible[0], Row::Group(_)));
        assert_eq!(app.visible[1], Row::Session(0));
        assert_eq!(app.groups[0].sessions, 1);
        assert_eq!(app.matched, 1);
    }

    /// Subagents nest one level further in, under their session's own rail.
    #[test]
    fn subagents_hang_under_their_session_in_the_tree() {
        let fx = Scratch::new("subagents");
        let repo = fx.repo("r");
        let mut app = test_app();
        app.tree = true;
        let mut parent = session("p", true, &repo);
        parent.subagents = vec![crate::session::Subagent {
            agent_id: "agent-1".into(),
            agent_type: "general-purpose".into(),
            description: "look".into(),
            model: "claude-opus-5".into(),
            started_at: None,
            last_active: None,
            duration_ms: 0,
            status: crate::session::SubagentStatus::Running,
            cost: 0.0,
            tool_count: 0,
            tool_use_id: None,
            context: None,
            ghost: false,
        }];
        // Older, so the newest-first sort puts it below `p` whatever the clock
        // did between the two fixtures.
        let mut older = session("q", true, &repo);
        older.last_active = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
        app.sessions = vec![parent, older];
        app.expanded.insert(app.sessions[0].key());
        app.refilter();

        let at = position(&app, "p");
        assert_eq!(
            app.visible[at + 1],
            Row::Subagent {
                parent: 0,
                index: 0
            }
        );
        // `p` is not the last session, so its children carry the rail down.
        assert_eq!(app.indent[at], "├─ ");
        assert_eq!(app.indent[at + 1], "│  ");
    }

    /// Switching views keeps the cursor on the session it was on, and the
    /// flat table has no headings or glyphs left over.
    #[test]
    fn toggling_the_tree_keeps_the_cursor_on_its_session() {
        let fx = Scratch::new("toggle");
        let (x, y) = (fx.repo("x"), fx.repo("y"));
        let mut app = test_app();
        app.sessions = vec![session("a", true, &x), session("b", true, &y)];
        app.refilter();
        app.selected = position(&app, "b");

        app.toggle_tree();
        assert!(app.tree);
        assert_eq!(app.selected_session().unwrap().session_id, "b");
        assert_eq!(app.visible.len(), 4);

        app.toggle_tree();
        assert!(!app.tree);
        assert_eq!(app.selected_session().unwrap().session_id, "b");
        assert_eq!(app.visible.len(), 2);
        assert!(app.groups.is_empty() && app.indent.is_empty());
    }

    /// The keys as pressed: `T` switches the view, and on a heading Enter and
    /// Space fold it rather than opening a menu or marking — while ←/→ still
    /// move the bottom panels, heading or not.
    #[test]
    fn the_keys_fold_a_heading_and_leave_the_panels_alone() {
        use crate::ui::tests::key;
        use ratatui::crossterm::event::KeyCode;
        let fx = Scratch::new("keys");
        let repo = fx.repo("r");
        let mut app = test_app();
        app.sessions = vec![session("a", true, &repo)];
        app.refilter();

        app.on_key(key(KeyCode::Char('T')));
        assert!(app.tree);
        app.selected = 0;
        assert!(app.on_group());

        app.on_key(key(KeyCode::Enter));
        assert_eq!(app.mode, Mode::List, "no row menu for a heading");
        assert_eq!(app.visible.len(), 1, "Enter folded it");
        app.on_key(key(KeyCode::Char(' ')));
        assert_eq!(app.visible.len(), 2, "Space unfolded it");
        assert!(app.marked.is_empty(), "and marked nothing");

        let tab = app.bottom_tab;
        app.on_key(key(KeyCode::Right));
        assert_ne!(app.bottom_tab, tab, "→ still moves the panels");
        assert_eq!(app.visible.len(), 2);
    }

    /// `F` forks from the checkout under the cursor but always into the main
    /// repository's `.claude/worktrees/`, and refuses a directory that is not
    /// a repository at all.
    #[test]
    fn f_resolves_where_a_worktree_forks_from() {
        use crate::ui::tests::key;
        use ratatui::crossterm::event::KeyCode;
        let fx = Scratch::new("fork");
        let repo = fx.repo("r");
        let wt = fx.worktree(&repo, "wt", "side");
        let plain = fx.0.join("plain");
        std::fs::create_dir_all(&plain).expect("plain dir");
        let mut app = test_app();
        app.tree = true;
        app.sessions = vec![
            session("a", true, &repo),
            session("b", true, &wt),
            session("c", true, &plain.to_string_lossy()),
        ];
        app.refilter();

        let heading = |app: &App, prefix: &str| {
            app.visible
                .iter()
                .position(|r| matches!(r, Row::Group(g) if app.groups[*g].key.starts_with(prefix)))
                .expect(prefix)
        };
        app.selected = heading(&app, "repo:");
        app.on_key(key(KeyCode::Char('F')));
        assert_eq!(app.mode, Mode::NewWorktree);
        assert_eq!(app.worktree_base, Path::new(&repo));
        assert_eq!(app.worktree_repo, Path::new(&repo));

        app.mode = Mode::List;
        app.selected = heading(&app, "wt:");
        app.on_key(key(KeyCode::Char('F')));
        assert_eq!(app.worktree_base, Path::new(&wt), "forks from the worktree");
        assert_eq!(
            app.worktree_repo,
            Path::new(&repo),
            "but lands in the main repo"
        );

        app.mode = Mode::List;
        app.selected = heading(&app, "dir:");
        app.on_key(key(KeyCode::Char('F')));
        assert_eq!(app.mode, Mode::List, "no repository, no prompt");
    }

    /// A session in a folded group is unfolded to, not silently unreachable.
    #[test]
    fn revealing_a_session_unfolds_its_group() {
        let fx = Scratch::new("reveal");
        let repo = fx.repo("r");
        let mut app = test_app();
        app.tree = true;
        app.sessions = vec![session("a", true, &repo)];
        app.refilter();
        app.selected = 0;
        app.toggle_group();
        assert_eq!(app.visible.len(), 1);

        let key = app.sessions[0].key();
        app.reveal(&key);
        assert_eq!(app.visible.len(), 2);
    }

    /// With a second user on screen, each user heads their own subtree and the
    /// repositories hang beneath them, railed like checkouts — so two people
    /// in the same repository are two headings, folded separately.
    #[test]
    fn a_second_user_adds_a_level_above_the_repositories() {
        let fx = Scratch::new("users");
        let (x, y) = (fx.repo("x"), fx.repo("y"));
        let mut app = test_app();
        app.tree = true;
        let mut ana_x = session("ana-x", true, &x);
        ana_x.owner = Some("ana".into());
        let mut ana_y = session("ana-y", true, &y);
        ana_y.owner = Some("ana".into());
        ana_y.last_active = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
        let mut mine = session("mine", true, &x);
        mine.last_active = (chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339();
        app.sessions = vec![ana_x, ana_y, mine];
        app.refilter();

        let groups = groups_of(&app);
        let users: Vec<&str> = groups
            .iter()
            .filter(|g| g.0 == 0)
            .map(|g| g.1.as_str())
            .collect();
        assert_eq!(
            users,
            ["ana", crate::config::MY_USER.as_str()],
            "{groups:?}"
        );
        assert_eq!(
            groups.iter().filter(|g| g.0 == 1).count(),
            3,
            "x and y under ana, x again under me: {groups:?}"
        );
        // ana's two repositories are railed as her children, their sessions
        // one level further in.
        let at = position(&app, "ana-x");
        assert_eq!(app.indent[at - 1], "├─ ");
        assert_eq!(app.indent[at], "│  └─ ");
        assert_eq!(app.indent[position(&app, "ana-y")], "   └─ ");

        // Folding ana's x leaves my x open: the keys are scoped per user.
        app.selected = at - 1;
        app.toggle_group();
        let _ = position(&app, "mine");
        assert!(
            app.visible.iter().all(|r| r.session() != Some(0)),
            "ana-x is folded away"
        );

        // A filter down to one user drops the level again.
        app.search = "user:ana".into();
        app.refilter();
        assert!(
            groups_of(&app).iter().all(|g| g.1 != "ana"),
            "{:?}",
            groups_of(&app)
        );
    }

    /// A relative directory must not be looked up against cctop's own working
    /// directory, which is itself a checkout when the tests run.
    #[test]
    fn a_relative_directory_is_its_own_group() {
        assert_eq!(locate(Path::new("src")), None);
        let s = session("a", false, "src");
        assert_eq!(place(&s).repo, "dir:src");
    }
}