teamctl-ui 0.7.2

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
//! Keystroke-driven integration tests for the TUI.
//!
//! `Harness` builds an `App` together with mock collaborators
//! (`MockMessageSender`, `MockApprovalDecider`, `EmptyMailbox`) once
//! at construction time so subsequent dispatches spy through the
//! same instances. T-079 sub-tickets layer real coverage on top of
//! the shorthands defined here — keep this file ergonomic.
//!
//! `dispatch_key` / `dispatch_key_mods` mirror the inline
//! `dispatch(app, ev)` shape from `app.rs` unit tests, lifted into
//! the integration layer through the now-public `app::handle_event`.
//!
//! Snapshots intentionally aren't asserted here — those live in
//! `tests/snapshots.rs`. This file pins state transitions; the
//! snapshot file pins what they render to.
//!
//! ## Convention
//!
//! Set up state via direct method calls (`h.app.dismiss_splash()`,
//! `h.app.replace_team(...)`, `h.app.select_next()`); exercise the
//! verb under test via `dispatch_key` so the production
//! `handle_event` routing is what's actually being asserted. That
//! keeps the keystroke surface area narrow and the test signal
//! sharp — a regression in `handle_event` shows up as a single
//! failing dispatch, not a wall of setup that has to be untangled.
//!
//! ## Adding a test
//!
//! Negative shape (state-transition only):
//!
//! ```ignore
//! let mut h = Harness::new();
//! h.app.replace_team(fixture_team("t", vec![synth_agent("t:m", AgentState::Running, 0, 0)]));
//! h.app.dismiss_splash();
//! h.dispatch_key(KeyCode::Char('@'));        // open DM compose
//! assert_eq!(h.app.stage, Stage::ComposeModal);
//! assert!(h.sender.dm_calls.lock().unwrap().is_empty());
//! ```
//!
//! Affirmative shape (recorder captured the call):
//!
//! ```ignore
//! // …open compose, type body, fire send chord…
//! let calls = h.sender.dm_calls.lock().unwrap();
//! assert_eq!(calls.len(), 1, "exactly one send fired");
//! assert_eq!(calls[0].0, "t:m", "DM target is the focused agent");
//! assert_eq!(calls[0].1, "hello", "captured body matches what was typed");
//! ```

use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
use team_core::supervisor::AgentState;
use teamctl_ui::app::{self, render_to_buffer, App, Stage};
use teamctl_ui::approvals::test_support::MockApprovalDecider;
use teamctl_ui::approvals::{Approval, Decision};
use teamctl_ui::compose::test_support::MockMessageSender;
use teamctl_ui::data::{AgentInfo, TeamSnapshot};
use teamctl_ui::mailbox::test_support::MockMailboxSource;
use teamctl_ui::triptych::{MainLayout, Pane};

/// Harness binds an `App` to its mock collaborators so every
/// `dispatch_key` reaches the same recorders. Construct with
/// `Harness::new()`; seed a team via `app.replace_team(...)` when
/// the test needs roster state. The mailbox source is a recorder —
/// `MockMailboxSource::default()` returns empty rows on every
/// query, but tests that exercise mailbox traffic can seed
/// `h.mailbox.inbox_rows` (etc.) before driving a refresh and then
/// inspect `h.mailbox.inbox_calls.lock()` to verify the right filter
/// was queried with the right (agent_id, after_id) pair.
pub struct Harness {
    pub app: App,
    pub sender: MockMessageSender,
    pub decider: MockApprovalDecider,
    pub mailbox: MockMailboxSource,
}

impl Harness {
    /// Build a fresh App + default mocks. `NO_COLOR` is set so any
    /// downstream snapshot capture stays monochrome (matches the
    /// `tests/snapshots.rs` convention).
    pub fn new() -> Self {
        std::env::set_var("NO_COLOR", "1");
        Self {
            app: App::new(),
            sender: MockMessageSender::default(),
            decider: MockApprovalDecider::default(),
            mailbox: MockMailboxSource::default(),
        }
    }

    /// Dispatch a single key (no modifiers) through the production
    /// `handle_event` routing, with the harness's mocks captured.
    pub fn dispatch_key(&mut self, code: KeyCode) {
        self.dispatch_key_mods(code, KeyModifiers::NONE);
    }

    /// Dispatch a single key with modifiers — for `Ctrl+W`,
    /// `Shift+Tab`, etc.
    pub fn dispatch_key_mods(&mut self, code: KeyCode, modifiers: KeyModifiers) {
        let ev = Event::Key(KeyEvent {
            code,
            modifiers,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        });
        app::handle_event(
            &mut self.app,
            ev,
            &self.decider,
            &self.sender,
            &self.mailbox,
        );
    }
}

impl Default for Harness {
    fn default() -> Self {
        Self::new()
    }
}

/// Build an `AgentInfo` row from a `project:agent` id string —
/// lifted from `tests/snapshots.rs::synth_agent` so test authors
/// don't have to assemble the struct by hand.
pub fn synth_agent(id: &str, state: AgentState, unread: u32, pending: u32) -> AgentInfo {
    let (project, agent) = id.split_once(':').unwrap_or(("p", id));
    AgentInfo {
        id: id.into(),
        agent: agent.into(),
        project: project.into(),
        tmux_session: format!("t-{}-{}", project, agent),
        state,
        unread_mail: unread,
        pending_approvals: pending,
        is_manager: false,
    }
}

