teamctl-ui 0.10.0

Interactive TUI for teamctl — Triptych view, approvals modal, send-mail compose.
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
//! Mailbox-pane data source and tab definitions.
//!
//! The Triptych mailbox presents **two** tabs, organised by direction
//! rather than channel type (#462):
//!
//! - `Inbox` — everything inbound to the focused agent, time-merged:
//!   DMs (`recipient = '<project>:<agent>'`) plus inbound channel and
//!   wire traffic (`sender != '<project>:<agent>'`, so a broadcast the
//!   agent itself sent shows under Sent, not here).
//! - `Sent` — every row whose `sender = '<project>:<agent>'`,
//!   irrespective of recipient class. Sender-side, so it already
//!   catches outbound DMs, channel posts, and broadcasts.
//!
//! Four data shapes still back these tabs — the SQL fetch is unchanged
//! (`inbox`, `sent`, `channel_feed`, `wire`); only the tab *surface*
//! folds them by direction. The `Channel` and `Wire` `MailboxTab`
//! variants survive as **internal** buffer keys (they're dropped from
//! [`MailboxTab::ALL`], so they're never user-navigable tabs) because
//! the channel buffer still feeds the MailboxFirst layout's channel
//! feed and the Inbox merge:
//!
//! - `Channel` — channel traffic for channels the focused agent is
//!   a member of (recipient is `'channel:<channel_id>'`, filtered
//!   through `channel_members`).
//! - `Wire` — project-wide broadcast traffic on the `all` channel
//!   (`recipient = 'channel:<project>:all'`).
//!
//! INVARIANT: every `messages.recipient` value falls into exactly
//! one of three prefix classes — `<project>:<agent>` (DM, no scheme
//! prefix; the channel-or-user split below depends on this absence),
//! `channel:<channel_id>`, or `user:<handle>`. `data::mailbox_counts`
//! relies on the same contract when it filters out channel/user rows
//! for the per-agent unread-mail counter; if a fourth prefix class
//! ever lands, the comment there and the queries here both need to
//! learn it. Sent is the one tab whose filter is sender-side and
//! recipient-class-agnostic — it returns rows from all three
//! recipient prefix classes.

use std::borrow::Cow;
use std::path::PathBuf;

use anyhow::Result;
use rusqlite::{params, Connection};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MailboxTab {
    Inbox,
    Sent,
    Channel,
    Wire,
}

impl MailboxTab {
    /// The user-navigable tabs, in tab-bar order. Channel and Wire are
    /// deliberately absent (#462): their traffic folds into Inbox by
    /// direction, but the variants survive as internal buffer keys.
    pub const ALL: [MailboxTab; 2] = [MailboxTab::Inbox, MailboxTab::Sent];

    pub fn label(self) -> &'static str {
        match self {
            MailboxTab::Inbox => "Inbox",
            MailboxTab::Sent => "Sent",
            MailboxTab::Channel => "Channel",
            MailboxTab::Wire => "Wire",
        }
    }

    pub fn empty_hint(self) -> &'static str {
        match self {
            MailboxTab::Inbox => "(no DMs)",
            MailboxTab::Sent => "(no sent messages)",
            MailboxTab::Channel => "(no channel traffic)",
            MailboxTab::Wire => "(quiet)",
        }
    }

    pub fn next(self) -> Self {
        match self {
            MailboxTab::Inbox => MailboxTab::Sent,
            MailboxTab::Sent => MailboxTab::Inbox,
            // Channel/Wire are internal-only (folded into Inbox, never
            // the active tab); map them to Inbox defensively so cycling
            // can never strand the cursor on a non-tab.
            MailboxTab::Channel | MailboxTab::Wire => MailboxTab::Inbox,
        }
    }

    pub fn prev(self) -> Self {
        match self {
            MailboxTab::Inbox => MailboxTab::Sent,
            MailboxTab::Sent => MailboxTab::Inbox,
            MailboxTab::Channel | MailboxTab::Wire => MailboxTab::Inbox,
        }
    }
}

#[derive(Debug, Clone)]
pub struct MessageRow {
    pub id: i64,
    pub sender: String,
    pub recipient: String,
    pub text: String,
    pub sent_at: f64,
}

/// Format a single row for the mailbox pane. Kept terse: prefix in
/// brackets + one-line body. Multi-line bodies are flattened with a
/// space so a single message stays one row in the pane.
///
/// Prefix is tab-aware (T-231, #462):
///
/// - **Inbox** → `[<senderName>]` for a DM, or `[#channel] [<sender>]`
///   for a folded-in channel/wire row (recipient `channel:…`). The
///   channel segment keeps the disambiguator-first labelling (T-249)
///   so a broadcast stays distinct from a direct message now that both
///   share the Inbox.
/// - **Sent** → `[→<recipientName>]`. Sender on a Sent row is
///   always the focused agent (that's the filter), so showing it is
///   redundant. Operators want to see WHO the agent talked to;
///   recipient resolution goes through
///   [`crate::data::recipient_label`] which handles agent,
///   `channel:`, and `user:` recipient shapes.
/// - **Channel** (internal — the MailboxFirst feed) → `[#channel]
///   [<sender>]`, the two-segment T-249 shape.
pub fn render_row(row: &MessageRow, team: &crate::data::TeamSnapshot, tab: MailboxTab) -> String {
    let one_line: String = row
        .text
        .replace('\n', " ")
        .replace('\r', "")
        .chars()
        .take(180)
        .collect();
    match tab {
        MailboxTab::Sent => {
            let recipient = crate::data::recipient_label(team, &row.recipient);
            format!("[→{recipient}] {one_line}")
        }
        MailboxTab::Inbox => {
            // #462: the Inbox folds inbound DMs + channel + wire. A
            // channel/wire row (recipient `channel:…`) keeps the T-249
            // disambiguator-first labelling — `[#channel] [sender]` — so
            // it stays distinguishable from a direct DM (`[sender]`).
            // `recipient_label` maps `channel:<p>:<n>` to `#<n>`.
            if row.recipient.starts_with("channel:") {
                let channel = crate::data::recipient_label(team, &row.recipient);
                let sender = crate::data::agent_label(team, &row.sender);
                format!("[{channel}] [{sender}] {one_line}")
            } else {
                let sender = crate::data::agent_label(team, &row.sender);
                format!("[{sender}] {one_line}")
            }
        }
        MailboxTab::Channel => {
            // T-249, still used by the MailboxFirst channel feed: two
            // bracketed segments — channel, then sender — so operators
            // can tell `#all` from `#dev` from `#docs` in a rolled-up
            // feed. `recipient_label` maps `channel:<p>:<n>` to `#<n>`.
            let channel = crate::data::recipient_label(team, &row.recipient);
            let sender = crate::data::agent_label(team, &row.sender);
            format!("[{channel}] [{sender}] {one_line}")
        }
        MailboxTab::Wire => {
            // Internal variant, not a user tab; kept for exhaustiveness.
            // Same sender-only shape it always had.
            let sender = crate::data::agent_label(team, &row.sender);
            format!("[{sender}] {one_line}")
        }
    }
}

/// T-131 PR-4: short absolute-datetime stamp for the right-side
/// mailbox-row indicator. Computed every render from `now_secs`
/// (clock reading at render time) and the row's `sent_at` (epoch
/// seconds). Format is **today-folded** to save column budget on
/// the common case:
///
/// - same calendar day in the operator's local timezone → `HH:MM`
///   (24-hour, 5 chars; e.g. `15:42`).
/// - any earlier day → `%b %d %H:%M` (12 chars; e.g. `May 22 15:42`).
///
/// Variants ratified by owner (tg 3388):
/// - (1) today-vs-not folding: YES.
/// - (2) 24-hour clock: YES.
///
/// Silent defaults preserved: no seconds; local-to-operator TZ
/// (the detail modal already shows UTC for the precise reference);
/// past-day format `%b %d %H:%M`.
///
/// Production callers use [`row_timestamp`] (wraps `Local`); tests
/// drive [`row_timestamp_in`] with `chrono::Utc` for determinism.
pub fn row_timestamp(now_secs: f64, sent_at: f64) -> String {
    row_timestamp_in(&chrono::Local, now_secs, sent_at)
}

