Skip to main content

vtcode_ui/tui/core_tui/runner/
mod.rs

1use std::io;
2use std::time::Duration;
3
4use anyhow::{Context, Result};
5use ratatui::{Terminal, backend::CrosstermBackend};
6use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
7use tokio_util::sync::CancellationToken;
8
9use crate::tui::config::types::UiSurfacePreference;
10use crate::tui::options::FullscreenInteractionSettings;
11use crate::tui::ui::tui::log::{clear_tui_log_sender, register_tui_log_sender, set_log_theme_name};
12
13type EventCallback<E> = std::sync::Arc<dyn Fn(&E) + Send + Sync + 'static>;
14
15pub trait TuiCommand {
16    fn is_suspend_event_loop(&self) -> bool;
17    fn is_resume_event_loop(&self) -> bool;
18    fn is_clear_input_queue(&self) -> bool;
19    fn is_force_redraw(&self) -> bool;
20    fn is_stop_event_stream(&self) -> bool;
21    fn is_start_event_stream(&self) -> bool;
22
23    /// Merge `next` into `self` when both are adjacent transcript appends.
24    ///
25    /// The drain loop uses this to paint a burst of streamed lines in one frame
26    /// instead of one frame per `MAX_COMMANDS_PER_TURN` slice. Returns `Ok(())`
27    /// when `next` was absorbed, or `Err(next)` unchanged otherwise. The default
28    /// keeps every command distinct.
29    fn absorb_transcript_append(&mut self, next: Self) -> Result<(), Self>
30    where
31        Self: Sized,
32    {
33        Err(next)
34    }
35}
36
37pub trait TuiSessionDriver {
38    type Command: TuiCommand;
39    type Event;
40
41    fn handle_command(&mut self, command: Self::Command);
42    #[expect(
43        clippy::type_complexity,
44        reason = "Intentional compatibility, platform, test, or API-shape suppression."
45    )]
46    fn handle_event(
47        &mut self,
48        event: crossterm::event::Event,
49        events: &UnboundedSender<Self::Event>,
50        callback: Option<&(dyn Fn(&Self::Event) + Send + Sync + 'static)>,
51    );
52    fn handle_tick(&mut self);
53    /// Whether the session needs active-rate ticks (animations or transient
54    /// expiries pending). The drive loop uses this to extend active-mode
55    /// ticking independently of recent user input, so truly idle sessions rest
56    /// instead of polling. Input, commands, and crossterm events always render
57    /// immediately regardless of this flag.
58    fn needs_animation_tick(&self) -> bool;
59    fn render(&mut self, frame: &mut ratatui::Frame<'_>);
60    fn take_redraw(&mut self) -> bool;
61    fn use_steady_cursor(&self) -> bool;
62    fn is_hovering_link(&self) -> bool;
63    fn is_selecting_text(&self) -> bool;
64    fn should_exit(&self) -> bool;
65    fn request_exit(&mut self);
66    fn mark_dirty(&mut self);
67    fn update_terminal_title(&mut self);
68    fn attach_program_status_terminal(&mut self);
69    fn flush_program_status(&mut self);
70    fn shutdown_program_status(&mut self);
71    fn clear_terminal_title(&mut self);
72    fn is_running_activity(&self) -> bool;
73    fn has_status_spinner(&self) -> bool;
74    fn thinking_spinner_active(&self) -> bool;
75    fn has_active_navigation_ui(&self) -> bool;
76    fn apply_coalesced_scroll(&mut self, line_delta: i32, page_delta: i32);
77    fn set_show_logs(&mut self, show: bool);
78    fn set_active_pty_sessions(&mut self, sessions: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>);
79    fn set_workspace_root(&mut self, root: Option<std::path::PathBuf>);
80    fn set_log_receiver(&mut self, receiver: UnboundedReceiver<crate::tui::core_tui::log::LogEntry>);
81    fn set_fullscreen_active(&mut self, active: bool);
82    fn set_fullscreen_interaction(&mut self, config: FullscreenInteractionSettings);
83    fn set_preview_callback(&mut self, callback: Option<PreviewCallback>);
84}
85
86impl TuiCommand for crate::tui::core_tui::types::InlineCommand {
87    fn is_suspend_event_loop(&self) -> bool {
88        matches!(self, crate::tui::core_tui::types::InlineCommand::SuspendEventLoop)
89    }
90
91    fn is_resume_event_loop(&self) -> bool {
92        matches!(self, crate::tui::core_tui::types::InlineCommand::ResumeEventLoop)
93    }
94
95    fn is_clear_input_queue(&self) -> bool {
96        matches!(self, crate::tui::core_tui::types::InlineCommand::ClearInputQueue)
97    }
98
99    fn is_force_redraw(&self) -> bool {
100        matches!(self, crate::tui::core_tui::types::InlineCommand::ForceRedraw)
101    }
102
103    fn is_stop_event_stream(&self) -> bool {
104        matches!(self, crate::tui::core_tui::types::InlineCommand::StopEventStream)
105    }
106
107    fn is_start_event_stream(&self) -> bool {
108        matches!(self, crate::tui::core_tui::types::InlineCommand::StartEventStream)
109    }
110
111    fn absorb_transcript_append(&mut self, next: Self) -> Result<(), Self> {
112        self.absorb_append(next)
113    }
114}
115
116use super::types::FocusChangeCallback;
117pub(crate) use super::types::PreviewCallback;
118
119mod drive;
120mod events;
121mod signal;
122mod surface;
123pub(crate) mod terminal_io;
124mod terminal_modes;
125
126use drive::{DriveRuntimeOptions, drive_terminal};
127use events::{EventListener, EventSender, TerminalEvent, spawn_event_loop};
128use signal::SignalCleanupGuard;
129use surface::TerminalSurface;
130use terminal_io::{drain_terminal_events, finalize_terminal, prepare_terminal};
131use terminal_modes::{TerminalModeState, enable_terminal_modes, restore_terminal_modes};
132
133/// Controls the lifecycle of the async crossterm event stream.
134///
135/// The event loop must be fully stopped before launching an external editor
136/// that needs stdin (e.g., nvim), otherwise the background EventStream task
137/// competes with the editor for terminal input, causing freezes.
138pub(super) struct EventStreamController {
139    cancellation_token: CancellationToken,
140    join_handle: Option<tokio::task::JoinHandle<()>>,
141    event_tx: EventSender,
142    rx_paused: std::sync::Arc<std::sync::atomic::AtomicBool>,
143    last_input_elapsed_ms: std::sync::Arc<std::sync::atomic::AtomicU64>,
144    session_start: std::time::Instant,
145}
146
147impl EventStreamController {
148    fn new(
149        cancellation_token: CancellationToken,
150        join_handle: tokio::task::JoinHandle<()>,
151        event_tx: EventSender,
152        rx_paused: std::sync::Arc<std::sync::atomic::AtomicBool>,
153        last_input_elapsed_ms: std::sync::Arc<std::sync::atomic::AtomicU64>,
154        session_start: std::time::Instant,
155    ) -> Self {
156        Self {
157            cancellation_token,
158            join_handle: Some(join_handle),
159            event_tx,
160            rx_paused,
161            last_input_elapsed_ms,
162            session_start,
163        }
164    }
165
166    /// Cancel the current event loop task and await its termination.
167    /// Creates a fresh CancellationToken for the next `start()` call.
168    ///
169    /// Bounded: a stuck crossterm reader must not park TUI teardown, and a
170    /// leaked reader would keep stdin claimed after exit. The handle is
171    /// aborted on timeout so shutdown always makes progress.
172    async fn stop(&mut self) {
173        self.cancellation_token.cancel();
174        if let Some(mut handle) = self.join_handle.take()
175            && tokio::time::timeout(Duration::from_millis(100), &mut handle).await.is_err()
176        {
177            tracing::debug!("event loop did not stop within 100ms; aborting");
178            handle.abort();
179        }
180        self.cancellation_token = CancellationToken::new();
181    }
182
183    /// Spawn a new event loop task with a fresh EventStream.
184    /// Safe to call multiple times after `stop()`.
185    fn start(&mut self) {
186        let token = self.cancellation_token.clone();
187        let event_tx = self.event_tx.clone();
188        let rx_paused = self.rx_paused.clone();
189        let last_input = self.last_input_elapsed_ms.clone();
190        let session_start = self.session_start;
191        self.join_handle = Some(tokio::spawn(async move {
192            spawn_event_loop(event_tx, token, rx_paused, last_input, session_start).await;
193        }));
194    }
195
196    /// Ensure the event loop is stopped for final cleanup on TUI exit.
197    ///
198    /// Bounded like [`Self::stop`]: abort on timeout so a wedged reader can
199    /// never delay the alternate-screen teardown and shell return.
200    async fn shutdown(&mut self) {
201        if let Some(mut handle) = self.join_handle.take() {
202            self.cancellation_token.cancel();
203            if tokio::time::timeout(Duration::from_millis(100), &mut handle).await.is_err() {
204                tracing::debug!("event loop did not shut down within 100ms; aborting");
205                handle.abort();
206            }
207        }
208    }
209}
210
211struct TerminalModeRestoreGuard {
212    state: Option<TerminalModeState>,
213}
214
215impl TerminalModeRestoreGuard {
216    fn new(state: TerminalModeState) -> Self {
217        Self { state: Some(state) }
218    }
219
220    fn state_mut(&mut self) -> &mut TerminalModeState {
221        self.state
222            .as_mut()
223            .expect("terminal mode restore guard must stay armed until shutdown")
224    }
225
226    fn restore(&mut self) -> Result<()> {
227        if let Some(state) = self.state.take() {
228            restore_terminal_modes(&state)?;
229        }
230        Ok(())
231    }
232
233    fn restore_silently(&mut self) {
234        if self.state.is_some() {
235            if let Err(error) = self.restore() {
236                tracing::warn!(%error, "failed to restore terminal modes");
237            }
238        }
239    }
240}
241
242impl Drop for TerminalModeRestoreGuard {
243    fn drop(&mut self) {
244        self.restore_silently();
245    }
246}
247
248pub(crate) struct TuiOptions<E> {
249    pub(crate) surface_preference: UiSurfacePreference,
250    pub(crate) inline_rows: u16,
251    pub(crate) show_logs: bool,
252    pub(crate) log_theme: Option<String>,
253    pub(crate) event_callback: Option<EventCallback<E>>,
254    pub(crate) focus_callback: Option<FocusChangeCallback>,
255    pub(crate) active_pty_sessions: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
256    pub(crate) input_activity_counter: Option<std::sync::Arc<std::sync::atomic::AtomicU64>>,
257    pub(crate) keyboard_protocol: crate::tui::config::KeyboardProtocolConfig,
258    pub(crate) fullscreen: FullscreenInteractionSettings,
259    pub(crate) workspace_root: Option<std::path::PathBuf>,
260    pub(crate) preview_callback: Option<PreviewCallback>,
261}
262
263pub(crate) async fn run_tui<S, F>(
264    mut commands: UnboundedReceiver<S::Command>,
265    events: UnboundedSender<S::Event>,
266    options: TuiOptions<S::Event>,
267    make_session: F,
268) -> Result<()>
269where
270    S: TuiSessionDriver,
271    F: FnOnce(u16) -> S,
272{
273    // Create a guard to mark TUI as initialized during the session
274    // This ensures the panic hook knows to restore terminal state
275    let _panic_guard = crate::tui::ui::tui::panic_hook::TuiPanicGuard::new();
276    crate::tui::frame_metrics::initialize_from_env();
277
278    let _signal_guard = SignalCleanupGuard::new()?;
279
280    let surface = TerminalSurface::detect(options.surface_preference, options.inline_rows)?;
281    set_log_theme_name(options.log_theme.clone());
282    let mut session = make_session(surface.rows());
283    session.attach_program_status_terminal();
284    session.set_preview_callback(options.preview_callback.clone());
285    session.set_show_logs(options.show_logs);
286    session.set_active_pty_sessions(options.active_pty_sessions);
287    session.set_workspace_root(options.workspace_root.clone());
288    session.set_fullscreen_active(surface.use_alternate());
289    session.set_fullscreen_interaction(options.fullscreen);
290    if options.show_logs {
291        let (log_tx, log_rx) = tokio::sync::mpsc::unbounded_channel();
292        session.set_log_receiver(log_rx);
293        register_tui_log_sender(log_tx);
294    } else {
295        clear_tui_log_sender();
296    }
297
298    let keyboard_flags = crate::tui::config::keyboard_protocol_to_flags(&options.keyboard_protocol);
299    let mut stderr = io::stderr();
300    let mut mode_restore_guard =
301        TerminalModeRestoreGuard::new(enable_terminal_modes(&mut stderr, &options.fullscreen)?);
302    if surface.use_alternate() {
303        // Alternate-screen sessions return to the pre-TUI cursor after
304        // leaving the buffer, so save it up front. Inline sessions must keep
305        // the cursor at the end of their transcript: restoring to the startup
306        // position would yank it to the top of the frame and force the exit
307        // summary onto a viewport-height jump (blank gap).
308        mode_restore_guard.state_mut().save_cursor_position(&mut stderr);
309        mode_restore_guard.state_mut().enter_alternate_screen(&mut stderr)?;
310        // Record the surface so the canonical restore path can skip the
311        // full-screen clear: leaving the alternate buffer already restores
312        // the main screen (see panic_hook::restore_tui).
313        crate::tui::core_tui::panic_hook::state::mark_alternate_screen_active(true);
314    }
315    mode_restore_guard
316        .state_mut()
317        .push_keyboard_enhancement_flags(&mut stderr, keyboard_flags);
318
319    session.update_terminal_title();
320    super::session::terminal_title::apply_iterm2_profile_once();
321
322    let backend = CrosstermBackend::new(stderr);
323    let mut terminal = Terminal::new(backend).context("failed to initialize inline terminal")?;
324    prepare_terminal(&mut terminal)?;
325
326    // Create event listener and channels using the new async pattern
327    let (mut input_listener, event_channels) = EventListener::new();
328    let cancellation_token = CancellationToken::new();
329    let event_loop_token = cancellation_token.clone();
330    let event_channels_for_loop = event_channels.clone();
331    let rx_paused = event_channels.rx_paused.clone();
332    let last_input_elapsed_ms = event_channels.last_input_elapsed_ms.clone();
333    let session_start = event_channels.session_start;
334
335    // Ensure any capability or resize responses emitted during terminal setup are not treated as
336    // the user's first keystrokes.
337    drain_terminal_events();
338
339    // Clone the sender before moving event_channels_for_loop into tokio::spawn.
340    let event_tx_for_controller = event_channels_for_loop.tx.clone();
341
342    // Spawn the async event loop after the terminal is fully configured so the first keypress is
343    // captured immediately (avoids cooked-mode buffering before raw mode is enabled).
344    let event_loop_handle = tokio::spawn(async move {
345        spawn_event_loop(
346            event_channels_for_loop.tx.clone(),
347            event_loop_token,
348            rx_paused,
349            last_input_elapsed_ms,
350            session_start,
351        )
352        .await;
353    });
354
355    let mut event_stream = EventStreamController::new(
356        cancellation_token,
357        event_loop_handle,
358        event_tx_for_controller,
359        event_channels.rx_paused.clone(),
360        event_channels.last_input_elapsed_ms.clone(),
361        event_channels.session_start,
362    );
363
364    let drive_result = drive_terminal(
365        &mut terminal,
366        &mut session,
367        &mut commands,
368        &events,
369        &mut input_listener,
370        event_channels,
371        DriveRuntimeOptions {
372            event_callback: options.event_callback,
373            focus_callback: options.focus_callback,
374            use_alternate_screen: surface.use_alternate(),
375            input_activity_counter: options.input_activity_counter,
376            keyboard_flags,
377            fullscreen: options.fullscreen,
378            preview_callback: options.preview_callback,
379        },
380        &mut event_stream,
381    )
382    .await;
383
384    session.shutdown_program_status();
385
386    // Gracefully shutdown the event loop (may already be stopped by StopEventStream)
387    event_stream.shutdown().await;
388
389    // Drain any pending events before finalizing terminal and disabling modes
390    drain_terminal_events();
391
392    // When another party already restored the terminal (host backstop or panic
393    // hook), the main screen buffer is live: writes here (line clear, cursor
394    // show, clear) would land there instead of on the alternate screen.
395    let is_alternate = surface.use_alternate();
396    let finalize_result = if crate::tui::core_tui::panic_hook::is_restore_claimed() {
397        Ok(())
398    } else {
399        finalize_terminal(&mut terminal, is_alternate)
400    };
401
402    // Restore terminal modes (handles all modes including raw mode)
403    if let Err(error) = mode_restore_guard.restore() {
404        tracing::warn!(%error, "failed to restore terminal modes");
405    }
406
407    // Clear terminal title on exit.
408    session.clear_terminal_title();
409
410    drive_result?;
411    finalize_result?;
412
413    clear_tui_log_sender();
414    vtcode_commons::trace_flush::flush_trace_log();
415
416    Ok(())
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use std::sync::atomic::{AtomicBool, Ordering};
423
424    /// Sets a flag when dropped, so a test can observe that an aborted task
425    /// future was actually dropped (not merely detached).
426    struct DropFlag(std::sync::Arc<AtomicBool>);
427    impl Drop for DropFlag {
428        fn drop(&mut self) {
429            self.0.store(true, Ordering::SeqCst);
430        }
431    }
432
433    /// A wedged event-loop task must be aborted, not silently detached: the
434    /// prior implementation dropped the join handle on timeout, which left the
435    /// crossterm reader holding stdin past TUI teardown.
436    #[tokio::test]
437    async fn event_stream_shutdown_aborts_a_wedged_reader() {
438        let (_listener, channels) = EventListener::new();
439        let dropped = std::sync::Arc::new(AtomicBool::new(false));
440        let flag = dropped.clone();
441        let handle = tokio::spawn(async move {
442            let _guard = DropFlag(flag);
443            std::future::pending::<()>().await;
444        });
445
446        let mut controller = EventStreamController::new(
447            CancellationToken::new(),
448            handle,
449            channels.tx.clone(),
450            channels.rx_paused.clone(),
451            channels.last_input_elapsed_ms.clone(),
452            channels.session_start,
453        );
454
455        let started = std::time::Instant::now();
456        controller.shutdown().await;
457        assert!(started.elapsed() < Duration::from_secs(1), "shutdown must not block on a wedged reader");
458
459        tokio::time::timeout(Duration::from_secs(1), async {
460            while !dropped.load(Ordering::SeqCst) {
461                tokio::task::yield_now().await;
462            }
463        })
464        .await
465        .expect("shutdown must abort the wedged event-loop task");
466    }
467}