A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix Shift+Enter on Ghostty (#3398)
Florian Brand49480faa0295
diff --git a/crates/pa-cli/tests/chat_open_first_frame_pty_e2e.rs b/crates/pa-cli/tests/chat_open_first_frame_pty_e2e.rsindex 4e52fd61e2..f73a8eb3ba 100644--- a/crates/pa-cli/tests/chat_open_first_frame_pty_e2e.rs+++ b/crates/pa-cli/tests/chat_open_first_frame_pty_e2e.rs@@ -78,15 +78,25 @@ fn chat_open_first_frame_pins_the_first_paint() {// The one complete frame: transcript, title row, and dock row all land;// each wait is an observable-readiness barrier, not a wall-clock window.harness.wait_from_start("settled answer", "the transcript painted");- harness.wait_from_start("layout probe", "the pinned title row painted");+ harness.wait_from_start("probe", "the pinned title row painted");harness.wait_from_start("\u{25f7} 1 heartbeat", "the dock panel painted");+ harness.wait_from_start("\x1b[>7u", "the kitty keyboard flags enabled");// Let the surface settle so the audit covers every repaint the open can produce, then read the// whole byte stream.harness.drain_until_quiet(10);let collected = harness.output();+ harness.finish();let stream: &[u8] = &collected;+ // Ghostty stores keyboard flags per screen. Enable them after the completed first+ // paint, so setup cannot arm the primary screen or flush an empty alternate screen.+ let entered = find_subsequence(stream, b"\x1b[?1049h").expect("alternate screen entered");+ let painted = find_subsequence(stream, b"\x1b[?2026l").expect("first paint completed");+ let enabled = find_subsequence(stream, b"\x1b[>7u").expect("kitty flags enabled");+ assert!(entered < painted && painted < enabled);+ assert_eq!(count_occurrences(stream, b"\x1b[>7u"), 1);+// The brand splash never paints (no flash, no one-row shift under the title).assert!(find_subsequence(stream, b"prime agent").is_none(),@@ -109,8 +119,6 @@ fn chat_open_first_frame_pins_the_first_paint() {find_subsequence(stream, "\u{25f7} 1 heartbeat".as_bytes()).is_some(),"the dock's heartbeat panel row painted");-- harness.finish();}/// Whether this runner is attached to a controlling-terminal session (the@@ -277,7 +285,13 @@ fn spawn_child(socket: &std::path::Path, slave: &OwnedFd) -> Child {.arg("--exact").arg("chat_open_first_frame_child_mode").env(CHILD_SOCKET_ENV, socket)+ .env("TERM", "xterm-ghostty")+ .env("TERM_PROGRAM", "ghostty").env_remove("TMUX")+ .env_remove("STY")+ .env_remove("ZELLIJ")+ .env_remove("SSH_CONNECTION")+ .env_remove("SSH_TTY").stdin(slave_as_stdio(slave)).stdout(slave_as_stdio(slave)).stderr(slave_as_stdio(slave));diff --git a/crates/pa-tui/src/app.rs b/crates/pa-tui/src/app.rsindex 1145f474d6..788ebd2b6c 100644--- a/crates/pa-tui/src/app.rs+++ b/crates/pa-tui/src/app.rs@@ -249,7 +249,8 @@ pub(crate) fn draw(// The mount sequences (the alt-screen adopt/enter, the queued clear, the cursor hide) ride// THIS draw's single flush: the first paint is the mount, and a mid-gap flush can never// carry the clear out early over it.- if crate::altscreen::take_first_draw_mount() {+ let mounting = crate::altscreen::take_first_draw_mount();+ if mounting {let mut out = std::io::stdout();crate::altscreen::enter_queued(&mut out)?;crossterm::queue!(@@ -309,7 +310,12 @@ pub(crate) fn draw(// Always release the terminal's pending update, including on paint errors.crossterm::execute!(stdout(), terminal::EndSynchronizedUpdate)?;painted?;- markers+ markers?;+ if mounting {+ // Mode setup flushes stdout, so it must follow the completed first paint.+ crate::enhanced_keys::enable(&mut stdout())?;+ }+ Ok(())}/// Write OSC 133 zone-marker sequences at their frame rows. The sequences are zero-width: onlydiff --git a/crates/pa-tui/src/enhanced_keys.rs b/crates/pa-tui/src/enhanced_keys.rsindex 89463b929f..8a34e3373f 100644--- a/crates/pa-tui/src/enhanced_keys.rs+++ b/crates/pa-tui/src/enhanced_keys.rs@@ -60,19 +60,9 @@//! 250ms — measured: the raced suspend's teardown waits to ~250ms on a//! silent pty and lands at its dispatch on every answered class).//!-//! DIVERGENCE FROM TS (the shift-modified printable bug class): this port-//! never arms modifyOtherKeys mode 2 and instead resets it-//! (`\x1b[>4;0m`) at every surface start. TS parses the resulting-//! `CSI 27;<mods>;<key>~` sequences itself (keys.ts-//! `parseModifyOtherKeysSequence`), but crossterm 0.28 has no case for-//! them and drops the whole pending input buffer on the parse error-//! (`Parser::advance` clears on `Err`) — a terminal in mode 2 (a sticky-//! mode any other pane or process may have armed) makes shift-modified-//! printables like `shift+=` vanish entirely. The reset returns such-//! terminals to legacy encodings (shift+= arrives as the produced `+`),-//! and the kitty path covers the enhanced-reporting surface crossterm-//! can parse (kitty CSI-u with shifted alternates resolves to the-//! produced character in crossterm's own parser).+//! We reset modifyOtherKeys mode 2 at each surface start to keep legacy+//! printable-key behavior. Some terminals still emit modifyOtherKeys for+//! modified control keys; the vendored parser accepts those reports.//!//! Every mode-flag transition is serialized (a module-wide lock pairs each//! flag write with its escape write), and the force-quit exit path marks@@ -151,10 +141,10 @@ fn lock_modes() -> std::sync::MutexGuard<'static, ()> {.unwrap_or_else(std::sync::PoisonError::into_inner)}-/// Whether the kitty probe's answer window is open. The input reader keys-/// its bounded poll cadence on this so its park cannot starve the probe.-pub(crate) fn query_in_flight() -> bool {- QUERY_IN_FLIGHT.load(Ordering::SeqCst)+/// Whether Kitty setup or its probe is pending. Keep input polls bounded even+/// before the first draw starts the probe, so an idle reader cannot starve it.+pub(crate) fn kitty_probe_pending() -> bool {+ !KITTY_PROBED.load(Ordering::SeqCst) || QUERY_IN_FLIGHT.load(Ordering::SeqCst)}/// Mark the terminal released for process exit, before writing the restore@@ -283,6 +273,11 @@ pub(crate) fn enable(out: &mut Stdout) -> Result<()> {write_all(out, ENABLE_BRACKETED_PASTE)?;}write_all(out, MODIFY_OTHER_KEYS_RESET)?;+ // Ghostty keeps keyboard flags per screen. The first draw enables Kitty once+ // the alternate screen is painted; bracketed paste is already safe to enable.+ if !crate::altscreen::active() {+ return Ok(());+ }match kitty_action(KITTY_SUPPORTED.load(Ordering::SeqCst),KITTY_PROBED.load(Ordering::SeqCst),@@ -296,7 +291,7 @@ pub(crate) fn enable(out: &mut Stdout) -> Result<()> {KeyboardCapability::Supported => {KITTY_PROBED.store(true, Ordering::SeqCst);record_kitty_supported();- if !KITTY_ACTIVE.swap(true, Ordering::SeqCst) {+ if !KITTY_ACTIVE.load(Ordering::SeqCst) {// The stale-level drain: clear the levels a// killed session (or a miscounting relay) left// before this process's own push (see@@ -305,6 +300,7 @@ pub(crate) fn enable(out: &mut Stdout) -> Result<()> {write_all(out, POP_KITTY_FLAGS)?;}write_all(out, ENABLE_KITTY_FLAGS)?;+ KITTY_ACTIVE.store(true, Ordering::SeqCst);}}KeyboardCapability::Unsupported => {@@ -319,7 +315,7 @@ pub(crate) fn enable(out: &mut Stdout) -> Result<()> {}}KittyAction::PushFlags => {- if !KITTY_ACTIVE.swap(true, Ordering::SeqCst) {+ if !KITTY_ACTIVE.load(Ordering::SeqCst) {// 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.@@ -327,6 +323,7 @@ pub(crate) fn enable(out: &mut Stdout) -> Result<()> {write_all(out, POP_KITTY_FLAGS)?;}write_all(out, ENABLE_KITTY_FLAGS)?;+ KITTY_ACTIVE.store(true, Ordering::SeqCst);}}KittyAction::None => {}@@ -487,13 +484,13 @@ fn enable_kitty(out: &mut Stdout) {if EXIT_RELEASE.load(Ordering::SeqCst) {return;}- if !KITTY_ACTIVE.swap(true, Ordering::SeqCst) {+ if !KITTY_ACTIVE.load(Ordering::SeqCst) {// The stale-level drain (see STALE_LEVEL_DRAIN): the probe// answer's push drains the stale levels too.for _ in 0..STALE_LEVEL_DRAIN {let _ = write_all(out, POP_KITTY_FLAGS);}- let _ = write_all(out, ENABLE_KITTY_FLAGS);+ KITTY_ACTIVE.store(write_all(out, ENABLE_KITTY_FLAGS).is_ok(), Ordering::SeqCst);}}diff --git a/crates/pa-tui/src/input.rs b/crates/pa-tui/src/input.rsindex e5160f2690..90e67eae51 100644--- a/crates/pa-tui/src/input.rs+++ b/crates/pa-tui/src/input.rs@@ -112,10 +112,10 @@ where// The wait never runs past a held escape sequence's deadline (the guard flushes on the// next wake); otherwise the reader parks edge-driven on real input, so an idle surface// costs no wakeups. Two bounded exceptions: a held sequence's flush deadline, and the- // kitty probe's answer window (`query_in_flight`), whose slices must interleave through- // crossterm's process-global event-reader lock.+ // Kitty setup and its answer window: an indefinite park before the first draw+ // would hold crossterm's reader lock and prevent the deferred probe from reading replies.let timeout = guard.poll_deadline(Instant::now()).or_else(|| {- if thread_waker.is_none() || crate::enhanced_keys::query_in_flight() {+ if thread_waker.is_none() || crate::enhanced_keys::kitty_probe_pending() {Some(Duration::from_millis(POLL_TIMEOUT_MS))} else {Nonediff --git a/crates/pa-tui/src/interactive/render.rs b/crates/pa-tui/src/interactive/render.rsindex a5b3ca361e..94b6120b44 100644--- a/crates/pa-tui/src/interactive/render.rs+++ b/crates/pa-tui/src/interactive/render.rs@@ -187,9 +187,8 @@ impl Renderer {if mouse {crate::mouse_tracking::enable(&mut std::io::stdout())?;}- // Bracketed paste and the kitty keyboard protocol come up with the raw-mode- // bracket: pastes arrive as one chunk, and the kitty probe (once per process —- // see `enhanced_keys`) runs before the reader thread starts polling.+ // Enable bracketed paste before the reader starts. On a fresh alternate+ // screen, Kitty setup waits until the first draw finishes painting.crate::enhanced_keys::enable(&mut std::io::stdout())?;spawn_session_reader(ui_tx.clone(), exit_guard.clone());let terminal = Terminal::new(crate::hyperlinks::stdout_backend())?;diff --git a/crates/pa-tui/src/sequence_guard.rs b/crates/pa-tui/src/sequence_guard.rsindex 6d978a7d86..07b73f7542 100644--- a/crates/pa-tui/src/sequence_guard.rs+++ b/crates/pa-tui/src/sequence_guard.rs@@ -518,12 +518,29 @@ fn parse_kind(kind: u8) -> KeyEventKind {}}-/// The tilde forms: navigation and function keys; every other number (paste-/// markers included) is consumed.+/// The tilde forms: navigation, function keys, and modifyOtherKeys reports.+/// Other forms, including paste markers, are consumed.fn tilde_key(body: &[u8]) -> Option<Event> {let text = std::str::from_utf8(body).ok()?;let mut fields = text.split(';');let first: u8 = fields.next()?.parse().ok()?;+ // Ghostty uses modifyOtherKeys for Shift+Enter when Kitty is inactive.+ if first == 27 {+ let modifiers = parse_modifiers(fields.next()?.parse().ok()?);+ let codepoint = fields.next()?.parse().ok()?;+ if fields.next().is_some() {+ return None;+ }+ let code = match char::from_u32(codepoint)? {+ '\r' => KeyCode::Enter,+ '\x1b' => KeyCode::Esc,+ '\t' if modifiers.contains(KeyModifiers::SHIFT) => KeyCode::BackTab,+ '\t' => KeyCode::Tab,+ '\x7f' => KeyCode::Backspace,+ c => KeyCode::Char(c),+ };+ return Some(Event::Key(KeyEvent::new(code, modifiers)));+ }let (modifiers, kind) = match fields.next() {Some(mods_field) => {let mut parts = mods_field.split(':');diff --git a/crates/pa-tui/src/sequence_guard/tests.rs b/crates/pa-tui/src/sequence_guard/tests.rsindex 9ac1737919..07c2e1ce43 100644--- a/crates/pa-tui/src/sequence_guard/tests.rs+++ b/crates/pa-tui/src/sequence_guard/tests.rs@@ -331,6 +331,10 @@ fn model_parse(buf: &[u8], more: bool) -> ModelParse {))),}}+ b'~' if payload == b"27;2;13~" => ModelParse::Event(Event::Key(KeyEvent::new(+ KeyCode::Enter,+ KeyModifiers::SHIFT,+ ))),b'~' if payload == b"200~" || payload == b"201~" => ModelParse::Invalid,_ => ModelParse::Invalid,}@@ -885,6 +889,35 @@ fn a_split_kitty_shift_enter_arrives_as_the_shift_enter_key() {);}+#[test]+fn modify_other_keys_shift_enter_survives_every_read_boundary() {+ let input = b"a\x1b[27;2;13~b";+ for split in 0..=input.len() {+ let events = leaks(&run_guard(read_projection(input, &[split])));+ assert_eq!(+ events,+ vec![+ char_press('a'),+ Event::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT)),+ char_press('b'),+ ],+ "split at {split}"+ );+ let mut editor = crate::editor::Editor::new();+ for event in events {+ let Event::Key(key) = event else {+ unreachable!("key events asserted above");+ };+ editor.handle_input(&crate::keys::key_event_to_id(&key).expect("key id"));+ }+ assert_eq!(editor.get_lines(), vec!["a", "b"], "split at {split}");+ assert!(editor+ .take_events()+ .iter()+ .all(|event| !matches!(event, crate::editor::EditorEvent::Submitted(_))));+ }+}+/// The composed seam: a split kitty shift+enter reassembles, decodes to the `shift+enter` key id,/// and lands in the editor as a newline — never a submit.#[test]diff --git a/vendor/crossterm/src/event/sys/unix/parse.rs b/vendor/crossterm/src/event/sys/unix/parse.rsindex 0278856975..d510438480 100644--- a/vendor/crossterm/src/event/sys/unix/parse.rs+++ b/vendor/crossterm/src/event/sys/unix/parse.rs@@ -627,6 +627,26 @@ pub(crate) fn parse_csi_special_key_code(buffer: &[u8]) -> io::Result<Option<Int// This CSI sequence can be a list of semicolon-separated numbers.let first = next_parsed::<u8>(&mut split)?;+ // Ghostty emits modifyOtherKeys for modified control keys when Kitty is inactive.+ if first == 27 {+ let modifiers = parse_modifiers(next_parsed::<u8>(&mut split)?);+ let codepoint = next_parsed::<u32>(&mut split)?;+ if split.next().is_some() {+ return Err(could_not_parse_event_error());+ }+ let keycode = match char::from_u32(codepoint).ok_or_else(could_not_parse_event_error)? {+ '\r' => KeyCode::Enter,+ '\x1b' => KeyCode::Esc,+ '\t' if modifiers.contains(KeyModifiers::SHIFT) => KeyCode::BackTab,+ '\t' => KeyCode::Tab,+ '\x7f' => KeyCode::Backspace,+ c => KeyCode::Char(c),+ };+ return Ok(Some(InternalEvent::Event(Event::Key(KeyEvent::new(+ keycode, modifiers,+ )))));+ }+let (modifiers, kind, state) =if let Ok((modifier_mask, kind_code)) = modifier_and_kind_parsed(&mut split) {(@@ -1464,6 +1484,33 @@ mod tests {);}+ #[test]+ fn test_parse_modify_other_keys() {+ for (sequence, code, modifiers) in [+ ("\x1b[27;2;13~", KeyCode::Enter, KeyModifiers::SHIFT),+ ("\x1b[27;5;13~", KeyCode::Enter, KeyModifiers::CONTROL),+ ("\x1b[27;3;27~", KeyCode::Esc, KeyModifiers::ALT),+ ("\x1b[27;2;9~", KeyCode::BackTab, KeyModifiers::SHIFT),+ ("\x1b[27;5;9~", KeyCode::Tab, KeyModifiers::CONTROL),+ ("\x1b[27;3;127~", KeyCode::Backspace, KeyModifiers::ALT),+ ("\x1b[27;5;97~", KeyCode::Char('a'), KeyModifiers::CONTROL),+ ] {+ assert_eq!(+ parse_event(sequence.as_bytes(), false).unwrap(),+ Some(InternalEvent::Event(Event::Key(KeyEvent::new(+ code, modifiers+ )))),+ "{sequence:?}"+ );+ }+ for sequence in ["\x1b[27;2~", "\x1b[27;2;13;13~", "\x1b[27;2;1114112~"] {+ assert!(+ parse_event(sequence.as_bytes(), false).is_err(),+ "{sequence:?}"+ );+ }+ }+#[test]fn test_parse_csi_special_key_code_with_types() {assert_eq!(