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
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
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
//! Frame layout, drawing, and mouse hit-testing.

use super::columns::ColumnId;
use super::modals;
use super::spark;
use super::table;
use super::theme::{self, Gradient};
use super::{App, Mode, panels, tabs};
use crate::pricing::Provider;
use crate::session::Surface;
use crate::util;
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout as RLayout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Paragraph};

/// Screen regions recorded during a draw, so mouse events can be mapped back to
/// what was actually rendered rather than to a guessed layout.
#[derive(Debug, Default, Clone)]
pub struct Layout {
    pub(super) header_row: u16,
    pub(super) rows_start: u16,
    pub(super) rows_end: u16,
    pub(super) tab_row: u16,
    pub(super) bottom_start: u16,
    /// `(start_col, end_col, column)` spans in the table header.
    pub(super) column_spans: Vec<(u16, u16, ColumnId)>,
    /// `(start_col, end_col, tab_index)` spans in the bottom tab bar.
    pub(super) tab_spans: Vec<(u16, u16, usize)>,
    /// `(start_col, end_col, workspace_index)` spans in the top tab bar.
    pub(super) workspace_spans: Vec<(u16, u16, usize)>,
    /// `(start_col, end_col)` of the bar's new-tab button.
    pub(super) workspace_new: Option<(u16, u16)>,
    /// The rectangle a modal covers while one is up. A click inside it belongs
    /// to the modal, and a click outside it must not reach the dashboard the
    /// modal is sitting on top of.
    pub(super) modal_rect: Option<Rect>,
    /// `(row, choice_index)` for each row of the launcher's list.
    pub(super) launch_rows: Vec<(u16, usize)>,
    /// Tool Activity sidebar: `(x_end, y_start, first_index, row_count)`.
    pub(super) tool_sidebar: Option<(u16, u16, usize, usize)>,
    /// Tool Activity log area: `(x_start, y_start, height)`.
    pub(super) tool_log: Option<(u16, u16, u16)>,
    /// Where each pane of the open tab has its agent's screen, in pane order.
    ///
    /// The agent's screen, not the pane: the border is cctop's and the shim may
    /// have granted less room than the pane has, so this is the rectangle a
    /// mouse position can be turned into a cell of.
    pub(super) pane_rects: Vec<Rect>,
}

impl Layout {
    pub fn in_bottom_panel(&self, row: u16) -> bool {
        row >= self.bottom_start
    }

    pub fn row_at(&self, row: u16) -> Option<usize> {
        (row >= self.rows_start && row < self.rows_end).then(|| (row - self.rows_start) as usize)
    }

    pub fn header_column_at(&self, col: u16, row: u16) -> Option<ColumnId> {
        if row != self.header_row {
            return None;
        }
        self.column_spans
            .iter()
            .find(|(a, b, _)| col >= *a && col < *b)
            .map(|(_, _, id)| *id)
    }

    /// Index of the tool-filter row under the cursor, if any.
    pub fn tool_sidebar_at(&self, col: u16, row: u16) -> Option<usize> {
        let (x_end, y_start, first, count) = self.tool_sidebar?;
        if col >= x_end || row < y_start {
            return None;
        }
        let offset = (row - y_start) as usize;
        (offset < count).then_some(first + offset)
    }

    /// Line offset within the tool log under the cursor, before scrolling.
    pub fn tool_log_row_at(&self, col: u16, row: u16) -> Option<usize> {
        let (x_start, y_start, height) = self.tool_log?;
        if col < x_start || row < y_start || row >= y_start + height {
            return None;
        }
        Some((row - y_start) as usize)
    }

    pub fn tab_at(&self, col: u16, row: u16) -> Option<usize> {
        if row != self.tab_row {
            return None;
        }
        self.tab_spans
            .iter()
            .find(|(a, b, _)| col >= *a && col < *b)
            .map(|(_, _, i)| *i)
    }

    /// Index of the workspace tab under the cursor. The bar is always the top
    /// row when it is drawn at all.
    pub fn workspace_at(&self, col: u16, row: u16) -> Option<usize> {
        if row != 0 {
            return None;
        }
        self.workspace_spans
            .iter()
            .find(|(a, b, _)| col >= *a && col < *b)
            .map(|(_, _, i)| *i)
    }

    /// Whether the cursor is on the bar's new-tab button.
    pub fn workspace_new_at(&self, col: u16, row: u16) -> bool {
        matches!(self.workspace_new, Some((a, b)) if row == 0 && col >= a && col < b)
    }

    /// Whether the cursor is inside the modal that is up, if one is.
    pub fn in_modal(&self, col: u16, row: u16) -> bool {
        self.modal_rect
            .is_some_and(|r| r.contains((col, row).into()))
    }

    /// Index of the launcher choice under the cursor, if any.
    /// The pane under `(col, row)`, and where in its agent's screen that is.
    pub fn pane_at(&self, col: u16, row: u16) -> Option<(usize, u16, u16)> {
        self.pane_rects.iter().enumerate().find_map(|(i, r)| {
            (col >= r.x && col < r.right() && row >= r.y && row < r.bottom())
                .then(|| (i, col - r.x, row - r.y))
        })
    }

    pub fn launch_row_at(&self, col: u16, row: u16) -> Option<usize> {
        self.in_modal(col, row)
            .then(|| self.launch_rows.iter().find(|(y, _)| *y == row))
            .flatten()
            .map(|(_, i)| *i)
    }
}

pub(super) fn panel_block(title: &str) -> Block<'static> {
    Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme::BORDER))
        .title(Span::styled(format!(" {title} "), theme::title()))
}

