chabeau 0.7.3

A full-screen terminal chat interface that connects to various AI APIs for real-time conversations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Mode-aware keybinding registry system
//!
//! This module provides the core registry system for handling keybindings
//! in a mode-aware manner, including types, registry, and builder.

use crate::core::app::ui_state::UiMode;
use crate::core::app::AppActionDispatcher;
use crate::ui::chat_loop::{AppHandle, KeyLoopAction};
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::collections::HashMap;

// ============================================================================
// Types and Traits
// ============================================================================

/// Result of handling a key event
#[derive(Debug, Clone, PartialEq)]
pub enum KeyResult {
    /// Key was handled and should continue the loop
    Continue,
    /// Key was handled and should exit the loop
    Exit,
    /// Key was handled (generic)
    Handled,
    /// Key was not handled by this handler
    NotHandled,
}

impl From<KeyLoopAction> for KeyResult {
    fn from(action: KeyLoopAction) -> Self {
        match action {
            KeyLoopAction::Continue => KeyResult::Continue,
            KeyLoopAction::Break => KeyResult::Exit,
        }
    }
}

impl From<bool> for KeyResult {
    fn from(handled: bool) -> Self {
        if handled {
            KeyResult::Handled
        } else {
            KeyResult::NotHandled
        }
    }
}

/// Trait for keybinding handlers
#[async_trait::async_trait]
pub trait KeyHandler: Send + Sync {
    /// Handle a key event
    async fn handle(
        &self,
        app: &AppHandle,
        dispatcher: &AppActionDispatcher,
        key: &KeyEvent,
        term_width: u16,
        term_height: u16,
        last_input_layout_update: Option<std::time::Instant>,
    ) -> KeyResult;
}

/// Execution context shared across key handlers.
pub struct KeyExecutionContext<'a> {
    pub app: &'a AppHandle,
    pub dispatcher: &'a AppActionDispatcher,
}

/// Terminal/layout context for handling a single key event.
#[derive(Debug, Clone, Copy)]
pub struct KeyHandlingContext {
    pub term_width: u16,
    pub term_height: u16,
    pub last_input_layout_update: Option<std::time::Instant>,
}

/// Pattern for matching key events
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeyPattern {
    pub code: KeyCode,
    pub modifiers: KeyModifiers,
}

impl KeyPattern {
    pub fn simple(code: KeyCode) -> Self {
        Self {
            code,
            modifiers: KeyModifiers::NONE,
        }
    }

    pub fn ctrl(code: KeyCode) -> Self {
        Self {
            code,
            modifiers: KeyModifiers::CONTROL,
        }
    }

    pub fn with_modifiers(code: KeyCode, modifiers: KeyModifiers) -> Self {
        Self { code, modifiers }
    }

    /// Match any key (catch-all for mode-specific handlers)
    pub fn any() -> Self {
        Self {
            code: KeyCode::Null,          // Special marker for any key
            modifiers: KeyModifiers::ALT, // Use ALT as a marker for "any"
        }
    }

    pub fn matches(&self, key: &KeyEvent) -> bool {
        // Handle special patterns
        if self.code == KeyCode::Null && self.modifiers == KeyModifiers::ALT {
            // "any" pattern matches everything (for mode-specific catch-all handlers)
            return true;
        }

        // Normal exact pattern matching
        self.code == key.code && self.modifiers == key.modifiers
    }
}

impl From<&KeyEvent> for KeyPattern {
    fn from(key: &KeyEvent) -> Self {
        Self {
            code: key.code,
            modifiers: key.modifiers,
        }
    }
}

// ============================================================================
// Context and Registry
// ============================================================================

/// Context for mode-aware key handling
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum KeyContext {
    /// Normal typing mode
    Typing,
    /// Edit select mode (selecting messages to edit)
    EditSelect,
    /// Block select mode (selecting code blocks)
    BlockSelect,
    /// In-place edit mode
    InPlaceEdit,
    /// File prompt mode
    FilePrompt,
    /// Tool permission prompt mode
    ToolPrompt,
    /// MCP prompt argument input
    McpPromptInput,
    /// Picker is open (model/theme selection)
    Picker,
}

