Skip to content

macOS: SGR mouse reports become Escape + literal text during rapid scrolling (still reproducible in 0.167.1) #60814

Closed as duplicate

Description

@marakulin-a

Rapid wheel scrolling still leaks SGR mouse-report text into the composer and can interrupt an active turn in Codex CLI 0.167.1 on macOS.

This is a follow-up to #49184, which was closed as fixed in 0.159.0. This report adds a reproducible Unix read-boundary failure in Codex's pinned crossterm fork, a candidate patch, and regression tests.

Environment and observed behavior

  • Codex CLI 0.167.1, default fullscreen TUI
  • macOS 26.7.1 (25G241), Apple Silicon
  • agterm 0.40.0, Logitech MX Master 4
  • Mos 4.2.1 smooth scrolling and Logi Options+ were running during manual reproduction. I have not separately ruled them out by disabling them; the library reproducer below does not use either application or a physical mouse.

Rapid wheel/free-spin scrolling sometimes inserts text such as <65;103;75M into the composer and can interrupt an active turn without an intentional Escape press. --no-alt-screen appeared to avoid the symptom in my manual trials.

Steps to reproduce and expected behavior

  1. Start Codex CLI 0.167.1 in its default fullscreen TUI in agterm.
  2. Open a conversation with enough history to scroll; to observe the interruption symptom, scroll while a turn is running.
  3. Rapidly spin the mouse wheel, particularly in free-spin mode.
  4. Intermittently, mouse-report tails such as <65;103;75M appear in the composer; an active turn can also be interrupted without pressing Escape.

Expected: scrolling moves the transcript without inserting text or sending an Escape key to the application.

The manual reproduction is intermittent. The regression tests below reproduce the underlying read-boundary error deterministically without a physical mouse.

Unix read-boundary failure

Codex 0.167.1 pins openai-oss-forks/crossterm at ed1cdab335221515706178d68495bba2aed1924f.

Both Unix readers (mio.rs, tty.rs) pass read_count == TTY_BUFFER_SIZE as the parser's more flag. A short read is therefore treated as the end of available input, although it can split an escape sequence immediately after its initial ESC.