pub fn draw(frame: &mut Frame, app: &mut App) -> Layout {
    let mut area = frame.area();
    let mut layout = Layout::default();

    // The bar is always there, even with only the dashboard in it: the way to
    // open an agent has to be visible before you have opened one, or nobody
    // finds it. One row is a cheap price for that.
    {
        let bar = Rect { height: 1, ..area };
        draw_workspace_bar(frame, bar, app, &mut layout);
        area = Rect {
            y: area.y + 1,
            height: area.height.saturating_sub(1),
            ..area
        };
    }

    // A tab's terminals replace the table and panels, and the Overview stays put
    // so the money and the alerts never leave the frame. Agents are resized to
    // the space that leaves them rather than cropped to fit, so giving cctop
    // these rows costs nothing but the rows.
    if app.tab > 0 {
        let chunks = RLayout::vertical([
            Constraint::Length(6),
            Constraint::Min(3),
            Constraint::Length(1),
        ])
        .split(area);
        draw_overview(frame, chunks[0], app);
        draw_panes(frame, chunks[1], app, &mut layout);
        draw_footer(frame, chunks[2], app);
        if app.mode == Mode::Launch {
            modals::draw_launch(frame, area, app, &mut layout);
        }
        return layout;
    }

    // Overview and limits are fixed; the table and bottom panel split the rest,
    // with the bottom panel capped so the list never collapses to nothing.
    let body_height = area.height.saturating_sub(5 + 3 + 1);
    let bottom_height = ((body_height as f32 * 0.45) as u16)
        .clamp(8, 24)
        .min(body_height.saturating_sub(4));

    let chunks = RLayout::vertical([
        // Four spend rows plus the border.
        Constraint::Length(6),
        Constraint::Min(4),
        Constraint::Length(bottom_height),
        Constraint::Length(3),
        Constraint::Length(1),
    ])
    .split(area);

    draw_overview(frame, chunks[0], app);
    table::draw_table(frame, chunks[1], app, &mut layout);
    draw_bottom(frame, chunks[2], app, &mut layout);
    draw_limits(frame, chunks[3], app);
    draw_footer(frame, chunks[4], app);

    match app.mode {
        Mode::Help => modals::draw_help(frame, area),
        Mode::Search => modals::draw_search(frame, area, app),
        Mode::SortBy => modals::draw_sortby(frame, area, app),
        Mode::AgeFilter => modals::draw_age_filter(frame, area, app),
        Mode::DeleteConfirm => modals::draw_delete_confirm(frame, area, app),
        Mode::DeleteBlocked => modals::draw_delete_blocked(frame, area, app),
        Mode::KillConfirm => modals::draw_kill_confirm(frame, area, app),
        Mode::ResumeConfirm => modals::draw_resume_confirm(frame, area, app),
        Mode::TmuxInstall => modals::draw_tmux_install(frame, area, app),
        Mode::QuitConfirm => modals::draw_quit_confirm(frame, area, app),
        Mode::KillBlocked => modals::draw_kill_blocked(frame, area, app),
        Mode::BatchConfirm => modals::draw_batch_confirm(frame, area, app),
        Mode::BatchDeleteBlocked => modals::draw_batch_blocked(frame, area, app, true),
        Mode::BatchKillBlocked => modals::draw_batch_blocked(frame, area, app, false),
        Mode::CostFilter => modals::draw_cost_filter(frame, area, app),
        Mode::SendKeys => modals::draw_send_keys(frame, area, app),
        Mode::Launch => modals::draw_launch(frame, area, app, &mut layout),
        Mode::Hooks => modals::draw_hooks(frame, area, app),
        Mode::List => {}
    }
    layout
}