impl KeyContext {
    /// Convert from UiMode to KeyContext
    pub fn from_ui_mode(ui_mode: &UiMode, picker_open: bool) -> Self {
        if picker_open {
            return KeyContext::Picker;
        }

        match ui_mode {
            UiMode::Typing => KeyContext::Typing,
            UiMode::EditSelect { .. } => KeyContext::EditSelect,
            UiMode::BlockSelect { .. } => KeyContext::BlockSelect,
            UiMode::InPlaceEdit { .. } => KeyContext::InPlaceEdit,
            UiMode::FilePrompt(_) => KeyContext::FilePrompt,
            UiMode::ToolPrompt(_) => KeyContext::ToolPrompt,
            UiMode::McpPromptInput(_) => KeyContext::McpPromptInput,
        }
    }
}

/// Mode-aware keybinding registry
pub struct ModeAwareRegistry {
    /// Handlers organized by context and key pattern
    handlers: HashMap<KeyContext, HashMap<KeyPattern, Box<dyn KeyHandler>>>,
}

impl ModeAwareRegistry {
    pub fn new() -> Self {
        Self {
            handlers: HashMap::new(),
        }
    }

    /// Register a handler for a specific context
    pub fn register_for_context(
        &mut self,
        context: KeyContext,
        pattern: KeyPattern,
        handler: Box<dyn KeyHandler>,
    ) {
        self.handlers
            .entry(context)
            .or_default()
            .insert(pattern, handler);
    }

