Handle delayed terminal color replies without swallowing TUI input (#65159)

## Why

A terminal's startup color reply can arrive in pieces across the handoff
from the startup probe to the live input reader. If the reader treats
the leading Escape as a key, the rest of the reply can leak into the
composer or trigger a shortcut. A standalone Escape still needs to
dismiss reverse history search and leave subsequent typing intact.

## What changed

Pass the outstanding foreground and background color queries to
Crossterm along with replayed input and the remainder of a two-second
reply window measured from the query. Track each completed reply,
including valid replies consumed inside bracketed paste. Update the
Crossterm pin and let the input drain at screen transitions wait for
an ambiguous Escape to resolve within that window.

## Testing

Add parser and PTY regression tests for replies completed during
probing, split across the handoff, or started in the live reader.
Cover bracketed paste, idle Escape followed by typing, and the
distinction between a reply's BEL terminator and the editor shortcut.
Run the timing-sensitive PTY cases serially in a dedicated Linux
Bazel target.

GitOrigin-RevId: b7d7db6f7d57866aad18e5bc99c32773ad25f95c
This commit is contained in:
Felipe Coury
2026-12-02 03:48:16 +00:00
committed by copyberry
parent abb3701f4c
commit 258e04a50a
15 changed files with 710 additions and 45 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -6621,7 +6621,7 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "crossterm"
version = "0.29.0"
source = "git+https://github.com/openai-oss-forks/crossterm?rev=37ca4a27a9424ec5dbe6451f48c339d7b45f8d63#37ca4a27a9424ec5dbe6451f48c339d7b45f8d63"
source = "git+https://github.com/openai-oss-forks/crossterm?rev=dba8a0c326f197ff20ad2653cbecd736eb8374d0#dba8a0c326f197ff20ad2653cbecd736eb8374d0"
dependencies = [
"bitflags 2.13.1",
"crossterm_winapi",
+1 -1
View File
@@ -706,7 +706,7 @@ opt-level = 0
[patch.crates-io]
# Uncomment to debug local changes.
# ratatui = { path = "../../ratatui" }
crossterm = { git = "https://github.com/openai-oss-forks/crossterm", rev = "37ca4a27a9424ec5dbe6451f48c339d7b45f8d63" }
crossterm = { git = "https://github.com/openai-oss-forks/crossterm", rev = "dba8a0c326f197ff20ad2653cbecd736eb8374d0" }
# SQLx 0.9.0 excludes libsqlite3-sys 0.39. Keep its driver and Core traits on
# the same reviewed source until a release includes transact-rs/sqlx#4502.
sqlx-core = { git = "https://github.com/transact-rs/sqlx", rev = "10462fa4414c6c7f1ed1d39bb31678e3b726878c" }
+8
View File
@@ -7,6 +7,14 @@ codex_rust_crate(
"assets/**",
]),
crate_name = "codex_tui",
# Startup reply budgets must not compete with unrelated builds or PTY tests.
exclusive_linux_cases = {
"tui-all-test": [
"suite::focus_palette::startup_color_replay::startup_color_reply_consumed_inside_paste_does_not_delay_escape",
"suite::focus_palette::startup_idle_escape::startup_color_reply_idle_escape_preserves_open_typing",
"suite::focus_palette::startup_idle_escape::startup_color_reply_idle_escape_preserves_x_typing",
],
},
extra_binaries = [
"//codex-rs/bwrap:bwrap",
"//codex-rs/cli:codex",
@@ -337,6 +337,7 @@ mod imp {
if query_identity {
query.extend_from_slice(b"\x1B[>c");
}
let color_reply_deadline = Instant::now() + Duration::from_secs(/*secs*/ 2);
tty.write_all(&query)?;
let mut buffer = Vec::new();
@@ -348,9 +349,17 @@ mod imp {
probe_kitty_graphics,
&mut buffer,
);
let (replay, kitty_graphics, implicit_bidi) =
parse_startup_input(&buffer, probe_kitty_graphics, probe_bidi);
crossterm::event::buffer_input(&replay)?;
let super::startup_replay::StartupInput {
replay,
kitty_graphics,
implicit_bidi,
pending_color_replies,
} = parse_startup_input(&buffer, probe_kitty_graphics, probe_bidi);
crossterm::event::buffer_input_with_pending_color_replies(
&replay,
pending_color_replies,
color_reply_deadline.saturating_duration_since(Instant::now()),
)?;
let saw_da1 = find_primary_device_attributes(&buffer).is_some();
DA1_SUPPORTED.store(saw_da1, Ordering::Relaxed);
result.map(|probe| StartupProbe {
@@ -865,12 +874,15 @@ mod imp {
);
let mut expected_replay = vec![b'x'; 2_048];
expected_replay.extend_from_slice(b"\x1B[20;10R\x1B[?64;1;2c\x1B[?7u");
let parsed = parse_startup_input(
&buffer, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false,
);
assert_eq!(
parse_startup_input(
&buffer, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false
),
(parsed.replay, parsed.kitty_graphics, parsed.implicit_bidi),
(expected_replay, false, None)
);
assert!(!parsed.pending_color_replies.foreground);
assert!(!parsed.pending_color_replies.background);
}
#[test]
@@ -2,18 +2,82 @@
const MAX_REPLAYED_OSC_BYTES: usize = 1024;
/// Return typeahead, the Kitty graphics acknowledgment, and the reported bidi mode.
/// Track completed color frames separately from their RGB value, without treating paste as replies.
#[cfg(unix)]
pub(super) fn pending_color_replies(input: &[u8]) -> crossterm::event::PendingColorReplies {
let mut pending = crossterm::event::PendingColorReplies {
foreground: true,
background: true,
};
let mut cursor = 0;
let mut inside_paste = false;
while cursor < input.len() {
let rest = &input[cursor..];
if inside_paste {
if rest.starts_with(b"\x1b[201~") {
inside_paste = false;
cursor += 6;
} else {
cursor += 1;
}
continue;
}
if rest.starts_with(b"\x1b[200~") {
inside_paste = true;
cursor += 6;
continue;
}
if rest.starts_with(b"\x1b]")
&& let Some(end) = complete_color_frame_end(rest)
{
if rest.starts_with(b"\x1b]10;") {
pending.foreground = false;
} else if rest.starts_with(b"\x1b]11;") {
pending.background = false;
}
cursor += end;
} else {
cursor += 1;
}
}
pending
}
#[cfg(unix)]
fn complete_color_frame_end(input: &[u8]) -> Option<usize> {
let limit = input.len().min(MAX_REPLAYED_OSC_BYTES);
for i in 2..limit {
match input[i] {
0x07 => return Some(i + 1),
0x03 | 0x04 => return None,
0x1b => return (i + 1 < limit && input[i + 1] == b'\\').then_some(i + 2),
_ => {}
}
}
None
}
/// Input preserved after probing, including replies consumed inside bracketed paste.
pub(super) struct StartupInput {
pub(super) replay: Vec<u8>,
pub(super) kitty_graphics: bool,
pub(super) implicit_bidi: Option<bool>,
pub(super) pending_color_replies: crossterm::event::PendingColorReplies,
}
/// Return typeahead, terminal capabilities, and the color replies still outstanding.
///
/// Keep bounded incomplete OSC prefixes so unread continuations stay parser-framed.
pub(super) fn parse_startup_input(
input: &[u8],
probe_kitty_graphics: bool,
probe_bidi: bool,
) -> (Vec<u8>, bool, Option<bool>) {
) -> StartupInput {
const PASTE_START: &[u8] = b"\x1b[200~";
const PASTE_END: &[u8] = b"\x1b[201~";
const KITTY_REPLY: &[u8] = b"\x1b_Gi=31;";
let mut pending_color_replies = pending_color_replies(input);
let mut replay = Vec::with_capacity(input.len());
let mut kitty_graphics = false;
let mut implicit_bidi = None;
@@ -54,6 +118,13 @@ pub(super) fn parse_startup_input(
.any(|window| window == PASTE_END)
&& super::parse_osc_color(response, slot).is_some()
{
// These RGB replies are consumed rather than replayed as paste, so
// the live reader must not keep waiting for the same slots.
if slot == 10 {
pending_color_replies.foreground = false;
} else {
pending_color_replies.background = false;
}
cursor += 2 + end + terminator_len;
} else {
replay.push(input[cursor]);
@@ -93,7 +164,12 @@ pub(super) fn parse_startup_input(
replay.push(input[cursor]);
cursor += 1;
}
(replay, kitty_graphics, implicit_bidi)
StartupInput {
replay,
kitty_graphics,
implicit_bidi,
pending_color_replies,
}
}
#[cfg(test)]
@@ -2,13 +2,15 @@
use super::MAX_REPLAYED_OSC_BYTES;
use super::parse_startup_input;
#[cfg(unix)]
use super::pending_color_replies;
use pretty_assertions::assert_eq;
fn startup_replay_input(input: &[u8]) -> Vec<u8> {
parse_startup_input(
input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false,
)
.0
.replay
}
#[test]
@@ -45,19 +47,32 @@ fn startup_replay_omits_terminal_color_replies_interleaved_with_bracketed_paste(
let input = b"prefix\x1b[200~hello\x1b]10;rgb:eeee/eeee/eeee\x07 \
\x1b]11;rgb:1111/1111/1111\x1b\\world\x1b[201~suffix";
assert_eq!(
startup_replay_input(input),
b"prefix\x1b[200~hello world\x1b[201~suffix"
let parsed = parse_startup_input(
input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false,
);
assert_eq!(parsed.replay, b"prefix\x1b[200~hello world\x1b[201~suffix");
assert!(!parsed.pending_color_replies.foreground);
assert!(!parsed.pending_color_replies.background);
let unfinished_paste = b"\x1b[200~hello\x1b]10;rgb:eeee/eeee/eeee\x07 world";
assert_eq!(
startup_replay_input(unfinished_paste),
b"\x1b[200~hello world"
let parsed = parse_startup_input(
unfinished_paste,
/*probe_kitty_graphics*/ false,
/*probe_bidi*/ false,
);
assert_eq!(parsed.replay, b"\x1b[200~hello world");
assert!(!parsed.pending_color_replies.foreground);
assert!(parsed.pending_color_replies.background);
let unrelated_osc = b"\x1b[200~\x1b]52;preserve me\x07\x1b[201~";
assert_eq!(startup_replay_input(unrelated_osc), unrelated_osc);
let parsed = parse_startup_input(
unrelated_osc,
/*probe_kitty_graphics*/ false,
/*probe_bidi*/ false,
);
assert_eq!(parsed.replay, unrelated_osc);
assert!(parsed.pending_color_replies.foreground);
assert!(parsed.pending_color_replies.background);
let response_after_paste = b"\x1b[200~\x1b]10;unfinished\x1b[201~suffix\x07";
assert_eq!(
@@ -75,10 +90,11 @@ fn herdr_graphics_reply_selects_previews_without_replaying_the_response_as_keys(
(b"", false),
] {
let input = [paste.as_slice(), reply, b"typed"].concat();
let parsed = parse_startup_input(
&input, /*probe_kitty_graphics*/ true, /*probe_bidi*/ false,
);
assert_eq!(
parse_startup_input(
&input, /*probe_kitty_graphics*/ true, /*probe_bidi*/ false
),
(parsed.replay, parsed.kitty_graphics, parsed.implicit_bidi),
([paste.as_slice(), b"typed"].concat(), expected, None)
);
}
@@ -94,12 +110,48 @@ fn bidi_replies_interleaved_with_paste_are_consumed_only_when_queried() {
(4, Some(false)),
] {
let input = format!("typed\x1b[200~a\x1b[8;{mode}$yb\x1b[201~").into_bytes();
let parsed = parse_startup_input(
&input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ true,
);
assert_eq!(
parse_startup_input(
&input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ true
),
(parsed.replay, parsed.kitty_graphics, parsed.implicit_bidi),
(b"typed\x1b[200~ab\x1b[201~".to_vec(), false, implicit)
);
assert_eq!(startup_replay_input(&input), input);
}
}
#[cfg(unix)]
#[test]
fn pending_color_tracks_each_complete_slot_without_requiring_rgb() {
let pending = pending_color_replies(b"\x1b]10;unsupported\x07\x1b]11;");
assert!(!pending.foreground);
assert!(pending.background);
let pending = pending_color_replies(b"\x1b]11;unsupported\x1b\\");
assert!(pending.foreground);
assert!(!pending.background);
}
#[cfg(unix)]
#[test]
fn pending_color_interrupted_reply_does_not_consume_the_next_frame() {
let pending = pending_color_replies(b"\x1b]10;partial\x1b]11;unsupported\x07");
assert!(pending.foreground);
assert!(!pending.background);
let pending = pending_color_replies(b"\x1b]10;partial\x1b[200~\x1b]11;text\x07\x1b[201~");
assert!(pending.foreground);
assert!(pending.background);
}
#[cfg(unix)]
#[test]
fn pending_color_paste_and_interrupted_replies_stay_pending() {
for input in [
b"\x1b[200~\x1b]10;rgb:1111/2222/3333\x07\x1b]11;x\x07\x1b[201~".as_slice(),
b"\x1b]10;rgb:1111\x1bX",
] {
let pending = pending_color_replies(input);
assert!(pending.foreground);
assert!(pending.background);
}
}
+1
View File
@@ -382,6 +382,7 @@ impl<S: EventSource + Default + Unpin> TuiEventStream<S> {
}
Some(TuiEvent::Resize(size))
}
Event::CellSize(_, _) => None,
Event::Paste(pasted) => Some(TuiEvent::Paste(pasted)),
Event::FocusGained => {
self.terminal_focused.store(true, Ordering::Relaxed);
+7 -5
View File
@@ -65,7 +65,7 @@ pub(super) fn drain_pending_input(mut focus_events: Option<&mut VecDeque<Event>>
}
#[cfg(unix)]
if focus_events.is_some() {
let status = if focus_events.is_some() {
// Crossterm may have read a bare Escape just before poll returned.
// Wait for its 20 ms parser timeout without consuming more bytes.
// New bytes restart the drain. Poll once more to resolve the Escape.
@@ -78,12 +78,14 @@ pub(super) fn drain_pending_input(mut focus_events: Option<&mut VecDeque<Event>>
if crossterm::event::poll(Duration::ZERO)? {
continue;
}
}
// A split color reply can extend the Escape timeout past the usual 20 ms.
crossterm::event::discard_buffered_input_after_poll()?
} else {
crossterm::event::discard_buffered_input()?
};
#[cfg(unix)]
if crossterm::event::discard_buffered_input()?
!= crossterm::event::InputDiscardStatus::Complete
{
if status != crossterm::event::InputDiscardStatus::Complete {
continue;
}
+41 -1
View File
@@ -293,6 +293,10 @@ async fn startup_typeahead_pty_child() {
assert!(draft.local_images.is_empty());
tui.draw(u16::MAX, |_| {}).expect("draw actionable screen");
// This fixture does not answer the startup color queries. Complete them before
// checking ordinary Escape timing, then arm a separate short budget below.
crossterm::event::buffer_input(b"\x1b]10;unsupported\x07\x1b]11;unsupported\x07")
.expect("complete the initial startup color replies");
crossterm::event::buffer_input(b"\x1b").expect("buffer a standalone escape");
let escape_started_at = Instant::now();
assert!(
@@ -305,6 +309,40 @@ async fn startup_typeahead_pty_child() {
));
assert!(escape_started_at.elapsed() < Duration::from_millis(/*millis*/ 250));
// A missing startup color can extend Escape beyond the normal 20 ms. Transition
// retries must let its deadline expire without quarantining it until another key.
crossterm::event::buffer_input_with_pending_color_replies(
b"\x1b",
crossterm::event::PendingColorReplies {
foreground: false,
background: true,
},
Duration::from_millis(/*millis*/ 400),
)
.expect("buffer an ambiguous startup Escape");
assert!(
tui.discard_pending_input_after_thread_transition()
.is_pending()
);
let transition_deadline = Instant::now() + Duration::from_secs(/*secs*/ 1);
while tui
.discard_pending_input_after_thread_transition()
.is_pending()
{
assert!(
Instant::now() < transition_deadline,
"startup Escape stranded the input transition"
);
}
crossterm::event::buffer_input(b"q").expect("buffer fresh input after grace expiry");
assert!(
crossterm::event::poll(Duration::from_millis(/*millis*/ 100))
.expect("fresh key after transition")
);
assert!(
matches!(crossterm::event::read().expect("read fresh transition key"), Event::Key(key) if key.code == KeyCode::Char('q'))
);
// Focus changes buffered alongside typeahead must still reach the app in order.
crossterm::event::buffer_input(b"\x1b[O\r\x1b[I\x1b")
.expect("buffer focus changes, Enter and Escape");
@@ -408,8 +446,10 @@ async fn startup_typeahead_pty_child() {
);
std::fs::write(signals.join("boundary-ready"), []).expect("signal paste-boundary readiness");
wait_for_unread_input(PASTE_BOUNDARY);
// Allow both Unix readers to consume the queued boundary before the next action.
assert!(
!crossterm::event::poll(Duration::ZERO).expect("poll a completed paste with unread input")
!crossterm::event::poll(Duration::from_millis(/*millis*/ 50))
.expect("poll a completed paste with unread input")
);
assert_eq!(
crossterm::event::discard_buffered_input().expect("discard completed paste boundary"),
@@ -28,6 +28,10 @@ mod external_editor;
mod gov_cloud_guidance;
#[path = "job_control_tests.rs"]
mod job_control;
#[path = "startup_color_replay_tests.rs"]
mod startup_color_replay;
#[path = "startup_idle_escape_tests.rs"]
mod startup_idle_escape;
#[path = "tui_mode_picker_tests.rs"]
mod tui_mode_picker;
@@ -0,0 +1,236 @@
//! Exercise a color reply split across the startup probe and the live input reader.
use super::PtyCodex;
use super::STARTUP_TIMEOUT;
use super::contains_bytes;
use super::write_test_config_with_bundled_models;
use anyhow::Result;
use anyhow::ensure;
use std::time::Duration;
use std::time::Instant;
enum Continuation {
DuringProbe,
AfterReplay,
EntirelyLate,
}
#[test]
fn startup_color_reply_completed_during_probe_preserves_input() -> Result<()> {
check_split_color_reply(Continuation::DuringProbe)
}
#[test]
fn startup_color_reply_completed_after_replay_preserves_input() -> Result<()> {
check_split_color_reply(Continuation::AfterReplay)
}
#[test]
fn startup_color_reply_started_after_probe_preserves_input() -> Result<()> {
check_split_color_reply(Continuation::EntirelyLate)
}
#[test]
fn startup_color_reply_consumed_inside_paste_does_not_delay_escape() -> Result<()> {
let repo_root = codex_utils_cargo_bin::repo_root()?;
let codex = codex_utils_cargo_bin::cargo_bin("codex-tui")
.or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?;
let home = tempfile::tempdir()?;
write_test_config_with_bundled_models(home.path(), &repo_root)?;
let mut terminal = PtyCodex::start_binary(
&codex,
&repo_root,
home,
&["--no-daemon", "-c", "check_for_update_on_startup=false"],
/*editor*/ None,
)?;
let deadline = Instant::now() + STARTUP_TIMEOUT;
while !contains_bytes(&terminal.output, b"\x1b]11;?") {
terminal.ensure_running()?;
ensure!(Instant::now() < deadline, "missing startup color query");
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
}
let query_observed_at = Instant::now();
let mut input = b"\x1b[200~paste-\x1b]10;rgb:ffff/ffff/ffff\x07kept\
\x1b]11;rgb:0000/0000/0000\x1b\\\x1b[201~\
\x1b[1;1R\x1b[?1;2c"
.to_vec();
for (query, reply) in [
(b"\x1b[?u".as_slice(), b"\x1b[?7u".as_slice()),
(b"\x1b[8$p", b"\x1b[8;2$y"),
(b"\x1b[?1007$p", b"\x1b[?1007;2$y"),
] {
if contains_bytes(&terminal.output, query) {
input.extend_from_slice(reply);
}
}
terminal.write_input(&input)?;
terminal.palette_answered = true;
terminal.cursor_answered = true;
terminal.keyboard_answered = true;
terminal.wait_for_screen("paste-kept")?;
terminal.wait_for_screen("GPT-5.6-Terra")?;
terminal.write_input(b"\x12")?;
terminal.wait_for_screen("reverse-i-search:")?;
ensure!(
query_observed_at.elapsed() < Duration::from_millis(/*millis*/ 1500),
"search setup missed the startup color grace window"
);
terminal.write_input(b"\x1b")?;
let escape_deadline = Instant::now() + Duration::from_millis(/*millis*/ 250);
while terminal.screen_contains("reverse-i-search:") {
terminal.ensure_running()?;
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
ensure!(
Instant::now() < escape_deadline,
"consumed color replies delayed Escape: {}",
terminal.screen_contents(),
);
}
ensure!(
terminal.screen_contains("paste-kept"),
"paste draft was lost"
);
ensure!(!terminal.screen_contains(";rgb:"), "color reply leaked");
Ok(())
}
fn check_split_color_reply(continuation: Continuation) -> Result<()> {
let repo_root = codex_utils_cargo_bin::repo_root()?;
let codex = codex_utils_cargo_bin::cargo_bin("codex-tui")
.or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?;
let slots: &[u8] = if matches!(continuation, Continuation::EntirelyLate) {
&[10, 11]
} else {
&[11]
};
let prefixes: &[&[u8]] = if matches!(continuation, Continuation::EntirelyLate) {
&[b"\x1b", b"\x1b]"]
} else {
&[b"\x1b]"]
};
for (&slot, &prefix, terminator) in slots.iter().flat_map(|slot| {
prefixes.iter().flat_map(move |prefix| {
[b"\x07".as_slice(), b"\x1b\\"]
.into_iter()
.map(move |end| (slot, prefix, end))
})
}) {
let home = tempfile::tempdir()?;
write_test_config_with_bundled_models(home.path(), &repo_root)?;
let editor = home.path().join("editor.sh");
codex_utils_cargo_bin::write_executable(
&editor,
"#!/bin/sh\ncp \"$1\" \"$0.draft\" && : > \"$0.invoked\"\n",
)?;
let mut terminal = PtyCodex::start_binary(
&codex,
&repo_root,
home,
&["--no-daemon", "-c", "check_for_update_on_startup=false"],
Some(&editor),
)?;
let deadline = Instant::now() + STARTUP_TIMEOUT;
while !contains_bytes(&terminal.output, b"\x1b]11;?") {
terminal.ensure_running()?;
ensure!(Instant::now() < deadline, "missing startup color query");
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
}
let query_seen = Instant::now();
// Do not use answer_startup_queries: it would complete both color replies.
terminal.write_input(b"\x1b[1;1R\x1b[?1;2c")?;
let completed_slot = if slot == 10 { 11 } else { 10 };
terminal
.write_input(format!("\x1b]{completed_slot};rgb:ffff/ffff/ffff\x1b\\").as_bytes())?;
for (query, reply) in [
(b"\x1b[?u".as_slice(), b"\x1b[?7u".as_slice()),
(b"\x1b[8$p", b"\x1b[8;2$y"),
(b"\x1b[?1007$p", b"\x1b[?1007;2$y"),
] {
if contains_bytes(&terminal.output, query) {
terminal.write_input(reply)?;
}
}
terminal.palette_answered = true;
terminal.cursor_answered = true;
terminal.keyboard_answered = true;
if matches!(continuation, Continuation::EntirelyLate) {
// The entire reply starts after the probe, with an empty replay buffer.
while query_seen.elapsed() < Duration::from_millis(/*millis*/ 500) {
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
}
terminal.write_input(b"before-color-")?;
terminal.wait_for_screen("before-color-")?;
ensure!(
query_seen.elapsed() < Duration::from_millis(/*millis*/ 1500),
"late-prefix fixture missed the startup reply budget"
);
terminal.write_input(prefix)?;
} else {
// Leave scheduling margin before the shared 250 ms probe deadline.
while query_seen.elapsed() < Duration::from_millis(/*millis*/ 40) {
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
}
terminal.write_input(b"before-color-\x1b]")?;
if matches!(continuation, Continuation::AfterReplay) {
terminal.wait_for_screen("before-color-")?;
}
}
let prefix_seen = Instant::now();
while prefix_seen.elapsed() < Duration::from_millis(/*millis*/ 80) {
// Keep the real input loop running past its 20 ms ambiguity deadline.
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
}
let reply = format!("\x1b]{slot};rgb:0000/0000/0000");
terminal.write_input(&reply.as_bytes()[prefix.len()..])?;
terminal.write_input(terminator)?;
terminal.write_input(b"after-color")?;
let marker_deadline = Instant::now() + STARTUP_TIMEOUT;
loop {
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
terminal.ensure_running()?;
let screen = terminal.screen_contents();
ensure!(!screen.contains(";rgb:"), "color reply leaked: {screen}");
ensure!(
!editor.with_extension("sh.invoked").exists(),
"the color reply's BEL opened the external editor",
);
if screen.contains("before-color-after-color") {
break;
}
ensure!(
Instant::now() < marker_deadline,
"missing typed marker: {screen}"
);
}
terminal.wait_for_screen("GPT-5.6-Terra")?;
let settle = Instant::now() + Duration::from_millis(/*millis*/ 150);
while Instant::now() < settle {
terminal.read_output(Duration::from_millis(/*millis*/ 10))?;
}
let screen = terminal.screen_contents();
ensure!(!screen.contains(";rgb:"), "color reply leaked: {screen}");
ensure!(
screen.matches("before-color-after-color").count() == 1,
"typed marker was lost or duplicated: {screen}",
);
ensure!(
!editor.with_extension("sh.invoked").exists(),
"the color reply's BEL opened the external editor",
);
terminal.ensure_running()?;
// Intentionally invoke the editor now to verify its sentinel and the entire draft.
terminal.write_input(b"\x07")?;
let editor_deadline = Instant::now() + STARTUP_TIMEOUT;
let draft = editor.with_extension("sh.draft");
while !editor.with_extension("sh.invoked").exists() {
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
ensure!(
Instant::now() < editor_deadline,
"editor control did not run"
);
}
pretty_assertions::assert_eq!(std::fs::read_to_string(draft)?, "before-color-after-color",);
}
Ok(())
}
@@ -0,0 +1,182 @@
//! Keep an idle Escape separate from later typing while a startup color reply is outstanding.
//! Only preparation may restart; every assertion after Escape fails immediately.
use super::PtyCodex;
use super::STARTUP_TIMEOUT;
use super::contains_bytes;
use super::write_test_config_with_bundled_models;
use anyhow::Result;
use anyhow::ensure;
use std::os::fd::AsRawFd;
use std::path::PathBuf;
use std::time::Duration;
use std::time::Instant;
#[test]
fn startup_color_reply_idle_escape_preserves_open_typing() -> Result<()> {
check_idle_escape_typing("Open")
}
#[test]
fn startup_color_reply_idle_escape_preserves_x_typing() -> Result<()> {
check_idle_escape_typing("x")
}
fn prepare_idle_escape() -> Result<(PtyCodex, PathBuf, Instant)> {
let repo_root = codex_utils_cargo_bin::repo_root()?;
let codex = codex_utils_cargo_bin::cargo_bin("codex-tui")
.or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?;
let home = tempfile::tempdir()?;
write_test_config_with_bundled_models(home.path(), &repo_root)?;
let editor = home.path().join("editor.sh");
codex_utils_cargo_bin::write_executable(
&editor,
"#!/bin/sh\ncp \"$1\" \"$0.draft\" && : > \"$0.invoked\"\n",
)?;
let mut terminal = PtyCodex::start_binary(
&codex,
&repo_root,
home,
&["--no-daemon", "-c", "check_for_update_on_startup=false"],
Some(&editor),
)?;
let deadline = Instant::now() + STARTUP_TIMEOUT;
while !contains_bytes(&terminal.output, b"\x1b]11;?") {
terminal.ensure_running()?;
ensure!(Instant::now() < deadline, "missing startup color query");
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
}
let query_observed_at = Instant::now();
// Complete only OSC 10. The fixture must not automatically answer OSC 11.
terminal.write_input(b"\x1b[1;1R\x1b[?1;2c\x1b]10;rgb:ffff/ffff/ffff\x1b\\seed-")?;
for (query, reply) in [
(b"\x1b[?u".as_slice(), b"\x1b[?7u".as_slice()),
(b"\x1b[8$p", b"\x1b[8;2$y"),
(b"\x1b[?1007$p", b"\x1b[?1007;2$y"),
] {
if contains_bytes(&terminal.output, query) {
terminal.write_input(reply)?;
}
}
terminal.palette_answered = true;
terminal.cursor_answered = true;
terminal.keyboard_answered = true;
terminal.wait_for_screen("seed-")?;
terminal.wait_for_screen("GPT-5.6-Terra")?;
terminal.write_input(b"\x12")?;
terminal.wait_for_screen("reverse-i-search:")?;
Ok((terminal, editor, query_observed_at))
}
fn check_idle_escape_typing(text: &str) -> Result<()> {
let mut attempt = 0;
let (mut terminal, editor, query_observed_at) = loop {
attempt += 1;
let (terminal, editor, query_observed_at) = prepare_idle_escape()?;
let query_age = query_observed_at.elapsed();
// Leave the full 250 ms idle-helper allowance inside the 1500 ms guard.
// A slow startup has not exercised Escape yet; discard that process.
if query_age < Duration::from_millis(/*millis*/ 1200) {
break (terminal, editor, query_observed_at);
}
eprintln!(
"idle Escape preparation {attempt}/3 reached search at {query_age:?}; no Escape sent"
);
ensure!(
attempt < 3,
"could not prepare idle Escape inside the startup reply budget"
);
};
terminal.write_input(b"\x1b")?;
let idle = observe_input_idle(&mut terminal)?;
ensure!(
query_observed_at.elapsed() < Duration::from_millis(/*millis*/ 1500),
"idle Escape setup missed the startup reply budget"
);
eprintln!(
"idle Escape before {text:?}: input queue drained, idle for {idle:?}, query age {:?}",
query_observed_at.elapsed()
);
terminal.write_input(text.as_bytes())?;
let expected = format!("seed-{text}");
// Deferred draw work may outlast a keyboard poll. Keep the typing assertion
// and subsequent genuine reply inside the original startup query budget.
let typing_deadline = query_observed_at + Duration::from_millis(/*millis*/ 1700);
loop {
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
terminal.ensure_running()?;
if !terminal.screen_contains("reverse-i-search:") && terminal.screen_contains(&expected) {
break;
}
ensure!(
Instant::now() < typing_deadline,
"idle Escape captured later typing {text:?}: {}",
terminal.screen_contents()
);
}
// The key boundary must not retire the genuine outstanding color reply.
ensure!(
query_observed_at.elapsed() < Duration::from_millis(/*millis*/ 1700),
"post-typing color reply missed the startup reply budget"
);
terminal.write_input(b"\x1b")?;
let reply_idle = observe_input_idle(&mut terminal)?;
eprintln!("post-typing OSC 11 prefix idle for {reply_idle:?}");
terminal.write_input(b"]11;rgb:0000/0000/0000\x07\x1b[200~-paste\x1b[201~")?;
let expected = format!("{expected}-paste");
terminal.wait_for_screen(&expected)?;
ensure!(!terminal.screen_contains(";rgb:"), "color reply leaked");
ensure!(
!editor.with_extension("sh.invoked").exists(),
"the color reply's BEL opened the external editor"
);
terminal.write_input(b"\x07")?;
let editor_deadline = Instant::now() + STARTUP_TIMEOUT;
while !editor.with_extension("sh.invoked").exists() {
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
ensure!(
Instant::now() < editor_deadline,
"editor control did not run"
);
}
pretty_assertions::assert_eq!(
std::fs::read_to_string(editor.with_extension("sh.draft"))?,
expected
);
Ok(())
}
fn observe_input_idle(terminal: &mut PtyCodex) -> Result<Duration> {
// Observe that the child consumed Escape, then allow an input-free idle poll.
// A continuation already queued before that poll is a different case.
let idle_deadline = Instant::now() + Duration::from_millis(/*millis*/ 250);
loop {
let mut unread = 0;
// SAFETY: the owned slave PTY and initialized integer are valid for this ioctl.
ensure!(
unsafe { libc::ioctl(terminal.slave.as_raw_fd(), libc::FIONREAD, &mut unread) } == 0,
"could not observe the terminal input queue"
);
if unread == 0 {
break;
}
ensure!(
Instant::now() < idle_deadline,
"reader did not consume Escape"
);
terminal.ensure_running()?;
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
}
let idle_since = Instant::now();
while idle_since.elapsed() < Duration::from_millis(/*millis*/ 80) {
// Repaints do not end the input-free interval seen by the reader.
terminal.read_output(Duration::from_millis(/*millis*/ 5))?;
terminal.ensure_running()?;
ensure!(
Instant::now() < idle_deadline,
"input idle interval exceeded the fixture deadline"
);
}
Ok(idle_since.elapsed())
}
+30 -11
View File
@@ -242,7 +242,8 @@ def codex_rust_crate(
extra_binaries_non_windows = [],
run_tests_with_wine_exec = False,
integration_test_tags = {},
local_linux_cases = {}):
local_linux_cases = {},
exclusive_linux_cases = {}):
"""Defines a Rust crate with library, binaries, and tests wired for Bazel + Cargo parity.
The macro mirrors Cargo conventions: it builds a library when `src/` exists,
@@ -301,6 +302,9 @@ def codex_rust_crate(
linux_python_tests: Unit and integration test names that run python3 on Linux.
local_linux_cases: Exact libtest names keyed by test launcher. On Linux,
run these cases in a companion launcher with no-remote-exec.
exclusive_linux_cases: Exact libtest names keyed by native integration
test launcher. On Linux, run these cases serially after other Bazel
builds and tests, without changing their behavioral deadlines.
test_tags: Tags applied to unit + integration test targets.
Typically used to disable the sandbox, but see https://bazel.build/reference/be/common-definitions#common.tags
integration_test_tags: Extra execution tags keyed by native integration
@@ -605,7 +609,7 @@ def codex_rust_crate(
integration_test_binary = test_name + "-bin"
execution_tags = integration_test_tags.get(test_name, [])
use_test_launcher = test_shard_count or execution_tags or test_name in linux_python_tests or test_name in local_linux_cases
use_test_launcher = test_shard_count or execution_tags or test_name in linux_python_tests or test_name in local_linux_cases or test_name in exclusive_linux_cases
# There are four generated integration-test shapes:
#
@@ -652,6 +656,7 @@ def codex_rust_crate(
_partitioned_workspace_test(
name = test_name,
local_cases = local_linux_cases.get(test_name, []),
exclusive_cases = exclusive_linux_cases.get(test_name, []),
# Unsharded rust_test binaries can embed paths relative to
# Bazel's runfiles workspace. Preserve that working directory.
chdir_workspace_root = bool(test_shard_count),
@@ -783,13 +788,15 @@ def codex_rust_crate(
**windows_cross_test_kwargs
)
def _partitioned_workspace_test(name, local_cases, env, tags, **kwargs):
def _partitioned_workspace_test(name, local_cases, env, tags, exclusive_cases = [], **kwargs):
"""Share one binary between complementary Linux test launchers."""
if not local_cases:
if not local_cases and not exclusive_cases:
workspace_root_test(name = name, env = env, tags = tags, **kwargs)
return
cases = ",".join(local_cases)
if any([case in local_cases for case in exclusive_cases]):
fail("{} has overlapping local and exclusive test cases".format(name))
cases = ",".join(local_cases + exclusive_cases)
workspace_root_test(
name = name,
env = select({
@@ -809,12 +816,24 @@ def _partitioned_workspace_test(name, local_cases, env, tags, **kwargs):
else:
compatible = ["@platforms//os:linux"]
local_kwargs["target_compatible_with"] = compatible
workspace_root_test(
name = name + "-linux-local",
env = env | {"CODEX_BAZEL_INCLUDE_CASES": cases},
tags = tags + ["no-remote-exec"],
**local_kwargs
)
if local_cases:
workspace_root_test(
name = name + "-linux-local",
env = env | {"CODEX_BAZEL_INCLUDE_CASES": ",".join(local_cases)},
tags = tags + ["no-remote-exec"],
**local_kwargs
)
if exclusive_cases:
# These cases must meet their original deadlines on the first run.
exclusive_kwargs = dict(local_kwargs)
exclusive_kwargs.pop("flaky", None)
exclusive_kwargs["test_threads"] = 1
workspace_root_test(
name = name + "-linux-exclusive",
env = env | {"CODEX_BAZEL_INCLUDE_CASES": ",".join(exclusive_cases)},
tags = tags + ["exclusive"],
**exclusive_kwargs
)
def _test_python_runtime(linux_python_tests, test_name):
if test_name not in linux_python_tests:
+34 -1
View File
@@ -91,11 +91,20 @@ test_shard_index() {
echo $(( hash % TOTAL_SHARDS ))
}
partition_cases="${CODEX_BAZEL_INCLUDE_CASES:-${CODEX_BAZEL_EXCLUDE_CASES:-}}"
run_selected_libtest() {
if [[ -n "${TEST_SHARD_STATUS_FILE:-}" && "${TEST_TOTAL_SHARDS:-0}" != "0" ]]; then
touch "${TEST_SHARD_STATUS_FILE}"
fi
# Some targets configure a fixed libtest concurrency. Keep that setting
# without treating it as an explicit request to override case selection.
if [[ -n "${partition_cases}" && "${libtest_args[0]:-}" == --test-threads=* ]]; then
export RUST_TEST_THREADS="${libtest_args[0]#*=}"
libtest_args=("${libtest_args[@]:1}")
fi
# Extra libtest args are usually ad-hoc local filters. Preserve those exactly
# rather than combining them with generated exact filters.
if [[ ${#libtest_args[@]} -gt 0 ]]; then
@@ -117,6 +126,30 @@ run_selected_libtest() {
list_output="$(run_test_bin --list --format terse)"
test_list="$(printf '%s\n' "${list_output}" | grep ': test$' | sed 's/: test$//' | LC_ALL=C sort || true)"
if [[ -n "${partition_cases}" ]]; then
# Check the complete list before sharding. An exact name belongs to one
# launcher only, and a renamed or removed case must update the partition.
test_list="$(awk -v cases="${partition_cases}" -v want_local="${CODEX_BAZEL_INCLUDE_CASES:+1}" '
BEGIN {
split(cases, names, ",")
for (i in names) selected[names[i]] = 0
}
{
local_case = ($0 in selected)
if (local_case) selected[$0]++
if (local_case == (want_local == "1")) print
}
END {
for (name in selected) {
if (!selected[name]) {
print "Missing local libtest case: " name > "/dev/stderr"
exit 1
}
}
}
' <<< "${test_list}")"
fi
if [[ -z "${test_list}" ]]; then
exit 0
fi
@@ -158,7 +191,7 @@ __WORKSPACE_ROOT_SETUP__
TOTAL_SHARDS="${RULES_RUST_TEST_TOTAL_SHARDS:-${TEST_TOTAL_SHARDS:-}}"
SHARD_INDEX="${RULES_RUST_TEST_SHARD_INDEX:-${TEST_SHARD_INDEX:-}}"
if [[ -n "${CODEX_BAZEL_TEST_SKIP_FILTERS:-}" || ( -n "${TOTAL_SHARDS}" && "${TOTAL_SHARDS}" != "0" ) ]]; then
if [[ -n "${partition_cases}" || -n "${CODEX_BAZEL_TEST_SKIP_FILTERS:-}" || ( -n "${TOTAL_SHARDS}" && "${TOTAL_SHARDS}" != "0" ) ]]; then
run_selected_libtest
fi