agent-core-tui 0.6.0

TUI frontend for agent-core - ratatui-based terminal interface
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Slash command popup widget and state
//!
//! Displays an interactive popup when the user types `/` in the input box.
//! Shows filtered commands with keyboard navigation.
//!
//! This is a generic implementation - applications provide their own command
//! definitions via the SlashCommand trait.

use ratatui::{
    layout::Rect,
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
    Frame,
};

use crate::themes::Theme;

/// Default configuration values for SlashPopup
pub mod defaults {
    /// Header text shown at top of popup
    pub const HEADER_TEXT: &str = " Slash command mode \u{2014} Use arrow keys to select, Enter to execute, Esc to cancel";
    /// Message when no commands match
    pub const NO_MATCHES_MESSAGE: &str = " No matching commands";
    /// Command prefix (the slash)
    pub const COMMAND_PREFIX: &str = " /";
    /// Description indent
    pub const DESCRIPTION_INDENT: &str = " ";
}

/// Configuration for SlashPopup widget
#[derive(Clone)]
pub struct SlashPopupConfig {
    /// Header text shown at top of popup
    pub header_text: String,
    /// Message when no commands match the filter
    pub no_matches_message: String,
    /// Prefix shown before command names
    pub command_prefix: String,
    /// Indent for description lines
    pub description_indent: String,
}

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

impl SlashPopupConfig {
    /// Create a new SlashPopupConfig with default values
    pub fn new() -> Self {
        Self {
            header_text: defaults::HEADER_TEXT.to_string(),
            no_matches_message: defaults::NO_MATCHES_MESSAGE.to_string(),
            command_prefix: defaults::COMMAND_PREFIX.to_string(),
            description_indent: defaults::DESCRIPTION_INDENT.to_string(),
        }
    }

    /// Set the header text
    pub fn with_header_text(mut self, text: impl Into<String>) -> Self {
        self.header_text = text.into();
        self
    }

    /// Set the no matches message
    pub fn with_no_matches_message(mut self, message: impl Into<String>) -> Self {
        self.no_matches_message = message.into();
        self
    }

    /// Set the command prefix
    pub fn with_command_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.command_prefix = prefix.into();
        self
    }
}

/// Trait for displaying slash commands in the popup.
///
/// This is a simple trait that just requires name and description.
/// The full `SlashCommand` trait from `commands` module extends this.
pub trait SlashCommandDisplay {
    /// The command name (without the leading /)
    fn name(&self) -> &str;

    /// A short description of what the command does
    fn description(&self) -> &str;
}

// Blanket impl: any commands::SlashCommand also implements SlashCommandDisplay
impl<T: crate::commands::SlashCommand + ?Sized> SlashCommandDisplay for T {
    fn name(&self) -> &str {
        crate::commands::SlashCommand::name(self)
    }

    fn description(&self) -> &str {
        crate::commands::SlashCommand::description(self)
    }
}

// Impl for references to dyn SlashCommand
impl SlashCommandDisplay for &dyn crate::commands::SlashCommand {
    fn name(&self) -> &str {
        crate::commands::SlashCommand::name(*self)
    }

    fn description(&self) -> &str {
        crate::commands::SlashCommand::description(*self)
    }
}

/// State for the slash command popup
pub struct SlashPopupState {
    /// Whether the popup is currently visible
    pub active: bool,
    /// Index of the currently selected command
    pub selected_index: usize,
    /// Number of filtered commands (for bounds checking)
    filtered_count: usize,
    /// Configuration for display customization
    config: SlashPopupConfig,
}

impl SlashPopupState {
    /// Create a new slash popup with default configuration.
    pub fn new() -> Self {
        Self::with_config(SlashPopupConfig::new())
    }

    /// Create a new slash popup with custom configuration
    pub fn with_config(config: SlashPopupConfig) -> Self {
        Self {
            active: false,
            selected_index: 0,
            filtered_count: 0,
            config,
        }
    }

    /// Get the current configuration
    pub fn config(&self) -> &SlashPopupConfig {
        &self.config
    }

    /// Set a new configuration
    pub fn set_config(&mut self, config: SlashPopupConfig) {
        self.config = config;
    }

    /// Activate popup and reset state
    pub fn activate(&mut self) {
        self.active = true;
        self.selected_index = 0;
    }

    /// Deactivate popup
    pub fn deactivate(&mut self) {
        self.active = false;
        self.selected_index = 0;
        self.filtered_count = 0;
    }