/// Build a `TeamSnapshot` with a fixture root path. Lifted from
/// `tests/snapshots.rs::fixture_team`.
pub fn fixture_team(team_name: &str, agents: Vec<AgentInfo>) -> TeamSnapshot {
    TeamSnapshot {
        root: std::path::PathBuf::from("/fixture"),
        team_name: team_name.into(),
        agents,
        channels: Vec::new(),
    }
}

// ── Demonstrator tests ──────────────────────────────────────────

#[test]
fn splash_dismisses_on_any_key() {
    // Splash is the boot stage; any keypress drops to Triptych. The
    // production handler routes every Splash-stage key through
    // `dismiss_splash()` regardless of code, so a single space is
    // enough to pin the contract.
    let mut h = Harness::new();
    assert_eq!(h.app.stage, Stage::Splash);
    h.dispatch_key(KeyCode::Char(' '));
    assert_eq!(h.app.stage, Stage::Triptych);
}

#[test]
fn tab_cycles_focus_through_panes() {
    // Tab walks Roster → Detail → Mailbox → Roster uniformly. The
    // wrap back to Roster is load-bearing — it's the bug T-074
    // shipped a fix for, and the integration test layer needs to
    // catch any future regression.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    assert_eq!(h.app.focused_pane, Pane::Roster);

    h.dispatch_key(KeyCode::Tab);
    assert_eq!(h.app.focused_pane, Pane::Detail);

    h.dispatch_key(KeyCode::Tab);
    assert_eq!(h.app.focused_pane, Pane::Mailbox);

    h.dispatch_key(KeyCode::Tab);
    assert_eq!(
        h.app.focused_pane,
        Pane::Roster,
        "Tab from Mailbox wraps back to Roster"
    );
}

#[test]
fn compose_modal_opens_via_at_key_without_sending() {
    // Wires the MockMessageSender end-to-end: a fixture team is
    // seeded, the operator picks an agent, `@` opens DM compose
    // pointed at that agent. Crucially, opening the modal does NOT
    // send — the recorder must still be empty. Subsequent T-079-B
    // tests will type a body + Enter and assert that the same
    // recorder captures the call.
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![
            synth_agent("writing:manager", AgentState::Running, 0, 0),
            synth_agent("writing:dev1", AgentState::Running, 0, 0),
        ],
    ));
    h.app.dismiss_splash();
    // Cursor lands on the first agent after replace_team; advance
    // once so the DM target is dev1, not manager.
    h.app.select_next();

    h.dispatch_key(KeyCode::Char('@'));

    assert_eq!(h.app.stage, Stage::ComposeModal);
    assert!(
        h.app.compose_target.is_some(),
        "compose_target seeded by `@`"
    );
    assert!(
        h.sender.dm_calls.lock().unwrap().is_empty(),
        "opening the modal must not trigger a send"
    );
    assert!(
        h.sender.broadcast_calls.lock().unwrap().is_empty(),
        "opening the modal must not trigger a broadcast"
    );
}

// ── T-079-B: DM compose flow coverage ───────────────────────────

/// Type a body into an open compose modal, one character at a time
/// through the public dispatcher. Each char goes through
/// `handle_event` → `editor.apply_key`, exactly mirroring what the
/// run loop sees from a real terminal.
fn type_body(h: &mut Harness, body: &str) {
    for c in body.chars() {
        h.dispatch_key(KeyCode::Char(c));
    }
}

/// Set up the canonical DM-flow fixture: a two-agent team with the
/// roster cursor parked on `dev1` and the splash dismissed. Returns
/// the harness so each test can drive the verb under test.
fn dm_compose_setup() -> Harness {
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![
            synth_agent("writing:manager", AgentState::Running, 0, 0),
            synth_agent("writing:dev1", AgentState::Running, 0, 0),
        ],
    ));
    h.app.dismiss_splash();
    h.app.select_next(); // park on dev1, not manager
    h
}

#[test]
fn dm_compose_sends_via_send_chord_with_focused_target_and_typed_body() {
    // The project-owner-reported affirmative path: open DM compose
    // for the focused agent, type a body, fire the send chord. The
    // mock sender must capture exactly one DM with the right
    // recipient and body. The send chord we drive here is the one a
    // real terminal can deliver — the historical `Ctrl+Enter` is
    // unreachable on standard terminals (xterm / Terminal.app /
    // tmux strip the Ctrl modifier on Enter), so the affirmative
    // path the operator actually uses is `Alt+Enter`.
    let mut h = dm_compose_setup();
    h.dispatch_key(KeyCode::Char('@'));
    assert_eq!(h.app.stage, Stage::ComposeModal);

    type_body(&mut h, "ready for review");
    h.dispatch_key_mods(KeyCode::Enter, KeyModifiers::ALT);

    let calls = h.sender.dm_calls.lock().unwrap();
    assert_eq!(calls.len(), 1, "exactly one DM should fire");
    assert_eq!(calls[0].0, "writing:dev1", "DM target is the focused agent");
    assert_eq!(
        calls[0].1, "ready for review",
        "body matches what was typed"
    );
    assert_eq!(
        h.app.stage,
        Stage::Triptych,
        "successful send closes the modal"
    );
    assert!(
        h.app.compose_target.is_none(),
        "compose target cleared on close"
    );
}