/// The workspace tab bar: the dashboard first, then a tab per set of terminals.
fn draw_workspace_bar(frame: &mut Frame, area: Rect, app: &App, layout: &mut Layout) {
    let titles = std::iter::once("Dashboard".to_string()).chain(app.tabs.iter().map(|t| t.title()));
    let on = app.blink_on();
    let mut spans = Vec::new();
    let mut pos = area.x;
    for (i, title) in titles.enumerate() {
        let text = format!(" {}:{} ", i + 1, title);
        let width = text.chars().count() as u16;
        // A tab wanting something outranks the plain selected/unselected look:
        // the whole point of the colour is to be seen while you are reading a
        // different tab.
        let style = match app.tab_attention(i) {
            // Blinking by hand rather than with `Modifier::SLOW_BLINK`, which
            // many terminals quietly drop — an attention cue that only works on
            // some emulators is worse than none, because you stop trusting it.
            Some(what) => {
                let colour = match what {
                    tabs::Attention::NeedsInput => theme::COST_MID,
                    tabs::Attention::Idle => theme::COST_LOW,
                };
                match on {
                    true => Style::default()
                        .bg(colour)
                        .fg(Color::Black)
                        .add_modifier(Modifier::BOLD),
                    false => Style::default().fg(colour).add_modifier(Modifier::BOLD),
                }
            }
            None if i == app.tab => Style::default()
                .bg(theme::SELECTED_BG)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
            None => Style::default().fg(theme::DIM),
        };
        spans.push(Span::styled(text, style));
        layout.workspace_spans.push((pos, pos + width, i));
        pos += width;
    }

    // The button that says the feature exists. It carries its key as well as
    // its click target, because the keyboard is how anyone will use it twice.
    // Which key to name depends on where the keyboard is: inside a pane it
    // belongs to the agent, so only the Alt- form gets through.
    let new_tab = match app.tab {
        0 => " + Tab (t) ",
        _ => " + Tab (Alt+n) ",
    };
    let width = new_tab.chars().count() as u16;
    if pos + width <= area.x + area.width {
        spans.push(Span::styled(
            new_tab,
            Style::default()
                .fg(theme::ACCENT)
                .add_modifier(Modifier::BOLD),
        ));
        layout.workspace_new = Some((pos, pos + width));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// Every terminal in the active tab, sharing the space evenly.
///
/// Sizing is the part that already worked: each pane asks the shim for exactly
/// the rectangle it was given, so a split is two agents each drawing a real
/// screen rather than two crops of one.
fn draw_panes(frame: &mut Frame, area: Rect, app: &mut App, layout: &mut Layout) {
    let Some(tab) = app.active_tab() else {
        return;
    };
    if tab.panes.is_empty() {
        return;
    }
    let share = Constraint::Ratio(1, tab.panes.len() as u32);
    let slots = match tab.stacked {
        true => RLayout::vertical(vec![share; tab.panes.len()]),
        false => RLayout::horizontal(vec![share; tab.panes.len()]),
    }
    .split(area);

    let focus = tab.focus;
    for (i, pane) in tab.panes.iter_mut().enumerate() {
        let mut block = panel_block(&pane.label);
        if i == focus {
            block = block
                .border_style(Style::default().fg(theme::BORDER_HI))
                .title_bottom(Span::styled(" F12 back · Alt+w close ", theme::title()));
        }
        // Scrolled back, this pane is showing history rather than the agent, and
        // there is nothing on a still screen to say so — the agent may well be
        // working below it. Only cctop's own history says anything here: a pane
        // scrolled inside tmux is in tmux's copy-mode, which draws its own.
        let behind = pane.view.parser.screen().scrollback();
        if behind > 0 {
            block = block.title_bottom(
                Line::from(Span::styled(
                    format!("{behind} — type to catch up "),
                    theme::title(),
                ))
                .right_aligned(),
            );
        }
        let inner = block.inner(slots[i]);
        pane.view.resize(inner.width, inner.height);

        // The shim may grant less than was asked for — it has to satisfy every
        // watcher at once — so the answer, not the request, is what gets drawn,
        // and the leftover is left blank rather than stretched into.
        let (cols, rows) = pane.view.size;
        let screen = Rect {
            width: cols.min(inner.width),
            height: rows.min(inner.height),
            ..inner
        };
        frame.render_widget(block, slots[i]);
        frame.render_widget(
            tui_term::widget::PseudoTerminal::new(pane.view.parser.screen()),
            screen,
        );
        layout.pane_rects.push(screen);
    }
}

// ---------------------------------------------------------------------------
// Overview
// ---------------------------------------------------------------------------

fn draw_overview(frame: &mut Frame, area: Rect, app: &App) {
    let block = panel_block("Overview");
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let cols =
        RLayout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).split(inner);
    let (left, right) = (cols[0], cols[1]);

    let realtime = app.stats.spend_per_min;
    let label_w = 15usize;
    let value_w = 12usize;
    let chart_w = left.width.saturating_sub((label_w + value_w + 2) as u16) as usize;

    let row = |name: &str, amount: f64, series: &[f64], now_idx: Option<usize>| -> Line<'static> {
        let mut spans = vec![
            Span::styled(format!("{name:<label_w$}"), theme::label()),
            Span::styled(
                format!("{:>value_w$} ", util::adaptive_usd(amount)),
                Style::default()
                    .fg(Color::Indexed(221))
                    .add_modifier(Modifier::BOLD),
            ),
        ];
        spans.extend(spark::sparkline(series, chart_w, 0.0, Gradient::Spend, now_idx).spans);
        Line::from(spans)
    };

    let now = chrono::Local::now();
    let hour_idx = Some(chrono::Timelike::hour(&now) as usize);
    let day_idx = Some(chrono::Datelike::day(&now) as usize - 1);
    let rt_idx = app.global_spend.values().len().checked_sub(1);

    let left_lines = vec![
        row(
            "Live Spend/min",
            realtime,
            app.global_spend.values(),
            rt_idx,
        ),
        row(
            "Today Spend",
            app.stats.spend_today,
            &app.stats.daily_hourly,
            hour_idx,
        ),
        row(
            "Month-to-date",
            app.stats.spend_calendar_month,
            &app.stats.monthly_daily,
            day_idx,
        ),
        // Every session ever recorded, across every provider. Deliberately without
        // a sparkline: the others chart a window that scrolls, and a running total
        // only ever climbs, so a chart of it says nothing the number doesn't.
        Line::from(vec![
            Span::styled(format!("{:<label_w$}", "Total Spend"), theme::label()),
            Span::styled(
                format!("{:>value_w$}", util::adaptive_usd(app.stats.spend_total)),
                Style::default()
                    .fg(Color::Indexed(221))
                    .add_modifier(Modifier::BOLD),
            ),
        ]),
    ];
    frame.render_widget(Paragraph::new(left_lines), left);

    let mem_mb = app.stats.total_memory as f64 / (1024.0 * 1024.0);
    let r_label_w = 12usize;
    let r_value_w = 9usize;
    let r_chart_w = right
        .width
        .saturating_sub((r_label_w + r_value_w + 2) as u16) as usize;

    let mut cpu_spans = vec![
        Span::styled(format!("{:<r_label_w$}", "Agents CPU"), theme::label()),
        Span::styled(
            format!("{:>r_value_w$} ", format!("{:.1}%", app.stats.total_cpu)),
            theme::value(),
        ),
    ];
    cpu_spans.extend(
        spark::sparkline(
            app.global_cpu.values(),
            r_chart_w,
            100.0,
            Gradient::Cpu,
            app.global_cpu.values().len().checked_sub(1),
        )
        .spans,
    );

    let right_lines = vec![
        Line::from(cpu_spans),
        Line::from(vec![
            Span::styled(format!("{:<r_label_w$}", "Agents Mem"), theme::label()),
            Span::styled(
                format!("{:>r_value_w$}", format!("{mem_mb:.0} MB")),
                theme::value(),
            ),
        ]),
        Line::from(vec![
            Span::styled(format!("{:<r_label_w$}", "Sessions"), theme::label()),
            Span::styled(
                format!("{:>r_value_w$}", app.stats.total.to_string()),
                theme::value(),
            ),
            Span::raw("  "),
            Span::styled(
                format!("{} active", app.stats.running),
                Style::default().fg(theme::COST_LOW),
            ),
        ]),
    ];
    frame.render_widget(Paragraph::new(right_lines), right);
}

// ---------------------------------------------------------------------------
// Bottom panels
// ---------------------------------------------------------------------------

