Support Unicode characters in TUI keybindings (#65176)

## Why

The TUI keymap required ASCII characters, so users on layouts such as Russian
could press `Ctrl+В` but could not save the corresponding `ctrl-в` shortcut.

## What changed

Accept Unicode character keys in `tui.keymap` and shortcut capture, including
modified keys and chord strokes. Apply the same case handling to configured
bindings and terminal events so `Ф` and `shift-ф` match the same keypress.

Keep Kitty's base-layout Ctrl+C and Ctrl+D fallbacks when no active binding
claims the reported key. Reserve physical Ctrl+C for list cancellation and
reject non-ASCII character bindings on actions that can grant consent,
including both strokes of a chord and expanded leader prefixes.

## Testing

Add regression tests for Unicode capture, chord matching and conflicts,
Ctrl+C and Ctrl+D fallback behavior, and consent safeguards.

GitOrigin-RevId: 8624218efcba2784f19f502770523fe00c6f1af1
This commit is contained in:
Felipe Coury
2026-12-02 06:30:47 +00:00
committed by copyberry
parent 21e643d32e
commit 0d17a47212
18 changed files with 921 additions and 27 deletions
+1
View File
@@ -2953,6 +2953,7 @@ dependencies = [
"tonic-prost",
"tonic-prost-build",
"tracing",
"unicode-general-category",
"wildmatch",
"winapi-util",
"windows-sys 0.61.2",
+1
View File
@@ -582,6 +582,7 @@ uds_windows = "1.1.0"
unicode-bidi = "0.3.18"
unicode-linebreak = "0.1.5"
unicode-normalization = "0.1.25"
unicode-general-category = "1.1"
unicode-segmentation = "1.12.0"
unicode-width = "0.2"
url = "2"
+1
View File
@@ -47,6 +47,7 @@ toml_edit = { workspace = true }
tonic = { workspace = true, features = ["tls-native-roots", "tls-ring"] }
tonic-prost = { workspace = true }
tracing = { workspace = true }
unicode-general-category = { workspace = true }
wildmatch = { workspace = true }
[target.'cfg(unix)'.dependencies]
+35 -5
View File
@@ -25,6 +25,8 @@ use serde::de::SeqAccess;
use serde::de::Visitor;
use std::collections::BTreeMap;
use std::fmt;
use unicode_general_category::GeneralCategory;
use unicode_general_category::get_general_category;
/// Highest function key supported by portable TUI keymap configuration.
pub const MAX_FUNCTION_KEY: u8 = 24;
@@ -43,6 +45,14 @@ const MAX_KEY_CHORD_STROKES: usize = 2;
pub struct KeybindingSpec(#[schemars(with = "String")] pub String);
impl KeybindingSpec {
/// Whether a character can be written literally in a keybinding stroke.
pub fn is_literal_character(ch: char) -> bool {
!ch.is_control()
&& !ch.is_whitespace()
&& ch != '-'
&& get_general_category(ch) != GeneralCategory::Format
}
/// Returns the canonical key-spec string (for example `ctrl-x ctrl-s`).
pub fn as_str(&self) -> &str {
self.0.as_str()
@@ -777,11 +787,11 @@ fn normalize_key_name(key: &str, original: &str) -> Result<String, String> {
other => other,
};
if alias.len() == 1 {
let ch = alias.chars().next().unwrap_or_default();
if ch.is_ascii() && !ch.is_ascii_control() && ch != '-' {
return Ok(alias.to_string());
}
if alias
.parse()
.is_ok_and(KeybindingSpec::is_literal_character)
{
return Ok(alias.to_string());
}
if matches!(
@@ -825,6 +835,26 @@ mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn formatting_characters_cannot_replace_list_shortcuts() {
for ch in ['\u{200b}', '\u{202e}', '\u{2066}', '\u{feff}', '\u{e0001}'] {
for binding in [ch.to_string(), format!("ctrl-{ch}"), format!("ctrl-x {ch}")] {
let config = format!("[list]\nmove_down = '{binding}'");
let error = toml::from_str::<TuiKeymap>(&config)
.expect_err("formatting characters must not replace navigable shortcuts");
assert!(error.to_string().contains("unknown key"));
}
}
for binding in ["с", "ctrl-с", "界", "shift-Ф", "ctrl-x é", "alt-y"] {
let config = format!("[list]\nmove_down = '{binding}'");
let parsed = toml::from_str::<TuiKeymap>(&config).expect("visible shortcut");
assert_eq!(
parsed.list.move_down,
Some(KeybindingsSpec::One(KeybindingSpec(binding.to_owned())))
);
}
}
#[test]
fn action_under_global_context_is_accepted() {
let toml_input = r#"
+234 -12
View File
@@ -86,10 +86,14 @@ const RUSSIAN_CTRL_D: KeyEvent = KeyEvent {
};
#[tokio::test]
async fn kitty_control_keys_fall_back_with_default_keymap() -> Result<()> {
async fn kitty_control_keys_fall_back_when_the_layout_binding_is_inactive() -> 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()?;
apply_keymap(
&mut app,
toml::from_str("[list]\nmove_down = ['ctrl-с', 'ctrl-в']")?,
)?;
let thread_id = ThreadId::new();
app.chat_widget.handle_server_notification(
super::turn_started_notification(thread_id, "turn-1"),
@@ -110,11 +114,32 @@ async fn kitty_control_keys_fall_back_with_default_keymap() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn kitty_control_keys_dispatch_active_layout_bindings_before_fixed_shortcuts() -> Result<()> {
let (mut app, mut tui, mut app_server) = chord_app().await?;
let config = toml::from_str(
r#"
[global]
toggle_raw_output = "ctrl-в"
[composer]
history_search_previous = "ctrl-с"
"#,
)?;
apply_keymap(&mut app, config)?;
press(&mut app, &mut tui, &mut app_server, RUSSIAN_CTRL_D).await?;
assert!(app.chat_widget.raw_output_mode());
press(&mut app, &mut tui, &mut app_server, RUSSIAN_CTRL_C).await?;
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("reverse-i-search:"));
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()?;
assert!(apply_keymap(&mut app, toml::from_str("[approval]\napprove = 'ctrl-с'")?).is_err());
apply_keymap(&mut app, toml::from_str("[approval]\napprove = 'alt-y'")?)?;
let thread_id = ThreadId::new();
app.chat_widget
@@ -152,6 +177,151 @@ async fn kitty_physical_ctrl_c_cancels_approval_with_safe_layout_accept_binding(
Ok(())
}
#[tokio::test]
async fn kitty_physical_ctrl_c_cannot_confirm_full_access_through_list_binding() -> Result<()> {
for (base_layout, modifiers, expected_policy_updates, remains_open) in [
(
Some(('c', KeyModifiers::CONTROL)),
KeyModifiers::CONTROL,
0,
false,
),
(None, KeyModifiers::CONTROL, 0, true),
(None, KeyModifiers::ALT, 2, false),
] {
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()?;
assert!(apply_keymap(&mut app, toml::from_str("[list]\naccept = 'ctrl-с'")?).is_err());
apply_keymap(&mut app, toml::from_str("[list]\naccept = 'alt-y'")?)?;
let preset = codex_utils_approval_presets::builtin_approval_presets()
.into_iter()
.find(|preset| preset.id == "full-access")
.expect("full access preset");
app.chat_widget.open_full_access_confirmation(
preset, /*return_to_permissions*/ false, /*profile_selection*/ None,
);
assert!(
render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("Enable full access?")
);
assert!(
app.chat_widget
.keymap_contexts()
.contains(KeymapContext::List)
);
while events.try_recv().is_ok() {}
press(
&mut app,
&mut tui,
&mut app_server,
KeyEvent {
base_layout,
modifiers,
..ctrl(if modifiers == KeyModifiers::ALT {
'y'
} else {
'с'
})
},
)
.await?;
let policy_updates = std::iter::from_fn(|| events.try_recv().ok())
.filter(|event| {
matches!(
event,
AppEvent::UpdateAskForApprovalPolicy(_)
| AppEvent::UpdateActivePermissionProfile(_)
)
})
.count();
assert_eq!(policy_updates, expected_policy_updates);
assert_eq!(app.chat_widget.has_active_modal(), remains_open);
}
Ok(())
}
#[tokio::test]
async fn kitty_physical_ctrl_c_cannot_approve_guardian_denial_through_list_binding() -> Result<()> {
use codex_app_server_protocol as protocol;
for (base_layout, modifiers, expected_approvals, remains_open) in [
(
Some(('c', KeyModifiers::CONTROL)),
KeyModifiers::CONTROL,
0,
false,
),
(None, KeyModifiers::CONTROL, 0, true),
(None, KeyModifiers::ALT, 1, false),
] {
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()?;
assert!(apply_keymap(&mut app, toml::from_str("[list]\naccept = 'ctrl-с'")?).is_err());
apply_keymap(&mut app, toml::from_str("[list]\naccept = '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_notification(
protocol::ServerNotification::ItemGuardianApprovalReviewCompleted(
protocol::ItemGuardianApprovalReviewCompletedNotification {
thread_id: thread_id.to_string(),
turn_id: "turn-denied".to_string(),
started_at_ms: 0,
completed_at_ms: 1,
review_id: "denied-action".to_string(),
target_item_id: None,
decision_source: protocol::AutoReviewDecisionSource::Agent,
review: protocol::GuardianApprovalReview {
status: protocol::GuardianApprovalReviewStatus::Denied,
risk_level: None,
user_authorization: None,
rationale: Some("Requires explicit consent".to_string()),
},
action: protocol::GuardianApprovalReviewAction::Command {
source: protocol::GuardianCommandSource::Shell,
command: "echo guarded".to_string(),
cwd: app.config.cwd.clone().into(),
},
},
),
/*replay_kind*/ None,
);
app.chat_widget.open_auto_review_denials_popup();
assert!(
render_bottom_popup(&app.chat_widget, /*width*/ 80)
.contains("Select a denied action to approve.")
);
while events.try_recv().is_ok() {}
press(
&mut app,
&mut tui,
&mut app_server,
KeyEvent {
base_layout,
modifiers,
..ctrl(if modifiers == KeyModifiers::ALT {
'y'
} else {
'с'
})
},
)
.await?;
let approvals = std::iter::from_fn(|| events.try_recv().ok())
.filter(|event| matches!(event, AppEvent::ApproveRecentAutoReviewDenial { thread_id: target, id } if *target == thread_id && id == "denied-action"))
.count();
assert_eq!(approvals, expected_approvals);
assert_eq!(app.chat_widget.has_active_modal(), remains_open);
}
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;
@@ -753,8 +923,9 @@ async fn legacy_terminal_preserves_configured_composer_alt_shortcuts() -> Result
#[cfg(unix)]
#[tokio::test]
async fn legacy_terminal_preserves_active_alt_chords() -> Result<()> {
async fn terminal_fallbacks_preserve_active_chord_strokes() -> Result<()> {
for (binding, prefix, completion) in [
("ctrl-в ctrl-с", RUSSIAN_CTRL_D, RUSSIAN_CTRL_C),
(
"alt-q r",
KeyEvent::new(KeyCode::Char('q'), KeyModifiers::ALT),
@@ -1781,6 +1952,53 @@ parent draft!");
Ok(())
}
#[tokio::test]
async fn key_capture_rejects_unusable_list_shortcuts_through_app() -> Result<()> {
let (mut app, mut rx, _op_rx) = 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()?;
for (key, warning) in [
(RUSSIAN_CTRL_C, "Ctrl+C, which exits list pickers"),
(KeyCode::Char('\u{200b}').into(), "Only printable keys"),
(KeyCode::Char('\u{202e}').into(), "Only printable keys"),
] {
app.chat_widget.open_keymap_capture(
"list".into(),
"move_down".into(),
crate::app_event::KeymapEditIntent::ReplaceAll,
crate::app_event::KeymapCaptureMode::SingleKey,
&app.keymap,
);
press(&mut app, &mut tui, &mut app_server, key).await?;
assert!(rx.try_recv().is_err(), "invalid shortcut must not be saved");
assert!(!app.chat_widget.no_modal_or_popup_active());
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 100).contains(warning));
press(
&mut app,
&mut tui,
&mut app_server,
KeyEvent::new(KeyCode::Char('j'), KeyModifiers::ALT),
)
.await?;
let AppEvent::KeymapCaptured {
context,
action,
key,
..
} = rx.try_recv()?
else {
panic!("expected the replacement shortcut");
};
assert_eq!(
(context.as_str(), action.as_str(), key.as_str()),
("list", "move_down", "alt-j")
);
assert!(app.chat_widget.no_modal_or_popup_active());
}
app_server.shutdown().await?;
Ok(())
}
#[tokio::test]
async fn key_capture_receives_voice_shortcut_and_chord_prefix() -> Result<()> {
let (mut app, mut rx, _op_rx) = super::make_test_app_with_channels().await;
@@ -1793,14 +2011,18 @@ async fn key_capture_receives_voice_shortcut_and_chord_prefix() -> Result<()> {
let child = ThreadId::new();
app.side_threads
.insert(child, super::SideThreadState::new(parent));
for (config, key) in [
("", 8),
("[chat]\ntoggle_voice = 'f8 v'", 8),
("[global]\nhide_pane = 'f12'", 12),
("[global]\nfocus_main_composer = 'f12'", 12),
("[global]\nfocus_sidebar_content = 'f12 s'", 12),
("[global]\nfocus_pane_left = 'f12 h'", 12),
("[global]\nfocus_pane_right = 'f12 l'", 12),
let f8 = KeyCode::F(8).into();
let f12 = KeyCode::F(12).into();
for (config, key, expected) in [
("", RUSSIAN_CTRL_C, "ctrl-с"),
("", RUSSIAN_CTRL_D, "ctrl-в"),
("", f8, "f8"),
("[chat]\ntoggle_voice = 'f8 v'", f8, "f8"),
("[global]\nhide_pane = 'f12'", f12, "f12"),
("[global]\nfocus_main_composer = 'f12'", f12, "f12"),
("[global]\nfocus_sidebar_content = 'f12 s'", f12, "f12"),
("[global]\nfocus_pane_left = 'f12 h'", f12, "f12"),
("[global]\nfocus_pane_right = 'f12 l'", f12, "f12"),
] {
app.keymap =
RuntimeKeymap::for_session(&toml::from_str(config)?, /*workspace*/ true).unwrap();
@@ -1811,9 +2033,9 @@ async fn key_capture_receives_voice_shortcut_and_chord_prefix() -> Result<()> {
crate::app_event::KeymapCaptureMode::SingleKey,
&app.keymap,
);
press(&mut app, &mut tui, &mut app_server, KeyCode::F(key).into()).await?;
press(&mut app, &mut tui, &mut app_server, key).await?;
assert!(
matches!(rx.try_recv()?, crate::app_event::AppEvent::KeymapCaptured { key: captured, .. } if captured == format!("f{key}"))
matches!(rx.try_recv()?, crate::app_event::AppEvent::KeymapCaptured { key: captured, .. } if captured == expected)
);
}
// A printable remap belongs to the composer unless this session and thread own a pane.
@@ -2591,6 +2591,21 @@ mod tests {
keymap.approval,
keymap.list,
);
let ambiguous = toml::from_str("[approval]\napprove = 'т'").unwrap();
assert!(crate::keymap::RuntimeKeymap::from_config(&ambiguous).is_err());
assert!(render_overlay_lines(&view, /*width*/ 80).contains("Decline and continue (n)"));
// Plain UTF-8 has no physical-key metadata: Russian N must not approve.
view.handle_key_event(KeyEvent::new(KeyCode::Char('т'), KeyModifiers::NONE));
assert!(!view.is_complete());
assert!(
!std::iter::from_fn(|| rx.try_recv().ok()).any(|event| matches!(
event,
AppEvent::SubmitThreadOp {
op: Op::ResolveElicitation { .. },
..
}
))
);
view.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
let mut n_decision = None;
while let Ok(ev) = rx.try_recv() {
@@ -1800,6 +1800,10 @@ fn wrap_footer_tips(width: u16, tips: Vec<Line<'static>>) -> Vec<Vec<Line<'stati
)
}
#[cfg(test)]
#[path = "mcp_server_elicitation_consent_tests.rs"]
mod consent_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -1812,12 +1816,12 @@ mod tests {
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::mpsc::unbounded_channel;
fn test_sender() -> (AppEventSender, UnboundedReceiver<AppEvent>) {
pub(super) fn test_sender() -> (AppEventSender, UnboundedReceiver<AppEvent>) {
let (tx_raw, rx) = unbounded_channel::<AppEvent>();
(AppEventSender::new(tx_raw), rx)
}
fn form_request(
pub(super) fn form_request(
message: &str,
requested_schema: Value,
meta: Option<Value>,
@@ -1840,7 +1844,7 @@ mod tests {
AppServerRequestId::String(value.to_string())
}
fn from_form_request(
pub(super) fn from_form_request(
thread_id: ThreadId,
request: McpServerElicitationRequestParams,
) -> Option<McpServerElicitationFormRequest> {
@@ -0,0 +1,66 @@
//! MCP text forms preserve drafts until an unambiguous configured shortcut grants consent.
#![cfg(test)]
use super::tests::form_request;
use super::tests::from_form_request;
use super::tests::test_sender;
use super::*;
use crate::app_event::AppEvent;
#[test]
fn text_fields_cannot_accept_through_ambiguous_control_bindings() {
for action in ["submit", "queue"] {
let ambiguous = toml::from_str(&format!("[composer]\n{action} = 'ctrl-с'")).unwrap();
assert!(RuntimeKeymap::from_config(&ambiguous).is_err());
let config = toml::from_str(&format!("[composer]\n{action} = 'alt-y'")).unwrap();
let keymap = RuntimeKeymap::from_config(&config).unwrap();
let (tx, mut events) = test_sender();
let request = from_form_request(
ThreadId::default(),
form_request(
"Enter a name",
serde_json::json!({
"type": "object",
"properties": {"name": {"type": "string"}},
"required": ["name"],
}),
/*meta*/ None,
),
)
.unwrap();
let mut overlay = McpServerElicitationOverlay::new_with_keymap(
request, tx, /*has_input_focus*/ true, /*enhanced_keys_supported*/ true,
/*disable_paste_burst*/ true, keymap,
);
overlay.handle_paste("Alice".to_string());
assert!(overlay.keymap_contexts().contains(KeymapContext::Composer));
overlay.handle_key_event(KeyEvent::new(KeyCode::Char('с'), KeyModifiers::CONTROL));
assert!(!overlay.is_complete());
assert!(
!std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
event,
AppEvent::SubmitThreadOp {
op: Op::ResolveElicitation {
decision: McpServerElicitationAction::Accept,
..
},
..
}
)),
"metadata-free Ctrl+с must not accept the form"
);
overlay.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::ALT));
assert!(overlay.is_complete());
assert!(
std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
event,
AppEvent::SubmitThreadOp {
op: Op::ResolveElicitation { decision: McpServerElicitationAction::Accept, content: Some(content), .. },
..
} if content == serde_json::json!({"name": "Alice"})
)),
"safe Alt binding must accept the exact form content"
);
}
}
@@ -4,6 +4,55 @@ use ApprovalsReviewer::AutoReview;
use ApprovalsReviewer::User;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn permission_shortcuts_reject_ambiguous_control_bindings() {
for action in ["next_permission_mode", "previous_permission_mode"] {
let (mut chat, mut events, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::GuardianApproval, /*enabled*/ true);
#[cfg(target_os = "windows")]
chat.set_windows_sandbox_mode(Some(WindowsSandboxSetupMode::Unelevated));
chat.config
.permissions
.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::active(
PermissionProfile::read_only(),
ActivePermissionProfile::new(":read-only"),
))
.expect("set initial read-only mode");
chat.config.approvals_reviewer = User;
chat.permission_discovery = Some(crate::permission_discovery::PermissionDiscovery::local(
&chat.config,
));
let ambiguous = toml::from_str(&format!("[chat]\n{action} = 'ctrl-с'")).unwrap();
assert!(crate::keymap::RuntimeKeymap::from_config(&ambiguous).is_err());
let config = toml::from_str(&format!("[chat]\n{action} = 'alt-y'")).unwrap();
let runtime = crate::keymap::RuntimeKeymap::from_config(&config).unwrap();
chat.apply_keymap_update(config, &runtime);
while events.try_recv().is_ok() {}
for base_layout in [Some(('c', KeyModifiers::CONTROL)), None] {
chat.handle_key_event(KeyEvent {
base_layout,
..KeyEvent::new(KeyCode::Char('с'), KeyModifiers::CONTROL)
});
assert!(
!std::iter::from_fn(|| events.try_recv().ok())
.any(|event| matches!(event, AppEvent::ApplyPermissionShortcut { .. })),
"physical cancellation must not select a permission mode"
);
}
chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::ALT));
assert!(
std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
event,
AppEvent::ApplyPermissionShortcut { selection, .. }
if selection.profile_id == ":workspace"
)),
"the safe shortcut must still select the next writable mode"
);
}
}
#[tokio::test]
async fn permission_shortcuts_cycle_builtin_modes() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
+25
View File
@@ -202,9 +202,34 @@ pub(crate) fn normalize_key_parts(
modifiers.insert(KeyModifiers::SHIFT);
return (KeyCode::Char(ch.to_ascii_lowercase()), modifiers);
}
let (key, modifiers) = normalize_non_ascii_key_parts(key, modifiers);
KeyBinding::new(key, modifiers).normalized_parts()
}
/// Give configured Unicode literals and terminal events the same scalar identity.
/// ASCII and named-key aliases keep their existing configuration rules.
pub(crate) fn normalize_non_ascii_key_parts(
key: KeyCode,
mut modifiers: KeyModifiers,
) -> (KeyCode, KeyModifiers) {
if let KeyCode::Char(ch) = key
&& !ch.is_ascii()
&& ch.is_uppercase()
{
let mut lowercase = ch.to_lowercase();
if let Some(lower) = lowercase.next()
&& lowercase.next().is_none()
&& lower != ch
&& !lower.is_ascii()
{
// A key contains one scalar. Never fold a Unicode key into an ASCII consent key.
modifiers.insert(KeyModifiers::SHIFT);
return (KeyCode::Char(lower), modifiers);
}
}
(key, modifiers)
}
fn c0_control_char_to_ctrl_char(ch: char) -> Option<char> {
let code = u32::from(ch);
match code {
+51 -1
View File
@@ -38,6 +38,14 @@ mod leader;
mod vim_search;
pub(crate) use vim_search::VimSearchKeymap;
#[cfg(test)]
#[path = "keymap/consent_tests.rs"]
mod consent_tests;
#[cfg(test)]
#[path = "keymap/unicode_tests.rs"]
mod unicode_tests;
#[cfg(test)]
#[path = "keymap/conflict_tests.rs"]
mod conflict_tests;
@@ -2302,6 +2310,44 @@ impl RuntimeKeymap {
/// 2. Contexts with hard-coded sequence behavior, such as edit-previous
/// backtracking, intentionally stay outside this configurable keymap.
fn validate_conflicts(&self) -> Result<(), String> {
// Non-ASCII characters can alias denial or cancellation keys on another
// layout, including plain UTF-8 input without physical-key metadata.
// Keep consent shortcuts ASCII and validate resolved strokes so
// chord completions and every expanded leader prefix obey the same rule.
// Composer submit/queue also accept MCP elicitation text forms.
for action in runtime_action_bindings(self).filter(|action| {
matches!(
(action.id.context, action.id.action),
(KeymapContext::List, "accept")
| (KeymapContext::Composer, "submit" | "queue")
| (
KeymapContext::Chat,
"next_permission_mode" | "previous_permission_mode"
)
| (
KeymapContext::Approval,
"approve" | "approve_for_session" | "approve_for_prefix"
)
)
}) {
let mut strokes = action.bindings.iter().copied().chain(
self.chords
.bindings
.iter()
.filter(|binding| binding.action == action.id)
.flat_map(|binding| [binding.chord.prefix, binding.chord.completion]),
);
if strokes.any(|binding| {
let (code, _) = binding.parts();
matches!(code, KeyCode::Char(ch) if !ch.is_ascii())
}) {
let path = action.id.config_path();
return Err(format!(
"Invalid `{path}`: non-ASCII bindings can alias denial or cancellation keys \
on another keyboard layout. Choose an ASCII key for consent actions."
));
}
}
for (action, bindings) in [
("global.change_host", &self.app.change_host),
(
@@ -3233,6 +3279,11 @@ fn parse_keybinding(spec: &str) -> Option<KeyBinding> {
key_name.push_str(trailing);
}
if let Ok(ch) = key_name.parse() {
let (key, modifiers) =
key_hint::normalize_non_ascii_key_parts(KeyCode::Char(ch), modifiers);
return Some(KeyBinding::new(key, modifiers));
}
let key = match key_name.as_str() {
"enter" => KeyCode::Enter,
"tab" => KeyCode::Tab,
@@ -3249,7 +3300,6 @@ fn parse_keybinding(spec: &str) -> Option<KeyBinding> {
"page-down" => KeyCode::PageDown,
"space" => KeyCode::Char(' '),
"minus" => KeyCode::Char('-'),
other if other.len() == 1 => KeyCode::Char(char::from(other.as_bytes()[0])),
other if other.starts_with('f') => {
let number = other[1..].parse::<u8>().ok()?;
if (1..=MAX_FUNCTION_KEY).contains(&number) {
+73
View File
@@ -0,0 +1,73 @@
//! Consent shortcuts must remain unambiguous across layouts, chords, and expanded leaders.
#![cfg(test)]
use super::RuntimeKeymap;
#[test]
fn consent_actions_reject_ambiguous_unicode_strokes() {
for (context, action) in [
("list", "accept"),
("composer", "submit"),
("composer", "queue"),
("global", "submit"),
("global", "queue"),
("approval", "approve"),
("approval", "approve_for_session"),
("approval", "approve_for_prefix"),
("chat", "next_permission_mode"),
("chat", "previous_permission_mode"),
] {
for spec in [
"т",
"shift-т",
"alt-т",
"super-т",
"ctrl-с",
"ctrl-shift-с",
"ctrl-alt-с",
"ctrl-x ctrl-с",
"ctrl-с x",
"leader ctrl-с",
] {
let config = toml::from_str(&format!("[{context}]\n{action} = '{spec}'"))
.expect("Unicode syntax is valid");
let error = RuntimeKeymap::from_config(&config)
.expect_err("ambiguous control stroke must not grant consent");
let resolved_context = if context == "global" {
"composer"
} else {
context
};
assert!(error.contains(&format!("tui.keymap.{resolved_context}.{action}")));
assert!(error.contains("non-ASCII"), "{spec}: {error}");
}
let section = if context == "global" {
String::new()
} else {
format!("[{context}]\n")
};
let config = toml::from_str(&format!(
"[global]\nleader = ['ctrl-x', 'ctrl-с']\n{section}{action} = 'leader y'"
))
.expect("valid leader syntax");
let error = RuntimeKeymap::from_config(&config)
.expect_err("each expanded consent leader must be safe");
assert!(error.contains("non-ASCII"), "{error}");
}
}
#[test]
fn unicode_control_bindings_remain_available_outside_consent() {
for config in [
"[list]\nmove_down = 'ctrl-с'",
"[composer]\nhistory_search_previous = 'ctrl-с'",
"[global]\ntoggle_raw_output = 'ctrl-с'",
"[global]\nleader = 'ctrl-с'\n[composer]\nhistory_search_previous = 'leader h'",
"[list]\naccept = 'alt-y'",
"[approval]\napprove = 'alt-y'",
] {
let keymap = toml::from_str(config).expect("valid config syntax");
RuntimeKeymap::from_config(&keymap).expect("unambiguous binding remains available");
}
}
+205
View File
@@ -0,0 +1,205 @@
//! Match configured Unicode shortcuts without introducing aliases for ASCII consent keys.
#![cfg(test)]
use super::KeyChordMatch;
use super::KeyChordMatcher;
use super::KeymapContextSet;
use super::ListAction;
use super::RuntimeKeymap;
use super::bindings::KeymapContext;
use crate::key_hint::KeyBinding;
use crate::key_hint::KeyBindingListExt;
use codex_config::types::TuiKeymap;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
#[test]
fn built_in_aliases_preserve_primary_hints_and_startup_validity() {
for workspace in [false, true] {
let runtime = RuntimeKeymap::for_session(&TuiKeymap::default(), workspace)
.expect("built-in aliases must not prevent startup");
assert_eq!(
runtime.vim_search.previous,
vec![
KeyBinding::new(KeyCode::Char('N'), KeyModifiers::NONE),
KeyBinding::new(KeyCode::Char('n'), KeyModifiers::SHIFT),
]
);
for (ch, modifiers) in [
('N', KeyModifiers::NONE),
('N', KeyModifiers::SHIFT),
('n', KeyModifiers::SHIFT),
] {
assert!(
runtime
.vim_search
.previous
.is_pressed(KeyEvent::new(KeyCode::Char(ch), modifiers))
);
}
assert!(
!runtime
.vim_search
.previous
.is_pressed(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE))
);
}
}
#[test]
fn shifted_unicode_config_matches_terminal_events_and_capture() {
for (spec, other_modifiers) in [
("shift-ф", KeyModifiers::NONE),
(
"ctrl-alt-shift-ф",
KeyModifiers::CONTROL | KeyModifiers::ALT,
),
] {
let config = toml::from_str(&format!("[list]\nmove_down = '{spec}'")).unwrap();
let runtime = RuntimeKeymap::from_config(&config).unwrap();
for (ch, shift) in [
('ф', KeyModifiers::SHIFT),
('Ф', KeyModifiers::SHIFT),
('Ф', KeyModifiers::NONE),
] {
let event = KeyEvent::new(KeyCode::Char(ch), other_modifiers | shift);
assert_eq!(runtime.list.action_for(event), Some(ListAction::MoveDown));
assert_eq!(
KeyBinding::from_event(event).normalized_parts(),
runtime.list.move_down[0].normalized_parts(),
);
assert_eq!(
runtime.list.action_for(KeyEvent {
kind: KeyEventKind::Release,
..event
}),
None,
);
}
assert_eq!(
runtime
.list
.action_for(KeyEvent::new(KeyCode::Char('ф'), other_modifiers)),
None,
);
if !other_modifiers.is_empty() {
assert_eq!(
runtime
.list
.action_for(KeyEvent::new(KeyCode::Char('Ф'), KeyModifiers::CONTROL,)),
None,
);
}
}
}
#[test]
fn unicode_matching_aliases_deduplicate_and_conflict_consistently() {
let config = toml::from_str("[list]\nmove_down = ['Ф', 'shift-ф']").unwrap();
let runtime = RuntimeKeymap::from_config(&config).unwrap();
assert_eq!(runtime.list.move_down.len(), 1);
let config = toml::from_str("[list]\nmove_down = 'Ф'\nmove_up = 'shift-ф'").unwrap();
let error = RuntimeKeymap::from_config(&config).expect_err("matching aliases conflict");
assert!(error.contains("Ambiguous `tui.keymap.list`"), "{error}");
}
#[test]
fn reserved_shift_tab_rejects_configured_chords_and_leader() {
for setting in [
"open_transcript = 'shift-tab x'",
"open_transcript = 'ctrl-x shift-tab'",
"leader = 'shift-tab'",
] {
let config = toml::from_str(&format!("[global]\n{setting}")).unwrap();
let error = RuntimeKeymap::from_config(&config)
.expect_err("configured Shift+Tab must remain reserved");
assert!(
error.contains("fixed.cycle_collaboration_mode"),
"{setting}: {error}"
);
}
}
#[test]
fn built_in_sidebar_shift_tab_completes_for_both_terminal_encodings() {
let runtime = RuntimeKeymap::for_session(&TuiKeymap::default(), /*workspace*/ true).unwrap();
let contexts = KeymapContextSet::new(KeymapContext::Global).with_focused_sidebar();
for event in [
KeyEvent::new(KeyCode::BackTab, KeyModifiers::NONE),
KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT),
KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT),
] {
let mut matcher = KeyChordMatcher::default();
let (code, modifiers) = runtime.chords.leader[0].parts();
assert!(matches!(
matcher.advance(KeyEvent::new(code, modifiers), &runtime.chords, contexts),
KeyChordMatch::Pending(_)
));
let KeyChordMatch::Completed(dispatch) = matcher.advance(event, &runtime.chords, contexts)
else {
panic!("the built-in leader Shift+Tab must complete sidebar_up");
};
assert!(runtime.app.sidebar_up.is_pressed(dispatch));
}
}
#[test]
fn unicode_aliases_conflict_across_vim_search_contexts() {
for (context, action) in [("vim_normal", "move_left"), ("vim_operator", "motion_left")] {
let config = toml::from_str(&format!(
"[{context}]\n{action} = 'Ф'\n[vim_search]\nforward = 'shift-ф'"
))
.unwrap();
let error = RuntimeKeymap::from_config(&config)
.expect_err("matching Unicode aliases cannot select both a motion and search");
assert!(
error.contains("Conflicting `tui.keymap.vim_search.forward`"),
"{error}"
);
assert!(
error.contains(&format!("tui.keymap.{context}.{action}")),
"{error}"
);
}
}
#[test]
fn unicode_aliases_conflict_in_chord_prefixes_and_completions() {
for (left, right) in [("Ф x", "shift-ф x"), ("g Ф", "g shift-ф")] {
let config = toml::from_str(&format!(
"[vim_normal]\nmove_left = '{left}'\nmove_right = '{right}'"
))
.unwrap();
let error = RuntimeKeymap::from_config(&config)
.expect_err("matching Unicode chords cannot select two actions");
assert!(error.contains("tui.keymap.vim_normal.move_"), "{error}");
}
}
#[test]
fn unicode_case_folding_preserves_scalar_and_consent_boundaries() {
// İ expands, K crosses into ASCII, ℂ has no lowercase mapping, and 山 is uncased.
for ch in ['İ', 'K', 'ℂ', '山'] {
for modifiers in [KeyModifiers::NONE, KeyModifiers::SHIFT] {
let event = KeyEvent::new(KeyCode::Char(ch), modifiers);
assert_eq!(
KeyBinding::from_event(event).parts(),
(event.code, modifiers)
);
}
}
for (ascii, unicode) in [('i', 'İ'), ('k', 'K')] {
let binding = KeyBinding::new(KeyCode::Char(ascii), KeyModifiers::SHIFT);
assert!(!binding.is_press(KeyEvent::new(KeyCode::Char(unicode), KeyModifiers::NONE)));
assert!(!binding.is_press(KeyEvent::new(KeyCode::Char(unicode), KeyModifiers::SHIFT)));
}
for spec in ["Ф", "shift-ф", "K", "shift-K"] {
let config = toml::from_str(&format!("[approval]\napprove = '{spec}'")).unwrap();
let error = RuntimeKeymap::from_config(&config).expect_err("Unicode cannot grant consent");
assert!(error.contains("non-ASCII"), "{spec}: {error}");
}
}
+8 -6
View File
@@ -728,8 +728,8 @@ fn key_parts_to_config_key_spec(
if ch == '-' {
return Ok(format_key_spec(modifiers, "minus"));
}
if !ch.is_ascii() || ch.is_ascii_control() {
return Err("Only printable ASCII keys can be stored in `tui.keymap`.".to_string());
if !KeybindingSpec::is_literal_character(ch) {
return Err("Only printable keys can be stored in `tui.keymap`.".to_string());
}
if ch.is_ascii_uppercase() {
modifiers.insert(KeyModifiers::SHIFT);
@@ -1570,15 +1570,17 @@ mod tests {
#[test]
fn debug_view_uses_custom_binding_source() {
let keymap =
keymap_with_replacement(&TuiKeymap::default(), "global", "copy", "ctrl-x").unwrap();
keymap_with_replacement(&TuiKeymap::default(), "global", "copy", "ctrl-в").unwrap();
let runtime = RuntimeKeymap::from_config(&keymap).unwrap();
let mut view = build_keymap_debug_view(&runtime, &keymap);
view.handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL));
view.handle_key_event(KeyEvent {
base_layout: Some(('d', KeyModifiers::CONTROL)),
..KeyEvent::new(KeyCode::Char('в'), KeyModifiers::CONTROL)
});
let rendered = render_debug(&view, /*width*/ 100);
assert!(rendered.contains("global.copy (Copy)"));
assert!(rendered.contains("[Custom]"));
assert_snapshot!("keymap_debug_view_custom_binding", rendered);
}
#[test]
+13
View File
@@ -154,6 +154,19 @@ impl BottomPaneView for KeymapCaptureView {
return;
}
// Serializing the active character loses Kitty's physical-key metadata.
// Lists reserve physical Ctrl+C before matching configured shortcuts.
if self.context == "list"
&& crate::key_hint::base_layout_shortcut(key_event)
.is_some_and(|fallback| fallback.code == KeyCode::Char('c'))
{
self.error_message = Some(
"Your terminal reports this as Ctrl+C, which exits list pickers. Choose another key."
.to_string(),
);
return;
}
match key_event_to_config_key_spec(key_event) {
Ok(key) => {
self.error_message = None;
@@ -255,3 +255,124 @@ fn replacing_one_list_binding_with_chord_preserves_other_alternatives() {
}
);
}
#[test]
fn physical_cancel_capture_warns_and_allows_another_list_key() {
let physical_cancel = KeyEvent {
base_layout: Some(('c', KeyModifiers::CONTROL)),
..ctrl_key(KeyCode::Char('с'))
};
for (mode, first_stroke, expected) in [
(KeymapCaptureMode::SingleKey, None, "alt-j"),
(KeymapCaptureMode::LeaderChord, None, "leader alt-j"),
(KeymapCaptureMode::Chord, None, "alt-j alt-j"),
(KeymapCaptureMode::Chord, Some("ctrl-x"), "ctrl-x alt-j"),
] {
for action in ["move_down", "cancel"] {
let (mut view, mut rx) = capture_view();
view.action = action.to_string();
view.label = if action == "move_down" {
"Move Down"
} else {
"Cancel"
}
.to_string();
view.capture_mode = mode;
view.first_stroke = first_stroke.map(str::to_string);
view.handle_key_event(physical_cancel);
assert!(!view.is_complete());
assert!(rx.try_recv().is_err());
assert_eq!(view.first_stroke.as_deref(), first_stroke);
let screen = capture_lines_at_width(&view, /*width*/ 100);
assert!(screen.contains("Ctrl+C, which exits list pickers"));
assert!(screen.contains("Choose another key."));
if mode == KeymapCaptureMode::SingleKey && action == "move_down" {
insta::assert_snapshot!(screen, @r"
Remap Shortcut
Action: Move Down list.move_down
Current: home
Press the new key now. Esc cancels.
Error: Your terminal reports this as Ctrl+C, which exits list pickers. Choose another key.
");
}
let replacement = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::ALT);
view.handle_key_event(replacement);
if mode == KeymapCaptureMode::Chord && first_stroke.is_none() {
view.handle_key_event(replacement);
}
let AppEvent::KeymapCaptured { key, .. } = rx.try_recv().expect("replacement captured")
else {
panic!("expected captured replacement");
};
assert_eq!(key, expected);
assert_eq!(view.error_message, None);
assert!(view.is_complete());
}
}
}
#[test]
fn capture_preserves_unicode_keys_without_a_list_cancellation_conflict() {
for (context, base_layout, modifiers, expected) in [
(
"composer",
Some(('c', KeyModifiers::CONTROL)),
KeyModifiers::CONTROL,
"ctrl-с",
),
("list", None, KeyModifiers::CONTROL, "ctrl-с"),
(
"list",
Some(('d', KeyModifiers::CONTROL)),
KeyModifiers::CONTROL,
"ctrl-с",
),
(
"list",
Some(('c', KeyModifiers::CONTROL | KeyModifiers::SHIFT)),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
"ctrl-shift-с",
),
(
"list",
Some(('c', KeyModifiers::CONTROL | KeyModifiers::ALT)),
KeyModifiers::CONTROL | KeyModifiers::ALT,
"ctrl-alt-с",
),
] {
let (mut view, mut rx) = capture_view();
view.context = context.to_string();
view.capture_mode = KeymapCaptureMode::SingleKey;
view.handle_key_event(KeyEvent {
base_layout,
..KeyEvent::new(KeyCode::Char('с'), modifiers)
});
let AppEvent::KeymapCaptured { key, .. } = rx.try_recv().expect("supported shortcut")
else {
panic!("expected captured key");
};
assert_eq!(key, expected);
assert!(view.is_complete());
}
}
#[test]
fn formatting_character_capture_keeps_the_view_open() {
for ch in ['\u{200b}', '\u{202e}', '\u{2066}', '\u{feff}', '\u{e0001}'] {
let (mut view, mut rx) = capture_view();
view.capture_mode = KeymapCaptureMode::SingleKey;
view.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
assert!(!view.is_complete());
assert!(rx.try_recv().is_err());
assert!(capture_lines_at_width(&view, /*width*/ 100).contains("Only printable keys"));
view.handle_key_event(KeyEvent::new(KeyCode::Char('界'), KeyModifiers::NONE));
let AppEvent::KeymapCaptured { key, .. } = rx.try_recv().expect("visible replacement")
else {
panic!("expected captured replacement");
};
assert_eq!(key, "界");
assert_eq!(view.error_message, None);
}
}
@@ -0,0 +1,14 @@
---
source: tui/src/keymap_setup.rs
expression: rendered
---
Keypress Inspector
Press any key to see what Codex receives. Esc is inspected; Ctrl+C closes.
Tip: Codex can only inspect keys your terminal sends.
Detected: ⌃в
Config key: ctrl-в
Raw event: code=Char('в'), modifiers=ctrl, kind=Press
Assigned actions:
- global.copy (Copy) - Copy the last agent response to the clipboard. [Custom]
@@ -11,6 +11,8 @@ use pretty_assertions::assert_eq;
#[test]
fn physical_ctrl_c_cannot_confirm_startup_hook_trust_through_layout_binding() {
let ambiguous = toml::from_str("[list]\naccept = 'ctrl-с'").unwrap();
assert!(RuntimeKeymap::from_config(&ambiguous).is_err());
let config = toml::from_str("[list]\naccept = 'alt-y'").unwrap();
let keymap = RuntimeKeymap::from_config(&config).unwrap();
for (code, base_layout, modifiers, expected) in [