#[test]
fn dm_compose_blank_body_surfaces_error_and_does_not_send() {
    // Hitting send with no body must NOT fire the sender — the
    // modal stays open with `compose_error` populated so the
    // operator sees why nothing went out.
    let mut h = dm_compose_setup();
    h.dispatch_key(KeyCode::Char('@'));
    h.dispatch_key_mods(KeyCode::Enter, KeyModifiers::ALT);

    assert!(
        h.sender.dm_calls.lock().unwrap().is_empty(),
        "blank body must not reach the sender"
    );
    assert_eq!(
        h.app.stage,
        Stage::ComposeModal,
        "modal stays open on blank-body error"
    );
    assert!(
        h.app
            .compose_error
            .as_deref()
            .is_some_and(|e| e.contains("empty")),
        "compose_error should explain the no-send: got {:?}",
        h.app.compose_error
    );
}

#[test]
fn dm_compose_esc_esc_cancels_without_sending() {
    // Esc-Esc closes the modal without invoking the sender. The
    // editor consumes the first Esc to leave Insert mode, the
    // second Esc to fire EditorAction::Cancel.
    let mut h = dm_compose_setup();
    h.dispatch_key(KeyCode::Char('@'));
    type_body(&mut h, "draft");

    h.dispatch_key(KeyCode::Esc);
    h.dispatch_key(KeyCode::Esc);

    assert!(
        h.sender.dm_calls.lock().unwrap().is_empty(),
        "Esc-Esc must not fire the sender"
    );
    assert_eq!(h.app.stage, Stage::Triptych, "Esc-Esc closes the modal");
    assert!(
        h.app.compose_target.is_none(),
        "compose target cleared on cancel"
    );
}

#[test]
fn dm_compose_multi_line_body_is_sent_with_embedded_newline() {
    // Plain Enter inserts a newline (multi-line composition); the
    // send chord then ships the joined body. The captured payload
    // must preserve the embedded `\n` so downstream rendering
    // doesn't collapse the operator's intent.
    let mut h = dm_compose_setup();
    h.dispatch_key(KeyCode::Char('@'));
    type_body(&mut h, "line one");
    h.dispatch_key(KeyCode::Enter); // newline within Insert mode
    type_body(&mut h, "line two");
    h.dispatch_key_mods(KeyCode::Enter, KeyModifiers::ALT);

    let calls = h.sender.dm_calls.lock().unwrap();
    assert_eq!(calls.len(), 1, "multi-line send fires exactly once");
    assert_eq!(
        calls[0].1, "line one\nline two",
        "newline preserved in body"
    );
}

#[test]
fn dm_compose_target_follows_roster_selection_after_cancel() {
    // Cancel mid-compose, advance the roster cursor, reopen
    // compose. The new target must be the freshly-focused agent —
    // a stale target would silently DM the wrong person.
    let mut h = dm_compose_setup();
    // First open: cursor parked on dev1, cancel.
    h.dispatch_key(KeyCode::Char('@'));
    h.dispatch_key(KeyCode::Esc);
    h.dispatch_key(KeyCode::Esc);
    assert_eq!(h.app.stage, Stage::Triptych);

    // Advance to manager (wraps from dev1 → manager via select_next).
    h.app.select_next();
    h.dispatch_key(KeyCode::Char('@'));
    type_body(&mut h, "ping");
    h.dispatch_key_mods(KeyCode::Enter, KeyModifiers::ALT);

    let calls = h.sender.dm_calls.lock().unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(
        calls[0].0, "writing:manager",
        "DM follows the new roster selection, not the prior cancelled target"
    );
}

// ── Layout-switch coverage (T-079-C) ────────────────────────────
//
// Affirmative paths, return paths, cross-layout transitions, edge
// cases (focused pane, modal stages). The render-side assertions
// catch the "state flips but the view doesn't follow" failure mode
// — the project-owner-reported bug shape.

fn buffer_to_string(buf: &ratatui::buffer::Buffer) -> String {
    let area = buf.area();
    let mut out = String::with_capacity((area.width as usize + 1) * area.height as usize);
    for y in 0..area.height {
        for x in 0..area.width {
            let cell = &buf[(area.x + x, area.y + y)];
            out.push_str(cell.symbol());
        }
        out.push('\n');
    }
    out
}

#[test]
fn ctrl_w_switches_triptych_to_wall() {
    let mut h = Harness::new();
    h.app.dismiss_splash();
    assert_eq!(h.app.layout, MainLayout::Triptych);

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);

    assert_eq!(h.app.layout, MainLayout::Wall);
}

#[test]
fn ctrl_w_returns_wall_to_triptych() {
    let mut h = Harness::new();
    h.app.dismiss_splash();
    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);
    assert_eq!(h.app.layout, MainLayout::Wall);

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);

    assert_eq!(h.app.layout, MainLayout::Triptych);
}

#[test]
fn ctrl_m_switches_triptych_to_mailbox_first() {
    let mut h = Harness::new();
    h.app.dismiss_splash();
    assert_eq!(h.app.layout, MainLayout::Triptych);

    h.dispatch_key_mods(KeyCode::Char('m'), KeyModifiers::CONTROL);

    assert_eq!(h.app.layout, MainLayout::MailboxFirst);
}

#[test]
fn ctrl_m_returns_mailbox_first_to_triptych() {
    let mut h = Harness::new();
    h.app.dismiss_splash();
    h.dispatch_key_mods(KeyCode::Char('m'), KeyModifiers::CONTROL);
    assert_eq!(h.app.layout, MainLayout::MailboxFirst);

    h.dispatch_key_mods(KeyCode::Char('m'), KeyModifiers::CONTROL);

    assert_eq!(h.app.layout, MainLayout::Triptych);
}