/// TZ-injected variant of [`row_timestamp`] — keeps the production
/// path on `Local` while tests pin behaviour with `Utc`.
pub fn row_timestamp_in<Tz>(tz: &Tz, now_secs: f64, sent_at: f64) -> String
where
    Tz: chrono::TimeZone,
    Tz::Offset: std::fmt::Display,
{
    let Some(now) = tz.timestamp_opt(now_secs as i64, 0).single() else {
        return "".to_string();
    };
    let Some(sent) = tz.timestamp_opt(sent_at as i64, 0).single() else {
        return "".to_string();
    };
    if now.date_naive() == sent.date_naive() {
        sent.format("%H:%M").to_string()
    } else {
        sent.format("%b %d %H:%M").to_string()
    }
}

/// T-131 PR-3: human-readable kind label for the detail modal.
/// Derived from the recipient shape — the same prefix classes the
/// module-doc INVARIANT pins (`<project>:<agent>` DM,
/// `channel:<project>:all` wire, other `channel:` channel,
/// `user:` DM-from-or-to-a-user).
pub fn kind_label(row: &MessageRow) -> &'static str {
    if let Some(rest) = row.recipient.strip_prefix("channel:") {
        // `channel:<project>:all` is the project-wide wire; anything
        // else under `channel:` is a named channel.
        if rest.ends_with(":all") {
            "wire broadcast"
        } else {
            "channel broadcast"
        }
    } else {
        // Agent id (`<project>:<agent>`) or `user:<handle>` —
        // either way, a directed message.
        "DM"
    }
}

/// T-131 PR-3: best-effort transport / origin label for the detail
/// modal. Heuristic from the sender prefix (variant (b) locked):
///
/// - `user:telegram` → "via telegram" — by far the most common
///   non-agent origin, worth its own label.
/// - any other `user:<handle>` → "via user" — DMs from a different
///   human-facing adapter, future-proof against new `user:*` shapes.
/// - agent id (`<project>:<agent>`) → "via mcp" — every agent emits
///   through the MCP broker.
/// - else → "—" (unparseable / future schema).
pub fn transport_label(row: &MessageRow) -> &'static str {
    if row.sender.starts_with("user:telegram") {
        "via telegram"
    } else if row.sender.starts_with("user:") {
        "via user"
    } else if row.sender.contains(':') {
        "via mcp"
    } else {
        ""
    }
}

