shuvarie 0.2.2

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
use std::io::{self, Write};
use std::time::{Duration, Instant};

use futures_util::StreamExt;
use ratatui::prelude::*;
use termina::{
    EventReader, EventStream, PlatformTerminal, Terminal,
    escape::csi::{Csi, Keyboard},
    event::Event as TerminalEvent,
};
use tokio::sync::mpsc::{Receiver, Sender};

use shuvarie_core::{Command, Config, Connections, Event as CoreEvent, ThemeSet};

use crate::tui::event::Event;

use self::app::{App, AppEffect, AppMessage};

pub mod add_provider;
mod app;
mod auth;
mod command_menu;
mod commands;
mod components;
mod confirm_quit;
mod context;
mod escape;
mod event;
mod history_search;
mod list;
mod model_picker;
mod permission;
mod question;
mod registry;
mod scene;
mod search;
mod session;
mod session_picker;
mod sidebar;
mod slash;
mod spinner;
mod theme;
mod title;
pub mod trust;
mod utils;
mod variant;
mod warning;
mod welcome;
mod workspace;

pub enum TuiResponse {
    SessionSaved { session_id: uuid::Uuid },
}

pub async fn run_tui(
    config: Config,
    theme_set: ThemeSet,
    cmd_tx: Sender<Command>,
    event_rx: Receiver<CoreEvent>,
) -> io::Result<Option<TuiResponse>> {
    let mut term = PlatformTerminal::new()?;
    term.enter_raw_mode()?;

    let reader = term.event_reader();
    let theme = theme_set.resolve(
        config.ui.theme.as_deref(),
        self::theme::detect_variant(&mut term, &reader),
    );
    let event_stream = EventStream::new(reader.clone(), |_| true);

    let initial_cols = term.get_dimensions()?.cols;
    let frame_budget = frame_budget(config.ui.frame_rate);
    let mut rat = ratatui::Terminal::new(TerminaBackend::new(term))?;
    let connections = Connections::load().map_err(|e| io::Error::other(e.to_string()))?;
    let workspace = workspace::WorkspaceInfo::detect();
    let app = App::new(
        config.ui,
        theme,
        config.registries.selune(),
        connections,
        cmd_tx,
        initial_cols,
        workspace,
    );

    init_terminal(rat.backend_mut().terminal_mut())?;

    // Decide how modified keys reach the TUI before the render loop starts
    // consuming events: the probe shares the reader, so any keystrokes typed
    // during the wait stay buffered and are delivered by the stream later.
    let modify_other_keys = probe_keyboard_protocol(rat.backend_mut().terminal_mut(), &reader)?;

    let session_id = render_tui(app, &mut rat, event_rx, event_stream, frame_budget).await;

    let deinit = deinit_terminal(rat.backend_mut().terminal_mut(), modify_other_keys);
    let session_id = session_id?;
    deinit?;

    if let Some(session_id) = session_id {
        return Ok(Some(TuiResponse::SessionSaved { session_id }));
    }

    Ok(None)
}

/// Minimum interval between frames. `None` disables the cap (one draw per
/// event, the original behavior).
fn frame_budget(frame_rate: u32) -> Option<Duration> {
    if frame_rate == 0 {
        None
    } else {
        Some(Duration::from_secs_f64(1.0 / frame_rate as f64))
    }
}

