tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
//! The triage inbox and its decision modal (WP06, T029–T032).
//!
//! One view over the queue the WP02 service answers, plus the modal that
//! decides an item of it. The view is a **modal over the board**, exactly like
//! settings, planning and the batch modal, so nothing about the board, the
//! tabs or the card cursor changes to make room for it: the inbox renders on
//! top and `esc` drops it, leaving the cursor where it was (T029).
//!
//! ## What this module computes, and what it does not
//!
//! Nothing here decides anything. Age, membership, counts and the histogram
//! come from [`crate::triage::inbox::scope`] plus
//! [`crate::triage::inbox::collect`] — one pass over one snapshot. A
//! decision is [`crate::triage::batch::build_plan`] plus, only after a second
//! `y`, [`crate::triage::batch::apply`], which is the same #173 core
//! `tix triage batch` drives (C-005, T031). The preview and report text is the
//! CLI's own [`crate::commands::triage`] renderers, so the two surfaces cannot
//! describe the same plan differently (NFR-003).
//!
//! There is no second completion rule, no status compared against a literal,
//! and no `store.update` outside the batch engine's. The one thing that *is*
//! restated here is the shape of a refusal when there is no inbox at all —
//! `TriageState::open` needs a message, and `commands::triage::scope_of` is
//! private to that module; both are `TixError::InvalidInput` and both name
//! `[triage]` in `tix.toml`, which is the part the contract makes load-bearing.
//!
//! ## Why the decision keys are not in the key table
//!
//! `a`, `d`, `u`, `f`, `p`, `y`, `q` and every letter a reason or a duplicate
//! target might contain are deliberately **unbound** in
//! [`crate::keybindings::InputContext::Triage`], so
//! [`crate::app::App::handle_key`]'s fallback hands them to the handler
//! verbatim. Binding `q` to close the inbox — which the board does — would
//! canonicalise a `q` typed into a decline reason into an `Esc` and close the
//! modal mid-sentence; the same defect is why `LinkPrompt` and `Comment` bind
//! only `esc`. What the modal can do at any moment is named by its own
//! [`TriageModal::footer`], which is how the batch modal names its keys.

use std::fmt::Write as _;

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};

use crate::app::{Action, App};
use crate::bulk::{Selection, SelectionScope, SelectionSource};
use crate::commands::triage as cli_triage;
use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::storage::Store;
use crate::triage::inbox::{self, AgeBucket, InboxScope, QueueMetrics};
use crate::triage::{DecisionKind, TriageDecision, TriagePlan, batch};
use crate::ui::bulk::BulkSelection;
use crate::ui::pickers::{DropdownState, PickerEvent, PickerItem};

// ---------------------------------------------------------------------------
// T029/T030 — the queue snapshot
// ---------------------------------------------------------------------------

/// One row of the inbox: the issue, how long it has waited, and the last
/// decision recorded on it.
///
/// Owned rather than borrowed because [`inbox::QueueMetrics`] borrows the
/// snapshot it was collected from, and the inbox outlives the query that
/// filled it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueueRow {
    /// The issue as the snapshot read it.
    pub issue: Issue,
    /// Days since the entry stamp; `None` when nothing recorded one. Never
    /// `0` for "unknown" — that is [`inbox`]'s rule and it is copied, not
    /// re-derived.
    pub age_days: Option<i64>,
    /// The last triage decision, told apart from none and from a line that no
    /// longer parses (tix #1494). A reader that shows the queue wants all three
    /// states; `None` used to mean both "undecided" and "unreadable".
    pub last_decision: crate::triage::history::LastDecision,
}

/// The counts and histogram the header renders, copied out of [`QueueMetrics`]
/// so the snapshot outlives the query that produced it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TriageSummary {
    /// Inbox entries.
    pub total: usize,
    /// Entries in the entry column.
    pub awaiting: usize,
    /// Entries in the deferred column.
    pub deferred: usize,
    /// Entries already `completed` while still in an inbox column.
    pub accepted: usize,
    /// Entries already `canceled` while still in an inbox column.
    pub declined: usize,
    /// Entries that originate a `duplicates` edge.
    pub duplicated: usize,
    /// Entries with no readable entry stamp.
    pub unknown_age: usize,
    /// The age histogram, in [`inbox::AGE_BUCKETS`] order. Sums to `total`.
    pub age: Vec<AgeBucket>,
}

impl TriageSummary {
    /// Copy the metrics out of the query that borrowed them.
    #[must_use]
    pub fn of(metrics: &QueueMetrics<'_>) -> Self {
        Self {
            total: metrics.total,
            awaiting: metrics.awaiting,
            deferred: metrics.deferred,
            accepted: metrics.accepted,
            declined: metrics.declined,
            duplicated: metrics.duplicated,
            unknown_age: metrics.unknown_age,
            age: metrics.age_distribution.clone(),
        }
    }

    /// The header line, in the **CLI's** wording.
    ///
    /// `commands::triage::summary_line` prints this same string for
    /// `tix triage list --count`, and
    /// `triage_tui_the_inbox_counts_are_the_clis_counts_for_the_same_snapshot`
    /// pins the two together: a header the two surfaces could spell differently
    /// is a header a reader would trust differently.
    #[must_use]
    pub fn header(&self) -> String {
        format!(
            "inbox: {} entr{} ({} awaiting, {} deferred)",
            self.total,
            if self.total == 1 { "y" } else { "ies" },
            self.awaiting,
            self.deferred
        )
    }

    /// The age histogram, every bucket named including the zeros.
    #[must_use]
    pub fn age_line(&self) -> String {
        let cells: Vec<String> = self
            .age
            .iter()
            .map(|bucket| format!("{} {}", bucket.label, bucket.count))
            .collect();
        format!("age: {}", cells.join(" · "))
    }

    /// The decision counts. `accepted`/`declined` are the WP02 *staleness*
    /// readings — they come from `is_completed` and the category resolver, not
    /// from a column name.
    #[must_use]
    pub fn decisions_line(&self) -> String {
        format!(
            "decisions: {} accepted · {} declined · {} duplicated · {} unknown age",
            self.accepted, self.declined, self.duplicated, self.unknown_age
        )
    }
}

/// The one row under the cursor, for the detail line below the list.
#[must_use]
pub fn decision_summary(row: &QueueRow) -> String {
    let mut out = format!(
        "#{number} \"{title}\" — {status}",
        number = row.issue.number,
        title = row.issue.title,
        status = row.issue.status.display(),
    );
    match &row.last_decision {
        crate::triage::history::LastDecision::Readable(record) => {
            let _ = write!(out, " — last decision: {}", format_decision(record));
        }
        crate::triage::history::LastDecision::Unreadable => {
            out.push_str(" — last decision: unreadable");
        }
        crate::triage::history::LastDecision::None => {
            out.push_str(" — last decision: none");
        }
    }
    out
}