/// Lookup contract: each method returns rows newer than `after_id`
/// for the given filter, in ascending id order. Callers fold the
/// returned rows into a per-tab buffer and bump `after_id` to the
/// last returned id.
pub trait MailboxSource: Send + Sync {
    fn inbox(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>>;
    fn sent(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>>;
    fn channel_feed(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>>;
    fn wire(&self, project_id: &str, after_id: i64) -> Result<Vec<MessageRow>>;
}

/// Production impl reading the broker SQLite at `<root>/state/mailbox.db`.
/// Each call opens a fresh connection — `mailbox.db` is local and
/// short-lived connections cost effectively zero.
#[derive(Debug, Clone)]
pub struct BrokerMailboxSource {
    pub db_path: PathBuf,
}

impl BrokerMailboxSource {
    pub fn new(db_path: PathBuf) -> Self {
        Self { db_path }
    }

    fn open(&self) -> Result<Option<Connection>> {
        if !self.db_path.is_file() {
            return Ok(None);
        }
        let conn = Connection::open(&self.db_path)?;
        Ok(Some(conn))
    }
}

impl MailboxSource for BrokerMailboxSource {
    fn inbox(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
        let Some(conn) = self.open()? else {
            return Ok(Vec::new());
        };
        let mut stmt = conn.prepare(
            "SELECT id, sender, recipient, text, sent_at FROM messages
             WHERE id > ?1 AND recipient = ?2
             ORDER BY id ASC",
        )?;
        let rows = stmt
            .query_map(params![after_id, agent_id], |r| {
                Ok(MessageRow {
                    id: r.get(0)?,
                    sender: r.get(1)?,
                    recipient: r.get(2)?,
                    text: r.get(3)?,
                    sent_at: r.get(4)?,
                })
            })?
            .flatten()
            .collect();
        Ok(rows)
    }

    fn sent(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
        let Some(conn) = self.open()? else {
            return Ok(Vec::new());
        };
        // Sender-side filter — every row the focused agent emitted,
        // irrespective of recipient class. Returns DMs, telegram
        // replies, channel posts, and wire broadcasts in a single
        // stream.
        let mut stmt = conn.prepare(
            "SELECT id, sender, recipient, text, sent_at FROM messages
             WHERE id > ?1 AND sender = ?2
             ORDER BY id ASC",
        )?;
        let rows = stmt
            .query_map(params![after_id, agent_id], |r| {
                Ok(MessageRow {
                    id: r.get(0)?,
                    sender: r.get(1)?,
                    recipient: r.get(2)?,
                    text: r.get(3)?,
                    sent_at: r.get(4)?,
                })
            })?
            .flatten()
            .collect();
        Ok(rows)
    }

    fn channel_feed(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
        let Some(conn) = self.open()? else {
            return Ok(Vec::new());
        };
        // Same shape as `teamctl tail <agent>`'s channel arm: rows
        // whose recipient is a `channel:` URL the agent is a member
        // of. Membership lives in `channel_members.agent_id =
        // <project>:<agent>`.
        let mut stmt = conn.prepare(
            "SELECT id, sender, recipient, text, sent_at FROM messages
             WHERE id > ?1
               AND recipient IN (
                   SELECT 'channel:' || cm.channel_id FROM channel_members cm
                   WHERE cm.agent_id = ?2
               )
             ORDER BY id ASC",
        )?;
        let rows = stmt
            .query_map(params![after_id, agent_id], |r| {
                Ok(MessageRow {
                    id: r.get(0)?,
                    sender: r.get(1)?,
                    recipient: r.get(2)?,
                    text: r.get(3)?,
                    sent_at: r.get(4)?,
                })
            })?
            .flatten()
            .collect();
        Ok(rows)
    }

    fn wire(&self, project_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
        let Some(conn) = self.open()? else {
            return Ok(Vec::new());
        };
        // The project-wide `all` channel is the broadcast wire.
        // Channel ids are `<project>:<name>`; messages address them
        // via `channel:<channel_id>`.
        let target = format!("channel:{project_id}:all");
        let mut stmt = conn.prepare(
            "SELECT id, sender, recipient, text, sent_at FROM messages
             WHERE id > ?1 AND recipient = ?2
             ORDER BY id ASC",
        )?;
        let rows = stmt
            .query_map(params![after_id, target], |r| {
                Ok(MessageRow {
                    id: r.get(0)?,
                    sender: r.get(1)?,
                    recipient: r.get(2)?,
                    text: r.get(3)?,
                    sent_at: r.get(4)?,
                })
            })?
            .flatten()
            .collect();
        Ok(rows)
    }
}

/// Per-agent buffer state — four tabs, four `after_id` cursors.
/// Lives on `App` so swapping the focused agent resets the cursors
/// without trying to back-fill: the operator sees only forward
/// motion in the tab they're watching.
#[derive(Debug, Default, Clone)]
pub struct MailboxBuffers {
    /// The focused agent's id (`<project>:<agent>`), set by
    /// `refresh_mailbox`. The `sender != me` source for the Inbox
    /// merge's inbound filter (#462) — kept here so `rows()` and the
    /// cursor methods that read it don't have to thread `me` through
    /// every signature. Empty until the first refresh; an empty id
    /// means the filter is a no-op (one transient frame at most).
    pub agent_id: String,
    pub inbox: Vec<MessageRow>,
    pub sent: Vec<MessageRow>,
    pub channel: Vec<MessageRow>,
    pub wire: Vec<MessageRow>,
    pub inbox_after: i64,
    pub sent_after: i64,
    pub channel_after: i64,
    pub wire_after: i64,
    // T-131 PR-1: UI cursor state per tab. `selected_idx` is an index
    // INTO `visible_indices(tab)`, not directly into `rows(tab)` — the
    // two coincide when no filter/search is set; PR-2 made them
    // diverge without changing this invariant or any call site (the
    // composability payoff of returning `Vec<usize>` indices, not a
    // slice).
    pub inbox_cursor: CursorState,
    pub sent_cursor: CursorState,
    pub channel_cursor: CursorState,
    pub wire_cursor: CursorState,
    // T-131 PR-2: per-tab filter (sender substring) + search (body
    // substring) text. Both compose: a row is visible iff it passes
    // BOTH (empty = no-op on that axis). Mirrors the existing per-tab
    // Vec + cursor pattern. Case-insensitive substring match.
    pub inbox_filter: String,
    pub sent_filter: String,
    pub channel_filter: String,
    pub wire_filter: String,
    pub inbox_search: String,
    pub sent_search: String,
    pub channel_search: String,
    pub wire_search: String,
}

/// Which mailbox input the operator is editing. Singleton at the App
/// level (only one input can be open at a time across all tabs);
/// distinct from the per-tab `filter_text` / `search_text` it targets,
/// which live on [`MailboxBuffers`]. Defined here so the data-side
/// methods (`input_push_char`, `input_pop_char`, etc.) can take it
/// without crossing the App boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MailboxInputKind {
    Filter,
    Search,
}

/// UI cursor state for one mailbox tab. PR-1 stores only the selected
/// row index; the rendered scroll-window is derived at render time
/// from `selected_idx` + the actual pane height, so a terminal resize
/// just changes the next-paint window without touching persisted
/// state. `selected_idx` is an index into
/// [`MailboxBuffers::visible_indices`].
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct CursorState {
    pub selected_idx: usize,
}

const MAX_TAB_ROWS: usize = 500;

/// PageUp/PageDown jump size — a screen-ish chunk of rows. Fixed for
/// PR-1 to keep scope surgical; a follow-up can wire this to the
/// actual rendered mailbox-pane height once that's plumbed onto App.
pub const PAGE_JUMP: usize = 10;

impl MailboxBuffers {
    /// Rows for `tab`, in ascending broker-id (receipt) order.
    ///
    /// Most tabs hand back a borrow of their backing buffer. `Inbox`
    /// is the exception (#462): it returns an owned, time-merged view
    /// of inbound DMs + channel + wire, so it allocates. `Cow` lets the
    /// common borrowed case stay zero-copy while the merged case owns
    /// its Vec; callers use the result as a slice either way (`Cow`
    /// derefs to `[MessageRow]`).
    pub fn rows(&self, tab: MailboxTab) -> Cow<'_, [MessageRow]> {
        match tab {
            MailboxTab::Inbox => Cow::Owned(self.merged_inbox()),
            MailboxTab::Sent => Cow::Borrowed(&self.sent),
            MailboxTab::Channel => Cow::Borrowed(&self.channel),
            MailboxTab::Wire => Cow::Borrowed(&self.wire),
        }
    }

    /// The Inbox feed (#462): inbound DMs + inbound channel + inbound
    /// wire, merged and sorted ascending by broker `id` (receipt
    /// order, the same order each buffer already holds). Inbound means
    /// `sender != self.agent_id`, so a channel post or broadcast the
    /// focused agent itself sent stays under Sent and never
    /// double-shows here.
    ///
    /// **Dedup by id is load-bearing.** The project-wide `all` channel
    /// is a real channel every agent joins (its `members: "*"`
    /// registers all of them in `channel_members`), so a broadcast to
    /// `channel:<project>:all` is returned by *both* the membership
    /// query behind the `channel` buffer *and* the `wire` buffer — the
    /// same message id via two paths. Without the dedup every wire
    /// broadcast would render twice in the folded Inbox. Equal ids are
    /// adjacent after the id-sort, so `dedup_by_key` collapses them.
    fn merged_inbox(&self) -> Vec<MessageRow> {
        let me = self.agent_id.as_str();
        let mut rows: Vec<MessageRow> = self
            .inbox
            .iter()
            .chain(self.channel.iter().filter(|r| r.sender != me))
            .chain(self.wire.iter().filter(|r| r.sender != me))
            .cloned()
            .collect();
        rows.sort_by_key(|r| r.id);
        rows.dedup_by_key(|r| r.id);
        rows
    }

    /// Indices into `rows(tab)` for the rows currently presented to
    /// the operator — filter ∩ search. PR-2 swapped this body in;
    /// every cursor method and the render call site stayed unchanged
    /// from PR-1 because they go through this abstraction. A row at
    /// `rows(tab)[i]` is visible iff:
    ///
    /// 1. `filter_text(tab)` is empty OR `row.sender` (lower-cased)
    ///    contains the filter (lower-cased) as a substring.
    /// 2. `search_text(tab)` is empty OR `row.text` (lower-cased)
    ///    contains the search (lower-cased) as a substring.
    ///
    /// When both axes are empty, the result is identity
    /// `(0..rows.len())` — PR-1's default behavior recovers exactly.
    /// Case-insensitive substring is the documented contract; the
    /// per-keystroke recompute on small (~500-row) buffers is well
    /// within budget.
    pub fn visible_indices(&self, tab: MailboxTab) -> Vec<usize> {
        self.visible_indices_in(&self.rows(tab), tab)
    }

    /// Like [`visible_indices`] but against an already-materialised row
    /// slice. The render path already holds `rows(tab)`, so it computes
    /// visibility through this to avoid a second `rows()` call — for the
    /// Inbox that call is non-trivial (it clones, sorts, and dedups the
    /// merged feed, #462), and the per-frame render would otherwise pay
    /// for the merge twice.
    pub fn visible_indices_in(&self, rows: &[MessageRow], tab: MailboxTab) -> Vec<usize> {
        let filter = self.filter_text(tab).to_lowercase();
        let search = self.search_text(tab).to_lowercase();
        if filter.is_empty() && search.is_empty() {
            return (0..rows.len()).collect();
        }
        (0..rows.len())
            .filter(|&i| {
                let row = &rows[i];
                (filter.is_empty() || row.sender.to_lowercase().contains(&filter))
                    && (search.is_empty() || row.text.to_lowercase().contains(&search))
            })
            .collect()
    }

    /// Current sender-substring filter on `tab`; empty = no filter.
    pub fn filter_text(&self, tab: MailboxTab) -> &str {
        match tab {
            MailboxTab::Inbox => &self.inbox_filter,
            MailboxTab::Sent => &self.sent_filter,
            MailboxTab::Channel => &self.channel_filter,
            MailboxTab::Wire => &self.wire_filter,
        }
    }

    /// Current body-substring search on `tab`; empty = no search.
    pub fn search_text(&self, tab: MailboxTab) -> &str {
        match tab {
            MailboxTab::Inbox => &self.inbox_search,
            MailboxTab::Sent => &self.sent_search,
            MailboxTab::Channel => &self.channel_search,
            MailboxTab::Wire => &self.wire_search,
        }
    }

    fn filter_text_mut(&mut self, tab: MailboxTab) -> &mut String {
        match tab {
            MailboxTab::Inbox => &mut self.inbox_filter,
            MailboxTab::Sent => &mut self.sent_filter,
            MailboxTab::Channel => &mut self.channel_filter,
            MailboxTab::Wire => &mut self.wire_filter,
        }
    }

    fn search_text_mut(&mut self, tab: MailboxTab) -> &mut String {
        match tab {
            MailboxTab::Inbox => &mut self.inbox_search,
            MailboxTab::Sent => &mut self.sent_search,
            MailboxTab::Channel => &mut self.channel_search,
            MailboxTab::Wire => &mut self.wire_search,
        }
    }

    /// Push `c` onto the active input buffer for `tab`, then clamp
    /// the cursor against the (possibly shorter) new visible_indices.
    /// Called per-keystroke by the App input-mode handler.
    pub fn input_push_char(&mut self, tab: MailboxTab, kind: MailboxInputKind, c: char) {
        match kind {
            MailboxInputKind::Filter => self.filter_text_mut(tab).push(c),
            MailboxInputKind::Search => self.search_text_mut(tab).push(c),
        }
        self.clamp_cursor(tab);
    }

    /// Pop one character (Backspace) from the active input buffer for
    /// `tab`, then re-clamp the cursor.
    pub fn input_pop_char(&mut self, tab: MailboxTab, kind: MailboxInputKind) {
        match kind {
            MailboxInputKind::Filter => {
                self.filter_text_mut(tab).pop();
            }
            MailboxInputKind::Search => {
                self.search_text_mut(tab).pop();
            }
        }
        self.clamp_cursor(tab);
    }

    /// Replace the active input buffer for `tab` wholesale — used by
    /// the Esc-cancel-revert path to restore the pre-open snapshot.
    pub fn set_input(&mut self, tab: MailboxTab, kind: MailboxInputKind, value: String) {
        match kind {
            MailboxInputKind::Filter => *self.filter_text_mut(tab) = value,
            MailboxInputKind::Search => *self.search_text_mut(tab) = value,
        }
        self.clamp_cursor(tab);
    }

    /// Clamp the per-tab cursor to the current visible_indices range.
    /// Called from every input mutation and from extend()'s drain
    /// path so a stale `selected_idx` can never index past the
    /// visible set.
    fn clamp_cursor(&mut self, tab: MailboxTab) {
        let len = self.visible_indices(tab).len();
        let cur = self.cursor_mut(tab);
        if len == 0 {
            cur.selected_idx = 0;
        } else if cur.selected_idx >= len {
            cur.selected_idx = len - 1;
        }
    }

    pub fn cursor(&self, tab: MailboxTab) -> &CursorState {
        match tab {
            MailboxTab::Inbox => &self.inbox_cursor,
            MailboxTab::Sent => &self.sent_cursor,
            MailboxTab::Channel => &self.channel_cursor,
            MailboxTab::Wire => &self.wire_cursor,
        }
    }

    fn cursor_mut(&mut self, tab: MailboxTab) -> &mut CursorState {
        match tab {
            MailboxTab::Inbox => &mut self.inbox_cursor,
            MailboxTab::Sent => &mut self.sent_cursor,
            MailboxTab::Channel => &mut self.channel_cursor,
            MailboxTab::Wire => &mut self.wire_cursor,
        }
    }

    /// Move the cursor one row toward the tail; clamps at the last
    /// visible row (vim-like — no wrap).
    pub fn move_cursor_down(&mut self, tab: MailboxTab) {
        let max = self.visible_indices(tab).len().saturating_sub(1);
        let c = self.cursor_mut(tab);
        c.selected_idx = (c.selected_idx + 1).min(max);
    }

    /// Move the cursor one row toward the head; clamps at 0.
    pub fn move_cursor_up(&mut self, tab: MailboxTab) {
        let c = self.cursor_mut(tab);
        c.selected_idx = c.selected_idx.saturating_sub(1);
    }

    /// Jump a screen toward the tail.
    pub fn page_cursor_down(&mut self, tab: MailboxTab) {
        let max = self.visible_indices(tab).len().saturating_sub(1);
        let c = self.cursor_mut(tab);
        c.selected_idx = (c.selected_idx + PAGE_JUMP).min(max);
    }

    /// Jump a screen toward the head.
    pub fn page_cursor_up(&mut self, tab: MailboxTab) {
        let c = self.cursor_mut(tab);
        c.selected_idx = c.selected_idx.saturating_sub(PAGE_JUMP);
    }

    /// Jump to the first visible row.
    pub fn cursor_home(&mut self, tab: MailboxTab) {
        self.cursor_mut(tab).selected_idx = 0;
    }

    /// Jump to the last visible row.
    pub fn cursor_end(&mut self, tab: MailboxTab) {
        let max = self.visible_indices(tab).len().saturating_sub(1);
        self.cursor_mut(tab).selected_idx = max;
    }

    /// Whether the Inbox cursor is at (or past) the tail of the merged
    /// view — i.e. the operator is following new arrivals. Captured
    /// before a refresh's extends so [`follow_inbox_tail`] can re-anchor
    /// the cursor afterwards: per-tab `extend` only follows the tab it
    /// touches, but a channel/wire arrival grows the *Inbox* view too,
    /// so without this the highlight would stop tracking the newest row
    /// on the merged tab (#462).
    pub fn inbox_at_tail(&self) -> bool {
        let len = self.visible_indices(MailboxTab::Inbox).len();
        len == 0 || self.inbox_cursor.selected_idx + 1 >= len
    }

    /// Snap the Inbox cursor to the tail of the post-merge view. Called
    /// after a refresh's extends when [`inbox_at_tail`] held before
    /// them, so following the Inbox keeps tracking the newest row even
    /// when the new arrival came via the channel or wire buffer (#462).
    pub fn follow_inbox_tail(&mut self) {
        let len = self.visible_indices(MailboxTab::Inbox).len();
        if len > 0 {
            self.inbox_cursor.selected_idx = len - 1;
        }
    }

    /// Fold a freshly-fetched batch into the appropriate tab,
    /// trimming to the last `MAX_TAB_ROWS`. Bumps the broker
    /// pagination cursor to the last returned id when the batch is
    /// non-empty. T-131 PR-1: when the UI cursor was already at the
    /// tail (or the tab was empty), follow new arrivals — matching
    /// the pre-T-131 "tail to whatever fits" UX. Always re-clamps the
    /// UI cursor against the (possibly drained) post-extend visible
    /// length so a stale index can never reference a missing row.
    pub fn extend(&mut self, tab: MailboxTab, batch: Vec<MessageRow>) {
        let prev_visible_len = self.visible_indices(tab).len();
        let was_at_tail =
            prev_visible_len == 0 || self.cursor(tab).selected_idx + 1 >= prev_visible_len;
        let last_id = batch.last().map(|r| r.id);
        let (buf, after) = match tab {
            MailboxTab::Inbox => (&mut self.inbox, &mut self.inbox_after),
            MailboxTab::Sent => (&mut self.sent, &mut self.sent_after),
            MailboxTab::Channel => (&mut self.channel, &mut self.channel_after),
            MailboxTab::Wire => (&mut self.wire, &mut self.wire_after),
        };
        buf.extend(batch);
        if buf.len() > MAX_TAB_ROWS {
            let drop = buf.len() - MAX_TAB_ROWS;
            buf.drain(..drop);
        }
        if let Some(id) = last_id {
            *after = id;
        }
        let new_visible_len = self.visible_indices(tab).len();
        let cur = self.cursor_mut(tab);
        if was_at_tail && new_visible_len > 0 {
            cur.selected_idx = new_visible_len - 1;
        } else if new_visible_len > 0 {
            let max = new_visible_len - 1;
            if cur.selected_idx > max {
                cur.selected_idx = max;
            }
        } else {
            cur.selected_idx = 0;
        }
    }

    /// Reset every tab's contents and cursor. Called when the
    /// focused agent changes — the new agent's `inbox` filter would
    /// otherwise skip historical rows that landed before our last
    /// `inbox_after`, and the UI cursor would point into the wrong
    /// agent's buffer.
    pub fn reset(&mut self) {
        *self = Self::default();
    }
}

pub mod test_support {
    //! Shared mock — public so unit tests, integration tests, and
    //! downstream coverage can wire in a recorder without rolling
    //! their own. Matches the shape used by `compose::test_support`
    //! and `approvals::test_support`.