    /// Update the filtered command count and clamp selection
    pub fn set_filtered_count(&mut self, count: usize) {
        self.filtered_count = count;
        if count > 0 {
            self.selected_index = self.selected_index.min(count - 1);
        } else {
            self.selected_index = 0;
        }
    }

    /// Move selection up (with wrap)
    pub fn select_previous(&mut self) {
        if self.filtered_count == 0 {
            return;
        }
        if self.selected_index == 0 {
            self.selected_index = self.filtered_count - 1;
        } else {
            self.selected_index -= 1;
        }
    }

    /// Move selection down (with wrap)
    pub fn select_next(&mut self) {
        if self.filtered_count == 0 {
            return;
        }
        self.selected_index = (self.selected_index + 1) % self.filtered_count;
    }

    /// Get the currently selected index
    pub fn selected_index(&self) -> usize {
        self.selected_index
    }

    /// Calculate the popup height based on filtered commands
    pub fn popup_height(&self, max_height: u16) -> u16 {
        let filtered_count = self.filtered_count.max(1);
        // header(1) + blank(1) + commands * 3 lines each + border(2)
        let content_height = 2 + (filtered_count * 3) + 2;
        (content_height as u16).min(max_height.saturating_sub(10))
    }
}

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

// --- Widget trait implementation ---

use std::any::Any;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::{widget_ids, Widget, WidgetAction, WidgetKeyContext, WidgetKeyResult};

/// Result of handling a key event in the slash popup
#[derive(Debug, Clone, PartialEq)]
pub enum SlashKeyAction {
    /// No action taken
    None,
    /// Navigation (up/down) handled
    Navigated,
    /// Command selected at given index
    Selected(usize),
    /// Popup was cancelled
    Cancelled,
    /// Character typed (for filtering) - not consumed, App should handle
    CharTyped(char),
    /// Backspace pressed - not consumed, App should handle
    Backspace,
}

impl SlashPopupState {
    /// Handle a key event
    ///
    /// Returns the action. For CharTyped and Backspace, the App needs to
    /// update the input buffer and filtered commands.
    pub fn process_key(&mut self, key: KeyEvent) -> SlashKeyAction {
        if !self.active {
            return SlashKeyAction::None;
        }

        match key.code {
            KeyCode::Up => {
                self.select_previous();
                SlashKeyAction::Navigated
            }
            KeyCode::Down => {
                self.select_next();
                SlashKeyAction::Navigated
            }
            KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.select_previous();
                SlashKeyAction::Navigated
            }
            KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.select_next();
                SlashKeyAction::Navigated
            }
            KeyCode::Enter => {
                let idx = self.selected_index;
                SlashKeyAction::Selected(idx)
            }
            KeyCode::Esc => {
                self.deactivate();
                SlashKeyAction::Cancelled
            }
            KeyCode::Backspace => SlashKeyAction::Backspace,
            KeyCode::Char(c) => SlashKeyAction::CharTyped(c),
            _ => {
                self.deactivate();
                SlashKeyAction::Cancelled
            }
        }
    }
}

