adk-surface 3.0.0

Agent surfaces for ADK-Rust: one engine that turns a kernel's sessions, decisions and activity into plain words for every surface, and the surfaces that show them
Documentation
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
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
//! Drawing the terminal (spec 3.3 §5.2, §7.1, §9): the full-screen layout, and the lines the
//! inline UI prints. Every on-screen word comes from the engine's projection (§8); every string
//! a model, a tool or a file wrote passes through [`terminal_safe`](super::terminal_safe).

use std::collections::HashMap;
use std::ops::Range;
use std::time::Instant;

use chrono::{Local, Timelike};
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Position, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use serde_json::Value;
use unicode_width::UnicodeWidthStr;

use super::app::{App, BoxView, DecidedLine, Input, OpenCard, Tone, View, named_decisions};
use super::commands::{BUILT_IN, Completion, ON_YOUR_SCREENS};
use super::markdown::{markdown, wrap, wrap_spans};
use super::safe::{safe_line, safe_lines};
use super::theme::Theme;
use crate::model::{AgentStatus, DecidedAnswer, FeedEntry, Mode, Pill, Speaker, ThreadItem};
use crate::rules::Answer;
use crate::words;

/// How many argument rows a decision shows before `?` must show the whole call.
const COMPACT_ROWS: usize = 10;

/// How long a call's arguments may be, as JSON, before `?` must show the whole call.
const COMPACT_CHARS: usize = 600;

/// The widest a decision box is drawn.
const BOX_WIDTH: usize = 110;

/// The fewest rows a decision box is fitted to, whatever follows it.
const MIN_BOX_ROWS: usize = 8;

/// The words of the §7.1 "Details" part, on the `?` key.
const DETAILS: &str = "Details";

/// The key that opens a decision's image in the home (spec 3.7 §8.2).
const OPEN_IMAGE: &str = "open image";

/// How many rendered agent messages the cache keeps before it starts again.
const MARKDOWN_CACHE: usize = 512;

/// How many of a run's last lines the terminal shows under it.
const RUN_TAIL: usize = 6;

/// What marks a line break inside a one-line view of model or tool text, so a multi-line
/// value never reads as one line (§7.1 "the exact call").
const NEWLINE_MARK: &str = "⏎";

/// The most commands the completion shows at once.
const COMPLETION_ROWS: usize = 6;

/// How wide the name column of `/help` is.
const HELP_KEYS: usize = 16;

/// Whether a decision's call is too long for the box: it must be shown in full with `?`
/// before it can be approved (spec 3.3 §7.1).
pub(crate) fn needs_details(open: &OpenCard) -> bool {
    let call = &open.card.call;
    call.truncated
        || call.args.to_string().chars().count() > COMPACT_CHARS
        || call.args.as_object().is_some_and(|map| map.len() > COMPACT_ROWS)
}

/// The key that gives `answer` (spec 3.3 §5.2).
pub(crate) fn key_of(answer: Answer) -> char {
    match answer {
        Answer::AllowOnce => 'y',
        Answer::AlwaysAllow => 'a',
        Answer::Edit => 'e',
        Answer::Deny => 'n',
    }
}

/// Draws the terminal, caching what is costly to lay out.
pub(crate) struct Renderer {
    pub theme: Theme,
    /// Rendered agent messages by entry, item and width, with the text each was rendered
    /// from: an entry number is a place in one session's store, so another session's entry,
    /// or a rewound one, under the same number is rendered again.
    markdown: HashMap<(u64, usize, usize), (String, Vec<Line<'static>>)>,
    /// How far the view other than the thread drawn last can scroll.
    pub view_max_scroll: usize,
    /// The rows of one page of that view: all but the last, which says how much more there is.
    pub view_page: usize,
    /// The drawings of the thread drawn last: which version of each is live, and each sent
    /// form's state (spec 3.3 §7.4 rule 5).
    pub(crate) drawings: super::drawn::Drawings,
    /// The web home's address, which a decision with images links to (spec 3.7 §8.2).
    pub home: Option<String>,
}

/// One row of a decision box: its spans and its background.
type Row = (Vec<Span<'static>>, Style);

/// How a decision box is fitted to the screen (spec 3.3 §7.1).
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Fit {
    /// The most rows the box may take, its keys included; `None` draws it whole.
    pub rows: Option<usize>,
    /// The first row of the call shown, when the call shows a window at a time.
    pub scroll: usize,
    /// PageUp and PageDown move the window (the full screen); otherwise `?` shows the rest.
    pub scrolls: bool,
}

/// A decision box as drawn: its lines, and which rows of its call they show.
pub(crate) struct DrawnBox {
    pub lines: Vec<Line<'static>>,
    /// How many rows the call has, or its details while `?` shows them.
    pub body_len: usize,
    /// The rows of the call drawn, counted from its first.
    pub body_shown: Range<usize>,
}

/// The box the keys answer, as laid out in the thread: its rows, and which rows of its call
/// they show.
pub(crate) struct FocusedBox {
    pub rows: Range<usize>,
    pub body_len: usize,
    pub body_shown: Range<usize>,
}

impl Renderer {
    pub(crate) fn new(theme: Theme) -> Self {
        Self {
            theme,
            markdown: HashMap::new(),
            view_max_scroll: 0,
            view_page: 1,
            drawings: super::drawn::Drawings::default(),
            home: None,
        }
    }

    // -----------------------------------------------------------------------
    // The status line and the footer
    // -----------------------------------------------------------------------

    pub(crate) fn status_line(&self, app: &App) -> Line<'static> {
        let t = &self.theme;
        let mut spans = vec![Span::styled(
            format!(" {} ", app.app_name),
            t.text().add_modifier(Modifier::BOLD),
        )];
        let part = |spans: &mut Vec<Span<'static>>, text: String, style: Style| {
            spans.push(Span::raw("  "));
            spans.push(Span::styled(text, style));
        };
        if let Some(place) = &app.place {
            part(&mut spans, place.clone(), t.label());
        }
        if let Some(agent) = app.shown_agent() {
            part(&mut spans, safe_line(&agent.agent.display_name), t.text());
        }
        if let Some(status) = &app.status {
            if let Some(mode) = &status.mode {
                part(&mut spans, mode.label.clone(), t.text());
            }
            if let Some(model) = &app.model {
                part(&mut spans, safe_line(model), t.secondary());
            }
            if let Some(spend) = &status.spend {
                part(&mut spans, spend.text.clone(), t.text());
            }
            if let Some(quiet) = &status.quiet {
                part(&mut spans, quiet.text.clone(), t.label());
            }
        } else if let Some(model) = &app.model {
            part(&mut spans, safe_line(model), t.secondary());
        }
        // Never fewer than the decisions on screen, which the status line may not count yet.
        let counted = app.status.as_ref().map_or(0, |status| status.decisions as usize);
        let decisions = counted.max(app.cards.len());
        spans.push(Span::raw("  "));
        // The filled badge marks decisions that wait, and only those (§9).
        if decisions > 0 {
            spans.push(Span::styled(words::DECISIONS, t.accent().add_modifier(Modifier::BOLD)));
            spans.push(Span::raw(" "));
            spans.push(Span::styled(format!(" {decisions} "), t.badge()));
        } else {
            spans.push(Span::styled(words::DECISIONS, t.label()));
        }
        if let Some(stopped) = app.status.as_ref().and_then(|status| status.stopped_text.as_ref()) {
            part(
                &mut spans,
                stopped.clone(),
                t.fg(t.palette().failed).add_modifier(Modifier::BOLD),
            );
        }
        Line::from(spans)
    }