/// Helper function for rendering TUI and handling errors.
///
/// All events flow through one scheduler: each wake applies the event (core
/// events are drained as a batch) and then either draws — when the frame
/// budget has elapsed — or arms a deadline at `last_draw + budget` so further
/// events coalesce into the pending frame. Terminal input outranks core
/// events, and input latency is bounded by one frame budget.
async fn render_tui(
    mut app: App,
    rat: &mut ratatui::Terminal<TerminaBackend<PlatformTerminal>>,
    mut event_rx: Receiver<CoreEvent>,
    mut event_stream: EventStream,
    frame_budget: Option<Duration>,
) -> io::Result<Option<uuid::Uuid>>
where
    io::Error: From<<TerminaBackend<PlatformTerminal> as Backend>::Error>,
{
    let mut last_draw: Instant;
    // A pending frame deadline armed when an event arrived too soon after
    // the last draw. `None` means no frame is pending.
    let mut frame_deadline: Option<tokio::time::Instant> = None;
    // Last tab title written to the terminal. Starts empty so the first
    // iteration writes the initial title.
    let mut last_title = String::new();
    // Drives spinner animation: wakes at the earliest next frame change
    // across the spinners currently animating. `None` when none are. Armed
    // after each draw, before it is ever read.
    let mut spinner_wake;
    // Session picker list refresh: while the picker is open the list is
    // re-fetched periodically so lock states stay live.
    let mut picker_wake;
    const PICKER_REFRESH: Duration = Duration::from_secs(2);

    'render_loop: loop {
        sync_window_title(
            rat.backend_mut().terminal_mut(),
            &mut last_title,
            &app.window_title(),
        )?;

        // Draw frame.
        rat.draw(|frame| app.view(frame, frame.area()))?;
        last_draw = Instant::now();

        // Spinners advance on wall-clock time, so waking at each earliest
        // frame boundary keeps every spinner at its own frame rate.
        spinner_wake = spinner::next_wake(app.active_spinners())
            .map(|until| tokio::time::Instant::now() + until);
        picker_wake = app
            .session_picker
            .open
            .then(|| tokio::time::Instant::now() + PICKER_REFRESH);

        'event_listening: loop {
            let changed = tokio::select! {
                // Flush the armed frame timer: a coalesced frame is due.
                // The `if` guard only disables polling — the future
                // expression is still evaluated, so handle `None` here.
                _ = async {
                    if let Some(deadline) = frame_deadline {
                        tokio::time::sleep_until(deadline).await;
                    } else {
                        std::future::pending::<()>().await;
                    }
                }, if frame_deadline.is_some() => {
                    // Deadline elapsed — draw the coalesced frame.
                    frame_deadline = None;
                    break 'event_listening;
                }
                // Spinner wake: redraw when the next in-progress frame is
                // due. The `if` guard only disables polling — the future
                // expression is still evaluated, so handle `None` here.
                _ = async {
                    if let Some(deadline) = spinner_wake {
                        tokio::time::sleep_until(deadline).await;
                    } else {
                        std::future::pending::<()>().await;
                    }
                }, if spinner_wake.is_some() => {
                    // Consumed; re-armed from the current state after the
                    // next draw. The wake becomes a message so the animated
                    // models refresh through their `update` paths.
                    spinner_wake = None;
                    apply_msg(
                        &mut app,
                        rat.backend_mut().terminal_mut(),
                        Some(AppMessage::SpinnerUpdate),
                    )
                }
                _ = async {
                    if let Some(deadline) = picker_wake {
                        tokio::time::sleep_until(deadline).await;
                    } else {
                        std::future::pending::<()>().await;
                    }
                }, if picker_wake.is_some() => {
                    picker_wake = Some(tokio::time::Instant::now() + PICKER_REFRESH);
                    apply_msg(
                        &mut app,
                        rat.backend_mut().terminal_mut(),
                        Some(AppMessage::PickerRefresh),
                    )
                }
                // Terminal event — draws under the same frame budget as core
                // events; when idle the budget has already elapsed, so keys
                // still render immediately.
                ev = event_stream.next() => {
                    let Some(ev_result) = ev else { break 'render_loop Ok(app.session.session_id); };
                    let msg = app.map_event(Event::Terminal(ev_result?));
                    apply_msg(&mut app, rat.backend_mut().terminal_mut(), msg)
                }
                // Core event — drain all already-queued core events as one batch.
                ev = event_rx.recv() => {
                    let Some(ev) = ev else { break 'render_loop Ok(app.session.session_id); };
                    let msg = app.map_event(Event::Core(ev));
                    apply_msg(&mut app, rat.backend_mut().terminal_mut(), msg)
                }
            };

            if app.quit_requested() {
                break 'render_loop Ok(app.session.session_id);
            }

            if !changed {
                // Nothing changed — keep listening without redrawing.
                continue;
            }

            // One draw decision for every event kind.
            match frame_budget {
                None => {
                    // No cap — draw every state change.
                    frame_deadline = None;
                    break 'event_listening;
                }
                Some(budget) => {
                    if last_draw.elapsed() >= budget {
                        // Budget satisfied — draw now.
                        frame_deadline = None;
                        break 'event_listening;
                    }
                    // Arm a deadline at the earliest frame the budget allows
                    // and keep coalescing events until it fires. The deadline
                    // anchors on the last draw, so re-arming during a burst
                    // never pushes it later.
                    frame_deadline = Some(tokio::time::Instant::from_std(last_draw + budget));
                }
            }
        }
    }
}

/// Apply a mapped message, recording a quit request on `AppEffect::Quit`,
/// writing `AppEffect::CopyToClipboard` as OSC 52 (the render loop owns the
/// terminal), and launching the browser for `AppEffect::OpenBrowser`.
fn apply_msg(app: &mut App, terminal: &mut PlatformTerminal, msg: Option<AppMessage>) -> bool {
    if let Some(msg) = msg {
        match app.update(msg) {
            Some(AppEffect::Quit) => app.mark_quit(),
            Some(AppEffect::CopyToClipboard(text)) => {
                let _ = write!(terminal, "{}", escape::set_clipboard(&text));
                let _ = terminal.flush();
            }
            Some(AppEffect::OpenBrowser(url)) => auth::open_in_browser(&url),
            None => {}
        }
        true
    } else {
        false
    }
}