/// The last decision on `issue`, told apart from none and unreadable (tix
/// #1494).
///
/// The display half of the triage History seam: an issue whose newest triage
/// line exists but no longer parses must read as *unreadable*, not as
/// *undecided*, so the maintainer sees the file that needs attention.
fn last_decision(issue: &Issue) -> crate::triage::history::LastDecision {
    crate::triage::history::last_decision_state(issue)
}

/// Format a parsed decision the way a queue row shows it.
///
/// `triage_decided` and friends rather than the decision verb: the History
/// event's own kind is what is on disk, and a summary that renamed it would be
/// a second spelling of the same fact.
fn format_decision(record: &crate::triage::history::TriageDecisionRecord) -> String {
    let mut out = format!("{} -> {}", record.kind.as_str(), record.result);
    if let Some(reason) = &record.reason {
        let _ = write!(out, " — {reason}");
    }
    let when = record.timestamp.get(..10).unwrap_or(&record.timestamp);
    let _ = write!(out, " ({}, {})", record.actor, when);
    out
}

/// The inbox scope, or the one refusal every triage surface shares.
///
/// The message names the *inbox* rather than `tix triage`, because this is the
/// TUI. What the contract makes load-bearing is the category and the fact that
/// both name `[triage]` in `tix.toml`, and both are the crate's existing
/// `invalid input` variant — no triage diagnostic in
/// `crate::workflow::DiagnosticKind` (whose `ALL` stays at seven).
fn scope_of(store: &Store) -> Result<InboxScope> {
    inbox::scope(&store.config)?.ok_or_else(|| {
        TixError::InvalidInput(
            "the triage inbox needs a `[triage]` section in tix.toml, and this project has none"
                .to_string(),
        )
    })
}

// ---------------------------------------------------------------------------
// T031 — the decision modal
// ---------------------------------------------------------------------------

/// What the modal is asking for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecisionField {
    Reason,
    Actor,
    /// The accept target (`--to`). Present for `accept` only, so `--to` on a
    /// decline cannot be typed — the same check `run_batch` makes on a flag.
    Target,
    /// The duplicate target (`--of`). Present for `duplicate` only, so `--of`
    /// on an accept cannot be typed either.
    DuplicateOf,
}

impl DecisionField {
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Reason => "reason",
            Self::Actor => "actor",
            Self::Target => "to",
            Self::DuplicateOf => "of",
        }
    }
}

/// The issue a decision is about: one from the cursor, or everything marked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModalScope {
    /// One issue, by number. Resolved from the **store** at plan time, so the
    /// plan is built from the file on disk and not from a row the list drew
    /// before the file changed.
    One(u32),
    /// The marked issues, in the order they were marked.
    Many(BulkSelection),
}

/// Where the modal is in its own cycle. The #173 batch modal's shape, because
/// "I saw it" and "I approved it" are two decisions here too.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModalState {
    /// The fields, ready to edit.
    Editing,
    /// The modal asked for something it cannot plan without.
    NeedsInput(String),
    /// A plan is on screen. **Nothing has been written.**
    Preview(Box<TriagePlan>),
    /// The plan is armed: one more `y` writes.
    Confirming(Box<TriagePlan>),
    /// The apply ran. Its per-item outcomes and counts are in the string.
    Done(String),
    /// The plan or the apply was refused. Its reasons are in the string.
    Refused(String),
}

/// The decision modal: four fields, four states, one plan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TriageModal {
    /// Which decision.
    pub kind: DecisionKind,
    /// One issue or the marked set.
    pub scope: ModalScope,
    /// What the title says: `#12 Alpha` or `3 marked issues`.
    pub heading: String,
    /// The fields this decision has, in the order they are drawn.
    pub fields: Vec<DecisionField>,
    /// Which field the cursor is on.
    pub cursor: usize,
    /// Whether the cursor's field is being typed into.
    pub editing: bool,
    /// The text being typed. Discarded on `esc`, never committed.
    pub draft: String,
    pub reason: String,
    pub actor: String,
    pub target: String,
    pub duplicate_of: String,
    /// The decision timestamp, fixed when the modal opened so a preview and the
    /// apply it authorises stamp the same event.
    pub timestamp: String,
    pub state: ModalState,
    /// The last message, for the status bar and the body.
    pub note: Option<String>,
    /// Whether the plan no longer matches the screen.
    pub plan_stale: bool,
}

impl TriageModal {
    /// A fresh modal for `kind` over `scope`.
    ///
    /// The fields are fixed per decision rather than per keystroke, which is
    /// how `--to` on a decline and `--of` on an accept become *untypeable*
    /// instead of merely refused: the flag does not exist to type into.
    #[must_use]
    pub fn new(kind: DecisionKind, scope: ModalScope, heading: String) -> Self {
        let fields = Self::fields_for(kind);
        Self {
            kind,
            scope,
            heading,
            fields,
            cursor: 0,
            editing: false,
            draft: String::new(),
            reason: String::new(),
            actor: String::new(),
            target: String::new(),
            duplicate_of: String::new(),
            timestamp: crate::model::utc_now_rfc3339(),
            state: ModalState::Editing,
            note: None,
            plan_stale: false,
        }
    }

    #[must_use]
    pub fn field(&self, index: usize) -> DecisionField {
        self.fields
            .get(index)
            .copied()
            .unwrap_or(DecisionField::Reason)
    }

    #[must_use]
    pub fn field_value(&self, field: DecisionField) -> &str {
        match field {
            DecisionField::Reason => &self.reason,
            DecisionField::Actor => &self.actor,
            DecisionField::Target => &self.target,
            DecisionField::DuplicateOf => &self.duplicate_of,
        }
    }

    fn field_mut(&mut self, field: DecisionField) -> &mut String {
        match field {
            DecisionField::Reason => &mut self.reason,
            DecisionField::Actor => &mut self.actor,
            DecisionField::Target => &mut self.target,
            DecisionField::DuplicateOf => &mut self.duplicate_of,
        }
    }

    pub fn begin_edit(&mut self) {
        let field = self.field(self.cursor);
        self.draft = self.field_value(field).to_string();
        self.editing = true;
    }

    pub fn push_char(&mut self, c: char) {
        if self.editing {
            self.draft.push(c);
        }
    }

    pub fn pop_char(&mut self) {
        if self.editing {
            self.draft.pop();
        }
    }

    pub fn commit_edit(&mut self) {
        if !self.editing {
            return;
        }
        let field = self.field(self.cursor);
        let draft = std::mem::take(&mut self.draft);
        *self.field_mut(field) = draft;
        self.editing = false;
        // The row changed, so the plan on screen no longer describes it. The
        // state is deliberately **not** reset to `Editing`: the plan is left
        // visible and labelled stale, because a preview that silently vanished
        // the moment a field was edited leaves the user with no way to see
        // what their edit invalidated (contract §4: any change requires a new
        // preview — and `confirm` is what refuses the old one).
        self.plan_stale = true;
    }