#[test]
fn ctrl_m_from_wall_switches_to_mailbox_first() {
    // Cross-layout: operator in Wall hits Ctrl+M, expects to land
    // in MailboxFirst directly without a Triptych pit-stop.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);
    assert_eq!(h.app.layout, MainLayout::Wall);

    h.dispatch_key_mods(KeyCode::Char('m'), KeyModifiers::CONTROL);

    assert_eq!(h.app.layout, MainLayout::MailboxFirst);
}

#[test]
fn ctrl_w_from_mailbox_first_switches_to_wall() {
    let mut h = Harness::new();
    h.app.dismiss_splash();
    h.dispatch_key_mods(KeyCode::Char('m'), KeyModifiers::CONTROL);
    assert_eq!(h.app.layout, MainLayout::MailboxFirst);

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);

    assert_eq!(h.app.layout, MainLayout::Wall);
}

#[test]
fn ctrl_w_with_mailbox_pane_focused_still_switches_layout() {
    // Layout-switch must work regardless of which pane has focus —
    // Ctrl+W is a layout-level chord, not a pane-level one.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    h.dispatch_key(KeyCode::Tab);
    h.dispatch_key(KeyCode::Tab);
    assert_eq!(h.app.focused_pane, Pane::Mailbox);

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);

    assert_eq!(h.app.layout, MainLayout::Wall);
}

#[test]
fn compose_modal_blocks_layout_switch() {
    // The compose modal owns input — Ctrl+W must NOT bypass the
    // editor and flip the underlying main-view layout. Operator
    // would see a confused state ("modal is up but layout
    // changed") otherwise.
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![synth_agent("writing:manager", AgentState::Running, 0, 0)],
    ));
    h.app.dismiss_splash();
    h.dispatch_key(KeyCode::Char('@'));
    assert_eq!(h.app.stage, Stage::ComposeModal);

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);

    assert_eq!(
        h.app.layout,
        MainLayout::Triptych,
        "compose modal owns input — layout must not flip underneath"
    );
}

#[test]
fn quit_confirm_overlay_blocks_layout_switch() {
    let mut h = Harness::new();
    h.app.dismiss_splash();
    h.dispatch_key(KeyCode::Char('q'));
    assert_eq!(h.app.stage, Stage::QuitConfirm);

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);

    assert_eq!(
        h.app.layout,
        MainLayout::Triptych,
        "quit-confirm overlay must not be bypassed by layout chord"
    );
}

#[test]
fn rendered_buffer_reflects_wall_after_ctrl_w() {
    // The named bug shape: state flips but the rendered view
    // doesn't follow. Triptych shows ROSTER + MAILBOX pane titles;
    // Wall is a tile grid with no such pane chrome. If `app.layout`
    // is Wall but `render_to_buffer` still emits ROSTER/MAILBOX,
    // the user sees "switching layouts doesn't work."
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![
            synth_agent("writing:manager", AgentState::Running, 0, 0),
            synth_agent("writing:dev1", AgentState::Running, 0, 0),
        ],
    ));
    h.app.dismiss_splash();

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);
    assert_eq!(h.app.layout, MainLayout::Wall);

    let s = buffer_to_string(&render_to_buffer(&h.app, 120, 30));
    assert!(
        !s.contains("ROSTER"),
        "Wall buffer must not render the Triptych ROSTER pane title:\n{s}"
    );
    assert!(
        !s.contains("MAILBOX"),
        "Wall buffer must not render the Triptych MAILBOX pane title:\n{s}"
    );
}

#[test]
fn rendered_buffer_reflects_mailbox_first_after_ctrl_m() {
    // Same shape for the MailboxFirst layout — the failure mode
    // covered here is the project-owner-reported "switching
    // layouts doesn't work" surface for Ctrl+M.
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![synth_agent("writing:manager", AgentState::Running, 0, 0)],
    ));
    h.app.dismiss_splash();

    h.dispatch_key_mods(KeyCode::Char('m'), KeyModifiers::CONTROL);
    assert_eq!(h.app.layout, MainLayout::MailboxFirst);

    let s = buffer_to_string(&render_to_buffer(&h.app, 120, 30));
    assert!(
        !s.contains("ROSTER"),
        "MailboxFirst buffer must not render the Triptych ROSTER pane title:\n{s}"
    );
    assert!(
        !s.contains("DETAIL"),
        "MailboxFirst buffer must not render the Triptych DETAIL pane title:\n{s}"
    );
}

#[test]
fn ctrl_shift_w_still_toggles_wall_layout() {
    // The project-owner-reported "switching layouts doesn't work"
    // surface. With CapsLock on, or with Shift held alongside
    // Ctrl, crossterm reports `KeyCode::Char('W')` (uppercase)
    // with `CONTROL` (and possibly `SHIFT`) modifiers. The current
    // routing only matches lowercase `Char('w')`, so the chord
    // dies silently and the operator sees a no-op. Layout chord
    // must accept either casing — the user's intent is "Ctrl
    // plus the W key," not "the lowercase glyph 'w'."
    let mut h = Harness::new();
    h.app.dismiss_splash();

    h.dispatch_key_mods(
        KeyCode::Char('W'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );

    assert_eq!(h.app.layout, MainLayout::Wall);
}

#[test]
fn ctrl_shift_m_still_toggles_mailbox_first_layout() {
    // Mirror of the Ctrl+W case for Ctrl+M — same root cause,
    // same fix surface.
    let mut h = Harness::new();
    h.app.dismiss_splash();

    h.dispatch_key_mods(
        KeyCode::Char('M'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );

    assert_eq!(h.app.layout, MainLayout::MailboxFirst);
}

#[test]
fn ctrl_w_with_detail_split_open_arms_chord_not_layout() {
    // Documented PR-UI-7 behaviour pinned: when there's at least
    // one detail split, Ctrl+W arms the close-split chord prefix
    // rather than toggling the Wall layout. The chord follows
    // with `q` (close focused split) or `o` (close others).
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![synth_agent("writing:manager", AgentState::Running, 0, 0)],
    ));
    h.app.dismiss_splash();
    h.dispatch_key_mods(KeyCode::Char('|'), KeyModifiers::CONTROL);
    assert_eq!(h.app.detail_splits.len(), 1);

    h.dispatch_key_mods(KeyCode::Char('w'), KeyModifiers::CONTROL);

    assert_eq!(
        h.app.pending_chord,
        Some(KeyCode::Char('w')),
        "Ctrl+W with splits arms the chord prefix"
    );
    assert_eq!(
        h.app.layout,
        MainLayout::Triptych,
        "Ctrl+W with splits must not flip layout (chord wins)"
    );
}

