shuvarie 0.2.0

Blazingly fast AI coding TUI for chivalrous people
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
use ratatui::prelude::*;
use ratatui::widgets::{Block, Clear, ListItem, Padding};
use termina::event::{KeyCode, KeyEvent};

use crate::tui::utils::ctrl;

use super::commands::{
    CommandAction, CommandEntry, CommandRef, TRIGGER_CHARS, default_commands, is_escaped,
};
use super::list::{render_list_item_line, scroll_offset_for};
use super::search;
use super::theme;

/// Maximum rows visible in the tooltip before it scrolls.
pub const MAX_VISIBLE: usize = 6;

pub enum SlashMessage {
    Next,
    Prev,
    Complete,
    Run,
    Dismiss,
}

pub struct SlashMenu {
    commands: Vec<CommandEntry>,
    open: bool,
    trigger: char,
    filtered: Vec<usize>,
    selected: usize,
    offset: usize,
    dismissed: Option<char>,
}

impl SlashMenu {
    pub fn new() -> Self {
        Self {
            commands: default_commands(),
            open: false,
            trigger: '/',
            filtered: Vec::new(),
            selected: 0,
            offset: 0,
            dismissed: None,
        }
    }

    pub fn active(&self) -> bool {
        self.open && !self.filtered.is_empty()
    }

    pub fn trigger_char(&self) -> char {
        self.trigger
    }

    pub fn filtered_len(&self) -> usize {
        self.filtered.len()
    }

    /// Tooltip rect floating above the input area, clamped to the history
    /// pane so it never covers the title row or the input itself.
    pub fn popup_rect(&self, history: Rect, input: Rect) -> Rect {
        let visible = (self.filtered_len() as u16).min(MAX_VISIBLE as u16).max(1);
        let width = input.width.saturating_sub(4).clamp(20, 48);
        let height = (visible + 1).min(history.height.max(1));
        let y = input.y.saturating_sub(height).max(history.y);
        let height = input.y.saturating_sub(y);
        Rect::new(input.x + 2, y, width, height)
    }

    pub fn set_availability(&mut self, action: CommandAction, available: bool) {
        let action = CommandRef::Builtin(action);
        for cmd in &mut self.commands {
            if cmd.action == action {
                cmd.available = available;
            }
        }
    }

    /// Replace the custom-command suffix of the command list. Builtins keep
    /// their availability state; custom commands are always available and
    /// sort after the builtins in name order.
    pub fn set_custom_commands(&mut self, commands: &[shuvarie_core::CustomCommand]) {
        let builtins = default_commands().len();
        self.commands.truncate(builtins);
        self.commands
            .extend(commands.iter().map(CommandEntry::custom));
        if self.open {
            self.refilter("");
        }
    }

    /// Whether `action` is currently marked available.
    #[cfg(test)]
    pub fn available(&self, action: CommandAction) -> bool {
        self.commands
            .iter()
            .find(|cmd| cmd.action == CommandRef::Builtin(action))
            .is_some_and(|cmd| cmd.available)
    }

    /// Recompute open/filtered state from the current buffer text.
    pub fn sync(&mut self, buffer: &str) {
        match trigger_state(buffer) {
            Some((c, query)) => {
                if self.dismissed == Some(c) {
                    self.open = false;
                } else {
                    self.open = true;
                    self.trigger = c;
                    self.dismissed = None;
                    self.refilter(query);
                }
            }
            None => {
                self.open = false;
                self.dismissed = None;
            }
        }
    }

    pub fn dismiss(&mut self) {
        if self.open {
            self.dismissed = Some(self.trigger);
        }
    }

    fn refilter(&mut self, query: &str) {
        self.filtered = search::filter_indices(query, self.commands.len(), |i| {
            self.commands[i].action.slash_alias()
        })
        .into_iter()
        .filter(|&i| self.commands[i].available)
        .collect();
        self.selected = 0;
        self.offset = 0;
        self.recompute_offset();
    }

    fn viewport(&self) -> usize {
        self.filtered.len().min(MAX_VISIBLE)
    }

    pub fn next(&mut self) {
        if !self.filtered.is_empty() {
            self.selected = (self.selected + 1).min(self.filtered.len() - 1);
            self.recompute_offset();
        }
    }