    /// Abandon the draft. The row keeps whatever `commit_edit` last stored.
    pub fn abort_edit(&mut self) {
        self.draft.clear();
        self.editing = false;
    }

    pub fn move_cursor(&mut self, delta: isize) {
        if self.fields.is_empty() {
            return;
        }
        let len = self.fields.len() as isize;
        let next = (self.cursor as isize + delta).rem_euclid(len);
        self.cursor = next as usize;
    }

    /// What the batch modal's `a` does: pick the next decision.
    ///
    /// The typed fields survive, so a reason the user already wrote does not
    /// have to be written again because they changed their mind about which
    /// decision it belonged to. What does **not** survive is any plan built
    /// for the old verb — `state` goes back to [`ModalState::Editing`] and
    /// `plan_stale` is set, so the only way to see a plan is to preview this
    /// one (contract §4: any change requires a new preview).
    pub fn cycle_kind(&mut self) {
        self.kind = match self.kind {
            DecisionKind::Accept => DecisionKind::Decline,
            DecisionKind::Decline => DecisionKind::Duplicate,
            DecisionKind::Duplicate => DecisionKind::Defer,
            DecisionKind::Defer => DecisionKind::Accept,
        };
        self.fields = Self::fields_for(self.kind);
        if self.cursor >= self.fields.len() {
            self.cursor = self.fields.len() - 1;
        }
        self.state = ModalState::Editing;
        self.plan_stale = true;
    }

    /// The rows this decision has, in the order they are drawn.
    ///
    /// Fixed per decision rather than per keystroke: `--to` on a decline and
    /// `--of` on an accept do not exist as flags, so here they do not exist as
    /// rows either, and the check `run_batch` makes on those flags is
    /// unreachable by construction.
    fn fields_for(kind: DecisionKind) -> Vec<DecisionField> {
        let mut fields = vec![DecisionField::Reason, DecisionField::Actor];
        match kind {
            DecisionKind::Accept => fields.push(DecisionField::Target),
            DecisionKind::Duplicate => fields.push(DecisionField::DuplicateOf),
            DecisionKind::Decline | DecisionKind::Defer => {}
        }
        fields
    }

    /// The decision request these fields describe, shaped exactly like
    /// `commands::triage::run_batch`'s: a whitespace-only target is no target,
    /// and an accept that named none of its own names the configured one so the
    /// preview and the service cannot propose two destinations.
    ///
    /// A blank actor means *not specified*, so it falls back to the identity
    /// the CLI also uses when `--actor` is absent — an audit entry with no
    /// actor is worse than no entry (contract §Required reason and actor).
    #[must_use]
    pub fn request(&self, store: &Store) -> TriageDecision {
        let actor = if self.actor.trim().is_empty() {
            crate::storage::actor_identity()
        } else {
            self.actor.trim().to_string()
        };
        let mut decision = TriageDecision::new(
            self.kind,
            self.timestamp.clone(),
            actor,
            self.reason.clone(),
        );
        if self.kind == DecisionKind::Accept {
            let target = self.target.trim();
            decision.target_status = if target.is_empty() {
                None
            } else {
                Some(target.to_string())
            };
            if decision.target_status.is_none() {
                decision.target_status = store
                    .config
                    .triage
                    .as_ref()
                    .and_then(|triage| triage.accepted_status.clone());
            }
        }
        decision
    }

    /// The `--of` this modal carries, for a duplicate only.
    #[must_use]
    pub fn duplicate_target(&self) -> Option<String> {
        let raw = self.duplicate_of.trim();
        (!raw.is_empty() && self.kind == DecisionKind::Duplicate).then(|| raw.to_string())
    }

    /// One read-only plan over the modal's scope. **Writes nothing.**
    ///
    /// Both the single issue and the marked set go through
    /// [`batch::build_plan`], which is T031's "route single and batch
    /// operations through WP03/WP04": one preview engine, one refusal
    /// vocabulary, one per-item outcome shape, whatever the size of the batch.
    ///
    /// # Errors
    ///
    /// Propagates a *plan-level* failure (no `[triage]` section, an unresolvable
    /// `--of`, a `--to` on a decision that has none). A per-item refusal is not
    /// an error — it is a refused item in the plan, which is where a surface
    /// that reports every outcome has to put it.
    pub fn plan(&self, store: &Store, issues: &[(u32, Issue)]) -> Result<TriagePlan> {
        let selection = match &self.scope {
            ModalScope::One(number) => Selection::from_issues(
                [store.resolve_issue(&number.to_string())?],
                SelectionSource::Explicit,
                SelectionScope::Active,
            ),
            ModalScope::Many(marked) => marked.to_selection(issues).0,
        };
        batch::build_plan(
            store,
            selection,
            self.request(store),
            self.duplicate_target().as_deref(),
        )
    }

    /// Build the preview. A refusal the modal caused lands in `state`, not in
    /// the `Result`: an `Err` out of here would reach the event loop, and the
    /// only thing that could do with it is end the session (the rule WP04 froze
    /// for `BulkModal::preview`, and the reason `tix triage batch` prints a
    /// refusal and exits non-zero instead of erroring).
    pub fn preview(&mut self, store: &Store, issues: &[(u32, Issue)]) -> Result<()> {
        if let ModalScope::Many(marked) = &self.scope {
            if marked.is_empty() {
                self.state =
                    ModalState::NeedsInput("press `space` on a card to mark it".to_string());
                return Ok(());
            }
            // A marked number that has left the inbox between marking and
            // previewing is left out and **named**, the same way
            // `BulkModal::preview` reports a card that left the board.
            let (_selection, dropped) = marked.to_selection(issues);
            self.note = (!dropped.is_empty()).then(|| {
                format!(
                    "{} marked issue(s) left the inbox and were left out: #{}",
                    dropped.len(),
                    dropped
                        .iter()
                        .map(u32::to_string)
                        .collect::<Vec<_>>()
                        .join(", #")
                )
            });
        }
        match self.plan(store, issues) {
            Ok(plan) => {
                self.state = ModalState::Preview(Box::new(plan));
                self.plan_stale = false;
            }
            Err(e) => {
                self.state = ModalState::Refused(e.to_string());
                self.note = Some(e.to_string());
            }
        }
        Ok(())
    }