// ── Approvals modal coverage (T-079-D) ──────────────────────────
//
// Drive: `a` to enter when there's a pending row, j/k (or arrows)
// to navigate, `y` / `Y` approve, `Shift+N` deny (asymmetric chord
// is load-bearing — see T-074 bug 4 fix at app::handle_event), Esc
// or `q` exit. Asserts target the `MockApprovalDecider`'s captured
// (id, kind, note) tuple so the routing reaches the right row.

/// Build an `Approval` with stable defaults — tests vary the id /
/// action / summary fields and pin everything else.
fn approval(id: i64, action: &str, summary: &str) -> Approval {
    Approval {
        id,
        project_id: "writing".into(),
        agent_id: "writing:manager".into(),
        action: action.into(),
        summary: summary.into(),
        payload_json: String::new(),
    }
}

/// Seed a fixture team + N pending approvals + dismiss splash.
/// Returns the harness so each test drives the verb under test.
fn approvals_setup(approvals: Vec<Approval>) -> Harness {
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![synth_agent("writing:manager", AgentState::Running, 0, 0)],
    ));
    h.app.dismiss_splash();
    h.app.replace_approvals(approvals);
    h
}

#[test]
fn a_key_enters_approvals_modal_when_pending_non_empty() {
    let mut h = approvals_setup(vec![approval(7, "publish", "post the brief")]);

    h.dispatch_key(KeyCode::Char('a'));

    assert_eq!(h.app.stage, Stage::ApprovalsModal);
    assert_eq!(h.app.selected_approval, 0);
}

#[test]
fn a_key_is_no_op_when_no_pending_approvals() {
    // `enter_approvals_modal` early-returns on empty queue (app.rs
    // L428). Without a pending row there's nothing to triage, so
    // the chord is silent rather than opening an empty modal.
    let mut h = approvals_setup(vec![]);

    h.dispatch_key(KeyCode::Char('a'));

    assert_eq!(h.app.stage, Stage::Triptych);
}

#[test]
fn y_approves_focused_row_via_decider() {
    // Affirmative path: open modal, hit `y`, the decider receives
    // (focused-row-id, Approve, ""). Modal auto-closes because the
    // queue is now empty.
    let mut h = approvals_setup(vec![approval(7, "publish", "post the brief")]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key(KeyCode::Char('y'));

    let calls = h.decider.calls.lock().unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0], (7, Decision::Approve, String::new()));
    assert_eq!(
        h.app.stage,
        Stage::Triptych,
        "queue emptied — modal auto-closes"
    );
}

#[test]
fn capital_y_also_approves_focused_row() {
    // Approve accepts both `y` and `Y` — matches the QuitConfirm
    // loose convention. Pin both casings so the chord stays
    // discoverable for CapsLock/Shift operators.
    let mut h = approvals_setup(vec![approval(7, "publish", "post the brief")]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key_mods(KeyCode::Char('Y'), KeyModifiers::SHIFT);

    let calls = h.decider.calls.lock().unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0].1, Decision::Approve);
}

#[test]
fn shift_n_denies_focused_row_via_decider() {
    // Deny is the destructive side — Shift-gated (`N` only) per
    // T-074 bug 4 fix. Drives the asymmetric-chord contract.
    let mut h = approvals_setup(vec![approval(7, "publish", "post the brief")]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key_mods(KeyCode::Char('N'), KeyModifiers::SHIFT);

    let calls = h.decider.calls.lock().unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0], (7, Decision::Deny, String::new()));
}