    /// Check if a key should be handled as text input (bypass registry)
    pub fn should_handle_as_text_input(&self, key: &KeyEvent, context: &KeyContext) -> bool {
        match context {
            KeyContext::Typing => {
                // In typing mode, only character keys are text input
                if let KeyCode::Char(c) = key.code {
                    // System shortcuts should not be treated as text input
                    if key.modifiers.contains(KeyModifiers::CONTROL) {
                        // These have dedicated handlers
                        return !matches!(
                            c,
                            'c' | 'l'
                                | 'd'
                                | 'b'
                                | 'p'
                                | 'j'
                                | 'r'
                                | 't'
                                | 'a'
                                | 'e'
                                | 'n'
                                | 'o'
                                | 'x'
                        );
                    }
                    // All other character input (regular chars, Shift+chars, Alt+chars, etc.)
                    return true;
                }
                false
            }
            KeyContext::ToolPrompt => false,
            KeyContext::McpPromptInput => {
                // Treat MCP prompt input like file prompt input.
                match key.code {
                    KeyCode::Esc => false,
                    KeyCode::Enter => false,
                    KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => !matches!(
                        c,
                        'b' | 'p' | 'j' | 'r' | 't' | 'c' | 'l' | 'd' | 'n' | 'o' | 'x'
                    ),
                    KeyCode::F(4) => false,
                    _ if key.modifiers.contains(KeyModifiers::ALT)
                        && key.code == KeyCode::Enter =>
                    {
                        false
                    }
                    _ => true,
                }
            }
            KeyContext::InPlaceEdit => {
                // In in-place edit mode, keep navigation keys routed through handlers
                match key.code {
                    // Navigation keys need custom wrapping logic
                    KeyCode::Left
                    | KeyCode::Right
                    | KeyCode::Up
                    | KeyCode::Down
                    | KeyCode::Home
                    | KeyCode::End
                    | KeyCode::PageUp
                    | KeyCode::PageDown => false,
                    KeyCode::Esc => false,
                    KeyCode::Enter => false,
                    KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => !matches!(
                        c,
                        'b' | 'p' | 'j' | 'r' | 't' | 'c' | 'l' | 'd' | 'n' | 'o' | 'x'
                    ),
                    KeyCode::F(4) => false,
                    _ if key.modifiers.contains(KeyModifiers::ALT)
                        && key.code == KeyCode::Enter =>
                    {
                        false
                    }
                    _ => true,
                }
            }
            KeyContext::FilePrompt => {
                // In file prompt mode, let tui-textarea handle most keys
                match key.code {
                    KeyCode::Esc => false,
                    KeyCode::Enter => false,
                    KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        !matches!(c, 'b' | 'p' | 'j' | 'r' | 't' | 'c' | 'l' | 'd' | 'n' | 'x')
                    }
                    KeyCode::F(4) => false,
                    _ if key.modifiers.contains(KeyModifiers::ALT)
                        && key.code == KeyCode::Enter =>
                    {
                        false
                    }
                    _ => true,
                }
            }
            _ => false,
        }
    }

    /// Handle a key event in the given context
    pub async fn handle_key_event(
        &self,
        key: &KeyEvent,
        context: KeyContext,
        execution: KeyExecutionContext<'_>,
        handling: KeyHandlingContext,
    ) -> ModeAwareResult {
        // First try context-specific handlers (they have priority)
        if let Some(context_handlers) = self.handlers.get(&context) {
            // First pass: try exact matches (non-wildcard patterns)
            for (pattern, handler) in context_handlers {
                if pattern.matches(key) && !is_wildcard_pattern(pattern) {
                    let result = handler
                        .handle(
                            execution.app,
                            execution.dispatcher,
                            key,
                            handling.term_width,
                            handling.term_height,
                            handling.last_input_layout_update,
                        )
                        .await;
                    // Only return if the handler actually handled the key
                    if result != KeyResult::NotHandled {
                        return ModeAwareResult {
                            result,
                            updated_layout_time: handling.last_input_layout_update,
                        };
                    }
                }
            }

            // Second pass: try wildcard patterns (any(), any_char())
            for (pattern, handler) in context_handlers {
                if pattern.matches(key) && is_wildcard_pattern(pattern) {
                    let result = handler
                        .handle(
                            execution.app,
                            execution.dispatcher,
                            key,
                            handling.term_width,
                            handling.term_height,
                            handling.last_input_layout_update,
                        )
                        .await;
                    // Only return if the handler actually handled the key
                    if result != KeyResult::NotHandled {
                        return ModeAwareResult {
                            result,
                            updated_layout_time: handling.last_input_layout_update,
                        };
                    }
                    // If handler returned NotHandled, continue to try other handlers
                }
            }
        }

        ModeAwareResult {
            result: KeyResult::NotHandled,
            updated_layout_time: None,
        }
    }
}

/// Result from mode-aware key handling
pub struct ModeAwareResult {
    pub result: KeyResult,
    pub updated_layout_time: Option<std::time::Instant>,
}

/// Helper function to detect wildcard patterns that should have lower priority
fn is_wildcard_pattern(pattern: &KeyPattern) -> bool {
    // Wildcard patterns use KeyCode::Null as a marker
    pattern.code == KeyCode::Null
}

impl Default for ModeAwareRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Builder
// ============================================================================

/// Builder for creating a fully configured mode-aware registry
pub struct ModeAwareBuilder {
    registry: ModeAwareRegistry,
}

impl ModeAwareBuilder {
    pub fn new() -> Self {
        Self {
            registry: ModeAwareRegistry::new(),
        }
    }

    /// Build the final registry
    pub fn build(self) -> ModeAwareRegistry {
        self.registry
    }

    /// Register a handler for a specific context
    pub fn register_for_context(
        mut self,
        context: KeyContext,
        pattern: KeyPattern,
        handler: Box<dyn KeyHandler>,
    ) -> Self {
        self.registry
            .register_for_context(context, pattern, handler);
        self
    }
}

impl Default for ModeAwareBuilder {
    fn default() -> Self {
        Self::new()
    }
}