Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent-tui): restore terminal state on panic + real-PTY test (#9155)

Akarshan Biswasc34728d6b30b
diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lock
index 985ccc735..cf83396a9 100644
--- a/src-tauri/jan-cli/Cargo.lock
+++ b/src-tauri/jan-cli/Cargo.lock
@@ -2551,6 +2551,7 @@ dependencies = [
"clap",
"console",
"env_logger",
+ "nix 0.30.1",
"serde_json",
"tauri-plugin-agent-tools",
"tokio",
diff --git a/src-tauri/jan-cli/Cargo.toml b/src-tauri/jan-cli/Cargo.toml
index 56a4e71aa..14d159aca 100644
--- a/src-tauri/jan-cli/Cargo.toml
+++ b/src-tauri/jan-cli/Cargo.toml
@@ -33,6 +33,11 @@ env_logger = "0.11"
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }
+# Real-PTY panic-recovery test (tests/tui_panic.rs): nix's safe `openpty`
+# keeps the test free of `unsafe`. Pinned to the version ../Cargo.toml uses.
+[target.'cfg(unix)'.dev-dependencies]
+nix = { version = "=0.30.1", features = ["term"] }
+
# Mirror the desktop crate's release profile: the CLI inherited it while it was a
# bin of ../Cargo.toml, and a standalone crate would otherwise fall back to the
# default (opt-level 3, no LTO) and ship a differently sized binary.
diff --git a/src-tauri/jan-cli/tests/tui_panic.rs b/src-tauri/jan-cli/tests/tui_panic.rs
new file mode 100644
index 000000000..58b8da687
--- /dev/null
+++ b/src-tauri/jan-cli/tests/tui_panic.rs
@@ -0,0 +1,179 @@
+//! A panic inside the TUI (`JAN_TUI_PANIC_AFTER_RAW_MODE`, see
+//! `core::cli::tui::run`) must leave a real terminal clean: no raw mode, no
+//! alternate screen, no mouse tracking, no Kitty keyboard protocol, cursor
+//! visible. An in-memory `TestBackend` cannot show this -- there is no real
+//! terminal underneath it, so nothing proves the escape sequences the panic
+//! hook emits ever reach a tty. This spawns the real `jan` binary under a
+//! real PTY (`nix::pty::openpty`) and reads back the raw bytes the binary wrote.
+//!
+//! unix-only: the panic hook and its terminal-mode sequences are written for
+//! an ANSI terminal; `openpty` itself is a POSIX API.
+#![cfg(unix)]
+
+use std::fs::File;
+use std::io::Read;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use nix::pty::{openpty, Winsize};
+use nix::sys::termios::{tcgetattr, LocalFlags};
+
+/// A scratch `HOME` of our own, so the binary's "not signed in" first-run path
+/// runs (no provider configured, no network, no credentials) rather than
+/// touching a real `~/.jan`.
+fn scratch_home() -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("jan-tui-panic-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+/// Generous for a debug build on a loaded CI runner; a healthy run exits in
+/// well under a second.
+const EXIT_DEADLINE: Duration = Duration::from_secs(60);
+
+#[test]
+fn panic_after_raw_mode_leaves_the_terminal_clean() {
+ let size = Winsize {
+ ws_row: 24,
+ ws_col: 80,
+ ws_xpixel: 0,
+ ws_ypixel: 0,
+ };
+ // nix's safe wrapper hands back two `OwnedFd`s, so no raw-fd ownership
+ // transfer (and no `unsafe`) is needed here.
+ let pty = openpty(&size, None).expect("open test PTY");
+ let mut master = File::from(pty.master);
+ let slave = File::from(pty.slave);
+ // Raw mode is termios state, not an escape sequence, so it never shows up
+ // in the captured bytes. A master-side `tcgetattr` reads the line
+ // discipline the slave shares, and works after the child has exited and
+ // closed the last slave fd (keeping a slave clone instead would block the
+ // reader below forever, since EIO only arrives once every slave is gone).
+ let termios_probe = master.try_clone().expect("clone PTY master");
+
+ let home = scratch_home();
+ let child = Command::new(env!("CARGO_BIN_EXE_jan"))
+ .env("HOME", &home)
+ .env("JAN_CLI_NO_UPDATE_CHECK", "1")
+ .env("JAN_TUI_PANIC_AFTER_RAW_MODE", "1")
+ // RUST_BACKTRACE off: the panic hook's output is what is under test,
+ // not the backtrace, and a backtrace could itself contain bytes that
+ // confuse the escape-sequence assertions below.
+ .env("RUST_BACKTRACE", "0")
+ .stdin(Stdio::from(slave.try_clone().expect("clone PTY slave")))
+ .stdout(Stdio::from(slave.try_clone().expect("clone PTY slave")))
+ .stderr(Stdio::from(slave))
+ .spawn()
+ .expect("spawn jan under the test PTY");
+
+ let reader = std::thread::spawn(move || {
+ let mut output = Vec::new();
+ let mut buffer = [0u8; 4096];
+ loop {
+ match master.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(n) => output.extend_from_slice(&buffer[..n]),
+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
+ // Linux reports EIO once the last PTY slave closes.
+ Err(e) if e.raw_os_error() == Some(nix::libc::EIO) => break,
+ Err(e) => panic!("read child PTY: {e}"),
+ }
+ }
+ output
+ });
+
+ // Bounded: if the trigger ever stops firing, the TUI would sit in its
+ // input loop forever and hang CI instead of failing. Killing the child
+ // closes the last slave fd, which also ends the reader with EIO.
+ let mut child = child;
+ let deadline = Instant::now() + EXIT_DEADLINE;
+ let status = loop {
+ if let Some(status) = child.try_wait().expect("poll the jan process") {
+ break Some(status);
+ }
+ if Instant::now() >= deadline {
+ let _ = child.kill();
+ let _ = child.wait();
+ break None;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ };
+ let output = reader.join().expect("read terminal output");
+ let text = String::from_utf8_lossy(&output);
+ let Some(status) = status else {
+ let _ = std::fs::remove_dir_all(&home);
+ panic!("jan did not exit within {EXIT_DEADLINE:?} of the induced panic: {text}");
+ };
+
+ let _ = std::fs::remove_dir_all(&home);
+
+ // `install_panic_hook` runs `restore_terminal_modes` before unwinding
+ // continues, so the process exits with a panic (non-zero), not a clean 0 --
+ // the thing under test is what reached the terminal before that exit, not
+ // the exit code itself, but a successful exit would mean the panic never
+ // fired and the test is not exercising anything.
+ assert!(
+ !status.success(),
+ "the induced panic did not abort the process; stderr/stdout: {text}"
+ );
+
+ // `disable_raw_mode` restores the termios crossterm saved at
+ // `enable_raw_mode`: canonical line editing and echo back on.
+ let termios = tcgetattr(&termios_probe).expect("read PTY termios");
+ assert!(
+ termios
+ .local_flags
+ .contains(LocalFlags::ICANON | LocalFlags::ECHO),
+ "the panic hook left the terminal in raw mode: {:?}",
+ termios.local_flags
+ );
+
+ // Private modes `run` turns on at startup and `restore_terminal_modes`
+ // turns off: bracketed paste, mouse tracking (buttons, drag, SGR
+ // coordinates), the alternate screen buffer and the Kitty keyboard
+ // protocol push/pop.
+ let enabled = [
+ ("bracketed paste enabled", "\x1b[?2004h"),
+ ("mouse buttons+wheel enabled", "\x1b[?1000h"),
+ ("mouse drag enabled", "\x1b[?1002h"),
+ ("SGR mouse coordinates enabled", "\x1b[?1006h"),
+ ("alternate screen entered", "\x1b[?1049h"),
+ ("Kitty keyboard protocol pushed", "\x1b[>5u"),
+ ];
+ for (label, seq) in enabled {
+ assert!(
+ text.contains(seq),
+ "expected the session to have turned {label} on ({seq:?}) before panicking: {text}"
+ );
+ }
+
+ // The last enable `run` writes before the panic trigger. Every restore
+ // sequence must come after it, proving the hook -- not some earlier code
+ // path -- is what turned each mode back off.
+ let last_enable_at = enabled
+ .iter()
+ .map(|(_, seq)| text.rfind(seq).expect("checked present above"))
+ .max()
+ .expect("non-empty");
+ let restored = [
+ ("bracketed paste disabled", "\x1b[?2004l"),
+ ("mouse buttons+wheel disabled", "\x1b[?1000l"),
+ ("mouse drag disabled", "\x1b[?1002l"),
+ ("SGR mouse coordinates disabled", "\x1b[?1006l"),
+ ("alternate screen left", "\x1b[?1049l"),
+ ("Kitty keyboard protocol popped", "\x1b[<u"),
+ ("cursor shown", "\x1b[?25h"),
+ // A panic inside `terminal.draw` would otherwise leave a synchronized
+ // frame held over the restore and the panic message.
+ ("synchronized update ended", "\x1b[?2026l"),
+ ];
+ for (label, seq) in restored {
+ let at = text.rfind(seq).unwrap_or_else(|| {
+ panic!("expected the panic hook to have {label} ({seq:?}): {text}")
+ });
+ assert!(
+ at > last_enable_at,
+ "{label} ({seq:?}) must follow the last startup mode, not precede it: {text}"
+ );
+ }
+}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 804969489..4fe657119 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -19,14 +19,13 @@ use super::path_refs;
use ratatui::crossterm::{
event::{
- self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, Event, KeyCode,
- KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
+ self, EnableBracketedPaste, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
+ MouseButton, MouseEvent, MouseEventKind,
},
execute,
- style::Print,
terminal::{
disable_raw_mode, enable_raw_mode, BeginSynchronizedUpdate, EndSynchronizedUpdate,
- EnterAlternateScreen, LeaveAlternateScreen,
+ EnterAlternateScreen,
},
};
use ratatui::prelude::*;
@@ -145,6 +144,92 @@ fn sync_output_for(kind: super::terminal_setup::Kind) -> bool {
fn use_synchronized_output() -> bool {
sync_output_for(super::terminal_setup::identify(|k| std::env::var(k).ok()))
}
+
+/// Everything `run` turns on between `enable_raw_mode` and the first frame,
+/// undone in one write. Shared by the clean-shutdown path and the panic hook
+/// (`install_panic_hook`) so the two can never drift: whichever one runs, the
+/// shell gets back exactly what it had -- no raw mode, no alternate screen, no
+/// mouse tracking, no Kitty keyboard protocol, alternate scroll restored, and a
+/// visible cursor. Plain writes rather than `execute!`/`Terminal`, since the
+/// panic hook has no `&mut Terminal` to hand (the panic can land while one is
+/// borrowed) and raw mode's own disable is independent of stdout entirely.
+///
+/// Best-effort: a panic is already an error path, and a second one here (an
+/// already-closed stdout, say) must not stop the first panic's message from
+/// reaching the terminal, so every step is `let _ =`.
+fn restore_terminal_modes() {
+ let _ = disable_raw_mode();
+ let mut stdout = io::stdout();
+ let _ = stdout.write_all(
+ format!(
+ "{END_SYNC_UPDATE}{DISABLE_BRACKETED_PASTE}{DISABLE_MOUSE_CAPTURE}\
+ {KITTY_KEYS_OFF}{}{LEAVE_ALT_SCREEN}",
+ alt_scroll_restore(),
+ )
+ .as_bytes(),
+ );
+ let _ = stdout.write_all(SHOW_CURSOR.as_bytes());
+ let _ = stdout.flush();
+}
+
+/// Raw escape sequences standing in for the `crossterm::Command` types used
+/// elsewhere (`DisableBracketedPaste`, `DisableMouseCapture`,
+/// `LeaveAlternateScreen`, cursor show): `restore_terminal_modes` has no
+/// `impl Write` the `Command` trait can target other than `Stdout` directly,
+/// and writing the bytes once here keeps the panic hook and the normal exit
+/// path byte-for-byte identical.
+/// First, because a panic inside `terminal.draw` lands between the loop's
+/// `BeginSynchronizedUpdate` and its `EndSynchronizedUpdate`: with the frame
+/// still held, the terminal would sit on everything below -- restore and panic
+/// message alike -- until its own sync timeout. A no-op when no frame is open.
+const END_SYNC_UPDATE: &str = "\x1b[?2026l";
+const DISABLE_BRACKETED_PASTE: &str = "\x1b[?2004l";
+const DISABLE_MOUSE_CAPTURE: &str = "\x1b[?1006l\x1b[?1002l\x1b[?1000l";
+const LEAVE_ALT_SCREEN: &str = "\x1b[?1049l";
+const SHOW_CURSOR: &str = "\x1b[?25h";
+
+/// The thread running the render loop while it owns the terminal's modes, or
+/// `None` once they have been restored. Panic hooks are process-wide, but only
+/// a panic on this thread ends the session: a spawned job's panic surfaces as a
+/// `JoinError` the loop shrugs off (`await_mcp_job`, `await_context`, ...), and
+/// tearing the modes down under a TUI that keeps drawing would wreck it. A job
+/// panic the loop does propagate re-panics here, on the owning thread.
+static TERMINAL_OWNER: std::sync::Mutex<Option<std::thread::ThreadId>> =
+ std::sync::Mutex::new(None);
+
+/// Give up the terminal if the current thread owns it, reporting whether it
+/// did. Taking the slot makes the restore run once: a clean exit releases it,
+/// so a later panic (or a second one while unwinding) leaves the shell alone.
+fn release_terminal() -> bool {
+ // A poisoned lock still holds a valid id; the hook must not panic on it.
+ let mut owner = TERMINAL_OWNER.lock().unwrap_or_else(|e| e.into_inner());
+ if *owner == Some(std::thread::current().id()) {
+ *owner = None;
+ true
+ } else {
+ false
+ }
+}
+
+/// Install a panic hook that restores the terminal before the default hook
+/// prints the panic message, so the message lands on a normal, scrollable
+/// screen instead of being swallowed by the alternate buffer or mangled by
+/// raw mode's disabled line-editing. Call once, after `enable_raw_mode` and
+/// before `EnterAlternateScreen`, on the thread that runs the render loop; it
+/// claims the terminal for that thread (`TERMINAL_OWNER`). Does not call
+/// `std::process::exit`: unwinding continues exactly as it would have.
+fn install_panic_hook() {
+ *TERMINAL_OWNER.lock().unwrap_or_else(|e| e.into_inner()) =
+ Some(std::thread::current().id());
+ let default_hook = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ if release_terminal() {
+ restore_terminal_modes();
+ }
+ default_hook(info);
+ }));
+}
+
/// How long the dock advertises a finished copy.
const COPY_NOTICE: Duration = Duration::from_millis(1500);
/// Terminals cap the OSC 52 payload they will accept; past this the sequence is
@@ -9931,6 +10016,10 @@ pub async fn run(
log::set_max_level(log::LevelFilter::Off);
enable_raw_mode().map_err(|e| e.to_string())?;
+ // From here a panic must not leave the shell in raw mode / the alternate
+ // screen / mouse-tracking / Kitty keys: install before anything else that
+ // can panic runs, so every failure from this point is caught by it.
+ install_panic_hook();
// Under raw mode (so an OSC 11 reply is not echoed) but before the alternate
// screen, so a query the terminal ignores leaves no stray bytes on the frame.
theme::resolve_and_apply(theme_pref);
@@ -9940,12 +10029,32 @@ pub async fn run(
// resolved so it caches the right variant.
tokio::task::spawn_blocking(highlight::warm);
let mut stdout = io::stdout();
- execute!(stdout, EnterAlternateScreen, EnableBracketedPaste).map_err(|e| e.to_string())?;
+ // A startup error past `enable_raw_mode` returns to `main`, which prints it
+ // and exits: restore first, the same as the clean and panic exits, or the
+ // message lands on a raw-mode alternate screen.
+ let abort_startup = |e: io::Error| {
+ release_terminal();
+ restore_terminal_modes();
+ log::set_max_level(prev_log_level);
+ e.to_string()
+ };
+ execute!(stdout, EnterAlternateScreen, EnableBracketedPaste).map_err(abort_startup)?;
let modes = startup_modes(crate::core::agent::global_config::mouse_enabled());
let _ = stdout.write_all(modes.as_bytes());
let _ = stdout.flush();
+ // Test-only hook for the real-PTY panic-recovery integration test
+ // (`jan-cli/tests/tui_panic.rs`): an in-memory unit test can prove the hook
+ // fires, but only a genuine panic on a genuine terminal, with every mode
+ // above already turned on, proves the terminal is actually left clean.
+ // Gated on an env var rather than `#[cfg(test)]`: the test spawns the real
+ // `jan` binary (`CARGO_BIN_EXE_jan`), which is never built with cfg(test),
+ // so the trigger ships in every build. Setting it only crashes the caller's
+ // own session.
+ if std::env::var_os("JAN_TUI_PANIC_AFTER_RAW_MODE").is_some() {
+ panic!("JAN_TUI_PANIC_AFTER_RAW_MODE");
+ }
let backend = CrosstermBackend::new(stdout);
- let mut terminal = Terminal::new(backend).map_err(|e| e.to_string())?;
+ let mut terminal = Terminal::new(backend).map_err(abort_startup)?;
// A git repo enables workspace snapshots (rewind can restore files); a
// non-repo runs exactly as before with conversation-only rewind. With a
@@ -10074,16 +10183,8 @@ pub async fn run(
// process that exits now would lose it, and with it that turn's resume.
app.join_journal();
- let _ = disable_raw_mode();
- let _ = execute!(
- terminal.backend_mut(),
- DisableBracketedPaste,
- DisableMouseCapture,
- Print(KITTY_KEYS_OFF),
- Print(alt_scroll_restore()),
- LeaveAlternateScreen,
- );
- let _ = terminal.show_cursor();
+ release_terminal();
+ restore_terminal_modes();
log::set_max_level(prev_log_level);
// The session is closed: leave a copyable continuation command on the real
// terminal, the same line the non-interactive path prints after a save.
@@ -32950,6 +33051,18 @@ mod tests {
assert_eq!(KITTY_KEYS_OFF, "\x1b[<u", "the push must be popped on exit");
}
+ /// Only the render-loop thread's panic restores the terminal: a spawned
+ /// job's panic is a `JoinError` the loop survives, so it must not tear the
+ /// modes down under a live TUI. And the restore happens once.
+ #[test]
+ fn only_the_owning_thread_releases_the_terminal() {
+ *super::TERMINAL_OWNER.lock().unwrap() = Some(std::thread::current().id());
+ let other = std::thread::spawn(super::release_terminal).join().unwrap();
+ assert!(!other, "a job thread must not release the terminal");
+ assert!(super::release_terminal(), "the owner releases it");
+ assert!(!super::release_terminal(), "and only once");
+ }
+
/// Keyboard enhancement is not the mouse: it goes out whether or not
/// tracking is on, since the composer's editing keys depend on it.
#[test]