#[test]
fn lowercase_n_does_not_deny_destructive_chord_is_shift_gated() {
    // Counter-test of the asymmetric chord: stray lowercase `n` in
    // the modal must not fire deny. Operator hammering keys can't
    // accidentally drop an approval on the floor.
    let mut h = approvals_setup(vec![approval(7, "publish", "post the brief")]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key(KeyCode::Char('n'));

    assert!(
        h.decider.calls.lock().unwrap().is_empty(),
        "lowercase n must not reach the decider"
    );
    assert_eq!(
        h.app.stage,
        Stage::ApprovalsModal,
        "modal stays open on no-op key"
    );
}

#[test]
fn j_advances_focused_approval_and_k_retreats() {
    let mut h = approvals_setup(vec![
        approval(7, "publish", "first"),
        approval(8, "deploy", "second"),
        approval(9, "merge", "third"),
    ]);
    h.dispatch_key(KeyCode::Char('a'));
    assert_eq!(h.app.selected_approval, 0);

    h.dispatch_key(KeyCode::Char('j'));
    assert_eq!(h.app.selected_approval, 1);

    h.dispatch_key(KeyCode::Char('j'));
    assert_eq!(h.app.selected_approval, 2);

    h.dispatch_key(KeyCode::Char('k'));
    assert_eq!(h.app.selected_approval, 1);
}

#[test]
fn down_and_up_arrows_navigate_like_j_and_k() {
    // Arrows mirror j/k for non-vim operators. Both shapes route
    // through the same cycle_approval_next/prev — pin parity.
    let mut h = approvals_setup(vec![
        approval(7, "publish", "first"),
        approval(8, "deploy", "second"),
    ]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key(KeyCode::Down);
    assert_eq!(h.app.selected_approval, 1);

    h.dispatch_key(KeyCode::Up);
    assert_eq!(h.app.selected_approval, 0);
}

#[test]
fn j_wraps_at_end_of_queue() {
    let mut h = approvals_setup(vec![
        approval(7, "publish", "first"),
        approval(8, "deploy", "second"),
    ]);
    h.dispatch_key(KeyCode::Char('a'));
    h.dispatch_key(KeyCode::Char('j'));
    assert_eq!(h.app.selected_approval, 1);

    h.dispatch_key(KeyCode::Char('j'));

    assert_eq!(
        h.app.selected_approval, 0,
        "j from last row wraps back to first"
    );
}

#[test]
fn k_wraps_at_start_of_queue() {
    let mut h = approvals_setup(vec![
        approval(7, "publish", "first"),
        approval(8, "deploy", "second"),
    ]);
    h.dispatch_key(KeyCode::Char('a'));
    assert_eq!(h.app.selected_approval, 0);

    h.dispatch_key(KeyCode::Char('k'));

    assert_eq!(h.app.selected_approval, 1, "k from first row wraps to last");
}

#[test]
fn esc_closes_approvals_modal_without_decision() {
    let mut h = approvals_setup(vec![approval(7, "publish", "post the brief")]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key(KeyCode::Esc);

    assert_eq!(h.app.stage, Stage::Triptych);
    assert!(h.decider.calls.lock().unwrap().is_empty());
    assert_eq!(h.app.pending_approvals.len(), 1, "queue intact after Esc");
}

#[test]
fn q_closes_approvals_modal_without_decision() {
    // `q` is the alternative exit chord (matches QuitConfirm/Help
    // overlay convention). No quit-confirm overlay should surface
    // — the modal owns input.
    let mut h = approvals_setup(vec![approval(7, "publish", "post the brief")]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key(KeyCode::Char('q'));

    assert_eq!(h.app.stage, Stage::Triptych);
    assert!(h.decider.calls.lock().unwrap().is_empty());
}

#[test]
fn navigate_then_approve_routes_correct_row_id_to_decider() {
    // The end-to-end test the ticket flags: 3-row queue, navigate
    // to the middle row, approve. Decider must receive the middle
    // id (8), not the first (7) or last (9). Catches "selected_
    // approval drifts but apply_decision uses index 0" regressions.
    let mut h = approvals_setup(vec![
        approval(7, "publish", "first"),
        approval(8, "deploy", "second"),
        approval(9, "merge", "third"),
    ]);
    h.dispatch_key(KeyCode::Char('a'));
    h.dispatch_key(KeyCode::Char('j'));
    assert_eq!(h.app.selected_approval, 1);

    h.dispatch_key(KeyCode::Char('y'));

    let calls = h.decider.calls.lock().unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(
        calls[0].0, 8,
        "decider received the focused-row id (middle), not the head"
    );
    assert_eq!(calls[0].1, Decision::Approve);
    assert_eq!(
        h.app.pending_approvals.len(),
        2,
        "approved row removed from local queue optimistically"
    );
    assert_eq!(
        h.app.stage,
        Stage::ApprovalsModal,
        "modal stays open while queue still has rows"
    );
}

#[test]
fn deny_followed_by_approve_routes_each_to_distinct_rows() {
    // Two-step end-to-end: Shift-N denies the head row (id 7),
    // selected_approval clamps onto the new head (id 8), `y` then
    // approves it. Decider must show one Deny on 7 and one Approve
    // on 8 — pins the optimistic-removal-and-clamp path through
    // `apply_decision`.
    let mut h = approvals_setup(vec![
        approval(7, "publish", "first"),
        approval(8, "deploy", "second"),
    ]);
    h.dispatch_key(KeyCode::Char('a'));

    h.dispatch_key_mods(KeyCode::Char('N'), KeyModifiers::SHIFT);
    h.dispatch_key(KeyCode::Char('y'));

    let calls = h.decider.calls.lock().unwrap();
    assert_eq!(calls.len(), 2);
    assert_eq!(calls[0], (7, Decision::Deny, String::new()));
    assert_eq!(calls[1], (8, Decision::Approve, String::new()));
    assert_eq!(
        h.app.stage,
        Stage::Triptych,
        "queue empty after both decisions"
    );
}

// ── Mailbox + tab coverage (T-079-E) ────────────────────────────
//
// Mailbox tab interactions sit on `[` / `]` (gated by the Mailbox
// pane having focus), Tab cycles pane focus only (T-074 bug 6 was
// the Tab-cycles-tabs shape that stranded operators), agent-switch
// resets every per-tab buffer, and `refresh_mailbox` fans out to
// the three filter shapes (`inbox` / `channel_feed` / `wire`) with
// the right `(agent_id, after_id)` / `(project_id, after_id)`
// pairs. Recorder assertions use the harness's `MockMailboxSource`
// fields directly.

use teamctl_ui::app::refresh_mailbox;
use teamctl_ui::mailbox::{MailboxTab, MessageRow};

fn mb_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 bracket_chord_cycles_mailbox_tabs_forward_when_mailbox_focused() {
    // `]` cycles Inbox → Channel → Wire → Inbox once the mailbox
    // pane has focus. The forward walker must wrap.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    // Walk Tab focus to Mailbox.
    h.dispatch_key(KeyCode::Tab);
    h.dispatch_key(KeyCode::Tab);
    assert_eq!(h.app.focused_pane, Pane::Mailbox);
    assert_eq!(h.app.mailbox_tab, MailboxTab::Inbox);

    h.dispatch_key(KeyCode::Char(']'));
    assert_eq!(h.app.mailbox_tab, MailboxTab::Channel);

    h.dispatch_key(KeyCode::Char(']'));
    assert_eq!(h.app.mailbox_tab, MailboxTab::Wire);

    h.dispatch_key(KeyCode::Char(']'));
    assert_eq!(
        h.app.mailbox_tab,
        MailboxTab::Inbox,
        "`]` from Wire wraps to Inbox"
    );
}

#[test]
fn bracket_chord_cycles_mailbox_tabs_backward_when_mailbox_focused() {
    // `[` walks the other direction: Inbox → Wire → Channel → Inbox.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    h.dispatch_key(KeyCode::Tab);
    h.dispatch_key(KeyCode::Tab);
    assert_eq!(h.app.focused_pane, Pane::Mailbox);

    h.dispatch_key(KeyCode::Char('['));
    assert_eq!(h.app.mailbox_tab, MailboxTab::Wire);

    h.dispatch_key(KeyCode::Char('['));
    assert_eq!(h.app.mailbox_tab, MailboxTab::Channel);

    h.dispatch_key(KeyCode::Char('['));
    assert_eq!(
        h.app.mailbox_tab,
        MailboxTab::Inbox,
        "`[` from Channel wraps back to Inbox"
    );
}

#[test]
fn bracket_chord_is_no_op_when_mailbox_not_focused() {
    // Gating on `focused_pane == Mailbox` is load-bearing — without
    // it, an operator hammering bracket keys while scrolling the
    // roster would see surprise tab switches. Pin the no-op.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    assert_eq!(h.app.focused_pane, Pane::Roster);

    h.dispatch_key(KeyCode::Char(']'));
    h.dispatch_key(KeyCode::Char('['));

    assert_eq!(
        h.app.mailbox_tab,
        MailboxTab::Inbox,
        "bracket chords must not cycle tabs from Roster focus"
    );
}

#[test]
fn tab_into_mailbox_preserves_active_tab() {
    // Tabbing pane focus INTO the mailbox must not silently reset
    // `mailbox_tab` — operators returning to a tab they were on
    // would otherwise lose place. Seed `mailbox_tab` to Channel
    // before tabbing in, assert it survives.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    // Walk into Mailbox, advance to Channel, walk back out.
    h.dispatch_key(KeyCode::Tab);
    h.dispatch_key(KeyCode::Tab);
    h.dispatch_key(KeyCode::Char(']'));
    assert_eq!(h.app.focused_pane, Pane::Mailbox);
    assert_eq!(h.app.mailbox_tab, MailboxTab::Channel);
    h.dispatch_key(KeyCode::Tab); // back to Roster
    assert_eq!(h.app.focused_pane, Pane::Roster);

    // Now tab back into Mailbox via Detail.
    h.dispatch_key(KeyCode::Tab);
    h.dispatch_key(KeyCode::Tab);
    assert_eq!(h.app.focused_pane, Pane::Mailbox);
    assert_eq!(
        h.app.mailbox_tab,
        MailboxTab::Channel,
        "active mailbox tab survives the Tab-walk away and back"
    );
}

#[test]
fn switching_focused_agent_resets_mailbox_buffers() {
    // The mailbox `inbox_after` / `channel_after` / `wire_after`
    // cursors are per-focused-agent. Switching agents without a
    // reset would skip historical rows for the new agent (next
    // refresh would query `id > <prior agent's high water>` and
    // miss everything older). `select_next` must `mailbox.reset()`
    // on agent change.
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![
            synth_agent("writing:manager", AgentState::Running, 0, 0),
            synth_agent("writing:dev1", AgentState::Running, 0, 0),
        ],
    ));
    h.app.dismiss_splash();
    // Seed inbox buffer + cursor as if a refresh had already
    // pulled rows for the manager.
    h.app.mailbox.extend(
        MailboxTab::Inbox,
        vec![mb_row(7, "writing:dev1", "writing:manager", "ping")],
    );
    assert_eq!(h.app.mailbox.inbox.len(), 1);
    assert_eq!(h.app.mailbox.inbox_after, 7);

    h.app.select_next(); // manager → dev1

    assert!(
        h.app.mailbox.inbox.is_empty(),
        "mailbox buffer cleared on agent switch"
    );
    assert_eq!(
        h.app.mailbox.inbox_after, 0,
        "inbox cursor reset to 0 on agent switch"
    );
}

#[test]
fn refresh_mailbox_fans_out_to_three_filters_with_recorded_args() {
    // `refresh_mailbox` queries `inbox(agent_id, after)`,
    // `channel_feed(agent_id, after)`, `wire(project_id, after)` —
    // three calls, three filter shapes. The recorder verifies the
    // right filter is asked the right thing.
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![synth_agent("writing:manager", AgentState::Running, 0, 0)],
    ));
    h.app.dismiss_splash();

    refresh_mailbox(&mut h.app, &h.mailbox);

    assert_eq!(
        *h.mailbox.inbox_calls.lock().unwrap(),
        vec![("writing:manager".into(), 0_i64)],
        "inbox queried for the focused agent's id"
    );
    assert_eq!(
        *h.mailbox.channel_calls.lock().unwrap(),
        vec![("writing:manager".into(), 0_i64)],
        "channel_feed queried for the focused agent's id (membership-scoped server-side)"
    );
    assert_eq!(
        *h.mailbox.wire_calls.lock().unwrap(),
        vec![("writing".into(), 0_i64)],
        "wire queried for the project id, NOT the agent id"
    );
}