    use super::*;
    use std::sync::Mutex;

    /// Test stub — returns canned rows on each call, records every
    /// arg pair. Mailbox is the most-asserted test surface in
    /// PR-UI-3 so the recorder lets snapshot + interaction tests
    /// verify "is the right filter being asked the right thing."
    #[derive(Default)]
    pub struct MockMailboxSource {
        pub inbox_rows: Vec<MessageRow>,
        pub sent_rows: Vec<MessageRow>,
        pub channel_rows: Vec<MessageRow>,
        pub wire_rows: Vec<MessageRow>,
        pub inbox_calls: Mutex<Vec<(String, i64)>>,
        pub sent_calls: Mutex<Vec<(String, i64)>>,
        pub channel_calls: Mutex<Vec<(String, i64)>>,
        pub wire_calls: Mutex<Vec<(String, i64)>>,
    }

    impl MailboxSource for MockMailboxSource {
        fn inbox(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
            self.inbox_calls
                .lock()
                .unwrap()
                .push((agent_id.into(), after_id));
            Ok(self.inbox_rows.clone())
        }

        fn sent(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
            self.sent_calls
                .lock()
                .unwrap()
                .push((agent_id.into(), after_id));
            Ok(self.sent_rows.clone())
        }

        fn channel_feed(&self, agent_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
            self.channel_calls
                .lock()
                .unwrap()
                .push((agent_id.into(), after_id));
            Ok(self.channel_rows.clone())
        }

        fn wire(&self, project_id: &str, after_id: i64) -> Result<Vec<MessageRow>> {
            self.wire_calls
                .lock()
                .unwrap()
                .push((project_id.into(), after_id));
            Ok(self.wire_rows.clone())
        }
    }
}

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

    fn row(id: i64, sender: &str, recipient: &str, text: &str) -> MessageRow {
        MessageRow {
            id,
            sender: sender.into(),
            recipient: recipient.into(),
            text: text.into(),
            sent_at: 0.0,
        }
    }

    #[test]
    fn all_is_inbox_and_sent_only() {
        // #462: Channel/Wire are no longer user tabs.
        assert_eq!(MailboxTab::ALL, [MailboxTab::Inbox, MailboxTab::Sent]);
    }