    /// `y`: from a preview, arm. From an armed preview, apply.
    ///
    /// Two presses because "I saw it" and "I approved it" are two decisions;
    /// one `y` conflates them (WP07's rule, kept rather than reinvented).
    ///
    /// The **stale** check runs before either branch: a plan built before the
    /// last field edit is a plan nobody read as it now stands, so the apply
    /// refuses rather than asking the second `y` to mean something different
    /// from what the first one did.
    ///
    /// # Errors
    ///
    /// Only an I/O failure behind the keyboard. A refusal lands in
    /// [`ModalState::Refused`], because the only thing an `Err` out of here
    /// could do is end the session.
    pub fn confirm(&mut self, store: &Store) -> Result<()> {
        if self.plan_stale
            && matches!(
                self.state,
                ModalState::Preview(_) | ModalState::Confirming(_)
            )
        {
            self.state = ModalState::Refused(
                "the fields changed since the preview — press `p` again to see what would \
                 happen now"
                    .to_string(),
            );
            return Ok(());
        }
        match &self.state {
            ModalState::Preview(plan) => {
                self.state = ModalState::Confirming(plan.clone());
                Ok(())
            }
            ModalState::Confirming(plan) => {
                let mut plan = (**plan).clone();
                plan.confirm();
                match batch::apply(store, &plan) {
                    Ok(report) => {
                        let text = cli_triage::render_report(&report, &plan);
                        self.state = ModalState::Done(text);
                        self.plan_stale = false;
                    }
                    Err(e) => {
                        self.state = ModalState::Refused(e.to_string());
                        self.note = Some(e.to_string());
                    }
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    #[must_use]
    pub fn is_armed(&self) -> bool {
        matches!(self.state, ModalState::Confirming(_))
    }

    #[must_use]
    pub fn state_label(&self) -> &'static str {
        match &self.state {
            ModalState::Editing => "editing",
            ModalState::NeedsInput(_) => "needs input",
            ModalState::Preview(_) | ModalState::Confirming(_) if self.plan_stale => {
                "stale — preview again"
            }
            ModalState::Preview(_) => "preview — nothing written",
            ModalState::Confirming(_) => "confirming — y writes",
            ModalState::Done(_) => "done",
            ModalState::Refused(_) => "refused",
        }
    }

    /// The footer: only the keys that mean something **right now**. A footer
    /// that names `y` while `y` types a letter teaches the wrong thing.
    #[must_use]
    pub fn footer(&self) -> String {
        if self.editing {
            return "enter commit · esc revert".to_string();
        }
        if self.plan_stale
            && matches!(
                self.state,
                ModalState::Preview(_) | ModalState::Confirming(_)
            )
        {
            return "press p to re-preview · esc to cancel".to_string();
        }
        match &self.state {
            ModalState::Preview(_) => "y to confirm · p to re-preview · esc to cancel".to_string(),
            ModalState::Confirming(_) => "y APPLIES THIS WRITE · esc to cancel".to_string(),
            ModalState::Done(_) | ModalState::Refused(_) | ModalState::NeedsInput(_) => {
                "p to re-preview · esc to close".to_string()
            }
            ModalState::Editing => {
                "a decision · j/k field · enter edit · t target · p preview · esc cancel"
                    .to_string()
            }
        }
    }

    /// The rows, as the modal draws them: a cursor, a label and a value.
    #[must_use]
    pub fn rows(&self) -> Vec<(bool, &'static str, String)> {
        self.fields
            .iter()
            .enumerate()
            .map(|(index, field)| {
                let value = if self.editing && index == self.cursor {
                    format!("{}█", self.draft)
                } else {
                    let value = self.field_value(*field);
                    if value.is_empty() {
                        "—".to_string()
                    } else {
                        value.to_string()
                    }
                };
                (index == self.cursor, field.label(), value)
            })
            .collect()
    }

    /// The text a surface shows for the current state, from the **CLI's**
    /// renderers wherever the CLI has one.
    #[must_use]
    pub fn body(&self) -> String {
        match &self.state {
            ModalState::Editing => {
                let mut out = format!("decision: {}\n", self.kind);
                if self.kind.requires_reason() {
                    out.push_str("a reason is required\n");
                }
                out.push_str("fields (enter to edit):\n");
                for (on, name, value) in self.rows() {
                    let cursor = if on { ">" } else { " " };
                    out.push_str(&format!("{cursor} {name}: {value}\n"));
                }
                if let Some(note) = &self.note {
                    out.push_str(&format!("\nnote: {note}\n"));
                }
                out.push('\n');
                out.push_str(&self.footer());
                out
            }
            ModalState::NeedsInput(what) => format!("{what}\n\n{}", self.footer()),
            // The plan table, verbatim from the CLI: `render_plan` is what
            // `tix triage batch --select …` prints for this same plan.
            ModalState::Preview(plan) => {
                let mut out = cli_triage::render_plan(plan);
                if let Some(note) = &self.note {
                    out.push_str(&format!("\nnote: {note}\n"));
                }
                out.push('\n');
                out.push_str(&self.footer());
                out
            }
            ModalState::Confirming(plan) => {
                let mut out = cli_triage::render_plan(plan);
                out.push('\n');
                out.push_str(&self.footer());
                out
            }
            ModalState::Done(text) | ModalState::Refused(text) => text.clone(),
        }
    }
}

// ---------------------------------------------------------------------------
// T029 — the inbox
// ---------------------------------------------------------------------------

/// Which picker the Triage mode has open (tui-triage-mode).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TriageDropdownKind {
    /// The board's columns, as a status to move the focused issue to.
    Status,
    /// The assignee storage folders plus configured team members.
    Assignee,
}

/// An open picker in the Triage mode: the reused [`DropdownState`] and which
/// field it is choosing for. Exactly one can be open at a time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TriageDropdown {
    pub kind: TriageDropdownKind,
    pub state: DropdownState,
}

/// Which control of the Triage mode's toolbar has the focus (tui-triage-mode).
///
/// The mode's horizontal axis: `h`/`l` and `←`/`→` walk these four and clamp at
/// the ends. The queue is a control rather than "the absence of one" so the
/// default focus has a visible home on the bar, and `enter` activates whatever
/// is focused — nothing at all for [`Self::Queue`], whose keys (`j`/`k`,
/// `space`, `a`/`d`/`u`/`f`/`p`) act directly on the list and need no
/// activation step.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TriageControl {
    /// The queue itself.
    #[default]
    Queue,
    /// The status picker (`s`).
    Status,
    /// The assignee picker (`@`).
    Assignee,
    /// The inline create prompt (`n`).
    New,
}

impl TriageControl {
    /// The four controls, in the order the toolbar draws them and `h`/`l` walk
    /// them.
    pub const ALL: [Self; 4] = [Self::Queue, Self::Status, Self::Assignee, Self::New];
}

