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.

fix(cli): restore the terminal when the TUI is stopped by SIGTTIN

James Dam4a3fb5ef6729
diff --git a/src-tauri/jan-cli/tests/tui_suspend.rs b/src-tauri/jan-cli/tests/tui_suspend.rs
index 6d2517fb0..122241a8c 100644
--- a/src-tauri/jan-cli/tests/tui_suspend.rs
+++ b/src-tauri/jan-cli/tests/tui_suspend.rs
@@ -61,12 +61,13 @@ impl Session {
}
}
- fn wait_stopped(&self) {
+ /// Wait for jan to stop, returning the signal that stopped it.
+ fn wait_stopped(&self) -> Signal {
let deadline = Instant::now() + DEADLINE;
loop {
let flags = WaitPidFlag::WUNTRACED | WaitPidFlag::WNOHANG;
match waitpid(self.pid, Some(flags)).expect("waitpid") {
- WaitStatus::Stopped(..) => return,
+ WaitStatus::Stopped(_, signal) => return signal,
WaitStatus::StillAlive => {}
other => panic!("jan did not stop: {other:?}: {:?}", self.text()),
}
@@ -90,11 +91,19 @@ impl Session {
/// Stop by `stop`, check the terminal is clean while stopped, resume, and
/// check the modes and raw mode come back.
fn cycle(&self, stop: impl FnOnce(), what: &str) {
+ self.cycle_with(stop, what, true);
+ }
+
+ /// `cycle`, optionally without the cooked-termios check while stopped;
+ /// returns the signal that stopped jan.
+ fn cycle_with(&self, stop: impl FnOnce(), what: &str, cooked_while_stopped: bool) -> Signal {
let before = self.text().len();
stop();
- self.wait_stopped();
+ let signal = self.wait_stopped();
self.wait_for(before, &LEAVE, &format!("{what}: modes restored before stopping"));
- assert!(!self.raw(), "{what}: the shell got a raw-mode terminal");
+ if cooked_while_stopped {
+ assert!(!self.raw(), "{what}: the shell got a raw-mode terminal");
+ }
let stopped_at = self.text().len();
kill(self.pid, Signal::SIGCONT).expect("SIGCONT");
self.wait_for(stopped_at, &ENTER, &format!("{what}: modes re-entered on resume"));
@@ -103,6 +112,7 @@ impl Session {
assert!(Instant::now() < deadline, "{what}: raw mode not re-enabled");
std::thread::sleep(Duration::from_millis(50));
}
+ signal
}
}
@@ -206,6 +216,29 @@ fn ctrl_z_and_sigtstp_suspend_and_resume_cleanly() {
assert!(session.alive(), "jan exited after resuming: {:?}", session.text());
}
+/// A read from the background (another group took the terminal's foreground)
+/// stops jan with SIGTTIN; the modes must be off before it stops and back on
+/// after SIGCONT, twice over, since the handler reinstalls itself. The kernel
+/// only sends SIGTTIN for a controlling terminal, which this PTY is not (that
+/// needs a session of jan's own), so the signal is sent directly: the same
+/// handler either way. Raw mode is not checked while stopped: the handler
+/// cannot `tcsetattr` from the background, and a job-control shell restores
+/// its own termios when it takes the terminal back.
+#[test]
+fn sigttin_restores_the_modes_and_resume_re_arms_them() {
+ let session = spawn();
+ session.wait_for(0, &ENTER, "the TUI to start");
+ for round in 1..=2 {
+ let signal = session.cycle_with(
+ || kill(session.pid, Signal::SIGTTIN).expect("SIGTTIN"),
+ &format!("SIGTTIN #{round}"),
+ false,
+ );
+ assert_eq!(signal, Signal::SIGTTIN, "round {round}: stopped for the real reason");
+ }
+ assert!(session.alive(), "jan exited after resuming: {:?}", session.text());
+}
+
/// With no job-control shell above it nothing would ever send SIGCONT, so
/// Ctrl-Z must refuse (and say so) rather than stop and hang the terminal.
#[test]
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index f7f8fa659..8d5cf4a1a 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -333,6 +333,140 @@ async fn await_stop_signal(signal: &mut StopSignal) {
pending().await
}
+/// Set by `on_tty_input_stop` once a SIGTTIN stop is continued, cleared when
+/// `rearm_after_tty_stop` has put the modes back.
+#[cfg(unix)]
+static TTY_REARM: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+/// A read from the background (another group took the terminal's foreground)
+/// stops jan with SIGTTIN, and by default with every mode still on: the shell
+/// prompt then fills with mouse reports. A plain `sigaction` handler rather
+/// than a tokio stream like SIGTSTP's: that registration is permanent, and a
+/// caught SIGTTIN no longer stops anything, so a background read outside
+/// `chat_loop` (startup, shutdown) would re-raise it in a tight loop forever.
+/// Installed once raw mode is on; `release_terminal` puts SIG_DFL back.
+#[cfg(unix)]
+fn install_tty_input_stop_handler() {
+ use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
+ let action = SigAction::new(
+ SigHandler::Handler(on_tty_input_stop),
+ SaFlags::SA_RESTART,
+ SigSet::empty(),
+ );
+ // SAFETY: the handler only makes async-signal-safe calls.
+ let _ = unsafe { sigaction(Signal::SIGTTIN, &action) };
+}
+
+#[cfg(unix)]
+fn reset_tty_input_stop_handler() {
+ use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
+ let action = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
+ // SAFETY: restoring the default disposition.
+ let _ = unsafe { sigaction(Signal::SIGTTIN, &action) };
+}
+
+/// Async-signal-safe only: one write of the restore bytes, then the real stop.
+/// No `disable_raw_mode`: from the background a `tcsetattr` raises SIGTTOU, and
+/// the termios is the new foreground's anyway -- a job-control shell restores
+/// its own when it takes the terminal back. `raise`, not the group-wide `kill`
+/// Ctrl-Z uses: the SIGTTIN that got here (the kernel's on a background read,
+/// or `stop_if_terminal_taken`'s) already went to the whole group, so a
+/// wrapper got its own copy; only this process caught it. The shell still
+/// reports `suspended (tty input)`. On SIGCONT the handler is reinstalled and
+/// the render loop re-arms the modes once jan holds the foreground again.
+#[cfg(unix)]
+extern "C" fn on_tty_input_stop(_: nix::libc::c_int) {
+ use nix::errno::Errno;
+ use nix::sys::signal::{
+ pthread_sigmask, raise, sigaction, SaFlags, SigAction, SigHandler, SigSet, SigmaskHow,
+ Signal,
+ };
+ let saved = Errno::last_raw();
+ let mut rest: &[u8] = &RESTORE_BYTES;
+ // Bounded: an EIO or a closed terminal ends it rather than looping.
+ for _ in 0..8 {
+ if rest.is_empty() {
+ break;
+ }
+ // SAFETY: writes from a static buffer.
+ let n =
+ unsafe { nix::libc::write(nix::libc::STDOUT_FILENO, rest.as_ptr().cast(), rest.len()) };
+ if n > 0 {
+ rest = &rest[n as usize..];
+ } else if n == 0 || Errno::last() != Errno::EINTR {
+ break;
+ }
+ }
+ let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
+ // SAFETY: async-signal-safe; the default action is what stops the process.
+ let _ = unsafe { sigaction(Signal::SIGTTIN, &default) };
+ let _ = raise(Signal::SIGTTIN);
+ // SIGTTIN is blocked while its handler runs; unblocking delivers the
+ // pending one, and the process stops here until SIGCONT.
+ let mut ttin = SigSet::empty();
+ ttin.add(Signal::SIGTTIN);
+ let _ = pthread_sigmask(SigmaskHow::SIG_UNBLOCK, Some(&ttin), None);
+ install_tty_input_stop_handler();
+ TTY_REARM.store(true, std::sync::atomic::Ordering::SeqCst);
+ Errno::set_raw(saved);
+}
+
+/// After a SIGTTIN stop, take the modes back as `suspend_to_shell` does after
+/// its SIGSTOP, but only once jan is the terminal's foreground again: a resume
+/// into the background (`bg`) leaves it pending. Returns whether the terminal
+/// is still not jan's, so the caller neither reads (that would only stop again)
+/// nor paints over the shell.
+#[cfg(unix)]
+fn rearm_after_tty_stop(app: &mut App, mouse: bool) -> bool {
+ use std::sync::atomic::Ordering;
+ if !TTY_REARM.load(Ordering::SeqCst) {
+ return false;
+ }
+ if !owns_terminal_foreground() {
+ return true;
+ }
+ TTY_REARM.store(false, Ordering::SeqCst);
+ // crossterm's enable is a no-op while it believes raw mode is on, and the
+ // handler could not turn it off; disable first so the termios is re-read.
+ let _ = disable_raw_mode();
+ if let Err(e) = enable_raw_mode().and_then(|()| enter_terminal_modes(&mut io::stdout(), mouse))
+ {
+ app.note(&format!("could not restore the terminal after a stop: {e}"));
+ }
+ app.request_repaint();
+ false
+}
+
+/// Another group holds the terminal's foreground: stop now, from the render
+/// loop, instead of on the next read. A stop inside crossterm's blocking read
+/// resumes into that same read, so after `fg` the TUI would stay off-screen
+/// until a key arrived; stopped here, the next pass re-arms at once. Sent to
+/// the whole group, as the kernel's own SIGTTIN is, so a wrapper stops too;
+/// jan's copy goes through the handler, so the same restore and the same
+/// `suspended (tty input)`. Returns whether it stopped (or tried to: in an
+/// orphaned group the stop is discarded, and `TTY_REARM` keeps the loop from
+/// trying again).
+#[cfg(unix)]
+fn stop_if_terminal_taken() -> bool {
+ use nix::sys::signal::{kill, Signal};
+ if owns_terminal_foreground() {
+ return false;
+ }
+ let _ = kill(nix::unistd::Pid::from_raw(0), Signal::SIGTTIN);
+ true
+}
+
+/// Whether jan's group is the foreground of the terminal it draws to. An
+/// unreadable answer counts as yes: re-arming wrongly only means the next read
+/// stops again, where waiting wrongly would freeze the session.
+#[cfg(unix)]
+fn owns_terminal_foreground() -> bool {
+ // libc directly: nix's wrapper sits behind its `term` feature.
+ // SAFETY: a plain query on stdout's descriptor.
+ let fg = unsafe { nix::libc::tcgetpgrp(nix::libc::STDOUT_FILENO) };
+ fg < 0 || fg == nix::unistd::getpgrp().as_raw()
+}
+
/// Raw escape sequences standing in for the `crossterm::Command` types used
/// elsewhere (`DisableBracketedPaste`, `DisableMouseCapture`,
/// `LeaveAlternateScreen`, cursor show): `restore_terminal_modes` has no
@@ -349,6 +483,46 @@ const DISABLE_MOUSE_CAPTURE: &str = "\x1b[?1006l\x1b[?1002l\x1b[?1000l";
const LEAVE_ALT_SCREEN: &str = "\x1b[?1049l";
const SHOW_CURSOR: &str = "\x1b[?25h";
+/// What `write_restore` writes, as one static buffer for the SIGTTIN handler,
+/// which cannot format or allocate. Built from the same constants; a test
+/// pins the two together. Unix only, like the handler (Windows omits the
+/// alternate-scroll restore).
+#[cfg(unix)]
+const RESTORE_PARTS: [&str; 7] = [
+ END_SYNC_UPDATE,
+ DISABLE_BRACKETED_PASTE,
+ DISABLE_MOUSE_CAPTURE,
+ KITTY_KEYS_OFF,
+ ALT_SCROLL_RESTORE,
+ LEAVE_ALT_SCREEN,
+ SHOW_CURSOR,
+];
+#[cfg(unix)]
+const RESTORE_LEN: usize = {
+ let (mut n, mut i) = (0, 0);
+ while i < RESTORE_PARTS.len() {
+ n += RESTORE_PARTS[i].len();
+ i += 1;
+ }
+ n
+};
+#[cfg(unix)]
+static RESTORE_BYTES: [u8; RESTORE_LEN] = {
+ let mut out = [0u8; RESTORE_LEN];
+ let (mut at, mut i) = (0, 0);
+ while i < RESTORE_PARTS.len() {
+ let part = RESTORE_PARTS[i].as_bytes();
+ let mut j = 0;
+ while j < part.len() {
+ out[at] = part[j];
+ at += 1;
+ j += 1;
+ }
+ i += 1;
+ }
+ out
+};
+
/// 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
@@ -366,6 +540,10 @@ fn release_terminal() -> bool {
let mut owner = TERMINAL_OWNER.lock().unwrap_or_else(|e| e.into_inner());
if *owner == Some(std::thread::current().id()) {
*owner = None;
+ // Back to the default stop, so whatever runs after the session (the
+ // resume hint, a panic message) behaves like any other program.
+ #[cfg(unix)]
+ reset_tty_input_stop_handler();
true
} else {
false
@@ -12903,6 +13081,8 @@ pub async fn run(
// 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();
+ #[cfg(unix)]
+ install_tty_input_stop_handler();
// 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);
@@ -13321,6 +13501,12 @@ async fn chat_loop<B: Backend>(
let sync_output = use_synchronized_output();
while !app.should_quit {
+ // Back from a SIGTTIN stop (`on_tty_input_stop`): re-arm the modes once
+ // the terminal is ours, and draw nothing until then.
+ #[cfg(unix)]
+ let mut tty_away = rearm_after_tty_stop(app, mouse);
+ #[cfg(not(unix))]
+ let tty_away = false;
// Drive the snapshot queue: run one job off-loop at a time. A job whose
// inputs no longer resolve (snapshots disabled) is dropped.
if snap_task.is_none() {
@@ -13601,7 +13787,9 @@ async fn chat_loop<B: Backend>(
since_last: last_frame.map(|t| t.elapsed()),
};
let draw_now = gate.due();
- if draw_now {
+ // A held frame stays dirty and is retried on the next tick; `deferred`
+ // below only covers `!draw_now`, so this cannot wake the loop early.
+ if draw_now && !tty_away {
if sync_output {
let _ = execute!(io::stdout(), BeginSynchronizedUpdate);
}
@@ -13659,7 +13847,12 @@ async fn chat_loop<B: Backend>(
if app.refresh_shell_tail() {
idle_tick = false;
}
- while event::poll(Duration::ZERO).unwrap_or(false) {
+ #[cfg(unix)]
+ if !tty_away && stop_if_terminal_taken() {
+ tty_away = true;
+ }
+ // The terminal is not ours: a read would only stop again.
+ while !tty_away && event::poll(Duration::ZERO).unwrap_or(false) {
// Input draws at once, past the frame cap: typing must not
// wait on output pacing.
idle_tick = false;
@@ -39342,6 +39535,29 @@ mod tests {
}
}
+ /// The SIGTTIN handler cannot format, so it writes a prebuilt copy of the
+ /// restore; it must stay byte-for-byte what every other exit writes.
+ #[cfg(unix)]
+ #[test]
+ fn tty_stop_restore_bytes_match_write_restore() {
+ let mut restored = Vec::new();
+ super::write_restore(&mut restored);
+ assert_eq!(
+ String::from_utf8_lossy(&super::RESTORE_BYTES),
+ String::from_utf8_lossy(&restored)
+ );
+ }
+
+ /// Nothing pending: the render loop draws as normal and makes no syscall.
+ #[cfg(unix)]
+ #[test]
+ fn no_tty_stop_means_nothing_to_rearm() {
+ let mut app = test_app();
+ super::TTY_REARM.store(false, std::sync::atomic::Ordering::SeqCst);
+ assert!(!super::rearm_after_tty_stop(&mut app, true));
+ assert!(!app.repaint, "no repaint without a stop");
+ }
+
/// Raw mode keeps the terminal from turning Ctrl-Z into SIGTSTP, so it
/// arrives as a key: only that press suspends, not a plain `z` or a
/// release, and it is not advertised as anything else.