From 610addbc2e28159ebaf9b33e77778ba04de588ab Mon Sep 17 00:00:00 2001
From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com>
Date: Thu, 31 Jul 2025 17:00:48 -0700
Subject: [PATCH 1/5] do not dispatch key releases (#1771)
when we enabled KKP in https://github.com/openai/codex/pull/1743, we
started receiving keyup events, but didn't expect them anywhere in our
code. for now, just don't dispatch them at all.
---
codex-rs/tui/src/app.rs | 11 ++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)
diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs
index 3013cb6df0..86c042f813 100644
--- a/codex-rs/tui/src/app.rs
+++ b/codex-rs/tui/src/app.rs
@@ -15,6 +15,7 @@ use color_eyre::eyre::Result;
use crossterm::SynchronizedUpdate;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
use ratatui::layout::Offset;
use ratatui::prelude::Backend;
use std::path::PathBuf;
@@ -213,6 +214,7 @@ impl App<'_> {
KeyEvent {
code: KeyCode::Char('c'),
modifiers: crossterm::event::KeyModifiers::CONTROL,
+ kind: KeyEventKind::Press,
..
} => {
match &mut self.app_state {
@@ -227,6 +229,7 @@ impl App<'_> {
KeyEvent {
code: KeyCode::Char('d'),
modifiers: crossterm::event::KeyModifiers::CONTROL,
+ kind: KeyEventKind::Press,
..
} => {
match &mut self.app_state {
@@ -245,9 +248,15 @@ impl App<'_> {
}
}
}
- _ => {
+ KeyEvent {
+ kind: KeyEventKind::Press | KeyEventKind::Repeat,
+ ..
+ } => {
self.dispatch_key_event(key_event);
}
+ _ => {
+ // Ignore Release key events for now.
+ }
};
}
AppEvent::Paste(text) => {
From ea69a1d72f11d0b1d24f9722dd3c31ff0fe69763 Mon Sep 17 00:00:00 2001
From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com>
Date: Thu, 31 Jul 2025 17:10:52 -0700
Subject: [PATCH 2/5] lighter approval modal (#1768)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The yellow hazard stripes were too scary :)
This also has the added benefit of not rendering anything at the full
width of the terminal, so resizing is a little easier to handle.
---
codex-rs/tui/src/app.rs | 40 ++-
codex-rs/tui/src/chatwidget.rs | 5 +-
codex-rs/tui/src/user_approval_widget.rs | 306 +++++++++--------------
3 files changed, 157 insertions(+), 194 deletions(-)
diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs
index 86c042f813..7454a1ca11 100644
--- a/codex-rs/tui/src/app.rs
+++ b/codex-rs/tui/src/app.rs
@@ -10,7 +10,6 @@ use crate::tui;
use codex_core::config::Config;
use codex_core::protocol::Event;
use codex_core::protocol::EventMsg;
-use codex_core::protocol::ExecApprovalRequestEvent;
use color_eyre::eyre::Result;
use crossterm::SynchronizedUpdate;
use crossterm::event::KeyCode;
@@ -313,14 +312,41 @@ impl App<'_> {
}
#[cfg(debug_assertions)]
SlashCommand::TestApproval => {
+ use std::collections::HashMap;
+
+ use codex_core::protocol::ApplyPatchApprovalRequestEvent;
+ use codex_core::protocol::FileChange;
+
self.app_event_tx.send(AppEvent::CodexEvent(Event {
id: "1".to_string(),
- msg: EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent {
- call_id: "1".to_string(),
- command: vec!["git".into(), "apply".into()],
- cwd: self.config.cwd.clone(),
- reason: Some("test".to_string()),
- }),
+ // msg: EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent {
+ // call_id: "1".to_string(),
+ // command: vec!["git".into(), "apply".into()],
+ // cwd: self.config.cwd.clone(),
+ // reason: Some("test".to_string()),
+ // }),
+ msg: EventMsg::ApplyPatchApprovalRequest(
+ ApplyPatchApprovalRequestEvent {
+ call_id: "1".to_string(),
+ changes: HashMap::from([
+ (
+ PathBuf::from("/tmp/test.txt"),
+ FileChange::Add {
+ content: "test".to_string(),
+ },
+ ),
+ (
+ PathBuf::from("/tmp/test2.txt"),
+ FileChange::Update {
+ unified_diff: "+test\n-test2".to_string(),
+ move_path: None,
+ },
+ ),
+ ]),
+ reason: None,
+ grant_root: Some(PathBuf::from("/tmp")),
+ },
+ ),
}));
}
},
diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs
index 50488f8b30..b0a6fb44e1 100644
--- a/codex-rs/tui/src/chatwidget.rs
+++ b/codex-rs/tui/src/chatwidget.rs
@@ -25,6 +25,7 @@ use codex_core::protocol::PatchApplyBeginEvent;
use codex_core::protocol::TaskCompleteEvent;
use codex_core::protocol::TokenUsage;
use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
@@ -157,7 +158,9 @@ impl ChatWidget<'_> {
}
pub(crate) fn handle_key_event(&mut self, key_event: KeyEvent) {
- self.bottom_pane.clear_ctrl_c_quit_hint();
+ if key_event.kind == KeyEventKind::Press {
+ self.bottom_pane.clear_ctrl_c_quit_hint();
+ }
match self.bottom_pane.handle_key_event(key_event) {
InputResult::Submitted(text) => {
diff --git a/codex-rs/tui/src/user_approval_widget.rs b/codex-rs/tui/src/user_approval_widget.rs
index 855a7ea3db..91febde208 100644
--- a/codex-rs/tui/src/user_approval_widget.rs
+++ b/codex-rs/tui/src/user_approval_widget.rs
@@ -7,23 +7,24 @@
//! driven workflow – a fully‑fledged visual match is not required.
use std::path::PathBuf;
+use std::sync::LazyLock;
use codex_core::protocol::Op;
use codex_core::protocol::ReviewDecision;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::*;
use ratatui::text::Line;
-use ratatui::text::Span;
-use ratatui::widgets::List;
+use ratatui::widgets::Block;
+use ratatui::widgets::BorderType;
+use ratatui::widgets::Borders;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
-use tui_input::Input;
-use tui_input::backend::crossterm::EventHandler;
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
@@ -47,68 +48,62 @@ pub(crate) enum ApprovalRequest {
/// Options displayed in the *select* mode.
struct SelectOption {
- label: &'static str,
- decision: Option,
- /// `true` when this option switches the widget to *input* mode.
- enters_input_mode: bool,
+ label: Line<'static>,
+ description: &'static str,
+ key: KeyCode,
+ decision: ReviewDecision,
}
-// keep in same order as in the TS implementation
-const SELECT_OPTIONS: &[SelectOption] = &[
- SelectOption {
- label: "Yes (y)",
- decision: Some(ReviewDecision::Approved),
+static COMMAND_SELECT_OPTIONS: LazyLock> = LazyLock::new(|| {
+ vec![
+ SelectOption {
+ label: Line::from(vec!["Y".underlined(), "es".into()]),
+ description: "Approve and run the command",
+ key: KeyCode::Char('y'),
+ decision: ReviewDecision::Approved,
+ },
+ SelectOption {
+ label: Line::from(vec!["A".underlined(), "lways".into()]),
+ description: "Approve the command for the remainder of this session",
+ key: KeyCode::Char('a'),
+ decision: ReviewDecision::ApprovedForSession,
+ },
+ SelectOption {
+ label: Line::from(vec!["N".underlined(), "o".into()]),
+ description: "Do not run the command",
+ key: KeyCode::Char('n'),
+ decision: ReviewDecision::Denied,
+ },
+ ]
+});
- enters_input_mode: false,
- },
- SelectOption {
- label: "Yes, always approve this exact command for this session (a)",
- decision: Some(ReviewDecision::ApprovedForSession),
-
- enters_input_mode: false,
- },
- SelectOption {
- label: "Edit or give feedback (e)",
- decision: None,
-
- enters_input_mode: true,
- },
- SelectOption {
- label: "No, and keep going (n)",
- decision: Some(ReviewDecision::Denied),
-
- enters_input_mode: false,
- },
- SelectOption {
- label: "No, and stop for now (esc)",
- decision: Some(ReviewDecision::Abort),
-
- enters_input_mode: false,
- },
-];
-
-/// Internal mode the widget is in – mirrors the TypeScript component.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum Mode {
- Select,
- Input,
-}
+static PATCH_SELECT_OPTIONS: LazyLock> = LazyLock::new(|| {
+ vec![
+ SelectOption {
+ label: Line::from(vec!["Y".underlined(), "es".into()]),
+ description: "Approve and apply the changes",
+ key: KeyCode::Char('y'),
+ decision: ReviewDecision::Approved,
+ },
+ SelectOption {
+ label: Line::from(vec!["N".underlined(), "o".into()]),
+ description: "Do not apply the changes",
+ key: KeyCode::Char('n'),
+ decision: ReviewDecision::Denied,
+ },
+ ]
+});
/// A modal prompting the user to approve or deny the pending request.
pub(crate) struct UserApprovalWidget<'a> {
approval_request: ApprovalRequest,
app_event_tx: AppEventSender,
confirmation_prompt: Paragraph<'a>,
+ select_options: &'a Vec,
/// Currently selected index in *select* mode.
selected_option: usize,
- /// State for the optional input widget.
- input: Input,
-
- /// Current mode.
- mode: Mode,
-
/// Set to `true` once a decision has been sent – the parent view can then
/// remove this widget from its queue.
done: bool,
@@ -116,7 +111,6 @@ pub(crate) struct UserApprovalWidget<'a> {
impl UserApprovalWidget<'_> {
pub(crate) fn new(approval_request: ApprovalRequest, app_event_tx: AppEventSender) -> Self {
- let input = Input::default();
let confirmation_prompt = match &approval_request {
ApprovalRequest::Exec {
command,
@@ -132,25 +126,20 @@ impl UserApprovalWidget<'_> {
None => cwd.display().to_string(),
};
let mut contents: Vec = vec![
- Line::from(vec![
- Span::from(cwd_str).dim(),
- Span::from("$"),
- Span::from(format!(" {cmd}")),
- ]),
+ Line::from(vec!["codex".bold().magenta(), " wants to run:".into()]),
+ Line::from(vec![cwd_str.dim(), "$".into(), format!(" {cmd}").into()]),
Line::from(""),
];
if let Some(reason) = reason {
contents.push(Line::from(reason.clone().italic()));
contents.push(Line::from(""));
}
- contents.extend(vec![Line::from("Allow command?"), Line::from("")]);
Paragraph::new(contents).wrap(Wrap { trim: false })
}
ApprovalRequest::ApplyPatch {
reason, grant_root, ..
} => {
- let mut contents: Vec =
- vec![Line::from("Apply patch".bold()), Line::from("")];
+ let mut contents: Vec = vec![];
if let Some(r) = reason {
contents.push(Line::from(r.clone().italic()));
@@ -165,20 +154,19 @@ impl UserApprovalWidget<'_> {
contents.push(Line::from(""));
}
- contents.push(Line::from("Allow changes?"));
- contents.push(Line::from(""));
-
- Paragraph::new(contents)
+ Paragraph::new(contents).wrap(Wrap { trim: false })
}
};
Self {
+ select_options: match &approval_request {
+ ApprovalRequest::Exec { .. } => &COMMAND_SELECT_OPTIONS,
+ ApprovalRequest::ApplyPatch { .. } => &PATCH_SELECT_OPTIONS,
+ },
approval_request,
app_event_tx,
confirmation_prompt,
selected_option: 0,
- input,
- mode: Mode::Select,
done: false,
}
}
@@ -194,9 +182,8 @@ impl UserApprovalWidget<'_> {
/// captures input while visible, we don’t need to report whether the event
/// was consumed—callers can assume it always is.
pub(crate) fn handle_key_event(&mut self, key: KeyEvent) {
- match self.mode {
- Mode::Select => self.handle_select_key(key),
- Mode::Input => self.handle_input_key(key),
+ if key.kind == KeyEventKind::Press {
+ self.handle_select_key(key);
}
}
@@ -208,58 +195,24 @@ impl UserApprovalWidget<'_> {
fn handle_select_key(&mut self, key_event: KeyEvent) {
match key_event.code {
- KeyCode::Up => {
- if self.selected_option == 0 {
- self.selected_option = SELECT_OPTIONS.len() - 1;
- } else {
- self.selected_option -= 1;
- }
+ KeyCode::Left => {
+ self.selected_option = (self.selected_option + self.select_options.len() - 1)
+ % self.select_options.len();
}
- KeyCode::Down => {
- self.selected_option = (self.selected_option + 1) % SELECT_OPTIONS.len();
- }
- KeyCode::Char('y') => {
- self.send_decision(ReviewDecision::Approved);
- }
- KeyCode::Char('a') => {
- self.send_decision(ReviewDecision::ApprovedForSession);
- }
- KeyCode::Char('n') => {
- self.send_decision(ReviewDecision::Denied);
- }
- KeyCode::Char('e') => {
- self.mode = Mode::Input;
+ KeyCode::Right => {
+ self.selected_option = (self.selected_option + 1) % self.select_options.len();
}
KeyCode::Enter => {
- let opt = &SELECT_OPTIONS[self.selected_option];
- if opt.enters_input_mode {
- self.mode = Mode::Input;
- } else if let Some(decision) = opt.decision {
- self.send_decision(decision);
- }
+ let opt = &self.select_options[self.selected_option];
+ self.send_decision(opt.decision);
}
KeyCode::Esc => {
self.send_decision(ReviewDecision::Abort);
}
- _ => {}
- }
- }
-
- fn handle_input_key(&mut self, key_event: KeyEvent) {
- // Handle special keys first.
- match key_event.code {
- KeyCode::Enter => {
- let feedback = self.input.value().to_string();
- self.send_decision_with_feedback(ReviewDecision::Denied, feedback);
- }
- KeyCode::Esc => {
- // Cancel input – treat as deny without feedback.
- self.send_decision(ReviewDecision::Denied);
- }
- _ => {
- // Feed into input widget for normal editing.
- let ct_event = crossterm::event::Event::Key(key_event);
- self.input.handle_event(&ct_event);
+ other => {
+ if let Some(opt) = self.select_options.iter().find(|opt| opt.key == other) {
+ self.send_decision(opt.decision);
+ }
}
}
}
@@ -312,87 +265,68 @@ impl UserApprovalWidget<'_> {
}
pub(crate) fn desired_height(&self, width: u16) -> u16 {
- self.get_confirmation_prompt_height(width - 2) + SELECT_OPTIONS.len() as u16 + 2
+ self.get_confirmation_prompt_height(width) + self.select_options.len() as u16
}
}
-const PLAIN: Style = Style::new();
-const BLUE_FG: Style = Style::new().fg(Color::LightCyan);
-
impl WidgetRef for &UserApprovalWidget<'_> {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
- // Take the area, wrap it in a block with a border, and divide up the
- // remaining area into two chunks: one for the confirmation prompt and
- // one for the response.
- let inner = area.inner(Margin::new(0, 2));
-
- // Determine how many rows we can allocate for the static confirmation
- // prompt while *always* keeping enough space for the interactive
- // response area (select list or input field). When the full prompt
- // would exceed the available height we truncate it so the response
- // options never get pushed out of view. This keeps the approval modal
- // usable even when the overall bottom viewport is small.
-
- // Full height of the prompt (may be larger than the available area).
- let full_prompt_height = self.get_confirmation_prompt_height(inner.width);
-
- // Minimum rows that must remain for the interactive section.
- let min_response_rows = match self.mode {
- Mode::Select => SELECT_OPTIONS.len() as u16,
- // In input mode we need exactly two rows: one for the guidance
- // prompt and one for the single-line input field.
- Mode::Input => 2,
- };
-
- // Clamp prompt height so confirmation + response never exceed the
- // available space. `saturating_sub` avoids underflow when the area is
- // too small even for the minimal layout – in this unlikely case we
- // fall back to zero-height prompt so at least the options are
- // visible.
- let prompt_height = full_prompt_height.min(inner.height.saturating_sub(min_response_rows));
-
- let chunks = Layout::default()
+ let prompt_height = self.get_confirmation_prompt_height(area.width);
+ let [prompt_chunk, response_chunk] = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(prompt_height), Constraint::Min(0)])
- .split(inner);
- let prompt_chunk = chunks[0];
- let response_chunk = chunks[1];
+ .areas(area);
- // Build the inner lines based on the mode. Collect them into a List of
- // non-wrapping lines rather than a Paragraph for predictable layout.
- let lines = match self.mode {
- Mode::Select => SELECT_OPTIONS
- .iter()
- .enumerate()
- .map(|(idx, opt)| {
- let (prefix, style) = if idx == self.selected_option {
- ("▶", BLUE_FG)
- } else {
- (" ", PLAIN)
- };
- Line::styled(format!(" {prefix} {}", opt.label), style)
- })
- .collect(),
- Mode::Input => {
- vec![
- Line::from("Give the model feedback on this command:"),
- Line::from(self.input.value()),
- ]
- }
+ let lines: Vec = self
+ .select_options
+ .iter()
+ .enumerate()
+ .map(|(idx, opt)| {
+ let style = if idx == self.selected_option {
+ Style::new().bg(Color::Cyan).fg(Color::Black)
+ } else {
+ Style::new().bg(Color::DarkGray)
+ };
+ opt.label.clone().alignment(Alignment::Center).style(style)
+ })
+ .collect();
+
+ let [title_area, button_area, description_area] = Layout::vertical([
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Min(0),
+ ])
+ .areas(response_chunk.inner(Margin::new(1, 0)));
+ let title = match &self.approval_request {
+ ApprovalRequest::Exec { .. } => "Allow command?",
+ ApprovalRequest::ApplyPatch { .. } => "Apply changes?",
};
-
- let border = ("◢◤")
- .repeat((area.width / 2).into())
- .fg(Color::LightYellow);
-
- border.render_ref(area, buf);
- Paragraph::new(" Execution Request ".bold().black().on_light_yellow())
- .alignment(Alignment::Center)
- .render_ref(area, buf);
+ Line::from(title).render(title_area, buf);
self.confirmation_prompt.clone().render(prompt_chunk, buf);
- List::new(lines).render_ref(response_chunk, buf);
+ let areas = Layout::horizontal(
+ lines
+ .iter()
+ .map(|l| Constraint::Length(l.width() as u16 + 2)),
+ )
+ .spacing(1)
+ .split(button_area);
+ for (idx, area) in areas.iter().enumerate() {
+ let line = &lines[idx];
+ line.render(*area, buf);
+ }
- border.render_ref(Rect::new(0, area.y + area.height - 1, area.width, 1), buf);
+ Line::from(self.select_options[self.selected_option].description)
+ .style(Style::new().italic().fg(Color::DarkGray))
+ .render(description_area.inner(Margin::new(1, 0)), buf);
+
+ Block::bordered()
+ .border_type(BorderType::QuadrantOutside)
+ .border_style(Style::default().fg(Color::Cyan))
+ .borders(Borders::LEFT)
+ .render_ref(
+ Rect::new(0, response_chunk.y, 1, response_chunk.height),
+ buf,
+ );
}
}
From d787434aa81c097f242b39c1101ec7f09afa8a72 Mon Sep 17 00:00:00 2001
From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com>
Date: Thu, 31 Jul 2025 17:13:36 -0700
Subject: [PATCH 3/5] fix: always send KeyEvent, we now check kind in the
handler (#1772)
https://github.com/openai/codex/pull/1754 and #1771 fixed the same thing
in colliding ways.
---
codex-rs/tui/src/app.rs | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs
index 7454a1ca11..24b2301bb9 100644
--- a/codex-rs/tui/src/app.rs
+++ b/codex-rs/tui/src/app.rs
@@ -96,9 +96,7 @@ impl App<'_> {
if let Ok(event) = crossterm::event::read() {
match event {
crossterm::event::Event::Key(key_event) => {
- if key_event.kind == crossterm::event::KeyEventKind::Press {
- app_event_tx.send(AppEvent::KeyEvent(key_event));
- }
+ app_event_tx.send(AppEvent::KeyEvent(key_event));
}
crossterm::event::Event::Resize(_, _) => {
app_event_tx.send(AppEvent::RequestRedraw);
From 4aca3e46c84431b6afd883e00baf6189805e2ab1 Mon Sep 17 00:00:00 2001
From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com>
Date: Thu, 31 Jul 2025 17:15:26 -0700
Subject: [PATCH 4/5] insert history lines with redraw (#1769)
This delays the call to insert_history_lines until a redraw is
happening. Crucially, the new lines are inserted _after the viewport is
resized_. This results in fewer stray blank lines below the viewport
when modals (e.g. user approval) are closed.
---
codex-rs/tui/src/app.rs | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs
index 24b2301bb9..a03cc89983 100644
--- a/codex-rs/tui/src/app.rs
+++ b/codex-rs/tui/src/app.rs
@@ -17,6 +17,7 @@ use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::layout::Offset;
use ratatui::prelude::Backend;
+use ratatui::text::Line;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
@@ -55,6 +56,8 @@ pub(crate) struct App<'a> {
/// True when a redraw has been scheduled but not yet executed.
pending_redraw: Arc,
+ pending_history_lines: Vec>,
+
/// Stored parameters needed to instantiate the ChatWidget later, e.g.,
/// after dismissing the Git-repo warning.
chat_args: Option,
@@ -152,6 +155,7 @@ impl App<'_> {
let file_search = FileSearchManager::new(config.cwd.clone(), app_event_tx.clone());
Self {
app_event_tx,
+ pending_history_lines: Vec::new(),
app_event_rx,
app_state,
config,
@@ -197,7 +201,7 @@ impl App<'_> {
while let Ok(event) = self.app_event_rx.recv() {
match event {
AppEvent::InsertHistory(lines) => {
- crate::insert_history::insert_history_lines(terminal, lines);
+ self.pending_history_lines.extend(lines);
self.app_event_tx.send(AppEvent::RequestRedraw);
}
AppEvent::RequestRedraw => {
@@ -409,6 +413,13 @@ impl App<'_> {
terminal.clear()?;
terminal.set_viewport_area(area);
}
+ if !self.pending_history_lines.is_empty() {
+ crate::insert_history::insert_history_lines(
+ terminal,
+ self.pending_history_lines.clone(),
+ );
+ self.pending_history_lines.clear();
+ }
match &mut self.app_state {
AppState::Chat { widget } => {
terminal.draw(|frame| frame.render_widget_ref(&**widget, frame.area()))?;
From 575590e4c2e432e8cf5392a5214da577621d4c8d Mon Sep 17 00:00:00 2001
From: easong-openai
Date: Thu, 31 Jul 2025 17:30:44 -0700
Subject: [PATCH 5/5] Detect kitty terminals (#1748)
We want to detect kitty terminals so we can preferentially upgrade their UX without degrading older terminals.
---
codex-rs/tui/Cargo.toml | 2 ++
codex-rs/tui/src/app.rs | 12 +++++++
.../src/bottom_pane/approval_modal_view.rs | 1 +
codex-rs/tui/src/bottom_pane/chat_composer.rs | 31 +++++++++++++------
codex-rs/tui/src/bottom_pane/mod.rs | 9 +++++-
...mposer__tests__backspace_after_pastes.snap | 2 +-
...tom_pane__chat_composer__tests__empty.snap | 2 +-
...tom_pane__chat_composer__tests__large.snap | 2 +-
...chat_composer__tests__multiple_pastes.snap | 2 +-
...tom_pane__chat_composer__tests__small.snap | 2 +-
codex-rs/tui/src/chatwidget.rs | 2 ++
11 files changed, 52 insertions(+), 15 deletions(-)
diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml
index 63d287ca11..468f2f3be6 100644
--- a/codex-rs/tui/Cargo.toml
+++ b/codex-rs/tui/Cargo.toml
@@ -62,6 +62,8 @@ unicode-segmentation = "1.12.0"
unicode-width = "0.1"
uuid = "1"
+
+
[dev-dependencies]
insta = "1.43.1"
pretty_assertions = "1"
diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs
index a03cc89983..cc3118e860 100644
--- a/codex-rs/tui/src/app.rs
+++ b/codex-rs/tui/src/app.rs
@@ -15,6 +15,7 @@ use crossterm::SynchronizedUpdate;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
+use crossterm::terminal::supports_keyboard_enhancement;
use ratatui::layout::Offset;
use ratatui::prelude::Backend;
use ratatui::text::Line;
@@ -61,6 +62,8 @@ pub(crate) struct App<'a> {
/// Stored parameters needed to instantiate the ChatWidget later, e.g.,
/// after dismissing the Git-repo warning.
chat_args: Option,
+
+ enhanced_keys_supported: bool,
}
/// Aggregate parameters needed to create a `ChatWidget`, as creation may be
@@ -70,6 +73,7 @@ struct ChatWidgetArgs {
config: Config,
initial_prompt: Option,
initial_images: Vec,
+ enhanced_keys_supported: bool,
}
impl App<'_> {
@@ -83,6 +87,8 @@ impl App<'_> {
let app_event_tx = AppEventSender::new(app_event_tx);
let pending_redraw = Arc::new(AtomicBool::new(false));
+ let enhanced_keys_supported = supports_keyboard_enhancement().unwrap_or(false);
+
// Spawn a dedicated thread for reading the crossterm event loop and
// re-publishing the events as AppEvents, as appropriate.
{
@@ -135,6 +141,7 @@ impl App<'_> {
config: config.clone(),
initial_prompt,
initial_images,
+ enhanced_keys_supported,
}),
)
} else {
@@ -143,6 +150,7 @@ impl App<'_> {
app_event_tx.clone(),
initial_prompt,
initial_images,
+ enhanced_keys_supported,
);
(
AppState::Chat {
@@ -162,6 +170,7 @@ impl App<'_> {
file_search,
pending_redraw,
chat_args,
+ enhanced_keys_supported,
}
}
@@ -284,6 +293,7 @@ impl App<'_> {
self.app_event_tx.clone(),
None,
Vec::new(),
+ self.enhanced_keys_supported,
));
self.app_state = AppState::Chat { widget: new_widget };
self.app_event_tx.send(AppEvent::RequestRedraw);
@@ -400,6 +410,7 @@ impl App<'_> {
AppState::Chat { widget } => widget.desired_height(size.width),
AppState::GitWarning { .. } => 10,
};
+
let mut area = terminal.viewport_area;
area.height = desired_height.min(size.height);
area.width = size.width;
@@ -451,6 +462,7 @@ impl App<'_> {
self.app_event_tx.clone(),
args.initial_prompt,
args.initial_images,
+ args.enhanced_keys_supported,
));
self.app_state = AppState::Chat { widget };
self.app_event_tx.send(AppEvent::RequestRedraw);
diff --git a/codex-rs/tui/src/bottom_pane/approval_modal_view.rs b/codex-rs/tui/src/bottom_pane/approval_modal_view.rs
index 4cd952f9eb..8e9ff6d936 100644
--- a/codex-rs/tui/src/bottom_pane/approval_modal_view.rs
+++ b/codex-rs/tui/src/bottom_pane/approval_modal_view.rs
@@ -99,6 +99,7 @@ mod tests {
let mut pane = BottomPane::new(super::super::BottomPaneParams {
app_event_tx: AppEventSender::new(tx_raw2),
has_input_focus: true,
+ enhanced_keys_supported: false,
});
assert_eq!(CancellationEvent::Handled, view.on_ctrl_c(&mut pane));
assert!(view.queue.is_empty());
diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs
index 3bc573a003..7e187bec8b 100644
--- a/codex-rs/tui/src/bottom_pane/chat_composer.rs
+++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs
@@ -41,6 +41,7 @@ pub(crate) struct ChatComposer<'a> {
app_event_tx: AppEventSender,
history: ChatComposerHistory,
ctrl_c_quit_hint: bool,
+ use_shift_enter_hint: bool,
dismissed_file_popup_token: Option,
current_file_query: Option,
pending_pastes: Vec<(String, String)>,
@@ -54,17 +55,24 @@ enum ActivePopup {
}
impl ChatComposer<'_> {
- pub fn new(has_input_focus: bool, app_event_tx: AppEventSender) -> Self {
+ pub fn new(
+ has_input_focus: bool,
+ app_event_tx: AppEventSender,
+ enhanced_keys_supported: bool,
+ ) -> Self {
let mut textarea = TextArea::default();
textarea.set_placeholder_text(BASE_PLACEHOLDER_TEXT);
textarea.set_cursor_line_style(ratatui::style::Style::default());
+ let use_shift_enter_hint = enhanced_keys_supported;
+
let mut this = Self {
textarea,
active_popup: ActivePopup::None,
app_event_tx,
history: ChatComposerHistory::new(),
ctrl_c_quit_hint: false,
+ use_shift_enter_hint,
dismissed_file_popup_token: None,
current_file_query: None,
pending_pastes: Vec::new(),
@@ -712,11 +720,16 @@ impl WidgetRef for &ChatComposer<'_> {
Span::from(" to quit"),
]
} else {
+ let newline_hint_key = if self.use_shift_enter_hint {
+ "Shift+⏎"
+ } else {
+ "Ctrl+J"
+ };
vec![
Span::from(" "),
"⏎".set_style(key_hint_style),
Span::from(" send "),
- "Shift+⏎".set_style(key_hint_style),
+ newline_hint_key.set_style(key_hint_style),
Span::from(" newline "),
"Ctrl+C".set_style(key_hint_style),
Span::from(" quit"),
@@ -890,7 +903,7 @@ mod tests {
let (tx, _rx) = std::sync::mpsc::channel();
let sender = AppEventSender::new(tx);
- let mut composer = ChatComposer::new(true, sender);
+ let mut composer = ChatComposer::new(true, sender, false);
let needs_redraw = composer.handle_paste("hello".to_string());
assert!(needs_redraw);
@@ -913,7 +926,7 @@ mod tests {
let (tx, _rx) = std::sync::mpsc::channel();
let sender = AppEventSender::new(tx);
- let mut composer = ChatComposer::new(true, sender);
+ let mut composer = ChatComposer::new(true, sender, false);
let large = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 10);
let needs_redraw = composer.handle_paste(large.clone());
@@ -942,7 +955,7 @@ mod tests {
let large = "y".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1);
let (tx, _rx) = std::sync::mpsc::channel();
let sender = AppEventSender::new(tx);
- let mut composer = ChatComposer::new(true, sender);
+ let mut composer = ChatComposer::new(true, sender, false);
composer.handle_paste(large);
assert_eq!(composer.pending_pastes.len(), 1);
@@ -978,7 +991,7 @@ mod tests {
for (name, input) in test_cases {
// Create a fresh composer for each test case
- let mut composer = ChatComposer::new(true, sender.clone());
+ let mut composer = ChatComposer::new(true, sender.clone(), false);
if let Some(text) = input {
composer.handle_paste(text);
@@ -1015,7 +1028,7 @@ mod tests {
let (tx, _rx) = std::sync::mpsc::channel();
let sender = AppEventSender::new(tx);
- let mut composer = ChatComposer::new(true, sender);
+ let mut composer = ChatComposer::new(true, sender, false);
// Define test cases: (paste content, is_large)
let test_cases = [
@@ -1088,7 +1101,7 @@ mod tests {
let (tx, _rx) = std::sync::mpsc::channel();
let sender = AppEventSender::new(tx);
- let mut composer = ChatComposer::new(true, sender);
+ let mut composer = ChatComposer::new(true, sender, false);
// Define test cases: (content, is_large)
let test_cases = [
@@ -1161,7 +1174,7 @@ mod tests {
let (tx, _rx) = std::sync::mpsc::channel();
let sender = AppEventSender::new(tx);
- let mut composer = ChatComposer::new(true, sender);
+ let mut composer = ChatComposer::new(true, sender, false);
// Define test cases: (cursor_position_from_end, expected_pending_count)
let test_cases = [
diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs
index 2710a3e997..281f0859a5 100644
--- a/codex-rs/tui/src/bottom_pane/mod.rs
+++ b/codex-rs/tui/src/bottom_pane/mod.rs
@@ -50,12 +50,18 @@ pub(crate) struct BottomPane<'a> {
pub(crate) struct BottomPaneParams {
pub(crate) app_event_tx: AppEventSender,
pub(crate) has_input_focus: bool,
+ pub(crate) enhanced_keys_supported: bool,
}
impl BottomPane<'_> {
pub fn new(params: BottomPaneParams) -> Self {
+ let enhanced_keys_supported = params.enhanced_keys_supported;
Self {
- composer: ChatComposer::new(params.has_input_focus, params.app_event_tx.clone()),
+ composer: ChatComposer::new(
+ params.has_input_focus,
+ params.app_event_tx.clone(),
+ enhanced_keys_supported,
+ ),
active_view: None,
app_event_tx: params.app_event_tx,
has_input_focus: params.has_input_focus,
@@ -298,6 +304,7 @@ mod tests {
let mut pane = BottomPane::new(BottomPaneParams {
app_event_tx: tx,
has_input_focus: true,
+ enhanced_keys_supported: false,
});
pane.push_approval_request(exec_request());
assert_eq!(CancellationEvent::Handled, pane.on_ctrl_c());
diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap
index 4f155dab30..178e2cc40f 100644
--- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap
+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap
@@ -11,4 +11,4 @@ expression: terminal.backend()
"▌ "
"▌ "
"▌ "
-" ⏎ send Shift+⏎ newline Ctrl+C quit "
+" ⏎ send Ctrl+J newline Ctrl+C quit "
diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap
index 4e8371f177..7a1a7f4ef3 100644
--- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap
+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap
@@ -11,4 +11,4 @@ expression: terminal.backend()
"▌ "
"▌ "
"▌ "
-" ⏎ send Shift+⏎ newline Ctrl+C quit "
+" ⏎ send Ctrl+J newline Ctrl+C quit "
diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap
index 80fea40d5f..d3f67c9219 100644
--- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap
+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap
@@ -11,4 +11,4 @@ expression: terminal.backend()
"▌ "
"▌ "
"▌ "
-" ⏎ send Shift+⏎ newline Ctrl+C quit "
+" ⏎ send Ctrl+J newline Ctrl+C quit "
diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap
index 26e8d26733..999e7b2e3f 100644
--- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap
+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap
@@ -11,4 +11,4 @@ expression: terminal.backend()
"▌ "
"▌ "
"▌ "
-" ⏎ send Shift+⏎ newline Ctrl+C quit "
+" ⏎ send Ctrl+J newline Ctrl+C quit "
diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap
index 0f1b9e6426..68d7711aab 100644
--- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap
+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap
@@ -11,4 +11,4 @@ expression: terminal.backend()
"▌ "
"▌ "
"▌ "
-" ⏎ send Shift+⏎ newline Ctrl+C quit "
+" ⏎ send Ctrl+J newline Ctrl+C quit "
diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs
index b0a6fb44e1..4c415777a9 100644
--- a/codex-rs/tui/src/chatwidget.rs
+++ b/codex-rs/tui/src/chatwidget.rs
@@ -95,6 +95,7 @@ impl ChatWidget<'_> {
app_event_tx: AppEventSender,
initial_prompt: Option,
initial_images: Vec,
+ enhanced_keys_supported: bool,
) -> Self {
let (codex_op_tx, mut codex_op_rx) = unbounded_channel::();
@@ -140,6 +141,7 @@ impl ChatWidget<'_> {
bottom_pane: BottomPane::new(BottomPaneParams {
app_event_tx,
has_input_focus: true,
+ enhanced_keys_supported,
}),
config,
initial_user_message: create_initial_user_message(