/// The inbox view's own state: a cursor and a selection that are **not** the
/// board's, so opening and closing the inbox leaves
/// `(active_col, selected)` exactly as it was (T029).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TriageState {
    /// The queue, in the order the store lists it (or oldest-first under `A`).
    pub rows: Vec<QueueRow>,
    /// The header's counts.
    pub summary: TriageSummary,
    /// The row under the cursor.
    pub cursor: usize,
    /// Which toolbar control has the focus. `Queue` on entry, so `j`/`k` mean
    /// exactly what they always did until `h`/`l` moves the focus off it.
    pub focus: TriageControl,
    /// The marked issues — #173's own ordered set, reused rather than grown
    /// beside it (the "duplicate selection model" risk, mitigated).
    pub selection: BulkSelection,
    /// Oldest-first, the TUI's `--age`.
    pub by_age: bool,
    /// The decision modal, `Some` exactly while one is open.
    pub modal: Option<TriageModal>,
    /// The status/assignee picker, `Some` exactly while one is open. A dropdown
    /// never coexists with a decision modal, so a letter typed into a decline
    /// reason can never be stolen by a picker (tui-triage-mode).
    pub dropdown: Option<TriageDropdown>,
    /// Whether the inline create prompt is capturing the keyboard.
    pub creating: bool,
    /// The title being typed into the inline create prompt.
    pub create_buffer: String,
    /// The last message worth showing under the list.
    pub note: Option<String>,
}

/// The status dropdown's options: exactly the active board's columns, in board
/// order (tui-triage-mode, "Status options match the board columns").
#[must_use]
pub fn status_options(columns: &[String]) -> Vec<PickerItem> {
    columns
        .iter()
        .map(|column| PickerItem {
            id: column.clone(),
            label: column.clone(),
        })
        .collect()
}

/// The assignee dropdown's options: the `docs/issues/<username>/` storage
/// folders, the configured `teams.*.members`, and the focused issue's current
/// value (design D6), each once, in that precedence order.
///
/// Deriving from the folders is the point: storage layout is the ground truth
/// for who has issues, and a teams-only list misses real users.
#[must_use]
pub fn assignee_options(store: &Store, current: Option<&str>) -> Vec<PickerItem> {
    let mut seen = std::collections::BTreeSet::new();
    let mut out = Vec::new();
    let mut push = |value: &str, out: &mut Vec<PickerItem>| {
        let value = value.trim();
        if value.is_empty() || !seen.insert(value.to_string()) {
            return;
        }
        out.push(PickerItem {
            id: value.to_string(),
            label: value.to_string(),
        });
    };
    if let Ok(folders) = store.assignee_segments() {
        for folder in folders {
            push(&folder, &mut out);
        }
    }
    for team in store.config.teams.values() {
        for member in &team.members {
            push(member, &mut out);
        }
    }
    if let Some(current) = current {
        push(current, &mut out);
    }
    out
}

impl TriageState {
    /// Query the queue and open the inbox.
    ///
    /// # Errors
    ///
    /// A project with no `[triage]` section has no inbox, and the refusal is
    /// raised **before** the mode is entered — the board does not change under
    /// a user who pressed `t` in a project that does not use triage.
    pub fn open(store: &Store) -> Result<Self> {
        let mut state = Self {
            rows: Vec::new(),
            summary: TriageSummary {
                total: 0,
                awaiting: 0,
                deferred: 0,
                accepted: 0,
                declined: 0,
                duplicated: 0,
                unknown_age: 0,
                age: Vec::new(),
            },
            cursor: 0,
            focus: TriageControl::Queue,
            selection: BulkSelection::new(),
            by_age: false,
            modal: None,
            dropdown: None,
            creating: false,
            create_buffer: String::new(),
            note: None,
        };
        state.refresh(store)?;
        Ok(state)
    }

    /// Re-query the queue. Called on open and after every apply, so the counts
    /// are never a stale snapshot of a file that has moved on.
    ///
    /// # Errors
    ///
    /// Propagates the scope refusal and any I/O failure.
    pub fn refresh(&mut self, store: &Store) -> Result<()> {
        // `scope_of` rather than `inbox::scope`, so the refusal this view shows
        // is the one refusal there is — a project with no `[triage]` section
        // has no inbox, and saying so in two different words would make the
        // TUI and the CLI disagree about the same missing config.
        let scope = scope_of(store)?;
        let corpus = crate::search::Corpus::build(store)?;
        // The same two calls `commands::triage::render_list` makes: one
        // snapshot, one scope, one `today`, one pass.
        let metrics = inbox::collect(&corpus.issues, &scope, &crate::model::today());
        self.summary = TriageSummary::of(&metrics);
        self.rows = metrics
            .entries
            .iter()
            .map(|entry| QueueRow {
                issue: (*entry.issue).clone(),
                age_days: entry.age_days,
                last_decision: last_decision(entry.issue),
            })
            .collect();
        if self.by_age {
            self.sort_by_age();
        }
        self.clamp_cursor();
        Ok(())
    }

    /// Oldest first, with an unknown age sorted **last** on both ends rather
    /// than coerced to `0` — the rule `commands::triage::render_list` gives
    /// `--age`, restated rather than re-invented.
    fn sort_by_age(&mut self) {
        self.rows.sort_by(|a, b| match (a.age_days, b.age_days) {
            (Some(x), Some(y)) => y.cmp(&x),
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            (None, None) => std::cmp::Ordering::Equal,
        });
    }

    fn clamp_cursor(&mut self) {
        if self.rows.is_empty() {
            self.cursor = 0;
        } else if self.cursor >= self.rows.len() {
            self.cursor = self.rows.len() - 1;
        }
    }

    pub fn move_cursor(&mut self, delta: isize) {
        if self.rows.is_empty() {
            return;
        }
        let len = self.rows.len() as isize;
        let next = (self.cursor as isize + delta).rem_euclid(len);
        self.cursor = next as usize;
    }

    /// Move the focus one control left or right, **clamped** at the ends: the
    /// control bar is a rail, so `h` on `queue` and `l` on `new` stay put
    /// rather than wrapping to the other end (tui-triage-mode).
    ///
    /// The queue cursor does not move with the focus. The two are different
    /// things: `j`/`k` keep walking the queue whichever control is focused, and
    /// the focus only decides what `enter` activates.
    pub fn move_focus(&mut self, delta: isize) {
        let index = TriageControl::ALL
            .iter()
            .position(|control| *control == self.focus)
            .unwrap_or_default() as isize;
        let last = TriageControl::ALL.len() as isize - 1;
        self.focus = TriageControl::ALL[(index + delta).clamp(0, last) as usize];
    }

    #[must_use]
    pub fn current(&self) -> Option<&QueueRow> {
        self.rows.get(self.cursor)
    }

    /// Open `kind`'s picker, preselecting `current` when it is one of the
    /// options. The options come from the caller (the board columns / the
    /// assignee derivation), so this view never re-derives them.
    pub fn open_dropdown(
        &mut self,
        kind: TriageDropdownKind,
        options: Vec<PickerItem>,
        current: Option<&str>,
    ) {
        let mut state = DropdownState::single(options);
        if let Some(current) = current
            && let Some(index) = state.options.iter().position(|option| option.id == current)
            && let Some(visible) = state
                .visible_indices()
                .iter()
                .position(|visible| *visible == index)
        {
            state.cursor = visible;
        }
        self.dropdown = Some(TriageDropdown { kind, state });
    }

