feat(tui): add configurable keymap support (#18593)

## Why

The TUI currently handles keyboard shortcuts as hard-coded event matches
spread across app, composer, pager, list, approval, and navigation code.
That makes shortcuts hard to customize, makes displayed hints easy to
drift from actual behavior, and makes future keymap work riskier because
there is no central action inventory.

This PR adds the foundation for configurable, action-based keymaps
without adding the interactive remapping UI yet. Onboarding
intentionally stays on fixed startup shortcuts because users cannot
reasonably configure keymaps before completing onboarding.

This is PR1 in the keymap stack:

- PR1: #18593: configurable keymap foundation
- PR2: #18594: `/keymap` picker and guided remapping UI
- PR3: #18595: Vim composer mode and the remap option

## Design Notes

The new model resolves named actions into concrete runtime bindings once
from config, then passes those bindings to the UI surfaces that handle
input or render shortcut hints.

The main concepts are:

- **Context**: a scope where an action is active, such as `global`,
`chat`, `composer`, `editor`, `pager`, `list`, or `approval`.
- **Action**: a named operation inside a context, such as
`global.open_transcript`, `composer.submit`, or `pager.close`.
- **Binding**: one or more single-key shortcuts assigned to an action,
written as config strings such as `ctrl-t`, `alt-backspace`, or
`page-down`. Multi-step sequences such as `ctrl-x ctrl-s`, `g g`, or
leader-key flows are not part of this PR.
- **Resolution order**: context-specific config wins first, supported
global fallbacks come next, and built-in defaults fill in anything
unset.
- **Explicit unbinding**: an empty array removes an action binding in
that scope and does not fall through to a fallback binding.
- **Conflict validation**: a resolved keymap rejects duplicate active
bindings inside the same scope so one keypress cannot dispatch two
actions.

## What Changed

- Added `TuiKeymap` config support under `[tui.keymap]`, including typed
contexts/actions, key alias normalization, generated schema coverage,
and user-facing config errors.
- Added `RuntimeKeymap` resolution in `codex-rs/tui/src/keymap.rs`,
including fallback precedence, built-in defaults, explicit unbinding,
and per-context conflict validation.
- Rewired existing TUI handlers to consume resolved keymap actions
instead of directly matching hard-coded keys in each component.
- Updated key hint rendering and footer/pager/list surfaces so displayed
shortcuts follow the resolved keymap.
- Kept onboarding shortcuts fixed in
`codex-rs/tui/src/onboarding/keys.rs` instead of exposing them through
`[tui.keymap]`.

## Validation

The branch includes focused coverage for config parsing, key
normalization, runtime fallback resolution, explicit unbinding,
duplicate-key conflict validation, default keymap consistency,
onboarding startup key behavior, and UI hint snapshots affected by
resolved key bindings.
This commit is contained in:
Felipe Coury authored and GitHub committed 2026-04-28 12:52:25 -03:00
1 parent a61c785040
commit 5e737372ee
63 files changed
+8142 -877

No files matched your search

+135 -10
View File
@@ -24,11 +24,12 @@ use crate::bottom_pane::pending_thread_approvals::PendingThreadApprovals;
use crate::bottom_pane::unified_exec_footer::UnifiedExecFooter;
use crate::key_hint;
use crate::key_hint::KeyBinding;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::FlexRenderable;
use crate::render::renderable::Renderable;
use crate::render::renderable::RenderableItem;
use crate::tui::FrameRequester;
use bottom_pane_view::BottomPaneView;
pub(crate) use bottom_pane_view::BottomPaneView;
use bottom_pane_view::ViewCompletion;
use codex_core_skills::model::SkillMetadata;
use codex_features::Features;
@@ -99,6 +100,8 @@ pub(crate) use footer::GoalStatusIndicator;
#[cfg(test)]
pub(crate) use footer::goal_status_indicator_line;
pub(crate) use list_selection_view::ColumnWidthMode;
#[cfg(test)]
pub(crate) use list_selection_view::ListSelectionView;
pub(crate) use list_selection_view::SelectionRowDisplay;
pub(crate) use list_selection_view::SelectionToggle;
pub(crate) use list_selection_view::SelectionViewParams;
@@ -220,6 +223,7 @@ pub(crate) struct BottomPane {
pending_thread_approvals: PendingThreadApprovals,
context_window_percent: Option<i64>,
context_window_used_tokens: Option<i64>,
keymap: RuntimeKeymap,
}
pub(crate) struct BottomPaneParams {
@@ -253,6 +257,8 @@ impl BottomPane {
disable_paste_burst,
);
composer.set_frame_requester(frame_requester.clone());
let keymap = RuntimeKeymap::defaults();
composer.set_keymap_bindings(&keymap);
composer.set_skill_mentions(skills);
Self {
composer,
@@ -273,6 +279,7 @@ impl BottomPane {
animations_enabled,
context_window_percent: None,
context_window_used_tokens: None,
keymap,
}
}
@@ -320,6 +327,19 @@ impl BottomPane {
self.composer.record_pending_slash_command_history();
}
/// Replace all bottom-pane keymap caches from one resolved runtime keymap.
///
/// The bottom pane owns several input surfaces: composer, overlays, and
/// selection views. Applying one snapshot through this method keeps those
/// surfaces synchronized after config reloads or interactive remaps. Callers
/// should not update the composer directly unless they deliberately want
/// overlays and selection views to continue using the previous bindings.
pub fn set_keymap_bindings(&mut self, keymap: &RuntimeKeymap) {
self.keymap = keymap.clone();
self.composer.set_keymap_bindings(keymap);
self.request_redraw();
}
/// Clear pending attachments and mention bindings e.g. when a slash command doesn't submit text.
pub(crate) fn drain_pending_submission_state(&mut self) {
let _ = self.take_recent_submission_images_with_placeholders();
@@ -393,7 +413,7 @@ impl BottomPane {
/// Update the key hint shown next to queued messages so it matches the
/// binding that `ChatWidget` actually listens for.
pub(crate) fn set_queued_message_edit_binding(&mut self, binding: KeyBinding) {
pub(crate) fn set_queued_message_edit_binding(&mut self, binding: Option<KeyBinding>) {
self.pending_input_preview.set_edit_binding(binding);
self.request_redraw();
}
@@ -491,8 +511,13 @@ impl BottomPane {
let Some(first) = self.delayed_approval_requests.pop_front() else {
return;
};
let mut modal =
ApprovalOverlay::new(first.request, self.app_event_tx.clone(), first.features);
let mut modal = ApprovalOverlay::new(
first.request,
self.app_event_tx.clone(),
first.features,
self.keymap.approval.clone(),
self.keymap.list.clone(),
);
while let Some(delayed) = self.delayed_approval_requests.pop_back() {
modal.enqueue_request(delayed.request);
}
@@ -933,16 +958,32 @@ impl BottomPane {
}
/// Show a generic list selection view with the provided items.
pub(crate) fn show_selection_view(&mut self, params: list_selection_view::SelectionViewParams) {
let view = list_selection_view::ListSelectionView::new(params, self.app_event_tx.clone());
pub(crate) fn show_selection_view(
&mut self,
mut params: list_selection_view::SelectionViewParams,
) {
self.apply_standard_popup_hint(&mut params);
let view = list_selection_view::ListSelectionView::new(
params,
self.app_event_tx.clone(),
self.keymap.list.clone(),
);
self.push_view(Box::new(view));
}
fn apply_standard_popup_hint(&self, params: &mut list_selection_view::SelectionViewParams) {
if params.footer_hint.is_none()
|| params.footer_hint.as_ref() == Some(&popup_consts::standard_popup_hint_line())
{
params.footer_hint = Some(self.standard_popup_hint_line());
}
}
/// Replace the active selection view when it matches `view_id`.
pub(crate) fn replace_selection_view_if_active(
&mut self,
view_id: &'static str,
params: list_selection_view::SelectionViewParams,
mut params: list_selection_view::SelectionViewParams,
) -> bool {
let is_match = self
.view_stack
@@ -953,7 +994,50 @@ impl BottomPane {
}
self.view_stack.pop();
let view = list_selection_view::ListSelectionView::new(params, self.app_event_tx.clone());
self.apply_standard_popup_hint(&mut params);
let view = list_selection_view::ListSelectionView::new(
params,
self.app_event_tx.clone(),
self.keymap.list.clone(),
);
self.push_view(Box::new(view));
true
}
pub(crate) fn standard_popup_hint_line(&self) -> Line<'static> {
popup_consts::standard_popup_hint_line_for_keymap(&self.keymap.list)
}
/// Replace one or more active views whose IDs are in `view_ids` with a
/// generic list selection view.
pub(crate) fn replace_active_views_with_selection_view(
&mut self,
view_ids: &[&'static str],
mut params: list_selection_view::SelectionViewParams,
) -> bool {
let is_match = self
.view_stack
.last()
.and_then(|view| view.view_id())
.is_some_and(|view_id| view_ids.contains(&view_id));
if !is_match {
return false;
}
while self
.view_stack
.last()
.and_then(|view| view.view_id())
.is_some_and(|view_id| view_ids.contains(&view_id))
{
self.view_stack.pop();
}
self.apply_standard_popup_hint(&mut params);
let view = list_selection_view::ListSelectionView::new(
params,
self.app_event_tx.clone(),
self.keymap.list.clone(),
);
self.push_view(Box::new(view));
true
}
@@ -1031,11 +1115,15 @@ impl BottomPane {
.is_some_and(bottom_pane_view::BottomPaneView::terminal_title_requires_action)
}
#[cfg(test)]
pub(crate) fn has_active_view(&self) -> bool {
!self.view_stack.is_empty()
}
#[cfg(test)]
pub(crate) fn active_view_id(&self) -> Option<&'static str> {
self.view_stack.last().and_then(|view| view.view_id())
}
/// Return true when the pane is in the regular composer state without any
/// overlays or popups and not running a task. This is the safe context to
/// use Esc-Esc for backtracking from the main view.
@@ -1087,7 +1175,13 @@ impl BottomPane {
self.maybe_show_delayed_approval_requests_at(now);
} else {
// No recent composer activity, so show the approval modal immediately.
let modal = ApprovalOverlay::new(request, self.app_event_tx.clone(), features.clone());
let modal = ApprovalOverlay::new(
request,
self.app_event_tx.clone(),
features.clone(),
self.keymap.approval.clone(),
self.keymap.list.clone(),
);
self.pause_status_timer_for_modal();
self.push_view(Box::new(modal));
}
@@ -2414,6 +2508,37 @@ mod tests {
);
}
#[test]
fn selection_view_esc_respects_remapped_list_cancel() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let tx = AppEventSender::new(tx_raw);
let mut pane = test_pane(tx);
let mut keymap = RuntimeKeymap::defaults();
keymap.list.cancel = vec![crate::key_hint::plain(KeyCode::Char('q'))];
pane.set_keymap_bindings(&keymap);
pane.show_selection_view(SelectionViewParams {
title: Some("Agents".to_string()),
items: vec![SelectionItem {
name: "Main".to_string(),
..Default::default()
}],
on_cancel: Some(Box::new(|tx: &_| {
tx.send(AppEvent::OpenApprovalsPopup);
})),
..Default::default()
});
pane.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(pane.active_view().is_some());
assert!(rx.try_recv().is_err());
pane.handle_key_event(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
assert!(pane.no_modal_or_popup_active());
assert!(matches!(rx.try_recv(), Ok(AppEvent::OpenApprovalsPopup)));
}
#[test]
fn esc_routes_to_handle_key_event_when_requested() {
#[derive(Default)]