    pub(crate) fn footer(&self) -> Line<'static> {
        let t = &self.theme;
        let mut hints = vec![
            ("tab", "next agent"),
            ("ctrl-g", "agents"),
            ("ctrl-t", "today"),
            ("ctrl-r", "permissions"),
            ("/", "commands"),
            ("ctrl-k", "stop all"),
            ("esc", "never decides"),
        ];
        // A form an agent drew is filled in with ctrl-f (spec 3.3 §5.2, wave 4 decision 19).
        if cfg!(feature = "genui") {
            hints.insert(1, ("ctrl-f", "fill in"));
        }
        let mut spans = vec![Span::raw(" ")];
        for (key, what) in hints {
            spans.push(Span::styled(key, t.text().add_modifier(Modifier::BOLD)));
            spans.push(Span::styled(format!(" {what}   "), t.label()));
        }
        Line::from(spans)
    }

    // -----------------------------------------------------------------------
    // The left column
    // -----------------------------------------------------------------------

    fn status_style(&self, status: AgentStatus) -> (char, Style) {
        let t = &self.theme;
        let p = t.palette();
        match status {
            AgentStatus::Working => ('●', t.fg(p.working)),
            AgentStatus::WaitingForYou => ('◆', t.accent()),
            AgentStatus::Asleep => ('○', t.label()),
            AgentStatus::Done => ('✓', t.fg(p.done)),
            AgentStatus::Failed => ('✗', t.fg(p.failed)),
            // Agents a person added (spec 3.3 §5.7).
            AgentStatus::Ready => ('○', t.label()),
            AgentStatus::Paused => ('‖', t.label()),
            AgentStatus::CantStart => ('✗', t.fg(p.failed)),
        }
    }

    pub(crate) fn left(&self, app: &App, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let inner = width.saturating_sub(2);
        let mut lines = vec![Line::default()];
        lines.push(Line::from(vec![Span::raw(" "), Span::styled("Agents", t.heading())]));
        // The person's agents sit under their area when the kernel has more than one (spec
        // 3.3 §5.7 "The roster"); the engine lists them in that order.
        let mut areas: Vec<&str> = app
            .agents
            .iter()
            .filter(|row| row.added)
            .filter_map(|row| row.area.as_deref())
            .collect();
        areas.dedup();
        let grouped = areas.len() > 1;
        let mut area_shown: Option<&str> = None;
        for row in &app.agents {
            if grouped
                && row.added
                && let Some(area) = row.area.as_deref()
                && area_shown != Some(area)
            {
                area_shown = Some(area);
                lines.push(Line::from(vec![
                    Span::raw(" "),
                    Span::styled(fit(&safe_line(area), inner.saturating_sub(1)), t.label()),
                ]));
            }
            let (glyph, style) = self.status_style(row.status);
            let selected = row.session_id.as_deref() == Some(app.session.as_str());
            let name = safe_line(&row.agent.display_name);
            let status = row.status_text.clone();
            let room = inner.saturating_sub(status.width() + 3);
            let name = fit(&name, room);
            let gap = inner.saturating_sub(2 + name.width() + status.width());
            let name_style = if selected { t.accent() } else { t.text() };
            let mut line = Line::from(vec![
                Span::raw(" "),
                Span::styled(glyph.to_string(), style),
                Span::raw(" "),
                Span::styled(name, name_style),
                Span::raw(" ".repeat(gap)),
                Span::styled(status, style),
                Span::raw(" "),
            ]);
            if selected {
                line = line.style(Style::new().bg(t.color(t.palette().decision_strong)));
            }
            lines.push(line);
        }
        // "Removed agents" at the roster's foot: Ctrl-G lists them, and their threads stay
        // readable (spec 3.3 §5.7).
        if !app.removed.is_empty() {
            let count = app.removed.len().to_string();
            let room = inner.saturating_sub(count.width() + 2);
            let label = fit(words::REMOVED_AGENTS, room);
            let gap = inner.saturating_sub(1 + label.width() + count.width());
            lines.push(Line::from(vec![
                Span::raw(" "),
                Span::styled(label, t.label()),
                Span::raw(" ".repeat(gap)),
                Span::styled(count, t.label()),
            ]));
        }
        lines.push(Line::default());
        lines.push(Line::from(vec![Span::raw(" "), Span::styled("Coming up", t.heading())]));
        let mut upcoming: Vec<_> =
            app.agents.iter().filter_map(|row| row.wake_at.map(|at| (at, row))).collect();
        upcoming.sort_by_key(|(at, _)| *at);
        if upcoming.is_empty() {
            lines.push(Line::from(vec![Span::raw(" "), Span::styled("—", t.label())]));
        }
        for (at, row) in upcoming {
            let local = at.with_timezone(&Local);
            lines.push(Line::from(vec![
                Span::raw(" "),
                Span::styled(format!("{:02}:{:02}", local.hour(), local.minute()), t.text()),
                Span::raw(" "),
                Span::styled(
                    fit(&safe_line(&row.agent.display_name), inner.saturating_sub(7)),
                    t.text(),
                ),
            ]));
        }
        lines.push(Line::default());
        let title = app
            .briefing
            .as_ref()
            .map_or(words::WHILE_YOU_WERE_AWAY.to_string(), |briefing| briefing.title.clone());
        lines.push(Line::from(vec![Span::raw(" "), Span::styled(title, t.heading())]));
        if let Some(briefing) = &app.briefing {
            let mut counts: Vec<(Pill, String, usize)> = Vec::new();
            for line in &briefing.lines {
                if let (Some(pill), Some(text)) = (line.pill, &line.pill_text) {
                    match counts.iter_mut().find(|(p, _, _)| *p == pill) {
                        Some(entry) => entry.2 += 1,
                        None => counts.push((pill, text.clone(), 1)),
                    }
                }
            }
            let mut parts: Vec<Span<'static>> = Vec::new();
            for (pill, text, count) in counts {
                if !parts.is_empty() {
                    parts.push(Span::styled(" · ", t.label()));
                }
                parts.push(Span::styled(format!("{text} {count}"), self.pill_style(pill)));
            }
            if !parts.is_empty() {
                let mut spans = vec![Span::raw(" ")];
                spans.extend(parts);
                lines.extend(wrap_spans(spans, inner, 1));
            }
            let mut tail = vec![Span::raw(" ")];
            if let Some(spend) = &briefing.spend {
                tail.push(Span::styled(spend.text.clone(), t.text()));
            } else {
                tail.push(Span::styled(briefing.since_text.clone(), t.text()));
            }
            lines.push(Line::from(tail));
        }
        lines.push(Line::from(vec![
            Span::raw(" "),
            Span::styled("ctrl-t", t.text()),
            Span::styled(" to open Today", t.label()),
        ]));
        lines
    }

    fn pill_style(&self, pill: Pill) -> Style {
        let t = &self.theme;
        let p = t.palette();
        match pill {
            Pill::Done => t.fg(p.done),
            Pill::Failed => t.fg(p.failed),
            Pill::YouDecided => t.fg(p.working),
            Pill::WaitingForYou | Pill::Suggestion | Pill::Question => t.accent(),
        }
    }

    // -----------------------------------------------------------------------
    // The thread
    // -----------------------------------------------------------------------

    /// The lines of one feed entry. `results` are the later results by call, so an activity
    /// shows how it ended; without them (inline), a result prints its own line.
    pub(crate) fn entry_lines(
        &mut self,
        entry: &FeedEntry,
        results: Option<&HashMap<String, (bool, String)>>,
        width: usize,
    ) -> Vec<Line<'static>> {
        let t = self.theme;
        let mut lines = Vec::new();
        for (index, item) in entry.items.iter().enumerate() {
            match item {
                ThreadItem::Message { from, author, text, images } => {
                    lines.push(Line::default());
                    lines.push(Line::from(Span::styled(
                        format!("{} · {}", safe_line(author), entry.at_text),
                        t.label(),
                    )));
                    match from {
                        Speaker::You => {
                            for line in safe_lines(text) {
                                lines.extend(wrap_spans(
                                    vec![Span::styled(line, t.secondary())],
                                    width,
                                    0,
                                ));
                            }
                            // The terminal cannot show them; it says they are there.
                            if !images.is_empty() {
                                lines.push(Line::from(Span::styled(
                                    format!("[{}]", words::images_attached(images.len())),
                                    t.label(),
                                )));
                            }
                        }
                        Speaker::Agent => {
                            let key = (entry.seq, index, width);
                            match self.markdown.get(&key) {
                                Some((source, rendered)) if source == text => {
                                    lines.extend(rendered.iter().cloned());
                                }
                                _ => {
                                    if self.markdown.len() >= MARKDOWN_CACHE {
                                        self.markdown.clear();
                                    }
                                    let rendered = wrap(markdown(text, &t), width);
                                    lines.extend(rendered.iter().cloned());
                                    self.markdown.insert(key, (text.clone(), rendered));
                                }
                            }
                        }
                    }
                }
                // A render call is shown as its drawing.
                ThreadItem::Activity { call_id: Some(id), .. }
                    if self.drawings.calls.contains(id) => {}
                ThreadItem::Activity { text, call_id, .. } => {
                    let ended = results.and_then(|results| {
                        call_id.as_ref().and_then(|id| results.get(id)).cloned()
                    });
                    let (mark, mark_style, right) = match ended {
                        Some((true, text)) => ('✓', t.fg(t.palette().working), text),
                        Some((false, text)) => ('✗', t.fg(t.palette().failed), text),
                        None => ('·', t.label(), String::new()),
                    };
                    let left = fit(&safe_line(text), width.saturating_sub(right.width() + 4));
                    let gap = width.saturating_sub(2 + left.width() + right.width());
                    lines.push(Line::from(vec![
                        Span::styled(mark.to_string(), mark_style),
                        Span::raw(" "),
                        Span::styled(left, t.secondary()),
                        Span::raw(" ".repeat(gap)),
                        Span::styled(right, t.label()),
                    ]));
                }
                // Suggested replies: the terminal lists them; the person types what they send.
                ThreadItem::Suggestions { replies, .. } => {
                    let shown: Vec<String> = replies.iter().map(|reply| safe_line(reply)).collect();
                    lines.push(Line::from(Span::styled(
                        fit(&format!("{}: {}", words::SUGGESTED_REPLIES, shown.join(" · ")), width),
                        t.label(),
                    )));
                }
                // A run: its line unless its activity shows it, then its last lines.
                ThreadItem::Run { tool, call_id, ok, text, run } => {
                    if !(results.is_some() && call_id.is_some()) {
                        let (mark, style) = if *ok {
                            ('✓', t.fg(t.palette().working))
                        } else {
                            ('✗', t.fg(t.palette().failed))
                        };
                        let what = run.command.as_deref().unwrap_or(tool);
                        lines.push(Line::from(vec![
                            Span::styled(mark.to_string(), style),
                            Span::raw(" "),
                            Span::styled(fit(&safe_line(what), width / 2), t.secondary()),
                            Span::styled(format!(" · {text}"), t.label()),
                        ]));
                    }
                    for line in run.output.iter().rev().take(RUN_TAIL).rev() {
                        let style = if line.stderr { t.fg(t.palette().failed) } else { t.label() };
                        lines.push(Line::from(vec![
                            Span::styled("  │ ".to_string(), t.label()),
                            Span::styled(
                                fit(&safe_line(&line.text), width.saturating_sub(4)),
                                style,
                            ),
                        ]));
                    }
                }
                ThreadItem::Result { tool, call_id, ok, text, .. } => {
                    let shown_on_activity = results.is_some() && call_id.is_some();
                    if !shown_on_activity {
                        let (mark, style) = if *ok {
                            ('✓', t.fg(t.palette().working))
                        } else {
                            ('✗', t.fg(t.palette().failed))
                        };
                        lines.push(Line::from(vec![
                            Span::styled(mark.to_string(), style),
                            Span::raw(" "),
                            Span::styled(fit(&safe_line(tool), width / 2), t.secondary()),
                            Span::styled(format!(" · {text}"), t.label()),
                        ]));
                    }
                }
                // A decision is drawn only as its box, from its open inbox entry (S-I1): the
                // event that held the call says "Waiting for you" also once it is decided.
                ThreadItem::Decision { .. } => {}
                // A drawing: its box on the full screen, a plain block in the scrollback
                // (spec 3.3 §5.2, §7.4 rule 5).
                ThreadItem::Drawn { surface } => {
                    lines.push(Line::default());
                    match results {
                        Some(_) => lines.extend(super::drawn::box_lines(
                            &t,
                            surface,
                            &self.drawings,
                            width,
                        )),
                        None => lines.extend(super::drawn::inline_lines(&t, surface, width)),
                    }
                }
                ThreadItem::DrawnRefused { refusal } => {
                    lines.push(Line::default());
                    lines.extend(super::drawn::refused_lines(&t, refusal, width));
                }
                // On the full screen the form's box says it was sent; the scrollback prints it.
                ThreadItem::DrawnSent { sent } => {
                    if results.is_none() {
                        lines.push(Line::from(Span::styled(
                            fit(&safe_line(&sent.text), width),
                            t.label(),
                        )));
                    }
                }
                // An app is shown in the web home only (spec 3.3 §6.1 `genui-apps`).
                ThreadItem::App { app } => {
                    lines.push(Line::default());
                    lines.extend(super::drawn::app_lines(&t, app, width));
                }
                // Where the reply would have been: who could not answer, and why.
                ThreadItem::TurnFailed { text, reason, .. } => {
                    let said = match reason {
                        Some(reason) => format!("{text}: {reason}"),
                        None => text.clone(),
                    };
                    lines.push(Line::default());
                    lines.extend(wrap_spans(
                        vec![
                            Span::styled("✗ ".to_string(), t.fg(t.palette().failed)),
                            Span::styled(safe_line(&said), t.secondary()),
                        ],
                        width,
                        2,
                    ));
                }
            }
        }
        lines
    }

    /// The thread of the shown session with its open decisions and notices, and the lines of
    /// the box the keys answer. Only that box is drawn, fitted to `height` rows with its keys;
    /// the other open decisions wait below it as one line each, so the box the keys answer is
    /// the one on screen (§7.1). A decision no longer open is a line at its place, as the web
    /// home's decided card is (§8.1 "Decided"); notices pass.
    pub(crate) fn thread(
        &mut self,
        app: &App,
        width: usize,
        height: usize,
        now: Instant,
    ) -> (Vec<Line<'static>>, Option<FocusedBox>) {
        let mut results = HashMap::new();
        let mut named = std::collections::HashSet::new();
        for entry in &app.entries {
            named.extend(named_decisions(entry));
            for item in &entry.items {
                match item {
                    ThreadItem::Result { call_id: Some(id), ok, text, .. }
                    | ThreadItem::Run { call_id: Some(id), ok, text, .. } => {
                        results.insert(id.clone(), (*ok, text.clone()));
                    }
                    _ => {}
                }
            }
        }
        let open = |id: &str| app.cards.iter().any(|open| open.card.id == id);
        let decided = |id: &str| app.decided.iter().find(|line| line.id == id && !open(id));
        self.drawings =
            super::drawn::Drawings::of(&app.entries, |id| decided(id).map(|line| line.answer));
        let mut placed = std::collections::HashSet::new();
        let mut lines = Vec::new();
        for entry in &app.entries {
            lines.extend(self.entry_lines(entry, Some(&results), width));
            for id in named_decisions(entry) {
                if let Some(line) = decided(id)
                    && placed.insert(line.id.as_str())
                {
                    lines.extend(self.decided_line(line, width));
                }
            }
            // Decided where no line names it: after the entry it followed.
            for line in &app.decided {
                if line.after_seq == entry.seq
                    && !named.contains(line.id.as_str())
                    && !open(&line.id)
                    && placed.insert(line.id.as_str())
                {
                    lines.extend(self.decided_line(line, width));
                }
            }
        }
        for line in &app.decided {
            if !open(&line.id) && placed.insert(line.id.as_str()) {
                lines.extend(self.decided_line(line, width));
            }
        }
        // What follows the box: the notices first, so a refusal of a key is right under it,
        // then where else it is shown and the decisions after it. The box leaves room for
        // them where the screen allows.
        let mut tail = Vec::new();
        let notices: Vec<_> = app.visible_notices(now).collect();
        if !notices.is_empty() && app.cards.is_empty() {
            tail.push(Line::default());
        }
        for notice in notices {
            tail.extend(self.notice(&notice.text, notice.tone, width));
        }
        if let Some(open) = app.cards.first() {
            tail.extend(self.also_shown(open, width));
        }
        for open in app.cards.iter().skip(1) {
            tail.extend(self.waiting_line(open, width));
        }
        let live = app.keys_answer(now);
        let mut focused = None;
        if let Some(open) = app.cards.first() {
            lines.push(Line::default());
            let hint = app.typing || !app.composer.is_empty();
            let start = lines.len();
            let rows = height.saturating_sub(tail.len()).max(MIN_BOX_ROWS.min(height));
            let fit = Fit { rows: Some(rows), scroll: app.box_scroll, scrolls: true };
            let drawn = self.decision_box(open, width, live, hint, fit);
            lines.extend(drawn.lines);
            focused = Some(FocusedBox {
                rows: start..lines.len(),
                body_len: drawn.body_len,
                body_shown: drawn.body_shown,
            });
        }
        lines.extend(tail);
        (lines, focused)
    }

    /// A decision no longer open, at its place in the thread: "✓ Decided · Send email to
    /// [CLIENT] · You said yes in the terminal at 06:12" (spec 3.3 §8.1).
    pub(crate) fn decided_line(&self, line: &DecidedLine, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let (mark, mark_style) = match line.answer {
            DecidedAnswer::Yes | DecidedAnswer::Edited => ("✓ ", t.fg(t.palette().working)),
            DecidedAnswer::No => ("✗ ", t.fg(t.palette().failed)),
            DecidedAnswer::Replied | DecidedAnswer::Ended | DecidedAnswer::Unknown => {
                ("· ", t.label())
            }
        };
        let mut out = vec![Line::default()];
        out.extend(wrap_spans(
            vec![
                Span::styled(mark, mark_style),
                Span::styled(line.status.clone(), t.text().add_modifier(Modifier::BOLD)),
                Span::styled(" · ", t.label()),
                Span::styled(marked_line(&line.heading), t.secondary()),
                Span::styled(" · ", t.label()),
                Span::styled(line.text.clone(), t.label()),
            ],
            width,
            2,
        ));
        out
    }

    /// An open decision after the one the keys answer, as one line: it is drawn whole when it
    /// takes the focus (§7.1).
    pub(crate) fn waiting_line(&self, open: &OpenCard, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let text = format!("{} · {}", open.card.status_text, marked_line(&open.card.heading));
        vec![Line::from(vec![
            Span::styled("◆ ", t.accent()),
            Span::styled(fit(&text, width.saturating_sub(16)), t.secondary()),
            Span::styled(" · after this one", t.label()),
        ])]
    }

    pub(crate) fn also_shown(&self, open: &OpenCard, width: usize) -> Vec<Line<'static>> {
        let text = match &open.card.also_shown {
            Some(also) => format!("{also}. {}", words::ANSWERED_ELSEWHERE_UPDATES),
            None => words::ANSWERED_ELSEWHERE_UPDATES.to_string(),
        };
        wrap_spans(vec![Span::styled(text, self.theme.label())], width, 0)
    }

    pub(crate) fn notice(&self, text: &str, tone: Tone, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let (mark, style) = match tone {
            Tone::Decided => ("✓ ", t.fg(t.palette().working)),
            Tone::Problem => ("! ", t.accent()),
            Tone::Info => ("· ", t.label()),
        };
        wrap_spans(
            vec![Span::styled(mark, style), Span::styled(safe_line(text), t.secondary())],
            width,
            2,
        )
    }

    /// The images of a decision as rows of its box (spec 3.7 §8.2, board choice A16).
    fn media_rows(
        &self,
        card: &crate::model::DecisionCard,
        media: &crate::evidence::CardMedia,
        inner: usize,
        body: Style,
    ) -> Vec<Row> {
        let t = &self.theme;
        let mut rows: Vec<Row> = Vec::new();
        let line = |rows: &mut Vec<Row>, label: &str, value: String, style: Style| {
            for wrapped in wrap_spans(
                vec![
                    Span::styled(format!("{label:<9}"), t.label()),
                    Span::styled(safe_line(&value), style),
                ],
                inner,
                9,
            ) {
                rows.push((wrapped.spans, body));
            }
        };
        let one = media.images.len() == 1;
        for image in &media.images {
            let label = if one { "image".to_string() } else { format!("{}", image.index + 1) };
            line(&mut rows, &label, image.digest.clone(), t.text());
            let mut about = vec![image.size_text.clone()];
            about.extend(image.field.clone());
            about.extend(image.why.clone());
            if one {
                about.extend(media.cut_from.as_ref().map(|from| format!("cut from {from}")));
                about.extend(media.cut_note.clone());
            }
            line(&mut rows, "", about.join(" · "), t.label());
            if let Some(purged) = &image.purged {
                line(&mut rows, "", format!("{} — {}", purged.title, purged.text), t.accent());
            }
        }
        if let Some(to) = &media.goes_to {
            let who = match (&to.provider, &to.model) {
                (Some(provider), Some(model)) => format!("{provider} {model} → "),
                (None, Some(model)) => format!("{model} → "),
                (Some(provider), None) => format!("{provider} → "),
                (None, None) => String::new(),
            };
            let what = media
                .what
                .as_ref()
                .map(|what| format!(" · {}", what.to_lowercase()))
                .unwrap_or_default();
            line(&mut rows, "goes to", format!("{who}{}{what}", to.host), t.text());
        }
        let mut covered: Vec<String> = media
            .covered
            .iter()
            .map(|covered| match &covered.note {
                Some(note) => format!("{} {note}", covered.text),
                None => covered.text.clone(),
            })
            .collect();
        if covered.is_empty() {
            covered.push(crate::words::NOTHING_COVERED.to_string());
        }
        covered.extend(media.covered_all_text.clone());
        line(&mut rows, "covered", covered.join(" · "), t.text());
        let regions: Vec<&crate::evidence::EvidenceRegion> =
            media.images.iter().flat_map(|image| image.regions.iter()).collect();
        if !regions.is_empty() {
            let count = format!("{}, in the image's pixels (x0,y0 → x1,y1)", regions.len());
            line(&mut rows, "regions", count, t.text());
            // The tag column fits the longest tag, so "face · whole person" reads in full.
            let tag_width =
                regions.iter().map(|region| region.tag.width()).max().unwrap_or(0).min(24);
            for (number, region) in regions.iter().enumerate() {
                rows.push((
                    vec![
                        Span::styled(format!("  {:>2}  ", number + 1), t.label()),
                        Span::styled(
                            format!("{:<tag_width$}  ", fit(&region.tag, tag_width)),
                            t.accent(),
                        ),
                        Span::styled(
                            format!(
                                "covered  {},{} → {},{}",
                                region.x0.round(),
                                region.y0.round(),
                                region.x1.round(),
                                region.y1.round()
                            ),
                            t.text(),
                        ),
                    ],
                    body,
                ));
            }
        }
        if let Some(cost) = &media.cost_text {
            let detail =
                media.cost_detail.as_ref().map(|detail| format!(" · {detail}")).unwrap_or_default();
            line(&mut rows, "cost", format!("{}{detail}", cost.to_lowercase()), t.text());
        }
        let path = crate::evidence::decision_path(&card.id);
        let link = match &self.home {
            Some(home) => format!("{home}{path} (o opens it)"),
            None => format!("{path} in the home"),
        };
        line(&mut rows, "see it", link, t.fg(t.palette().brand));
        if let Some(notice) = &media.notice {
            line(&mut rows, "", format!("{} {}", notice.title, notice.text), t.accent());
        }
        if let Some(kept) = &media.kept_text {
            let kept = format!("{kept} · {}", crate::words::IMAGES_LEAVE_ONLY_COVERED);
            line(&mut rows, "", kept, t.label());
        }
        rows
    }

    /// A decision as a box answered by key (spec 3.3 §5.2, §7.1): who and when, what will
    /// happen, the exact call, how it got here, the answers this terminal may give, details.
    /// The box fits `fit.rows` with its keys: when the whole call does not fit, the call shows
    /// a window at a time, and a line under it says how much more there is.
    pub(crate) fn decision_box(
        &self,
        open: &OpenCard,
        width: usize,
        live: bool,
        typing_hint: bool,
        fit: Fit,
    ) -> DrawnBox {
        let t = &self.theme;
        let p = t.palette();
        let card = &open.card;
        let outer = width.clamp(24, BOX_WIDTH);
        let inner = outer - 4;
        let border = t.fg(p.brand);
        let strong = Style::new().bg(t.color(p.decision_strong));
        let body = Style::new().bg(t.color(p.decision));
        let blank: Row = (Vec::new(), body);

        // Heading: the pill and what will happen; the risk and whether it can be taken back.
        let mut heading: Vec<Row> = Vec::new();
        let right = format!("{} · {}", card.risk_text, card.reversibility_text);
        let title = format!("{} · {}", card.status_text, marked_line(&card.heading));
        let accent = t.accent().add_modifier(Modifier::BOLD);
        if title.width() + right.width() + 2 <= inner {
            let gap = inner - title.width() - right.width();
            heading.push((
                vec![
                    Span::styled(title, accent),
                    Span::raw(" ".repeat(gap)),
                    Span::styled(right, t.accent()),
                ],
                strong,
            ));
        } else {
            // A narrow box: what will happen is wrapped whole, never cut (§7.1).
            for line in wrap_spans(vec![Span::styled(title, accent)], inner, 0) {
                heading.push((line.spans, strong));
            }
            heading.push((vec![Span::styled(right, t.accent())], strong));
        }
        // What the heading alone does not say, for a decision the kernel itself asks: who
        // suggests the work and when it runs once allowed (spec 3.3 §7.1, §8.1).
        let mut summary: Vec<Row> = Vec::new();
        if let Some(text) = &card.summary {
            for line in wrap_spans(vec![Span::styled(safe_line(text), t.text())], inner, 0) {
                summary.push((line.spans, body));
            }
        }
        let agent: Row = (
            vec![Span::styled(
                format!("{} · {}", safe_line(&card.agent.display_name), card.since_text),
                t.label(),
            )],
            body,
        );
        // A suggested agent is named, never by the kernel's tool name (§8).
        let tool_name = match &card.adds_agent {
            Some(suggested) => suggested.agent.display_name.clone(),
            None => card.call.tool.clone(),
        };
        let tool: Row = (
            vec![Span::styled(safe_line(&tool_name), t.text().add_modifier(Modifier::BOLD))],
            body,
        );

        // The exact call, or with `?` the whole call, how it got here and the details.
        let mut call: Vec<Row> = Vec::new();
        let too_long = needs_details(open);
        if open.details {
            let pretty = serde_json::to_string_pretty(&card.call.args).unwrap_or_default();
            for line in safe_lines(&pretty) {
                for wrapped in wrap_spans(vec![Span::styled(line, t.text())], inner - 2, 0) {
                    let mut spans = vec![Span::raw("  ")];
                    spans.extend(wrapped.spans);
                    call.push((spans, body));
                }
            }
            call.push(blank.clone());
            for step in &card.timeline {
                let (mark, style) =
                    if step.current { ("● ", t.accent()) } else { ("○ ", t.label()) };
                call.push((
                    vec![Span::styled(mark, style), Span::styled(step.text.clone(), t.secondary())],
                    body,
                ));
            }
            call.push(blank.clone());
            let mut details = format!("{} · {}", card.risk_text, card.reversibility_text);
            if let Some(also) = &card.also_shown {
                details.push_str(" · ");
                details.push_str(also);
            }
            for line in wrap_spans(vec![Span::styled(details, t.secondary())], inner, 0) {
                call.push((line.spans, body));
            }
        } else if let Some(suggested) = &card.adds_agent {
            // A suggested agent: its definition in full, what it can do, the comparison with
            // the agent that suggested it, and what it starts with (spec 3.3 §5.7, S-I13).
            let line = |label: &str, value: &str, style: Style| -> Vec<Row> {
                wrap_spans(
                    vec![
                        Span::styled(format!("  {label}  "), t.label()),
                        Span::styled(safe_line(value), style),
                    ],
                    inner,
                    4,
                )
                .into_iter()
                .map(|line| (line.spans, body))
                .collect()
            };
            if !suggested.description.is_empty() {
                call.extend(line("What it does", &suggested.description, t.text()));
            }
            for item in &suggested.lines {
                let style =
                    if item.mono { t.text().add_modifier(Modifier::BOLD) } else { t.text() };
                call.extend(line(&item.label, &item.value, style));
            }
            for text in safe_lines(&suggested.instructions) {
                call.extend(line("›", &text, t.secondary()));
            }
            for ability in &suggested.abilities {
                call.extend(line("·", ability, t.text()));
            }
            if let Some(compared) = &suggested.compared {
                call.extend(line("", compared, t.secondary()));
            }
            call.extend(line(
                "Allowed without asking",
                &suggested.allowed_without_asking,
                t.text(),
            ));
        } else {
            let arg_rows = self.compact_args(&card.call.args, inner - 2);
            let shown = if too_long { arg_rows.len().min(COMPACT_ROWS) } else { arg_rows.len() };
            for spans in arg_rows.iter().take(shown) {
                let mut row = vec![Span::raw("  ")];
                row.extend(spans.clone());
                call.push((row, body));
            }
            if too_long {
                call.push((
                    vec![Span::styled(
                        "  … press ? to see the whole call before you answer",
                        t.accent(),
                    )],
                    body,
                ));
            }
        }

        // The images the call would send, as text: the full digest, what was covered, the
        // regions in the image's pixels, where it goes and a link (spec 3.7 §8.2, A16).
        if let Some(media) = &card.media {
            call.push(blank.clone());
            call.extend(self.media_rows(card, media, inner, body));
        }
        if let Some(parked) = &card.parked {
            for line in wrap_spans(vec![Span::styled(parked.text.clone(), t.accent())], inner, 0) {
                call.push((line.spans, body));
            }
        }

        // How it got here, in one line (the details show each step).
        let mut timeline: Vec<Row> = Vec::new();
        if !open.details {
            let steps: Vec<&str> = card.timeline.iter().map(|step| step.text.as_str()).collect();
            for line in wrap_spans(vec![Span::styled(steps.join(" · "), t.label())], inner, 0) {
                timeline.push((line.spans, body));
            }
        }
        let mut note: Vec<Row> = Vec::new();
        if let Some(text) = &card.allowed.note {
            for line in wrap_spans(vec![Span::styled(text.clone(), t.accent())], inner, 0) {
                note.push((line.spans, body));
            }
        }

        // The answers, by key.
        let cap = if live { t.keycap() } else { t.keycap().add_modifier(Modifier::DIM) };
        let words_style = if live { t.text() } else { t.label() };
        let mut keys: Vec<Span<'static>> = Vec::new();
        for option in &card.allowed.options {
            keys.push(Span::styled(format!(" {} ", key_of(option.answer)), cap));
            keys.push(Span::styled(format!(" {}   ", option.label), words_style));
        }
        if card.adds_agent.is_some() {
            keys.push(Span::styled(" c ", cap));
            keys.push(Span::styled(format!(" {}   ", words::CHANGE_IT_FIRST), words_style));
        }
        if card.media.is_some() {
            keys.push(Span::styled(" o ", cap));
            keys.push(Span::styled(format!(" {OPEN_IMAGE}   "), words_style));
        }
        keys.push(Span::styled(" ? ", cap));
        keys.push(Span::styled(format!(" {DETAILS}"), words_style));
        let key_rows: Vec<Row> =
            wrap_keys(keys, inner).into_iter().map(|row| (row, body)).collect();
        let hint: Option<Row> = typing_hint.then(|| {
            (vec![Span::styled("Typing a message: Esc to answer by key.", t.label())], body)
        });

        // What may go when the box does not fit, first to last; the heading, the tool, the
        // keys and a note on what this terminal may answer always stay.
        let mut keep = [true; 7];
        let [blank_end, blank_call, blank_head, steps, blank_note, typing, who] =
            [0, 1, 2, 3, 4, 5, 6];
        let others = |keep: &[bool; 7]| {
            2 + heading.len()
                + summary.len()
                + 1
                + note.len()
                + key_rows.len()
                + usize::from(keep[blank_end])
                + usize::from(keep[blank_call])
                + usize::from(keep[blank_head])
                + if keep[steps] && !timeline.is_empty() { timeline.len() + 1 } else { 0 }
                + usize::from(keep[blank_note] && !note.is_empty())
                + usize::from(keep[typing] && hint.is_some())
                + usize::from(keep[who])
        };
        let mut window = call.len();
        let mut more_line = false;
        if let Some(rows) = fit.rows
            && others(&keep) + call.len() > rows
        {
            more_line = true;
            let wanted = call.len().min(3);
            for drop in [blank_end, blank_call, blank_head, steps, blank_note, typing, who] {
                if rows.saturating_sub(others(&keep) + 1) >= wanted {
                    break;
                }
                keep[drop] = false;
            }
            window = rows.saturating_sub(others(&keep) + 1).clamp(1, call.len().max(1));
            if window >= call.len() {
                // Dropping what may go made room for the whole call.
                window = call.len();
                more_line = false;
            }
        }
        let scroll = fit.scroll.min(call.len().saturating_sub(window));
        let body_shown = scroll..scroll + window.min(call.len());

        let mut rows: Vec<Row> = Vec::new();
        rows.extend(heading);
        rows.extend(summary);
        if keep[blank_head] {
            rows.push(blank.clone());
        }
        if keep[who] {
            rows.push(agent);
        }
        rows.push(tool);
        rows.extend(call[body_shown.clone()].iter().cloned());
        if more_line {
            let above = body_shown.start;
            let below = call.len() - body_shown.end;
            let noun = |n: usize| if n == 1 { "line" } else { "lines" };
            let text = match (fit.scrolls, above, below) {
                (false, _, _) => format!(
                    "  … {below} more {}: press ? to see the whole call before you answer",
                    noun(below)
                ),
                (true, 0, below) => {
                    format!("  ↓ {below} more {} · PageDown to read on", noun(below))
                }
                (true, above, 0) => format!("  ↑ {above} {} above · PageUp", noun(above)),
                (true, above, below) => {
                    format!("  ↑ {above} above · ↓ {below} more · PageUp, PageDown")
                }
            };
            rows.push((vec![Span::styled(text, t.accent())], body));
        }
        if keep[blank_call] {
            rows.push(blank.clone());
        }
        if keep[steps] && !timeline.is_empty() {
            rows.extend(timeline);
            rows.push(blank.clone());
        }
        if !note.is_empty() {
            rows.extend(note);
            if keep[blank_note] {
                rows.push(blank.clone());
            }
        }
        rows.extend(key_rows);
        if keep[typing]
            && let Some(hint) = hint
        {
            rows.push(hint);
        }
        if keep[blank_end] {
            rows.push(blank);
        }

        let mut lines = Vec::with_capacity(rows.len() + 2);
        lines.push(Line::from(Span::styled(format!("┌{}┐", "─".repeat(outer - 2)), border)));
        for (spans, style) in rows {
            let used: usize = spans.iter().map(|span| span.content.width()).sum();
            let mut line = vec![Span::styled("│", border), Span::styled(" ", style)];
            for span in spans {
                let patched = style.patch(span.style);
                line.push(Span::styled(span.content, patched));
            }
            line.push(Span::styled(" ".repeat(inner.saturating_sub(used) + 1), style));
            line.push(Span::styled("│", border));
            lines.push(Line::from(line));
        }
        lines.push(Line::from(Span::styled(format!("└{}┘", "─".repeat(outer - 2)), border)));
        DrawnBox { lines, body_len: call.len(), body_shown }
    }

    /// The arguments as `key  value` rows, values wrapped under themselves.
    fn compact_args(&self, args: &Value, width: usize) -> Vec<Vec<Span<'static>>> {
        let t = &self.theme;
        let Some(map) = args.as_object() else {
            let text = match args {
                Value::Null => String::new(),
                other => other.to_string(),
            };
            return wrap_spans(vec![Span::styled(safe_line(&text), t.text())], width, 0)
                .into_iter()
                .map(|line| line.spans)
                .collect();
        };
        let key_width = map.keys().map(|key| safe_line(key).width()).max().unwrap_or(0).min(18);
        let mut rows = Vec::new();
        for (key, value) in map {
            let text = match value {
                Value::String(text) => text.clone(),
                other => other.to_string(),
            };
            let key = fit(&safe_line(key), key_width);
            let pad = key_width - key.width() + 2;
            // Each line of a multi-line value is a row of its own, its break marked: a shell
            // command's second line never reads as part of the first (§7.1).
            let parts = safe_lines(&text);
            let last = parts.len() - 1;
            for (index, part) in parts.into_iter().enumerate() {
                let label = if index == 0 { key.clone() } else { String::new() };
                let pad = if index == 0 { pad } else { key_width + 2 };
                let mark = if index < last { NEWLINE_MARK } else { "" };
                let spans = vec![
                    Span::styled(label, t.label()),
                    Span::raw(" ".repeat(pad)),
                    Span::styled(part, t.text()),
                    Span::styled(mark, t.accent()),
                ];
                for line in wrap_spans(spans, width, key_width + 2) {
                    rows.push(line.spans);
                }
            }
        }
        rows
    }

    // -----------------------------------------------------------------------
    // The other views
    // -----------------------------------------------------------------------

    pub(crate) fn today(&self, app: &App, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let mut lines = vec![Line::default()];
        let Some(briefing) = &app.briefing else {
            lines.push(Line::from(Span::styled(words::WHILE_YOU_WERE_AWAY, t.heading())));
            return lines;
        };
        lines.push(Line::from(vec![
            Span::styled(briefing.title.clone(), t.text().add_modifier(Modifier::BOLD)),
            Span::styled(format!("  {}", briefing.since_text), t.label()),
        ]));
        let mut summary = Vec::new();
        if let Some(spend) = &briefing.spend {
            summary.push(Span::styled(spend.text.clone(), t.text()));
            summary.push(Span::styled("  ·  ", t.label()));
        }
        summary.push(Span::styled(words::DECISIONS, t.text()));
        if briefing.waiting > 0 {
            summary.push(Span::raw(" "));
            summary.push(Span::styled(format!(" {} ", briefing.waiting), t.badge()));
        } else {
            summary.push(Span::styled(" —", t.label()));
        }
        lines.push(Line::from(summary));
        lines.push(Line::default());
        for line in &briefing.lines {
            let pill = line.pill_text.clone().unwrap_or_default();
            let style = line.pill.map_or(t.label(), |pill| self.pill_style(pill));
            let spans = vec![
                Span::styled(format!("{}  ", line.at_text), t.label()),
                Span::styled(format!("{pill:<16}"), style),
                Span::styled(safe_line(&line.text), t.secondary()),
            ];
            lines.extend(wrap_spans(spans, width, 23));
        }
        lines.push(Line::default());
        lines.push(Line::from(Span::styled("esc to go back", t.label())));
        lines
    }

    pub(crate) fn permissions(&self, app: &App, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let mut lines = vec![
            Line::default(),
            Line::from(Span::styled(
                "What your agents can do",
                t.text().add_modifier(Modifier::BOLD),
            )),
            Line::default(),
        ];
        let status = app.status.as_ref();
        let current = status.and_then(|status| status.mode.as_ref()).map(|mode| mode.mode);
        let mut modes = vec![Span::styled("How much they ask first  ", t.label())];
        for (key, mode, word) in [
            ('1', Mode::JustLook, words::JUST_LOOK),
            ('2', Mode::Suggest, words::SUGGEST),
            ('3', Mode::AskFirst, words::ASK_FIRST),
            ('4', Mode::GoAhead, words::GO_AHEAD),
        ] {
            modes.push(Span::styled(format!(" {key} "), t.keycap()));
            let style = if current == Some(mode) { t.badge() } else { t.text() };
            modes.push(Span::styled(format!(" {word} "), style));
            modes.push(Span::raw("  "));
        }
        lines.extend(wrap_keys(modes, width).into_iter().map(Line::from));
        lines.push(Line::from(Span::styled(
            "Press a key twice to change it, so a message typed here changes nothing.",
            t.label(),
        )));
        let row = |label: &str, value: String| {
            Line::from(vec![
                Span::styled(format!("{label:<24}"), t.label()),
                Span::styled(value, t.text()),
            ])
        };
        let spend = status.and_then(|status| status.spend.as_ref()).map(|spend| spend.text.clone());
        lines.push(row(words::DAILY_SPENDING_LIMIT, spend.unwrap_or_else(|| "—".into())));
        let quiet = status.and_then(|status| status.quiet.as_ref()).map(|quiet| quiet.text.clone());
        lines.push(row(words::QUIET_TIME, quiet.unwrap_or_else(|| "—".into())));
        lines.push(Line::default());
        lines.push(Line::from(Span::styled(
            // The engine's rule for money (spec 3.3 §7.2), on every surface.
            "A call that spends money is never allowed always.",
            t.secondary(),
        )));
        lines.push(Line::default());
        lines.push(Line::from(vec![
            Span::styled(" ctrl-k ", t.stop()),
            Span::styled(format!(" {}", words::STOP_ALL), t.text()),
        ]));
        if let Some(stopped) = status.and_then(|status| status.stopped_text.clone()) {
            lines.push(Line::from(vec![
                Span::styled(stopped, t.fg(t.palette().failed)),
                Span::raw("   "),
                Span::styled(" r ", t.keycap()),
                Span::styled(format!(" {} (press r twice)", words::RESUME_ALL), t.text()),
            ]));
        }
        lines.push(Line::default());
        lines.push(Line::from(Span::styled("esc to go back", t.label())));
        lines
    }

    /// Keys, then every command: the terminal's own and those its embedder added (spec 3.3
    /// §5.2).
    pub(crate) fn help(&self, app: &App, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let keys = [
            ("y", "Allow once"),
            ("a", "Always allow (the scope the decision names)"),
            ("e", "Edit the call's arguments, then allow"),
            ("n", "Deny, with a reason if you like"),
            ("?", "Details: the whole call, how it got here"),
            ("esc", "Never decides: switch between answering by key and typing"),
            ("tab", "The next agent's thread"),
            ("ctrl-t", "Today: while you were away"),
            ("ctrl-r", "Permissions: what your agents can do"),
            ("ctrl-g", "Your agents"),
            ("ctrl-k", "Stop all"),
            ("pgup pgdn", "Scroll the thread, or the call in a decision box"),
            ("↑", "Take back the newest queued message, into the empty message box"),
            ("ctrl-c", "Leave; a kernel's agents carry on"),
        ];
        let row = |key: String, what: String| {
            wrap_spans(
                vec![
                    Span::styled(
                        format!("{key:<HELP_KEYS$}"),
                        t.text().add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(what, t.secondary()),
                ],
                width,
                HELP_KEYS,
            )
        };
        let mut lines = vec![Line::default(), Line::from(Span::styled("Keys", t.heading()))];
        for (key, what) in keys {
            lines.extend(row(key.to_string(), what.to_string()));
        }
        lines.push(Line::default());
        lines.push(Line::from(Span::styled("Commands", t.heading())));
        let own = BUILT_IN.iter().map(|(name, what)| ((*name).to_string(), (*what).to_string()));
        let screens = app.commands.screens();
        for (name, what) in own.chain(app.commands.added()) {
            if screens.iter().any(|(screen, ..)| *screen == name) {
                continue;
            }
            lines.extend(row(format!("/{}", safe_line(&name)), safe_line(&what)));
        }
        // Screen actions under their own heading (spec 3.3 §2 item 7).
        if !screens.is_empty() {
            lines.push(Line::default());
            lines.push(Line::from(Span::styled(ON_YOUR_SCREENS, t.heading())));
            for (name, usage, what, more) in screens {
                lines.extend(row(format!("/{} {usage}", safe_line(&name)), safe_line(&what)));
                lines.extend(row(String::new(), more));
            }
        }
        lines.push(Line::default());
        lines.push(Line::from(Span::styled(
            "/ and Tab complete a command · esc to go back",
            t.label(),
        )));
        lines
    }

    /// A slash command run from the message box: what was typed, then what it returned, as
    /// it returned it (spec 3.3 §5.2). The text is the embedder's, escaped (S-I9).
    pub(crate) fn output(&self, app: &App, width: usize) -> Vec<Line<'static>> {
        let t = &self.theme;
        let mut lines = vec![Line::default()];
        let Some(output) = &app.output else {
            return lines;
        };
        let line = safe_line(&output.line);
        lines.push(Line::from(Span::styled(line.clone(), t.text().add_modifier(Modifier::BOLD))));
        lines.push(Line::default());
        match &output.result {
            None => lines.push(Line::from(Span::styled(format!("Running {line}…"), t.label()))),
            Some(Ok(text)) if text.trim().is_empty() => {
                lines.push(Line::from(Span::styled("Done; it has nothing to show.", t.label())));
            }
            Some(Ok(text)) => {
                for row in safe_lines(text.trim_end()) {
                    for part in hard_wrap(&row, width) {
                        lines.push(Line::from(Span::styled(part, t.text())));
                    }
                }
            }
            Some(Err(error)) => lines.extend(self.notice(error, Tone::Problem, width)),
        }
        lines.push(Line::default());
        lines.push(Line::from(Span::styled("esc to go back", t.label())));
        lines
    }

    /// The commands a `/` and the start of a name may be, the one the arrows chose marked, at
    /// most `rows` lines (spec 3.3 §5.2).
    pub(crate) fn completion(
        &self,
        completion: &Completion,
        width: usize,
        rows: usize,
    ) -> Vec<Line<'static>> {
        let t = &self.theme;
        let count = completion.candidates.len();
        if count == 0 {
            let text = format!(
                "No command starts with /{} · /help lists them",
                safe_line(&completion.typed)
            );
            return vec![Line::from(Span::styled(fit(&text, width), t.label()))];
        }
        let hint = "↑↓ choose · Tab completes · Enter runs";
        let shown = rows.saturating_sub(1).clamp(1, COMPLETION_ROWS).min(count);
        let first = completion.selected.saturating_sub(shown - 1).min(count - shown);
        let names = completion
            .candidates
            .iter()
            .map(|(name, _)| safe_line(name).width() + 1)
            .max()
            .unwrap_or(0)
            .min(HELP_KEYS);
        let raised = Style::new().bg(t.color(t.palette().raised));
        let mut lines = Vec::with_capacity(shown + 1);
        for (index, (name, what)) in
            completion.candidates.iter().enumerate().skip(first).take(shown)
        {
            let chosen = index == completion.selected;
            let name = fit(&format!("/{}", safe_line(name)), names + 1);
            let pad = (names + 1).saturating_sub(name.width());
            let what = fit(&safe_line(what), width.saturating_sub(names + 5));
            let (mark, name_style, background) = if chosen {
                ("› ", t.accent().add_modifier(Modifier::BOLD), raised)
            } else {
                ("  ", t.text(), Style::new())
            };
            let used = 2 + name.width() + pad + 2 + what.width();
            lines.push(Line::from(vec![
                Span::styled(mark, t.accent().patch(background)),
                Span::styled(name, name_style.patch(background)),
                Span::styled(" ".repeat(pad + 2), background),
                Span::styled(what, t.secondary().patch(background)),
                Span::styled(" ".repeat(width.saturating_sub(used)), background),
            ]));
        }
        let more = if count > shown { format!("{count} commands · ") } else { String::new() };
        lines.push(Line::from(Span::styled(fit(&format!("{more}{hint}"), width), t.label())));
        lines
    }

    // -----------------------------------------------------------------------
    // The message box
    // -----------------------------------------------------------------------

    pub(crate) fn prompt(&self, app: &App) -> (Span<'static>, String) {
        let t = &self.theme;
        let label = match &app.input {
            Input::Message => "› ".to_string(),
            Input::EditArgs { .. } => format!("{} › ", words::EDIT),
            Input::DenyReason { .. } => format!("{} — reason (optional) › ", words::DENY),
        };
        let text = safe_line(&app.composer.text);
        (Span::styled(label, t.accent().add_modifier(Modifier::BOLD)), text)
    }

    pub(crate) fn placeholder(&self, app: &App, now: Instant) -> Option<String> {
        if !app.composer.is_empty() || app.input != Input::Message {
            return None;
        }
        if app.view == View::Permissions {
            if let Some(pending) = app.pending_permission(now) {
                return Some(pending);
            }
            return Some("Press 1–4 twice to change the mode · Esc to go back".to_string());
        }
        // A removed agent's thread is read only (spec 3.3 §5.7).
        if app.view == View::Thread
            && let Some(agent) = app.removed_agent_of(&app.session)
        {
            return Some(words::was_removed(&safe_line(&agent.agent.display_name)));
        }
        let box_shown = app.view == View::Thread && !app.cards.is_empty() && !app.typing;
        let text = if box_shown && app.box_hidden {
            "PageDown to the decision, then answer it"
        } else if box_shown {
            "Answer with a key above, or Esc to type a message"
        } else {
            "Type a message · / for commands"
        };
        Some(text.to_string())
    }

    /// Messages queued for the shown thread; with `take_back`, the newest says that ↑ takes it
    /// back into the empty message box (§7.4 rule 2).
    pub(crate) fn queued(
        &self,
        queued: &[String],
        width: usize,
        take_back: bool,
    ) -> Vec<Line<'static>> {
        let t = &self.theme;
        let newest = queued.len().saturating_sub(1);
        queued
            .iter()
            .enumerate()
            .flat_map(|(index, text)| {
                let mut note = format!("   ({}", words::SENT_AFTER_THIS_CARD_IS_ANSWERED);
                if take_back && index == newest {
                    note.push_str(" · ↑ takes it back");
                }
                note.push(')');
                wrap_spans(
                    vec![
                        Span::styled("Queued › ", t.label()),
                        Span::styled(safe_line(text), t.secondary()),
                        Span::styled(note, t.label()),
                    ],
                    width,
                    9,
                )
            })
            .collect()
    }

    // -----------------------------------------------------------------------
    // The whole screen
    // -----------------------------------------------------------------------

    /// Draws the whole screen; returns what is on screen of the box the keys answer, when the
    /// thread shows one (§7.1).
    pub(crate) fn draw(
        &mut self,
        frame: &mut Frame<'_>,
        app: &App,
        now: Instant,
    ) -> Option<BoxView> {
        let t = self.theme;
        let area = frame.area();
        frame.buffer_mut().set_style(area, t.base());
        let [status_area, body, footer_area] =
            Layout::vertical([Constraint::Length(1), Constraint::Min(3), Constraint::Length(1)])
                .areas(area);

        let strong = Style::new().bg(t.color(t.palette().decision_strong));
        frame.render_widget(
            Paragraph::new(self.status_line(app)).style(t.base().patch(strong)),
            status_area,
        );
        let raised = Style::new().bg(t.color(t.palette().raised));
        frame.render_widget(
            Paragraph::new(self.footer()).style(t.base().patch(raised)),
            footer_area,
        );

        let left_width = match area.width {
            100.. => 34,
            72..=99 => 28,
            _ => 0,
        };
        let [left, divider, right] = Layout::horizontal([
            Constraint::Length(left_width),
            Constraint::Length(u16::from(left_width > 0)),
            Constraint::Min(20),
        ])
        .areas(body);
        if left_width > 0 {
            frame.render_widget(
                Paragraph::new(self.left(app, left.width.into())).style(t.base()),
                left,
            );
            for y in divider.top()..divider.bottom() {
                frame.buffer_mut()[(divider.x, y)].set_symbol("│").set_style(t.border());
            }
        }

        // The right pane: two cells of margin.
        let right = Rect { x: right.x + 2, width: right.width.saturating_sub(4).max(1), ..right };
        let width = usize::from(right.width);
        let take_back = app.composer.is_empty() && app.input == Input::Message;
        let queued = self.queued(&app.queued, width, take_back);
        let queued_height = u16::try_from(queued.len().min(3)).unwrap_or(3);
        // The commands a `/` may be, between the thread and the message box, in at most half of
        // what is left of the pane.
        let room = usize::from(right.height).saturating_sub(usize::from(queued_height) + 3) / 2;
        let completion = match app.completion() {
            Some(completion) if room > 0 => self.completion(&completion, width, room),
            _ => Vec::new(),
        };
        let completion_height = u16::try_from(completion.len()).unwrap_or(0);
        #[cfg(feature = "voice")]
        let voice_height = u16::from(app.voice.is_some());
        #[cfg(not(feature = "voice"))]
        let voice_height = 0;
        let [main, completion_area, queued_area, voice_area, input] = Layout::vertical([
            Constraint::Min(1),
            Constraint::Length(completion_height),
            Constraint::Length(queued_height),
            Constraint::Length(voice_height),
            Constraint::Length(3),
        ])
        .areas(right);
        #[cfg(feature = "voice")]
        if let Some(voice) = &app.voice {
            let line = Line::from(Span::styled(voice.text(now), t.accent()));
            frame.render_widget(Paragraph::new(line).style(t.base()), voice_area);
        }
        #[cfg(not(feature = "voice"))]
        let _ = voice_area;

        // The fill-in pane of a drawn form sits beside the thread where there is room, else
        // in its place (spec 3.3 §5.2, wave 4 decision 19).
        let (main, width, beside) = match (&app.fill, app.view) {
            (Some(fill), View::FillIn) if main.width >= 90 => {
                let [thread, divider, pane] = Layout::horizontal([
                    Constraint::Min(40),
                    Constraint::Length(1),
                    Constraint::Length(44),
                ])
                .areas(main);
                for y in divider.top()..divider.bottom() {
                    frame.buffer_mut()[(divider.x, y)].set_symbol("│").set_style(t.border());
                }
                let pane = Rect { x: pane.x + 2, width: pane.width.saturating_sub(2), ..pane };
                let lines = fill.lines(&t, usize::from(pane.width));
                frame.render_widget(Paragraph::new(lines).style(t.base()), pane);
                (thread, usize::from(thread.width), true)
            }
            _ => (main, width, false),
        };
        let height = usize::from(main.height);
        let thread_shown = app.view == View::Thread || beside;
        let (lines, focused) = match app.view {
            View::Thread => self.thread(app, width, height, now),
            View::FillIn if beside => self.thread(app, width, height, now),
            View::FillIn => {
                (app.fill.as_ref().map(|fill| fill.lines(&t, width)).unwrap_or_default(), None)
            }
            View::Today => (self.today(app, width), None),
            View::Permissions => (self.permissions(app, width), None),
            View::Help => (self.help(app, width), None),
            View::Output => (self.output(app, width), None),
            View::Agents => (super::agents::lines(&app.agents_pane, &self.theme, width), None),
        };
        let scroll =
            if thread_shown { app.scroll.min(lines.len().saturating_sub(height)) } else { 0 };
        let mut box_view = None;
        let visible: Vec<Line<'static>> = if thread_shown {
            let mut end = lines.len().saturating_sub(scroll);
            let mut start = end.saturating_sub(height);
            // Unscrolled, the box the keys answer is kept in view from its top, before what
            // follows it: it fits the pane, keys included.
            if let Some(focused) = &focused
                && scroll == 0
                && focused.rows.start < start
            {
                start = focused.rows.start;
                end = (start + height).min(lines.len());
            }
            box_view = focused.map(|focused| {
                let on_screen = focused.rows.start >= start && focused.rows.end <= end;
                BoxView {
                    on_screen,
                    body_len: focused.body_len,
                    body_shown: if on_screen { focused.body_shown } else { 0..0 },
                    scrolls: true,
                }
            });
            self.view_max_scroll = 0;
            lines[start..end].to_vec()
        } else {
            // Help, Today and a command's output scroll a page at a time; the last row says
            // how much more there is.
            let max = lines.len().saturating_sub(height);
            self.view_max_scroll = max;
            self.view_page = height.saturating_sub(1).max(1);
            let from = app.view_scroll.min(max);
            let below = lines.len().saturating_sub(from + height);
            let mut shown: Vec<Line<'static>> = lines.into_iter().skip(from).take(height).collect();
            if below > 0
                && let Some(last) = shown.last_mut()
            {
                let more = below + 1;
                let noun = if more == 1 { "line" } else { "lines" };
                *last = Line::from(Span::styled(
                    format!("↓ {more} more {noun} · PageDown"),
                    t.accent(),
                ));
            }
            shown
        };
        frame.render_widget(Paragraph::new(visible).style(t.base()), main);
        frame.render_widget(Paragraph::new(completion).style(t.base()), completion_area);
        let tail = queued.len().saturating_sub(usize::from(queued_height));
        frame.render_widget(Paragraph::new(queued[tail..].to_vec()).style(t.base()), queued_area);

        let block = Block::new().borders(Borders::ALL).border_style(t.border()).style(t.base());
        let inner = block.inner(input);
        frame.render_widget(block, input);
        let (prompt, text) = self.prompt(app);
        let prompt_width = prompt.content.width();
        let room = usize::from(inner.width).saturating_sub(prompt_width + 1);
        let before: String = text.chars().take(app.composer.cursor).collect();
        let skip = before.width().saturating_sub(room);
        let shown: String = skip_width(&text, skip);
        let mut spans = vec![prompt];
        match self.placeholder(app, now) {
            Some(placeholder) => spans.push(Span::styled(placeholder, t.label())),
            None => spans.push(Span::styled(shown, t.text())),
        }
        frame.render_widget(Paragraph::new(Line::from(spans)), inner);
        let cursor_x = inner.x + u16::try_from(prompt_width + before.width() - skip).unwrap_or(0);
        frame.set_cursor_position(Position::new(
            cursor_x.min(inner.right().saturating_sub(1)),
            inner.y,
        ));
        box_view
    }
}