    /// Drop the open picker without choosing anything.
    pub fn close_dropdown(&mut self) {
        self.dropdown = None;
    }

    /// Feed one key to the open picker. `Ok(Some((kind, id)))` is a choice,
    /// `Ok(None)` means the key was consumed without choosing, and `Err` is
    /// unreachable — a picker cancel is a `None`, not an error.
    #[must_use]
    pub fn handle_dropdown_key(
        &mut self,
        key: crossterm::event::KeyCode,
    ) -> Option<(TriageDropdownKind, String)> {
        let dropdown = self.dropdown.as_mut()?;
        match dropdown.state.handle_key(key) {
            PickerEvent::Cancelled => {
                self.dropdown = None;
                None
            }
            PickerEvent::Selected(ids) => {
                let kind = dropdown.kind;
                let id = ids.first().cloned();
                self.dropdown = None;
                id.map(|id| (kind, id))
            }
            // The pickers here have no inline-create row; `Created` cannot happen
            // because `+`/`Insert` is the only route to it and the triage handler
            // never forwards those keys. `None` is the honest answer.
            PickerEvent::Created(_) | PickerEvent::None => None,
        }
    }

    /// Mark or unmark the row under the cursor. A refusal (a full selection, a
    /// number already marked) is reported, not swallowed.
    pub fn toggle_current(&mut self) {
        let Some(row) = self.rows.get(self.cursor) else {
            return;
        };
        match self.selection.toggle(row.issue.number) {
            Ok(_) => {}
            Err(problem) => self.note = Some(problem.to_string()),
        }
    }

    pub fn clear_selection(&mut self) {
        self.selection.clear();
    }

    /// Open the decision modal for the row under the cursor.
    pub fn open_single(&mut self, kind: DecisionKind) -> bool {
        let Some(row) = self.rows.get(self.cursor) else {
            self.note = Some("the inbox is empty — there is nothing to decide".to_string());
            return false;
        };
        let heading = format!("#{} {}", row.issue.number, row.issue.title);
        self.modal = Some(TriageModal::new(
            kind,
            ModalScope::One(row.issue.number),
            heading,
        ));
        true
    }

    /// Open the decision modal over everything marked.
    pub fn open_batch(&mut self, kind: DecisionKind) -> bool {
        if self.selection.is_empty() {
            self.note = Some("press `space` on a card to mark it first".to_string());
            return false;
        }
        let heading = format!("{} marked issue(s)", self.selection.len());
        self.modal = Some(TriageModal::new(
            kind,
            ModalScope::Many(self.selection.clone()),
            heading,
        ));
        true
    }

    /// Drop the modal and whatever state it was in. The queue and the
    /// selection are untouched: a cancel changes nothing, which is T032's
    /// claim about cancellation in full.
    pub fn close_modal(&mut self) {
        self.modal = None;
    }

    /// The snapshot the plan is built from, as the batch modal asks for it.
    fn issues(&self) -> Vec<(u32, Issue)> {
        self.rows
            .iter()
            .map(|row| (row.issue.number, row.issue.clone()))
            .collect()
    }

    /// Preview the open decision. Writes nothing, in every branch.
    ///
    /// # Errors
    /// Propagates an I/O failure behind the keyboard; a *refusal* is reported
    /// through [`ModalState::Refused`].
    pub fn preview(&mut self, store: &Store) -> Result<()> {
        let issues = self.issues();
        if let Some(modal) = self.modal.as_mut() {
            modal.preview(store, &issues)?;
        }
        Ok(())
    }

    /// `y` on the open decision: arm, then apply.
    ///
    /// # Errors
    /// Propagates an I/O failure behind the keyboard only.
    pub fn confirm(&mut self, store: &Store) -> Result<()> {
        // No `issues` here: the plan that is applied is the one the preview
        // built and stored, re-checked by `batch::apply` for freshness — not a
        // second plan rebuilt from a snapshot that may have moved on.
        if let Some(modal) = self.modal.as_mut() {
            modal.confirm(store)?;
        }
        Ok(())
    }

    /// Whether the modal finished, so the caller can refresh the queue and
    /// report the result the way `BulkModal`'s handler does.
    #[must_use]
    pub fn modal_finished(&self) -> bool {
        matches!(
            self.modal.as_ref().map(|modal| &modal.state),
            Some(ModalState::Done(_))
        )
    }

    /// The note worth showing under the list, preferring a completed apply's
    /// report over an older message.
    #[must_use]
    pub fn display_note(&self) -> Option<String> {
        match self.modal.as_ref().map(|modal| &modal.state) {
            Some(ModalState::Done(text)) | Some(ModalState::Refused(text)) => Some(text.clone()),
            _ => self.note.clone(),
        }
    }

    /// The inbox's own footer: what the list can do right now.
    #[must_use]
    pub fn footer(&self) -> String {
        if self.creating {
            return "enter create · esc cancel".to_string();
        }
        if self.selection.is_empty() {
            "h/l focus · enter activate · j/k move · space mark · a accept · d decline · u duplicate · f defer · p batch · s status · @ assignee · n new · A age · esc back"
                .to_string()
        } else {
            format!(
                "{} marked — p batch · X clear · a accept · d decline · u duplicate · f defer · s status · @ assignee · esc back",
                self.selection.len()
            )
        }
    }

    /// The text the inbox pane shows.
    #[must_use]
    pub fn body(&self) -> String {
        let mut out = String::new();
        let _ = writeln!(out, "{}", self.summary.header());
        let _ = writeln!(out, "{}", self.summary.age_line());
        let _ = writeln!(out, "{}", self.summary.decisions_line());
        out.push('\n');
        if self.rows.is_empty() {
            out.push_str("the inbox is empty\n");
        }
        for (index, row) in self.rows.iter().enumerate() {
            let cursor = if index == self.cursor { ">" } else { " " };
            let mark = if self.selection.contains(row.issue.number) {
                "*"
            } else {
                " "
            };
            let _ = writeln!(
                out,
                "{cursor}{mark}{:<4} {:<8} {}",
                row.issue.number,
                age_cell(row.age_days),
                row.issue.title
            );
        }
        if let Some(row) = self.current() {
            let _ = writeln!(out, "\n{}", decision_summary(row));
        }
        if let Some(note) = self.display_note() {
            let _ = writeln!(out, "\n{note}");
        }
        let _ = write!(out, "\n{}", self.footer());
        out
    }
}

