Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,471 @@
//! Catalog and accessors for keymap actions shown by `/keymap`.
//!
//! The catalog declaration generates both the UI-facing descriptors and the
//! matching root-config accessors. Each entry ties together the config path,
//! user-facing context label, stable action name, short description, and
//! optional feature gate used by the picker and action menu.
//!
//! Runtime lookups reuse the inventory owned by [`crate::keymap`]. A catalog
//! action must remain both writable in `TuiKeymap` and readable from the shared
//! runtime inventory.
use std::collections::BTreeSet;
use codex_config::types::KeybindingsSpec;
use codex_config::types::TuiKeymap;
use crossterm::event::KeyEvent;
use crate::keymap::RuntimeKeymap;
use crate::keymap::bindings_for_action;
#[derive(Clone, Copy, Debug)]
pub(super) struct KeymapActionDescriptor {
/// Config context segment, such as `composer` in `tui.keymap.composer.submit`.
pub(super) context: &'static str,
/// Human-readable group label shown in the picker.
pub(super) context_label: &'static str,
/// Config action segment, such as `submit` in `tui.keymap.composer.submit`.
pub(super) action: &'static str,
/// Short user-facing explanation of what the action does.
pub(super) description: &'static str,
/// Feature required before the action appears in `/keymap`.
required_feature: Option<KeymapActionFeature>,
}
#[derive(Clone, Copy, Debug)]
enum KeymapActionFeature {
FastMode,
MultiBackend,
Workspace,
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct KeymapActionFilter {
pub(crate) fast_mode_enabled: bool,
pub(crate) multi_backend_enabled: bool,
pub(crate) workspace_enabled: bool,
}
impl KeymapActionDescriptor {
pub(super) fn is_visible(self, filter: KeymapActionFilter) -> bool {
match self.required_feature {
None => true,
Some(KeymapActionFeature::FastMode) => filter.fast_mode_enabled,
Some(KeymapActionFeature::MultiBackend) => filter.multi_backend_enabled,
Some(KeymapActionFeature::Workspace) => filter.workspace_enabled,
}
}
}
macro_rules! required_feature {
() => {
None
};
($feature:ident) => {
Some(KeymapActionFeature::$feature)
};
}
macro_rules! define_keymap_actions {
(
$(
$context:ident $context_label:literal {
$(
$action:ident $( [$required_feature:ident] )? => $description:literal,
)*
}
)*
) => {
pub(super) const KEYMAP_ACTIONS: &[KeymapActionDescriptor] = &[
$(
$(
KeymapActionDescriptor {
context: stringify!($context),
context_label: $context_label,
action: stringify!($action),
description: $description,
required_feature: required_feature!($($required_feature)?),
},
)*
)*
];
/// Return the mutable root-config binding slot for one catalog action.
///
/// The returned `Option<KeybindingsSpec>` distinguishes three states that the
/// editor must preserve: absent means use fallback/default resolution, `Some`
/// with one or more keys is a custom binding, and `Some(Many([]))` is an
/// explicit unbind.
pub(super) fn binding_slot<'a>(
keymap: &'a mut TuiKeymap,
context: &str,
action: &str,
) -> Option<&'a mut Option<KeybindingsSpec>> {
match (context, action) {
$(
$(
(stringify!($context), stringify!($action)) => {
Some(&mut keymap.$context.$action)
}
)*
)*
_ => None,
}
}
};
}
define_keymap_actions! {
global "Global" {
change_host [MultiBackend] => "Change where a new conversation runs.",
focus_main_composer [Workspace] => "Focus the main conversation composer.",
focus_sidebar_tabs [Workspace] => "Open the sidebar tab chooser.",
focus_sidebar_content [Workspace] => "Focus the side conversation, or hide it when already focused.",
hide_pane [Workspace] => "Hide the focused sidebar pane.",
close_sidebar_tab [Workspace] => "Close the active sidebar tab.",
sidebar_up [Workspace] => "Switch to the previous sidebar tab.",
sidebar_down [Workspace] => "Switch to the next sidebar tab.",
focus_pane_left [Workspace] => "Focus the parent conversation.",
focus_pane_right [Workspace] => "Focus the open side conversation.",
minimize_pane_width [Workspace] => "Minimize the focused pane width.",
maximize_pane_width [Workspace] => "Maximize the focused pane width.",
equalize_pane_widths [Workspace] => "Equalize visible pane widths.",
resize_panes [Workspace] => "Enter keyboard resize mode for visible dividers.",
move_divider_left [Workspace] => "Move the divider left when the side pane has focus.",
move_divider_right [Workspace] => "Move the divider right when the side pane has focus.",
toggle_pane_zoom [Workspace] => "Zoom or restore the focused pane.",
open_agents => "Open the agent command center.",
open_transcript => "Open the transcript overlay.",
find_transcript => "Find text in the full transcript.",
// Keep the new warnings action out of shared-config writes until older strict readers
// accept it. Its built-in shortcuts remain available.
focus_activity => "Focus transcript activity groups to expand or collapse their details.",
open_external_editor => "Open the current draft in an external editor.",
copy => "Copy the last agent response to the clipboard.",
clear_terminal => "Clear the terminal UI.",
toggle_vim_mode => "Turn Vim composer mode on or off.",
toggle_fast_mode [FastMode] => "Turn Fast mode on or off.",
toggle_raw_output => "Toggle raw scrollback mode.",
toggle_side_conversation => "Switch between a side conversation and its parent.",
leader => "Set the prefix used by shared leader shortcuts.",
}
chat "Chat" {
interrupt_turn => "Interrupt the active turn.",
decrease_reasoning_effort => "Decrease reasoning effort.",
increase_reasoning_effort => "Increase reasoning effort.",
previous_permission_mode => "Switch to the previous available permission mode.",
next_permission_mode => "Switch to the next available permission mode.",
edit_queued_message => "Move forward through questions, then edit the last queued message.",
prompt_stack_back => "Move back through questions toward the composer.",
skip_question => "Skip the focused question.",
toggle_voice => "Start or stop a voice conversation.",
open_presets => "Run or save reusable inputs.",
toggle_voice_mute => "Mute or unmute the voice microphone.",
}
composer "Composer" {
submit => "Submit the current composer draft.",
queue => "Queue the draft while a task is running.",
toggle_shortcuts => "Show or hide the composer shortcut overlay.",
history_search_previous => "Open history search or move to the previous match.",
history_search_next => "Move to the next history search match.",
}
editor "Editor" {
insert_newline => "Insert a newline in the editor.",
move_left => "Move the cursor left.",
move_right => "Move the cursor right.",
move_up => "Move the cursor up.",
move_down => "Move the cursor down.",
move_word_left => "Move to the beginning of the previous word.",
move_word_right => "Move to the end of the next word.",
move_line_start => "Move to the beginning of the line.",
move_line_end => "Move to the end of the line.",
delete_backward => "Delete one grapheme to the left.",
delete_forward => "Delete one grapheme to the right.",
delete_backward_word => "Delete the previous word.",
delete_forward_word => "Delete the next word.",
kill_line_start => "Delete from cursor to line start.",
kill_whole_line => "Delete the current line.",
kill_line_end => "Delete from cursor to line end.",
yank => "Paste the kill buffer.",
}
vim_normal "Vim normal" {
enter_insert => "Enter insert mode at the cursor.",
append_after_cursor => "Enter insert mode after the cursor.",
append_line_end => "Enter insert mode at end of line.",
insert_line_start => "Enter insert mode at the first non-blank character.",
open_line_below => "Open a new line below and enter insert mode.",
open_line_above => "Open a new line above and enter insert mode.",
enter_replace_mode => "Enter replace mode and overwrite characters.",
move_left => "Move left in Vim normal mode.",
move_right => "Move right in Vim normal mode.",
move_up => "Move up or recall older history in Vim normal mode.",
move_down => "Move down or recall newer history in Vim normal mode.",
move_word_forward => "Move to the start of the next word.",
move_word_backward => "Move to the start of the previous word.",
move_word_end => "Move to the end of the current or next word.",
move_line_start => "Move to the start of the line.",
move_line_end => "Move to the end of the line.",
find_forward => "Find the next character on the current line.",
find_backward => "Find the previous character on the current line.",
till_forward => "Stop before the next character on the current line.",
till_backward => "Stop after the previous character on the current line.",
jump_top => "Jump to the first buffer line.",
jump_bottom => "Jump to the last buffer line.",
delete_char => "Delete the character under the cursor.",
replace_char => "Replace the character under the cursor.",
repeat_last_change => "Repeat the last complete edit.",
substitute_char => "Delete the character under the cursor and enter insert mode.",
delete_to_line_end => "Delete from cursor to end of line.",
change_to_line_end => "Change from cursor to end of line and enter insert mode.",
yank_line => "Yank the entire line.",
paste_after => "Paste after the cursor.",
start_delete_operator => "Begin a delete operator and wait for a motion.",
start_yank_operator => "Begin a yank operator and wait for a motion.",
start_change_operator => "Begin a change operator and wait for a motion or text object.",
undo => "Undo the last complete edit.",
redo => "Redo the last undone edit.",
cancel_operator => "Cancel a pending Vim operator.",
}
vim_search "Vim search" {
forward => "Search forward in the active buffer.",
backward => "Search backward in the active buffer.",
next => "Repeat the accepted search.",
previous => "Repeat the search in the opposite direction.",
}
vim_operator "Vim operator" {
delete_line => "Repeat delete operator to delete the whole line.",
yank_line => "Repeat yank operator to yank the whole line.",
motion_left => "Operator motion left.",
motion_right => "Operator motion right.",
motion_up => "Operator motion up.",
motion_down => "Operator motion down.",
motion_word_forward => "Operator motion to start of next word.",
motion_word_backward => "Operator motion to start of previous word.",
motion_word_end => "Operator motion to end of word.",
motion_line_start => "Operator motion to line start.",
motion_line_end => "Operator motion to line end.",
motion_find_forward => "Operator motion to the next character on the current line.",
motion_find_backward => "Operator motion to the previous character on the current line.",
motion_till_forward => "Stop before the next character on the current line.",
motion_till_backward => "Stop after the previous character on the current line.",
motion_jump_top => "Operator motion to the first buffer line.",
motion_jump_bottom => "Operator motion to the last buffer line.",
select_inner_text_object => "Select an inner text object.",
select_around_text_object => "Select an around text object.",
cancel => "Cancel the pending operator.",
}
vim_text_object "Vim text object" {
word => "Target the current word.",
big_word => "Target the current WORD.",
parentheses => "Target enclosing parentheses.",
brackets => "Target enclosing brackets.",
braces => "Target enclosing braces.",
double_quote => "Target enclosing double quotes.",
single_quote => "Target enclosing single quotes.",
backtick => "Target enclosing backticks.",
cancel => "Cancel the pending text object.",
}
pager "Pager" {
scroll_up => "Scroll up by one row.",
scroll_down => "Scroll down by one row.",
page_up => "Scroll up by one page.",
page_down => "Scroll down by one page.",
half_page_up => "Scroll up by half a page.",
half_page_down => "Scroll down by half a page.",
jump_top => "Jump to the beginning.",
jump_bottom => "Jump to the end.",
close => "Close the pager overlay.",
close_transcript => "Close the transcript overlay.",
find => "Find text in a transcript pager.",
}
list "List" {
move_up => "Move list selection up.",
move_down => "Move list selection down.",
move_left => "Move horizontally left in list pickers.",
move_right => "Move horizontally right in list pickers.",
page_up => "Move list selection up by one page.",
page_down => "Move list selection down by one page.",
jump_top => "Jump to the first list item.",
jump_bottom => "Jump to the last list item.",
accept => "Accept the current list selection.",
cancel => "Cancel and close selection views.",
}
agents "Agents" {
resume => "Open the session resume picker.",
search => "Search the available agent tasks.",
new_task => "Open a new session in the selected checkout.",
new_worktree => "Open a new session in a worktree from the project default branch.",
fork => "Fork the selected conversation and open the new session.",
rename => "Rename the selected task.",
stop => "Stop the selected running task.",
archive => "Archive the selected task and its child agents.",
delete => "Permanently delete the selected task and its child agents.",
hide => "Hide the selected task until explicitly resumed.",
toggle_grouping => "Cycle task grouping by project, directory, status, or model.",
}
approval "Approval" {
open_fullscreen => "Open approval details fullscreen.",
open_thread => "Open the approval source thread when available.",
approve => "Approve the primary option.",
approve_for_session => "Approve for the session when available.",
approve_for_prefix => "Approve with an exec-policy prefix when available.",
deny => "Choose the explicit deny option when available.",
decline => "Decline and provide corrective guidance.",
cancel => "Cancel an elicitation request.",
}
}
/// Convert a stable action identifier into a display label.
///
/// This is intentionally presentation-only: the returned string must never be
/// parsed back into an action name, because underscores and casing are part of
/// the stable config contract.
pub(super) fn action_label(action: &str) -> String {
if action == "change_host" {
return "Change Where to Run".to_string();
}
action
.split('_')
.map(|word| {
let mut chars = word.chars();
let Some(first) = chars.next() else {
return String::new();
};
format!("{}{}", first.to_ascii_uppercase(), chars.as_str())
})
.collect::<Vec<_>>()
.join(" ")
}
/// Format an action's active single-key and chord alternatives in config order.
///
/// Duplicate runtime variants that normalize to the same config spec are shown
/// once so compatibility defaults do not appear as separate user choices.
pub(super) fn format_action_binding_summary(
runtime_keymap: &RuntimeKeymap,
context: &str,
action: &str,
) -> String {
let specs = super::active_binding_specs(runtime_keymap, context, action).unwrap_or_else(|_| {
bindings_for_action(runtime_keymap, context, action)
.unwrap_or_default()
.iter()
.filter_map(|binding| super::binding_to_config_key_spec(*binding).ok())
.collect()
});
let mut seen = BTreeSet::new();
let specs = specs
.into_iter()
.filter(|spec| seen.insert(spec.clone()))
.map(|spec| {
let Some(completion) = spec.strip_prefix("leader ") else {
return spec;
};
let resolved = runtime_keymap
.chords
.leader
.iter()
.filter_map(|prefix| super::binding_to_config_key_spec(*prefix).ok())
.map(|prefix| format!("{prefix} {completion}"))
.collect::<Vec<_>>();
if resolved.is_empty() {
format!("{spec} (inactive)")
} else {
format!("{spec} ({})", resolved.join(", "))
}
})
.collect::<Vec<_>>();
if specs.is_empty() {
"unbound".to_string()
} else {
specs.join(", ")
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum KeymapDebugBindingSource {
Custom,
CustomGlobal,
Default,
}
impl KeymapDebugBindingSource {
pub(super) const fn label(&self) -> &'static str {
match self {
Self::Custom => "Custom",
Self::CustomGlobal => "Custom global",
Self::Default => "Default",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct KeymapDebugActionMatch {
pub(super) context: &'static str,
pub(super) action: &'static str,
pub(super) label: String,
pub(super) description: &'static str,
pub(super) source: KeymapDebugBindingSource,
}
pub(super) fn matching_actions_for_key_event(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
event: KeyEvent,
) -> Vec<KeymapDebugActionMatch> {
KEYMAP_ACTIONS
.iter()
.filter_map(|descriptor| {
let bindings =
bindings_for_action(runtime_keymap, descriptor.context, descriptor.action)?;
bindings
.iter()
.any(|binding| binding.is_press(event))
.then(|| KeymapDebugActionMatch {
context: descriptor.context,
action: descriptor.action,
label: action_label(descriptor.action),
description: descriptor.description,
source: debug_binding_source(keymap_config, descriptor),
})
})
.collect()
}
fn debug_binding_source(
keymap_config: &TuiKeymap,
descriptor: &KeymapActionDescriptor,
) -> KeymapDebugBindingSource {
let mut keymap_config = keymap_config.clone();
let Some(slot) = binding_slot(&mut keymap_config, descriptor.context, descriptor.action) else {
return KeymapDebugBindingSource::Default;
};
if slot.is_some() {
return KeymapDebugBindingSource::Custom;
}
let Some(global_slot) = global_fallback_slot(&mut keymap_config, descriptor) else {
return KeymapDebugBindingSource::Default;
};
if global_slot.is_some() {
KeymapDebugBindingSource::CustomGlobal
} else {
KeymapDebugBindingSource::Default
}
}
fn global_fallback_slot<'a>(
keymap: &'a mut TuiKeymap,
descriptor: &KeymapActionDescriptor,
) -> Option<&'a mut Option<KeybindingsSpec>> {
if descriptor.context != "composer" {
return None;
}
match descriptor.action {
"submit" => Some(&mut keymap.global.submit),
"queue" => Some(&mut keymap.global.queue),
"toggle_shortcuts" => Some(&mut keymap.global.toggle_shortcuts),
_ => None,
}
}

View File

@@ -0,0 +1,201 @@
//! Captures single keys, literal chords, and leader suffixes inside `/keymap`.
//!
//! Content is measured at the inset width, including wrapped action identifiers.
//! Raw key capture remains independent of list navigation bindings.
use super::key_event_to_config_key_spec;
use crate::app_event::AppEvent;
use crate::app_event::KeymapCaptureMode;
use crate::app_event::KeymapEditIntent;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::CancellationEvent;
use crate::bottom_pane::menu_surface_padding_height;
use crate::bottom_pane::popup_content_width;
use crate::bottom_pane::render_menu_surface;
use crate::render::renderable::Renderable;
use crate::style::accent_color;
use crate::wrapping::word_wrap_lines;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
/// Bottom-pane view that captures one key or a two-stroke `/keymap` chord.
///
/// The view is deliberately transient: it renders instructions, captures the
/// requested number of strokes, and emits their canonical config representation
/// to the app layer. It does not mutate config itself, because mutation needs
/// the latest runtime keymap to detect conflicts and stale selections.
pub(crate) struct KeymapCaptureView {
context: String,
action: String,
intent: KeymapEditIntent,
capture_mode: KeymapCaptureMode,
first_stroke: Option<String>,
label: String,
current_binding: String,
app_event_tx: AppEventSender,
complete: bool,
error_message: Option<String>,
}
impl KeymapCaptureView {
pub(super) fn new(
context: String,
action: String,
intent: KeymapEditIntent,
capture_mode: KeymapCaptureMode,
label: String,
current_binding: String,
app_event_tx: AppEventSender,
) -> Self {
Self {
context,
action,
intent,
capture_mode,
first_stroke: None,
label,
current_binding,
app_event_tx,
complete: false,
error_message: None,
}
}
fn lines(&self, width: u16) -> Vec<Line<'static>> {
let wrap_width = usize::from(width.max(1));
let header = vec![
Line::from("Remap Shortcut".bold()),
Line::from(vec![
"Action: ".dim(),
self.label.clone().into(),
" ".into(),
format!("{}.{}", self.context, self.action).dim(),
]),
Line::from(vec![
"Current: ".dim(),
self.current_binding.clone().fg(accent_color()),
]),
];
let mut lines = word_wrap_lines(&header, wrap_width);
let instructions = match (self.capture_mode, self.first_stroke.as_deref()) {
(KeymapCaptureMode::SingleKey, _) => "Press the new key now. Esc cancels.".to_string(),
(KeymapCaptureMode::Chord, None) => {
"Press the first key, then the second. Esc cancels.".to_string()
}
(KeymapCaptureMode::Chord, Some(first)) => {
format!("First key: {first}. Press the second key. Esc cancels.")
}
(KeymapCaptureMode::LeaderChord, _) => {
"Press the key that follows the configured leader. Esc cancels.".to_string()
}
};
lines.extend(
textwrap::wrap(&instructions, wrap_width)
.into_iter()
.map(|line| Line::from(line.into_owned().dim())),
);
if let Some(error) = &self.error_message {
lines.push(Line::from(""));
let options = textwrap::Options::new(wrap_width)
.initial_indent("Error: ")
.subsequent_indent(" ");
lines.extend(
textwrap::wrap(error, options)
.into_iter()
.map(|line| Line::from(line.into_owned().red())),
);
}
lines
}
}
impl Renderable for KeymapCaptureView {
fn render(&self, area: Rect, buf: &mut Buffer) {
let content_area = render_menu_surface(area, buf);
Paragraph::new(self.lines(content_area.width)).render(content_area, buf);
}
fn desired_height(&self, width: u16) -> u16 {
(self.lines(popup_content_width(width)).len() as u16)
.saturating_add(menu_surface_padding_height())
}
}
impl BottomPaneView for KeymapCaptureView {
fn keymap_contexts(&self) -> crate::keymap::KeymapContextSet {
crate::keymap::KeymapContextSet::raw_key_capture()
}
fn accepts_input_when_disconnected(&self) -> bool {
true
}
fn handle_key_event(&mut self, key_event: KeyEvent) {
if key_event.kind == KeyEventKind::Release
|| (self.capture_mode == KeymapCaptureMode::Chord
&& key_event.kind != KeyEventKind::Press)
{
return;
}
if crate::key_hint::plain(KeyCode::Esc).is_press(key_event) {
self.complete = true;
return;
}
match key_event_to_config_key_spec(key_event) {
Ok(key) => {
self.error_message = None;
let key = match self.capture_mode {
KeymapCaptureMode::SingleKey => key,
KeymapCaptureMode::LeaderChord => format!("leader {key}"),
KeymapCaptureMode::Chord => {
let Some(first_stroke) = self.first_stroke.take() else {
self.first_stroke = Some(key);
return;
};
format!("{first_stroke} {key}")
}
};
self.app_event_tx.send(AppEvent::KeymapCaptured {
context: self.context.clone(),
action: self.action.clone(),
key,
intent: self.intent.clone(),
});
self.complete = true;
}
Err(error) => {
self.error_message = Some(error);
}
}
}
fn is_complete(&self) -> bool {
self.complete
}
fn on_ctrl_c(&mut self) -> CancellationEvent {
self.complete = true;
CancellationEvent::Handled
}
fn prefer_esc_to_handle_key_event(&self) -> bool {
true
}
}
#[cfg(test)]
#[path = "capture_tests.rs"]
mod tests;

View File

@@ -0,0 +1,257 @@
use super::super::KeymapEditOutcome;
use super::super::build_keymap_replace_binding_menu_params;
use super::super::keymap_with_bindings;
use super::super::keymap_with_edit;
use super::KeymapCaptureView;
use crate::app_event::AppEvent;
use crate::app_event::KeymapCaptureMode;
use crate::app_event::KeymapEditIntent;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::BottomPaneView;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::Renderable;
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;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::mpsc::unbounded_channel;
fn capture_view() -> (KeymapCaptureView, UnboundedReceiver<AppEvent>) {
let (tx, rx) = unbounded_channel();
let view = KeymapCaptureView::new(
"list".to_string(),
"jump_top".to_string(),
KeymapEditIntent::AddAlternate,
KeymapCaptureMode::Chord,
"Jump Top".to_string(),
"home".to_string(),
AppEventSender::new(tx),
);
(view, rx)
}
fn ctrl_key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::CONTROL)
}
fn capture_lines_at_width(view: &KeymapCaptureView, width: u16) -> String {
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
width,
view.desired_height(width),
);
let mut buf = Buffer::empty(area);
view.render(area, &mut buf);
(0..area.height)
.map(|y| {
(0..area.width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_owned()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn chord_capture_instruction_snapshots() {
let (mut view, _rx) = capture_view();
insta::assert_snapshot!(capture_lines_at_width(&view, /*width*/ 80), @r"
Remap Shortcut
Action: Jump Top list.jump_top
Current: home
Press the first key, then the second. Esc cancels.
");
view.handle_key_event(ctrl_key(KeyCode::Char('x')));
insta::assert_snapshot!(capture_lines_at_width(&view, /*width*/ 80), @r"
Remap Shortcut
Action: Jump Top list.jump_top
Current: home
First key: ctrl-x. Press the second key. Esc cancels.
");
}
#[test]
fn chord_capture_instructions_wrap_to_narrow_panes() {
let (mut view, _rx) = capture_view();
insta::assert_snapshot!(capture_lines_at_width(&view, /*width*/ 24), @"
Remap Shortcut
Action: Jump Top
list.jump_top
Current: home
Press the first key,
then the second. Esc
cancels.
");
assert_eq!(view.desired_height(/*width*/ 24), 9);
view.handle_key_event(KeyEvent::new(
KeyCode::F(/*n*/ 24),
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT,
));
insta::assert_snapshot!(capture_lines_at_width(&view, /*width*/ 24), @"
Remap Shortcut
Action: Jump Top
list.jump_top
Current: home
First key: ctrl-
alt-shift-f24. Press
the second key. Esc
cancels.
");
assert_eq!(view.desired_height(/*width*/ 24), 10);
}
#[test]
fn captures_repeated_strokes_but_ignores_auto_repeat() {
let (mut view, mut rx) = capture_view();
view.handle_key_event(KeyEvent::from(KeyCode::F(/*n*/ 25)));
assert!(view.error_message.is_some());
view.handle_key_event(ctrl_key(KeyCode::Char('x')));
assert_eq!(view.error_message, None);
view.handle_key_event(KeyEvent {
kind: KeyEventKind::Repeat,
..ctrl_key(KeyCode::Char('x'))
});
assert!(!view.is_complete());
assert_eq!(view.first_stroke.as_deref(), Some("ctrl-x"));
assert!(rx.try_recv().is_err());
view.handle_key_event(ctrl_key(KeyCode::Char('x')));
let AppEvent::KeymapCaptured {
context,
action,
key,
intent,
} = rx.try_recv().expect("completed chord capture event")
else {
panic!("expected a captured key chord");
};
assert_eq!(context, "list");
assert_eq!(action, "jump_top");
assert_eq!(key, "ctrl-x ctrl-x");
assert_eq!(intent, KeymapEditIntent::AddAlternate);
assert!(view.is_complete());
}
#[test]
fn modified_escape_is_captured_as_a_chord_stroke() {
let (mut canceled_view, mut canceled_events) = capture_view();
canceled_view.handle_key_event(ctrl_key(KeyCode::Char('x')));
canceled_view.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(canceled_view.is_complete());
assert!(canceled_events.try_recv().is_err());
let ctrl_x = ctrl_key(KeyCode::Char('x'));
let ctrl_home = ctrl_key(KeyCode::Home);
let ctrl_esc = ctrl_key(KeyCode::Esc);
let alt_esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::ALT);
for (first, second, expected) in [
(ctrl_x, ctrl_esc, "ctrl-x ctrl-esc"),
(ctrl_x, alt_esc, "ctrl-x alt-esc"),
(ctrl_esc, ctrl_home, "ctrl-esc ctrl-home"),
(alt_esc, ctrl_home, "alt-esc ctrl-home"),
] {
let (mut view, mut rx) = capture_view();
view.handle_key_event(first);
assert!(
!view.is_complete(),
"the prefix of `{expected}` must be captured"
);
assert!(rx.try_recv().is_err());
view.handle_key_event(second);
let AppEvent::KeymapCaptured { key, .. } =
rx.try_recv().expect("completed modified-Escape chord")
else {
panic!("expected a captured key chord");
};
assert_eq!(key, expected);
assert!(view.is_complete());
}
}
#[test]
fn replacing_one_list_binding_with_chord_preserves_other_alternatives() {
let config = keymap_with_bindings(
&TuiKeymap::default(),
"list",
"jump_top",
&["home".to_string(), "ctrl-x home".to_string()],
)
.expect("list chord bindings");
let runtime = RuntimeKeymap::from_config(&config).expect("valid list key chords");
let params = build_keymap_replace_binding_menu_params(
"list".to_string(),
"jump_top".to_string(),
&runtime,
);
let chord_item = params
.items
.iter()
.find(|item| item.name == "home (key chord)")
.expect("replace-one chord capture option");
let (tx, mut rx) = unbounded_channel();
let sender = AppEventSender::new(tx);
chord_item.actions[0](&sender);
let AppEvent::OpenKeymapCapture {
context,
action,
intent,
capture_mode,
} = rx.try_recv().expect("open replace-one chord capture")
else {
panic!("expected a chord capture event");
};
assert_eq!(capture_mode, KeymapCaptureMode::Chord);
assert_eq!(
intent,
KeymapEditIntent::ReplaceOne {
old_key: "home".to_string()
}
);
let outcome = keymap_with_edit(
&config,
&runtime,
&context,
&action,
"ctrl-x ctrl-h",
&intent,
)
.expect("replace one binding with a key chord");
let expected_bindings = vec!["ctrl-x ctrl-h".to_string(), "ctrl-x home".to_string()];
let expected_keymap = keymap_with_bindings(&config, "list", "jump_top", &expected_bindings)
.expect("updated list key chords");
RuntimeKeymap::from_config(&expected_keymap).expect("updated list chord keymap is valid");
assert_eq!(
outcome,
KeymapEditOutcome::Updated {
keymap_config: Box::new(expected_keymap),
bindings: expected_bindings,
message: "Replaced `home` with `ctrl-x ctrl-h` for `list.jump_top`.".to_string(),
}
);
}

View File

@@ -0,0 +1,251 @@
use codex_config::types::TuiKeymap;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use std::time::Duration;
use std::time::Instant;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::CancellationEvent;
use crate::key_hint::KeyBinding;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::Renderable;
use super::actions;
use super::actions::matching_actions_for_key_event;
use super::key_event_to_config_key_spec;
const MISSING_KEY_HINT_DELAY: Duration = Duration::from_secs(3);
const SHORT_MISSING_KEY_HINT: &str = "Tip: Codex can only inspect keys your terminal sends.";
const DELAYED_MISSING_KEY_HINT: &str = "Still waiting? If nothing changes when you press a key, your terminal is not sending that key to Codex. Only received keys can be assigned as shortcuts.";
struct KeymapDebugReport {
detected: KeyBinding,
config_key: Result<String, String>,
raw_event: String,
matches: Vec<actions::KeymapDebugActionMatch>,
}
/// Bottom-pane view for inspecting how terminal key events map to keymap actions.
pub(crate) struct KeymapDebugView {
runtime_keymap: RuntimeKeymap,
keymap_config: TuiKeymap,
opened_at: Instant,
last_report: Option<KeymapDebugReport>,
complete: bool,
}
pub(crate) fn build_keymap_debug_view(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
) -> KeymapDebugView {
KeymapDebugView {
runtime_keymap: runtime_keymap.clone(),
keymap_config: keymap_config.clone(),
opened_at: Instant::now(),
last_report: None,
complete: false,
}
}
impl KeymapDebugView {
fn lines(&self, width: u16) -> Vec<Line<'static>> {
self.lines_at(width, Instant::now())
}
fn lines_at(&self, width: u16, now: Instant) -> Vec<Line<'static>> {
let wrap_width = usize::from(width.max(1));
let mut lines = vec![
Line::from("Keypress Inspector".bold()),
Line::from(
"Press any key to see what Codex receives. Esc is inspected; Ctrl+C closes.".dim(),
),
];
let hint = if self.should_show_delayed_hint(now) {
DELAYED_MISSING_KEY_HINT
} else {
SHORT_MISSING_KEY_HINT
};
push_wrapped_dim(&mut lines, hint.to_string(), wrap_width, "", "");
let Some(report) = &self.last_report else {
lines.push(Line::from(""));
lines.push(Line::from("Waiting for a keypress...".cyan()));
return lines;
};
lines.push(Line::from(""));
lines.push(Line::from(vec![
"Detected: ".dim(),
report.detected.display_label().cyan(),
]));
match &report.config_key {
Ok(config_key) => {
lines.push(Line::from(vec![
"Config key: ".dim(),
config_key.clone().cyan(),
]));
}
Err(error) => {
push_wrapped_dim(
&mut lines,
format!("unsupported - {error}"),
wrap_width,
"Config key: ",
" ",
);
}
}
push_wrapped_dim(
&mut lines,
report.raw_event.clone(),
wrap_width,
"Raw event: ",
" ",
);
lines.push(Line::from(""));
lines.push(Line::from("Assigned actions:".dim()));
if report.matches.is_empty() {
lines.push(Line::from(" none".dim()));
} else {
for matched_action in &report.matches {
let action = format!(
"{}.{} ({}) - {} [{}]",
matched_action.context,
matched_action.action,
matched_action.label,
matched_action.description,
matched_action.source.label()
);
push_wrapped_dim(&mut lines, action, wrap_width, " - ", " ");
}
}
lines
}
fn should_show_delayed_hint(&self, now: Instant) -> bool {
self.last_report.is_none() && now.duration_since(self.opened_at) >= MISSING_KEY_HINT_DELAY
}
#[cfg(test)]
pub(crate) fn show_delayed_hint_for_test(&mut self) {
self.opened_at = Instant::now() - MISSING_KEY_HINT_DELAY;
}
}
impl Renderable for KeymapDebugView {
fn render(&self, area: Rect, buf: &mut Buffer) {
Paragraph::new(self.lines(area.width)).render(area, buf);
}
fn desired_height(&self, width: u16) -> u16 {
self.lines(width).len() as u16
}
}
impl BottomPaneView for KeymapDebugView {
fn keymap_contexts(&self) -> crate::keymap::KeymapContextSet {
crate::keymap::KeymapContextSet::raw_key_capture()
}
fn accepts_input_when_disconnected(&self) -> bool {
true
}
fn handle_key_event(&mut self, key_event: KeyEvent) {
if key_event.kind == KeyEventKind::Release {
return;
}
self.last_report = Some(KeymapDebugReport {
detected: KeyBinding::from_event(key_event),
config_key: key_event_to_config_key_spec(key_event),
raw_event: key_event_debug_summary(key_event),
matches: matching_actions_for_key_event(
&self.runtime_keymap,
&self.keymap_config,
key_event,
),
});
}
fn is_complete(&self) -> bool {
self.complete
}
fn on_ctrl_c(&mut self) -> CancellationEvent {
self.complete = true;
CancellationEvent::Handled
}
fn prefer_esc_to_handle_key_event(&self) -> bool {
true
}
fn next_frame_delay(&self) -> Option<Duration> {
if self.last_report.is_some() {
return None;
}
self.opened_at
.checked_add(MISSING_KEY_HINT_DELAY)
.and_then(|show_at| show_at.checked_duration_since(Instant::now()))
.filter(|delay| !delay.is_zero())
}
}
fn push_wrapped_dim(
lines: &mut Vec<Line<'static>>,
text: String,
wrap_width: usize,
initial_indent: &'static str,
subsequent_indent: &'static str,
) {
let options = textwrap::Options::new(wrap_width)
.initial_indent(initial_indent)
.subsequent_indent(subsequent_indent);
lines.extend(
textwrap::wrap(&text, options)
.into_iter()
.map(|line| Line::from(line.into_owned().dim())),
);
}
fn key_event_debug_summary(key_event: KeyEvent) -> String {
format!(
"code={:?}, modifiers={}, kind={:?}",
key_event.code,
key_modifiers_debug_label(key_event.modifiers),
key_event.kind
)
}
fn key_modifiers_debug_label(modifiers: KeyModifiers) -> String {
if modifiers.is_empty() {
return "none".to_string();
}
let mut parts = Vec::new();
if modifiers.contains(KeyModifiers::CONTROL) {
parts.push("ctrl".to_string());
}
if modifiers.contains(KeyModifiers::ALT) {
parts.push("alt".to_string());
}
if modifiers.contains(KeyModifiers::SHIFT) {
parts.push("shift".to_string());
}
let known_modifiers = KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT;
let other_modifiers = modifiers.difference(known_modifiers);
if !other_modifiers.is_empty() {
parts.push(format!("{other_modifiers:?}"));
}
parts.join("|")
}

View File

@@ -0,0 +1,139 @@
//! Configured child-menu navigation and disabled-description alignment.
use super::*;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::ListSelectionView;
use crate::key_hint;
use crate::render::renderable::Renderable;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use tokio::sync::mpsc::unbounded_channel;
fn child_menus(runtime: &RuntimeKeymap) -> [(&'static str, SelectionViewParams); 3] {
let config = TuiKeymap::default();
let conflicting = keymap_with_replacement(&config, "composer", "submit", "tab")
.expect("valid key specification");
let error = RuntimeKeymap::from_config(&conflicting).expect_err("tab already queues a message");
[
(
"action",
build_keymap_action_menu_params(
"global".to_string(),
"open_transcript".to_string(),
runtime,
&config,
),
),
(
"replace",
build_keymap_replace_binding_menu_params(
"global".to_string(),
"open_transcript".to_string(),
runtime,
),
),
(
"conflict",
build_keymap_conflict_params(
"composer".to_string(),
"submit".to_string(),
"tab".to_string(),
KeymapEditIntent::ReplaceAll,
error,
runtime,
),
),
]
}
fn render_menu(view: &ListSelectionView) -> Vec<String> {
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 16,
);
let mut buf = Buffer::empty(area);
view.render(area, &mut buf);
(0..area.height)
.map(|y| {
(0..area.width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_owned()
})
.collect()
}
#[test]
fn child_menu_hints_and_actions_follow_configured_list_bindings() {
let mut runtime = RuntimeKeymap::defaults();
runtime.list.accept = vec![key_hint::plain(KeyCode::F(/*n*/ 3))];
runtime.list.cancel = vec![key_hint::plain(KeyCode::F(/*n*/ 2))];
for (_, params) in child_menus(&runtime) {
let (tx, mut rx) = unbounded_channel();
let mut view =
ListSelectionView::new(params, AppEventSender::new(tx), runtime.list.clone());
let rows = render_menu(&view);
assert_eq!(rows.last().unwrap().trim(), "f3 select · f2 back");
view.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(rx.try_recv().is_err());
view.handle_key_event(KeyEvent::from(KeyCode::F(/*n*/ 3)));
assert!(matches!(
rx.try_recv(),
Ok(AppEvent::OpenKeymapCapture {
capture_mode: KeymapCaptureMode::SingleKey,
..
})
));
}
for (_, params) in child_menus(&runtime) {
let (tx, mut rx) = unbounded_channel();
let mut view =
ListSelectionView::new(params, AppEventSender::new(tx), runtime.list.clone());
view.handle_key_event(KeyEvent::from(KeyCode::F(/*n*/ 2)));
assert!(view.is_complete());
assert!(rx.try_recv().is_err());
}
}
#[test]
fn disabled_reason_wraps_in_the_description_column() {
let runtime = RuntimeKeymap::defaults();
let params = build_keymap_action_menu_params(
"global".to_string(),
"open_transcript".to_string(),
&runtime,
&TuiKeymap::default(),
);
let (tx, _rx) = unbounded_channel();
let view = ListSelectionView::new(params, AppEventSender::new(tx), runtime.list);
let width = 64;
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
width,
view.desired_height(width),
);
let mut buf = Buffer::empty(area);
view.render(area, &mut buf);
let rows = buf
.content()
.chunks(usize::from(width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
})
.collect::<Vec<_>>();
let y = rows
.iter()
.position(|row| row.contains("Remove custom binding (disabled)"))
.expect("disabled action stays visible");
let reason_start = rows[y].find("No custom root override").unwrap();
let continuation_start = rows[y + 1].find("to remove").unwrap();
assert_eq!(
crate::width::display_width(&rows[y + 1][..continuation_start]),
crate::width::display_width(&rows[y][..reason_start])
);
}

View File

@@ -0,0 +1,499 @@
//! Shortcut picker construction for `/keymap`.
//!
//! Keep the shared picker panel and reserved result viewport on the production
//! factory so tabs and search stay anchored in the live picker.
use codex_config::types::TuiKeymap;
use ratatui::style::Styled;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::text::Span;
use unicode_width::UnicodeWidthStr;
use crate::app_event::AppEvent;
use crate::bottom_pane::ColumnWidthMode;
use crate::bottom_pane::PickerSurface;
use crate::bottom_pane::SelectionItem;
use crate::bottom_pane::SelectionRowDisplay;
use crate::bottom_pane::SelectionTab;
use crate::bottom_pane::SelectionViewParams;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::ColumnRenderable;
use crate::render::renderable::Renderable;
use crate::style::accent_style;
use super::actions::KEYMAP_ACTIONS;
use super::actions::KeymapActionFilter;
use super::actions::action_label;
use super::actions::format_action_binding_summary;
use super::has_custom_binding;
pub(crate) const KEYMAP_PICKER_VIEW_ID: &str = "keymap-picker";
pub(super) const KEYMAP_ALL_TAB_ID: &str = "all-shortcuts";
pub(super) const KEYMAP_COMMON_TAB_ID: &str = "common-shortcuts";
pub(super) const KEYMAP_CUSTOM_TAB_ID: &str = "custom-shortcuts";
pub(super) const KEYMAP_UNBOUND_TAB_ID: &str = "unbound-shortcuts";
pub(super) const KEYMAP_DEBUG_TAB_ID: &str = "debug-shortcuts";
const KEYMAP_CONTEXT_LABEL_WIDTH: usize = 12;
const KEYMAP_ROW_PREFIX_WIDTH: usize = KEYMAP_CONTEXT_LABEL_WIDTH + 3;
#[derive(Clone, Debug)]
struct KeymapActionRow {
context: &'static str,
context_label: &'static str,
action: &'static str,
label: String,
description: &'static str,
binding_summary: String,
custom_binding: bool,
}
impl KeymapActionRow {
fn is_unbound(&self) -> bool {
self.binding_summary == "unbound"
}
}
struct KeymapContextTab {
id: &'static str,
label: &'static str,
description: &'static str,
contexts: &'static [&'static str],
}
const KEYMAP_COMMON_ACTIONS: &[(&str, &str)] = &[
("composer", "submit"),
("chat", "interrupt_turn"),
("editor", "insert_newline"),
("composer", "queue"),
("global", "toggle_fast_mode"),
("global", "open_external_editor"),
("global", "copy"),
("global", "toggle_vim_mode"),
("editor", "delete_backward_word"),
("editor", "delete_forward_word"),
("editor", "move_word_left"),
("editor", "move_word_right"),
("global", "open_transcript"),
("pager", "close"),
("pager", "page_up"),
("pager", "page_down"),
("approval", "open_fullscreen"),
("approval", "approve"),
("approval", "approve_for_session"),
("approval", "decline"),
("approval", "cancel"),
];
const KEYMAP_CONTEXT_TABS: &[KeymapContextTab] = &[
KeymapContextTab {
id: "app-shortcuts",
label: "App",
description: "Global and chat-level shortcuts.",
contexts: &["global", "chat"],
},
KeymapContextTab {
id: "composer-shortcuts",
label: "Composer",
description: "Composer submission and queue shortcuts.",
contexts: &["composer"],
},
KeymapContextTab {
id: "editor-shortcuts",
label: "Editor",
description: "Inline editor movement and editing shortcuts.",
contexts: &["editor"],
},
KeymapContextTab {
id: "vim-shortcuts",
label: "Vim",
description: "Vim normal-mode and operator shortcuts.",
contexts: &[
"vim_normal",
"vim_operator",
"vim_search",
"vim_text_object",
],
},
KeymapContextTab {
id: "navigation-shortcuts",
label: "Navigation",
description: "Pager and selection-list navigation shortcuts.",
contexts: &["pager", "list"],
},
KeymapContextTab {
id: "agents-shortcuts",
label: "Agents",
description: "Shared agents dashboard shortcuts.",
contexts: &["agents"],
},
KeymapContextTab {
id: "approval-shortcuts",
label: "Approval",
description: "Approval prompt shortcuts.",
contexts: &["approval"],
},
];
#[cfg(test)]
pub(crate) fn build_keymap_picker_params(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
) -> SelectionViewParams {
build_keymap_picker_params_with_filter(
runtime_keymap,
keymap_config,
KeymapActionFilter::default(),
)
}
pub(crate) fn build_keymap_picker_params_with_filter(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
action_filter: KeymapActionFilter,
) -> SelectionViewParams {
build_keymap_picker_params_for_action(
runtime_keymap,
keymap_config,
action_filter,
/*selected_action*/ None,
)
}
#[cfg(test)]
pub(crate) fn build_keymap_picker_params_for_selected_action(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
context: &str,
action: &str,
) -> SelectionViewParams {
build_keymap_picker_params_for_selected_action_with_filter(
runtime_keymap,
keymap_config,
KeymapActionFilter::default(),
context,
action,
)
}
pub(crate) fn build_keymap_picker_params_for_selected_action_with_filter(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
action_filter: KeymapActionFilter,
context: &str,
action: &str,
) -> SelectionViewParams {
build_keymap_picker_params_for_action(
runtime_keymap,
keymap_config,
action_filter,
Some((context, action)),
)
}
fn build_keymap_picker_params_for_action(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
action_filter: KeymapActionFilter,
selected_action: Option<(&str, &str)>,
) -> SelectionViewParams {
let rows = build_keymap_rows(runtime_keymap, keymap_config, action_filter);
let total = rows.len();
let custom_count = rows.iter().filter(|row| row.custom_binding).count();
let unbound_count = rows.iter().filter(|row| row.is_unbound()).count();
let initial_selected_idx = selected_action.and_then(|(context, action)| {
rows.iter()
.position(|row| row.context == context && row.action == action)
});
let name_column_width = rows
.iter()
.map(|row| KEYMAP_ROW_PREFIX_WIDTH + UnicodeWidthStr::width(row.label.as_str()))
.max();
let mut tabs = Vec::new();
tabs.push(SelectionTab {
id: KEYMAP_ALL_TAB_ID.to_string(),
label: "All".to_string(),
header: keymap_header(
"All configurable shortcuts.".to_string(),
format!("{total} actions, {custom_count} customized, {unbound_count} unbound."),
),
items: keymap_selection_items(
rows.iter(),
"No shortcuts available",
"No configurable shortcuts are available",
),
});
let common_rows = keymap_common_rows(&rows);
let common_count = common_rows.len();
tabs.push(SelectionTab {
id: KEYMAP_COMMON_TAB_ID.to_string(),
label: "Common".to_string(),
header: keymap_header(
"Frequently customized shortcuts.".to_string(),
action_count_line(common_count),
),
items: keymap_selection_items(
common_rows,
"No common shortcuts",
"No common shortcut actions are available",
),
});
let custom_rows = rows
.iter()
.filter(|row| row.custom_binding)
.collect::<Vec<_>>();
tabs.push(SelectionTab {
id: KEYMAP_CUSTOM_TAB_ID.to_string(),
label: format!("Customized ({custom_count})"),
header: keymap_header(
"Root-level shortcut overrides.".to_string(),
action_count_line(custom_count),
),
items: keymap_selection_items(
custom_rows,
"No customized shortcuts",
"No root-level keymap overrides have been configured",
),
});
let unbound_rows = rows
.iter()
.filter(|row| row.is_unbound())
.collect::<Vec<_>>();
tabs.push(SelectionTab {
id: KEYMAP_UNBOUND_TAB_ID.to_string(),
label: format!("Unbound ({unbound_count})"),
header: keymap_header(
"Actions without an active shortcut.".to_string(),
action_count_line(unbound_count),
),
items: keymap_selection_items(
unbound_rows,
"No unbound shortcuts",
"Every configurable action currently has a shortcut",
),
});
for tab in KEYMAP_CONTEXT_TABS {
let tab_rows = rows
.iter()
.filter(|row| tab.contexts.contains(&row.context))
.collect::<Vec<_>>();
let count = tab_rows.len();
tabs.push(SelectionTab {
id: tab.id.to_string(),
label: tab.label.to_string(),
header: keymap_header(tab.description.to_string(), action_count_line(count)),
items: keymap_selection_items(
tab_rows,
"No shortcuts in this group",
"No configurable actions are available in this group",
),
});
}
tabs.push(keymap_debug_tab());
SelectionViewParams {
allow_input_when_disconnected: true,
view_id: Some(KEYMAP_PICKER_VIEW_ID),
picker_surface: PickerSurface::Panel,
max_visible_rows: 24,
reserve_result_rows: true,
header: Box::new(()),
footer_hint: Some(keymap_picker_hint_line()),
tab_footer_hints: vec![(KEYMAP_DEBUG_TAB_ID.to_string(), keymap_debug_hint_line())],
tabs,
initial_tab_id: Some(KEYMAP_ALL_TAB_ID.to_string()),
is_searchable: true,
search_placeholder: Some("Type to search shortcuts".to_string()),
col_width_mode: ColumnWidthMode::AutoAllRows,
row_display: SelectionRowDisplay::SingleLine,
name_column_width,
initial_selected_idx,
..Default::default()
}
}
fn keymap_debug_tab() -> SelectionTab {
SelectionTab {
id: KEYMAP_DEBUG_TAB_ID.to_string(),
label: "Debug".to_string(),
header: keymap_header(
"Inspect keypresses from your terminal.".to_string(),
"See the key Codex detects and any shortcuts assigned to it.".to_string(),
),
items: vec![SelectionItem {
name: "Inspect keypresses".to_string(),
description: Some(
"Press Enter, then any key to inspect it (Ctrl+C exits)"
.to_string(),
),
selected_description: Some(
"Open a live inspector that shows the detected key, config key, and matching actions"
.to_string(),
),
actions: vec![Box::new(|tx| {
tx.send(AppEvent::OpenKeymapDebug);
})],
search_value: Some("debug inspect keypress key terminal detected actions".to_string()),
..Default::default()
}],
}
}
fn build_keymap_rows(
runtime_keymap: &RuntimeKeymap,
keymap_config: &TuiKeymap,
action_filter: KeymapActionFilter,
) -> Vec<KeymapActionRow> {
KEYMAP_ACTIONS
.iter()
.copied()
.filter(|descriptor| descriptor.is_visible(action_filter))
.map(|descriptor| KeymapActionRow {
context: descriptor.context,
context_label: descriptor.context_label,
action: descriptor.action,
label: action_label(descriptor.action),
description: descriptor.description,
binding_summary: format_action_binding_summary(
runtime_keymap,
descriptor.context,
descriptor.action,
),
custom_binding: has_custom_binding(
keymap_config,
descriptor.context,
descriptor.action,
)
.unwrap_or(/*default*/ false),
})
.collect()
}
fn keymap_common_rows(rows: &[KeymapActionRow]) -> Vec<&KeymapActionRow> {
KEYMAP_COMMON_ACTIONS
.iter()
.filter_map(|(context, action)| {
rows.iter()
.find(|row| row.context == *context && row.action == *action)
})
.collect()
}
fn keymap_selection_items<'a>(
rows: impl IntoIterator<Item = &'a KeymapActionRow>,
empty_name: &str,
empty_description: &str,
) -> Vec<SelectionItem> {
let items = rows
.into_iter()
.map(keymap_selection_item)
.collect::<Vec<_>>();
if items.is_empty() {
return vec![SelectionItem {
name: empty_name.to_string(),
description: Some(empty_description.to_string()),
is_disabled: true,
..Default::default()
}];
}
items
}
fn keymap_selection_item(row: &KeymapActionRow) -> SelectionItem {
let context = row.context.to_string();
let action = row.action.to_string();
let source = if row.custom_binding {
"Custom"
} else {
"Default"
};
let search_value = format!(
"{} {} {} {} {} {}",
row.context_label, row.action, row.label, row.description, row.binding_summary, source
);
SelectionItem {
name: row.label.clone(),
name_prefix_spans: keymap_row_prefix(row),
description: Some(row.binding_summary.clone()),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::OpenKeymapActionMenu {
context: context.clone(),
action: action.clone(),
});
})],
search_value: Some(search_value),
..Default::default()
}
}
fn keymap_row_prefix(row: &KeymapActionRow) -> Vec<Span<'static>> {
let indicator = if row.custom_binding {
"*".set_style(accent_style())
} else if row.is_unbound() {
"-".dim()
} else {
" ".into()
};
vec![
format!(
"{:<width$} ",
row.context_label,
width = KEYMAP_CONTEXT_LABEL_WIDTH
)
.dim(),
indicator,
" ".dim(),
]
}
fn keymap_header(description: String, summary: String) -> Box<dyn Renderable> {
let mut header = ColumnRenderable::new();
header.push(Line::from("Keymap".bold()));
header.push(Line::from(description.dim()));
header.push(Line::from(summary.dim()));
Box::new(header)
}
fn action_count_line(count: usize) -> String {
match count {
1 => "1 action.".to_string(),
_ => format!("{count} actions."),
}
}
fn keymap_picker_hint_line() -> Line<'static> {
[
("left/right", " group · "),
("enter", " edit shortcut · "),
("*", " custom · "),
("-", " unbound · "),
("esc", " close"),
]
.into_iter()
.flat_map(|(key, label)| {
crate::key_hint::key_label_spans(key)
.into_iter()
.chain([label.set_style(crate::style::footer_hint_label_style())])
})
.collect::<Line>()
}
fn keymap_debug_hint_line() -> Line<'static> {
let mut spans = crate::key_hint::key_label_spans("enter");
spans.push(" start inspector · ".set_style(crate::style::footer_hint_label_style()));
spans.extend(crate::key_hint::key_label_spans("esc"));
spans.push(" close".set_style(crate::style::footer_hint_label_style()));
spans.into()
}
#[cfg(test)]
#[path = "picker_tests.rs"]
mod tests;