/// Write the OSC 2 tab title escape when the desired title differs from the
/// last written one. The render loop owns the terminal, so app-driven title
/// changes are applied here rather than from `update`.
fn sync_window_title<W: io::Write>(
    terminal: &mut W,
    last: &mut String,
    title: &str,
) -> io::Result<()> {
    if *last != title {
        write!(terminal, "{}", escape::set_window_title(title))?;
        terminal.flush()?;
        last.clear();
        last.push_str(title);
    }
    Ok(())
}

fn init_terminal(terminal: &mut PlatformTerminal) -> io::Result<()> {
    write!(
        terminal,
        "{}{}{}{}{}{}",
        escape::ENTER_ALTERNATE_SCREEN,
        escape::ENABLE_MOUSE,
        escape::ENABLE_SGR_MOUSE,
        escape::ENABLE_KITTY_KEYBOARD,
        escape::ENABLE_BRACKETED_PASTE,
        escape::push_window_title()
    )?;
    terminal.flush()?;
    Ok(())
}

fn deinit_terminal(
    terminal: &mut PlatformTerminal,
    reset_modify_other_keys: bool,
) -> io::Result<()> {
    write!(
        terminal,
        "{}{}{}{}{}{}{}",
        escape::DISABLE_KITTY_KEYBOARD,
        if reset_modify_other_keys {
            escape::RESET_MODIFY_OTHER_KEYS
        } else {
            ""
        },
        escape::DISABLE_SGR_MOUSE,
        escape::DISABLE_MOUSE,
        escape::DISABLE_BRACKETED_PASTE,
        escape::EXIT_ALTERNATE_SCREEN,
        escape::pop_window_title()
    )?;
    terminal.flush()?;
    Ok(())
}

/// Time to wait for a kitty keyboard protocol query answer before treating the
/// terminal as not speaking the protocol.
const PROBE_TIMEOUT: Duration = Duration::from_millis(250);

/// Decide how modified keys reach the TUI.
///
/// `init_terminal` pushes kitty keyboard protocol flags, which real
/// kitty-protocol terminals honor: they answer the `CSI ? u` query below and
/// send modified keys as CSI-u sequences (e.g. Shift+Enter as `\x1b[13;2u`),
/// which termina parses into modifier-carrying key events.
///
/// tmux does not implement the kitty protocol toward panes: it silently
/// ignores both the flag push and the query, and without help it strips the
/// modifiers from keys that have no legacy encoding — Shift+Enter arrives as
/// plain `\r`, indistinguishable from Enter. A silent terminal therefore gets
/// an xterm `modifyOtherKeys=1` request (`CSI > 4;1m`); tmux tracks it and
/// starts forwarding modified keys as CSI-u (its `extended-keys` and
/// `extended-keys-format csi-u` options, on by default since tmux 3.5).
///
/// Returns `true` when the kitty protocol is available and `false` when the
/// modifyOtherKeys fallback was requested, so `deinit_terminal` can reset it.
fn probe_keyboard_protocol(term: &mut PlatformTerminal, reader: &EventReader) -> io::Result<bool> {
    write!(term, "{}", escape::QUERY_KITTY_FLAGS)?;
    term.flush()?;
    if let Ok(true) = reader.poll(Some(PROBE_TIMEOUT), kitty_flags_report) {
        // Consume the report so it never surfaces as a stray CSI event;
        // keystrokes typed during the wait stay buffered for the stream.
        let _ = reader.read(kitty_flags_report)?;
        return Ok(true);
    }
    write!(term, "{}", escape::REQUEST_MODIFY_OTHER_KEYS)?;
    term.flush()?;
    Ok(false)
}

/// Matches the kitty keyboard flags report (`CSI ? flags u`). Non-matching
/// events are retained by the reader for later consumers.
fn kitty_flags_report(event: &TerminalEvent) -> bool {
    matches!(
        event,
        TerminalEvent::Csi(Csi::Keyboard(Keyboard::ReportFlags(_)))
    )
}

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

    #[test]
    fn sync_window_title_writes_only_on_change() {
        let mut out = Vec::new();
        let mut last = String::new();

        sync_window_title(&mut out, &mut last, "Shuvarie").unwrap();
        assert!(!out.is_empty());
        assert_eq!(last, "Shuvarie");

        let unchanged = out.len();
        sync_window_title(&mut out, &mut last, "Shuvarie").unwrap();
        assert_eq!(out.len(), unchanged);

        sync_window_title(&mut out, &mut last, "Shuvarie — fix the bug").unwrap();
        assert!(out.len() > unchanged);
        assert_eq!(last, "Shuvarie — fix the bug");
    }

    #[test]
    fn keyboard_protocol_probe_sequences() {
        assert_eq!(escape::QUERY_KITTY_FLAGS.to_string(), "\x1b[?u");
        assert_eq!(escape::REQUEST_MODIFY_OTHER_KEYS, "\x1b[>4;1m");
        assert_eq!(escape::RESET_MODIFY_OTHER_KEYS, "\x1b[>4n");
    }
}