cctop 0.2.0

An htop-like terminal monitor for AI coding agent sessions (Claude Code, Codex, Cursor, 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
//! Modal overlays: help, filters, and the confirmation dialogs.

use super::columns::COLUMNS;
use super::theme;
use super::{AGE_OPTIONS, App, BatchKind, LaunchInto, session_root_pid, tabs};
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Clear, Paragraph, Wrap};

// ---------------------------------------------------------------------------
// Modals
// ---------------------------------------------------------------------------

/// A centred rectangle of the given size, clamped to the screen.
fn centered(area: Rect, width: u16, height: u16) -> Rect {
    let w = width.min(area.width.saturating_sub(2));
    let h = height.min(area.height.saturating_sub(2));
    Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    }
}

/// Draws the overlay and returns `(outer, inner)`: the frame it covers, which is
/// what tells a click inside the modal from one meant for what it hides, and the
/// text area, whose rows are the lines that were passed in.
fn modal(
    frame: &mut Frame,
    area: Rect,
    title: &str,
    lines: Vec<Line<'static>>,
    width: u16,
) -> (Rect, Rect) {
    let height = lines.len() as u16 + 2;
    let rect = centered(area, width, height);
    frame.render_widget(Clear, rect);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme::BORDER_HI))
        .title(Span::styled(format!(" {title} "), theme::title()));
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
    (rect, inner)
}

pub(super) fn draw_help(frame: &mut Frame, area: Rect) {
    let section = |t: &str| Line::from(Span::styled(t.to_string(), theme::title()));
    let item = |k: &str, d: &str| {
        Line::from(vec![
            Span::styled(format!("  {k:<16}"), Style::default().fg(theme::ACCENT)),
            Span::raw(d.to_string()),
        ])
    };
    let lines = vec![
        section("Navigation"),
        item("↑  ↓/j", "Move between sessions"),
        item("PgUp / PgDn", "Page through the list"),
        item("Ctrl+U / Ctrl+D", "Half a page up / down"),
        item("g / G", "Jump to first / last"),
        item("Home / End", "Jump to first / last"),
        item("n / N", "Next / previous search match (wraps)"),
        item("b", "Jump to the session that rang last"),
        Line::default(),
        section("Panels"),
        item("←  →", "Move between bottom panels"),
        item("Tab / Shift+Tab", "Same, either direction"),
        item("1 – 7", "Jump to a panel directly"),
        item("Shift+↑ / ↓", "Scroll inside the active panel"),
        item("f", "Follow mode: keep the selection centered"),
        item("L", "Toggle the Tool Activity live filter"),
        item("v", "Toggle inline diffs for edits"),
        Line::default(),
        section("Filter and sort"),
        item("/ or F3", "Filter by label, project, branch, model, id"),
        item("  Tab", "Search inside the transcripts as well"),
        item("  ↑ / ↓", "Bring back an earlier search"),
        item("F6  >  <", "Open the sort-by panel"),
        item("F7", "Filter by age (1d / 1w / 1mo)"),
        item("#", "Cost floor: only sessions costing ≥ $X"),
        item("`", "Show only running sessions"),
        item("P / M / T", "Sort by status / memory / cost"),
        item("H / X / S", "Sort by harness / context / tools"),
        item("+ / - / =", "Speed up / slow down / reset refresh"),
        item("Esc", "Clear the active filter"),
        Line::default(),
        section("Batch actions"),
        item("Space", "Mark / unmark the selected session"),
        item("D", "Delete all marked sessions"),
        item("K", "Terminate all marked live sessions"),
        item("U", "Clear all marks"),
        Line::default(),
        section("Other"),
        item("w", "Bell + desktop alert when a session needs you"),
        item("y", "Copy resume command or transcript path"),
        item("d", "Delete the selected session (not running)"),
        item("k", "Terminate the selected live session"),
        item("s", "Type a line into the session's terminal"),
        item("R", "Resume the session in a tab of its own"),
        item("O", "Hand the session's context off to a different agent"),
        item("a", "Open the session's terminal in a tab"),
        item("A", "Open the agent this cctop launched"),
        item("h or F8", "Agent integration: what reports to cctop"),
        item("r or F5", "Refresh now"),
        item("q or F10", "Quit"),
        Line::default(),
        section("Tabs and splits"),
        item(
            "t or Alt+n",
            "New tab: an agent, a shell, or one still running",
        ),
        item("Alt+v / Alt+s", "Split the tab right / down"),
        item("Alt+← / →", "Previous / next tab"),
        item("Alt+1 – 9", "Jump to a tab (1 is the dashboard)"),
        item("Alt+o", "Move focus to the next pane"),
        item("Alt+w", "Close the pane; a tmux-backed agent keeps running"),
        item("Alt+W", "Stop the focused pane's agent for good"),
        item("F12", "Back to the dashboard, leaving it running"),
        Line::default(),
        Line::from(Span::styled(
            "  Costs are estimates from published per-token rates. Flat-rate plans",
            theme::dim(),
        )),
        Line::from(Span::styled(
            "  (Max, Pro, Team) bill differently, so these may not match your invoice.",
            theme::dim(),
        )),
        Line::default(),
        Line::from(Span::styled("  Press any key to return", theme::dim())),
    ];
    modal(frame, area, "Help", lines, 76);
}

