1use hashbrown::{HashMap, HashSet};
2use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
3use std::time::{Duration, Instant};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum Action {
13 Interrupt,
15 Exit,
17 BackgroundOperation,
19 OpenModelPicker,
21 ClearScreen,
23 ScrollPageUp,
25 ScrollPageDown,
27 EditQueue,
29 HistoryPrevious,
31 HistoryNext,
33 ToggleLogs,
35 ToggleToolDisplayMode,
37 ToggleTaskPanel,
39 OpenTranscriptReview,
41 ToggleTranscriptRenderMode,
43 GeneratePromptSuggestion,
45 JumpToLastChange,
47 FocusInput,
50}
51
52impl Action {
53 fn name(self) -> &'static str {
55 match self {
56 Action::Interrupt => "interrupt",
57 Action::Exit => "exit",
58 Action::BackgroundOperation => "background_operation",
59 Action::OpenModelPicker => "open_model_picker",
60 Action::ClearScreen => "clear_screen",
61 Action::ScrollPageUp => "scroll_page_up",
62 Action::ScrollPageDown => "scroll_page_down",
63 Action::EditQueue => "edit_queue",
64 Action::HistoryPrevious => "history_previous",
65 Action::HistoryNext => "history_next",
66 Action::ToggleLogs => "toggle_logs",
67 Action::ToggleToolDisplayMode => "toggle_tool_display_mode",
68 Action::ToggleTaskPanel => "toggle_task_panel",
69 Action::OpenTranscriptReview => "open_transcript_review",
70 Action::ToggleTranscriptRenderMode => "toggle_transcript_render_mode",
71 Action::GeneratePromptSuggestion => "generate_prompt_suggestion",
72 Action::JumpToLastChange => "jump_to_last_change",
73 Action::FocusInput => "focus_input",
74 }
75 }
76
77 fn all() -> &'static [Action] {
79 &[
80 Action::Interrupt,
81 Action::Exit,
82 Action::BackgroundOperation,
83 Action::OpenModelPicker,
84 Action::ClearScreen,
85 Action::ScrollPageUp,
86 Action::ScrollPageDown,
87 Action::EditQueue,
88 Action::HistoryPrevious,
89 Action::HistoryNext,
90 Action::ToggleLogs,
91 Action::ToggleToolDisplayMode,
92 Action::ToggleTaskPanel,
93 Action::OpenTranscriptReview,
94 Action::ToggleTranscriptRenderMode,
95 Action::GeneratePromptSuggestion,
96 Action::JumpToLastChange,
97 Action::FocusInput,
98 ]
99 }
100
101 fn from_name(name: &str) -> Option<Self> {
103 Self::all().iter().find(|a| a.name() == name).copied()
104 }
105}
106
107pub fn parse_key_binding(s: &str) -> Option<(KeyCode, KeyModifiers)> {
114 let normalized = s.trim().to_ascii_lowercase();
115 let s = normalized.as_str();
116 if s.is_empty() {
117 return None;
118 }
119
120 let parts: Vec<&str> = s.split('+').collect();
121 let (modifiers, key_part) = if parts.len() == 1 {
122 (KeyModifiers::empty(), parts[0])
123 } else {
124 let mut mods = KeyModifiers::empty();
125 for part in &parts[..parts.len() - 1] {
126 match *part {
127 "ctrl" | "control" => mods.insert(KeyModifiers::CONTROL),
128 "shift" => mods.insert(KeyModifiers::SHIFT),
129 "alt" | "option" => mods.insert(KeyModifiers::ALT),
130 "meta" => mods.insert(KeyModifiers::META),
131 "cmd" | "command" | "super" | "gui" | "win" => {
132 mods.insert(KeyModifiers::SUPER);
133 }
134 _ => return None,
135 }
136 }
137 (mods, parts[parts.len() - 1])
138 };
139
140 let code = match key_part {
141 "enter" => KeyCode::Enter,
142 "tab" => KeyCode::Tab,
143 "backtab" => KeyCode::BackTab,
144 "esc" | "escape" => KeyCode::Esc,
145 "backspace" => KeyCode::Backspace,
146 "delete" => KeyCode::Delete,
147 "space" => KeyCode::Char(' '),
148 "up" => KeyCode::Up,
149 "down" => KeyCode::Down,
150 "left" => KeyCode::Left,
151 "right" => KeyCode::Right,
152 "pageup" => KeyCode::PageUp,
153 "pagedown" => KeyCode::PageDown,
154 "home" => KeyCode::Home,
155 "end" => KeyCode::End,
156 "insert" => KeyCode::Insert,
157 "null" => KeyCode::Null,
158 "capslock" => KeyCode::CapsLock,
159 "scrolllock" => KeyCode::ScrollLock,
160 "numlock" => KeyCode::NumLock,
161 "printscreen" => KeyCode::PrintScreen,
162 "pause" => KeyCode::Pause,
163 "menu" => KeyCode::Menu,
164 name if name.starts_with('f') && name.len() > 1 => {
165 let n: u8 = name[1..].parse().ok()?;
166 match n {
167 1 => KeyCode::F(1),
168 2 => KeyCode::F(2),
169 3 => KeyCode::F(3),
170 4 => KeyCode::F(4),
171 5 => KeyCode::F(5),
172 6 => KeyCode::F(6),
173 7 => KeyCode::F(7),
174 8 => KeyCode::F(8),
175 9 => KeyCode::F(9),
176 10 => KeyCode::F(10),
177 11 => KeyCode::F(11),
178 12 => KeyCode::F(12),
179 _ => return None,
180 }
181 }
182 ch => {
183 let chars: Vec<char> = ch.chars().collect();
184 if chars.len() == 1 {
185 KeyCode::Char(chars[0])
186 } else {
187 return None;
188 }
189 }
190 };
191
192 Some((code, modifiers))
193}
194
195fn default_bindings() -> HashMap<Action, Vec<(KeyCode, KeyModifiers)>> {
197 use Action::*;
198 let mut m = HashMap::new();
199
200 m.insert(
201 Interrupt,
202 vec![
203 (KeyCode::Char('c'), KeyModifiers::CONTROL),
204 (KeyCode::Char('C'), KeyModifiers::CONTROL),
205 (KeyCode::Char('\u{3}'), KeyModifiers::empty()),
206 ],
207 );
208 m.insert(
209 Exit,
210 vec![
211 (KeyCode::Char('d'), KeyModifiers::CONTROL),
212 (KeyCode::Char('D'), KeyModifiers::CONTROL),
213 ],
214 );
215 m.insert(
216 BackgroundOperation,
217 vec![
218 (KeyCode::Char('b'), KeyModifiers::CONTROL),
219 (KeyCode::Char('B'), KeyModifiers::CONTROL),
220 ],
221 );
222 m.insert(
223 OpenModelPicker,
224 vec![
225 (KeyCode::Char('m'), KeyModifiers::CONTROL),
226 (KeyCode::Char('M'), KeyModifiers::CONTROL),
227 ],
228 );
229 m.insert(
230 ClearScreen,
231 vec![
232 (KeyCode::Char('l'), KeyModifiers::CONTROL),
233 (KeyCode::Char('L'), KeyModifiers::CONTROL),
234 ],
235 );
236 m.insert(ScrollPageUp, vec![(KeyCode::PageUp, KeyModifiers::empty())]);
237 m.insert(ScrollPageDown, vec![(KeyCode::PageDown, KeyModifiers::empty())]);
238
239 m.insert(EditQueue, vec![(KeyCode::Up, KeyModifiers::ALT), (KeyCode::Up, KeyModifiers::META)]);
240
241 m.insert(HistoryPrevious, vec![(KeyCode::Up, KeyModifiers::empty())]);
242 m.insert(HistoryNext, vec![(KeyCode::Down, KeyModifiers::empty())]);
243
244 m.insert(
245 ToggleToolDisplayMode,
246 vec![
247 (KeyCode::Char('t'), KeyModifiers::ALT),
248 (KeyCode::Char('T'), KeyModifiers::ALT),
249 ],
250 );
251 m.insert(
252 ToggleTaskPanel,
253 vec![
254 (KeyCode::Char('g'), KeyModifiers::ALT),
255 (KeyCode::Char('G'), KeyModifiers::ALT),
256 ],
257 );
258 m.insert(
259 OpenTranscriptReview,
260 vec![
261 (KeyCode::Char('t'), KeyModifiers::CONTROL),
262 (KeyCode::Char('T'), KeyModifiers::CONTROL),
263 ],
264 );
265 m.insert(ToggleTranscriptRenderMode, vec![(KeyCode::Char('r'), KeyModifiers::empty())]);
266 m.insert(
267 GeneratePromptSuggestion,
268 vec![
269 (KeyCode::Char('p'), KeyModifiers::ALT),
270 (KeyCode::Char('P'), KeyModifiers::ALT),
271 ],
272 );
273 m.insert(JumpToLastChange, vec![(KeyCode::End, KeyModifiers::CONTROL)]);
274 m.insert(FocusInput, vec![(KeyCode::Char('i'), KeyModifiers::ALT), (KeyCode::Char('I'), KeyModifiers::ALT)]);
275
276 m
277}
278
279#[derive(Debug, Clone)]
284pub struct BindingStore {
285 entries: Vec<(KeyCode, KeyModifiers, Action)>,
287 primary_labels: HashMap<Action, String>,
289 overridden_actions: HashSet<Action>,
291}
292
293impl Default for BindingStore {
294 fn default() -> Self {
295 Self::defaults()
296 }
297}
298
299impl BindingStore {
300 pub(crate) fn new(overlay: HashMap<String, Vec<String>>) -> Self {
306 let mut merged: HashMap<Action, Vec<(KeyCode, KeyModifiers)>> = default_bindings();
307 let mut configured_actions = HashSet::new();
308
309 for (action_name, key_specs) in overlay {
310 let Some(action) = Action::from_name(&action_name) else {
311 tracing::debug!(%action_name, "unknown action in keybinding overlay, skipping");
312 continue;
313 };
314
315 let parsed: Vec<(KeyCode, KeyModifiers)> = key_specs.iter().filter_map(|s| parse_key_binding(s)).collect();
316
317 if key_specs.is_empty() {
318 merged.remove(&action);
320 configured_actions.insert(action);
321 } else if parsed.is_empty() {
322 tracing::warn!(
323 action = action.name(),
324 "keybinding overlay contains no valid bindings; keeping defaults"
325 );
326 } else {
327 merged.insert(action, parsed);
328 configured_actions.insert(action);
329 }
330 }
331
332 let mut entries = Vec::new();
333 for action in Action::all()
337 .iter()
338 .copied()
339 .filter(|action| configured_actions.contains(action))
340 .chain(
341 Action::all()
342 .iter()
343 .copied()
344 .filter(|action| !configured_actions.contains(action)),
345 )
346 {
347 let Some(keys) = merged.get(&action) else {
348 continue;
349 };
350 for &(code, mods) in keys {
351 entries.push((code, mods, action));
352 }
353 }
354
355 let mut primary_labels = HashMap::new();
360 let mut claimed_bindings = Vec::with_capacity(entries.len());
361 for &(code, mods, action) in &entries {
362 let is_reachable = !claimed_bindings
363 .iter()
364 .any(|&(claimed_code, claimed_mods)| binding_covers(claimed_code, claimed_mods, code, mods));
365 if is_reachable {
366 primary_labels.entry(action).or_insert_with(|| format_key_label(code, mods));
367 }
368 claimed_bindings.push((code, mods));
369 }
370
371 Self {
372 entries,
373 primary_labels,
374 overridden_actions: configured_actions,
375 }
376 }
377
378 fn defaults() -> Self {
380 Self::new(HashMap::new())
381 }
382
383 pub(crate) fn resolve(&self, key: &KeyEvent) -> Option<Action> {
388 let (key_code, key_modifiers) = normalize_terminal_control_key(key.code, key.modifiers);
393 let mut best: Option<(usize, Action)> = None;
394
395 for (i, &(code, mods, action)) in self.entries.iter().enumerate() {
398 let code_match = match (code, key_code) {
399 (KeyCode::Char(bc), KeyCode::Char(kc)) if bc.eq_ignore_ascii_case(&kc) => true,
400 _ => code == key_code,
401 };
402
403 if !code_match {
404 continue;
405 }
406
407 if !key_modifiers.contains(mods) {
409 continue;
410 }
411
412 let char_shift_grace = if let KeyCode::Char(_) = key_code {
415 KeyModifiers::SHIFT
416 } else {
417 KeyModifiers::empty()
418 };
419 let extra = key_modifiers.difference(mods);
420 if extra.intersection(!char_shift_grace) != KeyModifiers::empty() {
421 continue;
422 }
423
424 best = match best {
427 None => Some((i, action)),
428 Some((bi, _)) if i < bi => Some((i, action)),
429 Some(other) => Some(other),
430 };
431 }
432
433 best.map(|(_, action)| action)
434 }
435
436 pub(crate) fn primary_key_label(&self, action: Action) -> Option<&str> {
437 self.primary_labels.get(&action).map(String::as_str)
438 }
439
440 pub(crate) fn action_is_overridden(&self, action: Action) -> bool {
441 self.overridden_actions.contains(&action)
442 }
443}
444
445fn binding_covers(
446 existing_code: KeyCode,
447 existing_modifiers: KeyModifiers,
448 candidate_code: KeyCode,
449 candidate_modifiers: KeyModifiers,
450) -> bool {
451 let code_matches = match (existing_code, candidate_code) {
452 (KeyCode::Char(existing), KeyCode::Char(candidate)) => existing.eq_ignore_ascii_case(&candidate),
453 _ => existing_code == candidate_code,
454 };
455 if !code_matches || !candidate_modifiers.contains(existing_modifiers) {
456 return false;
457 }
458
459 let char_shift_grace = if matches!(candidate_code, KeyCode::Char(_)) {
460 KeyModifiers::SHIFT
461 } else {
462 KeyModifiers::empty()
463 };
464 candidate_modifiers
465 .difference(existing_modifiers)
466 .intersection(!char_shift_grace)
467 == KeyModifiers::empty()
468}
469
470pub(crate) fn normalize_terminal_control_event(mut key: KeyEvent) -> KeyEvent {
471 let (code, modifiers) = normalize_terminal_control_key(key.code, key.modifiers);
472 key.code = code;
473 key.modifiers = modifiers;
474 key
475}
476
477pub(crate) const DOUBLE_ESCAPE_WINDOW: Duration = Duration::from_millis(800);
484
485pub(crate) fn is_double_escape_press(last_press: Option<Instant>, now: Instant) -> bool {
490 last_press.is_some_and(|last| now.duration_since(last) <= DOUBLE_ESCAPE_WINDOW)
491}
492
493pub(crate) fn is_readline_editing_key(key: &KeyEvent) -> bool {
496 let modifiers = key.modifiers;
497 let has_control = modifiers.contains(KeyModifiers::CONTROL);
498 let has_alt = modifiers.contains(KeyModifiers::ALT);
499 let has_command = modifiers.intersects(KeyModifiers::SUPER | KeyModifiers::META);
500
501 if has_command {
502 return false;
503 }
504
505 (has_control
506 && !has_alt
507 && matches!(
508 key.code,
509 KeyCode::Char('f')
510 | KeyCode::Char('F')
511 | KeyCode::Char('p')
512 | KeyCode::Char('P')
513 | KeyCode::Char('n')
514 | KeyCode::Char('N')
515 | KeyCode::Char('t')
516 | KeyCode::Char('T')
517 ))
518 || (has_alt
519 && !has_control
520 && matches!(
521 key.code,
522 KeyCode::Char('d')
523 | KeyCode::Char('D')
524 | KeyCode::Char('u')
525 | KeyCode::Char('U')
526 | KeyCode::Char('l')
527 | KeyCode::Char('L')
528 | KeyCode::Char('c')
529 | KeyCode::Char('C')
530 | KeyCode::Char('\\')
531 ))
532}
533
534fn normalize_terminal_control_key(code: KeyCode, modifiers: KeyModifiers) -> (KeyCode, KeyModifiers) {
535 let Some(control) = (match code {
536 KeyCode::Char(character) => Some(character as u32),
537 _ => None,
538 }) else {
539 return (code, modifiers);
540 };
541
542 if !(1..=26).contains(&control) || matches!(control, 9 | 13) {
546 return (code, modifiers);
547 }
548
549 let Some(letter) = char::from_u32(u32::from(b'a') + control - 1) else {
550 return (code, modifiers);
551 };
552 (KeyCode::Char(letter), modifiers | KeyModifiers::CONTROL)
553}
554
555fn format_key_label(code: KeyCode, modifiers: KeyModifiers) -> String {
556 let mut parts = Vec::with_capacity(5);
557 if modifiers.contains(KeyModifiers::CONTROL) {
558 parts.push("Ctrl");
559 }
560 if modifiers.contains(KeyModifiers::ALT) {
561 parts.push("Alt");
562 }
563 if modifiers.contains(KeyModifiers::SUPER) {
564 parts.push("Cmd");
565 } else if modifiers.contains(KeyModifiers::META) {
566 parts.push("Meta");
567 }
568 if modifiers.contains(KeyModifiers::SHIFT) {
569 parts.push("Shift");
570 }
571
572 let key = match code {
573 KeyCode::Char(' ') => "Space".to_string(),
574 KeyCode::Char(character) => character.to_ascii_uppercase().to_string(),
575 KeyCode::Enter => "Enter".to_string(),
576 KeyCode::Tab => "Tab".to_string(),
577 KeyCode::BackTab => "Backtab".to_string(),
578 KeyCode::Esc => "Esc".to_string(),
579 KeyCode::Backspace => "Backspace".to_string(),
580 KeyCode::Delete => "Delete".to_string(),
581 KeyCode::Insert => "Insert".to_string(),
582 KeyCode::Up => "Up".to_string(),
583 KeyCode::Down => "Down".to_string(),
584 KeyCode::Left => "Left".to_string(),
585 KeyCode::Right => "Right".to_string(),
586 KeyCode::PageUp => "PageUp".to_string(),
587 KeyCode::PageDown => "PageDown".to_string(),
588 KeyCode::Home => "Home".to_string(),
589 KeyCode::End => "End".to_string(),
590 KeyCode::F(number) => format!("F{number}"),
591 other => format!("{other:?}"),
592 };
593 parts.push(key.as_str());
594 parts.join("+")
595}
596
597impl super::Session {
598 pub(crate) fn resolve_rebindable_action(&self, key: &KeyEvent) -> Option<Action> {
599 self.bindings.resolve(key)
600 }
601
602 pub(crate) fn dispatch_rebindable_action(&mut self, action: Action) -> Option<super::super::types::InlineEvent> {
603 super::events::dispatch_rebindable_action(self, action)
604 }
605
606 pub(crate) fn primary_binding_label(&self, action: Action) -> Option<&str> {
607 self.bindings.primary_key_label(action)
608 }
609
610 pub(crate) fn rebindable_action_is_overridden(&self, action: Action) -> bool {
611 self.bindings.action_is_overridden(action)
612 }
613
614 pub(crate) fn set_bindings(&mut self, bindings: BindingStore) {
615 self.bindings = bindings;
616 self.mark_visual_dirty();
617 }
618
619 pub(crate) fn transcript_review_hints_visible(&self) -> bool {
620 self.appearance.show_transcript_review_hints
621 }
622
623 pub(crate) fn transcript_review_shortcut_guide_visible(&self) -> bool {
624 self.appearance.show_transcript_review_shortcut_guide
625 }
626
627 pub(crate) fn transcript_review_close_button_visible(&self) -> bool {
628 self.appearance.show_transcript_review_close_button
629 }
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635 use ratatui::crossterm::event::KeyEvent;
636
637 #[test]
638 fn test_parse_key_binding_simple() {
639 let (code, mods) = parse_key_binding("ctrl+c").unwrap();
640 assert_eq!(code, KeyCode::Char('c'));
641 assert!(mods.contains(KeyModifiers::CONTROL));
642 assert!(!mods.contains(KeyModifiers::SHIFT));
643 }
644
645 #[test]
646 fn test_parse_key_binding_modifier_combos() {
647 let (code, mods) = parse_key_binding("ctrl+shift+enter").unwrap();
648 assert_eq!(code, KeyCode::Enter);
649 assert!(mods.contains(KeyModifiers::CONTROL));
650 assert!(mods.contains(KeyModifiers::SHIFT));
651 }
652
653 #[test]
654 fn test_parse_key_binding_is_case_insensitive() {
655 let (code, mods) = parse_key_binding("CTRL+SHIFT+X").unwrap();
656 assert_eq!(code, KeyCode::Char('x'));
657 assert!(mods.contains(KeyModifiers::CONTROL | KeyModifiers::SHIFT));
658 }
659
660 #[test]
661 fn test_parse_key_binding_func_keys() {
662 let (code, _) = parse_key_binding("f5").unwrap();
663 assert_eq!(code, KeyCode::F(5));
664 }
665
666 #[test]
667 fn test_parse_key_binding_special() {
668 let (code, _) = parse_key_binding("pageup").unwrap();
669 assert_eq!(code, KeyCode::PageUp);
670 let (code, _) = parse_key_binding("backtab").unwrap();
671 assert_eq!(code, KeyCode::BackTab);
672 }
673
674 #[test]
675 fn test_default_bindings_resolve() {
676 let store = BindingStore::defaults();
677
678 let key = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
680 assert_eq!(store.resolve(&key), Some(Action::Interrupt));
681
682 let key = KeyEvent::new(KeyCode::PageUp, KeyModifiers::empty());
684 assert_eq!(store.resolve(&key), Some(Action::ScrollPageUp));
685
686 let key = KeyEvent::new(KeyCode::Up, KeyModifiers::ALT);
688 assert_eq!(store.resolve(&key), Some(Action::EditQueue));
689
690 let key = KeyEvent::new(KeyCode::Char('i'), KeyModifiers::ALT);
692 assert_eq!(store.resolve(&key), Some(Action::FocusInput));
693 let key = KeyEvent::new(KeyCode::Char('I'), KeyModifiers::ALT);
694 assert_eq!(store.resolve(&key), Some(Action::FocusInput));
695
696 let key = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL);
698 assert_eq!(store.resolve(&key), None);
699 }
700
701 #[test]
702 fn test_default_bindings_case_insensitive() {
703 let store = BindingStore::defaults();
704
705 let key = KeyEvent::new(KeyCode::Char('C'), KeyModifiers::CONTROL);
707 assert_eq!(store.resolve(&key), Some(Action::Interrupt));
708 }
709
710 #[test]
711 fn test_default_tool_display_binding_is_alt_t() {
712 let store = BindingStore::defaults();
713 let key = KeyEvent::new(KeyCode::Char('t'), KeyModifiers::ALT);
714 assert_eq!(store.resolve(&key), Some(Action::ToggleToolDisplayMode));
715 }
716
717 #[test]
718 fn test_default_task_panel_binding_is_alt_g() {
719 let store = BindingStore::defaults();
720 let key = KeyEvent::new(KeyCode::Char('g'), KeyModifiers::ALT);
721 assert_eq!(store.resolve(&key), Some(Action::ToggleTaskPanel));
722 }
723
724 #[test]
725 fn test_default_transcript_review_bindings() {
726 let store = BindingStore::defaults();
727 assert_eq!(
728 store.resolve(&KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL)),
729 Some(Action::OpenTranscriptReview)
730 );
731 assert_eq!(
732 store.resolve(&KeyEvent::new(KeyCode::Char('r'), KeyModifiers::empty())),
733 Some(Action::ToggleTranscriptRenderMode)
734 );
735 }
736
737 #[test]
738 fn test_raw_control_character_matches_transcript_review_binding() {
739 let store = BindingStore::defaults();
740
741 assert_eq!(
742 store.resolve(&KeyEvent::new(KeyCode::Char('\u{14}'), KeyModifiers::empty())),
743 Some(Action::OpenTranscriptReview)
744 );
745 }
746
747 #[test]
748 fn test_transcript_review_bindings_can_be_rebound() {
749 let mut overlay = HashMap::new();
750 overlay.insert("open_transcript_review".to_string(), vec!["ctrl+x".to_string()]);
751 overlay.insert("toggle_transcript_render_mode".to_string(), vec!["alt+x".to_string()]);
752 let store = BindingStore::new(overlay);
753
754 assert_eq!(
755 store.resolve(&KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)),
756 Some(Action::OpenTranscriptReview)
757 );
758 assert_eq!(
759 store.resolve(&KeyEvent::new(KeyCode::Char('x'), KeyModifiers::ALT)),
760 Some(Action::ToggleTranscriptRenderMode)
761 );
762 assert_eq!(store.resolve(&KeyEvent::new(KeyCode::Char('r'), KeyModifiers::empty())), None);
763 }
764
765 #[test]
766 fn test_task_panel_binding_can_be_rebound() {
767 let mut overlay = HashMap::new();
768 overlay.insert("toggle_task_panel".to_string(), vec!["ctrl+x".to_string()]);
769 let store = BindingStore::new(overlay);
770
771 assert_eq!(
772 store.resolve(&KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)),
773 Some(Action::ToggleTaskPanel)
774 );
775 assert_eq!(store.resolve(&KeyEvent::new(KeyCode::Char('g'), KeyModifiers::ALT)), None);
776 }
777
778 #[test]
779 fn test_tool_display_binding_can_be_rebound() {
780 let mut overlay = HashMap::new();
781 overlay.insert("toggle_tool_display_mode".to_string(), vec!["ctrl+x".to_string()]);
782 let store = BindingStore::new(overlay);
783
784 assert_eq!(
785 store.resolve(&KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)),
786 Some(Action::ToggleToolDisplayMode)
787 );
788 assert_eq!(store.resolve(&KeyEvent::new(KeyCode::Char('t'), KeyModifiers::ALT)), None);
789 }
790
791 #[test]
792 fn test_user_overlay_overrides_default() {
793 let mut overlay = HashMap::new();
794 overlay.insert("interrupt".to_string(), vec!["ctrl+x".to_string()]);
795 let store = BindingStore::new(overlay);
796
797 let key_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
799 assert_eq!(store.resolve(&key_c), None);
800
801 let key_x = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL);
803 assert_eq!(store.resolve(&key_x), Some(Action::Interrupt));
804 }
805
806 #[test]
807 fn test_user_overlay_unbind() {
808 let mut overlay = HashMap::new();
809 overlay.insert("interrupt".to_string(), Vec::new());
810 let store = BindingStore::new(overlay);
811
812 let key = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
813 assert_eq!(store.resolve(&key), None);
814 }
815
816 #[test]
817 fn test_invalid_overlay_keeps_defaults_and_does_not_override_action() {
818 let mut overlay = HashMap::new();
819 overlay.insert("interrupt".to_string(), vec!["not-a-key".to_string()]);
820 let store = BindingStore::new(overlay);
821
822 assert_eq!(store.resolve(&KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)), Some(Action::Interrupt));
823 assert!(!store.action_is_overridden(Action::Interrupt));
824 }
825
826 #[test]
827 fn test_configured_binding_collision_is_deterministic() {
828 let mut overlay = HashMap::new();
829 overlay.insert("interrupt".to_string(), vec!["ctrl+x".to_string()]);
830 overlay.insert("open_model_picker".to_string(), vec!["ctrl+x".to_string()]);
831 let store = BindingStore::new(overlay);
832
833 assert_eq!(store.resolve(&KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)), Some(Action::Interrupt));
834 assert_eq!(store.primary_key_label(Action::Interrupt), Some("Ctrl+X"));
835 assert_eq!(store.primary_key_label(Action::OpenModelPicker), None);
836 }
837
838 #[test]
839 fn test_parse_invalid_key() {
840 assert!(parse_key_binding("").is_none());
841 assert!(parse_key_binding("invalid_key_name").is_none());
842 assert!(parse_key_binding("ctrl+invalid").is_none());
843 assert!(parse_key_binding("+ctrl+c").is_none());
844 }
845
846 #[test]
847 fn test_action_name_roundtrip() {
848 for action in Action::all() {
849 let name = action.name();
850 let parsed = Action::from_name(name);
851 assert_eq!(parsed, Some(*action));
852 }
853 }
854
855 #[test]
856 fn test_action_from_name_unknown() {
857 assert_eq!(Action::from_name("nonexistent"), None);
858 }
859
860 #[test]
861 fn double_escape_press_requires_an_armed_consecutive_press() {
862 let now = Instant::now();
863 let exactly_at_window = now.checked_sub(DOUBLE_ESCAPE_WINDOW).expect("clock is past the window");
864 let beyond_window = now
865 .checked_sub(DOUBLE_ESCAPE_WINDOW + Duration::from_millis(1))
866 .expect("clock is past the window");
867
868 assert!(!is_double_escape_press(None, now));
869 assert!(is_double_escape_press(Some(now), now));
870 assert!(is_double_escape_press(Some(exactly_at_window), now));
871 assert!(!is_double_escape_press(Some(beyond_window), now));
872 }
873}