fn draw_bottom(frame: &mut Frame, area: Rect, app: &mut App, layout: &mut Layout) {
    app.ensure_available_tab();
    layout.bottom_start = area.y;
    layout.tab_row = area.y;
    layout.tool_sidebar = None;
    layout.tool_log = None;

    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme::BORDER));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Tab bar drawn on the top border line, htop-style.
    let mut spans = vec![Span::raw(" ")];
    let mut pos = area.x + 2;
    layout.tab_spans.clear();
    for (i, name) in panels::TABS.iter().enumerate() {
        if !app.tab_available(i) {
            continue;
        }
        let style = if i == app.bottom_tab {
            theme::title().add_modifier(Modifier::UNDERLINED)
        } else {
            theme::dim()
        };
        spans.push(Span::styled((*name).to_string(), style));
        spans.push(Span::raw("  "));
        let w = name.chars().count() as u16;
        layout.tab_spans.push((pos, pos + w, i));
        pos += w + 2;
    }
    // These panels describe the subagent, not the session it ran under, and the
    // two are a keystroke apart in the table. Naming it on the border is what
    // stops a subagent's small numbers from being read as its parent's.
    if let Some(sub) = app.selected_subagent() {
        let what = if sub.description.is_empty() {
            sub.agent_type.clone()
        } else {
            format!("{}: {}", sub.agent_type, sub.description)
        };
        spans.push(Span::styled(
            format!("{}", crate::util::truncate(&what, 48)),
            Style::default().fg(theme::ACCENT),
        ));
    }
    frame.render_widget(
        Paragraph::new(Line::from(spans)),
        Rect {
            x: area.x + 1,
            y: area.y,
            width: area.width.saturating_sub(2),
            height: 1,
        },
    );

    if app.selected_session().is_none() {
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                "No session selected",
                theme::dim(),
            ))),
            inner,
        );
        return;
    }

    // The Performance tab draws charts rather than text lines.
    if app.bottom_tab == 1 {
        if let Some(session) = app.selected_session() {
            draw_performance(frame, inner, session, &app.cpu_history, &app.mem_history);
        }
        return;
    }

    let mut tool_owners: Vec<Option<String>> = Vec::new();

    // Build the panel's lines under an immutable borrow, then release it before
    // touching the scroll state below. `Line<'static>` owns its text, so nothing
    // here keeps `app` borrowed — no per-frame clone of the session data needed.
    let (lines, scroll) = {
        let width = inner.width as usize;
        let Some(session) = app.selected_session() else {
            return;
        };
        let data = app.panel_data.as_ref();
        match app.bottom_tab {
            0 => (panels::info(session, data, app.plan), app.info_scroll),
            2 => (panels::processes(session, width), app.proc_scroll),
            3 => {
                let live = app.tool_live_only.then_some(app.started_at.as_str());
                match data {
                    Some(d) => {
                        let (lines, owners) =
                            draw_tool_sidebar(frame, inner, app, d, live, width, layout);
                        tool_owners = owners;
                        (lines, app.tool_scroll)
                    }
                    None => (vec![Line::from(Span::styled("Loading…", theme::dim()))], 0),
                }
            }
            4 => (
                panels::subagents(data, app.subagent_sort.0, app.subagent_sort.1, width),
                app.subagent_scroll,
            ),
            5 => (panels::cost(session, data, app.plan), app.cost_scroll),
            6 => (panels::config(session), app.config_scroll),
            _ => (panels::context(session, data, width), app.context_scroll),
        }
    };

    // The tool tab renders its own split; everything else fills the panel.
    let target = if app.bottom_tab == 3 {
        Rect {
            x: inner.x + TOOL_SIDEBAR_W + 1,
            width: inner.width.saturating_sub(TOOL_SIDEBAR_W + 1),
            ..inner
        }
    } else {
        inner
    };

    let max_scroll = (lines.len() as u16).saturating_sub(target.height);
    // Tool Activity follows its tail unless the user has scrolled away.
    let scroll = if app.bottom_tab == 3 {
        app.tool_owners = std::mem::take(&mut tool_owners);
        layout.tool_log = Some((target.x, target.y, target.height));
        app.tool_max_scroll = max_scroll;
        if app.tool_follow {
            app.tool_scroll = max_scroll;
        }
        app.tool_scroll.min(max_scroll)
    } else {
        scroll.min(max_scroll)
    };
    frame.render_widget(Paragraph::new(lines).scroll((scroll, 0)), target);
}

const TOOL_SIDEBAR_W: u16 = 18;

/// Draw the per-tool sidebar and return the invocation lines for the main area.
#[allow(clippy::too_many_arguments)]
fn draw_tool_sidebar(
    frame: &mut Frame,
    inner: Rect,
    app: &App,
    data: &crate::session::SessionData,
    live: Option<&str>,
    width: usize,
    layout: &mut Layout,
) -> (Vec<Line<'static>>, Vec<Option<String>>) {
    let tabs = panels::tool_tabs(data);
    // Keep the selected filter on screen when the list is longer than the panel.
    let first = app.tool_tab.saturating_sub(inner.height as usize / 2);
    let visible = tabs.len().saturating_sub(first).min(inner.height as usize);
    layout.tool_sidebar = Some((inner.x + TOOL_SIDEBAR_W, inner.y, first, visible));
    let lines: Vec<Line> = tabs
        .iter()
        .enumerate()
        .skip(first)
        .take(inner.height as usize)
        .map(|(i, (name, count))| {
            let selected = i == app.tool_tab;
            let display = util::pretty_mcp_name(name);
            let count_str = count.to_string();
            let name_w = (TOOL_SIDEBAR_W as usize).saturating_sub(count_str.len() + 2);
            Line::from(vec![
                Span::styled(
                    format!("{:<name_w$}", util::truncate(&display, name_w)),
                    if selected {
                        Style::default()
                            .fg(Color::White)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        theme::dim()
                    },
                ),
                Span::raw(" "),
                Span::styled(count_str, theme::dim()),
            ])
        })
        .collect();

    frame.render_widget(
        Paragraph::new(lines),
        Rect {
            width: TOOL_SIDEBAR_W,
            ..inner
        },
    );
    frame.render_widget(
        Paragraph::new(
            (0..inner.height)
                .map(|_| Line::from(Span::styled("", Style::default().fg(theme::DIMMER))))
                .collect::<Vec<_>>(),
        ),
        Rect {
            x: inner.x + TOOL_SIDEBAR_W,
            width: 1,
            ..inner
        },
    );

    panels::tool_activity(
        data,
        app.tool_tab,
        live,
        app.tool_show_diff,
        app.tool_expanded.as_deref(),
        width.saturating_sub(TOOL_SIDEBAR_W as usize + 1),
    )
}