    pub fn prev(&mut self) {
        if !self.filtered.is_empty() {
            self.selected = self.selected.saturating_sub(1);
            self.recompute_offset();
        }
    }

    fn recompute_offset(&mut self) {
        let vh = self.viewport();
        let len = self.filtered.len();
        self.offset = scroll_offset_for(self.selected, self.offset, vh, len);
    }

    pub fn selected_action(&self) -> Option<CommandRef> {
        let cmd_idx = self.filtered.get(self.selected)?;
        Some(self.commands[*cmd_idx].action.clone())
    }

    pub fn map_event(&self, key: &KeyEvent) -> Option<SlashMessage> {
        if ctrl(key) {
            return match key.code {
                KeyCode::Char('n') => Some(SlashMessage::Next),
                KeyCode::Char('p') => Some(SlashMessage::Prev),
                _ => None,
            };
        }
        match key.code {
            KeyCode::Tab => Some(SlashMessage::Complete),
            KeyCode::Up => Some(SlashMessage::Prev),
            KeyCode::Down => Some(SlashMessage::Next),
            KeyCode::Enter => Some(SlashMessage::Run),
            KeyCode::Escape => Some(SlashMessage::Dismiss),
            _ => None,
        }
    }

    pub fn view(&self, frame: &mut Frame<'_>, area: Rect) {
        if !self.active() || area.is_empty() {
            return;
        }
        frame.render_widget(Clear, area);
        let block = Block::new()
            .bg(theme::overlay())
            .padding(Padding::new(1, 1, 0, 1));
        let inner = block.inner(area);
        frame.render_widget(block, area);

        let offset = scroll_offset_for(
            self.selected,
            self.offset,
            inner.height as usize,
            self.filtered.len(),
        );
        let visible: Vec<ListItem> = self
            .filtered
            .iter()
            .enumerate()
            .skip(offset)
            .take(inner.height as usize)
            .map(|(idx, &i)| {
                let cmd = &self.commands[i];
                let line = Line::from(vec![
                    Span::raw(format!(
                        "{:<10}",
                        format!("{}{}", self.trigger, cmd.action.slash_alias())
                    ))
                    .fg(theme::accent())
                    .bold(),
                    Span::raw(cmd.description.to_string()).fg(theme::text_muted()),
                ]);
                render_list_item_line(line, idx == self.selected)
            })
            .collect();
        frame.render_widget(ratatui::widgets::List::new(visible), inner);
    }
}

