From 945ec1a30ddef2f1809bf8d32ded476e0e61818a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:09:38 +0100 Subject: [PATCH] thing-tui: the panic hook restores only a live guard, on the thread that owns it A guard registers when entered and unregisters on drop; the hook restores through the registered guard's own writer, claims the restore once so unwinding does not repeat it, and leaves a panic on any other thread, or after the drop, to the previous hook. Every constructor that enters installs the hook. Per the steward's decision on thing2:finding:cut-tui-host.s1.panic-hook-owner-blind. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 163 +++++++++++-------- crates/thing-tui/src/terminal/guard_tests.rs | 120 ++++++++++++++ crates/thing-tui/tests/pipeline.rs | 15 +- 3 files changed, 216 insertions(+), 82 deletions(-) create mode 100644 crates/thing-tui/src/terminal/guard_tests.rs diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 17dfc9e..56b68e0 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -1,9 +1,12 @@ //! The terminal's mode and bytes. `Terminal` is the guard (raw mode, alternate screen, hidden -//! cursor, mouse, focus and paste reporting, all undone when it drops, and by a panic hook chained -//! ahead of the previous one) and the writer that serializes `diff`'s operations as one -//! synchronized update per frame. It decides nothing about what is drawn. +//! cursor, mouse, focus and paste reporting, all undone when it drops, or by a panic on the thread +//! that owns it) and the writer that serializes `diff`'s operations as one synchronized update per +//! frame. It decides nothing about what is drawn. use std::io::{self, Write}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, Once, PoisonError, TryLockError}; +use std::thread::{self, ThreadId}; use crossterm::cursor::{Hide, MoveTo, Show}; use crossterm::event::{ @@ -18,82 +21,124 @@ use thing_contract::Rgba; use crate::diff::Op; -pub struct Terminal { - out: W, - /// Set once the modes are entered; `Drop` undoes them only then. - entered: bool, +/// What a guard holds, shared with the panic hook through `GUARDS`. `entered` is claimed by whichever +/// restores first (the hook on a panic, `Drop` otherwise), so the restore is written once. +struct Shared { + out: Mutex, + entered: AtomicBool, raw: bool, } -impl Terminal> { - /// Take the terminal over: raw mode, alternate screen, hidden cursor, mouse capture, focus and - /// paste reporting, and a panic hook that gives it back before the previous hook speaks. Stdout - /// is buffered so a frame reaches the terminal in as few writes as it holds. - pub fn stdout() -> io::Result { - let terminal = Self::enter(io::BufWriter::with_capacity(1 << 16, io::stdout()))?; - install_panic_hook(); - Ok(terminal) +trait Restore: Send + Sync { + fn restore(&self); +} + +impl Restore for Shared { + fn restore(&self) { + // The lock is held across a write: a panic inside one (on this thread) reaches the hook with + // it taken. Leave that restore to `Drop`, which runs once the unwinding has released it. + let mut out = match self.out.try_lock() { + Ok(out) => out, + Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), + Err(TryLockError::WouldBlock) => return, + }; + if !self.entered.swap(false, Ordering::SeqCst) { + return; + } + let _ = write_restore(&mut *out).and_then(|()| out.flush()); + if self.raw { + let _ = disable_raw_mode(); + } } } -impl Terminal { - /// Enter the terminal modes on `out`, raw mode included. +/// The guards that are entered, each with the thread that entered it: the only terminals a panic +/// hook may give back, and only to a panic on the thread that owns one. +static GUARDS: Mutex)>> = Mutex::new(Vec::new()); +static HOOK: Once = Once::new(); + +fn guards() -> MutexGuard<'static, Vec<(ThreadId, Arc)>> { + GUARDS.lock().unwrap_or_else(PoisonError::into_inner) +} + +pub struct Terminal { + shared: Arc>, +} + +impl Terminal> { + /// Take the terminal over on stdout, buffered so a frame reaches the terminal in as few writes + /// as it holds. See `enter` for what that does. + pub fn stdout() -> io::Result { + Self::enter(io::BufWriter::with_capacity(1 << 16, io::stdout())) + } +} + +impl Terminal { + /// Enter the terminal modes on `out`: raw mode, alternate screen, hidden cursor, mouse capture, + /// focus and paste reporting. Until the guard drops, a panic on this thread gives the terminal + /// back before the previous panic hook speaks, so its message lands on the user's screen; a + /// panic on another thread leaves it alone. The first guard of the process installs that hook, + /// chained ahead of the hook already there. pub fn enter(out: W) -> io::Result { Self::start(out, true) } - /// The same without raw mode, for a writer that is not a terminal (a test, a pipe): the byte - /// stream is identical and nothing global is touched. + /// The same without raw mode, for a writer that is not a terminal (a test, a pipe). pub fn enter_without_raw_mode(out: W) -> io::Result { Self::start(out, false) } fn start(out: W, raw: bool) -> io::Result { - // Built before anything is entered, so a failure part-way still restores on drop. - let mut terminal = Self { out, entered: true, raw: false }; + HOOK.call_once(install_panic_hook); if raw { enable_raw_mode()?; - terminal.raw = true; } - write_enter(&mut terminal.out)?; - terminal.out.flush()?; + // Registered before anything is written, so a failure part-way still restores on drop. + let shared = Arc::new(Shared { out: Mutex::new(out), entered: AtomicBool::new(true), raw }); + guards().push((thread::current().id(), shared.clone())); + let terminal = Self { shared }; + { + let mut out = terminal.out(); + write_enter(&mut *out)?; + out.flush()?; + } Ok(terminal) } + fn out(&self) -> MutexGuard<'_, W> { + self.shared.out.lock().unwrap_or_else(PoisonError::into_inner) + } + /// Serialize `ops` as one synchronized update and flush once. No ops write nothing. pub fn draw(&mut self, ops: &[Op]) -> io::Result<()> { if ops.is_empty() { return Ok(()); } - queue!(self.out, BeginSynchronizedUpdate)?; + let mut out = self.out(); + queue!(out, BeginSynchronizedUpdate)?; for op in ops { match op { - Op::MoveTo(col, row) => queue!(self.out, MoveTo(clamp(*col), clamp(*row)))?, + Op::MoveTo(col, row) => queue!(out, MoveTo(clamp(*col), clamp(*row)))?, Op::Style(fg, bg, style) => queue!( - self.out, + out, SetForegroundColor(color(fg)), SetBackgroundColor(color(bg)), SetAttribute(if style.bold { Attribute::Bold } else { Attribute::NormalIntensity }), SetAttribute(if style.italic { Attribute::Italic } else { Attribute::NoItalic }), SetAttribute(if style.underline { Attribute::Underlined } else { Attribute::NoUnderline }), )?, - Op::Print(text) => queue!(self.out, Print(text))?, + Op::Print(text) => queue!(out, Print(text))?, } } - queue!(self.out, EndSynchronizedUpdate)?; - self.out.flush() + queue!(out, EndSynchronizedUpdate)?; + out.flush() } } -impl Drop for Terminal { +impl Drop for Terminal { fn drop(&mut self) { - if !std::mem::take(&mut self.entered) { - return; - } - let _ = write_restore(&mut self.out).and_then(|()| self.out.flush()); - if std::mem::take(&mut self.raw) { - let _ = disable_raw_mode(); - } + guards().retain(|(_, guard)| !std::ptr::addr_eq(Arc::as_ptr(guard), Arc::as_ptr(&self.shared))); + self.shared.restore(); } } @@ -132,47 +177,26 @@ pub fn write_restore(out: &mut W) -> io::Result<()> { paste.and(rest) } -/// Chain a hook ahead of the current one that gives the terminal back before the panic message -/// is printed, so the message lands on the user's screen and not the alternate one. +/// Chain a hook ahead of the current one: a panic on a thread that owns an entered guard gives that +/// terminal back before the previous hook prints, and a panic anywhere else goes to the previous +/// hook alone. fn install_panic_hook() { - chain_panic_hook(|| { - let _ = disable_raw_mode(); - let mut out = io::stdout(); - let _ = write_restore(&mut out); - let _ = out.flush(); - }); -} - -/// Run `first` at every panic, then whatever hook was installed before. -fn chain_panic_hook(first: impl Fn() + Send + Sync + 'static) { let previous = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - first(); + let here = thread::current().id(); + let owned: Vec> = guards().iter().filter(|(owner, _)| *owner == here).map(|(_, guard)| guard.clone()).collect(); + for guard in owned { + guard.restore(); + } previous(info); })); } #[cfg(test)] mod tests { - use std::sync::Mutex; - use std::io; - use super::{chain_panic_hook, tolerate}; - - static ORDER: Mutex> = Mutex::new(Vec::new()); - - /// The only test in this binary that panics, so the global hook is its own. - #[test] - fn the_restore_runs_before_the_previous_hook() { - let original = std::panic::take_hook(); - std::panic::set_hook(Box::new(|_| ORDER.lock().unwrap().push("previous"))); - chain_panic_hook(|| ORDER.lock().unwrap().push("restore")); - let caught = std::panic::catch_unwind(|| panic!("forced")); - std::panic::set_hook(original); - assert!(caught.is_err()); - assert_eq!(*ORDER.lock().unwrap(), ["restore", "previous"]); - } + use super::tolerate; #[test] fn only_an_unsupported_mode_is_tolerated() { @@ -182,3 +206,6 @@ mod tests { assert_eq!(other.kind(), io::ErrorKind::BrokenPipe); } } + +#[cfg(test)] +mod guard_tests; diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs new file mode 100644 index 0000000..b3faca7 --- /dev/null +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -0,0 +1,120 @@ +//! The guard and its panic hook, on writers that are not terminals. The hook is process-global, so +//! these tests set a spy as the "previous hook" before any guard is built: it snapshots the watched +//! writer at the moment the chained hook hands over, which is how a test tells the hook's restore +//! from the one `Drop` makes later during unwinding. + +use std::cell::RefCell; +use std::io::{self, Write}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, Mutex, Once}; + +use super::Terminal; + +/// A writer the test keeps a handle on after the terminal that owns it is gone. +#[derive(Clone, Default)] +struct Shared(Arc>>); + +impl Shared { + fn bytes(&self) -> Vec { + self.0.lock().unwrap().clone() + } +} + +impl Write for Shared { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +thread_local! { + /// The writer of the guard this test thread watches, and what it held when the hook handed over. + static WATCH: RefCell> = const { RefCell::new(None) }; + static AT_HAND_OVER: RefCell>> = const { RefCell::new(None) }; +} + +static SPY: Once = Once::new(); + +/// Make the spy the hook the guard's hook will chain to. Every test that builds a guard calls this +/// first, so the spy is installed before the guard's hook is. +fn spy() { + SPY.call_once(|| { + let original = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + WATCH.with(|watch| { + if let Some(out) = watch.borrow().as_ref() { + AT_HAND_OVER.with(|seen| *seen.borrow_mut() = Some(out.bytes())); + } + }); + original(info); + })); + }); +} + +fn guard(out: &Shared) -> Terminal { + spy(); + WATCH.with(|watch| *watch.borrow_mut() = Some(out.clone())); + AT_HAND_OVER.with(|seen| *seen.borrow_mut() = None); + Terminal::start(out.clone(), false).unwrap() +} + +fn count(bytes: &[u8], needle: &str) -> usize { + bytes.windows(needle.len()).filter(|w| *w == needle.as_bytes()).count() +} + +const LEAVE: &str = "\x1b[?1049l"; + +/// What the watched writer held when the previous hook was handed the panic, if one was. +fn at_hand_over() -> Option> { + AT_HAND_OVER.with(|seen| seen.borrow_mut().take()) +} + +/// A panic on the thread that owns a live guard: the chained hook has restored the terminal before +/// the previous hook is called, and the unwinding drop adds nothing. +fn owner_panics(out: &Shared) { + let caught = catch_unwind(AssertUnwindSafe(|| { + let _terminal = guard(out); + panic!("forced on the owner"); + })); + assert!(caught.is_err()); +} + +#[test] +fn a_panic_on_the_owning_thread_restores_exactly_once() { + let out = Shared::default(); + owner_panics(&out); + assert_eq!(count(&out.bytes(), LEAVE), 1); + assert_eq!(count(&out.bytes(), "\x1b[?25h"), 1); +} + +#[test] +fn a_panic_on_another_thread_leaves_the_guard_alone() { + let out = Shared::default(); + let terminal = guard(&out); + let worker = std::thread::spawn(|| panic!("forced on a worker")); + assert!(worker.join().is_err()); + assert_eq!(count(&out.bytes(), LEAVE), 0, "a worker's panic must not take the terminal from a live host"); + drop(terminal); + assert_eq!(count(&out.bytes(), LEAVE), 1); + // The owner's own panic still restores through the hook. + let again = Shared::default(); + owner_panics(&again); + assert_eq!(count(&at_hand_over().expect("hook ran"), LEAVE), 1); +} + +#[test] +fn a_panic_after_the_guard_dropped_writes_nothing() { + let out = Shared::default(); + drop(guard(&out)); + let after_drop = out.bytes(); + assert_eq!(count(&after_drop, LEAVE), 1); + let _ = catch_unwind(|| panic!("forced after the guard")); + assert_eq!(out.bytes(), after_drop); + // And a later guard on the same thread is still served by the hook. + let next = Shared::default(); + owner_panics(&next); + assert_eq!(count(&at_hand_over().expect("hook ran"), LEAVE), 1); +} diff --git a/crates/thing-tui/tests/pipeline.rs b/crates/thing-tui/tests/pipeline.rs index 5bb5f62..d023c0b 100644 --- a/crates/thing-tui/tests/pipeline.rs +++ b/crates/thing-tui/tests/pipeline.rs @@ -15,7 +15,7 @@ use thing_testkit::golden; use thing_testkit::ids::SeqIds; use thing_testkit::mem_state::MemState; use thing_testkit::state; -use thing_tui::{Op, Screen, Terminal, diff, paint, translate}; +use thing_tui::{Op, Screen, diff, paint, translate}; struct Host { core: Core, @@ -75,19 +75,6 @@ fn a_second_frame_with_nothing_new_draws_nothing() { assert_eq!(host.frame(1_016, (100, 37), Vec::new()), Vec::new()); } -#[test] -fn the_first_frames_ops_replay_to_the_same_bytes_as_a_full_repaint() { - let mut host = Host::new(Fixture::F01SwarmDashboard); - let ops = host.frame(1_000, (100, 37), Vec::new()); - assert_eq!(ops, diff(&Screen::new(0, 0), &host.shown)); - // The writer takes exactly those ops: one synchronized update, flushed once. - let mut out = Vec::new(); - let mut terminal = Terminal::enter_without_raw_mode(&mut out).unwrap(); - terminal.draw(&ops).unwrap(); - drop(terminal); - assert!(out.windows(8).any(|w| w == b"\x1b[?2026h")); -} - /// The size read at a frame is that frame's viewport: after a resize the screen is the one a host /// that started at the new size draws, and the diff repaints rather than patches. #[test]