impl Widget for SlashPopupState {
    fn id(&self) -> &'static str {
        widget_ids::SLASH_POPUP
    }

    fn priority(&self) -> u8 {
        150 // Medium-high priority
    }

    fn is_active(&self) -> bool {
        self.active
    }

    fn handle_key(&mut self, key: KeyEvent, ctx: &WidgetKeyContext) -> WidgetKeyResult {
        if !self.active {
            return WidgetKeyResult::NotHandled;
        }

        // Use NavigationHelper for key bindings
        if ctx.nav.is_move_up(&key) {
            self.select_previous();
            return WidgetKeyResult::Handled;
        }
        if ctx.nav.is_move_down(&key) {
            self.select_next();
            return WidgetKeyResult::Handled;
        }
        if ctx.nav.is_select(&key) {
            let idx = self.selected_index;
            return WidgetKeyResult::Action(WidgetAction::ExecuteCommand {
                command: format!("__SLASH_INDEX_{}", idx),
            });
        }
        if ctx.nav.is_cancel(&key) {
            self.deactivate();
            return WidgetKeyResult::Action(WidgetAction::Close);
        }

        // Handle special keys not covered by nav helper
        match key.code {
            KeyCode::Backspace => WidgetKeyResult::NotHandled,
            KeyCode::Char(_) => WidgetKeyResult::NotHandled,
            _ => {
                // Unknown key - cancel the popup
                self.deactivate();
                WidgetKeyResult::Action(WidgetAction::Close)
            }
        }
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) {
        // Note: This is a simplified render that doesn't have commands.
        // App should use render_slash_popup directly with filtered commands.
        // This default render shows an empty state.
        if self.active {
            render_slash_popup(self, &[] as &[SimpleCommand], frame, area, theme);
        }
    }

    fn required_height(&self, max_height: u16) -> u16 {
        if self.active {
            self.popup_height(max_height)
        } else {
            0
        }
    }

    fn blocks_input(&self) -> bool {
        self.active // Block input when popup is active so keys reach the widget
    }

    fn is_overlay(&self) -> bool {
        false // Renders in dedicated area
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

/// Render the slash command popup
///
/// # Arguments
/// * `state` - The popup state
/// * `commands` - The filtered list of commands to display
/// * `frame` - The ratatui frame
/// * `area` - The area to render in
/// * `theme` - The theme to use
pub fn render_slash_popup<C: SlashCommandDisplay>(
    state: &SlashPopupState,
    commands: &[C],
    frame: &mut Frame,
    area: Rect,
    theme: &Theme,
) {
    if !state.active {
        return;
    }

    // Calculate available width inside borders (area width - 2 for left/right borders)
    let inner_width = area.width.saturating_sub(2) as usize;

    // Build lines: header + commands (all with leading space for padding)
    let mut lines = Vec::new();

    // Header line with leading space
    lines.push(Line::from(vec![Span::styled(
        state.config.header_text.clone(),
        theme.popup_header(),
    )]));
    lines.push(Line::from("")); // Blank line after header

    // Command list
    for (idx, cmd) in commands.iter().enumerate() {
        let is_selected = idx == state.selected_index;

        // Command name line with leading space, padded to full width for selected
        let name_text = format!("{}{}", state.config.command_prefix, cmd.name());
        let name_style = if is_selected {
            theme.popup_selected_bg().patch(theme.popup_item_selected())
        } else {
            theme.popup_item()
        };
        if is_selected {
            // Pad to full width for full-row highlight
            let padded = format!("{:<width$}", name_text, width = inner_width);
            lines.push(Line::from(Span::styled(padded, name_style)));
        } else {
            lines.push(Line::from(Span::styled(name_text, name_style)));
        }

        // Description line with leading space, padded to full width for selected
        let desc_text = format!("{}{}", state.config.description_indent, cmd.description());
        let desc_style = if is_selected {
            theme.popup_selected_bg().patch(theme.popup_item_desc_selected())
        } else {
            theme.popup_item_desc()
        };
        if is_selected {
            // Pad to full width for full-row highlight
            let padded = format!("{:<width$}", desc_text, width = inner_width);
            lines.push(Line::from(Span::styled(padded, desc_style)));
        } else {
            lines.push(Line::from(Span::styled(desc_text, desc_style)));
        }

        // Blank line between commands (except last)
        if idx < commands.len() - 1 {
            lines.push(Line::from(""));
        }
    }

    // If no matches, show empty message
    if commands.is_empty() {
        lines.push(Line::from(Span::styled(
            state.config.no_matches_message.clone(),
            theme.popup_empty(),
        )));
    }

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme.popup_border());

    // Clear the area first (for overlay effect)
    frame.render_widget(Clear, area);

    let popup = Paragraph::new(lines).block(block);
    frame.render_widget(popup, area);
}

/// A simple command implementation for testing
#[derive(Clone)]
pub struct SimpleCommand {
    name: String,
    description: String,
}

impl SimpleCommand {
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
        }
    }
}

impl SlashCommandDisplay for SimpleCommand {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_popup_state_navigation() {
        let mut state = SlashPopupState::new();
        state.activate();
        state.set_filtered_count(3);

        assert_eq!(state.selected_index, 0);

        state.select_next();
        assert_eq!(state.selected_index, 1);

        state.select_next();
        assert_eq!(state.selected_index, 2);

        // Wrap around
        state.select_next();
        assert_eq!(state.selected_index, 0);

        // Wrap backward
        state.select_previous();
        assert_eq!(state.selected_index, 2);
    }

    #[test]
    fn test_popup_state_empty() {
        let mut state = SlashPopupState::new();
        state.activate();
        state.set_filtered_count(0);

        // Should not crash on empty list
        state.select_next();
        state.select_previous();
        assert_eq!(state.selected_index, 0);
    }

    #[test]
    fn test_simple_command() {
        let cmd = SimpleCommand::new("help", "Show help message");
        assert_eq!(cmd.name(), "help");
        assert_eq!(cmd.description(), "Show help message");
    }
}