/// `text` escaped on one line, each line break shown as [`NEWLINE_MARK`].
pub(crate) fn marked_line(text: &str) -> String {
    safe_lines(text).join(&format!(" {NEWLINE_MARK} "))
}

/// `text` cut to `width` cells, with an ellipsis when cut.
pub(crate) fn fit(text: &str, width: usize) -> String {
    if text.width() <= width {
        return text.to_string();
    }
    let mut out = String::new();
    let mut used = 0;
    for c in text.chars() {
        let w = UnicodeWidthStr::width(c.encode_utf8(&mut [0; 4]) as &str);
        if used + w + 1 > width {
            break;
        }
        used += w;
        out.push(c);
    }
    out.push('…');
    out
}

/// One line of preformatted text cut into rows of `width` cells, spaces kept: what a command
/// returns is aligned in columns, which wrapping at words would break.
fn hard_wrap(line: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    let mut rows = vec![String::new()];
    let mut used = 0;
    for c in line.chars() {
        let w = UnicodeWidthStr::width(c.encode_utf8(&mut [0; 4]) as &str);
        if used + w > width && used > 0 {
            rows.push(String::new());
            used = 0;
        }
        used += w;
        if let Some(row) = rows.last_mut() {
            row.push(c);
        }
    }
    rows
}

/// `text` without its first `width` cells.
fn skip_width(text: &str, width: usize) -> String {
    let mut skipped = 0;
    text.chars()
        .skip_while(|c| {
            let w = UnicodeWidthStr::width(c.encode_utf8(&mut [0; 4]) as &str);
            if skipped + w <= width && width > 0 {
                skipped += w;
                true
            } else {
                false
            }
        })
        .collect()
}

/// Key hints laid out in rows, never splitting a key from its words.
fn wrap_keys(spans: Vec<Span<'static>>, width: usize) -> Vec<Vec<Span<'static>>> {
    let mut rows: Vec<Vec<Span<'static>>> = vec![Vec::new()];
    let mut used = 0;
    let mut pairs = spans.chunks(2);
    for pair in pairs.by_ref() {
        let w: usize = pair.iter().map(|span| span.content.width()).sum();
        if used + w > width && used > 0 {
            rows.push(Vec::new());
            used = 0;
        }
        used += w;
        if let Some(row) = rows.last_mut() {
            row.extend(pair.iter().cloned());
        }
    }
    rows
}