When that happens, the parser emits a standalone KeyCode::Esc; the remaining [<65;103;75M becomes ordinary key input. That false Escape can reach Codex's interrupt handling. This demonstrates a mechanism consistent with the observed interruption, rather than proving that every interruption has this cause.

In a raw macOS PTY experiment, requests for 1024 bytes repeatedly returned 1022-byte chunks. Feeding 12,000 valid SGR wheel reports produced 12 short reads ending immediately after ESC, with no input bytes lost.

A small Rust probe using crossterm::event::read() counted the following events when fed those reports through a real PTY:

Dependency Wheel events Escape keys Character keys
Pinned fork, unchanged 11,988 12 144
Candidate patch 12,000 0 0

These are library/PTY measurements, not an automated reproduction of the entire Codex UI.

Candidate fix and regression coverage

Use the existing Parser::buffer_external_input() in both readers instead of calling advance(..., read_count == TTY_BUFFER_SIZE). It retains a trailing ESC and uses the existing 20 ms ambiguity deadline. The readers already handle that deadline and prefer a readable continuation over expiring it. A genuine standalone Escape may consequently wait for that disambiguation interval.

The attached inline patch includes a deterministic regression test: write x followed by ESC into a UnixStream, consume x, then write [<65;103;75M; the next event must be a wheel event. No physical scrolling or PTY chunk-size assumption is needed for this test.

Additional tests cover every split position for SGR, arrow and Alt sequences, standalone ESC at 1022/1024-byte boundaries, a queued continuation after the deadline, and bracketed paste. All five added tests fail against the unchanged readers in both backends. With the patch, each of these commands passed with 147 passed, 0 failed, 7 ignored:

cargo test --lib --features event-stream -- --test-threads=1
cargo test --lib --features event-stream,use-dev-tty -- --test-threads=1

A locally built Codex 0.167.1 using the parser patch also stopped showing raw mouse-report text during my manual scrolling trial. This is limited manual validation, not a claim of comprehensive cross-platform coverage.

Candidate crossterm patch, including regression tests (apply at the pinned fork root)
--- a/src/event/source/unix/mio.rs
+++ b/src/event/source/unix/mio.rs
@@ -110,10 +110,10 @@
                             match self.tty_fd.read(&mut self.tty_buffer) {
                                 Ok(read_count) => {
                                     if read_count > 0 {
-                                        self.parser.advance(
-                                            &self.tty_buffer[..read_count],
-                                            read_count == TTY_BUFFER_SIZE,
-                                        );
+                                        // A short read can still split an escape sequence. Preserve a
+                                        // trailing ESC until its continuation or ambiguity timeout.
+                                        self.parser
+                                            .buffer_external_input(&self.tty_buffer[..read_count]);
                                     }
                                 }
                                 Err(e) => {
@@ -432,6 +432,10 @@
 }
 
 #[cfg(test)]
+#[path = "../fragmented_input_tests.rs"]
+mod fragmented_input_tests;
+
+#[cfg(test)]
 #[path = "../secondary_device_attributes_tests.rs"]
 mod secondary_device_attributes_tests;
 
--- a/src/event/source/unix/tty.rs
+++ b/src/event/source/unix/tty.rs
@@ -158,10 +158,10 @@
                 loop {
                     let read_count = read_complete(&self.tty, &mut self.tty_buffer)?;
                     if read_count > 0 {
-                        self.parser.advance(
-                            &self.tty_buffer[..read_count],
-                            read_count == TTY_BUFFER_SIZE,
-                        );
+                        // A short read can still split an escape sequence. Preserve a
+                        // trailing ESC until its continuation or ambiguity timeout.
+                        self.parser
+                            .buffer_external_input(&self.tty_buffer[..read_count]);
                     }
 
                     if let Some(event) = self.parser.next() {
@@ -479,6 +479,10 @@
 }
 
 #[cfg(test)]
+#[path = "../fragmented_input_tests.rs"]
+mod fragmented_input_tests;
+
+#[cfg(test)]
 #[path = "../secondary_device_attributes_tests.rs"]
 mod secondary_device_attributes_tests;
 
--- /dev/null
+++ b/src/event/source/fragmented_input_tests.rs
@@ -0,0 +1,148 @@
+//! Regression coverage for escape sequences split across ordinary Unix reads.
+
+use super::UnixInternalEventSource;
+use crate::event::{
+    Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind, internal::InternalEvent,
+    source::EventSource,
+};
+use crate::terminal::sys::file_descriptor::FileDesc;
+use std::{
+    io::Write,
+    os::unix::net::UnixStream,
+    time::{Duration, Instant},
+};
+
+fn source_with_input() -> (UnixInternalEventSource, UnixStream) {
+    let (reader, writer) = UnixStream::pair().unwrap();
+    #[cfg(feature = "libc")]
+    let reader = {
+        use std::os::fd::IntoRawFd;
+        FileDesc::new(reader.into_raw_fd(), true)
+    };
+    #[cfg(not(feature = "libc"))]
+    let reader = FileDesc::Owned(reader.into());
+    (
+        UnixInternalEventSource::from_file_descriptor(reader).unwrap(),
+        writer,
+    )
+}
+
+fn key(code: KeyCode) -> InternalEvent {
+    InternalEvent::Event(Event::Key(code.into()))
+}
+
+fn wheel() -> InternalEvent {
+    InternalEvent::Event(Event::Mouse(MouseEvent {
+        kind: MouseEventKind::ScrollDown,
+        column: 102,
+        row: 74,
+        modifiers: KeyModifiers::NONE,
+    }))
+}
+
+fn read(source: &mut UnixInternalEventSource) -> Option<InternalEvent> {
+    source.try_read(Some(Duration::from_secs(1))).unwrap()
+}
+
+#[test]
+fn mouse_report_survives_short_read_after_escape() {
+    let (mut source, mut writer) = source_with_input();
+    writer.write_all(b"x\x1b").unwrap();
+    assert_eq!(read(&mut source), Some(key(KeyCode::Char('x'))));
+    writer.write_all(b"[<65;103;75M").unwrap();
+    assert_eq!(read(&mut source), Some(wheel()));
+}
+
+#[test]
+fn escape_sequences_survive_every_read_boundary() {
+    let cases = [
+        (b"\x1b[<65;103;75M".as_slice(), wheel()),
+        (b"\x1b[A".as_slice(), key(KeyCode::Up)),
+        (
+            b"\x1bx".as_slice(),
+            InternalEvent::Event(Event::Key(KeyEvent::new(
+                KeyCode::Char('x'),
+                KeyModifiers::ALT,
+            ))),
+        ),
+    ];
+    for (input, expected) in cases {
+        for split in 1..input.len() {
+            let (mut source, mut writer) = source_with_input();
+            let mut first = b"x".to_vec();
+            first.extend_from_slice(&input[..split]);
+            writer.write_all(&first).unwrap();
+            assert_eq!(read(&mut source), Some(key(KeyCode::Char('x'))));
+            writer.write_all(&input[split..]).unwrap();
+            assert_eq!(
+                read(&mut source),
+                Some(expected.clone()),
+                "input {input:?}, split {split}"
+            );
+            assert_eq!(source.parser.next(), None);
+        }
+    }
+}
+
+#[test]
+fn standalone_escape_at_short_and_full_read_boundaries_is_eventually_emitted() {
+    for size in [1022, 1024] {
+        let (mut source, mut writer) = source_with_input();
+        let mut first = vec![b'x'; size - 1];
+        first.push(b'\x1b');
+        writer.write_all(&first).unwrap();
+        for _ in 0..size - 1 {
+            assert_eq!(read(&mut source), Some(key(KeyCode::Char('x'))));
+        }
+        assert!(
+            source.parser.pending_escape_deadline.is_some(),
+            "read size {size}"
+        );
+        assert_eq!(source.parser.next(), None);
+        source.parser.pending_escape_deadline = Some(Instant::now());
+        assert_eq!(
+            source.try_read(Some(Duration::ZERO)).unwrap(),
+            Some(key(KeyCode::Esc))
+        );
+        assert_eq!(source.parser.next(), None);
+    }
+}
+
+#[test]
+fn queued_input_does_not_expire_an_available_mouse_continuation() {
+    let (mut source, mut writer) = source_with_input();
+    let mut first = vec![b'x'; 1021];
+    first.push(b'\x1b');
+    writer.write_all(&first).unwrap();
+    assert_eq!(read(&mut source), Some(key(KeyCode::Char('x'))));
+    source.parser.pending_escape_deadline = Some(Instant::now());
+    writer.write_all(b"[<65;103;75M").unwrap();
+    for _ in 0..1020 {
+        assert_eq!(read(&mut source), Some(key(KeyCode::Char('x'))));
+    }
+    assert_eq!(
+        source.try_read(Some(Duration::ZERO)).unwrap(),
+        Some(wheel())
+    );
+}
+
+#[cfg(feature = "bracketed-paste")]
+#[test]
+fn bracketed_paste_survives_every_read_boundary() {
+    let input = b"\x1b[200~hello\x1b[<65;103;75M\x1b[201~";
+    for split in 1..input.len() {
+        let (mut source, mut writer) = source_with_input();
+        let mut first = b"x".to_vec();
+        first.extend_from_slice(&input[..split]);
+        writer.write_all(&first).unwrap();
+        assert_eq!(read(&mut source), Some(key(KeyCode::Char('x'))));
+        writer.write_all(&input[split..]).unwrap();
+        assert_eq!(
+            read(&mut source),
+            Some(InternalEvent::Event(Event::Paste(
+                "hello\x1b[<65;103;75M".into(),
+            ))),
+            "split {split}"
+        );
+    }
+}

Activity

  1. added
    bug
    CLI
    TUI
    on Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLITUIbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions