Skip to main content

trusty_code_tui/
terminal.rs

1//! The panic-safe terminal lifecycle: [`TerminalGuard`].
2//!
3//! Why: tagent's current `run_tui` (`crates/trusty-agents/src/repl/tui/run.rs`
4//! `setup_terminal`/`restore_terminal`) only restores the terminal AFTER
5//! `event_loop()` returns normally — a panic anywhere inside the loop unwinds
6//! straight past that teardown call and leaves the operator's terminal in raw
7//! mode + the alternate screen (no echo, no visible prompt, `Ctrl-C` doesn't
8//! even show up). That is a real bug in the code this crate will eventually
9//! replace, not a spec this crate should reproduce. `trusty-mpm`'s coordinator
10//! TUI (`crates/trusty-mpm/src/tui/coordinator/mod.rs` `TerminalGuard`) already
11//! fixed this the right way — restoration lives in `Drop`, which Rust runs on
12//! BOTH the normal return path and the panic-unwind path — and this module
13//! generalizes that fix to be the one terminal-lifecycle type both tagent
14//! (Slice 10) and tcode (Slice 3) share.
15//!
16//! What: [`TerminalGuard::enter`] performs the three terminal-mutating steps
17//! (raw mode, alternate screen, mouse capture) and returns a guard alongside
18//! a ready-to-use `ratatui::Terminal`. The guard's `Drop` best-effort undoes
19//! all three; every step swallows its own error since a `Drop` impl cannot
20//! propagate one and a partial restore is still strictly better than none.
21//! The actual OS-level restore calls are routed through the private
22//! [`TerminalOps`] trait so `tests` can substitute a recording fake instead
23//! of exercising a real TTY — sandboxes and CI routinely have no controlling
24//! terminal at all, and the property under test ("does `Drop` run during
25//! unwind") has nothing to do with whether `disable_raw_mode()` itself would
26//! succeed on this particular host.
27//!
28//! # Spec References
29//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 2 deliverable (§5, Slice 2): panic-safe terminal guard.
30
31use std::io::{self, Stdout};
32
33use crossterm::{
34    cursor::Show,
35    event::{DisableMouseCapture, EnableMouseCapture},
36    execute,
37    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
38};
39use ratatui::{Terminal, backend::CrosstermBackend};
40
41/// The terminal-restoring side effects [`TerminalGuard::drop`] performs.
42///
43/// Why: see the module doc comment — this indirection exists purely so
44/// [`tests`] can verify the unwind-safety *contract* (`Drop` runs) without
45/// depending on a real TTY being present. Production code only ever sees
46/// [`CrosstermOps`].
47trait TerminalOps: Send {
48    fn leave(&mut self);
49}
50
51/// The real implementation: disable raw mode, leave the alternate screen,
52/// disable mouse capture, and show the cursor again. Every step is
53/// best-effort (see the module doc comment for why errors are swallowed).
54struct CrosstermOps;
55
56impl TerminalOps for CrosstermOps {
57    fn leave(&mut self) {
58        let _ = disable_raw_mode();
59        let _ = execute!(
60            io::stdout(),
61            LeaveAlternateScreen,
62            DisableMouseCapture,
63            Show
64        );
65    }
66}
67
68/// RAII guard that restores the terminal on drop — including during a panic.
69///
70/// Why: see the module doc comment. Holding this guard for the lifetime of
71/// the render loop is what makes terminal restoration unconditional: there is
72/// no code path (early return, `?`, or panic) that can skip `Drop`.
73/// What: constructed by [`TerminalGuard::enter`], which is the ONLY way to
74/// get one — that constructor is also what performs the matching "enter" side
75/// effects, so a `TerminalGuard` existing is always proof the terminal was
76/// actually put into raw/alt-screen/mouse-capture mode. `Drop` undoes all
77/// three, ignoring errors (nothing useful can be done while unwinding).
78/// Test: `tests::drop_restores_on_normal_scope_exit`,
79/// `tests::drop_restores_on_panic_unwind`.
80pub struct TerminalGuard {
81    ops: Box<dyn TerminalOps>,
82}
83
84impl TerminalGuard {
85    /// Enter raw mode, the alternate screen, and mouse capture, returning a
86    /// guard (whose `Drop` restores all three) alongside a ready-to-`draw`
87    /// `ratatui::Terminal`.
88    ///
89    /// Why: bundling guard + terminal construction into one fallible call
90    /// means a caller can never end up with a live `Terminal` and no guard
91    /// (or vice versa) — the two are only ever created together.
92    /// What: `enable_raw_mode()` first; if entering the alternate screen or
93    /// mouse capture then fails, raw mode is unwound before the error is
94    /// returned (so a failed `enter()` never leaves the terminal half-mutated
95    /// for the caller to clean up). On success, builds a
96    /// `CrosstermBackend<Stdout>`-backed `Terminal`.
97    /// Test: exercised transitively by [`crate::run`](mod@crate::run)'s event-loop tests via
98    /// `ratatui::backend::TestBackend`; `enter()` itself needs a real TTY so
99    /// it is not unit-tested here (mirrors the precedent in
100    /// `crates/trusty-agents/src/repl/tui/run.rs::setup_terminal`, which is
101    /// likewise exercised only by launching the TUI).
102    pub fn enter() -> io::Result<(Self, Terminal<CrosstermBackend<Stdout>>)> {
103        enable_raw_mode()?;
104        let mut stdout = io::stdout();
105        if let Err(e) = execute!(stdout, EnterAlternateScreen, EnableMouseCapture) {
106            // Best-effort unwind of the step that DID succeed before
107            // propagating — otherwise a failed `enter()` leaves raw mode on
108            // with no guard in the caller's hands to undo it.
109            let _ = disable_raw_mode();
110            return Err(e);
111        }
112        let backend = CrosstermBackend::new(stdout);
113        let terminal = match Terminal::new(backend) {
114            Ok(t) => t,
115            Err(e) => {
116                let _ = disable_raw_mode();
117                let _ = execute!(
118                    io::stdout(),
119                    LeaveAlternateScreen,
120                    DisableMouseCapture,
121                    Show
122                );
123                return Err(e);
124            }
125        };
126        Ok((
127            Self {
128                ops: Box::new(CrosstermOps),
129            },
130            terminal,
131        ))
132    }
133
134    /// Test-only constructor: build a guard around a recording [`TerminalOps`]
135    /// fake instead of performing real terminal I/O.
136    #[cfg(test)]
137    fn with_ops(ops: Box<dyn TerminalOps>) -> Self {
138        Self { ops }
139    }
140}
141
142impl Drop for TerminalGuard {
143    /// Why: see [`TerminalGuard`] — runs on both normal return and panic
144    /// unwind, which is the entire point of this type existing.
145    /// What: delegates to the guard's [`TerminalOps::leave`].
146    /// Test: `tests::drop_restores_on_normal_scope_exit`,
147    /// `tests::drop_restores_on_panic_unwind`.
148    fn drop(&mut self) {
149        self.ops.leave();
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use std::panic::{self, AssertUnwindSafe};
157    use std::sync::Arc;
158    use std::sync::atomic::{AtomicUsize, Ordering};
159
160    /// Records how many times `leave()` was called instead of touching a
161    /// real TTY — see the module doc comment for why.
162    struct RecordingOps(Arc<AtomicUsize>);
163
164    impl TerminalOps for RecordingOps {
165        fn leave(&mut self) {
166            self.0.fetch_add(1, Ordering::SeqCst);
167        }
168    }
169
170    /// The ordinary case: a guard going out of scope normally must restore
171    /// exactly once.
172    #[test]
173    fn drop_restores_on_normal_scope_exit() {
174        let count = Arc::new(AtomicUsize::new(0));
175        {
176            let _guard = TerminalGuard::with_ops(Box::new(RecordingOps(count.clone())));
177            assert_eq!(
178                count.load(Ordering::SeqCst),
179                0,
180                "must not restore on construction"
181            );
182        }
183        assert_eq!(count.load(Ordering::SeqCst), 1);
184    }
185
186    /// The bug this type exists to fix: tagent's current `run_tui` only
187    /// restores the terminal AFTER the event loop returns, so a panic mid-loop
188    /// unwinds past that call and leaves the terminal in raw/alt-screen mode.
189    /// This test proves `TerminalGuard` closes that gap — a panic while the
190    /// guard is held still runs `Drop`, because unwinding runs destructors for
191    /// every value on the stack, not just values reached by a normal return.
192    #[test]
193    fn drop_restores_on_panic_unwind() {
194        let count = Arc::new(AtomicUsize::new(0));
195        let count_in_closure = count.clone();
196        let result = panic::catch_unwind(AssertUnwindSafe(|| {
197            let _guard = TerminalGuard::with_ops(Box::new(RecordingOps(count_in_closure)));
198            panic!("simulated panic mid-render-loop");
199        }));
200        assert!(
201            result.is_err(),
202            "the panic must have propagated to catch_unwind"
203        );
204        assert_eq!(
205            count.load(Ordering::SeqCst),
206            1,
207            "TerminalGuard::drop must run during unwind, restoring the terminal exactly once"
208        );
209    }
210
211    /// A guard dropped early (e.g. an explicit `drop(guard)` before a longer
212    /// scope ends) must not restore a second time when the scope itself later
213    /// ends — `Drop` runs exactly once per value, never twice.
214    #[test]
215    fn drop_restores_exactly_once_even_when_dropped_early() {
216        let count = Arc::new(AtomicUsize::new(0));
217        let guard = TerminalGuard::with_ops(Box::new(RecordingOps(count.clone())));
218        drop(guard);
219        assert_eq!(count.load(Ordering::SeqCst), 1);
220    }
221}