fn draw_performance(
    frame: &mut Frame,
    inner: Rect,
    session: &crate::session::Session,
    cpu_history: &std::collections::HashMap<String, spark::History>,
    mem_history: &std::collections::HashMap<String, spark::History>,
) {
    if session.surface == Surface::DesktopCowork {
        frame.render_widget(
            Paragraph::new(vec![
                Line::from(Span::styled(
                    "Cowork sessions run in a cloud VM.",
                    theme::dim(),
                )),
                Line::from(Span::styled(
                    "No local CPU or memory metrics are available.",
                    theme::dim(),
                )),
            ]),
            inner,
        );
        return;
    }
    if session.surface == Surface::Editor && session.provider == Provider::Cursor {
        frame.render_widget(
            Paragraph::new(vec![
                Line::from(Span::styled(
                    "Cursor uses a shared editor process.",
                    theme::dim(),
                )),
                Line::from(Span::styled(
                    "No per-session CPU or memory metrics are available.",
                    theme::dim(),
                )),
            ]),
            inner,
        );
        return;
    }
    let Some(pm) = &session.process else {
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                "Performance data is only available for running sessions.",
                theme::dim(),
            ))),
            inner,
        );
        return;
    };

    let key = session.key();
    let empty = spark::History::default();
    let cpu = cpu_history.get(&key).unwrap_or(&empty);
    let mem = mem_history.get(&key).unwrap_or(&empty);
    let mem_mb = pm.memory as f64 / (1024.0 * 1024.0);
    let mem_max = util::nice_max(mem.values().iter().cloned().fold(1.0, f64::max));

    // A gutter keeps the CPU plot from butting against the memory axis labels.
    let cols = RLayout::horizontal([
        Constraint::Percentage(50),
        Constraint::Length(2),
        Constraint::Percentage(50),
    ])
    .split(inner);
    let (cpu_area, mem_area) = (cols[0], cols[2]);
    let rows = inner.height.saturating_sub(2).max(2) as usize;
    // A shared gutter keeps the two plots' data columns aligned.
    let axis_w = format!("{}", mem_max.ceil() as i64).len().max(3) + 2;

    let mut left = vec![Line::from(vec![
        Span::styled("CPU ", theme::label()),
        Span::styled(
            format!("{:>6.1}%", pm.cpu),
            Style::default().fg(theme::cpu_color(pm.cpu)),
        ),
        Span::raw("   "),
        Span::styled("PIDs ", theme::label()),
        Span::styled(pm.pids.to_string(), theme::value()),
    ])];
    left.extend(spark::line_chart(
        cpu.values(),
        cpu_area.width as usize,
        rows,
        100.0,
        Gradient::Cpu,
        Some(axis_w),
    ));

    let mut right = vec![Line::from(vec![
        Span::styled("Mem ", theme::label()),
        Span::styled(format!("{mem_mb:>8.0} MB"), theme::value()),
    ])];
    right.extend(spark::line_chart(
        mem.values(),
        mem_area.width as usize,
        rows,
        mem_max,
        Gradient::Accent,
        Some(axis_w),
    ));

    frame.render_widget(Paragraph::new(left), cpu_area);
    frame.render_widget(Paragraph::new(right), mem_area);
}

// ---------------------------------------------------------------------------
// Limits
// ---------------------------------------------------------------------------

/// Colour quota usage by whether it is being spent faster than an even budget
/// across its reset window. Falling back to absolute pressure keeps windows
/// useful when a provider omits either its reset time or duration.
fn quota_color(window: &crate::quota::Window, now: i64) -> Color {
    if let (Some(duration), Some(reset)) = (window.duration, window.resets_at) {
        let duration_secs = duration.as_secs() as i64;
        let elapsed_secs = (now - (reset - duration_secs)).clamp(1, duration_secs);
        let pace_ratio = window.pct as f64 * duration_secs as f64 / (100.0 * elapsed_secs as f64);

        // A small overspend is worth noticing, while 50% above the sustainable
        // rate should be unmistakable. For a 7d window the sustainable rate is
        // 100 / (7 * 24), or roughly 0.6 percentage points per hour.
        if pace_ratio >= 1.5 {
            return theme::COST_HIGH;
        }
        if pace_ratio >= 1.1 {
            return theme::COST_MID;
        }
        return theme::COST_LOW;
    }

    if window.pct >= 90 {
        theme::COST_HIGH
    } else if window.pct >= 70 {
        theme::COST_MID
    } else {
        theme::COST_LOW
    }
}

