Skip to main content

agent_engine/skills/
keybinds.rs

1//! Plugin keybinds — registry, parser, and matching for custom keyboard shortcuts.
2//!
3//! Plugins declare keybinds in `plugin.json`. Users override in config.
4//! Core keybinds (Ctrl+C, Esc, etc.) are never overridable.
5
6use crossterm::event::{KeyCode, KeyModifiers};
7use std::collections::HashSet;
8use std::path::PathBuf;
9
10/// A key combination (modifiers + key).
11#[derive(Debug, Clone, PartialEq, Eq, Hash)]
12pub struct KeyCombo {
13    pub code: KeyCode,
14    pub modifiers: KeyModifiers,
15}
16
17/// What happens when a keybind fires.
18#[derive(Debug, Clone)]
19pub enum KeybindAction {
20    /// Execute a slash command (e.g. "scholar quantum")
21    SlashCommand(String),
22    /// Load a skill by name
23    LoadSkill(String),
24    /// Submit text as a user message
25    InjectPrompt(String),
26    /// Run a script and inject output as system message
27    RunScript { script: String, plugin_dir: PathBuf },
28    /// Explicitly disabled (user override)
29    Disabled,
30}
31
32/// Where a keybind came from — for conflict resolution and display.
33#[derive(Debug, Clone, PartialEq)]
34pub enum KeybindSource {
35    Core,
36    User,
37    Plugin(String),
38}
39
40/// A registered keybind.
41#[derive(Debug, Clone)]
42pub struct Keybind {
43    pub key: KeyCombo,
44    pub action: KeybindAction,
45    pub description: String,
46    pub source: KeybindSource,
47}
48
49/// A keybind that was rejected during plugin registration because the
50/// key was already taken. Phase 8 slice 8B.2.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct KeybindCollision {
53    /// Plugin whose keybind was rejected.
54    pub losing_plugin: String,
55    /// Notation of the key (e.g. "ctrl+space"), as written in the manifest.
56    pub key: String,
57    /// What already owned this key — either another plugin name (string)
58    /// or the literal "core" if `reserved.contains(&combo)`.
59    pub winning_owner: String,
60    /// Optional reason: "invalid notation: …" for parse errors,
61    /// "conflicts with core" for reserved keys, "already registered"
62    /// for plugin-vs-plugin collisions.
63    pub reason: String,
64}
65
66/// Registry of all keybinds with conflict resolution.
67#[derive(Debug, Clone)]
68pub struct KeybindRegistry {
69    binds: Vec<Keybind>,
70    reserved: HashSet<KeyCombo>,
71    collisions: Vec<KeybindCollision>,
72}
73
74impl Default for KeybindRegistry {
75    fn default() -> Self {
76        Self::new()
77    }
78}
79
80impl KeybindRegistry {
81    pub fn new() -> Self {
82        let mut registry = Self {
83            binds: Vec::new(),
84            reserved: HashSet::new(),
85            collisions: Vec::new(),
86        };
87        registry.register_core();
88        registry
89    }
90
91    /// Plugin keybinds that were rejected due to collisions. Phase 8 slice 8B.2.
92    pub fn collisions(&self) -> &[KeybindCollision] {
93        &self.collisions
94    }
95
96    /// Reset the recorded collision list (e.g. before a registry rebuild).
97    pub fn clear_collisions(&mut self) {
98        self.collisions.clear();
99    }
100
101    /// Register core keybinds that can never be overridden.
102    fn register_core(&mut self) {
103        let core_keys = vec![
104            (KeyCode::Char('c'), KeyModifiers::CONTROL, "Quit"),
105            (KeyCode::Esc, KeyModifiers::NONE, "Abort stream"),
106            (KeyCode::Enter, KeyModifiers::NONE, "Submit"),
107            (KeyCode::Enter, KeyModifiers::SHIFT, "Newline"),
108            (KeyCode::Tab, KeyModifiers::NONE, "Autocomplete"),
109            (KeyCode::Char('a'), KeyModifiers::CONTROL, "Cursor start"),
110            (KeyCode::Char('e'), KeyModifiers::CONTROL, "Cursor end"),
111            (KeyCode::Char('u'), KeyModifiers::CONTROL, "Clear input"),
112            (KeyCode::Char('w'), KeyModifiers::CONTROL, "Delete word"),
113            (KeyCode::Char('o'), KeyModifiers::CONTROL, "Toggle output"),
114            (KeyCode::Left, KeyModifiers::ALT, "Jump word left"),
115            (KeyCode::Right, KeyModifiers::ALT, "Jump word right"),
116            (KeyCode::Up, KeyModifiers::SHIFT, "Scroll up"),
117            (KeyCode::Down, KeyModifiers::SHIFT, "Scroll down"),
118            (KeyCode::Up, KeyModifiers::CONTROL, "Watch older subagent"),
119            (
120                KeyCode::Down,
121                KeyModifiers::CONTROL,
122                "Watch newer subagent / main",
123            ),
124            // The same on Alt: macOS takes Ctrl-↑/↓ for Mission Control.
125            (KeyCode::Up, KeyModifiers::ALT, "Watch older subagent"),
126            (KeyCode::Down, KeyModifiers::ALT, "Watch newer subagent / main"),
127            (KeyCode::Up, KeyModifiers::NONE, "History up"),
128            (KeyCode::Down, KeyModifiers::NONE, "History down"),
129            (KeyCode::Left, KeyModifiers::NONE, "Cursor left"),
130            (KeyCode::Right, KeyModifiers::NONE, "Cursor right"),
131            (KeyCode::Backspace, KeyModifiers::NONE, "Backspace"),
132            (KeyCode::Backspace, KeyModifiers::ALT, "Delete word"),
133            (KeyCode::Home, KeyModifiers::NONE, "Cursor start"),
134            (KeyCode::End, KeyModifiers::NONE, "Cursor end"),
135        ];
136        for (code, modifiers, desc) in core_keys {
137            let combo = KeyCombo { code, modifiers };
138            self.reserved.insert(combo.clone());
139            self.binds.push(Keybind {
140                key: combo,
141                action: KeybindAction::Disabled, // core actions handled elsewhere
142                description: desc.to_string(),
143                source: KeybindSource::Core,
144            });
145        }
146    }
147
148    /// Register keybinds from a plugin manifest.
149    pub fn register_plugin(
150        &mut self,
151        plugin_name: &str,
152        keybinds: &[ManifestKeybind],
153        plugin_dir: &std::path::Path,
154    ) {
155        for kb in keybinds {
156            let combo = match parse_key(&kb.key) {
157                Ok(c) => c,
158                Err(e) => {
159                    tracing::warn!(
160                        "plugin '{}': invalid keybind '{}': {}",
161                        plugin_name,
162                        kb.key,
163                        e
164                    );
165                    self.collisions.push(KeybindCollision {
166                        losing_plugin: plugin_name.to_string(),
167                        key: kb.key.clone(),
168                        winning_owner: "n/a".to_string(),
169                        reason: format!("invalid notation: {}", e),
170                    });
171                    continue;
172                }
173            };
174
175            // Skip if reserved (core)
176            if self.reserved.contains(&combo) {
177                tracing::warn!(
178                    "plugin '{}': keybind '{}' conflicts with core — skipped",
179                    plugin_name,
180                    kb.key
181                );
182                self.collisions.push(KeybindCollision {
183                    losing_plugin: plugin_name.to_string(),
184                    key: kb.key.clone(),
185                    winning_owner: "core".to_string(),
186                    reason: "conflicts with core".to_string(),
187                });
188                continue;
189            }
190
191            // Skip if already registered by another plugin
192            if let Some(existing) = self
193                .binds
194                .iter()
195                .find(|b| b.key == combo && b.source != KeybindSource::Core)
196            {
197                let winning_owner = match &existing.source {
198                    KeybindSource::Plugin(name) => name.clone(),
199                    KeybindSource::User => "user".to_string(),
200                    KeybindSource::Core => "core".to_string(),
201                };
202                tracing::warn!(
203                    "plugin '{}': keybind '{}' already registered — skipped",
204                    plugin_name,
205                    kb.key
206                );
207                self.collisions.push(KeybindCollision {
208                    losing_plugin: plugin_name.to_string(),
209                    key: kb.key.clone(),
210                    winning_owner,
211                    reason: "already registered".to_string(),
212                });
213                continue;
214            }
215
216            let action = match kb.action.as_str() {
217                "slash_command" => {
218                    KeybindAction::SlashCommand(kb.command.clone().unwrap_or_default())
219                }
220                "load_skill" => KeybindAction::LoadSkill(kb.skill.clone().unwrap_or_default()),
221                "inject_prompt" => {
222                    KeybindAction::InjectPrompt(kb.prompt.clone().unwrap_or_default())
223                }
224                "run_script" => KeybindAction::RunScript {
225                    script: kb.script.clone().unwrap_or_default(),
226                    plugin_dir: plugin_dir.to_path_buf(),
227                },
228                other => {
229                    tracing::warn!(
230                        "plugin '{}': unknown keybind action '{}'",
231                        plugin_name,
232                        other
233                    );
234                    continue;
235                }
236            };
237
238            self.binds.push(Keybind {
239                key: combo,
240                action,
241                description: kb.description.clone().unwrap_or_default(),
242                source: KeybindSource::Plugin(plugin_name.to_string()),
243            });
244        }
245    }
246
247    /// Register user keybind overrides from config.
248    pub fn register_user(&mut self, config_keybinds: &std::collections::HashMap<String, String>) {
249        for (key_str, value) in config_keybinds {
250            let combo = match parse_key(key_str) {
251                Ok(c) => c,
252                Err(e) => {
253                    tracing::warn!("config: invalid keybind '{}': {}", key_str, e);
254                    continue;
255                }
256            };
257
258            // Skip core — even users can't override these
259            if self.reserved.contains(&combo) {
260                tracing::warn!("config: keybind '{}' is a core bind — skipped", key_str);
261                continue;
262            }
263
264            // Remove any existing plugin bind for this key
265            self.binds
266                .retain(|b| b.key != combo || b.source == KeybindSource::Core);
267
268            let action = if value == "disabled" {
269                KeybindAction::Disabled
270            } else if let Some(stripped) = value.strip_prefix('/') {
271                let cmd = stripped.to_string();
272                KeybindAction::SlashCommand(cmd)
273            } else {
274                KeybindAction::InjectPrompt(value.clone())
275            };
276
277            self.binds.push(Keybind {
278                key: combo,
279                action,
280                description: format!("User: {}", value),
281                source: KeybindSource::User,
282            });
283        }
284    }
285
286    /// Match a key event against registered keybinds.
287    /// Returns None for core binds (handled by the existing match block).
288    pub fn match_key(&self, code: KeyCode, modifiers: KeyModifiers) -> Option<&Keybind> {
289        let combo = KeyCombo { code, modifiers };
290
291        // Skip core — those are handled by the static match in input.rs
292        if self.reserved.contains(&combo) {
293            return None;
294        }
295
296        self.binds
297            .iter()
298            .find(|b| b.key == combo && !matches!(b.source, KeybindSource::Core))
299    }
300
301    /// All registered keybinds (for display in /keybinds and settings).
302    pub fn all(&self) -> &[Keybind] {
303        &self.binds
304    }
305
306    /// Non-core keybinds only (plugin + user).
307    pub fn custom_binds(&self) -> Vec<&Keybind> {
308        self.binds
309            .iter()
310            .filter(|b| !matches!(b.source, KeybindSource::Core))
311            .collect()
312    }
313}
314
315/// Keybind declaration from plugin.json manifest.
316#[derive(Debug, Clone, serde::Deserialize)]
317pub struct ManifestKeybind {
318    pub key: String,
319    #[serde(default)]
320    pub action: String,
321    #[serde(default)]
322    pub command: Option<String>,
323    #[serde(default)]
324    pub skill: Option<String>,
325    #[serde(default)]
326    pub prompt: Option<String>,
327    #[serde(default)]
328    pub script: Option<String>,
329    #[serde(default)]
330    pub description: Option<String>,
331}
332
333/// Parse key notation string into a KeyCombo.
334///
335/// Format: `[modifier-]*key`
336/// Modifiers: `C` (Ctrl), `S` (Shift), `A` (Alt)
337/// Keys: single char, `F1`–`F12`, `Space`, `Tab`, `Enter`, `Esc`
338///
339/// Examples:
340/// - `C-s` → Ctrl+S
341/// - `C-S-s` → Ctrl+Shift+S
342/// - `A-p` → Alt+P
343/// - `F5` → F5
344/// - `C-Space` → Ctrl+Space
345pub fn parse_key(notation: &str) -> Result<KeyCombo, String> {
346    let notation = notation.trim();
347    if notation.is_empty() {
348        return Err("empty key notation".to_string());
349    }
350
351    let parts: Vec<&str> = notation.split('-').collect();
352    let mut modifiers = KeyModifiers::empty();
353
354    // All parts except the last are modifiers
355    for part in &parts[..parts.len().saturating_sub(1)] {
356        match *part {
357            "C" => modifiers |= KeyModifiers::CONTROL,
358            "S" => modifiers |= KeyModifiers::SHIFT,
359            "A" => modifiers |= KeyModifiers::ALT,
360            other => {
361                return Err(format!(
362                    "unknown modifier: '{}' (expected C, S, or A)",
363                    other
364                ))
365            }
366        }
367    }
368
369    let key_str = parts.last().ok_or("missing key")?;
370    let code = match *key_str {
371        k if k.len() == 1 => {
372            let ch = k.chars().next().unwrap();
373            KeyCode::Char(ch.to_ascii_lowercase())
374        }
375        k if k.starts_with('F') && k.len() <= 3 => {
376            let n: u8 = k[1..]
377                .parse()
378                .map_err(|_| format!("invalid F-key: '{}'", k))?;
379            if !(1..=12).contains(&n) {
380                return Err(format!("F-key out of range: F{} (expected F1–F12)", n));
381            }
382            KeyCode::F(n)
383        }
384        "Space" => KeyCode::Char(' '),
385        "Tab" => KeyCode::Tab,
386        "Enter" => KeyCode::Enter,
387        "Esc" => KeyCode::Esc,
388        "Backspace" | "BS" => KeyCode::Backspace,
389        "Delete" | "Del" => KeyCode::Delete,
390        "Home" => KeyCode::Home,
391        "End" => KeyCode::End,
392        "PageUp" | "PgUp" => KeyCode::PageUp,
393        "PageDown" | "PgDn" => KeyCode::PageDown,
394        "Up" => KeyCode::Up,
395        "Down" => KeyCode::Down,
396        "Left" => KeyCode::Left,
397        "Right" => KeyCode::Right,
398        other => return Err(format!("unknown key: '{}'", other)),
399    };
400
401    Ok(KeyCombo { code, modifiers })
402}
403
404/// Format a KeyCombo back to notation string (for display).
405pub fn format_key(combo: &KeyCombo) -> String {
406    let mut parts = Vec::new();
407    if combo.modifiers.contains(KeyModifiers::CONTROL) {
408        parts.push("Ctrl");
409    }
410    if combo.modifiers.contains(KeyModifiers::ALT) {
411        parts.push("Alt");
412    }
413    if combo.modifiers.contains(KeyModifiers::SHIFT) {
414        parts.push("Shift");
415    }
416
417    let key = match combo.code {
418        KeyCode::Char(' ') => "Space".to_string(),
419        KeyCode::Char(c) => c.to_uppercase().to_string(),
420        KeyCode::F(n) => format!("F{}", n),
421        KeyCode::Tab => "Tab".to_string(),
422        KeyCode::Enter => "Enter".to_string(),
423        KeyCode::Esc => "Esc".to_string(),
424        KeyCode::Backspace => "Backspace".to_string(),
425        KeyCode::Delete => "Delete".to_string(),
426        KeyCode::Home => "Home".to_string(),
427        KeyCode::End => "End".to_string(),
428        KeyCode::PageUp => "PageUp".to_string(),
429        KeyCode::PageDown => "PageDown".to_string(),
430        KeyCode::Up => "↑".to_string(),
431        KeyCode::Down => "↓".to_string(),
432        KeyCode::Left => "←".to_string(),
433        KeyCode::Right => "→".to_string(),
434        _ => "?".to_string(),
435    };
436    parts.push(&key);
437    parts.join("+")
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    // ── parse_key tests ──
445
446    #[test]
447    fn parse_single_char() {
448        let k = parse_key("s").unwrap();
449        assert_eq!(k.code, KeyCode::Char('s'));
450        assert_eq!(k.modifiers, KeyModifiers::NONE);
451    }
452
453    #[test]
454    fn parse_ctrl_char() {
455        let k = parse_key("C-s").unwrap();
456        assert_eq!(k.code, KeyCode::Char('s'));
457        assert_eq!(k.modifiers, KeyModifiers::CONTROL);
458    }
459
460    #[test]
461    fn parse_ctrl_shift() {
462        let k = parse_key("C-S-s").unwrap();
463        assert_eq!(k.code, KeyCode::Char('s'));
464        assert_eq!(k.modifiers, KeyModifiers::CONTROL | KeyModifiers::SHIFT);
465    }
466
467    #[test]
468    fn parse_alt() {
469        let k = parse_key("A-p").unwrap();
470        assert_eq!(k.code, KeyCode::Char('p'));
471        assert_eq!(k.modifiers, KeyModifiers::ALT);
472    }
473
474    #[test]
475    fn parse_ctrl_alt() {
476        let k = parse_key("C-A-x").unwrap();
477        assert_eq!(k.code, KeyCode::Char('x'));
478        assert_eq!(k.modifiers, KeyModifiers::CONTROL | KeyModifiers::ALT);
479    }
480
481    #[test]
482    fn parse_f_keys() {
483        let k = parse_key("F5").unwrap();
484        assert_eq!(k.code, KeyCode::F(5));
485        assert_eq!(k.modifiers, KeyModifiers::NONE);
486
487        let k = parse_key("C-F12").unwrap();
488        assert_eq!(k.code, KeyCode::F(12));
489        assert_eq!(k.modifiers, KeyModifiers::CONTROL);
490    }
491
492    #[test]
493    fn parse_special_keys() {
494        assert_eq!(parse_key("Space").unwrap().code, KeyCode::Char(' '));
495        assert_eq!(parse_key("Tab").unwrap().code, KeyCode::Tab);
496        assert_eq!(parse_key("Enter").unwrap().code, KeyCode::Enter);
497        assert_eq!(parse_key("Esc").unwrap().code, KeyCode::Esc);
498        assert_eq!(parse_key("Backspace").unwrap().code, KeyCode::Backspace);
499        assert_eq!(parse_key("Home").unwrap().code, KeyCode::Home);
500        assert_eq!(parse_key("End").unwrap().code, KeyCode::End);
501    }
502
503    #[test]
504    fn parse_ctrl_space() {
505        let k = parse_key("C-Space").unwrap();
506        assert_eq!(k.code, KeyCode::Char(' '));
507        assert_eq!(k.modifiers, KeyModifiers::CONTROL);
508    }
509
510    #[test]
511    fn parse_uppercase_normalized_to_lower() {
512        let k = parse_key("C-S").unwrap();
513        assert_eq!(k.code, KeyCode::Char('s'));
514    }
515
516    #[test]
517    fn parse_empty_errors() {
518        assert!(parse_key("").is_err());
519        assert!(parse_key("  ").is_err());
520    }
521
522    #[test]
523    fn parse_unknown_modifier_errors() {
524        assert!(parse_key("X-s").is_err());
525    }
526
527    #[test]
528    fn parse_unknown_key_errors() {
529        assert!(parse_key("C-FooBar").is_err());
530    }
531
532    #[test]
533    fn parse_f_key_out_of_range() {
534        assert!(parse_key("F0").is_err());
535        assert!(parse_key("F13").is_err());
536    }
537
538    // ── format_key tests ──
539
540    #[test]
541    fn format_ctrl_shift_s() {
542        let k = KeyCombo {
543            code: KeyCode::Char('s'),
544            modifiers: KeyModifiers::CONTROL | KeyModifiers::SHIFT,
545        };
546        assert_eq!(format_key(&k), "Ctrl+Shift+S");
547    }
548
549    #[test]
550    fn format_f5() {
551        let k = KeyCombo {
552            code: KeyCode::F(5),
553            modifiers: KeyModifiers::NONE,
554        };
555        assert_eq!(format_key(&k), "F5");
556    }
557
558    #[test]
559    fn format_alt_space() {
560        let k = KeyCombo {
561            code: KeyCode::Char(' '),
562            modifiers: KeyModifiers::ALT,
563        };
564        assert_eq!(format_key(&k), "Alt+Space");
565    }
566
567    // ── registry tests ──
568
569    #[test]
570    fn core_binds_are_reserved() {
571        let reg = KeybindRegistry::new();
572        // Ctrl+C should not match (it's core)
573        assert!(reg
574            .match_key(KeyCode::Char('c'), KeyModifiers::CONTROL)
575            .is_none());
576    }
577
578    #[test]
579    fn plugin_bind_matches() {
580        let mut reg = KeybindRegistry::new();
581        reg.register_plugin(
582            "test",
583            &[ManifestKeybind {
584                key: "C-S-s".to_string(),
585                action: "slash_command".to_string(),
586                command: Some("scholar".to_string()),
587                skill: None,
588                prompt: None,
589                script: None,
590                description: Some("Search papers".to_string()),
591            }],
592            std::path::Path::new("/tmp"),
593        );
594
595        let result = reg.match_key(
596            KeyCode::Char('s'),
597            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
598        );
599        assert!(result.is_some());
600        assert_eq!(result.unwrap().description, "Search papers");
601    }
602
603    #[test]
604    fn plugin_cannot_override_core() {
605        let mut reg = KeybindRegistry::new();
606        reg.register_plugin(
607            "evil",
608            &[ManifestKeybind {
609                key: "C-c".to_string(),
610                action: "inject_prompt".to_string(),
611                command: None,
612                skill: None,
613                prompt: Some("hacked".to_string()),
614                script: None,
615                description: Some("evil".to_string()),
616            }],
617            std::path::Path::new("/tmp"),
618        );
619
620        // Ctrl+C should still not match (core)
621        assert!(reg
622            .match_key(KeyCode::Char('c'), KeyModifiers::CONTROL)
623            .is_none());
624    }
625
626    #[test]
627    fn user_overrides_plugin() {
628        let mut reg = KeybindRegistry::new();
629        reg.register_plugin(
630            "test",
631            &[ManifestKeybind {
632                key: "F5".to_string(),
633                action: "slash_command".to_string(),
634                command: Some("scholar".to_string()),
635                skill: None,
636                prompt: None,
637                script: None,
638                description: Some("Scholar".to_string()),
639            }],
640            std::path::Path::new("/tmp"),
641        );
642
643        let mut overrides = std::collections::HashMap::new();
644        overrides.insert("F5".to_string(), "/compact".to_string());
645        reg.register_user(&overrides);
646
647        let result = reg.match_key(KeyCode::F(5), KeyModifiers::NONE);
648        assert!(result.is_some());
649        assert_eq!(result.unwrap().description, "User: /compact");
650    }
651
652    #[test]
653    fn user_can_disable_bind() {
654        let mut reg = KeybindRegistry::new();
655        reg.register_plugin(
656            "test",
657            &[ManifestKeybind {
658                key: "F5".to_string(),
659                action: "slash_command".to_string(),
660                command: Some("scholar".to_string()),
661                skill: None,
662                prompt: None,
663                script: None,
664                description: Some("Scholar".to_string()),
665            }],
666            std::path::Path::new("/tmp"),
667        );
668
669        let mut overrides = std::collections::HashMap::new();
670        overrides.insert("F5".to_string(), "disabled".to_string());
671        reg.register_user(&overrides);
672
673        let result = reg.match_key(KeyCode::F(5), KeyModifiers::NONE);
674        assert!(result.is_some());
675        assert!(matches!(result.unwrap().action, KeybindAction::Disabled));
676    }
677
678    #[test]
679    fn duplicate_plugin_binds_first_wins() {
680        let mut reg = KeybindRegistry::new();
681        reg.register_plugin(
682            "first",
683            &[ManifestKeybind {
684                key: "F5".to_string(),
685                action: "slash_command".to_string(),
686                command: Some("first".to_string()),
687                skill: None,
688                prompt: None,
689                script: None,
690                description: Some("First".to_string()),
691            }],
692            std::path::Path::new("/tmp"),
693        );
694
695        reg.register_plugin(
696            "second",
697            &[ManifestKeybind {
698                key: "F5".to_string(),
699                action: "slash_command".to_string(),
700                command: Some("second".to_string()),
701                skill: None,
702                prompt: None,
703                script: None,
704                description: Some("Second".to_string()),
705            }],
706            std::path::Path::new("/tmp"),
707        );
708
709        let result = reg.match_key(KeyCode::F(5), KeyModifiers::NONE);
710        assert!(result.is_some());
711        assert_eq!(result.unwrap().description, "First");
712    }
713
714    #[test]
715    fn custom_binds_excludes_core() {
716        let reg = KeybindRegistry::new();
717        let custom = reg.custom_binds();
718        assert!(custom.is_empty()); // No plugins registered = no custom binds
719    }
720
721    // ── collision recording (Phase 8 slice 8B.2) ──
722
723    fn mk_kb(key: &str, cmd: &str) -> ManifestKeybind {
724        ManifestKeybind {
725            key: key.to_string(),
726            action: "slash_command".to_string(),
727            command: Some(cmd.to_string()),
728            skill: None,
729            prompt: None,
730            script: None,
731            description: Some(cmd.to_string()),
732        }
733    }
734
735    /// 04-tui I7: Alt-↑/↓ switch subagent views (macOS takes Ctrl-↑/↓ for
736    /// Mission Control), so a plugin can't take them either.
737    #[test]
738    fn alt_arrows_are_reserved_for_subagent_views() {
739        let mut reg = KeybindRegistry::new();
740        reg.register_plugin(
741            "p",
742            &[mk_kb("A-Up", "x"), mk_kb("A-Down", "y")],
743            std::path::Path::new("/tmp"),
744        );
745        assert!(reg.match_key(KeyCode::Up, KeyModifiers::ALT).is_none());
746        assert!(reg.match_key(KeyCode::Down, KeyModifiers::ALT).is_none());
747        assert_eq!(reg.collisions().len(), 2);
748    }
749
750    #[test]
751    fn register_plugin_records_core_collision() {
752        let mut reg = KeybindRegistry::new();
753        // C-c is reserved by core (Quit).
754        reg.register_plugin(
755            "evil",
756            &[mk_kb("C-c", "hack")],
757            std::path::Path::new("/tmp"),
758        );
759        assert_eq!(reg.collisions().len(), 1);
760        let c = &reg.collisions()[0];
761        assert_eq!(c.losing_plugin, "evil");
762        assert_eq!(c.winning_owner, "core");
763        assert_eq!(c.reason, "conflicts with core");
764        assert_eq!(c.key, "C-c");
765    }
766
767    #[test]
768    fn register_plugin_records_plugin_vs_plugin_collision() {
769        let mut reg = KeybindRegistry::new();
770        // C-Space is not reserved by core.
771        reg.register_plugin(
772            "A",
773            &[mk_kb("C-Space", "alpha")],
774            std::path::Path::new("/tmp"),
775        );
776        reg.register_plugin(
777            "B",
778            &[mk_kb("C-Space", "beta")],
779            std::path::Path::new("/tmp"),
780        );
781        assert_eq!(reg.collisions().len(), 1);
782        let c = &reg.collisions()[0];
783        assert_eq!(c.losing_plugin, "B");
784        assert_eq!(c.winning_owner, "A");
785        assert_eq!(c.reason, "already registered");
786    }
787
788    #[test]
789    fn register_plugin_records_invalid_key_notation() {
790        let mut reg = KeybindRegistry::new();
791        reg.register_plugin(
792            "weird",
793            &[mk_kb("this is not a key", "noop")],
794            std::path::Path::new("/tmp"),
795        );
796        assert_eq!(reg.collisions().len(), 1);
797        let c = &reg.collisions()[0];
798        assert_eq!(c.losing_plugin, "weird");
799        assert_eq!(c.winning_owner, "n/a");
800        assert!(
801            c.reason.starts_with("invalid notation"),
802            "reason should start with 'invalid notation', got: {}",
803            c.reason
804        );
805    }
806
807    #[test]
808    fn collisions_is_empty_when_no_conflicts() {
809        let mut reg = KeybindRegistry::new();
810        reg.register_plugin("solo", &[mk_kb("F7", "solo")], std::path::Path::new("/tmp"));
811        assert!(reg.collisions().is_empty());
812    }
813
814    #[test]
815    fn multiple_collisions_are_all_recorded() {
816        let mut reg = KeybindRegistry::new();
817        reg.register_plugin(
818            "A",
819            &[mk_kb("C-Space", "alpha")],
820            std::path::Path::new("/tmp"),
821        );
822        // Two more plugins each colliding on the same key.
823        reg.register_plugin(
824            "B",
825            &[mk_kb("C-Space", "beta")],
826            std::path::Path::new("/tmp"),
827        );
828        reg.register_plugin(
829            "C",
830            &[mk_kb("C-Space", "gamma")],
831            std::path::Path::new("/tmp"),
832        );
833        assert_eq!(reg.collisions().len(), 2);
834        assert_eq!(reg.collisions()[0].losing_plugin, "B");
835        assert_eq!(reg.collisions()[1].losing_plugin, "C");
836        for c in reg.collisions() {
837            assert_eq!(c.winning_owner, "A");
838            assert_eq!(c.reason, "already registered");
839        }
840    }
841}