A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
pa-tui: drain the kitty stack past the alt-screen leave at exit (#3247)
Scott Cabrinha5784abc2aef5
diff --git a/crates/pa-cli/tests/kitty_exit_routes_e2e/main.rs b/crates/pa-cli/tests/kitty_exit_routes_e2e/main.rsindex 8c4e7074c3..6ea0d5e765 100644--- a/crates/pa-cli/tests/kitty_exit_routes_e2e/main.rs+++ b/crates/pa-cli/tests/kitty_exit_routes_e2e/main.rs@@ -63,6 +63,21 @@ use serde_json::{json, Value};const KITTY_FLAGS_PUSH: &[u8] = b"\x1b[>7u";/// The kitty flags pop (TS `ProcessTerminal.stop` / `drainInput`).const KITTY_FLAGS_POP: &[u8] = b"\x1b[<u";+/// The alternate-screen leave: the boundary a mode-counting relay+/// discards keyboard-protocol writes across (writes before it, made+/// while the pane's alt screen is up, never land on the relay's+/// stack).+const ALT_SCREEN_LEAVE: &[u8] = b"\x1b[?1049l";+/// The exit-tail stale-level drain (pa-tui `enhanced_keys`'s+/// `STALE_LEVEL_DRAIN`): the bare pops the exit writes AFTER the last+/// alt-screen leave. A mode-counting relay (herdr's pane emulator+/// re-encodes pane input from its own count of the push/pop pairs in+/// the pane output and never resets the count on foreground-program+/// exit) discards the pair's writes made inside the alt screen, so+/// only the post-leave drain lands — and the leftover level it clears+/// would otherwise turn every later Ctrl+C/Ctrl+D in the pane's shell+/// into a dead kitty CSI-u keypress.+const EXIT_POP_DRAIN: usize = 3;/// The probe's capability query.const KITTY_QUERY: &[u8] = b"\x1b[?u";/// The harness's answer: flags `1|2|4`, then primary device attributes.@@ -508,6 +523,30 @@ fn run_route(route: Route, known_terminal: bool) {"{}: the terminal's kitty-mode stack is {depth} deep after the exit — the shell receives CSI-u keys",route.name(),);+ // (1b) The exit-tail stale-level drain: the pops written after the+ // LAST alt-screen leave must cover the drain depth. A+ // mode-counting relay (herdr's pane emulator re-encodes pane input+ // from its own count of the push/pop pairs in the pane output and+ // never resets the count on foreground-program exit) discards the+ // pair's writes that land while the pane's alt screen is up — so+ // the teardown's own pop, written inside the alt screen, never+ // lands on the relay, and only post-leave pops (clamped no-ops at+ // spec depth zero) repair the leftover level that would otherwise+ // turn every later Ctrl+C/Ctrl+D in the pane's shell into a dead+ // kitty CSI-u keypress.+ let last_leave = find_subsequence_last(&stream, ALT_SCREEN_LEAVE)+ .unwrap_or_else(|| panic!("{}: the alt-screen leave never landed", route.name()));+ let mut pops_after_leave = 0usize;+ let mut at = last_leave;+ while let Some(hit) = find_subsequence_from(&stream, at, KITTY_FLAGS_POP) {+ pops_after_leave += 1;+ at = hit + 1;+ }+ assert!(+ pops_after_leave >= EXIT_POP_DRAIN,+ "{}: the exit wrote {pops_after_leave} pops after the last alt-screen leave — the stale-level drain never ran past the leave",+ route.name(),+ );// The exit code (the panic route dies on the unwind; everything// else ends clean).match route.expect_exit_code() {diff --git a/crates/pa-tui/src/enhanced_keys.rs b/crates/pa-tui/src/enhanced_keys.rsindex 89c45e6168..6c514ff9ce 100644--- a/crates/pa-tui/src/enhanced_keys.rs+++ b/crates/pa-tui/src/enhanced_keys.rs@@ -8,7 +8,10 @@//! alternate keys) when the terminal answers, and falls back to xterm//! modifyOtherKeys mode 2 (`\x1b[>4;2m`) when no kitty answer arrives in//! the fallback window. Teardown pops the kitty flags, resets-//! modifyOtherKeys, and disables bracketed paste in the same byte order.+//! modifyOtherKeys, and disables bracketed paste in the same byte+//! order; the exit tail (`exit_restore`) then drains the stack's stale+//! levels — bare pops after the alt-screen leave, clamped no-ops at+//! spec depth zero (see `STALE_LEVEL_DRAIN`).//!//! The kitty query runs on a probe thread that holds no UI state: it//! blocks inside crossterm's terminal support check until the terminal@@ -91,22 +94,32 @@ const DISABLE_BRACKETED_PASTE: &[u8] = b"\x1b[?2004l";/// Kitty keyboard protocol, flags `1|2|4` (TS `ProcessTerminal` writes the/// same set after the query answer).const ENABLE_KITTY_FLAGS: &[u8] = b"\x1b[>7u";-/// Pop the kitty flags stack at teardown (TS writes the bare pop).+/// Pop one level of the kitty flags stack (the bare form TS writes at+/// teardown).const POP_KITTY_FLAGS: &[u8] = b"\x1b[<u";-/// The stale-level drain before this process's own push (the-/// crashed-run hardening): a killed session never runs its teardown, so-/// its pushed level stays on the terminal's stack; every later session-/// in that terminal pushes once more and pops once — the stale level-/// survives every exit and the shell keeps receiving CSI-u escapes for-/// plain keys (the reported leak). The pre-pop drain (a bounded run of-/// pops before the push) clears EVERY stale level below this process's-/// own: the teardown pop then lands at depth zero regardless of the-/// entry depth. Pops against an empty stack are ignored (kitty spec),-/// so the drain is free on a clean terminal. The count covers a-/// killed-session pile-up (one wedge plus a couple of kill retries);-/// deeper stacks still self-heal one level per session run.-const PRE_POP_DRAIN: usize = 3;-const PRE_POP_KITTY_FLAGS: &[u8] = b"\x1b[<u";+/// The stale-level drain (the crashed-run and relay-accounting+/// hardening): a bounded run of bare pops. At the mount it runs BEFORE+/// the push: a killed session never runs its teardown, so its pushed+/// level stays on the terminal's stack; every later session in that+/// terminal pushes once more and pops once — the stale level survives+/// every exit and the shell keeps receiving CSI-u escapes for plain+/// keys (the reported leak). At the teardown it runs in the exit tail,+/// AFTER the alternate screen is left ([`pop_stale_levels`]): a+/// mode-counting relay — herdr's pane emulator re-encodes every+/// keystroke from its own count of the push/pop pairs in the pane+/// output, never resets the count on foreground-program exit, and+/// discards the pair's writes that land while the pane's alternate+/// screen is up — leaves the pane's stack one level deep after a plain+/// exit, and the leftover level turns every later Ctrl+C/Ctrl+D in the+/// pane's shell into a kitty CSI-u keypress no shell understands (the+/// live report, herdr 0.9.3: every exit left the pane one pop short;+/// pops written after the alt-screen leave survive, and one manual pop+/// repaired the pane). Pops against an empty stack are ignored (kitty+/// spec), so the drain is free on a clean terminal. The count covers a+/// killed-session pile-up (one wedge plus a couple of kill retries)+/// and the relay's miscount with margin; deeper stacks still self-heal+/// one level per session run.+const STALE_LEVEL_DRAIN: usize = 3;/// Reset xterm modifyOtherKeys (TS writes the reset at teardown; this port/// also writes it at every start — see the module docs for why the mode-2/// fallback is never armed here).@@ -316,11 +329,12 @@ pub(crate) fn enable(out: &mut Stdout) -> Result<()> {KITTY_PROBED.store(true, Ordering::SeqCst);record_kitty_supported();if !KITTY_ACTIVE.swap(true, Ordering::SeqCst) {- // The crashed-run hardening: clear a stale level- // left by a killed session before this process's- // own push (see PRE_POP_KITTY_FLAGS).- for _ in 0..PRE_POP_DRAIN {- write_all(out, PRE_POP_KITTY_FLAGS)?;+ // The stale-level drain: clear the levels a+ // killed session (or a miscounting relay) left+ // before this process's own push (see+ // STALE_LEVEL_DRAIN).+ for _ in 0..STALE_LEVEL_DRAIN {+ write_all(out, POP_KITTY_FLAGS)?;}write_all(out, ENABLE_KITTY_FLAGS)?;}@@ -338,11 +352,11 @@ pub(crate) fn enable(out: &mut Stdout) -> Result<()> {}KittyAction::PushFlags => {if !KITTY_ACTIVE.swap(true, Ordering::SeqCst) {- // The crashed-run hardening (see PRE_POP_KITTY_FLAGS):- // a suspend's pop and resume's re-push stay balanced; a+ // The stale-level drain (see STALE_LEVEL_DRAIN): a+ // suspend's pop and resume's re-push stay balanced; a// stale level from a killed session levels out here.- for _ in 0..PRE_POP_DRAIN {- write_all(out, PRE_POP_KITTY_FLAGS)?;+ for _ in 0..STALE_LEVEL_DRAIN {+ write_all(out, POP_KITTY_FLAGS)?;}write_all(out, ENABLE_KITTY_FLAGS)?;}@@ -535,15 +549,35 @@ fn enable_kitty(out: &mut Stdout) {return;}if !KITTY_ACTIVE.swap(true, Ordering::SeqCst) {- // The crashed-run hardening (see PRE_POP_KITTY_FLAGS): the probe+ // The stale-level drain (see STALE_LEVEL_DRAIN): the probe// answer's push drains the stale levels too.- for _ in 0..PRE_POP_DRAIN {- let _ = write_all(out, PRE_POP_KITTY_FLAGS);+ for _ in 0..STALE_LEVEL_DRAIN {+ let _ = write_all(out, POP_KITTY_FLAGS);}let _ = write_all(out, ENABLE_KITTY_FLAGS);}}+/// The exit tail's stale-level drain: [`STALE_LEVEL_DRAIN`] bare pops,+/// written after the alternate screen is left. A mode-counting relay+/// that tracks the keyboard protocol from the pane output discards the+/// pair's writes made while the pane's alt screen is up (herdr), so+/// the teardown's own pop — written inside the alt screen, where TS+/// writes it — never lands on the relay's stack, and the pane's shell+/// inherits the leftover level as dead Ctrl+C/Ctrl+D keys. The tail's+/// position is after the alt-screen leave on every exit route, where+/// the relay's accounting keeps the writes; the bare pops are clamped+/// no-ops at spec depth zero, so a clean terminal sees nothing change.+pub(crate) fn pop_stale_levels(out: &mut Stdout) {+ if !out.is_terminal() {+ return;+ }+ let _modes = lock_modes();+ for _ in 0..STALE_LEVEL_DRAIN {+ let _ = write_all(out, POP_KITTY_FLAGS);+ }+}+/// The probe thread: hold the query open for the TS fallback window,/// then settle. An answer within crossterm's patched 250ms query window/// enables kitty; no answer settles with no enhanced modes (this portdiff --git a/crates/pa-tui/src/exit_restore.rs b/crates/pa-tui/src/exit_restore.rsindex e088323285..08d6acfd5d 100644--- a/crates/pa-tui/src/exit_restore.rs+++ b/crates/pa-tui/src/exit_restore.rs@@ -17,13 +17,19 @@//! sync brackets or inside a styled write must not hand the shell a//! terminal holding pending updates or a dangling color;//! 5. the alternate screen is left (`?1049l`), the cursor shows;-//! 6. raw mode ends, and the tty is *verified* cooked — crossterm's+//! 6. the kitty stack drains its stale levels AFTER the alt-screen+//! leave ([`crate::enhanced_keys::pop_stale_levels`]) — a+//! mode-counting relay (herdr's pane emulator) discards the+//! keyboard-protocol writes made while the pane's alt screen is up,+//! so the pair's pop needs a post-leave drain to land on the relay+//! (the bare pops are clamped no-ops at spec depth zero);+//! 7. raw mode ends, and the tty is *verified* cooked — crossterm's//! `disable_raw_mode` restores its first-saved "original" and//! swallows errors, so a poisoned start (a killed previous run left//! the tty raw and crossterm adopted that state as the baseline)//! would silently restore raw ([`pa_types::platform::terminal`]'s//! `stty sane` reconstruction repairs it);-//! 7. a pending Ctrl+S output stop lifts FIRST — the stop is runtime+//! 8. a pending Ctrl+S output stop lifts FIRST — the stop is runtime//! state, not termios, and it HOLDS writes: the lift (the IXON-toggle,//! [`pa_types::platform::terminal::restart_output`]) must precede the//! restore's own output writes or the restore itself would hang on a@@ -94,6 +100,11 @@ pub(crate) fn restore_terminal() {// screen outside the module — a partial restore, a desynced flag —// would otherwise keep the alt buffer up past the process death).crate::altscreen::force_leave(&mut out);+ // The stale-level drain: bare kitty pops AFTER the alt-screen+ // leave, where a mode-counting relay keeps them — the drain's+ // own pop above, written inside the alt screen, does not (see+ // enhanced_keys::pop_stale_levels).+ crate::enhanced_keys::pop_stale_levels(&mut out);let _ = out.write_all(SYNC_OUTPUT_OFF);let _ = out.write_all(SGR_RESET);let _ = crossterm::execute!(out, crossterm::cursor::Show);@@ -125,6 +136,12 @@ pub(crate) fn terminal_release_tail(out: &mut Stdout) {// every write after it), hanging the release before the lift could// run — the exact stall the guard's progress windows exist to catch.pa_types::platform::terminal::restart_output();+ // The stale-level drain: bare kitty pops AFTER the alt-screen leave+ // (this tail runs past `flush_to_main_screen`'s `?1049l`), where a+ // mode-counting relay keeps them — the teardown's own pop, written+ // inside the alt screen, never lands on the relay's stack (see+ // enhanced_keys::pop_stale_levels).+ crate::enhanced_keys::pop_stale_levels(out);let _ = out.write_all(SYNC_OUTPUT_OFF);let _ = out.write_all(SGR_RESET);let _ = crossterm::execute!(out, crossterm::cursor::Show);