pub(super) fn draw_search(frame: &mut Frame, area: Rect, app: &App) {
    const WIDTH: u16 = 62;
    let text_w = WIDTH as usize - 4;

    let mut lines = vec![
        Line::from(vec![
            Span::raw(" > "),
            Span::styled(
                app.search.clone(),
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("", Style::default().fg(theme::ACCENT)),
        ]),
        Line::from(Span::styled(
            format!(
                " {} of {} session{}",
                app.visible.len(),
                app.sessions.len(),
                if app.sessions.len() == 1 { "" } else { "s" }
            ),
            theme::dim(),
        )),
    ];

    // What is actually being searched, and whether the answer on screen is
    // final. A scan is the one filter here that takes long enough to see, so
    // saying nothing would read as "no transcript matches" while it runs.
    let (marker, style, text) = match (app.search_content, app.scanning) {
        (false, _) => (
            "",
            theme::dim(),
            "Columns only — Tab also searches transcripts".to_string(),
        ),
        (true, true) => (
            "",
            Style::default().fg(theme::ACCENT),
            "Searching transcripts…".to_string(),
        ),
        (true, false) => (
            "",
            Style::default().fg(theme::COST_LOW),
            match app.scan_hits.len() {
                0 if app.search.chars().count() < 3 => {
                    "Transcripts: type three characters".to_string()
                }
                0 => "Transcripts: no matches".to_string(),
                n => format!("Transcripts: {n} matched"),
            },
        ),
    };
    lines.push(Line::from(vec![
        Span::styled(format!(" {marker} "), style),
        Span::styled(crate::util::truncate(&text, text_w), style),
    ]));

    // The matching line from the selected session's transcript. Without it a
    // content hit is a row that matches for reasons nothing on screen explains.
    if let Some(snippet) = app.selected_snippet() {
        lines.push(Line::from(Span::styled(
            // Less the three-space indent: the paragraph wraps, and a snippet
            // spilling onto a second line resizes the modal as you type.
            format!("   {}", crate::util::truncate(snippet, text_w - 3)),
            theme::value(),
        )));
    }

    lines.push(Line::from(Span::styled(
        if app.search_history.is_empty() {
            " Enter apply   Esc cancel"
        } else {
            " Enter apply   ↑/↓ past searches   Esc cancel"
        },
        theme::dim(),
    )));
    modal(frame, area, "Filter sessions", lines, WIDTH);
}

/// Resuming a session that is already running somewhere else.
pub(super) fn draw_resume_confirm(frame: &mut Frame, area: Rect, app: &App) {
    let Some(session) = app.selected_session() else {
        return;
    };
    let command = session
        .resume_argv()
        .map(|argv| argv.join(" "))
        .unwrap_or_default();
    // `modal` sizes the box by line count and the paragraph wraps, so a line
    // long enough to wrap pushes the last one out of the border. Every line
    // here is kept inside the 60 columns the box has room for.
    let lines = vec![
        Line::from(Span::styled(
            format!(
                " {} is still running.",
                crate::util::truncate(session.display_label(), 40)
            ),
            Style::default().fg(theme::COST_MID),
        )),
        Line::default(),
        Line::from(Span::raw(
            " Resuming starts a second agent on the same transcript,",
        )),
        Line::from(Span::raw(" which neither of them will know about.")),
        Line::default(),
        Line::from(Span::styled(
            format!("   {}", crate::util::truncate(&command, 56)),
            theme::value(),
        )),
        Line::default(),
        Line::from(Span::styled(
            " y to resume anyway · any other key to cancel",
            theme::dim(),
        )),
    ];
    modal(frame, area, "Resume a running session?", lines, 62);
}

/// Offering to install tmux, which is what would have made the agent about to
/// start outlive cctop.
pub(super) fn draw_tmux_install(frame: &mut Frame, area: Rect, app: &App) {
    let Some(install) = app.tmux_install.as_ref() else {
        return;
    };
    let command = install.shown();
    let sudo = command.starts_with("sudo ");
    let mut lines = vec![
        Line::from(Span::styled(
            " tmux is not installed.",
            Style::default().fg(theme::COST_MID),
        )),
        Line::default(),
        Line::from(Span::raw(
            " With it, agents run inside tmux and survive cctop",
        )),
        Line::from(Span::raw(
            " closing. Without it, quitting takes them with it.",
        )),
        Line::default(),
        Line::from(Span::styled(
            format!("   {}", crate::util::truncate(command, 56)),
            theme::value(),
        )),
    ];
    if sudo {
        lines.push(Line::default());
        lines.push(Line::from(Span::styled(
            " Runs in a tab, so sudo can ask you for a password.",
            theme::dim(),
        )));
    }
    lines.push(Line::default());
    lines.push(Line::from(Span::styled(
        " y to install · any other key to start without it",
        theme::dim(),
    )));
    // The manager goes in the title rather than the footer: naming it inline
    // takes that line past the 60 columns the box has, and a footer that wraps
    // pushes itself out through the bottom border.
    modal(
        frame,
        area,
        &format!("Install tmux with {}?", install.manager),
        lines,
        62,
    );
}

pub(super) fn draw_sortby(frame: &mut Frame, area: Rect, app: &App) {
    let mut lines: Vec<Line> = COLUMNS
        .iter()
        .enumerate()
        .map(|(i, c)| {
            let active = c.id == app.sort_col;
            let arrow = if active {
                if app.sort_asc { "" } else { "" }
            } else {
                ""
            };
            let text = format!(" {}{}", c.label.trim(), arrow);
            let style = if i == app.sortby_cursor {
                Style::default()
                    .bg(theme::SELECTED_BG)
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else if active {
                Style::default().fg(theme::ACCENT)
            } else {
                Style::default()
            };
            Line::from(Span::styled(format!("{text:<26}"), style))
        })
        .collect();
    // Explain the highlighted column, since several are non-obvious ($/1H, CTX%).
    lines.push(Line::default());
    for part in COLUMNS[app.sortby_cursor].desc.lines() {
        lines.push(Line::from(Span::styled(format!(" {part}"), theme::dim())));
    }
    lines.push(Line::default());
    lines.push(Line::from(Span::styled(
        " Enter select   Esc cancel",
        theme::dim(),
    )));
    modal(frame, area, "Sort by", lines, 54);
}

pub(super) fn draw_age_filter(frame: &mut Frame, area: Rect, app: &App) {
    let mut lines: Vec<Line> = AGE_OPTIONS
        .iter()
        .enumerate()
        .map(|(i, opt)| {
            let active = *opt == app.age_filter;
            let marker = if active { "" } else { "" };
            let text = opt.map(|o| o.label()).unwrap_or("No filter");
            let style = if i == app.age_cursor {
                Style::default()
                    .bg(theme::SELECTED_BG)
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };
            Line::from(vec![
                Span::styled(
                    format!(" {marker} "),
                    Style::default().fg(if active {
                        theme::COST_LOW
                    } else {
                        theme::DIMMER
                    }),
                ),
                Span::styled(format!("{text:<22}"), style),
            ])
        })
        .collect();
    lines.push(Line::from(Span::styled(
        " ↑/↓  Enter apply  Esc cancel",
        theme::dim(),
    )));
    modal(frame, area, "Show sessions active within", lines, 34);
}

/// The launcher: what to put in the tab, and where it will run.
pub(super) fn draw_launch(
    frame: &mut Frame,
    area: Rect,
    app: &App,
    layout: &mut super::render::Layout,
) {
    const WIDTH: u16 = 62;
    /// Room for the name, then where it is working, then what it is doing. The
    /// three together are what tells one `claude` from another `claude`.
    const NAME: usize = 24;
    const WHERE: usize = 20;
    const STATE: usize = 12;
    /// The lines held below the list: where it will run, and the keys.
    const FOOTER: usize = 2;

    let choices = app.launch_choices();
    let waiting = choices
        .iter()
        .filter(|c| matches!(c, tabs::Choice::Waiting(_)))
        .count();

    // Abbreviated together rather than each truncated, because the column exists
    // to tell two agents apart and the identifying part of a path is its tail.
    // This keeps whatever is needed to make each one unique and drops the rest:
    // one agent in ~/cctop reads `cctop`, and two in ~/a/api and ~/b/api read
    // `a/api` and `b/api` instead of the same elided prefix twice.
    let dirs: Vec<String> = choices
        .iter()
        .filter_map(|c| c.cwd())
        .map(|d| d.to_string_lossy().into_owned())
        .collect();
    let mut short = crate::util::abbreviate_paths(&dirs).into_iter();

    // The list on its own, kept apart from the two lines under it: it is the
    // part that scrolls, and they are the part that must stay on screen.
    let mut rows: Vec<Line> = Vec::new();
    // Which line each choice ends up on, so a click can be turned back into the
    // choice it landed on rather than into whatever the modal is covering.
    let mut choice_lines: Vec<usize> = Vec::new();
    for (i, choice) in choices.iter().enumerate() {
        // A heading above each group, so a still-running agent is never picked
        // in the belief that it starts a fresh one.
        if i == 0 && waiting > 0 {
            rows.push(Line::from(Span::styled(" Still running", theme::label())));
        }
        if i == waiting && waiting > 0 {
            rows.push(Line::from(Span::styled(" Start new", theme::label())));
        }
        let selected = i == app.launch_cursor;
        let style = if selected {
            Style::default()
                .bg(theme::SELECTED_BG)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };

        // What the agent last said about itself, which is the whole reason to
        // list it: an agent stuck on a question is the one to go back to, and it
        // looks exactly like an idle one from a list of names.
        let reported = match choice {
            tabs::Choice::Waiting(agent) => app.waiting_state(agent),
            tabs::Choice::Start(_) => None,
        };
        // The dot carries whether anyone is already looking, the word carries
        // what the agent said about itself. Two facts that can both be true at
        // once, so neither is made to wait for the other's column.
        let dot = match choice {
            // Ringed: a client is on this session already. Attaching a second
            // works, but the two then fight over one window's size.
            tabs::Choice::Waiting(agent) if agent.attached => "",
            tabs::Choice::Waiting(_) => "",
            tabs::Choice::Start(_) => " ",
        };
        let dot_color = match (choice, reported) {
            (tabs::Choice::Waiting(_), Some(signal)) => theme::signal_color(signal),
            // Running, but it has never reported: no hooks installed, or nothing
            // has happened since cctop started listening. Still a live agent, so
            // it keeps a dot — just one that claims nothing.
            (tabs::Choice::Waiting(_), None) => theme::DIM,
            (tabs::Choice::Start(_), _) => theme::DIMMER,
        };

        let state = match reported {
            Some(signal) => signal.label().to_string(),
            None => String::new(),
        };
        let state_color = match reported {
            Some(signal) => theme::signal_color(signal),
            None => theme::DIM,
        };

        // Drawn from the same iterator the abbreviation was built from, so the
        // paths stay lined up with the choices that have one.
        let at = match choice.cwd().is_some() {
            true => short.next().unwrap_or_default(),
            false => String::new(),
        };

        // The session's own title where cctop knows it. A resumed session's tmux
        // name carries the whole session id, which for Codex is a timestamp and a
        // uuid — two of those are identical for far more characters than this
        // column is wide, so the names alone would draw two rows that read the
        // same and do different things.
        let name = match choice {
            tabs::Choice::Waiting(agent) => app.waiting_label(agent),
            tabs::Choice::Start(_) => None,
        }
        .unwrap_or_else(|| choice.label());

        choice_lines.push(rows.len());
        rows.push(Line::from(vec![
            Span::styled(format!(" {dot} "), Style::default().fg(dot_color)),
            Span::styled(
                format!("{:<NAME$}", crate::util::truncate(&name, NAME)),
                style,
            ),
            Span::styled(
                format!("{:<WHERE$}", crate::util::truncate(&at, WHERE - 1)),
                theme::dim(),
            ),
            Span::styled(
                format!("{:<STATE$}", crate::util::truncate(&state, STATE)),
                Style::default().fg(state_color),
            ),
        ]));
    }

    // The list scrolls rather than being cut off. `modal` sizes itself to its
    // lines and `centered` then clamps that to the screen, so on a short
    // terminal a long list loses its last rows silently — including, once the
    // cursor walks into them, the highlight itself: nothing on screen would say
    // what Enter is about to do.
    //
    // Two lines are held back for the footer below, which is where the working
    // directory is stated; scrolling that off would answer "in which project?"
    // with silence for exactly the launches that need asking about.
    // Two for the borders, two more for what `centered` will not give.
    let room = (area.height as usize).saturating_sub(4 + FOOTER).max(1);
    let total = rows.len();
    let scrolled = total > room;
    let cursor_line = choice_lines.get(app.launch_cursor).copied().unwrap_or(0);
    let offset = match scrolled {
        // Keep the cursor in view, and never scroll past the final row.
        true => cursor_line.saturating_sub(room - 1).min(total - room),
        false => 0,
    };
    let shown = room.min(total - offset);
    let mut lines: Vec<Line> = rows.into_iter().skip(offset).take(shown).collect();

    // Where it starts is not a detail: a claude opened on the wrong project
    // reads its way into the wrong repository before you notice. It says
    // nothing about reattaching, which lands wherever the agent already is.
    let picked = choices.get(app.launch_cursor);
    let picked_waiting = matches!(picked, Some(tabs::Choice::Waiting(_)));
    lines.push(Line::from(Span::styled(
        match (picked, &app.launch_cwd) {
            // The ring is the only unexplained mark on the row, and it is the one
            // worth explaining: it is the difference between coming back to an
            // agent and joining someone else on it.
            (Some(tabs::Choice::Waiting(agent)), _) if agent.attached => {
                " ◉ already open elsewhere — both windows share one size".to_string()
            }
            (Some(tabs::Choice::Waiting(_)), _) => " where it already is".to_string(),
            (_, Some(dir)) => format!(
                " in {}",
                crate::util::truncate(
                    &crate::util::tildify(&dir.to_string_lossy()),
                    WIDTH as usize - 6
                )
            ),
            (_, None) => " in this directory".to_string(),
        },
        Style::default().fg(theme::LABEL),
    )));
    let keys = match picked_waiting {
        true => " ↑/↓  Enter reattach  Esc cancel",
        false => " ↑/↓  Enter start  Esc cancel",
    };
    lines.push(Line::from(Span::styled(
        // A scrolled list has to say so, or the choices above and below the
        // window are simply missing as far as anyone can tell.
        match scrolled {
            true => format!("{keys}   {} of {}", app.launch_cursor + 1, choices.len()),
            false => keys.to_string(),
        },
        theme::dim(),
    )));
    // A handoff opens the same launcher for a different reason, and the picked
    // agent is about to be typed at rather than just started — which is worth
    // saying before Enter, not after.
    let title = match (app.pending_brief.is_some(), app.launch_into) {
        (true, _) => "Hand the context to",
        (false, LaunchInto::Tab) => "New tab",
        (false, LaunchInto::Split { stacked: false }) => "Split right",
        (false, LaunchInto::Split { stacked: true }) => "Split down",
    };
    let (outer, inner) = modal(frame, area, title, lines, WIDTH);
    layout.modal_rect = Some(outer);
    layout.launch_rows = choice_lines
        .into_iter()
        .enumerate()
        .filter_map(|(i, line)| {
            // Scrolled out above, or below the window: no row to click. The
            // indices stay attached to their choices either way, so a click
            // still resolves to what is drawn on that row and not to whatever
            // choice happens to sit that far down the list.
            let drawn = line.checked_sub(offset).filter(|d| *d < shown)?;
            let row = inner.y + drawn as u16;
            (row < inner.y + inner.height).then_some((row, i))
        })
        .collect();
}

/// What the agents have been asked to report, and whether they are doing it.
///
/// The panel exists because every part of this is invisible otherwise: a hook
/// that is not installed, or is installed at a path that has moved, looks
/// exactly like an agent that has nothing to say.
pub(super) fn draw_hooks(frame: &mut Frame, area: Rect, app: &App) {
    let Some(report) = &app.hooks else { return };
    const WIDTH: u16 = 78;
    // Two for the border, one for the marker and the space after it.
    let text_w = WIDTH as usize - 5;

    let mut lines: Vec<Line> = Vec::new();
    for (text, problem) in report.lines() {
        let (marker, style) = match problem {
            true => ("! ", Style::default().fg(theme::COST_MID)),
            false => ("· ", theme::value()),
        };
        lines.push(Line::from(vec![
            Span::styled(format!(" {marker}"), style),
            Span::styled(crate::util::truncate(&text, text_w), style),
        ]));
    }

    // What has actually arrived, which is the only proof any of the above is
    // working. An install can be perfect and still deliver nothing, because
    // sessions started before it keep the hooks they were started with.
    lines.push(Line::default());
    let reporting = app.reporting();
    if reporting.is_empty() {
        lines.push(Line::from(Span::styled(
            " Nothing has reported in yet",
            theme::dim(),
        )));
    } else {
        lines.push(Line::from(Span::styled(" Reporting", theme::label())));
        for (project, state) in reporting.iter().take(6) {
            lines.push(Line::from(vec![
                Span::styled(
                    format!("   {:<24}", crate::util::truncate(project, 24)),
                    theme::value(),
                ),
                Span::styled(*state, theme::dim()),
            ]));
        }
        if reporting.len() > 6 {
            lines.push(Line::from(Span::styled(
                format!("   … and {} more", reporting.len() - 6),
                theme::dim(),
            )));
        }
    }

    lines.push(Line::default());
    // The project keys name the directory they would write into: a settings
    // file committed to somebody's repository is not a thing to install by
    // accident.
    lines.push(Line::from(Span::styled(
        match app.hook_project() {
            Some(dir) => format!(
                " p / P  install / remove in {}",
                crate::util::truncate(&dir.display().to_string(), text_w.saturating_sub(30))
            ),
            None => " p / P  install / remove for the selected project".into(),
        },
        theme::dim(),
    )));
    lines.push(Line::from(Span::styled(
        " i / x  install / remove for this user (every agent above)",
        theme::dim(),
    )));
    lines.push(Line::from(Span::styled(
        " Esc    close   ·   sessions already running keep their old hooks",
        theme::dim(),
    )));

    modal(frame, area, "Agent integration", lines, WIDTH);
}

pub(super) fn draw_delete_confirm(frame: &mut Frame, area: Rect, app: &App) {
    let Some(s) = app.selected_session() else {
        return;
    };
    let lines = vec![
        Line::from(Span::styled(
            format!("  {}", s.display_label()),
            theme::value(),
        )),
        Line::from(Span::styled(format!("  {}", s.session_id), theme::dim())),
        Line::default(),
        Line::from(Span::styled(
            "  This permanently removes the transcript from disk.",
            Style::default().fg(theme::COST_MID),
        )),
        Line::default(),
        Line::from(Span::styled(
            "  [y] delete    [n / Esc] cancel",
            theme::dim(),
        )),
    ];
    modal(frame, area, "Delete session?", lines, 62);
}

pub(super) fn draw_delete_blocked(frame: &mut Frame, area: Rect, app: &App) {
    let Some(s) = app.selected_session() else {
        return;
    };
    let lines = vec![
        Line::from(Span::styled(
            format!("  {}", s.display_label()),
            theme::value(),
        )),
        Line::default(),
        Line::from(Span::raw("  This session is still running.")),
        Line::from(Span::raw("  Stop the agent first, then delete it.")),
        Line::default(),
        Line::from(Span::styled("  [any key] dismiss", theme::dim())),
    ];
    modal(frame, area, "Cannot delete", lines, 62);
}

pub(super) fn draw_kill_confirm(frame: &mut Frame, area: Rect, app: &App) {
    let Some(s) = app.selected_session() else {
        return;
    };
    let lines = vec![
        Line::from(Span::styled(
            format!("  {}", s.display_label()),
            theme::value(),
        )),
        Line::from(Span::styled(format!("  {}", s.session_id), theme::dim())),
        Line::default(),
        Line::from(Span::styled(
            "  Send a termination signal to this agent process?",
            Style::default().fg(theme::COST_MID),
        )),
        Line::from(Span::raw("  Unsaved work in the agent may be interrupted.")),
        Line::default(),
        Line::from(Span::styled(
            "  [y] terminate    [n / Esc] cancel",
            theme::dim(),
        )),
    ];
    modal(frame, area, "Terminate session?", lines, 62);
}

pub(super) fn draw_quit_confirm(frame: &mut Frame, area: Rect, app: &App) {
    let label = match &app.hosted {
        Some((_, label)) => label.clone(),
        None => return,
    };
    let lines = vec![
        Line::from(Span::styled(format!("  {label}"), theme::value())),
        Line::default(),
        Line::from(Span::styled(
            "  This agent is running on a terminal cctop owns,",
            Style::default().fg(theme::COST_MID),
        )),
        Line::from(Span::styled(
            "  and quitting ends it.",
            Style::default().fg(theme::COST_MID),
        )),
        Line::from(Span::raw("  Exit the agent itself to leave it cleanly.")),
        Line::default(),
        Line::from(Span::styled(
            "  [y] quit anyway    [n / Esc] stay    [A] back to the agent",
            theme::dim(),
        )),
    ];
    modal(frame, area, "Quit and stop the agent?", lines, 62);
}

pub(super) fn draw_kill_blocked(frame: &mut Frame, area: Rect, app: &App) {
    let Some(s) = app.selected_session() else {
        return;
    };
    let lines = vec![
        Line::from(Span::styled(
            format!("  {}", s.display_label()),
            theme::value(),
        )),
        Line::default(),
        Line::from(Span::raw(
            "  This session has no locally controllable process.",
        )),
        Line::from(Span::raw("  It may be running in a remote or shared host.")),
        Line::default(),
        Line::from(Span::styled("  [any key] dismiss", theme::dim())),
    ];
    modal(frame, area, "Cannot terminate", lines, 62);
}

pub(super) fn draw_batch_confirm(frame: &mut Frame, area: Rect, app: &App) {
    let ms = app.marked_sessions();
    let (verb, noun) = match app.batch {
        BatchKind::Delete => ("delete", "sessions"),
        BatchKind::Kill => ("terminate", "live sessions"),
    };
    let mut lines = vec![
        Line::from(Span::styled(
            format!("  {} marked {noun}", ms.len()),
            theme::value(),
        )),
        Line::default(),
    ];
    for s in ms.iter().take(8) {
        lines.push(Line::from(Span::styled(
            format!("    · {}", s.display_label()),
            theme::dim(),
        )));
    }
    if ms.len() > 8 {
        lines.push(Line::from(Span::styled(
            format!("    … and {} more", ms.len() - 8),
            theme::dim(),
        )));
    }
    lines.push(Line::default());
    lines.push(Line::from(Span::styled(
        match app.batch {
            BatchKind::Delete => "  This permanently removes their transcripts from disk.",
            BatchKind::Kill => "  Unsaved work in the agents may be interrupted.",
        },
        Style::default().fg(theme::COST_MID),
    )));
    lines.push(Line::default());
    lines.push(Line::from(Span::styled(
        format!("  [y] {verb} all    [n / Esc] cancel"),
        theme::dim(),
    )));
    modal(frame, area, &format!("{verb} all?"), lines, 62);
}

pub(super) fn draw_batch_blocked(frame: &mut Frame, area: Rect, app: &App, deleting: bool) {
    let ms = app.marked_sessions();
    // First one that can't be processed, for the explanation.
    let (explain, name) = match app.batch {
        BatchKind::Delete => (
            "running — stop the agent first",
            ms.iter().find(|s| s.is_running()),
        ),
        BatchKind::Kill => (
            "has no locally controllable process",
            ms.iter().find(|s| session_root_pid(s).is_none()),
        ),
    };
    let lines = vec![
        Line::from(Span::styled(
            format!("  {} marked sessions", ms.len()),
            theme::value(),
        )),
        Line::default(),
        Line::from(Span::raw(format!(
            "  Not all can be {}.",
            if deleting { "deleted" } else { "killed" }
        ))),
        match name {
            Some(s) => Line::from(Span::styled(
                format!("  · {} {}", s.display_label(), explain),
                theme::dim(),
            )),
            None => Line::from(Span::raw("  At least one is not ready.")),
        },
        Line::default(),
        Line::from(Span::styled(
            "  e.g. unmark the running / remote sessions first.",
            theme::dim(),
        )),
        Line::default(),
        Line::from(Span::styled("  [any key] dismiss", theme::dim())),
    ];
    let title = if deleting {
        "Cannot delete all"
    } else {
        "Cannot terminate all"
    };
    modal(frame, area, title, lines, 62);
}

pub(super) fn draw_cost_filter(frame: &mut Frame, area: Rect, app: &App) {
    let mut input = app.cost_input.clone();
    if input.is_empty() {
        input = "0.00".to_string();
    }
    let lines = vec![
        Line::from(Span::styled(
            " Only show sessions whose total cost is at least:",
            theme::dim(),
        )),
        Line::from(vec![
            Span::raw(" $ "),
            Span::styled(
                input,
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("", Style::default().fg(theme::ACCENT)),
        ]),
        Line::default(),
        Line::from(Span::styled(
            " 0 clears the filter   Enter apply   Esc cancel",
            theme::dim(),
        )),
    ];
    modal(frame, area, "Cost floor", lines, 50);
}

pub(super) fn draw_send_keys(frame: &mut Frame, area: Rect, app: &App) {
    let Some(s) = app.selected_session() else {
        return;
    };
    let lines = vec![
        Line::from(Span::styled(
            format!(" {}", s.display_label()),
            theme::value(),
        )),
        Line::from(Span::styled(
            " Typed into the terminal running this agent, then submitted.",
            theme::dim(),
        )),
        Line::from(Span::styled(
            " Needs the agent under `cctop run`, tmux, or cctop as root.",
            theme::dim(),
        )),
        Line::default(),
        Line::from(vec![
            Span::raw(" > "),
            Span::styled(
                app.send_input.clone(),
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("", Style::default().fg(theme::ACCENT)),
        ]),
        Line::default(),
        Line::from(Span::styled(" Enter send   Esc cancel", theme::dim())),
    ];
    modal(frame, area, "Send to session", lines, 64);
}

// ---------------------------------------------------------------------------
// Clipboard
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn centered_rect_never_exceeds_screen() {
        let area = Rect {
            x: 0,
            y: 0,
            width: 20,
            height: 10,
        };
        let r = centered(area, 100, 100);
        assert!(r.width <= area.width && r.height <= area.height);
        assert!(r.x + r.width <= area.width);
    }
}