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