    #[test]
    fn next_toggles_between_inbox_and_sent() {
        // #462: two user tabs → next is a straight toggle.
        let mut t = MailboxTab::Inbox;
        t = t.next();
        assert_eq!(t, MailboxTab::Sent);
        t = t.next();
        assert_eq!(t, MailboxTab::Inbox);
    }

    #[test]
    fn prev_toggles_between_inbox_and_sent() {
        let mut t = MailboxTab::Inbox;
        t = t.prev();
        assert_eq!(t, MailboxTab::Sent);
        t = t.prev();
        assert_eq!(t, MailboxTab::Inbox);
    }

    #[test]
    fn internal_channel_wire_variants_fold_to_inbox_on_cycle() {
        // The folded-in internal variants are never the active tab, but
        // if cycling ever lands on one it must escape to a real tab, not
        // strand the cursor on a non-tab.
        assert_eq!(MailboxTab::Channel.next(), MailboxTab::Inbox);
        assert_eq!(MailboxTab::Wire.next(), MailboxTab::Inbox);
        assert_eq!(MailboxTab::Channel.prev(), MailboxTab::Inbox);
        assert_eq!(MailboxTab::Wire.prev(), MailboxTab::Inbox);
    }

    #[test]
    fn extend_appends_and_bumps_cursor() {
        let mut buf = MailboxBuffers::default();
        buf.extend(
            MailboxTab::Inbox,
            vec![row(7, "p:m", "p:dev", "hi"), row(8, "p:m", "p:dev", "yo")],
        );
        assert_eq!(buf.inbox.len(), 2);
        assert_eq!(buf.inbox_after, 8);
        // Empty batch must not move the cursor backward.
        buf.extend(MailboxTab::Inbox, vec![]);
        assert_eq!(buf.inbox_after, 8);
    }

    #[test]
    fn extend_trims_to_cap() {
        let mut buf = MailboxBuffers::default();
        let batch: Vec<MessageRow> = (1..=600).map(|i| row(i, "p:m", "p:dev", "x")).collect();
        buf.extend(MailboxTab::Wire, batch);
        assert_eq!(buf.wire.len(), MAX_TAB_ROWS);
        // Cap keeps the *latest* rows — the cursor reflects the
        // batch's actual high-water id, not the trimmed buffer's
        // first row.
        assert_eq!(buf.wire_after, 600);
        assert_eq!(buf.wire.last().unwrap().id, 600);
    }