#[test]
fn refresh_mailbox_with_seeded_rows_extends_buffers_and_advances_cursors() {
    // Seed canned rows into the recorder; `refresh_mailbox` should
    // fold them into `app.mailbox.<tab>` and bump the matching
    // `<tab>_after` cursor to the batch's high-water id.
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![synth_agent("writing:manager", AgentState::Running, 0, 0)],
    ));
    h.app.dismiss_splash();
    h.mailbox.inbox_rows = vec![
        mb_row(11, "writing:dev1", "writing:manager", "ready"),
        mb_row(12, "writing:dev2", "writing:manager", "merged"),
    ];
    h.mailbox.wire_rows = vec![mb_row(20, "user:cli", "channel:writing:all", "release cut")];

    refresh_mailbox(&mut h.app, &h.mailbox);

    assert_eq!(h.app.mailbox.inbox.len(), 2);
    assert_eq!(h.app.mailbox.inbox_after, 12);
    assert_eq!(h.app.mailbox.wire.len(), 1);
    assert_eq!(h.app.mailbox.wire_after, 20);
    // Channel returned no rows → its buffer + cursor stay empty.
    assert!(h.app.mailbox.channel.is_empty());
    assert_eq!(h.app.mailbox.channel_after, 0);
}

#[test]
fn refresh_mailbox_no_op_when_no_agent_focused() {
    // With an empty roster, no agent is focused; `refresh_mailbox`
    // must early-out without fanning out queries — there's no
    // agent_id to filter on. The recorder's call vectors stay
    // empty.
    let mut h = Harness::new();
    h.app.dismiss_splash();
    assert!(h.app.selected_agent.is_none());

    refresh_mailbox(&mut h.app, &h.mailbox);

    assert!(h.mailbox.inbox_calls.lock().unwrap().is_empty());
    assert!(h.mailbox.channel_calls.lock().unwrap().is_empty());
    assert!(h.mailbox.wire_calls.lock().unwrap().is_empty());
}

