codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
//! Documentation-only catalog of every user-facing keybinding.
//!
//! This module is the *single source of truth* for what shortcuts the help
//! overlay renders. The actual key handlers live in `tui/ui.rs` (and a few
//! sibling modules); they read keys directly off the crossterm event stream
//! and intentionally do **not** consult this catalog. The catalog exists so
//! that:
//!
//! 1. The help overlay (`tui/views/help.rs`) does not have to maintain a
//!    parallel list that silently rots when a handler is added or moved.
//! 2. New contributors have one place to look when answering "which keys are
//!    bound, and where do they go?"
//!
//! When you add or change a binding in `ui.rs`, **add or update the matching
//! entry here**. The compile-only side-effect of forgetting is a stale help
//! screen; there is no runtime crash, so the discipline lives in code review.
//!
//! Entries are grouped by `KeybindingSection`. The `chord` field is a
//! human-readable string formatted exactly the way it should appear in help —
//! we avoid storing `KeyBinding` values directly because many shortcuts are
//! pairs (`↑/↓`) or families (`1-8`) that don't map cleanly to a single
//! chord.

use std::borrow::Cow;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeybindingSection {
    Navigation,
    Editing,
    Submission,
    Modes,
    Sessions,
    Clipboard,
    Help,
}

impl KeybindingSection {
    pub fn label(self, locale: crate::localization::Locale) -> Cow<'static, str> {
        use crate::localization::{MessageId, tr};
        let id = match self {
            Self::Navigation => MessageId::HelpSectionNavigation,
            Self::Editing => MessageId::HelpSectionEditing,
            Self::Submission => MessageId::HelpSectionActions,
            Self::Modes => MessageId::HelpSectionModes,
            Self::Sessions => MessageId::HelpSectionSessions,
            Self::Clipboard => MessageId::HelpSectionClipboard,
            Self::Help => MessageId::HelpSectionHelp,
        };
        tr(locale, id)
    }

    /// Stable ordering for help rendering — matches the variant declaration
    /// order; explicit so adding a section forces a deliberate placement.
    pub fn rank(self) -> u8 {
        match self {
            Self::Navigation => 0,
            Self::Editing => 1,
            Self::Submission => 2,
            Self::Modes => 3,
            Self::Sessions => 4,
            Self::Clipboard => 5,
            Self::Help => 6,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct KeybindingEntry {
    pub chord: &'static str,
    pub description_id: crate::localization::MessageId,
    pub section: KeybindingSection,
}

/// Canonical list of keybindings shown in the help overlay.
///
/// Strings are written in the same notation the existing help screen uses so
/// readers can cross-reference with documentation: `Ctrl+X`, `Alt+X`,
/// `Shift+X`, `↑/↓`, `PgUp/PgDn`, etc. Help renderers may apply per-platform
/// substitutions (e.g. `⌥` for Alt on macOS) at render time, but the catalog
/// itself stores the portable form.
pub const KEYBINDINGS: &[KeybindingEntry] = &[
    // --- Navigation ---
    KeybindingEntry {
        chord: "↑ / ↓",
        description_id: crate::localization::MessageId::KbScrollTranscript,
        section: KeybindingSection::Navigation,
    },
    KeybindingEntry {
        chord: "Alt+↑ / Alt+↓",
        description_id: crate::localization::MessageId::KbScrollTranscriptAlt,
        section: KeybindingSection::Navigation,
    },
    KeybindingEntry {
        chord: "Shift+↑ / Shift+↓",
        description_id: crate::localization::MessageId::KbBrowseHistory,
        section: KeybindingSection::Navigation,
    },
    KeybindingEntry {
        chord: "PgUp / PgDn",
        description_id: crate::localization::MessageId::KbScrollPage,
        section: KeybindingSection::Navigation,
    },
    KeybindingEntry {
        chord: "Ctrl+Home / Ctrl+End",
        description_id: crate::localization::MessageId::KbJumpTopBottom,
        section: KeybindingSection::Navigation,
    },
    KeybindingEntry {
        chord: "Alt+G / Alt+Shift+G",
        description_id: crate::localization::MessageId::KbJumpTopBottomEmpty,
        section: KeybindingSection::Navigation,
    },
    KeybindingEntry {
        chord: "Alt+[ / Alt+]",
        description_id: crate::localization::MessageId::KbJumpToolBlocks,
        section: KeybindingSection::Navigation,
    },
    // --- Editing ---
    KeybindingEntry {
        chord: "← / → / Ctrl+←/→ / Alt+←/→",
        description_id: crate::localization::MessageId::KbMoveCursor,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Home / End",
        description_id: crate::localization::MessageId::KbJumpLineStartEnd,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+A / Ctrl+E",
        description_id: crate::localization::MessageId::KbJumpLineStartEnd,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Backspace / Delete",
        description_id: crate::localization::MessageId::KbDeleteChar,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+W / Ctrl+Backspace / Alt+Backspace",
        description_id: crate::localization::MessageId::KbDeleteWord,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+Y",
        description_id: crate::localization::MessageId::KbYank,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+Shift+E / Cmd+Shift+E",
        description_id: crate::localization::MessageId::KbToggleFileTree,
        section: KeybindingSection::Navigation,
    },
    KeybindingEntry {
        chord: "Shift+←/→ / Shift+Home/End / Ctrl+Shift+←/→ / Alt+Shift+←/→ / Ctrl+Shift+Home/End",
        description_id: crate::localization::MessageId::KbSelectText,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        // Ctrl+A keeps its readline meaning (start of input); select-all is
        // the shifted chord, plus native Cmd+A on terminals that forward Cmd.
        chord: "Ctrl+Shift+A / Cmd+A",
        description_id: crate::localization::MessageId::KbSelectAllDraft,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+U",
        description_id: crate::localization::MessageId::KbClearDraft,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+Z",
        description_id: crate::localization::MessageId::KbRestoreClearedDraft,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+G / Ctrl+S",
        description_id: crate::localization::MessageId::KbStashDraft,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Alt+R",
        description_id: crate::localization::MessageId::KbSearchHistory,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        chord: "Ctrl+J / Alt+Enter / Shift+Enter",
        description_id: crate::localization::MessageId::KbInsertNewline,
        section: KeybindingSection::Editing,
    },
    // --- Submission / actions ---
    KeybindingEntry {
        chord: "Enter",
        description_id: crate::localization::MessageId::KbSendDraft,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Esc",
        description_id: crate::localization::MessageId::KbCloseMenu,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+C",
        description_id: crate::localization::MessageId::KbCancelOrExit,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+B",
        description_id: crate::localization::MessageId::KbShellControls,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+D",
        description_id: crate::localization::MessageId::KbExitEmpty,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+K",
        description_id: crate::localization::MessageId::KbCommandPalette,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "F2",
        description_id: crate::localization::MessageId::KbSettings,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+X (Activity sidebar)",
        description_id: crate::localization::MessageId::KbCancelBackgroundShellJobs,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+P",
        description_id: crate::localization::MessageId::KbFuzzyFilePicker,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        // `/context` is the guaranteed path; Alt+C is an unadvertised
        // handler until proven in real terminals (TUI-DOG-003).
        chord: "/context",
        description_id: crate::localization::MessageId::KbCompactInspector,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Alt+L",
        description_id: crate::localization::MessageId::KbLastMessagePager,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        // Bare `v` always types `v`; details is Alt+V only (⌥V on macOS).
        chord: "Alt+V",
        description_id: crate::localization::MessageId::KbSelectedDetails,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+O",
        description_id: crate::localization::MessageId::KbReasoningDetail,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+Alt+O",
        description_id: crate::localization::MessageId::KbTurnInspector,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+Shift+O / F4",
        description_id: crate::localization::MessageId::KbExternalEditor,
        section: KeybindingSection::Editing,
    },
    KeybindingEntry {
        // `/transcript` is the reliable fallback when a terminal cannot
        // distinguish Ctrl+Shift+T from Ctrl+T.
        chord: "/transcript / Ctrl+Shift+T",
        description_id: crate::localization::MessageId::KbLiveTranscript,
        section: KeybindingSection::Submission,
    },
    KeybindingEntry {
        chord: "Ctrl+T",
        description_id: crate::localization::MessageId::KbCycleThinking,
        section: KeybindingSection::Modes,
    },
    KeybindingEntry {
        chord: "Esc Esc",
        description_id: crate::localization::MessageId::KbBacktrackMessage,
        section: KeybindingSection::Submission,
    },
    // --- Modes ---
    KeybindingEntry {
        chord: "Tab",
        description_id: crate::localization::MessageId::KbCompleteCycleModes,
        section: KeybindingSection::Modes,
    },
    KeybindingEntry {
        chord: "Shift+Tab",
        description_id: crate::localization::MessageId::KbCyclePermissions,
        section: KeybindingSection::Modes,
    },
    KeybindingEntry {
        chord: "Alt+1-8",
        description_id: crate::localization::MessageId::KbJumpPlanAgentYolo,
        section: KeybindingSection::Modes,
    },
    KeybindingEntry {
        chord: "Alt+P / Alt+A / Alt+Y",
        description_id: crate::localization::MessageId::KbAltJumpPlanAgentYolo,
        section: KeybindingSection::Modes,
    },
    KeybindingEntry {
        chord: "Alt+! / Alt+@ / Alt+# / Alt+$ / Alt+0 / Ctrl+Alt+0",
        description_id: crate::localization::MessageId::KbFocusSidebar,
        section: KeybindingSection::Modes,
    },
    // --- Sessions ---
    KeybindingEntry {
        chord: "Ctrl+R",
        description_id: crate::localization::MessageId::KbSessionPicker,
        section: KeybindingSection::Sessions,
    },
    KeybindingEntry {
        chord: "Ctrl+L",
        description_id: crate::localization::MessageId::KbCompactContext,
        section: KeybindingSection::Sessions,
    },
    // --- Clipboard ---
    KeybindingEntry {
        // Keep both terminal-client families visible: the TUI may be running
        // on Linux while the user's SSH terminal is on macOS (or vice versa).
        chord: "Cmd+V / Ctrl+Shift+V",
        description_id: crate::localization::MessageId::KbTerminalPaste,
        section: KeybindingSection::Clipboard,
    },
    KeybindingEntry {
        chord: "Ctrl+V",
        description_id: crate::localization::MessageId::KbPasteAttach,
        section: KeybindingSection::Clipboard,
    },
    KeybindingEntry {
        // Terminal-native copy chords are normally consumed by the local
        // terminal and never become Codewhale key events. Ctrl+C is the
        // reliable in-app copy path when a Codewhale selection is active.
        chord: "Ctrl+C (selection)",
        description_id: crate::localization::MessageId::KbCopySelection,
        section: KeybindingSection::Clipboard,
    },
    KeybindingEntry {
        chord: "Right click",
        description_id: crate::localization::MessageId::KbContextMenu,
        section: KeybindingSection::Clipboard,
    },
    KeybindingEntry {
        chord: "@path",
        description_id: crate::localization::MessageId::KbAttachPath,
        section: KeybindingSection::Clipboard,
    },
    // --- Help ---
    KeybindingEntry {
        // F1 is primary (with /help); Ctrl+/ is the secondary fallback.
        // Alt+? stays an unadvertised handler (TUI-DOG-003).
        chord: "F1 / Ctrl+/",
        description_id: crate::localization::MessageId::KbHelpOverlay,
        section: KeybindingSection::Help,
    },
];

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

    #[test]
    fn catalog_is_non_empty_and_sections_have_entries() {
        assert!(KEYBINDINGS.iter().any(|entry| !entry.chord.is_empty()));
        // Every declared section should appear in the catalog at least once,
        // otherwise the help overlay would render an empty heading.
        let sections = [
            KeybindingSection::Navigation,
            KeybindingSection::Editing,
            KeybindingSection::Submission,
            KeybindingSection::Modes,
            KeybindingSection::Sessions,
            KeybindingSection::Clipboard,
            KeybindingSection::Help,
        ];
        for section in sections {
            assert!(
                KEYBINDINGS.iter().any(|entry| entry.section == section),
                "no entries for section {section:?}"
            );
        }
    }

    #[test]
    fn help_advertises_f1_and_ctrl_slash_never_alt_question() {
        // TUI-DOG-003: Alt+? is not advertised anywhere; F1 (with /help) is
        // primary and Ctrl+/ is the secondary fallback.
        assert!(
            KEYBINDINGS.iter().any(|entry| {
                entry.section == KeybindingSection::Help
                    && entry.chord.contains("F1")
                    && entry.chord.contains("Ctrl+/")
            }),
            "help must document F1 with the Ctrl+/ fallback"
        );
        assert!(
            KEYBINDINGS
                .iter()
                .all(|entry| !entry.chord.contains("Alt+?")),
            "Alt+? must not be advertised in the help catalog"
        );
    }

    #[test]
    fn composer_catalog_assigns_one_stable_role_to_each_chord() {
        let chord_for = |id| {
            KEYBINDINGS
                .iter()
                .find(|entry| entry.description_id == id)
                .expect("composer binding should be documented")
                .chord
        };

        assert_eq!(
            chord_for(crate::localization::MessageId::KbInsertNewline),
            "Ctrl+J / Alt+Enter / Shift+Enter"
        );
        assert!(
            KEYBINDINGS
                .iter()
                .all(|entry| !entry.chord.contains("Ctrl+Enter")
                    && !entry.chord.contains("Cmd+Enter"))
        );
        assert_eq!(
            chord_for(crate::localization::MessageId::KbStashDraft),
            "Ctrl+G / Ctrl+S"
        );
        assert_eq!(
            chord_for(crate::localization::MessageId::KbSendDraft),
            "Enter"
        );

        let tab_copy = crate::localization::tr(
            crate::localization::Locale::En,
            crate::localization::MessageId::KbCompleteCycleModes,
        );
        assert!(!tab_copy.to_ascii_lowercase().contains("queue"));
        let stash_copy = crate::localization::tr(
            crate::localization::Locale::En,
            crate::localization::MessageId::KbStashDraft,
        );
        assert!(!stash_copy.to_ascii_lowercase().contains("send"));
    }

    #[test]
    fn clipboard_help_distinguishes_terminal_text_graphical_image_and_in_app_copy() {
        let terminal_paste = KEYBINDINGS
            .iter()
            .find(|entry| entry.description_id == crate::localization::MessageId::KbTerminalPaste)
            .expect("terminal paste binding should be documented");
        let graphical_paste = KEYBINDINGS
            .iter()
            .find(|entry| entry.description_id == crate::localization::MessageId::KbPasteAttach)
            .expect("graphical paste binding should be documented");
        let copy = KEYBINDINGS
            .iter()
            .find(|entry| entry.description_id == crate::localization::MessageId::KbCopySelection)
            .expect("copy binding should be documented");

        assert!(terminal_paste.chord.contains("Cmd+V"));
        assert!(terminal_paste.chord.contains("Ctrl+Shift+V"));
        assert_eq!(graphical_paste.chord, "Ctrl+V");
        let terminal_description = crate::localization::tr(
            crate::localization::Locale::En,
            crate::localization::MessageId::KbTerminalPaste,
        );
        let graphical_description = crate::localization::tr(
            crate::localization::Locale::En,
            crate::localization::MessageId::KbPasteAttach,
        );
        assert!(!terminal_description.to_ascii_lowercase().contains("image"));
        assert!(graphical_description.to_ascii_lowercase().contains("image"));
        assert_eq!(copy.chord, "Ctrl+C (selection)");
        assert!(!copy.chord.contains("Cmd+C"));
        assert!(!copy.chord.contains("Ctrl+Shift+C"));
    }

    #[test]
    fn transcript_navigation_catalog_does_not_advertise_bare_typing_keys() {
        for stale in [
            "g / G",
            "[ / ]",
            "l",
            "?",
            "Ctrl+↑ / Ctrl+↓",
            "v",
            "v / Alt+V",
        ] {
            assert!(
                KEYBINDINGS.iter().all(|entry| entry.chord != stale),
                "stale handler-free chord remains documented: {stale}"
            );
        }
        for wired in ["Alt+G / Alt+Shift+G", "Alt+[ / Alt+]", "Alt+L", "Alt+V"] {
            assert!(
                KEYBINDINGS.iter().any(|entry| entry.chord == wired),
                "wired transcript shortcut missing from help: {wired}"
            );
        }
    }

    #[test]
    fn live_transcript_documents_command_before_shaky_chord() {
        let transcript = KEYBINDINGS
            .iter()
            .find(|entry| entry.description_id == crate::localization::MessageId::KbLiveTranscript)
            .expect("live transcript entry should be documented");

        assert_eq!(transcript.chord, "/transcript / Ctrl+Shift+T");
    }

    #[test]
    fn shell_binding_source_matches_help_catalog_chords() {
        use crate::tui::shell_key_routing::{ShellBindingId, binding};
        assert_eq!(binding(ShellBindingId::ToolDetails).catalog_chord, "Alt+V");
        assert_eq!(
            binding(ShellBindingId::ContextInspector).catalog_chord,
            "/context"
        );
        assert_eq!(binding(ShellBindingId::Help).catalog_chord, "F1 / Ctrl+/");
        for id in [
            ShellBindingId::ToolDetails,
            ShellBindingId::ContextInspector,
            ShellBindingId::Help,
        ] {
            let chord = binding(id).catalog_chord;
            assert!(
                KEYBINDINGS
                    .iter()
                    .any(|entry| entry.chord == chord || entry.chord.contains(chord)),
                "shell binding {id:?} chord missing from help catalog: {chord}"
            );
        }
    }

    #[test]
    fn ctrl_o_and_ctrl_alt_o_help_copy_match_split_surfaces() {
        let ctrl_o = KEYBINDINGS
            .iter()
            .find(|entry| entry.chord == "Ctrl+O")
            .expect("Ctrl+O keybinding should be documented");

        // Ctrl+O now opens the full recorded Reasoning Detail; the whole-turn
        // Turn Inspector moved to Ctrl+Alt+O.
        assert_eq!(
            ctrl_o.description_id,
            crate::localization::MessageId::KbReasoningDetail
        );
        assert_eq!(
            crate::localization::tr(crate::localization::Locale::En, ctrl_o.description_id,),
            "Open reasoning detail for the selected or current turn"
        );

        let ctrl_alt_o = KEYBINDINGS
            .iter()
            .find(|entry| entry.chord == "Ctrl+Alt+O")
            .expect("Ctrl+Alt+O keybinding should be documented");
        assert_eq!(
            ctrl_alt_o.description_id,
            crate::localization::MessageId::KbTurnInspector
        );
        assert_eq!(
            crate::localization::tr(crate::localization::Locale::En, ctrl_alt_o.description_id,),
            "Open Turn Inspector"
        );

        let editor = KEYBINDINGS
            .iter()
            .find(|entry| entry.chord == "Ctrl+Shift+O / F4")
            .expect("external-editor keybinding should be documented");
        assert_eq!(
            crate::localization::tr(crate::localization::Locale::En, editor.description_id,),
            "Open composer draft in external editor"
        );
    }

    #[test]
    fn ctrl_x_activity_sidebar_cancel_all_is_documented() {
        let ctrl_x_activity = KEYBINDINGS
            .iter()
            .find(|entry| entry.chord == "Ctrl+X (Activity sidebar)")
            .expect("Ctrl+X Activity sidebar keybinding should be documented");

        assert_eq!(
            ctrl_x_activity.description_id,
            crate::localization::MessageId::KbCancelBackgroundShellJobs
        );
    }

    #[test]
    fn tool_details_documents_alt_v_only_never_bare_v() {
        let selected_details = KEYBINDINGS
            .iter()
            .filter(|entry| {
                entry.description_id == crate::localization::MessageId::KbSelectedDetails
            })
            .map(|entry| entry.chord)
            .collect::<Vec<_>>();

        // TUI-DOG-002: bare `v` always types `v`; details is Alt+V only.
        assert_eq!(selected_details, vec!["Alt+V"]);
        assert!(
            KEYBINDINGS
                .iter()
                .all(|entry| entry.chord != "v" && !entry.chord.starts_with("v /")),
            "bare `v` must not be advertised — composer typing owns it"
        );
    }

    /// #3758: a user who reads the help overlay must be able to answer "what
    /// does this key do?" with one answer. A key may appear twice only when
    /// every occurrence but one names its context in parentheses — the way
    /// `Ctrl+C` and `Ctrl+C (selection)` do — so the reader is told which
    /// reading applies. Two unqualified entries for the same key is the
    /// ambiguity this guard exists to reject.
    #[test]
    fn every_advertised_key_names_exactly_one_canonical_action() {
        struct Use {
            chord: &'static str,
            alternative: String,
            description_id: crate::localization::MessageId,
        }

        let mut uses_by_key: std::collections::BTreeMap<String, Vec<Use>> =
            std::collections::BTreeMap::new();
        for entry in KEYBINDINGS {
            for alternative in entry.chord.split(" / ") {
                let alternative = alternative.trim();
                // `Ctrl+C (selection)` → base key `Ctrl+C`, qualifier retained
                // on the alternative so the check below can see it.
                let base = alternative
                    .split_once(" (")
                    .map(|(head, _)| head)
                    .unwrap_or(alternative)
                    .trim()
                    .to_string();
                uses_by_key.entry(base).or_default().push(Use {
                    chord: entry.chord,
                    alternative: alternative.to_string(),
                    description_id: entry.description_id,
                });
            }
        }

        for (key, uses) in &uses_by_key {
            if uses.len() == 1 {
                continue;
            }
            let single_action = uses
                .iter()
                .all(|entry| entry.description_id == uses[0].description_id);
            if single_action {
                // The same action documented from two spellings is fine —
                // `Home / End` and `Ctrl+A / Ctrl+E` both jump to line edges.
                continue;
            }
            let unqualified: Vec<&str> = uses
                .iter()
                .filter(|entry| !entry.alternative.contains('('))
                .map(|entry| entry.chord)
                .collect();
            assert!(
                unqualified.len() <= 1,
                "{key} is advertised for more than one action without naming the \
                 context that selects between them: {unqualified:?}"
            );
        }
    }

    /// #440 / #3758: `Ctrl+G` and `Ctrl+S` stash the draft. They are not a
    /// send, a queue, a steer, or a file save, and a real-terminal report that
    /// says otherwise is reading ambiguous copy, not misusing the key.
    #[test]
    fn stash_chords_advertise_stashing_and_nothing_else() {
        let stash_entries: Vec<&KeybindingEntry> = KEYBINDINGS
            .iter()
            .filter(|entry| {
                entry
                    .chord
                    .split(" / ")
                    .map(str::trim)
                    .any(|chord| matches!(chord, "Ctrl+G" | "Ctrl+S"))
            })
            .collect();

        assert_eq!(
            stash_entries.len(),
            1,
            "Ctrl+G / Ctrl+S must be documented exactly once, together"
        );
        assert_eq!(stash_entries[0].chord, "Ctrl+G / Ctrl+S");
        assert_eq!(
            stash_entries[0].description_id,
            crate::localization::MessageId::KbStashDraft
        );

        let copy = crate::localization::tr(
            crate::localization::Locale::En,
            crate::localization::MessageId::KbStashDraft,
        )
        .to_ascii_lowercase();
        for forbidden in ["send", "queue", "steer", "submit", "save"] {
            assert!(
                !copy.contains(forbidden),
                "stash copy must not read as {forbidden:?}: {copy:?}"
            );
        }
        assert!(
            copy.contains("stash"),
            "stash copy must name the action it performs: {copy:?}"
        );
    }

    /// Only chords distinguishable by the baseline terminal protocol may be
    /// advertised. Enter sends or queues (then sends a queued message now),
    /// while the newline chords stay newlines.
    #[test]
    fn running_turn_verbs_belong_to_one_chord_each() {
        let entry_for = |id| {
            KEYBINDINGS
                .iter()
                .find(|entry| entry.description_id == id)
                .expect("running-turn binding should be documented")
        };

        assert_eq!(
            entry_for(crate::localization::MessageId::KbSendDraft).chord,
            "Enter"
        );
        assert!(
            KEYBINDINGS
                .iter()
                .all(|entry| !entry.chord.contains("Ctrl+Enter")
                    && !entry.chord.contains("Cmd+Enter"))
        );
        assert_eq!(
            entry_for(crate::localization::MessageId::KbInsertNewline).chord,
            "Ctrl+J / Alt+Enter / Shift+Enter"
        );

        let newline_copy = crate::localization::tr(
            crate::localization::Locale::En,
            crate::localization::MessageId::KbInsertNewline,
        )
        .to_ascii_lowercase();
        for forbidden in ["send", "steer", "queue"] {
            assert!(
                !newline_copy.contains(forbidden),
                "newline chords must not read as {forbidden:?}: {newline_copy:?}"
            );
        }
    }

    #[test]
    fn section_rank_is_a_total_order() {
        let sections = [
            KeybindingSection::Navigation,
            KeybindingSection::Editing,
            KeybindingSection::Submission,
            KeybindingSection::Modes,
            KeybindingSection::Sessions,
            KeybindingSection::Clipboard,
            KeybindingSection::Help,
        ];
        let mut ranks: Vec<u8> = sections.iter().map(|s| s.rank()).collect();
        ranks.sort_unstable();
        ranks.dedup();
        assert_eq!(ranks.len(), sections.len(), "ranks must be unique");
    }

    // ------------------------------------------------------------------
    // docs/KEYBINDINGS.md <-> KEYBINDINGS bidirectional drift gate
    // ------------------------------------------------------------------

    const KEYBINDINGS_DOC: &str = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../docs/KEYBINDINGS.md"
    ));

    /// Doc table chords that are deliberately NOT in the help catalog.
    /// Every entry needs a justification; adding one is a reviewed decision.
    const DOC_CHORD_ALLOWLIST: &[&str] = &[
        // Ctrl+Enter / Cmd+Enter: works, but deliberately unadvertised —
        // several terminals encode it exactly like bare Enter (handler
        // comment at ui.rs is_forced_submit_key call site; absence pinned by
        // composer_catalog_assigns_one_stable_role_to_each_chord).
        "ctrlenter",
        // Ctrl+click / Cmd+click opens OSC 8 links — terminal-owned.
        "ctrlclick",
        // Ctrl+N navigates the slash-command menu; menu-local chords are
        // documented in the md but intentionally not help-catalog entries.
        "ctrln",
    ];

    /// Normalize a chord for comparison: lowercase, macOS aliases folded
    /// (Option -> Alt, Cmd -> Ctrl), all separators stripped, so `Ctrl-Home`,
    /// `Ctrl+Home`, and `Ctrl + Home` compare equal.
    fn normalize_chord(raw: &str) -> String {
        raw.to_lowercase()
            .replace("option", "alt")
            .replace("cmd", "ctrl")
            .chars()
            .filter(|c| !matches!(c, '-' | '+' | ' ' | '`'))
            .collect()
    }

    /// `Alt+1-8`-style digit family -> one normalized atom per digit.
    fn expand_digit_family(lowered: &str) -> Option<Vec<String>> {
        let (head, tail) = lowered.rsplit_once('-')?;
        let end: u32 = tail.parse().ok()?;
        let start: u32 = head.chars().next_back()?.to_digit(10)?;
        let prefix = &head[..head.len() - 1];
        if !matches!(prefix, "alt+" | "ctrl+" | "shift+") || start > end {
            return None;
        }
        Some(
            (start..=end)
                .map(|digit| normalize_chord(&format!("{prefix}{digit}")))
                .collect(),
        )
    }

    /// Expand one chord segment (no ` / ` separators) into normalized atoms.
    /// Handles suffix families: `Ctrl+Home/End` -> ctrlhome + ctrlend,
    /// `Ctrl+Shift+←/→` -> ctrlshift← + ctrlshift→.
    fn segment_atoms(segment: &str, out: &mut Vec<String>) {
        let lowered = segment
            .trim()
            .to_lowercase()
            .replace("option", "alt")
            .replace("cmd", "ctrl");
        if lowered.is_empty() {
            return;
        }
        if let Some(family) = expand_digit_family(&lowered) {
            out.extend(family);
            return;
        }
        let mut prefix = String::new();
        let mut rest = lowered.as_str();
        loop {
            let mut consumed = false;
            for modifier in ["ctrl+", "alt+", "shift+", "ctrl-", "alt-", "shift-"] {
                if let Some(stripped) = rest.strip_prefix(modifier) {
                    prefix.push_str(&modifier[..modifier.len() - 1]);
                    prefix.push('+');
                    rest = stripped;
                    consumed = true;
                    break;
                }
            }
            if !consumed {
                break;
            }
        }
        let parts: Vec<&str> = rest.split('/').collect();
        if !prefix.is_empty() && parts.len() > 1 && parts.iter().all(|p| !p.is_empty()) {
            for part in parts {
                out.push(normalize_chord(&format!("{prefix}{part}")));
            }
        } else {
            out.push(normalize_chord(&lowered));
        }
    }

    /// Normalized chord atoms advertised by the help catalog. Qualified
    /// entries (`/context`, `@path`, `Right click`) are commands or mouse
    /// gestures, not chords, and are skipped by design.
    fn catalog_chord_atoms() -> Vec<String> {
        let mut out = Vec::new();
        for entry in KEYBINDINGS {
            let chord = entry.chord.split(" (").next().unwrap_or(entry.chord);
            for segment in chord.split(" / ") {
                let segment = segment.trim();
                if segment.starts_with('/') || segment.starts_with('@') || segment.contains("click")
                {
                    continue;
                }
                segment_atoms(segment, &mut out);
            }
        }
        out
    }

    /// Normalized chord atoms from backticked tokens in docs/KEYBINDINGS.md
    /// table rows. Prose backticks (terminal-local notes) are excluded by
    /// only reading `| ... |` lines; non-chord tokens (slash commands,
    /// mentions, mouse drags, single letters) are filtered out.
    fn doc_table_chord_atoms() -> Vec<String> {
        const NAMED: &[&str] = &[
            "tab",
            "esc",
            "enter",
            "backspace",
            "delete",
            "home",
            "end",
            "pgup",
            "pgdn",
            "",
            "",
            "",
            "",
        ];
        let mut out = Vec::new();
        for line in KEYBINDINGS_DOC.lines() {
            if !line.trim_start().starts_with('|') {
                continue;
            }
            for token in line.split('`').skip(1).step_by(2) {
                let lowered = token.to_lowercase();
                if lowered.starts_with('/') || lowered.starts_with('@') || lowered.starts_with('!')
                {
                    continue;
                }
                let has_modifier = ["ctrl", "alt", "shift", "option", "cmd"]
                    .iter()
                    .any(|m| lowered.contains(m));
                let is_named = NAMED.contains(&lowered.as_str())
                    || (lowered.len() == 2
                        && lowered.starts_with('f')
                        && lowered[1..].parse::<u8>().is_ok());
                let is_named_combo = lowered.contains(' ')
                    && lowered.split(' ').all(|part| {
                        let part = part.trim();
                        NAMED.contains(&part)
                            || ["ctrl", "alt", "shift", "option", "cmd"]
                                .iter()
                                .any(|m| part.contains(m))
                    });
                if has_modifier || is_named || is_named_combo {
                    segment_atoms(token, &mut out);
                }
            }
        }
        out
    }

    #[test]
    fn keybindings_md_and_help_catalog_do_not_drift() {
        use std::collections::BTreeSet;

        let catalog: BTreeSet<String> = catalog_chord_atoms().into_iter().collect();
        let doc_atoms: BTreeSet<String> = doc_table_chord_atoms().into_iter().collect();
        let allowlist: BTreeSet<&str> = DOC_CHORD_ALLOWLIST.iter().copied().collect();

        // Direction 1: every chord a docs table advertises must be in the
        // help catalog (or an explicitly justified exception).
        let undocumented: Vec<&String> = doc_atoms
            .iter()
            .filter(|atom| !catalog.contains(*atom) && !allowlist.contains(atom.as_str()))
            .collect();
        assert!(
            undocumented.is_empty(),
            "docs/KEYBINDINGS.md advertises chords missing from the KEYBINDINGS \
             catalog — add the binding, fix the docs, or justify an allowlist entry: \
             {undocumented:?}"
        );

        // Direction 2: every catalog chord must be documented in the md —
        // either as an expanded table token (doc_atoms) or anywhere in the
        // normalized prose (e.g. Backspace/Delete in the selection notes).
        let normalized_doc = normalize_chord(KEYBINDINGS_DOC);
        let undocumented: Vec<&String> = catalog
            .iter()
            .filter(|atom| !doc_atoms.contains(*atom) && !normalized_doc.contains(atom.as_str()))
            .collect();
        assert!(
            undocumented.is_empty(),
            "KEYBINDINGS catalog advertises chords absent from docs/KEYBINDINGS.md \
             — document the chord or remove it from the catalog: {undocumented:?}"
        );
    }
}