    #[test]
    fn reset_clears_buffers_and_cursors() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, vec![row(3, "a", "b", "x")]);
        buf.extend(MailboxTab::Channel, vec![row(4, "a", "channel:p:all", "y")]);
        buf.reset();
        assert!(buf.inbox.is_empty());
        assert!(buf.channel.is_empty());
        assert_eq!(buf.inbox_after, 0);
        assert_eq!(buf.channel_after, 0);
    }

    #[test]
    fn inbox_merges_inbound_channel_and_wire_sorted_excluding_self() {
        // #462: the Inbox tab folds inbound DMs + channel + wire,
        // time-ordered by id, with self-sent broadcasts dropped (they
        // live under Sent).
        let buf = MailboxBuffers {
            agent_id: "p:m".to_string(),
            inbox: vec![row(2, "p:dev", "p:m", "dm")],
            channel: vec![
                row(1, "p:dev", "channel:p:eng", "chan inbound"),
                row(4, "p:m", "channel:p:eng", "chan from me"), // self → dropped
            ],
            wire: vec![
                row(3, "p:ops", "channel:p:all", "wire inbound"),
                row(5, "p:m", "channel:p:all", "wire from me"), // self → dropped
            ],
            ..Default::default()
        };
        let inbox = buf.rows(MailboxTab::Inbox);
        let ids: Vec<i64> = inbox.iter().map(|r| r.id).collect();
        assert_eq!(ids, vec![1, 2, 3], "inbound DM+channel+wire, id-sorted");
        // The raw Channel/Wire buffers are untouched — they still back
        // the MailboxFirst feed and hold the self rows.
        assert_eq!(buf.rows(MailboxTab::Channel).len(), 2);
        assert_eq!(buf.rows(MailboxTab::Wire).len(), 2);
    }

    #[test]
    fn inbox_dedups_all_channel_wire_overlap() {
        // The `all` channel is membership-joined by every agent, so an
        // `all` broadcast lands in BOTH the channel buffer (via the
        // membership query) and the wire buffer — the same id via two
        // paths. The merged Inbox must show it once, not twice.
        let dup = row(7, "p:dev", "channel:p:all", "release cut");
        let buf = MailboxBuffers {
            agent_id: "p:m".to_string(),
            channel: vec![dup.clone()],
            wire: vec![dup],
            ..Default::default()
        };
        let ids: Vec<i64> = buf.rows(MailboxTab::Inbox).iter().map(|r| r.id).collect();
        assert_eq!(ids, vec![7], "the all-channel broadcast appears once");
    }

    #[test]
    fn inbox_merge_is_noop_filter_before_agent_id_set() {
        // Empty `agent_id` only co-occurs with empty buffers in
        // production (`reset` clears both, and `refresh_mailbox` sets
        // the id before any extend), so the no-op `sender != ""` filter
        // is unobservable there. Pinned defensively: even hand-fed a
        // self row with no agent_id, the merge drops nothing rather than
        // panicking or losing a row.
        let buf = MailboxBuffers {
            channel: vec![row(1, "p:m", "channel:p:eng", "self")],
            ..Default::default()
        };
        assert_eq!(buf.rows(MailboxTab::Inbox).len(), 1);
    }

    #[test]
    fn inbox_cursor_follows_channel_wire_arrivals_only_when_at_tail() {
        // The merged Inbox grows when channel/wire rows arrive, not just
        // DMs. The refresh re-anchor (inbox_at_tail + follow_inbox_tail)
        // keeps a tail-following cursor on the newest row — but must not
        // yank a scrolled-up cursor (#462).
        let mut buf = MailboxBuffers {
            agent_id: "p:m".to_string(),
            inbox: vec![row(1, "p:dev", "p:m", "dm one")],
            ..Default::default()
        };
        assert!(buf.inbox_at_tail(), "single row → at tail");
        // A channel arrival while following the tail.
        let was_at_tail = buf.inbox_at_tail();
        buf.extend(
            MailboxTab::Channel,
            vec![row(2, "p:dev", "channel:p:eng", "later")],
        );
        if was_at_tail {
            buf.follow_inbox_tail();
        }
        assert_eq!(
            buf.inbox_cursor.selected_idx, 1,
            "cursor tracked the channel arrival"
        );
        // Now scrolled up: a wire arrival must NOT pull the cursor down.
        buf.inbox_cursor.selected_idx = 0;
        let was_at_tail = buf.inbox_at_tail();
        buf.extend(
            MailboxTab::Wire,
            vec![row(3, "p:ops", "channel:p:all", "broadcast")],
        );
        if was_at_tail {
            buf.follow_inbox_tail();
        }
        assert_eq!(
            buf.inbox_cursor.selected_idx, 0,
            "scrolled-up cursor stays put"
        );
    }

    fn empty_team() -> crate::data::TeamSnapshot {
        crate::data::TeamSnapshot::empty(std::path::PathBuf::from("/tmp"))
    }

    #[test]
    fn render_row_flattens_newlines_and_truncates() {
        let team = empty_team();
        let r = row(1, "p:m", "p:dev", "first\nsecond\nthird");
        assert_eq!(
            render_row(&r, &team, MailboxTab::Inbox),
            "[p:m] first second third"
        );

        let long: String = "x".repeat(300);
        let r = row(1, "s", "r", &long);
        let rendered = render_row(&r, &team, MailboxTab::Inbox);
        // 5 chars ("[s] ") + at most 180 chars of body = 185.
        assert!(rendered.chars().count() <= 185);
    }

    #[test]
    fn render_row_inbox_disambiguates_channel_from_dm() {
        // #462: a folded-in channel/wire row keeps the `[#chan]
        // [sender]` T-249 shape; a DM stays `[sender]` so the two are
        // distinguishable now that they share the Inbox.
        let team = empty_team();
        let dm = row(1, "p:dev", "p:m", "direct");
        assert_eq!(render_row(&dm, &team, MailboxTab::Inbox), "[p:dev] direct");
        let chan = row(2, "p:dev", "channel:p:eng", "in channel");
        assert_eq!(
            render_row(&chan, &team, MailboxTab::Inbox),
            "[#eng] [p:dev] in channel"
        );
        let wire = row(3, "p:ops", "channel:p:all", "broadcast");
        assert_eq!(
            render_row(&wire, &team, MailboxTab::Inbox),
            "[#all] [p:ops] broadcast"
        );
    }

    #[test]
    fn render_row_uses_display_name_when_set() {
        // T-160: when the sender id has a `display_name` in the team
        // snapshot, the mailbox row renders the label, not the id.
        // Unknown senders fall through to the raw id (covered above).
        use crate::data::{AgentInfo, TeamSnapshot};
        use team_core::supervisor::AgentState;
        let agent = AgentInfo {
            id: "p:sage".into(),
            agent: "sage".into(),
            project: "p".into(),
            tmux_session: "a-p-sage".into(),
            state: AgentState::Unknown,
            unread_mail: 0,
            pending_approvals: 0,
            is_manager: true,
            display_name: Some("Sage (Visionary)".into()),
            rate_limit_resets_at: None,
            last_activity_at: None,
            reports_to: None,
        };
        let team = TeamSnapshot {
            root: std::path::PathBuf::from("/tmp"),
            team_name: "t".into(),
            agents: vec![agent],
            channels: vec![],
        };
        let r = row(1, "p:sage", "p:hugo", "ping");
        assert_eq!(
            render_row(&r, &team, MailboxTab::Inbox),
            "[Sage (Visionary)] ping"
        );
    }

    // T-231: tab-aware prefix — Sent shows recipient, others show
    // sender. These pin the contract the operator-visible UX rests on.

    #[test]
    fn render_row_sent_tab_shows_recipient_with_arrow() {
        // Sent rows have the focused agent as sender (constant);
        // recipient is the disambiguating column. Verify the arrow
        // glyph + recipient appear in place of the sender.
        let team = empty_team();
        let r = row(1, "p:me", "p:dev", "ack");
        assert_eq!(render_row(&r, &team, MailboxTab::Sent), "[→p:dev] ack");
    }

    #[test]
    fn render_row_sent_tab_resolves_recipient_display_name() {
        // Same display-name resolution as the Inbox path — the
        // recipient's label, not the raw id, when the team snapshot
        // has a display_name for them.
        use crate::data::{AgentInfo, TeamSnapshot};
        use team_core::supervisor::AgentState;
        let agent = AgentInfo {
            id: "p:hugo".into(),
            agent: "hugo".into(),
            project: "p".into(),
            tmux_session: "a-p-hugo".into(),
            state: AgentState::Running,
            unread_mail: 0,
            pending_approvals: 0,
            is_manager: true,
            display_name: Some("Hugo (PM)".into()),
            rate_limit_resets_at: None,
            last_activity_at: None,
            reports_to: None,
        };
        let team = TeamSnapshot {
            root: std::path::PathBuf::from("/tmp"),
            team_name: "t".into(),
            agents: vec![agent],
            channels: vec![],
        };
        let r = row(1, "p:sage", "p:hugo", "ping");
        assert_eq!(render_row(&r, &team, MailboxTab::Sent), "[→Hugo (PM)] ping");
    }

    #[test]
    fn render_row_sent_tab_renders_channel_recipient_with_hash() {
        // Broadcast-to-channel rows have `recipient = channel:<id>`.
        // The Sent prefix should render as `→#<short>` — operators
        // recognize `#dev`, not `channel:teamctl:dev`.
        let team = empty_team();
        let r = row(1, "p:me", "channel:teamctl:dev", "rolling 0.8.3");
        assert_eq!(
            render_row(&r, &team, MailboxTab::Sent),
            "[→#dev] rolling 0.8.3"
        );
    }

    #[test]
    fn render_row_sent_tab_renders_user_recipient_verbatim() {
        // Telegram-bound `reply_to_user` rows have `recipient = user:telegram`.
        // No special prefix-stripping — operators already recognize
        // the `user:*` shape and dropping the prefix would lose the
        // "this went to the operator" signal.
        let team = empty_team();
        let r = row(1, "p:mgr", "user:telegram", "PR url");
        assert_eq!(
            render_row(&r, &team, MailboxTab::Sent),
            "[→user:telegram] PR url"
        );
    }

    #[test]
    fn render_row_non_sent_tabs_still_show_sender() {
        // Inbox / Wire prefix is the sender. Channel has its own
        // two-segment shape pinned in the T-249 tests below.
        let team = empty_team();
        let r = row(1, "p:from", "p:me", "yo");
        assert_eq!(render_row(&r, &team, MailboxTab::Inbox), "[p:from] yo");
        assert_eq!(render_row(&r, &team, MailboxTab::Wire), "[p:from] yo");
    }

    // T-249: Channel tab — two bracketed segments, channel then sender.
    // The disambiguator the operator needs is "which channel was this
    // posted in", because the tab folds every subscribed channel into
    // a single feed.

    #[test]
    fn render_row_channel_tab_prefixes_channel_name_and_sender() {
        let team = empty_team();
        let r = row(1, "p:from", "channel:teamctl:dev", "yo");
        assert_eq!(
            render_row(&r, &team, MailboxTab::Channel),
            "[#dev] [p:from] yo"
        );
    }

    #[test]
    fn render_row_channel_tab_resolves_sender_display_name() {
        // Sender resolution mirrors the Inbox path — display_name
        // when set on the team snapshot, raw id otherwise. Channel
        // name resolution is independent.
        use crate::data::{AgentInfo, TeamSnapshot};
        use team_core::supervisor::AgentState;
        let agent = AgentInfo {
            id: "p:wren".into(),
            agent: "wren".into(),
            project: "p".into(),
            tmux_session: "a-p-wren".into(),
            state: AgentState::Running,
            unread_mail: 0,
            pending_approvals: 0,
            is_manager: false,
            display_name: Some("Wren (Engineer)".into()),
            rate_limit_resets_at: None,
            last_activity_at: None,
            reports_to: None,
        };
        let team = TeamSnapshot {
            root: std::path::PathBuf::from("/tmp"),
            team_name: "t".into(),
            agents: vec![agent],
            channels: vec![],
        };
        let r = row(1, "p:wren", "channel:p:all", "hello");
        assert_eq!(
            render_row(&r, &team, MailboxTab::Channel),
            "[#all] [Wren (Engineer)] hello"
        );
    }

    #[test]
    fn render_row_channel_tab_handles_malformed_channel_recipient() {
        // Defensive — channel_feed SQL only returns rows shaped
        // `channel:<channel_id>`, but if a malformed value ever
        // lands (manual write, future schema shift), the row still
        // renders without panic. Pins recipient_label's malformed
        // fallback (matches T-231's parallel sent-tab test).
        let team = empty_team();
        let r = row(1, "p:from", "channel:malformed", "yo");
        assert_eq!(
            render_row(&r, &team, MailboxTab::Channel),
            "[#malformed] [p:from] yo"
        );
    }

    #[test]
    fn mock_records_calls() {
        let mock = MockMailboxSource {
            inbox_rows: vec![row(1, "p:m", "p:a", "hi")],
            ..Default::default()
        };
        let _ = mock.inbox("p:a", 0).unwrap();
        let _ = mock.sent("p:a", 2).unwrap();
        let _ = mock.channel_feed("p:a", 5).unwrap();
        let _ = mock.wire("p", 9).unwrap();
        assert_eq!(*mock.inbox_calls.lock().unwrap(), vec![("p:a".into(), 0)]);
        assert_eq!(*mock.sent_calls.lock().unwrap(), vec![("p:a".into(), 2)]);
        assert_eq!(*mock.channel_calls.lock().unwrap(), vec![("p:a".into(), 5)]);
        assert_eq!(*mock.wire_calls.lock().unwrap(), vec![("p".into(), 9)]);
    }

    // T-131 PR-1: cursor + visible_indices invariants.

    fn rows_n(n: i64) -> Vec<MessageRow> {
        (1..=n).map(|i| row(i, "p:m", "p:dev", "x")).collect()
    }

    #[test]
    fn visible_indices_is_identity_in_pr1() {
        // PR-1 invariant: visible_indices(tab) == (0..rows(tab).len()).
        // PR-2 swaps the body — this test guards the PR-1 baseline so
        // a PR-2 regression that breaks PR-1's identity assumption
        // surfaces here, not in a render call site downstream.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(5));
        assert_eq!(buf.visible_indices(MailboxTab::Inbox), vec![0, 1, 2, 3, 4]);
        assert!(buf.visible_indices(MailboxTab::Sent).is_empty());
    }

    #[test]
    fn extend_into_empty_seats_cursor_at_tail() {
        // Pre-T-131 UX was "tail to whatever fits"; the cursor seat
        // preserves it — a freshly-populated tab shows the latest row
        // selected, matching the existing snapshot expectations for
        // unfocused mailbox panes.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(7));
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 6);
    }

    #[test]
    fn extend_when_cursor_at_tail_follows_new_arrivals() {
        // Standard chat-app "follow tail" UX: as long as the operator
        // hasn't scrolled away, new messages keep the cursor at the
        // newest row.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(3));
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 2);
        buf.extend(
            MailboxTab::Inbox,
            vec![row(4, "p:m", "p:dev", "x"), row(5, "p:m", "p:dev", "x")],
        );
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 4);
    }

    #[test]
    fn extend_when_cursor_scrolled_up_does_not_follow() {
        // Operator inspecting older history shouldn't be yanked back
        // to the tail by a new arrival — the cursor is sticky once it
        // leaves the tail.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(5));
        buf.cursor_home(MailboxTab::Inbox); // selected_idx = 0
        buf.extend(MailboxTab::Inbox, vec![row(6, "p:m", "p:dev", "x")]);
        assert_eq!(
            buf.cursor(MailboxTab::Inbox).selected_idx,
            0,
            "scrolled-up cursor must not jump on new arrival"
        );
    }

    #[test]
    fn extend_reclamps_cursor_after_drain() {
        // The MAX_TAB_ROWS drain shifts indices — a cursor that was
        // valid pre-drain must be re-clamped against the new visible
        // length so render never indexes past the buffer.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(MAX_TAB_ROWS as i64));
        buf.cursor_home(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
        // Push another batch large enough to drain off the front.
        let next: Vec<MessageRow> = (501..=510).map(|i| row(i, "p:m", "p:dev", "x")).collect();
        buf.extend(MailboxTab::Inbox, next);
        let visible = buf.visible_indices(MailboxTab::Inbox);
        assert_eq!(visible.len(), MAX_TAB_ROWS);
        assert!(
            buf.cursor(MailboxTab::Inbox).selected_idx < visible.len(),
            "post-drain cursor must stay in range; got {}, visible.len {}",
            buf.cursor(MailboxTab::Inbox).selected_idx,
            visible.len()
        );
    }

    #[test]
    fn move_cursor_down_and_up_clamp_at_ends() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(3)); // cursor seated at 2
        buf.move_cursor_down(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 2, "tail clamps");
        buf.move_cursor_up(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 1);
        buf.move_cursor_up(MailboxTab::Inbox);
        buf.move_cursor_up(MailboxTab::Inbox);
        buf.move_cursor_up(MailboxTab::Inbox); // extra up at 0 is no-op
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0, "head clamps");
    }

    #[test]
    fn page_cursor_jumps_a_screen() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(50));
        buf.cursor_home(MailboxTab::Inbox);
        buf.page_cursor_down(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, PAGE_JUMP);
        buf.page_cursor_down(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 2 * PAGE_JUMP);
        buf.page_cursor_up(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, PAGE_JUMP);
        // PageDown past the tail clamps.
        for _ in 0..20 {
            buf.page_cursor_down(MailboxTab::Inbox);
        }
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 49);
        // PageUp past the head clamps.
        for _ in 0..20 {
            buf.page_cursor_up(MailboxTab::Inbox);
        }
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
    }

    #[test]
    fn cursor_home_and_end_jump_to_ends() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(20));
        buf.cursor_home(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
        buf.cursor_end(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 19);
    }

    #[test]
    fn cursors_are_per_tab_and_independent() {
        // Issue AC: "Scrolling is per-tab — Inbox/Sent/Channel/Wire
        // each remember their own position."
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(10));
        buf.extend(MailboxTab::Sent, rows_n(10));
        buf.cursor_home(MailboxTab::Inbox); // Inbox cursor at 0
                                            // Sent cursor stays at its post-extend tail (idx 9).
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
        assert_eq!(buf.cursor(MailboxTab::Sent).selected_idx, 9);
        // And channel/wire are still at 0 with empty buffers.
        assert_eq!(buf.cursor(MailboxTab::Channel).selected_idx, 0);
        assert_eq!(buf.cursor(MailboxTab::Wire).selected_idx, 0);
    }

    #[test]
    fn reset_clears_cursors_too() {
        // Reset is called when the focused agent changes; the new
        // agent's mailbox starts from a clean slate, cursor at 0.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, rows_n(5));
        buf.cursor_home(MailboxTab::Inbox);
        buf.move_cursor_down(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 1);
        buf.reset();
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
        assert_eq!(buf.cursor(MailboxTab::Sent).selected_idx, 0);
    }

    #[test]
    fn cursor_methods_are_safe_on_empty_buffer() {
        // No rows yet — every cursor method must be a no-op on
        // selected_idx = 0 rather than panic.
        let mut buf = MailboxBuffers::default();
        buf.move_cursor_down(MailboxTab::Inbox);
        buf.move_cursor_up(MailboxTab::Inbox);
        buf.page_cursor_down(MailboxTab::Inbox);
        buf.page_cursor_up(MailboxTab::Inbox);
        buf.cursor_home(MailboxTab::Inbox);
        buf.cursor_end(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
    }

    // T-131 PR-2: filter + search semantics.

    fn mixed_rows() -> Vec<MessageRow> {
        vec![
            row(1, "p:ada", "p:dev", "ready for review"),
            row(2, "p:kian", "p:dev", "release pipeline notes"),
            row(3, "p:ada", "p:dev", "shipping the patch"),
            row(4, "user:telegram", "p:dev", "any blockers?"),
            row(5, "p:kian", "p:dev", "Release smoke green"),
        ]
    }

    #[test]
    fn visible_indices_identity_when_no_filter_no_search() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        assert_eq!(
            buf.visible_indices(MailboxTab::Inbox),
            vec![0, 1, 2, 3, 4],
            "no filter + no search must recover PR-1 identity exactly"
        );
    }

    #[test]
    fn filter_restricts_to_sender_substring_case_insensitive() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        buf.set_input(MailboxTab::Inbox, MailboxInputKind::Filter, "ADA".into());
        assert_eq!(
            buf.visible_indices(MailboxTab::Inbox),
            vec![0, 2],
            "filter `ADA` (case-insensitive) must match `p:ada` rows only"
        );
    }

    #[test]
    fn search_restricts_to_body_substring_case_insensitive() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        buf.set_input(
            MailboxTab::Inbox,
            MailboxInputKind::Search,
            "release".into(),
        );
        assert_eq!(
            buf.visible_indices(MailboxTab::Inbox),
            vec![1, 4],
            "search `release` must match both `release pipeline notes` and \
             `Release smoke green` case-insensitively"
        );
    }

    #[test]
    fn filter_and_search_compose_via_intersection() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        buf.set_input(MailboxTab::Inbox, MailboxInputKind::Filter, "kian".into());
        buf.set_input(
            MailboxTab::Inbox,
            MailboxInputKind::Search,
            "release".into(),
        );
        assert_eq!(
            buf.visible_indices(MailboxTab::Inbox),
            vec![1, 4],
            "filter `kian` ∩ search `release` must keep only kian's release rows"
        );
        // Pin "compose" semantics: each axis on its own would be a
        // superset; intersection is strictly smaller-or-equal.
        let only_filter = {
            let mut b = MailboxBuffers::default();
            b.extend(MailboxTab::Inbox, mixed_rows());
            b.set_input(MailboxTab::Inbox, MailboxInputKind::Filter, "kian".into());
            b.visible_indices(MailboxTab::Inbox)
        };
        assert_eq!(only_filter, vec![1, 4]); // here filter alone happens to coincide
    }

    #[test]
    fn empty_axis_is_noop() {
        // The empty-input contract: empty = clear that axis. Issue AC.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        // Set then clear filter — visible_indices returns to identity.
        buf.set_input(MailboxTab::Inbox, MailboxInputKind::Filter, "ada".into());
        assert_eq!(buf.visible_indices(MailboxTab::Inbox), vec![0, 2]);
        buf.set_input(MailboxTab::Inbox, MailboxInputKind::Filter, String::new());
        assert_eq!(
            buf.visible_indices(MailboxTab::Inbox),
            vec![0, 1, 2, 3, 4],
            "clearing the filter must restore identity"
        );
    }

    #[test]
    fn input_push_pop_updates_visible_and_clamps_cursor() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows()); // cursor lands at 4 (tail)
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 4);
        // Type `a`-`d`-`a` → filter shrinks visible to {0, 2}, len 2.
        // The cursor was at 4 (out of range for the shorter list), so
        // clamp_cursor must bring it to len-1 = 1.
        buf.input_push_char(MailboxTab::Inbox, MailboxInputKind::Filter, 'a');
        buf.input_push_char(MailboxTab::Inbox, MailboxInputKind::Filter, 'd');
        buf.input_push_char(MailboxTab::Inbox, MailboxInputKind::Filter, 'a');
        assert_eq!(buf.filter_text(MailboxTab::Inbox), "ada");
        assert_eq!(buf.visible_indices(MailboxTab::Inbox), vec![0, 2]);
        assert_eq!(
            buf.cursor(MailboxTab::Inbox).selected_idx,
            1,
            "cursor must clamp to the shorter visible_indices len-1"
        );
        // Backspace twice → filter becomes `a`, visible widens but
        // cursor stays where it landed (in range).
        buf.input_pop_char(MailboxTab::Inbox, MailboxInputKind::Filter);
        buf.input_pop_char(MailboxTab::Inbox, MailboxInputKind::Filter);
        assert_eq!(buf.filter_text(MailboxTab::Inbox), "a");
    }

    #[test]
    fn filter_and_search_are_per_tab() {
        // Issue AC: "Filter state is per-tab." So is search.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        buf.extend(MailboxTab::Sent, mixed_rows());
        buf.set_input(MailboxTab::Inbox, MailboxInputKind::Filter, "ada".into());
        buf.set_input(MailboxTab::Sent, MailboxInputKind::Search, "release".into());
        assert_eq!(buf.filter_text(MailboxTab::Inbox), "ada");
        assert_eq!(buf.filter_text(MailboxTab::Sent), "");
        assert_eq!(buf.search_text(MailboxTab::Inbox), "");
        assert_eq!(buf.search_text(MailboxTab::Sent), "release");
        assert_eq!(buf.visible_indices(MailboxTab::Inbox), vec![0, 2]);
        assert_eq!(buf.visible_indices(MailboxTab::Sent), vec![1, 4]);
    }

    #[test]
    fn reset_clears_filter_and_search() {
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        buf.set_input(MailboxTab::Inbox, MailboxInputKind::Filter, "ada".into());
        buf.set_input(MailboxTab::Inbox, MailboxInputKind::Search, "ship".into());
        buf.reset();
        assert_eq!(buf.filter_text(MailboxTab::Inbox), "");
        assert_eq!(buf.search_text(MailboxTab::Inbox), "");
        assert!(buf.rows(MailboxTab::Inbox).is_empty());
    }

    #[test]
    fn empty_visible_keeps_cursor_at_zero_not_panic() {
        // Filter that matches no rows yields empty visible_indices.
        // clamp_cursor must leave cursor at 0 rather than underflow.
        let mut buf = MailboxBuffers::default();
        buf.extend(MailboxTab::Inbox, mixed_rows());
        buf.set_input(
            MailboxTab::Inbox,
            MailboxInputKind::Filter,
            "no-such-sender".into(),
        );
        assert!(buf.visible_indices(MailboxTab::Inbox).is_empty());
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
        // Cursor methods on an empty visible set must not panic.
        buf.move_cursor_down(MailboxTab::Inbox);
        buf.move_cursor_up(MailboxTab::Inbox);
        buf.cursor_end(MailboxTab::Inbox);
        assert_eq!(buf.cursor(MailboxTab::Inbox).selected_idx, 0);
    }

    // T-131 PR-3: kind_label + transport_label derivation.

    #[test]
    fn kind_label_distinguishes_dm_channel_wire() {
        let r = row(1, "p:a", "p:dev", "x"); // agent-to-agent DM
        assert_eq!(kind_label(&r), "DM");
        let r = row(1, "p:a", "user:telegram", "x"); // agent-to-user DM
        assert_eq!(kind_label(&r), "DM");
        let r = row(1, "p:a", "channel:p:dev", "x"); // named channel
        assert_eq!(kind_label(&r), "channel broadcast");
        let r = row(1, "p:a", "channel:p:all", "x"); // project-wide wire
        assert_eq!(kind_label(&r), "wire broadcast");
    }

    #[test]
    fn transport_label_heuristic_covers_documented_cases() {
        // Issue's "if discernible" — heuristic from sender prefix.
        let r = row(1, "user:telegram", "p:a", "x");
        assert_eq!(transport_label(&r), "via telegram");
        let r = row(1, "user:discord", "p:a", "x");
        assert_eq!(transport_label(&r), "via user");
        let r = row(1, "p:agent", "p:other", "x");
        assert_eq!(transport_label(&r), "via mcp");
        let r = row(1, "p:agent", "channel:p:dev", "x");
        assert_eq!(transport_label(&r), "via mcp"); // agent emit, recipient class doesn't matter
        let r = row(1, "weird-no-colon", "p:a", "x");
        assert_eq!(transport_label(&r), ""); // graceful degrade
    }

    // T-131 PR-4: row_timestamp today-fold tests. Owner ratified
    // (tg 3388) (1) today-fold YES + (2) 24h YES; silent defaults
    // intact (no seconds, local-TZ, past-day `%b %d %H:%M`). Tests
    // drive `row_timestamp_in(&Utc, …)` so the assertions are
    // timezone-stable regardless of the dev machine's `Local`.

    fn ts(year: i32, month: u32, day: u32, hour: u32, minute: u32, sec: u32) -> f64 {
        use chrono::TimeZone;
        chrono::Utc
            .with_ymd_and_hms(year, month, day, hour, minute, sec)
            .unwrap()
            .timestamp() as f64
    }

    #[test]
    fn row_timestamp_same_day_renders_24h_hhmm() {
        let now = ts(2026, 5, 22, 15, 42, 30);
        // Sent earlier today at 10:15:00 UTC: `10:15`.
        let sent = ts(2026, 5, 22, 10, 15, 0);
        assert_eq!(row_timestamp_in(&chrono::Utc, now, sent), "10:15");
        // Sent exactly now (truncates the :30 seconds): `15:42`.
        assert_eq!(row_timestamp_in(&chrono::Utc, now, now), "15:42");
        // Sent at exact midnight same day: `00:00`.
        let sent_midnight = ts(2026, 5, 22, 0, 0, 0);
        assert_eq!(row_timestamp_in(&chrono::Utc, now, sent_midnight), "00:00");
    }

    #[test]
    fn row_timestamp_prior_day_renders_b_d_hhmm() {
        let now = ts(2026, 5, 22, 15, 42, 30);
        // Yesterday: full `%b %d %H:%M` past-day format.
        let sent_yesterday = ts(2026, 5, 21, 23, 59, 0);
        assert_eq!(
            row_timestamp_in(&chrono::Utc, now, sent_yesterday),
            "May 21 23:59"
        );
        // A month earlier: same shape, different date.
        let sent_earlier_month = ts(2026, 4, 22, 12, 0, 0);
        assert_eq!(
            row_timestamp_in(&chrono::Utc, now, sent_earlier_month),
            "Apr 22 12:00"
        );
    }

    #[test]
    fn row_timestamp_future_send_uses_sent_timestamp() {
        // Clock skew or test fixture with `sent_at > now`. The
        // helper folds purely by date equality, so a future-send on
        // the same day still renders `HH:MM`; a future-send on a
        // later day renders that day's `%b %d %H:%M`. No special
        // negative handling — matches the simplicity-first model.
        let now = ts(2026, 5, 22, 15, 42, 30);
        let sent_future_same_day = ts(2026, 5, 22, 16, 42, 30);
        assert_eq!(
            row_timestamp_in(&chrono::Utc, now, sent_future_same_day),
            "16:42"
        );
        let sent_future_next_day = ts(2026, 5, 23, 15, 42, 30);
        assert_eq!(
            row_timestamp_in(&chrono::Utc, now, sent_future_next_day),
            "May 23 15:42"
        );
    }

    #[test]
    fn row_timestamp_zero_epoch_is_same_day_as_itself() {
        // Snapshot tests use `App::new` (now_secs=0.0) + fixture
        // rows (sent_at=0.0) — both map to the Unix epoch, same
        // day, format `HH:MM` deterministically across machines
        // (snapshots.rs sets TZ=UTC so `Local` resolves to UTC).
        assert_eq!(row_timestamp_in(&chrono::Utc, 0.0, 0.0), "00:00");
    }
}