mirror of
https://github.com/openai/codex.git
synced 2026-11-22 23:00:42 +00:00
Discard TUI typeahead after prompt rewind and fork (#63193)
## Why Rewinding to edit an earlier prompt restores it in the composer. If a second rewind gesture is already buffered, its Enter can submit the restored prompt before the user edits it. [Prompt rewind behavior](https://github.com/openai/codex/pull/45845) ## What changed Pause terminal input as soon as a rewind is queued. Drain buffered input before showing the restored prompt, and use the same drain after forks from a locked thread or the agents overview. Retry in bounded batches while input is still pending, deliver buffered focus changes in order, and recheck terminal size when the drain finishes. ## Testing Extend PTY coverage to verify that repeated rewind keystrokes and a trailing Escape leave the restored prompt ready for a fresh edit and submission. Cover delayed paste completion, focus event ordering, and terminal resize during a drain. GitOrigin-RevId: 65ba4f343892ed3ba2eeb120172f66bfbebe120f
This commit is contained in:
@@ -522,6 +522,12 @@ impl AppExitInfo {
|
||||
pub use exit_summary::DisconnectInfo;
|
||||
pub use exit_summary::ResumableThread;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ThreadTransition {
|
||||
PromptReverted(ThreadId),
|
||||
DiscardTypeahead,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AppRunControl {
|
||||
Continue,
|
||||
@@ -615,6 +621,7 @@ pub(crate) struct App {
|
||||
transcript_reflow: TranscriptReflowState,
|
||||
initial_history_replay_buffer: Option<InitialHistoryReplayBuffer>,
|
||||
pending_thread_switch_resets: usize,
|
||||
pending_input_drain: Option<ThreadTransition>,
|
||||
pub(crate) scrollback_has_older_history: bool,
|
||||
|
||||
pub(crate) enhanced_keys_supported: bool,
|
||||
|
||||
@@ -30,6 +30,28 @@ use codex_app_server_protocol::WindowsSandboxSetupMode;
|
||||
pub(super) const SHUTDOWN_FIRST_EXIT_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 2);
|
||||
|
||||
impl App {
|
||||
pub(super) fn finish_thread_input_drain(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
transition: ThreadTransition,
|
||||
) {
|
||||
if tui
|
||||
.discard_pending_input_after_thread_transition()
|
||||
.is_pending()
|
||||
{
|
||||
self.pending_input_drain = Some(transition);
|
||||
return;
|
||||
}
|
||||
self.pending_input_drain = None;
|
||||
if let ThreadTransition::PromptReverted(thread_id) = transition
|
||||
&& self.chat_widget.thread_id() == Some(thread_id)
|
||||
{
|
||||
self.chat_widget
|
||||
.set_queue_autosend_suppressed(/*suppressed*/ false);
|
||||
self.chat_widget.emit_prompt_edit_thread_event();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn handle_event<'a>(
|
||||
&'a mut self,
|
||||
tui: &'a mut tui::Tui,
|
||||
@@ -59,7 +81,10 @@ impl App {
|
||||
} else {
|
||||
event
|
||||
};
|
||||
// Release the shortcut's input guard even when a fork is rejected below.
|
||||
// Release queued input guards even when the transition is rejected below.
|
||||
if matches!(event, AppEvent::RevertSessionForPromptEdit { .. }) {
|
||||
self.backtrack.revert_queued = false;
|
||||
}
|
||||
if matches!(event, AppEvent::ForkCurrentSession { .. }) {
|
||||
self.chat_widget.fork_in_progress = false;
|
||||
}
|
||||
@@ -884,10 +909,7 @@ impl App {
|
||||
}
|
||||
if from_locked_thread || from_agents_overview {
|
||||
// Repeated fork shortcuts must not act on the resulting view.
|
||||
if let Err(err) = tui.discard_pending_input_before_interactive_screen() {
|
||||
tracing::warn!(%err, "failed to discard input after forking");
|
||||
}
|
||||
tui.schedule_screen_size_recheck(Duration::ZERO);
|
||||
self.finish_thread_input_drain(tui, ThreadTransition::DiscardTypeahead);
|
||||
}
|
||||
} else {
|
||||
self.chat_widget.add_error_message(
|
||||
@@ -925,12 +947,12 @@ impl App {
|
||||
self.chat_widget.add_error_message(
|
||||
"Wait for permissions to update before editing this prompt.".into(),
|
||||
);
|
||||
tui.frame_requester().schedule_frame();
|
||||
self.finish_thread_input_drain(tui, ThreadTransition::DiscardTypeahead);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
let Some(index) = self.transcript_cells.iter().position(|cell| Arc::ptr_eq(cell, &selected_cell)) else {
|
||||
self.restore_backtrack_prompt_after_revert_error(prompt, "the selected prompt is no longer visible");
|
||||
tui.frame_requester().schedule_frame();
|
||||
self.finish_thread_input_drain(tui, ThreadTransition::DiscardTypeahead);
|
||||
return Ok(AppRunControl::Continue);
|
||||
};
|
||||
let nth_user_message = crate::app_backtrack::user_count(&self.transcript_cells[..index]);
|
||||
@@ -995,7 +1017,7 @@ impl App {
|
||||
Ok(selection) => selection,
|
||||
Err(err) => {
|
||||
self.restore_backtrack_prompt_after_revert_error(prompt, err);
|
||||
tui.frame_requester().schedule_frame();
|
||||
self.finish_thread_input_drain(tui, ThreadTransition::DiscardTypeahead);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
};
|
||||
@@ -1007,7 +1029,7 @@ impl App {
|
||||
if matches!(&err, codex_app_server_client::TypedRequestError::Server { source, .. }
|
||||
if matches!(source.code, -32602..=-32600)) {
|
||||
self.restore_backtrack_prompt_after_revert_error(prompt, err);
|
||||
tui.frame_requester().schedule_frame();
|
||||
self.finish_thread_input_drain(tui, ThreadTransition::DiscardTypeahead);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
self.chat_widget.restore_user_message_to_composer(prompt);
|
||||
@@ -1090,9 +1112,9 @@ impl App {
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
self.backtrack_render_pending = !tui.is_owned_screen();
|
||||
self.chat_widget.set_queue_autosend_suppressed(/*suppressed*/ false);
|
||||
self.chat_widget.emit_prompt_edit_thread_event();
|
||||
tui.frame_requester().schedule_frame();
|
||||
// Input was blocked through the transcript reset. A queued Enter must
|
||||
// not submit the prompt we just restored for editing.
|
||||
self.finish_thread_input_drain(tui, ThreadTransition::PromptReverted(thread_id));
|
||||
}
|
||||
}
|
||||
AppEvent::BeginInitialHistoryReplayBuffer => {
|
||||
|
||||
@@ -423,6 +423,7 @@ impl App {
|
||||
self.app_server_backend_id = Some(session.backend_id());
|
||||
*app_event_rx = rx;
|
||||
self.pending_thread_switch_resets = 0;
|
||||
self.backtrack.revert_queued = false;
|
||||
for (parent, pane) in &mut self.sidebars {
|
||||
pane.focus_document_request = None;
|
||||
pane.agents.pending_link = None;
|
||||
|
||||
@@ -179,9 +179,11 @@ impl App {
|
||||
tui: &tui::Tui,
|
||||
app_event_rx: &mpsc::UnboundedReceiver<AppEvent>,
|
||||
) -> bool {
|
||||
self.pending_thread_switch_resets == 0
|
||||
self.pending_input_drain.is_none()
|
||||
&& self.pending_thread_switch_resets == 0
|
||||
&& (app_event_rx.is_empty()
|
||||
|| (!self.config.features.enabled(Feature::TuiMultiBackend)
|
||||
|| (!self.backtrack.revert_queued
|
||||
&& !self.config.features.enabled(Feature::TuiMultiBackend)
|
||||
&& !self.side_retention_enabled(tui)
|
||||
&& self
|
||||
.current_displayed_thread_id()
|
||||
@@ -196,7 +198,8 @@ impl App {
|
||||
tui: &mut tui::Tui,
|
||||
app_event_rx: &mpsc::UnboundedReceiver<AppEvent>,
|
||||
) -> Result<()> {
|
||||
if self.awaiting_side_replay(tui)
|
||||
if self.pending_input_drain.is_some()
|
||||
|| self.awaiting_side_replay(tui)
|
||||
|| (tui.is_owned_screen()
|
||||
&& !app_event_rx.is_empty()
|
||||
&& !self.chat_widget.has_active_view())
|
||||
@@ -1086,6 +1089,7 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
transcript_reflow: TranscriptReflowState::default(),
|
||||
initial_history_replay_buffer: None,
|
||||
pending_thread_switch_resets: 0,
|
||||
pending_input_drain: None,
|
||||
scrollback_has_older_history: false,
|
||||
commit_animation: None,
|
||||
status_line_invalid_items_warned: status_line_invalid_items_warned.clone(),
|
||||
@@ -1601,6 +1605,11 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
cloud_inventory_poll.reset();
|
||||
}
|
||||
let control = select! {
|
||||
// Leave the previous frame visible and let other app work run between batches.
|
||||
Some(transition) = std::future::ready(app.pending_input_drain), if app.pending_input_drain.is_some() => {
|
||||
app.finish_thread_input_drain(tui, transition);
|
||||
AppRunControl::Continue
|
||||
}
|
||||
result = async {
|
||||
match app.daemon_restart.as_mut() {
|
||||
Some(task) => task.await,
|
||||
|
||||
@@ -100,6 +100,7 @@ pub(crate) async fn make_test_app() -> Box<App> {
|
||||
transcript_reflow: TranscriptReflowState::default(),
|
||||
initial_history_replay_buffer: None,
|
||||
pending_thread_switch_resets: 0,
|
||||
pending_input_drain: None,
|
||||
scrollback_has_older_history: false,
|
||||
enhanced_keys_supported: false,
|
||||
keymap: crate::keymap::RuntimeKeymap::defaults(),
|
||||
|
||||
@@ -9245,6 +9245,7 @@ async fn make_test_app() -> Box<App> {
|
||||
transcript_reflow: TranscriptReflowState::default(),
|
||||
initial_history_replay_buffer: None,
|
||||
pending_thread_switch_resets: 0,
|
||||
pending_input_drain: None,
|
||||
scrollback_has_older_history: false,
|
||||
enhanced_keys_supported: false,
|
||||
keymap: crate::keymap::RuntimeKeymap::defaults(),
|
||||
@@ -9394,6 +9395,7 @@ pub(super) async fn make_test_app_with_channels() -> (
|
||||
transcript_reflow: TranscriptReflowState::default(),
|
||||
initial_history_replay_buffer: None,
|
||||
pending_thread_switch_resets: 0,
|
||||
pending_input_drain: None,
|
||||
scrollback_has_older_history: false,
|
||||
enhanced_keys_supported: false,
|
||||
keymap: crate::keymap::RuntimeKeymap::defaults(),
|
||||
|
||||
@@ -858,6 +858,25 @@ async fn unattended_modals_survive_unfinished_terminal_input() -> Result<()> {
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
// A rewind must not advertise an editable prompt while typeahead is still draining.
|
||||
crossterm::event::buffer_input(b"\x1b[200~unfinished")?;
|
||||
let transition = ThreadTransition::PromptReverted(thread_id);
|
||||
app.finish_thread_input_drain(&mut tui, transition);
|
||||
assert!(!app.can_read_terminal_after_thread_switch(&tui, &app_event_rx));
|
||||
assert!(
|
||||
!std::iter::from_fn(|| app_event_rx.try_recv().ok())
|
||||
.any(|event| matches!(event, AppEvent::InsertHistoryCell(_))),
|
||||
"premature rewind notice"
|
||||
);
|
||||
crossterm::event::buffer_input(b"\x1b[201~\r")?;
|
||||
app.finish_thread_input_drain(&mut tui, transition);
|
||||
assert!(
|
||||
std::iter::from_fn(|| app_event_rx.try_recv().ok())
|
||||
.any(|event| matches!(event, AppEvent::InsertHistoryCell(_))),
|
||||
"missing rewind notice"
|
||||
);
|
||||
assert!(app.can_read_terminal_after_thread_switch(&tui, &app_event_rx));
|
||||
|
||||
crossterm::event::buffer_input(b"\x1b]10;")?;
|
||||
let request = exec_approval_request(thread_id, "turn-1", "call-1", /*approval_id*/ None);
|
||||
let _ = app
|
||||
|
||||
@@ -62,6 +62,8 @@ pub(crate) const SIDE_EDIT_PREVIOUS_UNAVAILABLE_MESSAGE: &str =
|
||||
/// Aggregates all backtrack-related state used by the App.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct BacktrackState {
|
||||
/// Hold terminal input between confirming a prompt edit and dispatching its revert.
|
||||
pub(crate) revert_queued: bool,
|
||||
/// True when Esc has primed backtrack mode in the main view.
|
||||
pub(crate) primed: bool,
|
||||
/// Session id of the base thread whose transcript is being inspected.
|
||||
@@ -171,6 +173,7 @@ impl App {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.backtrack.revert_queued = true;
|
||||
self.app_event_tx
|
||||
.send(AppEvent::RevertSessionForPromptEdit {
|
||||
thread_id: selection.thread_id,
|
||||
|
||||
@@ -1018,6 +1018,23 @@ impl Tui {
|
||||
drain_result
|
||||
}
|
||||
|
||||
/// Keep terminal events paused between batches. The caller retries before showing
|
||||
/// the restored composer or allowing fresh input.
|
||||
pub(crate) fn discard_pending_input_after_thread_transition(&mut self) -> std::task::Poll<()> {
|
||||
self.pause_events();
|
||||
let result = self.event_broker.drain_transition_input();
|
||||
if let Err(err) = result {
|
||||
if err.kind() == std::io::ErrorKind::TimedOut {
|
||||
return std::task::Poll::Pending;
|
||||
}
|
||||
tracing::warn!(%err, "failed to discard input after thread transition");
|
||||
}
|
||||
self.resume_events();
|
||||
// Any batch can consume a resize. Sample geometry after the final one.
|
||||
self.schedule_screen_size_recheck(Duration::ZERO);
|
||||
std::task::Poll::Ready(())
|
||||
}
|
||||
|
||||
/// Temporarily restore terminal state to run an external interactive program `f`.
|
||||
///
|
||||
/// This pauses crossterm's stdin polling by dropping the underlying event stream, restores
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
//!
|
||||
//! See https://ratatui.rs/recipes/apps/spawn-vim/ and https://www.reddit.com/r/rust/comments/1f3o33u/myterious_crossterm_input_after_running_vim for more details.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
@@ -51,11 +52,18 @@ pub trait EventSource: Send + 'static {
|
||||
///
|
||||
/// This intermediate layer enables dropping/recreating the underlying EventStream (pause/resume) without rebuilding consumers.
|
||||
pub struct EventBroker<S: EventSource = CrosstermEventSource> {
|
||||
state: Mutex<EventBrokerState<S>>,
|
||||
state: Mutex<BrokerInput<S>>,
|
||||
resume_events_tx: watch::Sender<()>,
|
||||
pub(super) size_monitor: Option<SizeMonitor>,
|
||||
}
|
||||
|
||||
struct BrokerInput<S: EventSource> {
|
||||
source: EventBrokerState<S>,
|
||||
// Deliver focus changes captured during a thread transition before newer input.
|
||||
pending_focus: VecDeque<Event>,
|
||||
drain_failed: bool,
|
||||
}
|
||||
|
||||
/// Tracks state of underlying [`EventSource`].
|
||||
enum EventBrokerState<S: EventSource> {
|
||||
Paused, // Underlying event source (i.e., crossterm EventStream) dropped
|
||||
@@ -84,7 +92,11 @@ impl<S: EventSource + Default> EventBroker<S> {
|
||||
pub fn new() -> Self {
|
||||
let (resume_events_tx, _resume_events_rx) = watch::channel(());
|
||||
Self {
|
||||
state: Mutex::new(EventBrokerState::Start),
|
||||
state: Mutex::new(BrokerInput {
|
||||
source: EventBrokerState::Start,
|
||||
pending_focus: VecDeque::new(),
|
||||
drain_failed: false,
|
||||
}),
|
||||
resume_events_tx,
|
||||
size_monitor: None,
|
||||
}
|
||||
@@ -99,7 +111,20 @@ impl<S: EventSource + Default> EventBroker<S> {
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
*state = EventBrokerState::Paused;
|
||||
state.source = EventBrokerState::Paused;
|
||||
}
|
||||
|
||||
/// Called with the event source paused. A terminal error must not expose stale keys.
|
||||
pub(super) fn drain_transition_input(&self) -> std::io::Result<()> {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let result = super::input_boundary::drain_pending_input(Some(&mut state.pending_focus));
|
||||
state.drain_failed = result
|
||||
.as_ref()
|
||||
.is_err_and(|err| err.kind() != std::io::ErrorKind::TimedOut);
|
||||
result
|
||||
}
|
||||
|
||||
/// Create a new instance of the underlying event source
|
||||
@@ -111,7 +136,7 @@ impl<S: EventSource + Default> EventBroker<S> {
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
*state = EventBrokerState::Start;
|
||||
state.source = EventBrokerState::Start;
|
||||
let _ = self.resume_events_tx.send(());
|
||||
}
|
||||
|
||||
@@ -220,7 +245,16 @@ impl<S: EventSource + Default + Unpin> TuiEventStream<S> {
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let events = match state.active_event_source_mut() {
|
||||
if !matches!(state.source, EventBrokerState::Paused) {
|
||||
if state.drain_failed {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
if let Some(event) = state.pending_focus.pop_front() {
|
||||
drop(state);
|
||||
return Poll::Ready(self.map_crossterm_event(event));
|
||||
}
|
||||
}
|
||||
let events = match state.source.active_event_source_mut() {
|
||||
Some(events) => events,
|
||||
None => {
|
||||
drop(state);
|
||||
@@ -235,7 +269,7 @@ impl<S: EventSource + Default + Unpin> TuiEventStream<S> {
|
||||
match Pin::new(events).poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(event))) => Some(event),
|
||||
Poll::Ready(Some(Err(_))) | Poll::Ready(None) => {
|
||||
*state = EventBrokerState::Start;
|
||||
state.source = EventBrokerState::Start;
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
@@ -399,7 +433,7 @@ mod tests {
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some(source) = state.active_event_source_mut() else {
|
||||
let Some(source) = state.source.active_event_source_mut() else {
|
||||
return;
|
||||
};
|
||||
let _ = source.tx.send(event);
|
||||
@@ -439,7 +473,7 @@ mod tests {
|
||||
fn setup() -> SetupState {
|
||||
let source = FakeEventSource::new();
|
||||
let broker = Arc::new(EventBroker::new());
|
||||
*broker.state.lock().unwrap() = EventBrokerState::Running(source);
|
||||
broker.state.lock().unwrap().source = EventBrokerState::Running(source);
|
||||
let handle = FakeEventSourceHandle::new(broker.clone());
|
||||
|
||||
let (draw_tx, draw_rx) = broadcast::channel(1);
|
||||
@@ -511,10 +545,11 @@ mod tests {
|
||||
assert!(matches!(stream.next().await, Some(TuiEvent::FocusGained)));
|
||||
assert!(terminal_focused.load(Ordering::Relaxed));
|
||||
assert!(matches!(
|
||||
&*broker
|
||||
&broker
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.source,
|
||||
EventBrokerState::Running(_)
|
||||
));
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Restore terminal ownership on initialization failures and quarantine protected-screen input.
|
||||
//! Restore terminal ownership on initialization failures and drain input across screen transitions.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::io;
|
||||
#[cfg(unix)]
|
||||
use std::io::IsTerminal;
|
||||
@@ -9,6 +10,8 @@ use std::io::stdin;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use crossterm::event::Event;
|
||||
|
||||
/// Restores terminal modes when initialization fails before ownership is transferred.
|
||||
pub(super) struct TerminalInitializationGuard {
|
||||
pub(super) active: bool,
|
||||
@@ -29,7 +32,19 @@ pub(crate) fn discard_pending_terminal_input() -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
let _ = crossterm::event::discard_buffered_input()?;
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 1);
|
||||
drain_pending_input(/*focus_events*/ None)
|
||||
}
|
||||
|
||||
/// A thread transition drains decoded events first so it can retain focus changes
|
||||
/// and let a standalone Escape expire before quarantining incomplete sequences.
|
||||
pub(super) fn drain_pending_input(mut focus_events: Option<&mut VecDeque<Event>>) -> Result<()> {
|
||||
let budget = if focus_events.is_some() {
|
||||
// Yield to the event loop between batches of continuous typeahead.
|
||||
Duration::from_millis(/*millis*/ 100)
|
||||
} else {
|
||||
Duration::from_secs(/*secs*/ 1)
|
||||
};
|
||||
let deadline = Instant::now() + budget;
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
@@ -40,10 +55,31 @@ pub(crate) fn discard_pending_terminal_input() -> Result<()> {
|
||||
}
|
||||
|
||||
if crossterm::event::poll(remaining.min(Duration::from_millis(/*millis*/ 10)))? {
|
||||
let _ = crossterm::event::read()?;
|
||||
let event = crossterm::event::read()?;
|
||||
if matches!(event, Event::FocusLost | Event::FocusGained)
|
||||
&& let Some(events) = &mut focus_events
|
||||
{
|
||||
events.push_back(event);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
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.
|
||||
match poll_terminal_input(/*timeout_ms*/ 20) {
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
if crossterm::event::poll(Duration::ZERO)? {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
if crossterm::event::discard_buffered_input()?
|
||||
!= crossterm::event::InputDiscardStatus::Complete
|
||||
@@ -66,6 +102,11 @@ pub(crate) fn discard_pending_terminal_input() -> Result<()> {
|
||||
/// Check Crossterm's terminal input source without consuming input or changing descriptor flags.
|
||||
#[cfg(unix)]
|
||||
pub(super) fn terminal_input_is_readable() -> Result<bool> {
|
||||
poll_terminal_input(/*timeout_ms*/ 0)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn poll_terminal_input(timeout_ms: libc::c_int) -> Result<bool> {
|
||||
use std::os::fd::AsRawFd;
|
||||
|
||||
let terminal = if stdin().is_terminal() {
|
||||
@@ -80,9 +121,9 @@ pub(super) fn terminal_input_is_readable() -> Result<bool> {
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
// Safety: `fd` is valid for the duration of this zero-timeout poll.
|
||||
// Safety: `fd` is valid for the duration of the poll.
|
||||
let result = unsafe {
|
||||
libc::poll(&mut fd, /*nfds*/ 1, /*timeout*/ 0)
|
||||
libc::poll(&mut fd, /*nfds*/ 1, timeout_ms)
|
||||
};
|
||||
if result < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
|
||||
@@ -11,6 +11,9 @@ use std::time::Instant;
|
||||
|
||||
use crossterm::event::Event;
|
||||
use crossterm::event::KeyCode;
|
||||
use tokio_stream::StreamExt;
|
||||
|
||||
use super::TuiEvent;
|
||||
|
||||
const STARTUP_INPUT_CHILD_TEST: &str = "tui::startup_tests::startup_typeahead_pty_child";
|
||||
|
||||
@@ -306,6 +309,65 @@ async fn startup_typeahead_pty_child() {
|
||||
));
|
||||
assert!(escape_started_at.elapsed() < Duration::from_millis(/*millis*/ 250));
|
||||
|
||||
// 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");
|
||||
assert!(
|
||||
tui.discard_pending_input_after_thread_transition()
|
||||
.is_ready()
|
||||
);
|
||||
crossterm::event::buffer_input(b"x").expect("buffer fresh input");
|
||||
let mut events = tui
|
||||
.event_stream()
|
||||
.filter(|event| !matches!(event, TuiEvent::Draw | TuiEvent::Resize(_)));
|
||||
assert!(matches!(events.next().await, Some(TuiEvent::FocusLost)));
|
||||
assert!(!tui.is_terminal_focused());
|
||||
assert!(matches!(events.next().await, Some(TuiEvent::FocusGained)));
|
||||
assert!(tui.is_terminal_focused());
|
||||
assert!(
|
||||
matches!(events.next().await, Some(TuiEvent::Key(key)) if key.code == KeyCode::Char('x'))
|
||||
);
|
||||
|
||||
// Hold the boundary open past the drain deadline. An Enter behind the delayed
|
||||
// paste terminator still belongs to the old screen, but the next edit is fresh.
|
||||
crossterm::event::buffer_input(b"\x1b[200~unfinished").expect("begin a paste");
|
||||
assert!(
|
||||
tui.discard_pending_input_after_thread_transition()
|
||||
.is_pending()
|
||||
);
|
||||
// The final draw must sample geometry even if a resize was consumed during a retry.
|
||||
let old_size = tui
|
||||
.screen_size_for_event(&TuiEvent::Resume)
|
||||
.expect("sample initial size");
|
||||
let resized = libc::winsize {
|
||||
ws_row: old_size.height,
|
||||
ws_col: old_size.width + 1,
|
||||
ws_xpixel: 0,
|
||||
ws_ypixel: 0,
|
||||
};
|
||||
// Safety: stdin is the child PTY and resized is valid for this ioctl.
|
||||
assert_eq!(
|
||||
unsafe { libc::ioctl(libc::STDIN_FILENO, libc::TIOCSWINSZ, &resized) },
|
||||
0
|
||||
);
|
||||
crossterm::event::buffer_input(b"\x1b[201~\r\x1b[O").expect("finish paste and queue Enter");
|
||||
assert!(
|
||||
tui.discard_pending_input_after_thread_transition()
|
||||
.is_ready()
|
||||
);
|
||||
assert_eq!(
|
||||
tui.screen_size_for_event(&TuiEvent::Draw)
|
||||
.expect("size after drain")
|
||||
.width,
|
||||
resized.ws_col
|
||||
);
|
||||
assert!(matches!(events.next().await, Some(TuiEvent::FocusLost)));
|
||||
crossterm::event::buffer_input(b"z").expect("buffer fresh post-timeout input");
|
||||
assert!(
|
||||
matches!(events.next().await, Some(TuiEvent::Key(key)) if key.code == KeyCode::Char('z'))
|
||||
);
|
||||
tui.pause_events();
|
||||
|
||||
for suffix in ["y", "1"] {
|
||||
crossterm::event::buffer_input(b"\x1b")
|
||||
.expect("buffer an incomplete modifier before the security screen");
|
||||
|
||||
@@ -112,6 +112,25 @@ async fn picker_side_worktree_fork_and_cd_run_on_the_production_stack() -> Resul
|
||||
terminal.wait_for_screen("Worked for")?;
|
||||
terminal.wait_for_screen("Ask Codex to do anything")?;
|
||||
|
||||
// A second rewind gesture is already buffered when the first is confirmed.
|
||||
// A trailing bare Escape must not consume the first character of the fresh edit.
|
||||
terminal.write_input(b"\x1b[27u\x1b[27u\r\x1b[27u\x1b[27u\r\x1b")?;
|
||||
terminal.wait_for_screen("Conversation reverted to this point")?;
|
||||
terminal.write_input(b" Revised.")?;
|
||||
terminal.wait_for_screen("Reply with the marker requested by this test. Revised.")?;
|
||||
let _edited_reply = responses::mount_sse_once_match(
|
||||
&server,
|
||||
body_string_contains("Reply with the marker requested by this test. Revised."),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("edited", "STACK_SAVED_HISTORY_EDITED"),
|
||||
responses::ev_completed("edited-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
terminal.write_input(b"\r")?;
|
||||
terminal.wait_for_screen("STACK_SAVED_HISTORY_EDITED")?;
|
||||
terminal.wait_for_screen("Worked for")?;
|
||||
|
||||
// Starting and closing a side conversation both rebuild the displayed chat widget.
|
||||
// Repeat through the real event loop, whose dev-build frames share the production stack.
|
||||
for attempt in 1..=3 {
|
||||
|
||||
Reference in New Issue
Block a user