/// The age cell: a number of days, `today` for zero, `unknown` for no stamp.
///
/// Duplicated from `commands::triage::age_cell`, which is private to that
/// module: a reader who sees `0` believes the issue arrived today, and
/// `unknown` is the whole point of the entry stamp. The two spellings are
/// pinned together by
/// `triage_tui_the_inbox_counts_are_the_clis_counts_for_the_same_snapshot`,
/// which strips the inbox row's cursor and mark and compares the rest with
/// `tix triage list`'s own row — byte for byte, age cell included.
fn age_cell(age: Option<i64>) -> String {
    match age {
        Some(0) => "today".to_string(),
        Some(days) => format!("{days}d"),
        None => "unknown".to_string(),
    }
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

/// Render the Triage mode's content: a toolbar, the queue, and — over it — the
/// decision modal or an open picker.
///
/// Never asserts on pixels; a test reads the buffer or the hit regions this
/// records.
pub fn render(app: &App, frame: &mut Frame, area: Rect, state: &TriageState) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" triage ")
        .border_style(Style::default().fg(Color::Cyan));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(1)])
        .split(inner);

    // The toolbar: the queue, the two pickers and the create action, each with
    // its own clickable region (keyboard parity: `s`, `@`, `n` — and `h`/`l`
    // to walk the bar). The focused control is drawn inverse; that is the whole
    // focus model on screen.
    let labels = control_labels(state);
    let mut spans: Vec<Span> = Vec::new();
    for (index, (control, label)) in labels.iter().enumerate() {
        if index > 0 {
            spans.push(Span::raw("   "));
        }
        spans.push(Span::styled(
            label.clone(),
            control_style(*control, state.focus),
        ));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), chunks[0]);

    if state.modal.is_none() && !state.creating {
        for (control, rect) in control_rects(area, state) {
            app.record_region(rect, control_action(control));
        }
    }

    if state.creating {
        let line = Line::from(vec![
            Span::styled(
                "new issue title: ",
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::raw(format!("{}█", state.create_buffer)),
        ]);
        frame.render_widget(Paragraph::new(line), chunks[1]);
        return;
    }

    frame.render_widget(Paragraph::new(state.body()), chunks[1]);

    if let Some(modal) = state.modal.as_ref() {
        render_modal(frame, area, modal);
    }
    if state.dropdown.is_some() {
        render_dropdown(app, frame, area, state);
    }
}

/// The toolbar's labels, in [`TriageControl::ALL`] order.
///
/// The three labelled controls keep the `[s]`/`[@]`/`[n]` key prefixes a user
/// already reads; the queue has no activation key, so its label is the bare
/// word.
fn control_labels(state: &TriageState) -> [(TriageControl, String); 4] {
    let status = state
        .current()
        .map(|row| row.issue.status.display().to_string())
        .unwrap_or_else(|| "—".to_string());
    let assignee = state
        .current()
        .and_then(|row| row.issue.assignee.clone())
        .unwrap_or_else(|| "unassigned".to_string());
    [
        (TriageControl::Queue, "queue".to_string()),
        (TriageControl::Status, format!("[s] status: {status}")),
        (TriageControl::Assignee, format!("[@] assignee: {assignee}")),
        (TriageControl::New, "[n] new issue".to_string()),
    ]
}

/// The style of one toolbar control: its own colour, plus the focus marker when
/// it is the focused one.
///
/// Inverse rather than a second pair of brackets: the labels already carry
/// `[s]`/`[@]`/`[n]`, and a bracket around a bracket reads as a third key.
fn control_style(control: TriageControl, focus: TriageControl) -> Style {
    let color = match control {
        TriageControl::Queue => Color::White,
        TriageControl::Status => Color::Cyan,
        TriageControl::Assignee => Color::Green,
        TriageControl::New => Color::Yellow,
    };
    let style = Style::default().fg(color);
    if control == focus {
        style.add_modifier(Modifier::REVERSED | Modifier::BOLD)
    } else {
        style
    }
}

/// What a click on `control` records: activating it — the same thing `enter`
/// does — except for the queue, whose click only moves the focus there.
fn control_action(control: TriageControl) -> Action {
    match control {
        TriageControl::Queue => Action::TriageFocusQueue,
        TriageControl::Status => Action::TriageOpenStatus,
        TriageControl::Assignee => Action::TriageOpenAssignee,
        TriageControl::New => Action::TriageCreate,
    }
}

fn label_width(label: &str) -> u16 {
    label.chars().count() as u16
}

/// The click rects of the toolbar controls, in [`TriageControl::ALL`] order —
/// the same geometry [`render`] records, exposed so a test can click a control,
/// or check which one carries the focus, without re-deriving the layout.
#[must_use]
pub fn control_rects(area: Rect, state: &TriageState) -> [(TriageControl, Rect); 4] {
    let inner = Block::default().borders(Borders::ALL).inner(area);
    let mut x = inner.x;
    control_labels(state).map(|(control, label)| {
        let width = label_width(&label).min(inner.width.saturating_sub(x.saturating_sub(inner.x)));
        let rect = Rect::new(x, inner.y, width, 1);
        x = x.saturating_add(width).saturating_add(3);
        (control, rect)
    })
}

/// Where an open picker draws inside `area`, and the rect of each visible
/// option row. `None` when no picker is open or there is nothing to show.
#[must_use]
pub fn dropdown_layout(area: Rect, state: &TriageState) -> Option<(Rect, Vec<Rect>)> {
    let dropdown = state.dropdown.as_ref()?;
    let visible = dropdown.state.visible_indices();
    if visible.is_empty() {
        return None;
    }
    let inner = Block::default().borders(Borders::ALL).inner(area);
    let widest = visible
        .iter()
        .map(|index| label_width(&dropdown.state.options[*index].label))
        .max()
        .unwrap_or(0);
    let width = (widest + 4).clamp(6, inner.width.max(6));
    let height = (visible.len() as u16 + 2).min(inner.height.max(3));
    if height < 3 || inner.width == 0 {
        return None;
    }
    let rect = Rect::new(inner.x, inner.y, width, height);
    let rows = (0..visible.len() as u16)
        .take(height as usize - 2)
        .map(|row| Rect::new(rect.x, rect.y + 1 + row, rect.width, 1))
        .collect();
    Some((rect, rows))
}

fn render_modal(frame: &mut Frame, area: Rect, modal: &TriageModal) {
    let modal_rect = crate::ui::modal::modal_rect(area);
    frame.render_widget(Clear, modal_rect);
    let modal_block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" {} — {} ", modal.kind, modal.state_label()))
        .border_style(Style::default().fg(Color::Magenta));
    let modal_inner = modal_block.inner(modal_rect);
    frame.render_widget(modal_block, modal_rect);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(1)])
        .split(modal_inner);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            modal.heading.clone(),
            Style::default().add_modifier(Modifier::BOLD),
        ))),
        chunks[0],
    );
    frame.render_widget(Paragraph::new(modal.body()), chunks[1]);
}