fn draw_limits(frame: &mut Frame, area: Rect, app: &App) {
    let block = panel_block("Limits");
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let cols =
        RLayout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).split(inner);

    for (i, (name, status)) in [("Claude", &app.quota.claude), ("Codex", &app.quota.codex)]
        .iter()
        .enumerate()
    {
        let mut spans = vec![Span::styled(format!("{name} "), theme::label())];
        // Each failure mode gets its own message: an expired sign-in needs the
        // user to act, a rate-limit clears on its own, and "not signed in" is
        // neither. One catch-all string would hide all of that.
        match status {
            crate::quota::ProviderStatus::Pending => {
                spans.push(Span::styled("checking…", theme::dim()));
            }
            crate::quota::ProviderStatus::NotSignedIn => {
                spans.push(Span::styled("not signed in", theme::dim()));
            }
            crate::quota::ProviderStatus::ApiBilling => {
                spans.push(Span::styled("API billing, no limits", theme::dim()));
            }
            crate::quota::ProviderStatus::Expired => {
                let cmd = if *name == "Codex" {
                    "codex login"
                } else {
                    "claude login"
                };
                spans.push(Span::styled(
                    "sign-in expired — ",
                    Style::default().fg(theme::COST_MID),
                ));
                spans.push(Span::styled(cmd.to_string(), theme::value()));
            }
            crate::quota::ProviderStatus::RateLimited { retry_at } => {
                spans.push(Span::styled(
                    "rate limited",
                    Style::default().fg(theme::COST_MID),
                ));
                if let Some(at) = retry_at {
                    let remaining = at - chrono::Utc::now().timestamp();
                    if remaining > 0 {
                        spans.push(Span::styled(
                            format!(" — retry in {}m{:02}s", remaining / 60, remaining % 60),
                            theme::dim(),
                        ));
                    }
                }
            }
            crate::quota::ProviderStatus::Unavailable(reason) => {
                spans.push(Span::styled(
                    format!("unavailable ({reason})"),
                    theme::dim(),
                ));
            }
            crate::quota::ProviderStatus::Ok(q) => {
                let now = chrono::Utc::now().timestamp();
                if let Some(plan) = &q.plan {
                    spans.push(Span::styled(format!("({plan}) "), theme::dim()));
                }
                for w in &q.windows {
                    let color = quota_color(w, now);
                    spans.push(Span::styled(format!("{} ", w.label), theme::label()));
                    spans.push(Span::styled(
                        format!("{:>3}% ", w.pct),
                        Style::default().fg(color),
                    ));
                    let filled = (w.pct as usize * 8 / 100).min(8);
                    spans.push(Span::styled(
                        "\u{2501}".repeat(filled),
                        Style::default().fg(color),
                    ));
                    spans.push(Span::styled(
                        "\u{2500}".repeat(8 - filled),
                        Style::default().fg(Color::Indexed(244)),
                    ));
                    if let Some(reset) = w.resets_at {
                        let remaining = reset - now;
                        if remaining > 0 {
                            spans.push(Span::styled(
                                format!(" {}h{:02}m", remaining / 3600, (remaining % 3600) / 60),
                                theme::dim(),
                            ));
                        }
                    }
                    spans.push(Span::raw("  "));
                }
                if q.limit_reached {
                    spans.push(Span::styled(
                        "\u{26a0} limit",
                        Style::default().fg(theme::COST_HIGH),
                    ));
                }
            }
        }
        frame.render_widget(Paragraph::new(Line::from(spans)), cols[i]);
    }
}

// ---------------------------------------------------------------------------
// Footer
// ---------------------------------------------------------------------------

