返回 CodeWhale
keybinding_table.rs
根目录 / crates / engine / src / keybinding_table.rs
1 //! Documentation-only catalog of every user-facing keybinding.
2 //!
3 //! This module is the *single source of truth* for what shortcuts the help
4 //! overlay renders. The actual key handlers live in `tui/ui.rs` (and a few
5 //! sibling modules); they read keys directly off the crossterm event stream
6 //! and intentionally do **not** consult this catalog. The catalog exists so
7 //! that:
8 //!
9 //! 1. The help overlay (`tui/views/help.rs`) does not have to maintain a
10 //! parallel list that silently rots when a handler is added or moved.
11 //! 2. New contributors have one place to look when answering "which keys are
12 //! bound, and where do they go?"
13 //!
14 //! When you add or change a binding in `ui.rs`, **add or update the matching
15 //! entry here**. The compile-only side-effect of forgetting is a stale help
16 //! screen; there is no runtime crash, so the discipline lives in code review.
17 //!
18 //! Entries are grouped by `KeybindingSection`. The `chord` field is a
19 //! human-readable string formatted exactly the way it should appear in help —
20 //! we avoid storing `KeyBinding` values directly because many shortcuts are
21 //! pairs (`↑/↓`) or families (`1-8`) that don't map cleanly to a single
22 //! chord.
23
24 use std::borrow::Cow;
25
26 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
27 pub enum KeybindingSection {
28 Navigation,
29 Editing,
30 Submission,
31 Modes,
32 Sessions,
33 Clipboard,
34 Pointer,
35 Help,
36 }
37
38 impl KeybindingSection {
39 /// Every section, in declaration order. Callers that need to walk the set —
40 /// the help overlay's fold defaults, its rank lookup — read this instead of
41 /// restating the list, which is how `Pointer` came to be missing from one
42 /// of them and not the other.
43 pub const ALL: [Self; 8] = [
44 Self::Navigation,
45 Self::Editing,
46 Self::Submission,
47 Self::Modes,
48 Self::Sessions,
49 Self::Clipboard,
50 Self::Pointer,
51 Self::Help,
52 ];
53
54 pub fn label(self, locale: codewhale_localization::Locale) -> Cow<'static, str> {
55 use codewhale_localization::{MessageId, tr};
56 let id = match self {
57 Self::Navigation => MessageId::HelpSectionNavigation,
58 Self::Editing => MessageId::HelpSectionEditing,
59 Self::Submission => MessageId::HelpSectionActions,
60 Self::Modes => MessageId::HelpSectionModes,
61 Self::Sessions => MessageId::HelpSectionSessions,
62 Self::Clipboard => MessageId::HelpSectionClipboard,
63 Self::Pointer => MessageId::HelpSectionPointer,
64 Self::Help => MessageId::HelpSectionHelp,
65 };
66 tr(locale, id)
67 }
68
69 /// Stable ordering for help rendering — matches the variant declaration
70 /// order; explicit so adding a section forces a deliberate placement.
71 pub fn rank(self) -> u8 {
72 match self {
73 Self::Navigation => 0,
74 Self::Editing => 1,
75 Self::Submission => 2,
76 Self::Modes => 3,
77 Self::Sessions => 4,
78 Self::Clipboard => 5,
79 Self::Pointer => 6,
80 Self::Help => 7,
81 }
82 }
83 }
84
85 #[derive(Debug, Clone, Copy)]
86 pub struct KeybindingEntry {
87 pub chord: &'static str,
88 pub description_id: codewhale_localization::MessageId,
89 pub section: KeybindingSection,
90 }
91
92 pub const EXTERNAL_EDITOR_CHORD: &str = "Ctrl+Shift+O / F4";
93
94 /// Canonical list of keybindings shown in the help overlay.
95 ///
96 /// Strings are written in the same notation the existing help screen uses so
97 /// readers can cross-reference with documentation: `Ctrl+X`, `Alt+X`,
98 /// `Shift+X`, `↑/↓`, `PgUp/PgDn`, etc. Help renderers may apply per-platform
99 /// substitutions (e.g. `⌥` for Alt on macOS) at render time, but the catalog
100 /// itself stores the portable form.
101 pub const KEYBINDINGS: &[KeybindingEntry] = &[
102 // --- Navigation ---
103 KeybindingEntry {
104 chord: "↑ / ↓",
105 description_id: codewhale_localization::MessageId::KbScrollTranscript,
106 section: KeybindingSection::Navigation,
107 },
108 KeybindingEntry {
109 chord: "Alt+↑ / Alt+↓",
110 description_id: codewhale_localization::MessageId::KbScrollTranscriptAlt,
111 section: KeybindingSection::Navigation,
112 },
113 KeybindingEntry {
114 chord: "Shift+↑ / Shift+↓",
115 description_id: codewhale_localization::MessageId::KbBrowseHistory,
116 section: KeybindingSection::Navigation,
117 },
118 KeybindingEntry {
119 chord: "PgUp / PgDn",
120 description_id: codewhale_localization::MessageId::KbScrollPage,
121 section: KeybindingSection::Navigation,
122 },
123 KeybindingEntry {
124 chord: "Ctrl+Home / Ctrl+End / Alt+G / Alt+Shift+G",
125 description_id: codewhale_localization::MessageId::KbJumpTopBottom,
126 section: KeybindingSection::Navigation,
127 },
128 KeybindingEntry {
129 chord: "Alt+[ / Alt+]",
130 description_id: codewhale_localization::MessageId::KbJumpToolBlocks,
131 section: KeybindingSection::Navigation,
132 },
133 // --- Editing ---
134 KeybindingEntry {
135 chord: "← / → / Ctrl+←/→ / Alt+←/→",
136 description_id: codewhale_localization::MessageId::KbMoveCursor,
137 section: KeybindingSection::Editing,
138 },
139 KeybindingEntry {
140 chord: "Home / End",
141 description_id: codewhale_localization::MessageId::KbJumpLineStartEnd,
142 section: KeybindingSection::Editing,
143 },
144 KeybindingEntry {
145 chord: "Ctrl+A / Ctrl+E",
146 description_id: codewhale_localization::MessageId::KbJumpLineStartEnd,
147 section: KeybindingSection::Editing,
148 },
149 KeybindingEntry {
150 chord: "Backspace / Delete",
151 description_id: codewhale_localization::MessageId::KbDeleteChar,
152 section: KeybindingSection::Editing,
153 },
154 KeybindingEntry {
155 chord: "Ctrl+W / Ctrl+Backspace / Alt+Backspace",
156 description_id: codewhale_localization::MessageId::KbDeleteWord,
157 section: KeybindingSection::Editing,
158 },
159 KeybindingEntry {
160 chord: "Ctrl+Y",
161 description_id: codewhale_localization::MessageId::KbYank,
162 section: KeybindingSection::Editing,
163 },
164 KeybindingEntry {
165 chord: "Ctrl+Shift+E / Cmd+Shift+E",
166 description_id: codewhale_localization::MessageId::KbToggleFileTree,
167 section: KeybindingSection::Navigation,
168 },
169 KeybindingEntry {
170 chord: "Shift+←/→ / Shift+Home/End / Ctrl+Shift+←/→ / Alt+Shift+←/→ / Ctrl+Shift+Home/End",
171 description_id: codewhale_localization::MessageId::KbSelectText,
172 section: KeybindingSection::Editing,
173 },
174 KeybindingEntry {
175 // Ctrl+A keeps its readline meaning (start of input); select-all is
176 // the shifted chord, plus native Cmd+A on terminals that forward Cmd.
177 chord: "Ctrl+Shift+A / Cmd+A",
178 description_id: codewhale_localization::MessageId::KbSelectAllDraft,
179 section: KeybindingSection::Editing,
180 },
181 KeybindingEntry {
182 chord: "Ctrl+U",
183 description_id: codewhale_localization::MessageId::KbClearDraft,
184 section: KeybindingSection::Editing,
185 },
186 KeybindingEntry {
187 chord: "Ctrl+Z",
188 description_id: codewhale_localization::MessageId::KbRestoreClearedDraft,
189 section: KeybindingSection::Editing,
190 },
191 KeybindingEntry {
192 chord: "Ctrl+G / Ctrl+S",
193 description_id: codewhale_localization::MessageId::KbStashDraft,
194 section: KeybindingSection::Editing,
195 },
196 KeybindingEntry {
197 chord: "Alt+R",
198 description_id: codewhale_localization::MessageId::KbSearchHistory,
199 section: KeybindingSection::Editing,
200 },
201 KeybindingEntry {
202 // Ctrl+J leads because it is a plain control byte every terminal
203 // sends. Shift+Enter only arrives where the kitty keyboard protocol
204 // is live — see `composer_ui::terminal_can_report_shift_enter` — so
205 // it is listed last rather than taught first.
206 chord: "Ctrl+J / Alt+Enter / Shift+Enter (enhanced terminals)",
207 description_id: codewhale_localization::MessageId::KbInsertNewline,
208 section: KeybindingSection::Editing,
209 },
210 // --- Submission / actions ---
211 KeybindingEntry {
212 chord: "Enter",
213 description_id: codewhale_localization::MessageId::KbSendDraft,
214 section: KeybindingSection::Submission,
215 },
216 KeybindingEntry {
217 chord: "Esc",
218 description_id: codewhale_localization::MessageId::KbCloseMenu,
219 section: KeybindingSection::Submission,
220 },
221 KeybindingEntry {
222 chord: "Ctrl+C",
223 description_id: codewhale_localization::MessageId::KbCancelOrExit,
224 section: KeybindingSection::Submission,
225 },
226 KeybindingEntry {
227 chord: "Ctrl+B",
228 description_id: codewhale_localization::MessageId::KbShellControls,
229 section: KeybindingSection::Submission,
230 },
231 KeybindingEntry {
232 chord: "Ctrl+D",
233 description_id: codewhale_localization::MessageId::KbExitEmpty,
234 section: KeybindingSection::Submission,
235 },
236 KeybindingEntry {
237 chord: "Ctrl+K",
238 description_id: codewhale_localization::MessageId::KbCommandPalette,
239 section: KeybindingSection::Submission,
240 },
241 KeybindingEntry {
242 chord: "Ctrl+\\",
243 description_id: codewhale_localization::MessageId::CmdDashboardDescription,
244 section: KeybindingSection::Submission,
245 },
246 KeybindingEntry {
247 chord: "F2",
248 description_id: codewhale_localization::MessageId::KbSettings,
249 section: KeybindingSection::Submission,
250 },
251 KeybindingEntry {
252 chord: "Ctrl+X (Activity workbar)",
253 description_id: codewhale_localization::MessageId::KbCancelBackgroundShellJobs,
254 section: KeybindingSection::Submission,
255 },
256 KeybindingEntry {
257 chord: "Ctrl+P",
258 description_id: codewhale_localization::MessageId::KbFuzzyFilePicker,
259 section: KeybindingSection::Submission,
260 },
261 KeybindingEntry {
262 // `/context` is the guaranteed path; Alt+C is an unadvertised
263 // handler until proven in real terminals (TUI-DOG-003).
264 chord: "/context",
265 description_id: codewhale_localization::MessageId::KbCompactInspector,
266 section: KeybindingSection::Submission,
267 },
268 KeybindingEntry {
269 // `/provider` remains the portable command route; F3 mirrors the
270 // clickable topbar route segment without consuming composer text.
271 chord: "F3 / /provider",
272 description_id: codewhale_localization::MessageId::CmdProviderDescription,
273 section: KeybindingSection::Submission,
274 },
275 KeybindingEntry {
276 chord: "Alt+L",
277 description_id: codewhale_localization::MessageId::KbLastMessagePager,
278 section: KeybindingSection::Submission,
279 },
280 KeybindingEntry {
281 // Bare `v` always types `v`; details is Alt+V only (⌥V on macOS).
282 chord: "Alt+V",
283 description_id: codewhale_localization::MessageId::KbSelectedDetails,
284 section: KeybindingSection::Submission,
285 },
286 KeybindingEntry {
287 chord: "Ctrl+O",
288 description_id: codewhale_localization::MessageId::KbReasoningDetail,
289 section: KeybindingSection::Submission,
290 },
291 KeybindingEntry {
292 chord: "Ctrl+Alt+O",
293 description_id: codewhale_localization::MessageId::KbTurnInspector,
294 section: KeybindingSection::Submission,
295 },
296 KeybindingEntry {
297 chord: EXTERNAL_EDITOR_CHORD,
298 description_id: codewhale_localization::MessageId::KbExternalEditor,
299 section: KeybindingSection::Editing,
300 },
301 KeybindingEntry {
302 // `/transcript` is the reliable fallback when a terminal cannot
303 // distinguish Ctrl+Shift+T from Ctrl+T.
304 chord: "/transcript / Ctrl+Shift+T",
305 description_id: codewhale_localization::MessageId::KbLiveTranscript,
306 section: KeybindingSection::Submission,
307 },
308 KeybindingEntry {
309 chord: "Ctrl+T",
310 description_id: codewhale_localization::MessageId::KbCycleThinking,
311 section: KeybindingSection::Modes,
312 },
313 KeybindingEntry {
314 chord: "Esc Esc",
315 description_id: codewhale_localization::MessageId::KbBacktrackMessage,
316 section: KeybindingSection::Submission,
317 },
318 // --- Modes ---
319 KeybindingEntry {
320 chord: "Tab",
321 description_id: codewhale_localization::MessageId::KbTabComplete,
322 section: KeybindingSection::Modes,
323 },
324 KeybindingEntry {
325 chord: "Shift+Tab",
326 description_id: codewhale_localization::MessageId::KbCyclePermissions,
327 section: KeybindingSection::Modes,
328 },
329 KeybindingEntry {
330 chord: "Alt+1-8",
331 description_id: codewhale_localization::MessageId::KbJumpPlanAgentYolo,
332 section: KeybindingSection::Modes,
333 },
334 KeybindingEntry {
335 chord: "Alt+P / Alt+A",
336 description_id: codewhale_localization::MessageId::KbAltJumpPlanAgentYolo,
337 section: KeybindingSection::Modes,
338 },
339 KeybindingEntry {
340 chord: "Alt+! / Alt+@ / Alt+# / Alt+$",
341 description_id: codewhale_localization::MessageId::KbFocusSidebar,
342 section: KeybindingSection::Modes,
343 },
344 KeybindingEntry {
345 chord: "Ctrl+Alt+0",
346 description_id: codewhale_localization::MessageId::HotbarActionSidebarToggleName,
347 section: KeybindingSection::Modes,
348 },
349 // --- Sessions ---
350 KeybindingEntry {
351 chord: "Ctrl+R",
352 description_id: codewhale_localization::MessageId::KbSessionPicker,
353 section: KeybindingSection::Sessions,
354 },
355 KeybindingEntry {
356 chord: "Ctrl+L",
357 description_id: codewhale_localization::MessageId::KbCompactContext,
358 section: KeybindingSection::Sessions,
359 },
360 KeybindingEntry {
361 // Same shifted-Ctrl family as Ctrl+Shift+A/E/O; routes through the
362 // `/update install` command, so managed installs keep their gate.
363 chord: "Ctrl+Shift+U",
364 description_id: codewhale_localization::MessageId::KbUpdateInstall,
365 section: KeybindingSection::Sessions,
366 },
367 // --- Clipboard ---
368 KeybindingEntry {
369 // Keep both terminal-client families visible: the TUI may be running
370 // on Linux while the user's SSH terminal is on macOS (or vice versa).
371 chord: "Cmd+V / Ctrl+Shift+V",
372 description_id: codewhale_localization::MessageId::KbTerminalPaste,
373 section: KeybindingSection::Clipboard,
374 },
375 KeybindingEntry {
376 chord: "Ctrl+V",
377 description_id: codewhale_localization::MessageId::KbPasteAttach,
378 section: KeybindingSection::Clipboard,
379 },
380 KeybindingEntry {
381 // Terminal-native copy chords are normally consumed by the local
382 // terminal and never become Codewhale key events. Ctrl+C is the
383 // reliable in-app copy path when a Codewhale selection is active.
384 chord: "Ctrl+C (selection)",
385 description_id: codewhale_localization::MessageId::KbCopySelection,
386 section: KeybindingSection::Clipboard,
387 },
388 KeybindingEntry {
389 chord: "@path",
390 description_id: codewhale_localization::MessageId::KbAttachPath,
391 section: KeybindingSection::Clipboard,
392 },
393 // --- Pointer ---
394 // The mouse is a first-class input here: every one of these is wired in
395 // `tui/mouse_ui.rs`. A pointer that does nothing where a user expects it
396 // to act reads as a broken app, so what responds is documented.
397 KeybindingEntry {
398 chord: "Wheel up / down",
399 description_id: codewhale_localization::MessageId::KbPointerScroll,
400 section: KeybindingSection::Pointer,
401 },
402 KeybindingEntry {
403 chord: "Click",
404 description_id: codewhale_localization::MessageId::KbPointerClick,
405 section: KeybindingSection::Pointer,
406 },
407 KeybindingEntry {
408 chord: "Drag",
409 description_id: codewhale_localization::MessageId::KbPointerDrag,
410 section: KeybindingSection::Pointer,
411 },
412 KeybindingEntry {
413 chord: "Right click",
414 description_id: codewhale_localization::MessageId::KbContextMenu,
415 section: KeybindingSection::Pointer,
416 },
417 // --- Help ---
418 KeybindingEntry {
419 // `/help` leads because it is the one route that works in every
420 // terminal. F1 is eaten by tmux and several emulators, and how a
421 // terminal encodes Ctrl+/ varies; both still open help where they
422 // arrive. Alt+? stays an unadvertised handler (TUI-DOG-003).
423 chord: "/help / F1 / Ctrl+/",
424 description_id: codewhale_localization::MessageId::KbHelpOverlay,
425 section: KeybindingSection::Help,
426 },
427 KeybindingEntry {
428 // The work dock was reachable but never listed here, so the only way
429 // to learn the chord was the footer's one-time hint.
430 chord: "Ctrl+Tab / Ctrl+]",
431 description_id: codewhale_localization::MessageId::KbCycleWorkDock,
432 section: KeybindingSection::Navigation,
433 },
434 KeybindingEntry {
435 chord: "Ctrl+Shift+Tab",
436 description_id: codewhale_localization::MessageId::KbCycleWorkDockBack,
437 section: KeybindingSection::Navigation,
438 },
439 ];
440
441 #[cfg(test)]
442 mod tests {
443 use super::*;
444
445 #[test]
446 fn catalog_is_non_empty_and_sections_have_entries() {
447 assert!(KEYBINDINGS.iter().any(|entry| !entry.chord.is_empty()));
448 // Every declared section should appear in the catalog at least once,
449 // otherwise the help overlay would render an empty heading.
450 let sections = [
451 KeybindingSection::Navigation,
452 KeybindingSection::Editing,
453 KeybindingSection::Submission,
454 KeybindingSection::Modes,
455 KeybindingSection::Sessions,
456 KeybindingSection::Clipboard,
457 KeybindingSection::Help,
458 ];
459 for section in sections {
460 assert!(
461 KEYBINDINGS.iter().any(|entry| entry.section == section),
462 "no entries for section {section:?}"
463 );
464 }
465 }
466
467 #[test]
468 fn help_advertises_f1_and_ctrl_slash_never_alt_question() {
469 // TUI-DOG-003: Alt+? is not advertised anywhere; F1 (with /help) is
470 // primary and Ctrl+/ is the secondary fallback.
471 assert!(
472 KEYBINDINGS.iter().any(|entry| {
473 entry.section == KeybindingSection::Help
474 && entry.chord.contains("F1")
475 && entry.chord.contains("Ctrl+/")
476 }),
477 "help must document F1 with the Ctrl+/ fallback"
478 );
479 assert!(
480 KEYBINDINGS
481 .iter()
482 .all(|entry| !entry.chord.contains("Alt+?")),
483 "Alt+? must not be advertised in the help catalog"
484 );
485 }
486
487 #[test]
488 fn composer_catalog_assigns_one_stable_role_to_each_chord() {
489 let chord_for = |id| {
490 KEYBINDINGS
491 .iter()
492 .find(|entry| entry.description_id == id)
493 .expect("composer binding should be documented")
494 .chord
495 };
496
497 assert_eq!(
498 chord_for(codewhale_localization::MessageId::KbInsertNewline),
499 "Ctrl+J / Alt+Enter / Shift+Enter (enhanced terminals)"
500 );
501 assert!(
502 KEYBINDINGS
503 .iter()
504 .all(|entry| !entry.chord.contains("Ctrl+Enter")
505 && !entry.chord.contains("Cmd+Enter"))
506 );
507 assert_eq!(
508 chord_for(codewhale_localization::MessageId::KbStashDraft),
509 "Ctrl+G / Ctrl+S"
510 );
511 assert_eq!(
512 chord_for(codewhale_localization::MessageId::KbSendDraft),
513 "Enter"
514 );
515
516 let tab_copy = codewhale_localization::tr(
517 codewhale_localization::Locale::En,
518 codewhale_localization::MessageId::KbTabComplete,
519 );
520 assert!(!tab_copy.to_ascii_lowercase().contains("queue"));
521 let stash_copy = codewhale_localization::tr(
522 codewhale_localization::Locale::En,
523 codewhale_localization::MessageId::KbStashDraft,
524 );
525 assert!(!stash_copy.to_ascii_lowercase().contains("send"));
526 }
527
528 #[test]
529 fn clipboard_help_distinguishes_terminal_text_graphical_image_and_in_app_copy() {
530 let terminal_paste = KEYBINDINGS
531 .iter()
532 .find(|entry| {
533 entry.description_id == codewhale_localization::MessageId::KbTerminalPaste
534 })
535 .expect("terminal paste binding should be documented");
536 let graphical_paste = KEYBINDINGS
537 .iter()
538 .find(|entry| entry.description_id == codewhale_localization::MessageId::KbPasteAttach)
539 .expect("graphical paste binding should be documented");
540 let copy = KEYBINDINGS
541 .iter()
542 .find(|entry| {
543 entry.description_id == codewhale_localization::MessageId::KbCopySelection
544 })
545 .expect("copy binding should be documented");
546
547 assert!(terminal_paste.chord.contains("Cmd+V"));
548 assert!(terminal_paste.chord.contains("Ctrl+Shift+V"));
549 assert_eq!(graphical_paste.chord, "Ctrl+V");
550 let terminal_description = codewhale_localization::tr(
551 codewhale_localization::Locale::En,
552 codewhale_localization::MessageId::KbTerminalPaste,
553 );
554 let graphical_description = codewhale_localization::tr(
555 codewhale_localization::Locale::En,
556 codewhale_localization::MessageId::KbPasteAttach,
557 );
558 assert!(!terminal_description.to_ascii_lowercase().contains("image"));
559 assert!(graphical_description.to_ascii_lowercase().contains("image"));
560 assert_eq!(copy.chord, "Ctrl+C (selection)");
561 assert!(!copy.chord.contains("Cmd+C"));
562 assert!(!copy.chord.contains("Ctrl+Shift+C"));
563 }
564
565 #[test]
566 fn transcript_navigation_catalog_does_not_advertise_bare_typing_keys() {
567 for stale in [
568 "g / G",
569 "[ / ]",
570 "l",
571 "?",
572 "Ctrl+↑ / Ctrl+↓",
573 "v",
574 "v / Alt+V",
575 ] {
576 assert!(
577 KEYBINDINGS.iter().all(|entry| entry.chord != stale),
578 "stale handler-free chord remains documented: {stale}"
579 );
580 }
581 for wired in [
582 "Ctrl+Home / Ctrl+End / Alt+G / Alt+Shift+G",
583 "Alt+[ / Alt+]",
584 "Alt+L",
585 "Alt+V",
586 ] {
587 assert!(
588 KEYBINDINGS.iter().any(|entry| entry.chord == wired),
589 "wired transcript shortcut missing from help: {wired}"
590 );
591 }
592 }
593
594 #[test]
595 fn live_transcript_documents_command_before_shaky_chord() {
596 let transcript = KEYBINDINGS
597 .iter()
598 .find(|entry| {
599 entry.description_id == codewhale_localization::MessageId::KbLiveTranscript
600 })
601 .expect("live transcript entry should be documented");
602
603 assert_eq!(transcript.chord, "/transcript / Ctrl+Shift+T");
604 }
605
606 #[test]
607 fn ctrl_o_and_ctrl_alt_o_help_copy_match_split_surfaces() {
608 let ctrl_o = KEYBINDINGS
609 .iter()
610 .find(|entry| entry.chord == "Ctrl+O")
611 .expect("Ctrl+O keybinding should be documented");
612
613 // Ctrl+O now opens the full recorded Reasoning Detail; the whole-turn
614 // Turn Inspector moved to Ctrl+Alt+O.
615 assert_eq!(
616 ctrl_o.description_id,
617 codewhale_localization::MessageId::KbReasoningDetail
618 );
619 assert_eq!(
620 codewhale_localization::tr(codewhale_localization::Locale::En, ctrl_o.description_id,),
621 "Open reasoning detail for the selected or current turn"
622 );
623
624 let ctrl_alt_o = KEYBINDINGS
625 .iter()
626 .find(|entry| entry.chord == "Ctrl+Alt+O")
627 .expect("Ctrl+Alt+O keybinding should be documented");
628 assert_eq!(
629 ctrl_alt_o.description_id,
630 codewhale_localization::MessageId::KbTurnInspector
631 );
632 assert_eq!(
633 codewhale_localization::tr(
634 codewhale_localization::Locale::En,
635 ctrl_alt_o.description_id,
636 ),
637 "Open Turn Inspector"
638 );
639
640 let editor = KEYBINDINGS
641 .iter()
642 .find(|entry| entry.chord == "Ctrl+Shift+O / F4")
643 .expect("external-editor keybinding should be documented");
644 assert_eq!(
645 codewhale_localization::tr(codewhale_localization::Locale::En, editor.description_id,),
646 "Edit the draft externally"
647 );
648 }
649
650 #[test]
651 fn ctrl_shift_u_update_install_is_documented_in_the_sessions_section() {
652 let entry = KEYBINDINGS
653 .iter()
654 .find(|entry| entry.chord == "Ctrl+Shift+U")
655 .expect("Ctrl+Shift+U keybinding should be documented");
656 assert_eq!(
657 entry.description_id,
658 codewhale_localization::MessageId::KbUpdateInstall
659 );
660 assert_eq!(entry.section, KeybindingSection::Sessions);
661 assert_eq!(
662 codewhale_localization::tr(codewhale_localization::Locale::En, entry.description_id),
663 "Check for and install the latest Codewhale update (`/update install`)"
664 );
665 }
666
667 #[test]
668 fn ctrl_x_activity_sidebar_cancel_all_is_documented() {
669 let ctrl_x_activity = KEYBINDINGS
670 .iter()
671 .find(|entry| entry.chord == "Ctrl+X (Activity workbar)")
672 .expect("Ctrl+X Activity workbar keybinding should be documented");
673
674 assert_eq!(
675 ctrl_x_activity.description_id,
676 codewhale_localization::MessageId::KbCancelBackgroundShellJobs
677 );
678 }
679
680 #[test]
681 fn tool_details_documents_alt_v_only_never_bare_v() {
682 let selected_details = KEYBINDINGS
683 .iter()
684 .filter(|entry| {
685 entry.description_id == codewhale_localization::MessageId::KbSelectedDetails
686 })
687 .map(|entry| entry.chord)
688 .collect::<Vec<_>>();
689
690 // TUI-DOG-002: bare `v` always types `v`; details is Alt+V only.
691 assert_eq!(selected_details, vec!["Alt+V"]);
692 assert!(
693 KEYBINDINGS
694 .iter()
695 .all(|entry| entry.chord != "v" && !entry.chord.starts_with("v /")),
696 "bare `v` must not be advertised — composer typing owns it"
697 );
698 }
699
700 /// #3758: a user who reads the help overlay must be able to answer "what
701 /// does this key do?" with one answer. A key may appear twice only when
702 /// every occurrence but one names its context in parentheses — the way
703 /// `Ctrl+C` and `Ctrl+C (selection)` do — so the reader is told which
704 /// reading applies. Two unqualified entries for the same key is the
705 /// ambiguity this guard exists to reject.
706 #[test]
707 fn every_advertised_key_names_exactly_one_canonical_action() {
708 struct Use {
709 chord: &'static str,
710 alternative: String,
711 description_id: codewhale_localization::MessageId,
712 }
713
714 let mut uses_by_key: std::collections::BTreeMap<String, Vec<Use>> =
715 std::collections::BTreeMap::new();
716 for entry in KEYBINDINGS {
717 for alternative in entry.chord.split(" / ") {
718 let alternative = alternative.trim();
719 // `Ctrl+C (selection)` → base key `Ctrl+C`, qualifier retained
720 // on the alternative so the check below can see it.
721 let base = alternative
722 .split_once(" (")
723 .map(|(head, _)| head)
724 .unwrap_or(alternative)
725 .trim()
726 .to_string();
727 uses_by_key.entry(base).or_default().push(Use {
728 chord: entry.chord,
729 alternative: alternative.to_string(),
730 description_id: entry.description_id,
731 });
732 }
733 }
734
735 for (key, uses) in &uses_by_key {
736 if uses.len() == 1 {
737 continue;
738 }
739 let single_action = uses
740 .iter()
741 .all(|entry| entry.description_id == uses[0].description_id);
742 if single_action {
743 // The same action documented from two spellings is fine —
744 // `Home / End` and `Ctrl+A / Ctrl+E` both jump to line edges.
745 continue;
746 }
747 let unqualified: Vec<&str> = uses
748 .iter()
749 .filter(|entry| !entry.alternative.contains('('))
750 .map(|entry| entry.chord)
751 .collect();
752 assert!(
753 unqualified.len() <= 1,
754 "{key} is advertised for more than one action without naming the \
755 context that selects between them: {unqualified:?}"
756 );
757 }
758 }
759
760 /// #440 / #3758: `Ctrl+G` and `Ctrl+S` stash the draft. They are not a
761 /// send, a queue, a steer, or a file save, and a real-terminal report that
762 /// says otherwise is reading ambiguous copy, not misusing the key.
763 #[test]
764 fn stash_chords_advertise_stashing_and_nothing_else() {
765 let stash_entries: Vec<&KeybindingEntry> = KEYBINDINGS
766 .iter()
767 .filter(|entry| {
768 entry
769 .chord
770 .split(" / ")
771 .map(str::trim)
772 .any(|chord| matches!(chord, "Ctrl+G" | "Ctrl+S"))
773 })
774 .collect();
775
776 assert_eq!(
777 stash_entries.len(),
778 1,
779 "Ctrl+G / Ctrl+S must be documented exactly once, together"
780 );
781 assert_eq!(stash_entries[0].chord, "Ctrl+G / Ctrl+S");
782 assert_eq!(
783 stash_entries[0].description_id,
784 codewhale_localization::MessageId::KbStashDraft
785 );
786
787 let copy = codewhale_localization::tr(
788 codewhale_localization::Locale::En,
789 codewhale_localization::MessageId::KbStashDraft,
790 )
791 .to_ascii_lowercase();
792 for forbidden in ["send", "queue", "steer", "submit", "save"] {
793 assert!(
794 !copy.contains(forbidden),
795 "stash copy must not read as {forbidden:?}: {copy:?}"
796 );
797 }
798 assert!(
799 copy.contains("stash"),
800 "stash copy must name the action it performs: {copy:?}"
801 );
802 }
803
804 /// Only chords distinguishable by the baseline terminal protocol may be
805 /// advertised. Enter sends or queues (then sends a queued message now),
806 /// while the newline chords stay newlines.
807 #[test]
808 fn running_turn_verbs_belong_to_one_chord_each() {
809 let entry_for = |id| {
810 KEYBINDINGS
811 .iter()
812 .find(|entry| entry.description_id == id)
813 .expect("running-turn binding should be documented")
814 };
815
816 assert_eq!(
817 entry_for(codewhale_localization::MessageId::KbSendDraft).chord,
818 "Enter"
819 );
820 assert!(
821 KEYBINDINGS
822 .iter()
823 .all(|entry| !entry.chord.contains("Ctrl+Enter")
824 && !entry.chord.contains("Cmd+Enter"))
825 );
826 assert_eq!(
827 entry_for(codewhale_localization::MessageId::KbInsertNewline).chord,
828 "Ctrl+J / Alt+Enter / Shift+Enter (enhanced terminals)"
829 );
830
831 let newline_copy = codewhale_localization::tr(
832 codewhale_localization::Locale::En,
833 codewhale_localization::MessageId::KbInsertNewline,
834 )
835 .to_ascii_lowercase();
836 for forbidden in ["send", "steer", "queue"] {
837 assert!(
838 !newline_copy.contains(forbidden),
839 "newline chords must not read as {forbidden:?}: {newline_copy:?}"
840 );
841 }
842 }
843
844 #[test]
845 fn section_rank_is_a_total_order() {
846 let sections = [
847 KeybindingSection::Navigation,
848 KeybindingSection::Editing,
849 KeybindingSection::Submission,
850 KeybindingSection::Modes,
851 KeybindingSection::Sessions,
852 KeybindingSection::Clipboard,
853 KeybindingSection::Help,
854 ];
855 let mut ranks: Vec<u8> = sections.iter().map(|s| s.rank()).collect();
856 ranks.sort_unstable();
857 ranks.dedup();
858 assert_eq!(ranks.len(), sections.len(), "ranks must be unique");
859 }
860
861 // ------------------------------------------------------------------
862 // docs/KEYBINDINGS.md <-> KEYBINDINGS bidirectional drift gate
863 // ------------------------------------------------------------------
864
865 const KEYBINDINGS_DOC: &str = include_str!(concat!(
866 env!("CARGO_MANIFEST_DIR"),
867 "/../../docs/KEYBINDINGS.md"
868 ));
869
870 /// Doc table chords that are deliberately NOT in the help catalog.
871 /// Every entry needs a justification; adding one is a reviewed decision.
872 const DOC_CHORD_ALLOWLIST: &[&str] = &[
873 // Ctrl+Enter / Cmd+Enter: works, but deliberately unadvertised —
874 // several terminals encode it exactly like bare Enter (handler
875 // comment at ui.rs is_forced_submit_key call site; absence pinned by
876 // composer_catalog_assigns_one_stable_role_to_each_chord).
877 "ctrlenter",
878 // Ctrl+click / Cmd+click opens OSC 8 links — terminal-owned.
879 "ctrlclick",
880 // Ctrl+N navigates the slash-command menu; menu-local chords are
881 // documented in the md but intentionally not help-catalog entries.
882 "ctrln",
883 ];
884
885 /// Normalize a chord for comparison: lowercase, macOS aliases folded
886 /// (Option -> Alt, Cmd -> Ctrl), all separators stripped, so `Ctrl-Home`,
887 /// `Ctrl+Home`, and `Ctrl + Home` compare equal.
888 fn normalize_chord(raw: &str) -> String {
889 raw.to_lowercase()
890 .replace("option", "alt")
891 .replace("cmd", "ctrl")
892 .chars()
893 .filter(|c| !matches!(c, '-' | '+' | ' ' | '`'))
894 .collect()
895 }
896
897 /// `Alt+1-8`-style digit family -> one normalized atom per digit.
898 fn expand_digit_family(lowered: &str) -> Option<Vec<String>> {
899 let (head, tail) = lowered.rsplit_once('-')?;
900 let end: u32 = tail.parse().ok()?;
901 let start: u32 = head.chars().next_back()?.to_digit(10)?;
902 let prefix = &head[..head.len() - 1];
903 if !matches!(prefix, "alt+" | "ctrl+" | "shift+") || start > end {
904 return None;
905 }
906 Some(
907 (start..=end)
908 .map(|digit| normalize_chord(&format!("{prefix}{digit}")))
909 .collect(),
910 )
911 }
912
913 /// Expand one chord segment (no ` / ` separators) into normalized atoms.
914 /// Handles suffix families: `Ctrl+Home/End` -> ctrlhome + ctrlend,
915 /// `Ctrl+Shift+←/→` -> ctrlshift← + ctrlshift→.
916 fn segment_atoms(segment: &str, out: &mut Vec<String>) {
917 let lowered = segment
918 .trim()
919 .to_lowercase()
920 .replace("option", "alt")
921 .replace("cmd", "ctrl");
922 if lowered.is_empty() {
923 return;
924 }
925 if let Some(family) = expand_digit_family(&lowered) {
926 out.extend(family);
927 return;
928 }
929 let mut prefix = String::new();
930 let mut rest = lowered.as_str();
931 loop {
932 let mut consumed = false;
933 for modifier in ["ctrl+", "alt+", "shift+", "ctrl-", "alt-", "shift-"] {
934 if let Some(stripped) = rest.strip_prefix(modifier) {
935 prefix.push_str(&modifier[..modifier.len() - 1]);
936 prefix.push('+');
937 rest = stripped;
938 consumed = true;
939 break;
940 }
941 }
942 if !consumed {
943 break;
944 }
945 }
946 let parts: Vec<&str> = rest.split('/').collect();
947 if !prefix.is_empty() && parts.len() > 1 && parts.iter().all(|p| !p.is_empty()) {
948 for part in parts {
949 out.push(normalize_chord(&format!("{prefix}{part}")));
950 }
951 } else {
952 out.push(normalize_chord(&lowered));
953 }
954 }
955
956 /// Normalized chord atoms advertised by the help catalog. Qualified
957 /// entries (`/context`, `@path`, `Right click`) are commands or mouse
958 /// gestures, not chords, and are skipped by design.
959 fn catalog_chord_atoms() -> Vec<String> {
960 let mut out = Vec::new();
961 for entry in KEYBINDINGS {
962 let chord = entry.chord.split(" (").next().unwrap_or(entry.chord);
963 for segment in chord.split(" / ") {
964 let segment = segment.trim();
965 if segment.starts_with('/') || segment.starts_with('@') || segment.contains("click")
966 {
967 continue;
968 }
969 segment_atoms(segment, &mut out);
970 }
971 }
972 out
973 }
974
975 /// Normalized chord atoms from backticked tokens in docs/KEYBINDINGS.md
976 /// table rows. Prose backticks (terminal-local notes) are excluded by
977 /// only reading `| ... |` lines; non-chord tokens (slash commands,
978 /// mentions, mouse drags, single letters) are filtered out.
979 fn doc_table_chord_atoms() -> Vec<String> {
980 const NAMED: &[&str] = &[
981 "tab",
982 "esc",
983 "enter",
984 "backspace",
985 "delete",
986 "home",
987 "end",
988 "pgup",
989 "pgdn",
990 "↑",
991 "↓",
992 "←",
993 "→",
994 ];
995 let mut out = Vec::new();
996 for line in KEYBINDINGS_DOC.lines() {
997 if !line.trim_start().starts_with('|') {
998 continue;
999 }
1000 for token in line.split('`').skip(1).step_by(2) {
1001 let lowered = token.to_lowercase();
1002 if lowered.starts_with('/') || lowered.starts_with('@') || lowered.starts_with('!')
1003 {
1004 continue;
1005 }
1006 let has_modifier = ["ctrl", "alt", "shift", "option", "cmd"]
1007 .iter()
1008 .any(|m| lowered.contains(m));
1009 let is_named = NAMED.contains(&lowered.as_str())
1010 || (lowered.len() == 2
1011 && lowered.starts_with('f')
1012 && lowered[1..].parse::<u8>().is_ok());
1013 let is_named_combo = lowered.contains(' ')
1014 && lowered.split(' ').all(|part| {
1015 let part = part.trim();
1016 NAMED.contains(&part)
1017 || ["ctrl", "alt", "shift", "option", "cmd"]
1018 .iter()
1019 .any(|m| part.contains(m))
1020 });
1021 if has_modifier || is_named || is_named_combo {
1022 segment_atoms(token, &mut out);
1023 }
1024 }
1025 }
1026 out
1027 }
1028
1029 #[test]
1030 fn keybindings_md_and_help_catalog_do_not_drift() {
1031 use std::collections::BTreeSet;
1032
1033 let catalog: BTreeSet<String> = catalog_chord_atoms().into_iter().collect();
1034 let doc_atoms: BTreeSet<String> = doc_table_chord_atoms().into_iter().collect();
1035 let allowlist: BTreeSet<&str> = DOC_CHORD_ALLOWLIST.iter().copied().collect();
1036
1037 // Direction 1: every chord a docs table advertises must be in the
1038 // help catalog (or an explicitly justified exception).
1039 let undocumented: Vec<&String> = doc_atoms
1040 .iter()
1041 .filter(|atom| !catalog.contains(*atom) && !allowlist.contains(atom.as_str()))
1042 .collect();
1043 assert!(
1044 undocumented.is_empty(),
1045 "docs/KEYBINDINGS.md advertises chords missing from the KEYBINDINGS \
1046 catalog — add the binding, fix the docs, or justify an allowlist entry: \
1047 {undocumented:?}"
1048 );
1049
1050 // Direction 2: every catalog chord must be documented in the md —
1051 // either as an expanded table token (doc_atoms) or anywhere in the
1052 // normalized prose (e.g. Backspace/Delete in the selection notes).
1053 let normalized_doc = normalize_chord(KEYBINDINGS_DOC);
1054 let undocumented: Vec<&String> = catalog
1055 .iter()
1056 .filter(|atom| !doc_atoms.contains(*atom) && !normalized_doc.contains(atom.as_str()))
1057 .collect();
1058 assert!(
1059 undocumented.is_empty(),
1060 "KEYBINDINGS catalog advertises chords absent from docs/KEYBINDINGS.md \
1061 — document the chord or remove it from the catalog: {undocumented:?}"
1062 );
1063 }
1064 }
1065
1065 lines RUST