/// `(trigger char, query)` when the buffer is a single `<trigger><query>`
/// token that is not escaped by a doubled prefix.
fn trigger_state(buffer: &str) -> Option<(char, &str)> {
    let first = buffer.chars().next()?;
    if !TRIGGER_CHARS.contains(&first) || is_escaped(buffer) {
        return None;
    }
    let query = &buffer[first.len_utf8()..];
    if query.chars().any(char::is_whitespace) {
        return None;
    }
    Some((first, query))
}

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

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

    fn actions(menu: &SlashMenu) -> Vec<CommandAction> {
        menu.filtered
            .iter()
            .filter_map(|&i| match &menu.commands[i].action {
                CommandRef::Builtin(action) => Some(*action),
                CommandRef::Custom { .. } => None,
            })
            .collect()
    }

    fn custom_names(menu: &SlashMenu) -> Vec<String> {
        menu.filtered
            .iter()
            .filter_map(|&i| match &menu.commands[i].action {
                CommandRef::Custom { name, .. } => Some(name.clone()),
                CommandRef::Builtin(_) => None,
            })
            .collect()
    }

    #[test]
    fn opens_on_trigger_prefix() {
        let mut menu = SlashMenu::new();
        menu.sync("/");
        assert!(menu.active());
        assert_eq!(actions(&menu).len(), CommandAction::ALL.len());
        menu.sync(":mo");
        assert!(menu.active());
        assert_eq!(menu.trigger, ':');
        assert!(actions(&menu).contains(&CommandAction::OpenModelSelect));
    }

    #[test]
    fn stays_closed_on_escaped_prefix() {
        let mut menu = SlashMenu::new();
        menu.sync("//");
        assert!(!menu.active());
        menu.sync("::x");
        assert!(!menu.active());
    }

    #[test]
    fn closes_on_whitespace_or_non_trigger() {
        let mut menu = SlashMenu::new();
        menu.sync("/mo");
        assert!(menu.active());
        menu.sync("/mo del");
        assert!(!menu.open);
        menu.sync("hi");
        assert!(!menu.open);
        menu.sync("");
        assert!(!menu.open);
    }

    #[test]
    fn esc_dismisses_until_trigger_cleared() {
        let mut menu = SlashMenu::new();
        menu.sync("/mo");
        assert!(menu.active());
        menu.dismiss();
        menu.sync("/mod");
        assert!(!menu.open, "dismissed state persists while typing");
        menu.sync("/m");
        assert!(!menu.open);
        menu.sync("hi");
        assert!(!menu.open);
        menu.sync("/");
        assert!(menu.active(), "clearing the trigger re-arms the menu");
        menu.sync(":n");
        assert!(menu.active(), "the other trigger opens the menu");
    }

    #[test]
    fn filters_by_query_and_availability() {
        let mut menu = SlashMenu::new();
        menu.set_availability(CommandAction::UndoLastTurn, false);
        menu.sync("/re");
        let acts = actions(&menu);
        assert!(acts.contains(&CommandAction::Replay));
        assert!(acts.contains(&CommandAction::Reload));
        menu.sync(":undo");
        assert!(
            actions(&menu).is_empty(),
            "unavailable commands stay hidden"
        );
        menu.set_availability(CommandAction::UndoLastTurn, true);
        menu.sync(":undo");
        assert!(actions(&menu).contains(&CommandAction::UndoLastTurn));
        menu.sync("/zzz");
        assert!(menu.filtered.is_empty());
        assert!(!menu.active());
    }

    #[test]
    fn selection_moves_and_wraps_clamped() {
        let mut menu = SlashMenu::new();
        menu.sync("/");
        menu.next();
        menu.next();
        assert_eq!(menu.selected, 2);
        menu.prev();
        assert_eq!(menu.selected, 1);
        for _ in 0..10 {
            menu.prev();
        }
        assert_eq!(menu.selected, 0);
        for _ in 0..20 {
            menu.next();
        }
        assert_eq!(menu.selected, menu.filtered.len() - 1);
    }

    #[test]
    fn selected_action_resolves() {
        let mut menu = SlashMenu::new();
        menu.sync(":se");
        assert_eq!(
            menu.selected_action(),
            Some(CommandRef::Builtin(CommandAction::OpenSessionPicker))
        );
    }

    #[test]
    fn custom_commands_append_after_builtins() {
        let mut menu = SlashMenu::new();
        menu.set_custom_commands(&[
            custom_command("commit", "Commit code", None),
            custom_command("model", "Fallback model", None),
        ]);
        menu.sync("/");
        // Builtins first (all still present), then the custom commands in
        // name order.
        assert_eq!(actions(&menu).len(), CommandAction::ALL.len());
        assert_eq!(custom_names(&menu), vec!["commit", "model"]);
        // Re-setting replaces (never duplicates) the custom suffix.
        menu.set_custom_commands(&[custom_command("review", "Review", None)]);
        menu.sync("/");
        assert_eq!(custom_names(&menu), vec!["review"]);
        assert_eq!(actions(&menu).len(), CommandAction::ALL.len());
    }

    #[test]
    fn custom_commands_survive_availability_updates() {
        let mut menu = SlashMenu::new();
        menu.set_custom_commands(&[custom_command("commit", "Commit code", None)]);
        menu.set_availability(CommandAction::Quit, false);
        menu.sync("/");
        assert_eq!(custom_names(&menu), vec!["commit"]);
        assert!(
            !actions(&menu).contains(&CommandAction::Quit),
            "builtin availability still applies"
        );
    }

    fn custom_command(
        name: &str,
        title: &str,
        model: Option<&str>,
    ) -> shuvarie_core::CustomCommand {
        shuvarie_core::CustomCommand {
            name: name.to_string(),
            title: title.to_string(),
            model: model.map(ToOwned::to_owned),
            path: std::path::PathBuf::from("/tmp"),
        }
    }
}