fn draw_footer(frame: &mut Frame, area: Rect, app: &App) {
    if let Some((msg, _)) = &app.status {
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                msg.clone(),
                Style::default().fg(theme::COST_LOW),
            ))),
            area,
        );
        return;
    }

    let key_style = Style::default()
        .fg(Color::Black)
        .bg(theme::ACCENT)
        .add_modifier(Modifier::BOLD);
    let label_style = Style::default().fg(theme::DIM);

    let mut spans = Vec::new();
    for (key, name) in [
        ("F1", "Help"),
        ("F3", "Filter"),
        ("F5", "Refresh"),
        ("F7", "Age"),
        ("←→", "Panel"),
        ("Space", "Mark"),
        ("D", "Batch"),
        ("y", "Copy"),
        ("d", "Delete"),
        ("k", "Kill"),
        ("+/-", "Speed"),
        ("F10", "Quit"),
    ] {
        spans.push(Span::styled(key, key_style));
        spans.push(Span::styled(format!("{name} "), label_style));
    }
    if let Some(age) = app.age_filter {
        spans.push(Span::styled(
            format!(" Age<{} ", age.short()),
            Style::default().fg(theme::PANEL_TITLE),
        ));
    }
    if !app.search.is_empty() {
        // The filter stays on the footer once the modal closes, so it has to
        // say whether transcripts are in scope — the two searches can return
        // very different tables for the same word.
        let scope = match (app.search_content, app.scanning) {
            (false, _) => String::new(),
            (true, true) => " +transcripts…".to_string(),
            (true, false) => format!(" +transcripts({})", app.scan_hits.len()),
        };
        spans.push(Span::styled(
            format!(" Filter: {}{scope} ", app.search),
            Style::default().fg(Color::Cyan),
        ));
    }
    if app.cost_floor > 0.0 {
        spans.push(Span::styled(
            format!(" ≥${:.2} ", app.cost_floor),
            Style::default().fg(theme::COST_HIGH),
        ));
    }
    if !app.marked.is_empty() {
        spans.push(Span::styled(
            format!(" [{} marked] ", app.marked.len()),
            Style::default()
                .fg(theme::ACCENT)
                .add_modifier(Modifier::BOLD),
        ));
    }
    spans.push(Span::styled(
        format!(" {}s ", app.refresh_secs),
        Style::default().fg(theme::DIMMER),
    ));
    if app.follow {
        spans.push(Span::styled(
            " FOLLOW ",
            Style::default().fg(theme::COST_MID),
        ));
    }
    // Who rang, kept there until you are looking at them. A bell you heard from
    // the next room has to still be answerable when you come back.
    if let Some(bell) = app
        .notify
        .footer(app.selected_session().map(|s| s.key()).as_deref())
    {
        spans.push(Span::styled(
            format!(" {bell} "),
            Style::default()
                .fg(theme::ACCENT)
                .add_modifier(Modifier::BOLD),
        ));
    }
    // Last, so it never pushes a key hint off the end of a narrow footer.
    if let Some(version) = &app.update_available {
        spans.push(Span::styled(
            format!(" v{version} available — cctop --update "),
            Style::default()
                .fg(theme::COST_MID)
                .add_modifier(Modifier::BOLD),
        ));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// Copy text via a platform helper, falling back to the OSC 52 escape sequence.
///
/// OSC 52 works over SSH and inside multiplexers where no local clipboard tool
/// exists, so it's the last resort rather than the first choice.
pub fn copy_to_clipboard(text: &str) {
    use std::io::Write;
    use std::process::{Command, Stdio};

    const HELPERS: &[(&str, &[&str])] = &[
        ("wl-copy", &[]),
        ("xclip", &["-selection", "clipboard"]),
        ("xsel", &["--clipboard", "--input"]),
        ("pbcopy", &[]),
        ("clip.exe", &[]),
    ];

    for (cmd, args) in HELPERS {
        let Ok(mut child) = Command::new(cmd)
            .args(*args)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
        else {
            continue;
        };
        if let Some(stdin) = child.stdin.as_mut()
            && stdin.write_all(text.as_bytes()).is_ok()
        {
            drop(child.stdin.take());
            if child.wait().map(|s| s.success()).unwrap_or(false) {
                return;
            }
        }
    }

    let mut out = std::io::stdout();
    let _ = write!(out, "\x1b]52;c;{}\x07", util::b64_encode(text.as_bytes()));
    let _ = out.flush();
}

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

    #[test]
    fn hit_testing_maps_regions() {
        let layout = Layout {
            workspace_spans: vec![(0, 12, 0)],
            workspace_new: Some((12, 23)),
            header_row: 6,
            rows_start: 7,
            rows_end: 12,
            tab_row: 20,
            bottom_start: 20,
            column_spans: vec![(0, 5, ColumnId::Status), (5, 12, ColumnId::Cost)],
            tab_spans: vec![(2, 6, 0), (8, 19, 1)],
            tool_sidebar: Some((18, 21, 0, 3)),
            tool_log: Some((19, 21, 4)),
            modal_rect: Some(Rect::new(10, 8, 20, 6)),
            launch_rows: vec![(10, 0), (11, 1)],
            pane_rects: vec![Rect::new(1, 7, 40, 10)],
        };
        // A modal takes the clicks that land on it, and its rows resolve to the
        // choice on them — not to the table underneath, which shares those rows.
        assert_eq!(layout.launch_row_at(15, 11), Some(1));
        assert_eq!(layout.launch_row_at(15, 12), None);
        // Same row, but outside the modal: still not a choice.
        assert_eq!(layout.launch_row_at(5, 11), None);
        assert!(layout.in_modal(10, 8));
        assert!(!layout.in_modal(30, 8));
        // The bar's tabs and its new-tab button are separate targets, and both
        // only exist on the top row.
        assert_eq!(layout.workspace_at(3, 0), Some(0));
        assert_eq!(layout.workspace_at(15, 0), None);
        assert!(layout.workspace_new_at(15, 0));
        assert!(!layout.workspace_new_at(3, 0));
        assert!(!layout.workspace_new_at(15, 1));
        assert_eq!(layout.row_at(7), Some(0));
        assert_eq!(layout.row_at(11), Some(4));
        assert_eq!(layout.row_at(12), None);
        assert_eq!(layout.header_column_at(6, 6), Some(ColumnId::Cost));
        assert_eq!(layout.header_column_at(6, 7), None);
        assert_eq!(layout.tab_at(9, 20), Some(1));
        assert_eq!(layout.tab_at(9, 21), None);
        assert!(layout.in_bottom_panel(20));
        assert!(!layout.in_bottom_panel(19));
        // A pane resolves to the cell of the agent's own screen under the
        // pointer, so the agent is told where the wheel is, not where cctop
        // happens to have drawn it.
        assert_eq!(layout.pane_at(1, 7), Some((0, 0, 0)));
        assert_eq!(layout.pane_at(10, 9), Some((0, 9, 2)));
        assert_eq!(layout.pane_at(41, 9), None);
        assert_eq!(layout.pane_at(10, 17), None);
        // Sidebar clicks map to a tool filter; clicks past its right edge don't.
        assert_eq!(layout.tool_sidebar_at(4, 22), Some(1));
        assert_eq!(layout.tool_sidebar_at(4, 24), None);
        assert_eq!(layout.tool_sidebar_at(40, 22), None);
        // Log clicks resolve to a line offset; the sidebar column is excluded.
        assert_eq!(layout.tool_log_row_at(30, 21), Some(0));
        assert_eq!(layout.tool_log_row_at(30, 24), Some(3));
        assert_eq!(layout.tool_log_row_at(30, 25), None);
        assert_eq!(layout.tool_log_row_at(5, 22), None);
    }

    #[test]
    fn quota_colour_tracks_spending_pace() {
        let duration = std::time::Duration::from_secs(7 * 24 * 60 * 60);
        let reset = 1_000_000;
        let window = crate::quota::Window {
            label: "7d",
            pct: 80,
            duration: Some(duration),
            // 80% used halfway through a seven-day window is well ahead of
            // the even 100/(7*24) percentage-points-per-hour pace.
            resets_at: Some(reset + duration.as_secs() as i64 / 2),
        };
        assert_eq!(quota_color(&window, reset), theme::COST_HIGH);

        let sustainable = crate::quota::Window {
            pct: 50,
            resets_at: Some(reset + duration.as_secs() as i64 / 2),
            ..window
        };
        assert_eq!(quota_color(&sustainable, reset), theme::COST_LOW);
    }

    /// A test agent that draws `text` once and then sits there, so anything on
    /// screen came from the replay and anything that moves came from a resize.
    ///
    /// Linux-only for the same reason as the shim's own tests — it needs a pty
    /// child, which hangs on the macOS runner.
    #[cfg(target_os = "linux")]
    fn test_pane(text: &str) -> (std::process::Child, u32, super::super::tabs::Pane) {
        let (child, pid) = crate::shim::test_session(
            &["sh", "-c", &format!("printf '{text}'; sleep 30")],
            // Wider and taller than any window below, so a crop would show.
            (200, 60),
        );
        let pane =
            super::super::tabs::Pane::view_of(pid, text.into()).expect("no attach connection");
        (child, pid, pane)
    }

    /// Draw until every pane has been granted the size it asked for. The resize
    /// is requested while drawing and answered a round trip later, so drawing
    /// once is never enough.
    #[cfg(target_os = "linux")]
    fn draw_until_sized(
        terminal: &mut ratatui::Terminal<ratatui::backend::TestBackend>,
        app: &mut App,
        want: &[(u16, u16)],
    ) -> bool {
        for _ in 0..50 {
            terminal
                .draw(|frame| {
                    draw(frame, app);
                })
                .expect("draw");
            let sized = app.tabs.iter_mut().any(|tab| {
                tab.pump();
                tab.panes.len() == want.len()
                    && tab.panes.iter().zip(want).all(|(p, w)| p.view.size == *w)
            });
            if sized {
                // One more frame, so what is asserted was drawn at the final size.
                terminal
                    .draw(|frame| {
                        draw(frame, app);
                    })
                    .expect("draw");
                return true;
            }
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        false
    }

    /// The way in has to be on screen before anyone has used it: with no tabs
    /// open the bar still names the dashboard and offers the new-tab button, and
    /// clicking that button is what `t` does.
    #[test]
    fn the_bar_offers_a_new_tab_with_nothing_open() {
        use crate::cache::UiPrefs;
        use crate::pricing::Plan;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let (tx, _rx) = std::sync::mpsc::channel();
        let mut app = App::with_prefs(Plan::Retail, tx, UiPrefs::default());
        let (cols, rows) = (80u16, 24u16);
        let mut terminal = Terminal::new(TestBackend::new(cols, rows)).expect("backend");
        let mut layout = Layout::default();
        terminal
            .draw(|frame| layout = draw(frame, &mut app))
            .expect("draw");

        let buffer = terminal.backend().buffer().clone();
        let top: String = (0..cols).map(|x| buffer[(x, 0)].symbol()).collect();
        assert!(
            top.starts_with(" 1:Dashboard  + Tab (t) "),
            "the new-tab button is not on the bar: {top:?}"
        );
        let (a, _) = layout.workspace_new.expect("no new-tab hit region");
        assert!(layout.workspace_new_at(a, 0));
        assert!(!layout.workspace_new_at(a, 1));
    }

    #[cfg(target_os = "linux")]
    fn screen(
        terminal: &ratatui::Terminal<ratatui::backend::TestBackend>,
        cols: u16,
        rows: u16,
    ) -> Vec<String> {
        let buffer = terminal.backend().buffer().clone();
        (0..rows)
            .map(|y| {
                (0..cols)
                    .map(|x| buffer[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect()
    }

    /// A tab keeps you inside cctop: the tab bar, the Overview and the footer
    /// stay, and the agent is resized into what is left rather than cropped.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_tab_resizes_its_agent_into_the_space_cctop_leaves_it() {
        use crate::cache::UiPrefs;
        use crate::pricing::Plan;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let (mut child, pid, pane) = test_pane("HELLO-FROM-AGENT");
        let (tx, _rx) = std::sync::mpsc::channel();
        let mut app = App::with_prefs(Plan::Retail, tx, UiPrefs::default());
        app.tabs.push(super::super::tabs::Tab::new(pane));
        app.tab = 1;

        let (cols, rows) = (60u16, 21u16);
        // One row of tab bar, six of Overview, one of footer, and a border.
        let want = (cols - 2, rows - 1 - 6 - 1 - 2);
        let mut terminal = Terminal::new(TestBackend::new(cols, rows)).expect("backend");
        let sized = draw_until_sized(&mut terminal, &mut app, &[want]);
        let screen = screen(&terminal, cols, rows);

        app.tabs.clear();
        let _ = child.kill();
        let _ = child.wait();
        let _ = crate::shim::socket_path(pid).map(std::fs::remove_file);

        assert!(
            sized,
            "the pty was never resized to the pane; wanted {want:?}"
        );
        assert!(
            screen[0].starts_with(" 1:Dashboard  2:HELLO-FROM-AGENT"),
            "the tab bar is not the top row: {:?}",
            screen[0]
        );
        assert!(
            screen[1].contains("Overview"),
            "the Overview is gone: {:?}",
            screen[1]
        );
        assert!(
            screen[8].starts_with("│HELLO-FROM-AGENT"),
            "the agent's screen is not inside the pane: {:?}",
            &screen[7..10]
        );
        assert!(
            screen[rows as usize - 2].contains("F12 back"),
            "the focused pane's hint is missing: {:?}",
            screen[rows as usize - 2]
        );
    }

    /// A split gives each agent a real screen of its own, not two crops of one:
    /// both are resized to their half and both draw in it.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_split_sizes_both_agents_to_their_own_half() {
        use crate::cache::UiPrefs;
        use crate::pricing::Plan;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let (mut left_child, left_pid, left) = test_pane("LEFT-AGENT");
        let (mut right_child, right_pid, right) = test_pane("RIGHT-AGENT");
        let (tx, _rx) = std::sync::mpsc::channel();
        let mut app = App::with_prefs(Plan::Retail, tx, UiPrefs::default());
        let mut tab = super::super::tabs::Tab::new(left);
        tab.panes.push(right);
        app.tabs.push(tab);
        app.tab = 1;

        let (cols, rows) = (80u16, 21u16);
        // Half the width each, minus each pane's own left and right border.
        let want = (cols / 2 - 2, rows - 1 - 6 - 1 - 2);
        let mut terminal = Terminal::new(TestBackend::new(cols, rows)).expect("backend");
        let sized = draw_until_sized(&mut terminal, &mut app, &[want, want]);
        let screen = screen(&terminal, cols, rows);

        app.tabs.clear();
        for child in [&mut left_child, &mut right_child] {
            let _ = child.kill();
            let _ = child.wait();
        }
        for pid in [left_pid, right_pid] {
            let _ = crate::shim::socket_path(pid).map(std::fs::remove_file);
        }

        assert!(
            sized,
            "one of the split panes was never resized; wanted {want:?} each"
        );
        // Both agents on one row, each starting just inside its own border.
        let split_row = &screen[8];
        assert!(
            split_row.starts_with("│LEFT-AGENT"),
            "the left agent is not in the left half: {split_row:?}"
        );
        // By character, not by byte: the borders are multi-byte.
        let right_half: String = split_row.chars().skip((cols / 2) as usize).collect();
        assert!(
            right_half.starts_with("│RIGHT-AGENT"),
            "the right agent is not in the right half: {split_row:?}"
        );
    }
}