// ── Ctrl+letter chord casing-fold sweep (T-082) ─────────────────
//
// Same root cause as T-079-C: with CapsLock or Shift+Ctrl,
// crossterm reports `KeyCode::Char('X')` (uppercase) and the
// chord arm dies silently if it only matches one casing. T-082
// sweeps the remaining Ctrl+letter chord arms — Ctrl+H/J/K/L
// (split-cycle) and Ctrl+Q (close-focused-split).

fn harness_with_two_splits() -> Harness {
    let mut h = Harness::new();
    h.app.replace_team(fixture_team(
        "writing",
        vec![
            synth_agent("writing:manager", AgentState::Running, 0, 0),
            synth_agent("writing:dev1", AgentState::Running, 0, 0),
        ],
    ));
    h.app.dismiss_splash();
    h.app.add_detail_split_vertical();
    h.app.add_detail_split_vertical();
    assert_eq!(h.app.detail_splits.len(), 2);
    h
}

#[test]
fn ctrl_h_lowercase_cycles_split_prev() {
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(KeyCode::Char('h'), KeyModifiers::CONTROL);

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_shift_h_cycles_split_prev() {
    // CapsLock or Shift+Ctrl reports `Char('H')` — must still cycle.
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(
        KeyCode::Char('H'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_k_lowercase_cycles_split_prev() {
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(KeyCode::Char('k'), KeyModifiers::CONTROL);

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_shift_k_cycles_split_prev() {
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(
        KeyCode::Char('K'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_l_lowercase_cycles_split_next() {
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(KeyCode::Char('l'), KeyModifiers::CONTROL);

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_shift_l_cycles_split_next() {
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(
        KeyCode::Char('L'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_j_lowercase_cycles_split_next() {
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(KeyCode::Char('j'), KeyModifiers::CONTROL);

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_shift_j_cycles_split_next() {
    let mut h = harness_with_two_splits();
    h.app.selected_split = 0;

    h.dispatch_key_mods(
        KeyCode::Char('J'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );

    assert_eq!(h.app.selected_split, 1);
}

#[test]
fn ctrl_q_uppercase_closes_focused_split() {
    let mut h = harness_with_two_splits();

    h.dispatch_key_mods(
        KeyCode::Char('Q'),
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    );

    assert_eq!(h.app.detail_splits.len(), 1);
}

#[test]
fn ctrl_q_lowercase_closes_focused_split() {
    // Plain Ctrl+q without Shift — operator without CapsLock typing
    // the natural unshifted form. Must still close the focused split.
    let mut h = harness_with_two_splits();

    h.dispatch_key_mods(KeyCode::Char('q'), KeyModifiers::CONTROL);

    assert_eq!(h.app.detail_splits.len(), 1);
}