返回 CodeWhale
shell_key_routing.rs
根目录 / crates / tui / src / tui / shell_key_routing.rs
1 //! Shell keyboard bindings for details / context / help.
2 //!
3 //! Footer hints, help catalog chords, and live handlers must agree on one
4 //! source. Outside exclusive consent gates, printable characters belong to
5 //! the composer: bare `v` types `v` in every ordinary focus state — work surface, transcript selection,
6 //! panel, or modal (TUI-DOG-002). Details/output fires only on
7 //! Option+V / Alt+V, and macOS renders the label as `⌥V`, never `Alt`/`Cmd`.
8 //! Help answers to `F1` and `Ctrl+/` (with `/help`); chrome advertises only
9 //! `Ctrl+/`, the chord every terminal delivers.
10 //! Provider/route is `F3` (with `/provider`); it is non-printable so it can
11 //! remain available while the composer owns ordinary text input.
12 //! `Alt+?` and `Alt+C` are still accepted where terminals deliver them but
13 //! are never advertised until proven in real terminals (TUI-DOG-003);
14 //! `/context` is the guaranteed context path.
15 //! Ambiguous macOS Option glyphs (`ç` / `¿`) remain text: terminals do not
16 //! identify whether they came from Option or from a user's keyboard layout.
17
18 use std::borrow::Cow;
19
20 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
21
22 use crate::tui::key_shortcuts;
23 use crate::tui::views::ModalKind;
24
25 /// Who owns the keyboard right now.
26 ///
27 /// One value, derived in one place ([`crate::tui::app::App::focus`]), in
28 /// place of the `app.input.is_empty()` guesses that used composer *content*
29 /// as a stand-in for composer *focus*. Composer editing keys still ask about
30 /// the text itself; every shell binding asks this instead.
31 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
32 pub enum Focus {
33 /// The model-bound redaction consent gate exclusively owns its decision.
34 RedactionGate,
35 /// The onboarding rail owns every key until it finishes.
36 Onboarding,
37 /// A modal view is on top of the stack and handles its own keys.
38 Modal(ModalKind),
39 /// The pre-session launch screen — its menu or its composer.
40 Launch,
41 /// A focused rail or workflow panel inside a live session.
42 Panel,
43 /// The live PTY dock owns terminal input, including control keys.
44 TerminalPanel,
45 /// The session composer: the default owner.
46 Composer,
47 }
48
49 /// Which focus states a binding is live in — the `ShellBinding` focus rule
50 /// that used to be re-invented at every call site as
51 /// `&& app.view_stack.is_empty()`. The variants nest: each admits everything
52 /// the one above it does, plus one more surface. The redaction consent gate
53 /// is exclusive and sits outside that shell hierarchy.
54 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
55 pub enum FocusScope {
56 TerminalPanel,
57 AccountLogin,
58 PetHabitat,
59 /// Only the sandbox-elevation decision card.
60 Elevation,
61 /// Only the model-bound redaction consent gate.
62 RedactionGate,
63 /// A live session: the composer, or a rail/workflow panel that has taken
64 /// the keys from it.
65 SessionShell,
66 /// [`FocusScope::SessionShell`], plus the pre-session launch stage.
67 AnyShell,
68 /// [`FocusScope::AnyShell`], plus the Config modal, which displays the
69 /// very setting the binding changes.
70 AnyShellOrConfig,
71 /// Every ordinary shell state, onboarding and modals included. Exclusive
72 /// consent gates keep their own keys.
73 Everywhere,
74 }
75
76 impl FocusScope {
77 #[must_use]
78 pub fn admits(self, focus: Focus) -> bool {
79 match self {
80 Self::TerminalPanel => focus == Focus::TerminalPanel,
81 Self::AccountLogin => focus == Focus::Modal(ModalKind::AccountLogin),
82 Self::PetHabitat => focus == Focus::Modal(ModalKind::PetHabitat),
83 Self::Elevation => focus == Focus::Modal(ModalKind::Elevation),
84 Self::RedactionGate => focus == Focus::RedactionGate,
85 Self::SessionShell => {
86 matches!(focus, Focus::Composer | Focus::Panel | Focus::TerminalPanel)
87 }
88 Self::AnyShell => matches!(
89 focus,
90 Focus::Composer | Focus::Panel | Focus::TerminalPanel | Focus::Launch
91 ),
92 Self::AnyShellOrConfig => matches!(
93 focus,
94 Focus::Composer
95 | Focus::Panel
96 | Focus::TerminalPanel
97 | Focus::Launch
98 | Focus::Modal(ModalKind::Config)
99 ),
100 Self::Everywhere => focus != Focus::RedactionGate,
101 }
102 }
103 }
104
105 /// Stable binding ids shared by handlers, footer hints, and help catalog.
106 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
107 pub enum ShellBindingId {
108 AccountLoginOpenBrowser,
109 AccountLoginCopyLink,
110 AccountLoginCancel,
111 AccountLoginSelect,
112 AccountLoginNext,
113 TerminalNew,
114 TerminalNext,
115 TerminalPrevious,
116 TerminalDetach,
117 ElevationUp,
118 ElevationDown,
119 ElevationConfirm,
120 ElevationAbort,
121 PetInspect,
122 PetResultUp,
123 PetResultDown,
124 PetResultPageUp,
125 PetResultPageDown,
126 PetBack,
127 PetResultStart,
128 PetResultEnd,
129 PetFocusAgents,
130 PetOpenAgent,
131 PetCopyReply,
132 RedactionGateConfirm,
133 RedactionGateKeepOrBack,
134 RedactionGateQuit,
135 RedactionGateScroll,
136 ToolDetails,
137 ContextInspector,
138 ProviderRoute,
139 Help,
140 ExternalEditor,
141 Settings,
142 /// Shift+Tab: step the permission dial.
143 PermissionCycle,
144 /// Ctrl+Tab / Ctrl+]: the next bottom-dock view, or the next pet view
145 /// while the pet main view is showing.
146 ViewCycle,
147 /// Ctrl+Shift+Tab: the previous bottom-dock view, or the previous pet view.
148 ViewCycleBack,
149 }
150
151 /// One advertised binding with the portable catalog chord and focus rules.
152 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
153 pub struct ShellBinding {
154 pub id: ShellBindingId,
155 /// Chord shown in help / documentation (portable Alt form; macOS
156 /// substitutes `⌥` at render time via [`display_chord`]).
157 pub catalog_chord: &'static str,
158 /// Compact footer chord when this binding is advertised.
159 pub footer_chord: &'static str,
160 /// The focus states this binding is live in. Never composer content:
161 /// a shell binding does the same thing whether or not you have typed.
162 pub focus: FocusScope,
163 }
164
165 impl ShellBinding {
166 /// Does this key press this binding, ignoring focus?
167 #[must_use]
168 pub fn matches(&self, key: &KeyEvent) -> bool {
169 match self.id {
170 ShellBindingId::AccountLoginSelect => {
171 key.code == KeyCode::Enter && key.modifiers.is_empty()
172 }
173 ShellBindingId::AccountLoginNext => {
174 matches!(key.code, KeyCode::Down | KeyCode::Tab) && key.modifiers.is_empty()
175 }
176 ShellBindingId::AccountLoginOpenBrowser => {
177 key.code == KeyCode::Char('o') && key.modifiers.is_empty()
178 }
179 ShellBindingId::AccountLoginCopyLink => {
180 key.code == KeyCode::Char('c') && key.modifiers.is_empty()
181 }
182 ShellBindingId::AccountLoginCancel => {
183 key.code == KeyCode::Esc && key.modifiers.is_empty()
184 }
185 ShellBindingId::TerminalNew => {
186 key.code == KeyCode::Char('n') && key.modifiers == KeyModifiers::CONTROL
187 }
188 ShellBindingId::TerminalNext => {
189 key.code == KeyCode::Down && key.modifiers == KeyModifiers::ALT
190 }
191 ShellBindingId::TerminalPrevious => {
192 key.code == KeyCode::Up && key.modifiers == KeyModifiers::ALT
193 }
194 ShellBindingId::TerminalDetach => key.code == KeyCode::Esc && key.modifiers.is_empty(),
195 ShellBindingId::ElevationUp => key.code == KeyCode::Up && key.modifiers.is_empty(),
196 ShellBindingId::ElevationDown => key.code == KeyCode::Down && key.modifiers.is_empty(),
197 ShellBindingId::ElevationConfirm => {
198 key.code == KeyCode::Enter && key.modifiers.is_empty()
199 }
200 ShellBindingId::ElevationAbort => key.code == KeyCode::Esc && key.modifiers.is_empty(),
201 ShellBindingId::PetInspect => key.code == KeyCode::F(5) && key.modifiers.is_empty(),
202 ShellBindingId::PetResultUp => key.code == KeyCode::Up && key.modifiers.is_empty(),
203 ShellBindingId::PetResultDown => key.code == KeyCode::Down && key.modifiers.is_empty(),
204 ShellBindingId::PetResultPageUp => {
205 key.code == KeyCode::PageUp && key.modifiers.is_empty()
206 }
207 ShellBindingId::PetResultPageDown => {
208 key.code == KeyCode::PageDown && key.modifiers.is_empty()
209 }
210 ShellBindingId::PetBack => key.code == KeyCode::Esc && key.modifiers.is_empty(),
211 ShellBindingId::PetResultStart => key.code == KeyCode::Home && key.modifiers.is_empty(),
212 ShellBindingId::PetResultEnd => key.code == KeyCode::End && key.modifiers.is_empty(),
213 ShellBindingId::PetFocusAgents => key.code == KeyCode::Tab && key.modifiers.is_empty(),
214 ShellBindingId::PetOpenAgent => key.code == KeyCode::Enter && key.modifiers.is_empty(),
215 ShellBindingId::PetCopyReply => {
216 key.code == KeyCode::Char('c') && key.modifiers.is_empty()
217 }
218
219 ShellBindingId::RedactionGateConfirm => is_redaction_gate_choice(key, '1', 'y'),
220 ShellBindingId::RedactionGateKeepOrBack => is_redaction_gate_choice(key, '2', 'u'),
221 ShellBindingId::RedactionGateQuit => is_redaction_gate_choice(key, '3', 'n'),
222 ShellBindingId::RedactionGateScroll => {
223 key.modifiers.is_empty()
224 && matches!(
225 key.code,
226 KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown
227 )
228 }
229 ShellBindingId::ToolDetails => is_tool_details_shortcut(key),
230 ShellBindingId::ContextInspector => is_context_inspector_shortcut(key),
231 ShellBindingId::ProviderRoute => is_provider_route_shortcut(key),
232 ShellBindingId::Help => is_help_shortcut(key),
233 ShellBindingId::ExternalEditor => key_shortcuts::is_external_editor_shortcut(key),
234 ShellBindingId::Settings => is_settings_shortcut(key),
235 ShellBindingId::PermissionCycle => is_permission_cycle_shortcut(key),
236 ShellBindingId::ViewCycle => is_view_cycle_shortcut(key),
237 ShellBindingId::ViewCycleBack => is_view_cycle_back_shortcut(key),
238 }
239 }
240 }
241
242 /// The shell's single key-admission authority: which binding, if any, this
243 /// key presses for this focus owner.
244 ///
245 /// Callers keep their position in the event loop — that ordering is a real
246 /// statement about which surface sees a key first — but none of them decides
247 /// admission any more, and none of them may ask about composer content.
248 #[must_use]
249 pub fn route(focus: Focus, key: &KeyEvent) -> Option<ShellBindingId> {
250 SHELL_BINDINGS
251 .iter()
252 .find(|binding| {
253 binding.focus.admits(focus)
254 && binding.matches(key)
255 && !(focus == Focus::TerminalPanel && binding.id == ShellBindingId::PermissionCycle)
256 })
257 .map(|binding| binding.id)
258 }
259
260 /// Canonical shell bindings. Handlers and chrome read from here.
261 pub const SHELL_BINDINGS: &[ShellBinding] = &[
262 ShellBinding {
263 id: ShellBindingId::AccountLoginSelect,
264 catalog_chord: "Enter",
265 footer_chord: "Enter",
266 focus: FocusScope::AccountLogin,
267 },
268 ShellBinding {
269 id: ShellBindingId::AccountLoginNext,
270 catalog_chord: "Down / Tab",
271 footer_chord: "↓/Tab",
272 focus: FocusScope::AccountLogin,
273 },
274 ShellBinding {
275 id: ShellBindingId::AccountLoginOpenBrowser,
276 catalog_chord: "o",
277 footer_chord: "o",
278 focus: FocusScope::AccountLogin,
279 },
280 ShellBinding {
281 id: ShellBindingId::AccountLoginCopyLink,
282 catalog_chord: "c",
283 footer_chord: "c",
284 focus: FocusScope::AccountLogin,
285 },
286 ShellBinding {
287 id: ShellBindingId::AccountLoginCancel,
288 catalog_chord: "Esc",
289 footer_chord: "Esc",
290 focus: FocusScope::AccountLogin,
291 },
292 ShellBinding {
293 id: ShellBindingId::TerminalNew,
294 catalog_chord: "Ctrl+N",
295 footer_chord: "Ctrl+N",
296 focus: FocusScope::TerminalPanel,
297 },
298 ShellBinding {
299 id: ShellBindingId::TerminalNext,
300 catalog_chord: "Alt+Down",
301 footer_chord: "Alt+Down",
302 focus: FocusScope::TerminalPanel,
303 },
304 ShellBinding {
305 id: ShellBindingId::TerminalPrevious,
306 catalog_chord: "Alt+Up",
307 footer_chord: "Alt+Up",
308 focus: FocusScope::TerminalPanel,
309 },
310 ShellBinding {
311 id: ShellBindingId::TerminalDetach,
312 catalog_chord: "Esc",
313 footer_chord: "Esc",
314 focus: FocusScope::TerminalPanel,
315 },
316 ShellBinding {
317 id: ShellBindingId::ElevationUp,
318 catalog_chord: "Up",
319 footer_chord: "↑",
320 focus: FocusScope::Elevation,
321 },
322 ShellBinding {
323 id: ShellBindingId::ElevationDown,
324 catalog_chord: "Down",
325 footer_chord: "↓",
326 focus: FocusScope::Elevation,
327 },
328 ShellBinding {
329 id: ShellBindingId::ElevationConfirm,
330 catalog_chord: "Enter",
331 footer_chord: "Enter",
332 focus: FocusScope::Elevation,
333 },
334 ShellBinding {
335 id: ShellBindingId::ElevationAbort,
336 catalog_chord: "Esc",
337 footer_chord: "Esc",
338 focus: FocusScope::Elevation,
339 },
340 ShellBinding {
341 id: ShellBindingId::PetInspect,
342 catalog_chord: "F5",
343 footer_chord: "F5",
344 focus: FocusScope::AnyShell,
345 },
346 ShellBinding {
347 id: ShellBindingId::PetResultUp,
348 catalog_chord: "Up",
349 footer_chord: "↑",
350 focus: FocusScope::PetHabitat,
351 },
352 ShellBinding {
353 id: ShellBindingId::PetResultDown,
354 catalog_chord: "Down",
355 footer_chord: "↓",
356 focus: FocusScope::PetHabitat,
357 },
358 ShellBinding {
359 id: ShellBindingId::PetResultPageUp,
360 catalog_chord: "PgUp",
361 footer_chord: "PgUp",
362 focus: FocusScope::PetHabitat,
363 },
364 ShellBinding {
365 id: ShellBindingId::PetResultPageDown,
366 catalog_chord: "PgDn",
367 footer_chord: "PgDn",
368 focus: FocusScope::PetHabitat,
369 },
370 ShellBinding {
371 id: ShellBindingId::PetBack,
372 catalog_chord: "Esc",
373 footer_chord: "Esc",
374 focus: FocusScope::PetHabitat,
375 },
376 ShellBinding {
377 id: ShellBindingId::PetResultStart,
378 catalog_chord: "Home",
379 footer_chord: "Home",
380 focus: FocusScope::PetHabitat,
381 },
382 ShellBinding {
383 id: ShellBindingId::PetResultEnd,
384 catalog_chord: "End",
385 footer_chord: "End",
386 focus: FocusScope::PetHabitat,
387 },
388 ShellBinding {
389 id: ShellBindingId::PetFocusAgents,
390 catalog_chord: "Tab",
391 footer_chord: "Tab",
392 focus: FocusScope::PetHabitat,
393 },
394 ShellBinding {
395 id: ShellBindingId::PetOpenAgent,
396 catalog_chord: "Enter",
397 footer_chord: "Enter",
398 focus: FocusScope::PetHabitat,
399 },
400 ShellBinding {
401 id: ShellBindingId::PetCopyReply,
402 catalog_chord: "c",
403 footer_chord: "c",
404 focus: FocusScope::PetHabitat,
405 },
406 ShellBinding {
407 id: ShellBindingId::RedactionGateConfirm,
408 catalog_chord: "1/Y",
409 footer_chord: "1/Y",
410 focus: FocusScope::RedactionGate,
411 },
412 ShellBinding {
413 id: ShellBindingId::RedactionGateKeepOrBack,
414 catalog_chord: "2/U",
415 footer_chord: "2/U",
416 focus: FocusScope::RedactionGate,
417 },
418 ShellBinding {
419 id: ShellBindingId::RedactionGateQuit,
420 catalog_chord: "3/N",
421 footer_chord: "3/N",
422 focus: FocusScope::RedactionGate,
423 },
424 ShellBinding {
425 id: ShellBindingId::RedactionGateScroll,
426 catalog_chord: "↑/↓",
427 footer_chord: "↑/↓",
428 focus: FocusScope::RedactionGate,
429 },
430 ShellBinding {
431 id: ShellBindingId::ToolDetails,
432 catalog_chord: "Alt+V",
433 footer_chord: "Alt+V",
434 // The rail claims the details chord for a selected row before the
435 // transcript pager sees it; both are session surfaces.
436 focus: FocusScope::SessionShell,
437 },
438 ShellBinding {
439 id: ShellBindingId::ContextInspector,
440 // `/context` is the guaranteed path; Alt+C stays an unadvertised
441 // handler until proven in Cursor/Terminal.app/iTerm2/tmux/PTY.
442 catalog_chord: "/context",
443 footer_chord: "/context",
444 focus: FocusScope::SessionShell,
445 },
446 ShellBinding {
447 id: ShellBindingId::ProviderRoute,
448 // `/provider` remains the portable, explicit command path.
449 catalog_chord: "F3 / /provider",
450 footer_chord: "F3",
451 // The route is also pickable before a session exists.
452 focus: FocusScope::AnyShell,
453 },
454 ShellBinding {
455 id: ShellBindingId::ExternalEditor,
456 catalog_chord: codewhale_engine::keybinding_table::EXTERNAL_EDITOR_CHORD,
457 footer_chord: "F4",
458 focus: FocusScope::AnyShell,
459 },
460 ShellBinding {
461 id: ShellBindingId::Help,
462 // `/help` also opens this. F1 is accepted but never advertised on
463 // chrome: tmux and several emulators eat it (see
464 // [`HELP_CHROME_CHORD`]).
465 catalog_chord: "F1 / Ctrl+/",
466 footer_chord: HELP_CHROME_CHORD,
467 focus: FocusScope::Everywhere,
468 },
469 ShellBinding {
470 id: ShellBindingId::Settings,
471 catalog_chord: "F2",
472 footer_chord: "F2",
473 // Shell-global for the same reason as Help: a settings route that
474 // disappears inside onboarding or a modal is not a route.
475 focus: FocusScope::Everywhere,
476 },
477 ShellBinding {
478 id: ShellBindingId::PermissionCycle,
479 catalog_chord: "Shift+Tab",
480 footer_chord: "Shift+Tab",
481 // A shell-level permission control, live wherever the shell is —
482 // including the launch screen, where it used to be dead — plus the
483 // Config modal that displays the posture it changes.
484 focus: FocusScope::AnyShellOrConfig,
485 },
486 ShellBinding {
487 id: ShellBindingId::ViewCycle,
488 // Ctrl+Tab only arrives under the kitty keyboard protocol (the loop
489 // pushes DISAMBIGUATE_ESCAPE_CODES); Ctrl+] is the chord every
490 // terminal delivers — unbound here, not eaten by VS Code/Cursor
491 // (Ctrl+F is), tmux, iTerm2, Terminal.app, or Windows Terminal.
492 catalog_chord: "Ctrl+Tab / Ctrl+]",
493 footer_chord: "Ctrl+]",
494 // The launch card advertises this same work-bar control.
495 focus: FocusScope::AnyShell,
496 },
497 ShellBinding {
498 id: ShellBindingId::ViewCycleBack,
499 catalog_chord: "Ctrl+Shift+Tab",
500 footer_chord: "Ctrl+Shift+Tab",
501 focus: FocusScope::AnyShell,
502 },
503 ];
504
505 fn is_redaction_gate_choice(key: &KeyEvent, digit: char, letter: char) -> bool {
506 // Modifiers must not turn an unrelated shortcut into consent. Shift is
507 // accepted for the uppercase letter advertised in the action rail.
508 (key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT)
509 && matches!(key.code, KeyCode::Char(ch) if ch == digit || ch.eq_ignore_ascii_case(&letter))
510 }
511
512 /// The chord the info line advertises for help.
513 ///
514 /// Not `F1`: tmux, screen, and several terminal emulators claim it before the
515 /// shell ever sees the key, so an info line that printed `F1 help` would be
516 /// advertising a key that does nothing for many users. Not `?` either — bare
517 /// `?` is composer text in every focus state, and help only answers to
518 /// `Alt+?`, which stays unadvertised until it is proven in real terminals
519 /// (TUI-DOG-003). `Ctrl+/` remains accepted, together with its legacy
520 /// `Ctrl+7` / `Ctrl+_` encodings, but it is no longer what chrome advertises:
521 /// how a terminal encodes Ctrl+/ varies enough that the printed hint was a
522 /// promise the product could not keep on the founder's own machine. `/help`
523 /// is a slash command — it reaches the same view through the composer, it
524 /// works in every terminal, and typing `/` already reveals it.
525 pub const HELP_CHROME_CHORD: &str = "/help";
526
527 /// The info line's single right-hand key hint.
528 ///
529 /// A slash command names itself, so it prints bare (`/help`); a key chord
530 /// still needs the word (`Ctrl+/ help`).
531 #[must_use]
532 pub fn info_help_hint(locale: codewhale_localization::Locale) -> String {
533 let chord = binding(ShellBindingId::Help).footer_chord;
534 if chord.starts_with('/') {
535 return chord.to_string();
536 }
537 format!(
538 "{} {}",
539 chord,
540 codewhale_localization::tr(locale, codewhale_localization::MessageId::InfoLineHelp)
541 )
542 }
543
544 #[must_use]
545 pub fn binding(id: ShellBindingId) -> &'static ShellBinding {
546 SHELL_BINDINGS
547 .iter()
548 .find(|binding| binding.id == id)
549 .expect("shell binding catalog is exhaustive")
550 }
551
552 /// Platform-aware chord for opening complete tool or approval details.
553 #[must_use]
554 pub fn tool_details_chord() -> Cow<'static, str> {
555 display_chord(binding(ShellBindingId::ToolDetails).footer_chord)
556 }
557
558 /// Render a portable `Alt+X` chord for the current platform. macOS normally
559 /// shows `⌥X` and `fn+F5`, because an Apple keyboard sends media keys from the
560 /// top row unless Fn is held; ASCII-safe terminals retain the portable spelling.
561 #[must_use]
562 pub fn display_chord(chord: &'static str) -> Cow<'static, str> {
563 display_chord_for_platform_and_ascii(
564 chord,
565 cfg!(target_os = "macos"),
566 crate::tui::color_compat::ascii_safe_enabled(),
567 )
568 }
569
570 #[cfg(test)]
571 #[must_use]
572 pub fn display_chord_for_platform(chord: &'static str, is_macos: bool) -> Cow<'static, str> {
573 display_chord_for_platform_and_ascii(chord, is_macos, false)
574 }
575
576 fn display_chord_for_platform_and_ascii(
577 chord: &'static str,
578 is_macos: bool,
579 ascii_safe: bool,
580 ) -> Cow<'static, str> {
581 if !is_macos {
582 return Cow::Borrowed(chord);
583 }
584 let mut rendered = String::with_capacity(chord.len() + 6);
585 let mut previous = None;
586 for (index, ch) in chord.char_indices() {
587 if ch == 'F'
588 && !previous.is_some_and(char::is_alphanumeric)
589 && chord[index + 1..].starts_with(|next: char| next.is_ascii_digit())
590 {
591 rendered.push_str("fn+");
592 }
593 rendered.push(ch);
594 previous = Some(ch);
595 }
596 let rendered = if ascii_safe {
597 rendered
598 } else {
599 rendered.replace("Alt+", "⌥")
600 };
601 if rendered == chord {
602 Cow::Borrowed(chord)
603 } else {
604 Cow::Owned(rendered)
605 }
606 }
607
608 /// Details/output opens only on Option+V (macOS legacy `√`) or Alt+V.
609 /// Bare `v` always types `v` — never a shortcut, in any focus state.
610 #[must_use]
611 pub fn is_tool_details_shortcut(key: &KeyEvent) -> bool {
612 if key_shortcuts::is_macos_option_v_legacy_key(key) {
613 return true;
614 }
615 matches!(key.code, KeyCode::Char('v') | KeyCode::Char('V'))
616 && key_shortcuts::alt_nav_modifiers(key.modifiers)
617 }
618
619 #[must_use]
620 pub fn is_context_inspector_shortcut(key: &KeyEvent) -> bool {
621 matches!(key.code, KeyCode::Char('c') | KeyCode::Char('C'))
622 && key_shortcuts::alt_nav_modifiers(key.modifiers)
623 }
624
625 /// Route entry stays on a non-printable function key so it never steals a
626 /// model/provider name from the composer. `/provider` remains available in
627 /// terminals that do not forward function keys.
628 #[must_use]
629 pub fn is_provider_route_shortcut(key: &KeyEvent) -> bool {
630 matches!(key.code, KeyCode::F(3)) && key.modifiers.is_empty()
631 }
632
633 #[must_use]
634 pub fn is_help_shortcut(key: &KeyEvent) -> bool {
635 if matches!(key.code, KeyCode::F(1)) {
636 return true;
637 }
638 // Windows delivers AltGr as Ctrl+Alt, so a layout-emitted glyph (e.g.
639 // AltGr+Q typing '/' on ABNT2) would satisfy a bare CONTROL check.
640 // AltGr chords are text, never shortcuts (#4723).
641 let altgr = crate::tui::widgets::key_hint::is_altgr(key.modifiers);
642 if matches!(key.code, KeyCode::Char('/'))
643 && key.modifiers.contains(KeyModifiers::CONTROL)
644 && !altgr
645 {
646 return true;
647 }
648 // Some legacy terminal stacks encode Ctrl+/ as the ASCII unit separator,
649 // which crossterm reports as Ctrl+7 or Ctrl+_. Accept both portable
650 // decodings so the documented fallback remains real.
651 if matches!(key.code, KeyCode::Char('7') | KeyCode::Char('_'))
652 && key.modifiers.contains(KeyModifiers::CONTROL)
653 && !altgr
654 {
655 return true;
656 }
657 // Alt+? still opens help where the terminal delivers it, but it is not
658 // advertised anywhere (TUI-DOG-003).
659 matches!(key.code, KeyCode::Char('?')) && key_shortcuts::alt_nav_modifiers(key.modifiers)
660 }
661
662 #[must_use]
663 pub fn is_settings_shortcut(key: &KeyEvent) -> bool {
664 matches!(key.code, KeyCode::F(2)) && key.modifiers.is_empty()
665 }
666
667 /// Shift+Tab steps the permission dial. Terminals encode the same chord
668 /// either as `BackTab` or as `Tab` + SHIFT; accept both.
669 #[must_use]
670 pub fn is_permission_cycle_shortcut(key: &KeyEvent) -> bool {
671 let forbidden = KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER;
672 if key.modifiers.intersects(forbidden) {
673 return false;
674 }
675 matches!(key.code, KeyCode::BackTab)
676 || (matches!(key.code, KeyCode::Tab) && key.modifiers.contains(KeyModifiers::SHIFT))
677 }
678
679 /// Ctrl+Tab (kitty protocol: `Tab` + CONTROL) or Ctrl+] cycles the bottom
680 /// dock view forward. Legacy terminals send Ctrl+] as ASCII 0x1d, which
681 /// crossterm decodes as Ctrl+5. AltGr chords stay text (#4723).
682 #[must_use]
683 pub fn is_view_cycle_shortcut(key: &KeyEvent) -> bool {
684 if crate::tui::widgets::key_hint::is_altgr(key.modifiers) {
685 return false;
686 }
687 let ctrl_only = key.modifiers.contains(KeyModifiers::CONTROL)
688 && !key
689 .modifiers
690 .intersects(KeyModifiers::ALT | KeyModifiers::SUPER | KeyModifiers::SHIFT);
691 ctrl_only && matches!(key.code, KeyCode::Tab | KeyCode::Char(']' | '5'))
692 }
693
694 /// Ctrl+Shift+Tab (kitty protocol: `BackTab` or `Tab` with CONTROL|SHIFT)
695 /// cycles the bottom dock view backward.
696 #[must_use]
697 pub fn is_view_cycle_back_shortcut(key: &KeyEvent) -> bool {
698 if key
699 .modifiers
700 .intersects(KeyModifiers::ALT | KeyModifiers::SUPER)
701 || !key.modifiers.contains(KeyModifiers::CONTROL)
702 {
703 return false;
704 }
705 matches!(key.code, KeyCode::BackTab)
706 || (matches!(key.code, KeyCode::Tab) && key.modifiers.contains(KeyModifiers::SHIFT))
707 }
708
709 #[cfg(test)]
710 mod tests {
711 use super::*;
712
713 #[test]
714 fn view_cycle_chords_are_ctrl_tab_and_ctrl_bracket() {
715 let ctrl_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::CONTROL);
716 let ctrl_bracket = KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL);
717 let ctrl_shift_tab = KeyEvent::new(
718 KeyCode::BackTab,
719 KeyModifiers::CONTROL | KeyModifiers::SHIFT,
720 );
721 assert_eq!(
722 route(Focus::Composer, &ctrl_tab),
723 Some(ShellBindingId::ViewCycle)
724 );
725 assert_eq!(
726 route(Focus::Panel, &ctrl_bracket),
727 Some(ShellBindingId::ViewCycle)
728 );
729 assert_eq!(
730 route(Focus::Composer, &ctrl_shift_tab),
731 Some(ShellBindingId::ViewCycleBack)
732 );
733 // Plain Tab is composer completion only; Shift+Tab is the dial.
734 assert_eq!(
735 route(
736 Focus::Composer,
737 &KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)
738 ),
739 None
740 );
741 assert_eq!(
742 route(
743 Focus::Composer,
744 &KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT)
745 ),
746 Some(ShellBindingId::PermissionCycle)
747 );
748 // Ctrl+T is reasoning effort, not ours; a bare `]` is composer text.
749 assert_eq!(
750 route(
751 Focus::Composer,
752 &KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL)
753 ),
754 None
755 );
756 assert_eq!(
757 route(
758 Focus::Composer,
759 &KeyEvent::new(KeyCode::Char(']'), KeyModifiers::NONE)
760 ),
761 None
762 );
763 // Modals keep every key.
764 assert_eq!(route(Focus::Modal(ModalKind::Pager), &ctrl_bracket), None);
765 }
766
767 #[test]
768 fn work_bar_accepts_legacy_and_enhanced_keys_on_launch() {
769 for code in [KeyCode::Tab, KeyCode::Char(']'), KeyCode::Char('5')] {
770 let key = KeyEvent::new(code, KeyModifiers::CONTROL);
771 assert_eq!(route(Focus::Launch, &key), Some(ShellBindingId::ViewCycle));
772 assert_eq!(route(Focus::Onboarding, &key), None);
773 assert_eq!(route(Focus::Modal(ModalKind::Pager), &key), None);
774 }
775 for modifiers in [
776 KeyModifiers::NONE,
777 KeyModifiers::ALT,
778 KeyModifiers::CONTROL | KeyModifiers::ALT,
779 ] {
780 assert!(!is_view_cycle_shortcut(&KeyEvent::new(
781 KeyCode::Char('5'),
782 modifiers
783 )));
784 }
785 let backwards = KeyEvent::new(
786 KeyCode::BackTab,
787 KeyModifiers::CONTROL | KeyModifiers::SHIFT,
788 );
789 assert_eq!(
790 route(Focus::Launch, &backwards),
791 Some(ShellBindingId::ViewCycleBack)
792 );
793 }
794
795 #[test]
796 fn bare_v_is_never_a_shortcut_in_any_state() {
797 // TUI-DOG-002: bare `v` always types `v`; there is no focus state in
798 // which it opens details, so the matcher takes no focus argument.
799 let plain_v = KeyEvent::new(KeyCode::Char('v'), KeyModifiers::NONE);
800 assert!(!is_tool_details_shortcut(&plain_v));
801 let plain_upper_v = KeyEvent::new(KeyCode::Char('V'), KeyModifiers::SHIFT);
802 assert!(!is_tool_details_shortcut(&plain_upper_v));
803 }
804
805 #[test]
806 fn alt_v_and_macos_option_v_open_details() {
807 let alt_v = KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT);
808 assert!(is_tool_details_shortcut(&alt_v));
809 let alt_upper_v = KeyEvent::new(KeyCode::Char('V'), KeyModifiers::ALT);
810 assert!(is_tool_details_shortcut(&alt_upper_v));
811 }
812
813 #[test]
814 fn details_label_is_option_glyph_on_macos_and_alt_elsewhere() {
815 assert_eq!(display_chord_for_platform("Alt+V", true), "⌥V");
816 assert_eq!(display_chord_for_platform("Alt+V", false), "Alt+V");
817 }
818
819 #[test]
820 fn chrome_never_advertises_a_key_terminals_eat() {
821 // F1 stays in the catalog (it works where delivered) but no chrome
822 // hint may print it; the help hint is derived from the binding.
823 // Ctrl+/ is still accepted, but chrome advertises the route that
824 // works in every terminal.
825 assert_eq!(binding(ShellBindingId::Help).footer_chord, "/help");
826 let hint = info_help_hint(codewhale_localization::Locale::En);
827 assert_eq!(hint, "/help", "a slash command names itself");
828 assert!(
829 is_help_shortcut(&KeyEvent::new(KeyCode::Char('/'), KeyModifiers::CONTROL)),
830 "Ctrl+/ must keep working for the terminals that deliver it"
831 );
832 for binding in SHELL_BINDINGS {
833 assert!(!binding.footer_chord.contains("F1"), "{:?}", binding.id);
834 assert!(!binding.footer_chord.contains("Alt+?"), "{:?}", binding.id);
835 }
836 }
837
838 #[test]
839 fn help_accepts_f1_ctrl_slash_and_unadvertised_fallbacks() {
840 assert!(is_help_shortcut(&KeyEvent::new(
841 KeyCode::F(1),
842 KeyModifiers::NONE
843 )));
844 assert!(is_help_shortcut(&KeyEvent::new(
845 KeyCode::Char('/'),
846 KeyModifiers::CONTROL
847 )));
848 assert!(is_help_shortcut(&KeyEvent::new(
849 KeyCode::Char('7'),
850 KeyModifiers::CONTROL
851 )));
852 assert!(is_help_shortcut(&KeyEvent::new(
853 KeyCode::Char('_'),
854 KeyModifiers::CONTROL
855 )));
856 // Unadvertised but accepted where the terminal delivers them.
857 assert!(is_help_shortcut(&KeyEvent::new(
858 KeyCode::Char('?'),
859 KeyModifiers::ALT
860 )));
861 let inverted_question = KeyEvent::new(KeyCode::Char('\u{00bf}'), KeyModifiers::NONE);
862 assert!(!is_help_shortcut(&inverted_question));
863 }
864
865 #[test]
866 fn altgr_slash_types_text_instead_of_opening_help() {
867 // Windows encodes AltGr as Ctrl+Alt: AltGr+Q on ABNT2 delivers '/'
868 // with CONTROL|ALT and must reach the composer as text (#4723).
869 let altgr_slash = KeyEvent::new(
870 KeyCode::Char('/'),
871 KeyModifiers::CONTROL | KeyModifiers::ALT,
872 );
873 let altgr_seven = KeyEvent::new(
874 KeyCode::Char('7'),
875 KeyModifiers::CONTROL | KeyModifiers::ALT,
876 );
877 if cfg!(windows) {
878 assert!(!is_help_shortcut(&altgr_slash));
879 assert!(!is_help_shortcut(&altgr_seven));
880 } else {
881 // Elsewhere Ctrl+Alt is a deliberate chord and keeps working.
882 assert!(is_help_shortcut(&altgr_slash));
883 assert!(is_help_shortcut(&altgr_seven));
884 }
885 // Plain Ctrl+/ still opens help everywhere.
886 assert!(is_help_shortcut(&KeyEvent::new(
887 KeyCode::Char('/'),
888 KeyModifiers::CONTROL
889 )));
890 }
891
892 #[test]
893 fn settings_accepts_only_plain_f2() {
894 assert!(is_settings_shortcut(&KeyEvent::new(
895 KeyCode::F(2),
896 KeyModifiers::NONE
897 )));
898 assert!(!is_settings_shortcut(&KeyEvent::new(
899 KeyCode::F(2),
900 KeyModifiers::SHIFT
901 )));
902 assert!(!is_settings_shortcut(&KeyEvent::new(
903 KeyCode::F(1),
904 KeyModifiers::NONE
905 )));
906 }
907
908 #[test]
909 fn context_accepts_explicit_alt_c_without_stealing_layout_characters() {
910 let alt_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::ALT);
911 assert!(is_context_inspector_shortcut(&alt_c));
912 let cedilla = KeyEvent::new(KeyCode::Char('\u{00e7}'), KeyModifiers::NONE);
913 assert!(!is_context_inspector_shortcut(&cedilla));
914 }
915
916 #[test]
917 fn infoline_route_f3_requires_a_plain_function_key() {
918 assert!(is_provider_route_shortcut(&KeyEvent::new(
919 KeyCode::F(3),
920 KeyModifiers::NONE
921 )));
922 assert!(!is_provider_route_shortcut(&KeyEvent::new(
923 KeyCode::F(3),
924 KeyModifiers::ALT
925 )));
926 assert!(!is_provider_route_shortcut(&KeyEvent::new(
927 KeyCode::Char('3'),
928 KeyModifiers::NONE
929 )));
930 }
931
932 #[test]
933 fn chrome_only_advertises_chords_that_are_live_where_it_is_shown() {
934 // The metrics line's help hint is built from this table, so it must
935 // not be able to name a chord the same table refuses at any focus
936 // the chrome is rendered in (the hint paints on every screen).
937 let hint = info_help_hint(codewhale_localization::Locale::En);
938 let help = binding(ShellBindingId::Help);
939 assert!(hint.starts_with(help.footer_chord), "{hint}");
940 assert_eq!(help.focus, FocusScope::Everywhere);
941 assert!(help.matches(&KeyEvent::new(KeyCode::Char('/'), KeyModifiers::CONTROL)));
942 }
943
944 #[test]
945 fn elevation_bindings_are_nontext_and_stay_in_the_elevation_card() {
946 for (code, id) in [
947 (KeyCode::Up, ShellBindingId::ElevationUp),
948 (KeyCode::Down, ShellBindingId::ElevationDown),
949 (KeyCode::Enter, ShellBindingId::ElevationConfirm),
950 (KeyCode::Esc, ShellBindingId::ElevationAbort),
951 ] {
952 let key = KeyEvent::new(code, KeyModifiers::NONE);
953 assert_eq!(route(Focus::Modal(ModalKind::Elevation), &key), Some(id));
954 assert!(!binding(id).footer_chord.is_empty());
955 for focus in [
956 Focus::Composer,
957 Focus::Launch,
958 Focus::Modal(ModalKind::Approval),
959 ] {
960 assert_ne!(route(focus, &key), Some(id));
961 }
962 for modifiers in [
963 KeyModifiers::ALT,
964 KeyModifiers::CONTROL,
965 KeyModifiers::SUPER,
966 KeyModifiers::SHIFT,
967 ] {
968 assert_ne!(
969 route(
970 Focus::Modal(ModalKind::Elevation),
971 &KeyEvent::new(code, modifiers)
972 ),
973 Some(id)
974 );
975 }
976 }
977 for letter in "nwfajkN W F A J K123".chars() {
978 assert_eq!(
979 route(
980 Focus::Modal(ModalKind::Elevation),
981 &KeyEvent::new(KeyCode::Char(letter), KeyModifiers::NONE)
982 ),
983 None
984 );
985 }
986 }
987
988 #[test]
989 fn focus_scopes_nest_from_the_session_outwards() {
990 let ladder = [
991 FocusScope::SessionShell,
992 FocusScope::AnyShell,
993 FocusScope::AnyShellOrConfig,
994 FocusScope::Everywhere,
995 ];
996 let states = [
997 Focus::RedactionGate,
998 Focus::Composer,
999 Focus::Panel,
1000 Focus::Launch,
1001 Focus::Modal(ModalKind::Config),
1002 Focus::Modal(ModalKind::Approval),
1003 Focus::Onboarding,
1004 ];
1005 for pair in ladder.windows(2) {
1006 for focus in states {
1007 assert!(
1008 !pair[0].admits(focus) || pair[1].admits(focus),
1009 "{:?} admits {focus:?} but the wider {:?} does not",
1010 pair[0],
1011 pair[1]
1012 );
1013 }
1014 }
1015 // Nothing but Help/Settings may reach a focused workflow.
1016 for binding in SHELL_BINDINGS {
1017 assert_eq!(
1018 binding.focus.admits(Focus::Modal(ModalKind::Approval)),
1019 binding.focus == FocusScope::Everywhere,
1020 "{:?} must not reach across an approval decision",
1021 binding.id
1022 );
1023 }
1024 }
1025
1026 #[test]
1027 fn tab_and_shift_tab_are_distinct_bindings() {
1028 let tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
1029 let shift_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT);
1030 assert_eq!(route(Focus::Composer, &tab), None);
1031 assert_eq!(
1032 route(Focus::Composer, &shift_tab),
1033 Some(ShellBindingId::PermissionCycle)
1034 );
1035 assert_eq!(route(Focus::Launch, &tab), None);
1036 assert_eq!(
1037 route(Focus::Launch, &shift_tab),
1038 Some(ShellBindingId::PermissionCycle)
1039 );
1040 }
1041
1042 #[test]
1043 fn redaction_choices_require_the_gate_and_explicit_unmodified_keys() {
1044 for (id, keys) in [
1045 (ShellBindingId::RedactionGateConfirm, ['1', 'y', 'Y']),
1046 (ShellBindingId::RedactionGateKeepOrBack, ['2', 'u', 'U']),
1047 (ShellBindingId::RedactionGateQuit, ['3', 'n', 'N']),
1048 ] {
1049 for key in keys {
1050 for modifiers in [KeyModifiers::NONE, KeyModifiers::SHIFT] {
1051 let event = KeyEvent::new(KeyCode::Char(key), modifiers);
1052 assert_eq!(route(Focus::RedactionGate, &event), Some(id));
1053 for focus in [
1054 Focus::Composer,
1055 Focus::Panel,
1056 Focus::Launch,
1057 Focus::Onboarding,
1058 Focus::Modal(ModalKind::Approval),
1059 ] {
1060 assert_eq!(route(focus, &event), None, "{focus:?}: {event:?}");
1061 }
1062 }
1063 for modifiers in [
1064 KeyModifiers::CONTROL,
1065 KeyModifiers::ALT,
1066 KeyModifiers::SUPER,
1067 KeyModifiers::CONTROL | KeyModifiers::SHIFT,
1068 ] {
1069 assert_eq!(
1070 route(
1071 Focus::RedactionGate,
1072 &KeyEvent::new(KeyCode::Char(key), modifiers)
1073 ),
1074 None
1075 );
1076 }
1077 }
1078 }
1079 for code in [KeyCode::Enter, KeyCode::F(1), KeyCode::F(2), KeyCode::Tab] {
1080 assert_eq!(
1081 route(
1082 Focus::RedactionGate,
1083 &KeyEvent::new(code, KeyModifiers::NONE)
1084 ),
1085 None
1086 );
1087 }
1088 for code in [
1089 KeyCode::Up,
1090 KeyCode::Down,
1091 KeyCode::PageUp,
1092 KeyCode::PageDown,
1093 ] {
1094 assert_eq!(
1095 route(
1096 Focus::RedactionGate,
1097 &KeyEvent::new(code, KeyModifiers::NONE)
1098 ),
1099 Some(ShellBindingId::RedactionGateScroll)
1100 );
1101 }
1102 }
1103
1104 #[test]
1105 fn catalog_chords_match_final_contract() {
1106 assert_eq!(binding(ShellBindingId::Help).catalog_chord, "F1 / Ctrl+/");
1107 assert_eq!(
1108 binding(ShellBindingId::ContextInspector).catalog_chord,
1109 "/context"
1110 );
1111 assert_eq!(binding(ShellBindingId::ToolDetails).catalog_chord, "Alt+V");
1112 assert_eq!(
1113 binding(ShellBindingId::ProviderRoute).catalog_chord,
1114 "F3 / /provider"
1115 );
1116 for binding in SHELL_BINDINGS {
1117 assert!(!binding.catalog_chord.contains("Alt+?"));
1118 assert_ne!(binding.catalog_chord, "v");
1119 assert!(!binding.catalog_chord.starts_with("v /"));
1120 assert!(!binding.footer_chord.contains("Alt+?"));
1121 assert_ne!(binding.footer_chord, "v");
1122 }
1123 }
1124
1125 #[test]
1126 fn shell_binding_source_matches_help_catalog_chords() {
1127 assert_eq!(binding(ShellBindingId::ToolDetails).catalog_chord, "Alt+V");
1128 assert_eq!(
1129 binding(ShellBindingId::ContextInspector).catalog_chord,
1130 "/context"
1131 );
1132 assert_eq!(
1133 binding(ShellBindingId::ProviderRoute).catalog_chord,
1134 "F3 / /provider"
1135 );
1136 assert_eq!(binding(ShellBindingId::Help).catalog_chord, "F1 / Ctrl+/");
1137 // Every ordinary shell binding: exclusive redaction choices are
1138 // advertised only by their consent screen, never as global shortcuts.
1139 // The two that were
1140 // not covered had already drifted (the view-cycle chord read
1141 // "Ctrl+] / Ctrl+Tab" here and "Ctrl+Tab / Ctrl+]" at the source),
1142 // which is exactly the rot this module's doc comment warns about.
1143 for id in [
1144 ShellBindingId::ToolDetails,
1145 ShellBindingId::ContextInspector,
1146 ShellBindingId::ProviderRoute,
1147 ShellBindingId::Help,
1148 ShellBindingId::Settings,
1149 ShellBindingId::PermissionCycle,
1150 ShellBindingId::ViewCycle,
1151 ShellBindingId::ViewCycleBack,
1152 ] {
1153 let chord = binding(id).catalog_chord;
1154 assert!(
1155 codewhale_engine::keybinding_table::KEYBINDINGS
1156 .iter()
1157 .any(|entry| entry.chord == chord || entry.chord.contains(chord)),
1158 "shell binding {id:?} chord missing from help catalog: {chord}"
1159 );
1160 }
1161 }
1162 }
1163
1163 lines RUST