diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index c79ea2a3df..6be46a3361 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -86,7 +86,7 @@ codex-utils-sandbox-summary = { workspace = true } codex-utils-sleep-inhibitor = { workspace = true } codex-utils-string = { workspace = true } color-eyre = { workspace = true } -crossterm = { workspace = true, features = ["bracketed-paste", "event-stream"] } +crossterm = { workspace = true, features = ["base-layout-key", "bracketed-paste", "event-stream"] } derive_more = { workspace = true, features = ["debug", "is_variant"] } diffy = { workspace = true } dirs = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index e69c629fd6..ae686d25bf 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -903,8 +903,11 @@ impl App { &mut self, tui: &mut tui::Tui, app_server: &mut AppServerSession, - event: TuiEvent, + mut event: TuiEvent, ) -> Result { + if let TuiEvent::Key(key) = &mut event { + *key = self.resolve_key_layout(tui, *key); + } if matches!(event, TuiEvent::Draw) && tui::mouse_capture_disabled() { self.sidebar_press = None; self.chat_widget.end_composer_drag(); diff --git a/codex-rs/tui/src/app/agents_overview_actions.rs b/codex-rs/tui/src/app/agents_overview_actions.rs index f75154a9e0..6a826f123b 100644 --- a/codex-rs/tui/src/app/agents_overview_actions.rs +++ b/codex-rs/tui/src/app/agents_overview_actions.rs @@ -78,6 +78,7 @@ async fn run_lifecycle_modal( .is_some(); match event { tui::TuiEvent::Key(key) if dashboard_active => { + let key = app.resolve_key_layout(tui, key); if let Some(key) = app.route_key_chord_event(tui, key) { if dock_owns_input { if let Some(view) = &mut app.agents_overview.workspace.view { diff --git a/codex-rs/tui/src/app/cloud_switch_wait.rs b/codex-rs/tui/src/app/cloud_switch_wait.rs index 1841efb1df..698e12c63b 100644 --- a/codex-rs/tui/src/app/cloud_switch_wait.rs +++ b/codex-rs/tui/src/app/cloud_switch_wait.rs @@ -68,7 +68,8 @@ fn handle_cloud_switch_event( } } match event { - tui::TuiEvent::Key(mut key) => { + tui::TuiEvent::Key(key) => { + let mut key = app.resolve_key_layout(tui, key); if key.kind == KeyEventKind::Press && crate::key_hint::ctrl(KeyCode::Char('c')).is_press(key) { diff --git a/codex-rs/tui/src/app/input.rs b/codex-rs/tui/src/app/input.rs index df22f70712..544016a5f7 100644 --- a/codex-rs/tui/src/app/input.rs +++ b/codex-rs/tui/src/app/input.rs @@ -7,12 +7,17 @@ use super::*; use crate::app_backtrack::SIDE_EDIT_PREVIOUS_UNAVAILABLE_MESSAGE; use crate::keymap::KeymapContextSet; -use crate::keymap::bindings_for_action; -use crate::keymap::keymap_action_ids; mod select_mode; impl App { + pub(super) fn resolve_key_layout(&self, tui: &tui::Tui, key: KeyEvent) -> KeyEvent { + self.keymap + .resolve_layout(key, &self.key_chord_matcher, || { + self.key_chord_contexts(tui) + }) + } + pub(super) fn overlay_owns_input(&self) -> bool { self.overlay.is_some() } @@ -59,12 +64,7 @@ impl App { && self.chat_widget.composer_text_with_pending().is_empty() && (previous_agent_shortcut_matches(key_event, /*allow_word_motion_fallback*/ true) || next_agent_shortcut_matches(key_event, /*allow_word_motion_fallback*/ true))) - && !keymap_action_ids() - .filter(|action| active_contexts.contains_action(*action)) - .any(|action| { - bindings_for_action(&self.keymap, action.context.config_name(), action.action) - .is_some_and(|bindings| bindings.is_pressed(key_event)) - }) + && !self.keymap.has_single_binding(key_event, active_contexts) && !matches!( self.key_chord_matcher.clone().advance( key_event, diff --git a/codex-rs/tui/src/app/tests/key_chords.rs b/codex-rs/tui/src/app/tests/key_chords.rs index a94645e0a3..4ff2a84172 100644 --- a/codex-rs/tui/src/app/tests/key_chords.rs +++ b/codex-rs/tui/src/app/tests/key_chords.rs @@ -46,16 +46,21 @@ async fn chord_app() -> Result<(Box, Tui, AppServerSession)> { config.list.accept = Some(KeybindingsSpec::One(KeybindingSpec( "ctrl-x enter".to_string(), ))); - let runtime = - RuntimeKeymap::from_config(&config).map_err(|error| color_eyre::eyre::eyre!(error))?; - app.chat_widget.apply_keymap_update(config, &runtime); - app.keymap = runtime; + apply_keymap(&mut app, config)?; let app_server = start_config_write_test_app_server(&app).await?; let tui = crate::tui::test_support::make_test_tui()?; Ok((app, tui, app_server)) } +fn apply_keymap(app: &mut App, config: TuiKeymap) -> Result<()> { + let runtime = + RuntimeKeymap::from_config(&config).map_err(|error| color_eyre::eyre::eyre!(error))?; + app.chat_widget.apply_keymap_update(config, &runtime); + app.keymap = runtime; + Ok(()) +} + pub(super) async fn press( app: &mut App, tui: &mut Tui, @@ -67,10 +72,86 @@ pub(super) async fn press( Ok(()) } -fn ctrl(ch: char) -> KeyEvent { +const fn ctrl(ch: char) -> KeyEvent { KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL) } +const RUSSIAN_CTRL_C: KeyEvent = KeyEvent { + base_layout: Some(('c', KeyModifiers::CONTROL)), + ..ctrl('с') +}; +const RUSSIAN_CTRL_D: KeyEvent = KeyEvent { + base_layout: Some(('d', KeyModifiers::CONTROL)), + ..ctrl('в') +}; + +#[tokio::test] +async fn kitty_control_keys_fall_back_with_default_keymap() -> Result<()> { + let (mut app, mut events, mut operations) = make_test_app_with_channels().await; + let mut app_server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + let thread_id = ThreadId::new(); + app.chat_widget.handle_server_notification( + super::turn_started_notification(thread_id, "turn-1"), + /*replay_kind*/ None, + ); + + press(&mut app, &mut tui, &mut app_server, RUSSIAN_CTRL_C).await?; + assert!(matches!(operations.try_recv()?, super::Op::Interrupt)); + app.chat_widget.handle_server_notification( + super::turn_completed_notification(thread_id, "turn-1", TurnStatus::Interrupted), + /*replay_kind*/ None, + ); + press(&mut app, &mut tui, &mut app_server, RUSSIAN_CTRL_D).await?; + assert!( + std::iter::from_fn(|| events.try_recv().ok()) + .any(|event| matches!(event, AppEvent::Exit(super::ExitMode::ShutdownFirst))) + ); + Ok(()) +} + +#[tokio::test] +async fn kitty_physical_ctrl_c_cancels_approval_with_safe_layout_accept_binding() -> Result<()> { + let (mut app, mut events, _operations) = make_test_app_with_channels().await; + let mut app_server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + apply_keymap(&mut app, toml::from_str("[approval]\napprove = 'alt-y'")?)?; + let thread_id = ThreadId::new(); + app.chat_widget + .handle_thread_session(test_thread_session(thread_id, app.config.cwd.to_path_buf())); + app.active_thread_id = Some(thread_id); + app.chat_widget.handle_server_request( + super::exec_approval_request(thread_id, "turn-1", "call-1", /*approval_id*/ None), + /*replay_kind*/ None, + ); + assert!(app.chat_widget.has_active_modal()); + assert!( + app.chat_widget + .keymap_contexts() + .contains(KeymapContext::Approval) + ); + + press(&mut app, &mut tui, &mut app_server, RUSSIAN_CTRL_C).await?; + let decisions = std::iter::from_fn(|| events.try_recv().ok()) + .filter_map(|event| match event { + AppEvent::SubmitThreadOp { + thread_id, + op: super::Op::ExecApproval { decision, .. }, + } => Some((thread_id, decision)), + _ => None, + }) + .collect::>(); + assert_eq!( + decisions, + vec![( + thread_id, + codex_app_server_protocol::CommandExecutionApprovalDecision::Cancel + )] + ); + assert!(!app.chat_widget.has_active_modal()); + Ok(()) +} + #[tokio::test] async fn empty_thread_backend_chord_preserves_draft_until_first_submission() -> Result<()> { let (mut app, mut events, _operations) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/cwd_prompt.rs b/codex-rs/tui/src/cwd_prompt.rs index 0a0f8702c9..47e1a5b7f9 100644 --- a/codex-rs/tui/src/cwd_prompt.rs +++ b/codex-rs/tui/src/cwd_prompt.rs @@ -131,7 +131,7 @@ pub(crate) async fn run_cwd_selection_prompt( })?; tui.discard_pending_input_before_interactive_screen()?; - let events = tui.event_stream(); + let events = tui.prompt_event_stream(); tokio::pin!(events); while !screen.is_done() { diff --git a/codex-rs/tui/src/daemon_recovery.rs b/codex-rs/tui/src/daemon_recovery.rs index f287c9c021..ca3a75ebf1 100644 --- a/codex-rs/tui/src/daemon_recovery.rs +++ b/codex-rs/tui/src/daemon_recovery.rs @@ -81,16 +81,15 @@ pub(super) async fn check( if let crate::tui::TuiEvent::Key(key) = event && matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) { + let contexts = + crate::keymap::KeymapContextSet::new(crate::keymap::KeymapContext::List); + let key = keymap.resolve_layout(key, &chord_matcher, || contexts); if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char('c' | 'd')) { break None; } - let key = match chord_matcher.advance( - key, - &keymap.chords, - crate::keymap::KeymapContextSet::new(crate::keymap::KeymapContext::List), - ) { + let key = match chord_matcher.advance(key, &keymap.chords, contexts) { crate::keymap::KeyChordMatch::PassThrough => key, crate::keymap::KeyChordMatch::Completed(key) => key, crate::keymap::KeyChordMatch::Pending(_) diff --git a/codex-rs/tui/src/external_agent_config_migration/mod.rs b/codex-rs/tui/src/external_agent_config_migration/mod.rs index 507862b9a6..991036f169 100644 --- a/codex-rs/tui/src/external_agent_config_migration/mod.rs +++ b/codex-rs/tui/src/external_agent_config_migration/mod.rs @@ -100,7 +100,7 @@ pub(crate) async fn run_external_agent_config_migration_prompt( } tui.discard_pending_input_before_interactive_screen()?; - let events = tui.event_stream(); + let events = tui.prompt_event_stream(); tokio::pin!(events); while !screen.is_done() { diff --git a/codex-rs/tui/src/external_agent_config_migration/source.rs b/codex-rs/tui/src/external_agent_config_migration/source.rs index bfdd6b8956..41bef16308 100644 --- a/codex-rs/tui/src/external_agent_config_migration/source.rs +++ b/codex-rs/tui/src/external_agent_config_migration/source.rs @@ -59,7 +59,7 @@ pub(crate) async fn run_external_agent_config_source_prompt( } tui.discard_pending_input_before_interactive_screen()?; - let events = tui.event_stream(); + let events = tui.prompt_event_stream(); tokio::pin!(events); while !screen.is_done() { diff --git a/codex-rs/tui/src/key_hint.rs b/codex-rs/tui/src/key_hint.rs index 78312301c2..933ebffdd2 100644 --- a/codex-rs/tui/src/key_hint.rs +++ b/codex-rs/tui/src/key_hint.rs @@ -166,6 +166,22 @@ impl KeyBinding { } } +/// The terminal can identify the physical Ctrl+C/D keys even when the active +/// layout produces another character. Check the original modifiers because a +/// shifted character can already have consumed Shift in `event.modifiers`. +pub(crate) fn base_layout_shortcut(event: KeyEvent) -> Option { + let (KeyCode::Char(active), Some((base @ ('c' | 'd'), KeyModifiers::CONTROL))) = + (event.code, event.base_layout) + else { + return None; + }; + (!active.is_ascii()).then_some(KeyEvent { + code: KeyCode::Char(base), + base_layout: None, + ..event + }) +} + pub(crate) fn normalize_key_parts( key: KeyCode, mut modifiers: KeyModifiers, diff --git a/codex-rs/tui/src/keymap.rs b/codex-rs/tui/src/keymap.rs index 175acc4d2a..c33292db9c 100644 --- a/codex-rs/tui/src/keymap.rs +++ b/codex-rs/tui/src/keymap.rs @@ -666,6 +666,50 @@ macro_rules! default_bindings { } impl RuntimeKeymap { + /// Resolve the layout before a fixed shortcut can intercept a configured + /// binding on the focused surface. Key capture needs the original character. + pub(crate) fn resolve_layout( + &self, + event: KeyEvent, + matcher: &KeyChordMatcher, + contexts: impl FnOnce() -> KeymapContextSet, + ) -> KeyEvent { + let Some(fallback) = key_hint::base_layout_shortcut(event) else { + return event; + }; + let contexts = contexts(); + if contexts.captures_raw_keys() { + return event; + } + // List and approval surfaces reserve Ctrl+C for cancellation even when + // the active layout character is configured as an approval shortcut. + if (contexts.contains(KeymapContext::Approval) || contexts.contains(KeymapContext::List)) + && fallback.code == KeyCode::Char('c') + { + return fallback; + } + // Use the press identity for matching even when the terminal reports + // a repeat or release. The dispatched event keeps its original kind. + let press = KeyEvent { + kind: crossterm::event::KeyEventKind::Press, + ..event + }; + if self.has_single_binding(press, contexts) { + return event; + } + match matcher.clone().advance(press, &self.chords, contexts) { + KeyChordMatch::Pending(_) | KeyChordMatch::Completed(_) | KeyChordMatch::Cancelled => { + event + } + KeyChordMatch::Ignored | KeyChordMatch::PassThrough => fallback, + } + } + + pub(crate) fn has_single_binding(&self, event: KeyEvent, contexts: KeymapContextSet) -> bool { + runtime_action_bindings(self) + .any(|action| contexts.contains_action(action.id) && action.bindings.is_pressed(event)) + } + /// Return built-in defaults. /// /// This is a convenience for tests and bootstrapping UI state before user diff --git a/codex-rs/tui/src/keymap/chords.rs b/codex-rs/tui/src/keymap/chords.rs index 10b5671a37..4ec92ab78e 100644 --- a/codex-rs/tui/src/keymap/chords.rs +++ b/codex-rs/tui/src/keymap/chords.rs @@ -145,6 +145,10 @@ impl KeymapContextSet { Self(RAW_KEY_CAPTURE) } + pub(super) fn captures_raw_keys(self) -> bool { + self.0 & RAW_KEY_CAPTURE != 0 + } + /// Only function-key voice bindings extend beyond chat; other surfaces own editing keys. /// Existing surface bindings and chord prefixes still win. pub(crate) fn with_voice_toggle(self, keymap: &RuntimeKeymap) -> Self { @@ -184,7 +188,7 @@ impl KeymapContextSet { && completion.is_none_or(|key| key == binding.chord.completion) }) }); - if self.0 & RAW_KEY_CAPTURE != 0 || conflicts { + if self.captures_raw_keys() || conflicts { Self(self.0 | VOICE_TOGGLE_BLOCKED) } else { Self(self.0 | VOICE_TOGGLE) diff --git a/codex-rs/tui/src/model_migration.rs b/codex-rs/tui/src/model_migration.rs index 47ed0fdb4f..54f80e55bc 100644 --- a/codex-rs/tui/src/model_migration.rs +++ b/codex-rs/tui/src/model_migration.rs @@ -151,7 +151,7 @@ pub(crate) async fn run_model_migration_prompt( })?; alt.tui.discard_pending_input_before_interactive_screen()?; - let events = alt.tui.event_stream(); + let events = alt.tui.prompt_event_stream(); tokio::pin!(events); while !screen.is_done() { diff --git a/codex-rs/tui/src/onboarding/onboarding_screen.rs b/codex-rs/tui/src/onboarding/onboarding_screen.rs index 0c2bbf8769..e2402944e8 100644 --- a/codex-rs/tui/src/onboarding/onboarding_screen.rs +++ b/codex-rs/tui/src/onboarding/onboarding_screen.rs @@ -770,6 +770,7 @@ async fn run_onboarding_screen_inner( tui.screen_size_for_event(&event)?; match event { TuiEvent::Key(key_event) => { + let key_event = crate::key_hint::base_layout_shortcut(key_event).unwrap_or(key_event); let copy_link = if key_event.kind == KeyEventKind::Press && keys::COPY_LINK.is_pressed(key_event) && let Some(Step::Auth(widget)) = onboarding_screen.current_steps().last() diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 375d2641c0..24e90773f6 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -19,6 +19,7 @@ use crate::legacy_core::config::Config; use crate::legacy_core::config::edit::ConfigEditsBuilder; use crate::markdown_render::render_streaming_markdown_lines_with_width_and_cwd as render_assistant; use crate::pager_overlay::Overlay; +use crate::pager_overlay::TranscriptOverlay; use crate::status::format_directory_display; use crate::style::footer_hint_label_style; use crate::style::readable_color_on; @@ -1429,45 +1430,47 @@ impl PickerState { use crate::keymap::KeymapContext; use crate::keymap::KeymapContextSet; - let mut contexts = KeymapContextSet::new(if self.overlay.is_some() { + let transcript = self.overlay.as_ref().and_then(Overlay::input_transcript); + let searching = transcript.is_some_and(TranscriptOverlay::is_search_editing); + let selecting = !searching && transcript.is_some_and(TranscriptOverlay::is_select_mode); + let mut contexts = KeymapContextSet::new(if searching { + KeymapContext::Editor + } else if self.overlay.is_some() { KeymapContext::Pager } else { KeymapContext::List }); - if let Some(Overlay::Transcript(overlay)) = &self.overlay { - if overlay.is_search_editing() { - contexts = KeymapContextSet::new(KeymapContext::Editor); - } - let selecting = overlay.is_select_mode() && !overlay.is_search_editing(); - if selecting { - contexts = contexts.with_transcript_select(); - } - if overlay.owns_interaction_key(key) { - let markdown_chord = selecting - && match self - .chord_matcher - .clone() - .advance(key, &self.keymap.chords, contexts) - { - KeyChordMatch::Completed(key) => { - self.keymap.pager.mark_markdown.is_pressed(key) - } - KeyChordMatch::Pending(prefix) => { - self.keymap.chords.bindings.iter().any(|binding| { - binding.action.action == "mark_markdown" - && binding.chord.prefix == prefix - }) - } - KeyChordMatch::PassThrough - | KeyChordMatch::Cancelled - | KeyChordMatch::Ignored => false, - }; - if !markdown_chord { - if self.chord_matcher.cancel() { - self.requester.schedule_frame(); + if selecting { + contexts = contexts.with_transcript_select(); + } + let key = self + .keymap + .resolve_layout(key, &self.chord_matcher, || contexts); + if transcript.is_some_and(|view| view.owns_interaction_key(key)) { + let markdown_chord = selecting + && match self + .chord_matcher + .clone() + .advance(key, &self.keymap.chords, contexts) + { + KeyChordMatch::Completed(key) => { + self.keymap.pager.mark_markdown.is_pressed(key) } - return Some(key); + KeyChordMatch::Pending(prefix) => { + self.keymap.chords.bindings.iter().any(|binding| { + binding.action.action == "mark_markdown" + && binding.chord.prefix == prefix + }) + } + KeyChordMatch::PassThrough + | KeyChordMatch::Cancelled + | KeyChordMatch::Ignored => false, + }; + if !markdown_chord { + if self.chord_matcher.cancel() { + self.requester.schedule_frame(); } + return Some(key); } } let was_pending = self.chord_matcher.is_pending(); diff --git a/codex-rs/tui/src/startup_draft_input.rs b/codex-rs/tui/src/startup_draft_input.rs index 1035b4a05c..9d018b2e0e 100644 --- a/codex-rs/tui/src/startup_draft_input.rs +++ b/codex-rs/tui/src/startup_draft_input.rs @@ -82,6 +82,16 @@ impl StartupDraftPump { } match event { TuiEvent::Key(key) => { + let key = + self.bottom_pane + .keymap() + .resolve_layout(key, &self.key_chord_matcher, || { + if self.initial_screen == StartupDraftInitialScreen::Composer { + self.bottom_pane.keymap_contexts() + } else { + crate::keymap::KeymapContextSet::default() + } + }); if self.initial_screen != StartupDraftInitialScreen::Composer && !key_hint::ctrl(KeyCode::Char('c')).is_press(key) && !key_hint::ctrl(KeyCode::Char('d')).is_press(key) diff --git a/codex-rs/tui/src/startup_hooks_review.rs b/codex-rs/tui/src/startup_hooks_review.rs index 27e83d9859..d205334573 100644 --- a/codex-rs/tui/src/startup_hooks_review.rs +++ b/codex-rs/tui/src/startup_hooks_review.rs @@ -117,23 +117,7 @@ async fn run_startup_hooks_review_app( } match event { TuiEvent::Key(key_event) => { - let key_event = match chord_matcher.advance( - key_event, - &keymap.chords, - crate::keymap::KeymapContextSet::new(crate::keymap::KeymapContext::List), - ) { - crate::keymap::KeyChordMatch::PassThrough => key_event, - crate::keymap::KeyChordMatch::Completed(dispatch_event) => dispatch_event, - crate::keymap::KeyChordMatch::Pending(_) - | crate::keymap::KeyChordMatch::Cancelled => { - tui.frame_requester().schedule_frame(); - continue; - } - crate::keymap::KeyChordMatch::Ignored => continue, - }; - if matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat) { - view.handle_key_event(key_event); - } + handle_review_key(&mut view, &mut chord_matcher, &keymap, key_event); let Some(selection) = selected_choice(&mut view) else { draw_view(tui, &view, &chord_matcher, &keymap)?; continue; @@ -197,6 +181,36 @@ async fn run_startup_hooks_review_app( } } +/// Trust confirmation reserves physical Ctrl+C before configurable list bindings. +fn handle_review_key( + view: &mut ListSelectionView, + chord_matcher: &mut crate::keymap::KeyChordMatcher, + keymap: &RuntimeKeymap, + key_event: crossterm::event::KeyEvent, +) { + let physical = crate::key_hint::base_layout_shortcut(key_event).unwrap_or(key_event); + if matches!(physical.kind, KeyEventKind::Press | KeyEventKind::Repeat) + && matches!(physical.code, crossterm::event::KeyCode::Char(c) if c.eq_ignore_ascii_case(&'c')) + && physical.modifiers == crossterm::event::KeyModifiers::CONTROL + { + chord_matcher.cancel(); + view.on_ctrl_c(); + return; + } + let contexts = crate::keymap::KeymapContextSet::new(crate::keymap::KeymapContext::List); + let key_event = keymap.resolve_layout(key_event, chord_matcher, || contexts); + let key_event = match chord_matcher.advance(key_event, &keymap.chords, contexts) { + crate::keymap::KeyChordMatch::PassThrough => key_event, + crate::keymap::KeyChordMatch::Completed(dispatch_event) => dispatch_event, + crate::keymap::KeyChordMatch::Pending(_) + | crate::keymap::KeyChordMatch::Cancelled + | crate::keymap::KeyChordMatch::Ignored => return, + }; + if matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat) { + view.handle_key_event(key_event); + } +} + fn selected_choice(view: &mut ListSelectionView) -> Option { if !view.is_complete() { return None; @@ -333,6 +347,10 @@ impl WidgetRef for &StandaloneSelectionView<'_> { } } +#[cfg(test)] +#[path = "startup_hooks_review_layout_tests.rs"] +mod layout_tests; + #[cfg(test)] mod tests { use super::StartupHooksReviewSelection; @@ -385,7 +403,7 @@ mod tests { } } - fn entry() -> HooksListEntry { + pub(super) fn entry() -> HooksListEntry { HooksListEntry { cwd: test_path_buf("/tmp"), hooks: vec![ diff --git a/codex-rs/tui/src/startup_hooks_review_layout_tests.rs b/codex-rs/tui/src/startup_hooks_review_layout_tests.rs new file mode 100644 index 0000000000..4533454991 --- /dev/null +++ b/codex-rs/tui/src/startup_hooks_review_layout_tests.rs @@ -0,0 +1,68 @@ +//! Startup-hook trust must keep physical Ctrl+C cancellation ahead of configured bindings. + +#![cfg(test)] + +use super::tests::entry; +use super::*; +use crossterm::event::KeyCode; +use crossterm::event::KeyEvent; +use crossterm::event::KeyModifiers; +use pretty_assertions::assert_eq; + +#[test] +fn physical_ctrl_c_cannot_confirm_startup_hook_trust_through_layout_binding() { + let config = toml::from_str("[list]\naccept = 'alt-y'").unwrap(); + let keymap = RuntimeKeymap::from_config(&config).unwrap(); + for (code, base_layout, modifiers, expected) in [ + ( + 'с', + Some(('c', KeyModifiers::CONTROL)), + KeyModifiers::CONTROL, + Some(StartupHooksReviewSelection::ContinueWithoutTrusting), + ), + ('с', None, KeyModifiers::CONTROL, None), + ( + 'y', + None, + KeyModifiers::ALT, + Some(StartupHooksReviewSelection::TrustAllAndContinue), + ), + ( + 'c', + None, + KeyModifiers::CONTROL, + Some(StartupHooksReviewSelection::ContinueWithoutTrusting), + ), + ( + 'C', + None, + KeyModifiers::CONTROL, + Some(StartupHooksReviewSelection::ContinueWithoutTrusting), + ), + ] { + let (tx_raw, _rx) = unbounded_channel::(); + let mut view = selection_view( + &entry(), + /*trust_all_error*/ None, + /*trusting_all*/ false, + AppEventSender::new(tx_raw), + &keymap, + ); + let mut matcher = crate::keymap::KeyChordMatcher::default(); + // Selecting the trust row alone must not confirm it. + view.handle_key_event(KeyEvent::new(KeyCode::Char('2'), KeyModifiers::NONE)); + assert_eq!(view.selected_index(), Some(1)); + assert!(!view.is_complete()); + handle_review_key( + &mut view, + &mut matcher, + &keymap, + KeyEvent { + base_layout, + ..KeyEvent::new(KeyCode::Char(code), modifiers) + }, + ); + assert_eq!(selected_choice(&mut view), expected); + assert!(!matcher.is_pending()); + } +} diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 3ca78bb4d0..ec1d81246e 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -1194,6 +1194,19 @@ impl Tui { Box::pin(self.input_stream()) } + /// Standalone prompts have fixed shortcuts. Surfaces with a keymap + /// resolve the layout after determining which bindings have focus. + pub(crate) fn prompt_event_stream(&self) -> impl Stream + Send + use<> { + tokio_stream::StreamExt::map(self.input_stream(), |mut event| { + if let TuiEvent::Key(key) = &mut event + && let Some(fallback) = crate::key_hint::base_layout_shortcut(*key) + { + *key = fallback; + } + event + }) + } + pub(crate) fn input_stream(&self) -> TuiEventStream { TuiEventStream::new( self.event_broker.clone(), diff --git a/codex-rs/tui/src/unarchive_prompt.rs b/codex-rs/tui/src/unarchive_prompt.rs index 96cac7dac5..9188c540a4 100644 --- a/codex-rs/tui/src/unarchive_prompt.rs +++ b/codex-rs/tui/src/unarchive_prompt.rs @@ -46,7 +46,7 @@ pub(crate) async fn run_unarchive_prompt( guard .tui .discard_pending_input_before_interactive_screen()?; - let events = guard.tui.event_stream(); + let events = guard.tui.prompt_event_stream(); tokio::pin!(events); guard.draw(&screen)?; loop { diff --git a/codex-rs/tui/src/update_prompt.rs b/codex-rs/tui/src/update_prompt.rs index c675bba22d..205aa086dc 100644 --- a/codex-rs/tui/src/update_prompt.rs +++ b/codex-rs/tui/src/update_prompt.rs @@ -75,7 +75,9 @@ pub(crate) async fn run_update_prompt_if_needed( if let Some(event) = events.next().await { tui.screen_size_for_event(&event)?; match event { - TuiEvent::Key(key_event) => screen.handle_key(key_event), + TuiEvent::Key(key_event) => screen.handle_key( + crate::key_hint::base_layout_shortcut(key_event).unwrap_or(key_event), + ), TuiEvent::Paste(_) | TuiEvent::FocusLost | TuiEvent::Mouse(_) => {} TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained => { tui.draw(u16::MAX, |frame| {