fn render_dropdown(app: &App, frame: &mut Frame, area: Rect, state: &TriageState) {
    let Some(dropdown) = state.dropdown.as_ref() else {
        return;
    };
    let Some((rect, rows)) = dropdown_layout(area, state) else {
        return;
    };
    // Clicking anywhere outside the list closes it. Recorded first, so the
    // option rows recorded below win on overlap (innermost/last wins).
    app.record_region(area, Action::TriageDropdownClose);
    frame.render_widget(Clear, rect);
    let title = match dropdown.kind {
        TriageDropdownKind::Status => " choose status ",
        TriageDropdownKind::Assignee => " choose assignee ",
    };
    let block = Block::default().borders(Borders::ALL).title(title);
    let inner = block.inner(rect);
    frame.render_widget(block, rect);

    let visible = dropdown.state.visible_indices();
    let lines: Vec<Line> = visible
        .iter()
        .enumerate()
        .map(|(row, index)| {
            let option = &dropdown.state.options[*index];
            let cursor = if row == dropdown.state.cursor {
                ">"
            } else {
                " "
            };
            Line::from(format!("{cursor} {}", option.label))
        })
        .collect();
    frame.render_widget(Paragraph::new(lines), inner);
    for (row, row_rect) in rows.iter().enumerate() {
        app.record_region(*row_rect, Action::TriagePickOption(row));
    }
}

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

    /// Every WP06 unit test is named `triage_tui_*`, matching the gate
    /// `cargo test --test tui_state` and the naming the other triage work
    /// packages use.
    #[test]
    fn triage_tui_fields_exist_only_for_the_decision_that_can_use_them() {
        let one = ModalScope::One(1);
        let accept = TriageModal::new(DecisionKind::Accept, one.clone(), "a".into());
        assert_eq!(
            accept.fields,
            vec![
                DecisionField::Reason,
                DecisionField::Actor,
                DecisionField::Target
            ]
        );
        let decline = TriageModal::new(DecisionKind::Decline, one.clone(), "d".into());
        assert_eq!(
            decline.fields,
            vec![DecisionField::Reason, DecisionField::Actor],
            "`--to` has nowhere to be typed on a decline, so it cannot be"
        );
        let duplicate = TriageModal::new(DecisionKind::Duplicate, one.clone(), "u".into());
        assert_eq!(
            duplicate.fields,
            vec![
                DecisionField::Reason,
                DecisionField::Actor,
                DecisionField::DuplicateOf
            ]
        );
        let defer = TriageModal::new(DecisionKind::Defer, one, "f".into());
        assert_eq!(
            defer.fields,
            vec![DecisionField::Reason, DecisionField::Actor]
        );
    }

    #[test]
    fn triage_tui_the_cursor_only_moves_over_the_fields_the_decision_has() {
        let mut modal = TriageModal::new(DecisionKind::Decline, ModalScope::One(1), "d".into());
        modal.move_cursor(1);
        assert_eq!(modal.field(modal.cursor), DecisionField::Actor);
        modal.move_cursor(1);
        assert_eq!(
            modal.field(modal.cursor),
            DecisionField::Reason,
            "two fields, so the third step wraps back to the first"
        );
        modal.move_cursor(-1);
        assert_eq!(modal.field(modal.cursor), DecisionField::Actor);
    }

    #[test]
    fn triage_tui_a_cancelled_draft_never_reaches_the_row_it_was_typed_into() {
        let mut modal = TriageModal::new(DecisionKind::Decline, ModalScope::One(1), "d".into());
        modal.begin_edit();
        for c in "half a reason".chars() {
            modal.push_char(c);
        }
        modal.abort_edit();
        assert!(!modal.editing);
        assert_eq!(modal.reason, "", "the row never saw the draft");
    }

    #[test]
    fn triage_tui_a_committed_draft_lands_on_the_row_under_the_cursor() {
        let mut modal = TriageModal::new(DecisionKind::Decline, ModalScope::One(1), "d".into());
        modal.begin_edit();
        for c in "no budget".chars() {
            modal.push_char(c);
        }
        modal.commit_edit();
        assert_eq!(modal.reason, "no budget");
        assert_eq!(modal.field_value(modal.field(0)), "no budget");
    }

    #[test]
    fn triage_tui_an_accept_without_a_configured_target_names_none() {
        let config = crate::config::Config::default();
        let modal = TriageModal::new(DecisionKind::Accept, ModalScope::One(1), "a".into());
        let request = modal.request(&Store::open(&config).expect("an empty store opens"));
        assert_eq!(
            request.target_status, None,
            "no `--to` and no `[triage].accepted_status` means the service \
             refuses `missing_target`, exactly as the CLI does"
        );
    }

    #[test]
    fn triage_tui_the_header_is_the_cli_headers_wording() {
        let summary = TriageSummary {
            total: 3,
            awaiting: 2,
            deferred: 1,
            accepted: 0,
            declined: 0,
            duplicated: 0,
            unknown_age: 1,
            age: Vec::new(),
        };
        assert_eq!(
            summary.header(),
            "inbox: 3 entries (2 awaiting, 1 deferred)"
        );
    }

    #[test]
    fn triage_tui_an_unknown_age_is_unknown_and_never_zero() {
        assert_eq!(age_cell(None), "unknown");
        assert_eq!(age_cell(Some(0)), "today");
        assert_eq!(age_cell(Some(7)), "7d");
    }

    #[test]
    fn triage_tui_the_footer_names_only_keys_that_mean_something_now() {
        let mut modal = TriageModal::new(DecisionKind::Decline, ModalScope::One(1), "d".into());
        assert!(modal.footer().contains("p preview"), "editing: preview");
        modal.begin_edit();
        assert!(
            modal.footer().contains("enter commit"),
            "a letter while editing must not be advertised as a command"
        );
        assert!(!modal.footer().contains("p preview"));
    }

    #[test]
    fn triage_tui_status_options_are_the_board_columns_in_order() {
        let columns = vec!["triage".to_string(), "todo".to_string(), "done".to_string()];
        let labels: Vec<String> = status_options(&columns)
            .into_iter()
            .map(|option| option.label)
            .collect();
        assert_eq!(labels, vec!["triage", "todo", "done"]);
    }

    #[test]
    fn triage_tui_assignee_options_are_folders_teams_and_current() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut config = crate::config::Config {
            issues_dir: tmp.path().to_path_buf(),
            ..crate::config::Config::default()
        };
        std::fs::create_dir_all(config.issues_dir.join("alice")).unwrap();
        std::fs::create_dir_all(config.issues_dir.join("bob")).unwrap();
        // The reserved fallback is not a person and is not an option.
        std::fs::create_dir_all(config.issues_dir.join("unassigned")).unwrap();
        config.teams.insert(
            "core".to_string(),
            crate::config::Team {
                members: vec!["carol".to_string()],
            },
        );
        let store = Store::open(&config).unwrap();

        let labels: Vec<String> = assignee_options(&store, Some("zoe"))
            .into_iter()
            .map(|option| option.label)
            .collect();

        assert_eq!(
            labels,
            vec!["alice", "bob", "carol", "zoe"],
            "folders first, then team members, then the current value"
        );
    }
}