Skip to main content

rpi_cli/
tui_shell.rs

1//! Driver-generic TUI shell.
2//!
3//! The shell half of the unification: a single terminal UI that drives **any**
4//! [`SessionDriver`] — chrome (banner + status slot + footer), the editor dock,
5//! the input loop, and the slash-command surface. It renders the transcript
6//! through the shared [`TranscriptView`] and applies normalized [`UiEvent`]s, so
7//! the same shell serves the remote client today and the in-process host once
8//! its runner adopts the driver seam.
9//!
10//! Local-only capabilities (session tree and extension management) are not part of
11//! this shell: it is the transport-agnostic floor both frontends share.
12//!
13//! [`UiEvent`]: crate::transcript_view::UiEvent
14
15use std::sync::{Arc, Mutex};
16use std::time::{Duration, Instant};
17
18use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEventKind};
19use rpi_tui::{
20    bold as tui_bold, Component, Container, Editor, Focusable, FooterComponent, ProcessTerminal,
21    ScrollView, StackChild, StackEntry, StatusIndicator, Text, TuiAltScreen, VStack, WorkingState,
22    TUI,
23};
24
25use crate::session_driver::{DriverCommand, DriverEvent, DriverStatus, SessionDriver};
26use crate::transcript_view::TranscriptView;
27
28mod dialogs;
29use dialogs::ShellDialogs;
30
31/// Drive the generic shell against `driver` until the user exits (or the
32/// driver's event stream ends). `addr` is a display label for the banner.
33pub async fn run_driver_tui<D: SessionDriver>(driver: &D, addr: &str) -> Result<(), String> {
34    run_driver_tui_with_echo(driver, addr, true).await
35}
36
37pub(crate) async fn run_driver_tui_with_echo<D: SessionDriver>(
38    driver: &D,
39    addr: &str,
40    echo_prompt: bool,
41) -> Result<(), String> {
42    let mut events = driver
43        .events()
44        .ok_or("driver did not yield an event stream")?;
45
46    // ---- Build the UI ----
47    let chrome = ChatChrome::new(addr);
48    let document = Arc::new(Container::new());
49    document.add_child(chrome.header.clone());
50    let transcript_container = Arc::new(Container::new());
51    document.add_child(transcript_container.clone());
52    let scroll = Arc::new(ScrollView::primary(document.clone()));
53
54    // Retained transcript view: the same pi-tui components the local TUI uses,
55    // updated in place from the driver's normalized event stream.
56    let view = TranscriptView::new(transcript_container.clone());
57
58    let keybindings = crate::interactive_tui::configured_keybindings();
59    let editor = Arc::new(Editor::new(
60        rpi_tui::EditorOptions::default(),
61        rpi_tui::EditorStyle::default(),
62        keybindings.clone(),
63    ));
64    let editor_slot = Arc::new(Container::new());
65    editor_slot.add_child(editor.clone());
66
67    // Layout mirrors the local TUI's bottom dock: transcript (grow) over
68    // status slot + editor + footer.
69    let root = VStack::from_children(vec![
70        StackChild::Entry(
71            StackEntry::new(scroll.clone())
72                .basis(0)
73                .grow(1)
74                .shrink(1)
75                .min_size(1),
76        ),
77        StackChild::Entry(StackEntry::new(chrome.status.clone())),
78        StackChild::Entry(StackEntry::new(editor_slot.clone()).shrink(0).min_size(3)),
79        StackChild::Entry(StackEntry::new(chrome.footer.clone())),
80    ]);
81    let root: Arc<dyn Component> = Arc::new(root);
82
83    let tui = Arc::new(TuiAltScreen::new(
84        Box::new(ProcessTerminal::new()),
85        false,
86        None,
87    ));
88    crate::transcript_navigation::install(&tui, keybindings.clone());
89    tui.set_layout_root(Some(root));
90    tui.set_focus(Some(editor.clone()));
91    editor.set_focused(true);
92    tui.start_render_scheduler();
93    tui.start_readerless();
94
95    // ---- Input plumbing ----
96    let (input_tx, mut input_rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
97    let (submit_tx, mut submit_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
98    editor.on_submit(Arc::new(move |text: &str| {
99        let _ = submit_tx.send(text.to_string());
100    }));
101
102    let reader_stop = tokio_util::sync::CancellationToken::new();
103    let stop_reader = reader_stop.clone();
104    let reader = tokio::task::spawn_blocking(move || {
105        while !stop_reader.is_cancelled() {
106            match crossterm::event::poll(Duration::from_millis(50)) {
107                Ok(true) => {}
108                Ok(false) => continue,
109                Err(_) => break,
110            }
111            match crossterm::event::read() {
112                Ok(event) => {
113                    // The size is adopted from `Event::Resize` in the run loop
114                    // below. Refreshing on every event used to invalidate the
115                    // painted frame on each keystroke (a full repaint per key)
116                    // without ever learning a new size.
117                    if input_tx.send(event).is_err() {
118                        break;
119                    }
120                }
121                Err(_) => break,
122            }
123        }
124    });
125
126    // Initial paint (the transcript starts empty; chrome shows connection state).
127    let mut status = DriverStatus::default();
128    chrome.refresh(addr, &status);
129    tui.request_render(true);
130
131    let outcome = run_loop(
132        driver,
133        &mut status,
134        &mut events,
135        &mut input_rx,
136        &mut submit_rx,
137        &tui,
138        &editor,
139        &editor_slot,
140        &chrome,
141        &view,
142        &keybindings,
143        addr,
144        echo_prompt,
145    )
146    .await;
147
148    reader_stop.cancel();
149    let _ = reader.await;
150    tui.stop(Default::default());
151    outcome
152}
153
154#[allow(clippy::too_many_arguments)]
155async fn run_loop<D: SessionDriver>(
156    driver: &D,
157    status: &mut DriverStatus,
158    events: &mut tokio::sync::mpsc::UnboundedReceiver<DriverEvent>,
159    input_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Event>,
160    submit_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
161    tui: &Arc<TuiAltScreen>,
162    editor: &Arc<Editor>,
163    editor_slot: &Arc<Container>,
164    chrome: &ChatChrome,
165    view: &TranscriptView,
166    keybindings: &rpi_tui::Keybindings,
167    addr: &str,
168    echo_prompt: bool,
169) -> Result<(), String> {
170    // Repaint cadence while a run is in flight so the in-editor spinner and the
171    // retry countdown animate between streamed tokens (mirrors the local render
172    // tick). Idle screens never request a frame.
173    let mut ticker = tokio::time::interval(Duration::from_millis(120));
174    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
175    let (dialog_tx, mut dialog_rx) = tokio::sync::mpsc::unbounded_channel();
176    let mut dialogs = ShellDialogs::new(dialog_tx);
177    loop {
178        dialogs.sync_view(editor_slot, editor, tui);
179        tokio::select! {
180            maybe_event = events.recv() => {
181                let Some(event) = maybe_event else { break };
182                match event {
183                    DriverEvent::UiDialog(request) => dialogs.push(request),
184                    DriverEvent::UiDialogClosed(id) => dialogs.close(&id),
185                    DriverEvent::Ui(ui) => {
186                        if matches!(ui, crate::transcript_view::UiEvent::AgentEnd) { let _ = dialogs.clear(); }
187                        view.apply(&ui, tui.width());
188                    }
189                    DriverEvent::Status(next) => {
190                        *status = next;
191                        sync_working(editor, status.streaming);
192                        chrome.refresh(addr, status);
193                    }
194                    DriverEvent::Notice(message) => view.add_notice(&message),
195                    DriverEvent::Ended => break,
196                }
197                tui.request_render(false);
198            }
199            maybe_input = input_rx.recv() => {
200                let Some(event) = maybe_input else { break };
201                match event {
202                    Event::Resize(..) => {
203                        tui.note_resize();
204                    }
205                    Event::Mouse(mouse) => {
206                        if tui.handle_scroll_to_end_indicator_mouse_event(&mouse) { continue; }
207                        // Click-to-toggle per-message thinking (see the local
208                        // TUI's mouse arm): resolve before selection/scrolling.
209                        if tui.thinking_region_hit(&mouse).is_some_and(|id| view.toggle_message_thinking(&id)) {
210                            tui.request_render_reusing_scroll_content();
211                            continue;
212                        }
213                        match mouse.kind {
214                            MouseEventKind::ScrollUp => tui.scroll_by(-3),
215                            MouseEventKind::ScrollDown => tui.scroll_by(3),
216                            _ => {}
217                        }
218                        tui.request_render(false);
219                    }
220                    Event::Key(key) if key.kind != KeyEventKind::Release => {
221                        crate::key_trace::key(&key, "driver-tui");
222                        if is_ctrl(&key, 'c') {
223                            let had_dialog = dialogs.has_active();
224                            for cancel in dialogs.clear() {
225                                let _ = driver.send(cancel).await;
226                            }
227                            if status.streaming {
228                                view.add_notice("aborting…");
229                                let _ = driver.send(DriverCommand::Abort).await;
230                            } else if !had_dialog {
231                                break;
232                            }
233                        } else if !dialogs.handle_key(key)
234                            && !crate::transcript_navigation::handle_key(tui, keybindings, &key) {
235                            editor.handle_key(key);
236                        }
237                        tui.request_render(false);
238                    }
239                    Event::Paste(text) => {
240                        if !dialogs.handle_paste(&text) { editor.insert(&text); }
241                        tui.request_render(false);
242                    }
243                    other => {
244                        crate::key_trace::note(&format!("driver tui event {other:?}"));
245                    }
246                }
247            }
248            maybe_text = submit_rx.recv() => {
249                let Some(text) = maybe_text else { break };
250                // A normal editor submission queued before a question arrived
251                // must not bypass the active approval UI.
252                if dialogs.has_active() { continue; }
253                match handle_submit(driver, status, view, &text, echo_prompt).await {
254                    Ok(SubmitAction::Continue) => {}
255                    Ok(SubmitAction::Quit) => break,
256                    Err(error) => view.add_notice(&format!("error: {error}")),
257                }
258                editor.clear();
259                tui.request_render(false);
260            }
261            Some(action) = dialog_rx.recv() => {
262                if let Some((id, command)) = dialogs.action(action) {
263                    match driver.send(command).await {
264                        Ok(()) => dialogs.close(&id),
265                        Err(error) => view.add_notice(&format!("error: {error}")),
266                    }
267                }
268            }
269            _ = ticker.tick() => {
270                // Size watchdog: an event can be missed (or arrive before the
271                // window rectangle moves), and a fullscreen frame must always
272                // match the real window.
273                tui.ensure_size();
274                let retrying = chrome.tick_retry();
275                if status.streaming || retrying {
276                    tui.request_render(false);
277                }
278            }
279            else => break,
280        }
281    }
282    for cancel in dialogs.clear() {
283        let _ = driver.send(cancel).await;
284    }
285    Ok(())
286}
287
288enum SubmitAction {
289    Continue,
290    Quit,
291}
292
293async fn handle_submit<D: SessionDriver>(
294    driver: &D,
295    status: &DriverStatus,
296    view: &TranscriptView,
297    text: &str,
298    echo_prompt: bool,
299) -> Result<SubmitAction, String> {
300    let trimmed = text.trim();
301    if trimmed.is_empty() {
302        return Ok(SubmitAction::Continue);
303    }
304
305    if let Some(rest) = trimmed.strip_prefix('/') {
306        let (name, arg) = match rest.split_once(char::is_whitespace) {
307            Some((name, arg)) => (name, arg.trim()),
308            None => (rest, ""),
309        };
310        match name {
311            "exit" | "quit" | "q" => return Ok(SubmitAction::Quit),
312            "abort" => driver.send(DriverCommand::Abort).await?,
313            "state" => driver.send(DriverCommand::RefreshState).await?,
314            "model" if !arg.is_empty() => {
315                driver
316                    .send(DriverCommand::SetModel(arg.to_string()))
317                    .await?
318            }
319            "thinking" if !arg.is_empty() => {
320                driver
321                    .send(DriverCommand::SetThinkingLevel(arg.to_string()))
322                    .await?
323            }
324            "tools" => {
325                let tools = if status.active_tools.is_empty() {
326                    "(default)".to_string()
327                } else {
328                    status.active_tools.join(", ")
329                };
330                view.add_notice(&format!("active tools: {tools}"));
331            }
332            "help" => view
333                .add_notice("commands: /abort /state /model <id> /thinking <level> /tools /exit"),
334            "" => view.add_notice("empty command (try /help)"),
335            other => view.add_notice(&format!(
336                "unsupported command: /{other} (session-tree and reload commands are not available in remote mode; try /help)"
337            )),
338        }
339        return Ok(SubmitAction::Continue);
340    }
341
342    if echo_prompt {
343        view.add_user(trimmed);
344    }
345    driver
346        .send(DriverCommand::Prompt(trimmed.to_string()))
347        .await?;
348    Ok(SubmitAction::Continue)
349}
350
351fn is_ctrl(key: &KeyEvent, ch: char) -> bool {
352    key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char(ch)
353}
354
355/// The non-transcript chrome (top banner + status slot + footer), built from
356/// the same `pi-tui` components the local TUI uses ([`StatusIndicator`],
357/// [`FooterComponent`]) so the two screens read the same.
358struct ChatChrome {
359    header: Arc<Text>,
360    status: Arc<Container>,
361    footer: Arc<FooterComponent>,
362    /// The live retry indicator, kept across refreshes so its countdown ticks.
363    retry: Mutex<Option<(u32, u32, Arc<StatusIndicator>)>>,
364}
365
366impl ChatChrome {
367    fn new(addr: &str) -> Self {
368        let footer = Arc::new(FooterComponent::new());
369        footer.set_hints(
370            "Enter: Send | Shift+Enter: New line | Ctrl+C: Clear/Exit | Esc: Abort | /help",
371        );
372        Self {
373            header: Arc::new(Text::new(format!("rpi · {addr} · connecting…"), 1, 0)),
374            status: Arc::new(Container::new()),
375            footer,
376            retry: Mutex::new(None),
377        }
378    }
379
380    /// Refresh header + footer + retry indicator from the driver status.
381    fn refresh(&self, addr: &str, status: &DriverStatus) {
382        let model = status.model.as_deref().unwrap_or("");
383        let thinking = status.thinking.as_deref().unwrap_or("off");
384        let connection = if status.ready { "ready" } else { "connecting" };
385        self.header.set_text(tui_bold(&format!(
386            "rpi · {addr} · {connection} · model {} · thinking {thinking}",
387            if model.is_empty() { "(default)" } else { model }
388        )));
389        self.footer.set_model(&short_model_name(model));
390        self.footer.set_thinking_level(Some(thinking));
391        self.footer.set_status("");
392
393        let mut slot = self.retry.lock().unwrap();
394        match status.retry {
395            Some((attempt, max, delay_ms)) => {
396                let unchanged =
397                    matches!(slot.as_ref(), Some((a, m, _)) if *a == attempt && *m == max);
398                if !unchanged {
399                    let indicator = Arc::new(StatusIndicator::retry(
400                        attempt,
401                        max,
402                        Duration::from_millis(delay_ms),
403                    ));
404                    self.status.clear();
405                    self.status.add_child(indicator.clone());
406                    *slot = Some((attempt, max, indicator));
407                }
408            }
409            None => {
410                if slot.take().is_some() {
411                    self.status.clear();
412                }
413            }
414        }
415    }
416
417    /// Tick the retry countdown; returns whether a retry is currently shown.
418    fn tick_retry(&self) -> bool {
419        match self.retry.lock().unwrap().as_ref() {
420            Some((_, _, indicator)) => {
421                indicator.tick_countdown();
422                true
423            }
424            None => false,
425        }
426    }
427}
428
429/// Keep the in-editor working indicator in step with the run state — the local
430/// TUI shows the spinner in the editor's top border, not the status slot.
431fn sync_working(editor: &Arc<Editor>, streaming: bool) {
432    if streaming {
433        if editor.working().is_none() {
434            editor.set_working(Some(WorkingState {
435                started_at: Instant::now(),
436                message: "Working…".to_string(),
437            }));
438        }
439    } else if editor.working().is_some() {
440        editor.set_working(None);
441    }
442}
443
444/// The trailing path segment of a model id (`provider/model` → `model`).
445fn short_model_name(id: &str) -> String {
446    id.rsplit([':', '/'])
447        .next()
448        .filter(|segment| !segment.is_empty())
449        .unwrap_or(id)
450        .to_string()
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456
457    #[test]
458    fn ctrl_detection_is_specific() {
459        assert!(is_ctrl(
460            &KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
461            'c'
462        ));
463        assert!(!is_ctrl(
464            &KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE),
465            'c'
466        ));
467    }
468
469    #[test]
470    fn short_model_name_keeps_the_trailing_segment() {
471        assert_eq!(short_model_name("openai/gpt-5.2"), "gpt-5.2");
472        assert_eq!(short_model_name("anthropic:claude-4"), "claude-4");
473        assert_eq!(short_model_name("bare"), "bare");
474        assert_eq!(short_model_name(""), "");
475    }
476}