View File

@@ -0,0 +1,84 @@
//! Keep the production shortcut picker's controls anchored while groups and results change.
use super::*;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::ListSelectionView;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use tokio::sync::mpsc::unbounded_channel;
#[test]
fn tabs_and_search_keep_production_picker_geometry_stable() {
for width in [80, 40] {
for height_limit in [u16::MAX, 16] {
let runtime = RuntimeKeymap::defaults();
let params = build_keymap_picker_params(&runtime, &TuiKeymap::default());
let tab_count = params.tabs.len();
let (tx, _rx) = unbounded_channel();
let mut view = ListSelectionView::new(params, AppEventSender::new(tx), runtime.list);
let mut geometry = Vec::new();
for (tab_id, tab_text, hint) in [
(KEYMAP_ALL_TAB_ID, "Common", "left/right"),
(KEYMAP_CUSTOM_TAB_ID, "Customized (0)", "left/right"),
(KEYMAP_DEBUG_TAB_ID, "Debug", "enter"),
] {
for _ in 0..tab_count {
if BottomPaneView::active_tab_id(&view) == Some(tab_id) {
break;
}
view.handle_key_event(KeyEvent::from(KeyCode::Right));
}
assert_eq!(BottomPaneView::active_tab_id(&view), Some(tab_id));
for query in ["", "zzzz-no-matching-shortcut"] {
view.set_search_query(query.to_owned());
let desired_height = view.desired_height(width);
let height = desired_height.min(height_limit);
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buffer = Buffer::empty(area);
view.render(area, &mut buffer);
let lines = (0..height)
.map(|y| {
(0..width)
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
})
.collect::<Vec<_>>();
let search_text = if query.is_empty() {
"Type to search shortcuts"
} else {
query
};
let header_y = lines
.iter()
.position(|line| line.trim() == "Keymap")
.expect("picker title remains visible");
let tabs_y = lines
.iter()
.position(|line| line.contains(tab_text))
.expect("active group remains visible");
let search_y = lines
.iter()
.position(|line| line.trim() == search_text)
.expect("search remains visible");
let hint_y = lines
.iter()
.position(|line| line.trim_start().starts_with(hint))
.expect("group-specific footer remains visible");
geometry.push((desired_height, height, header_y, tabs_y, search_y, hint_y));
}
}
assert_eq!(
geometry,
vec![geometry[0]; geometry.len()],
"group and search changes must keep controls anchored at width {width} and height limit {height_limit}"
);
}
}
}