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,554 @@
//! Snapshot each configuration group and exercise shared panel interactions.
use super::*;
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::CancellationEvent;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::Renderable;
use codex_config::types::CopyOnSelect;
use codex_config::types::Notifications;
use codex_config::types::ResumeCwdMode;
use codex_config::types::RightClickPaste;
use codex_config::types::SessionPickerViewMode;
use codex_config::types::Tui;
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;
const STATUS: ConfigPanelStatus = ConfigPanelStatus {
copy_on_select: true,
right_click_paste: Ok(false),
custom_notification_filters: false,
};
fn panel() -> (ConfigPanel, UnboundedReceiver<AppEvent>) {
let (tx, rx) = unbounded_channel();
(
ConfigPanel::new(
&Tui::default(),
AppEventSender::new(tx),
RuntimeKeymap::defaults().list,
STATUS,
),
rx,
)
}
fn render(view: &impl Renderable, width: u16) -> String {
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
width,
view.desired_height(width),
);
let mut buffer = Buffer::empty(area);
view.render(area, &mut buffer);
(0..area.height)
.map(|y| {
(0..area.width)
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn config_panel_renders_each_group_at_a_stable_height() {
let (mut panel, _rx) = panel();
let height = panel.desired_height(/*width*/ 140);
for section in ConfigSection::ALL {
assert_eq!(panel.picker.active_tab_id(), Some(section.title()));
assert_eq!(panel.desired_height(/*width*/ 140), height);
let narrow_height = panel.desired_height(/*width*/ 50);
panel
.picker
.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
assert_eq!(panel.desired_height(/*width*/ 50), narrow_height);
panel
.picker
.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
insta::assert_snapshot!(
format!("config_{}", section.title()),
render(&panel, /*width*/ 140)
);
panel
.picker
.handle_key_event(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
}
}
#[test]
fn effects_picker_groups_animation_settings() {
let (tx, mut rx) = unbounded_channel();
let keymap = RuntimeKeymap::defaults().list;
let mut view = ListSelectionView::new(
effects(&Tui::default(), &keymap),
AppEventSender::new(tx),
keymap,
);
insta::assert_snapshot!("effects_picker", render(&view, /*width*/ 80));
view.handle_key_event(KeyCode::Enter.into());
assert!(!view.is_complete());
assert!(matches!(
rx.try_recv().expect("save animation event"),
AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
setting: ConfigToggle::Animations,
enabled: true,
})
));
view.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("save animation event"),
AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
setting: ConfigToggle::Animations,
enabled: false,
})
));
}
#[test]
fn deselect_after_copy_requires_effective_copy_on_select() {
let (mut panel, mut rx) = self::panel();
panel.handle_key_event(KeyCode::Left.into());
panel.handle_key_event(KeyCode::Char('/').into());
assert!(panel.handle_paste("deselect after copy".to_string()));
panel.update_config_panel(&ConfigPanelUpdate {
tui: Tui::default(),
keymap: RuntimeKeymap::defaults().list,
status: ConfigPanelStatus {
copy_on_select: false,
..STATUS
},
notice: None,
});
insta::assert_snapshot!(
"deselect_after_copy_unavailable",
render(&panel, /*width*/ 50)
);
panel.handle_key_event(KeyCode::Enter.into());
assert!(rx.try_recv().is_err());
let (mut panel, mut rx) = self::panel();
panel.handle_key_event(KeyCode::Left.into());
panel.handle_key_event(KeyCode::Char('/').into());
assert!(panel.handle_paste("deselect after copy".to_string()));
panel.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("save toggle event"),
AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
setting: ConfigToggle::CopyOnSelectClearSelection,
enabled: true,
})
));
}
#[test]
fn notification_controls_render_dependency_states_and_condition_picker() {
let panel_with_notifications = |notifications, custom_notification_filters| {
let (tx, _rx) = unbounded_channel();
let mut tui = Tui::default();
tui.notification_settings.notifications = notifications;
ConfigPanel::new(
&tui,
AppEventSender::new(tx),
RuntimeKeymap::defaults().list,
ConfigPanelStatus {
custom_notification_filters,
..STATUS
},
)
};
let mut panel = panel_with_notifications(
Notifications::Enabled(true),
/*custom_notification_filters*/ true,
);
panel.handle_key_event(KeyCode::Right.into());
insta::assert_snapshot!("config_notifications_custom", render(&panel, /*width*/ 100));
let (tx, _rx) = unbounded_channel();
let keymap = RuntimeKeymap::defaults().list;
let picker = ListSelectionView::new(
notification_condition(&Tui::default(), &keymap),
AppEventSender::new(tx),
keymap,
);
insta::assert_snapshot!(
"config_notification_condition_choice",
render(&picker, /*width*/ 100)
);
let mut panel = panel_with_notifications(
Notifications::Enabled(false),
/*custom_notification_filters*/ false,
);
panel.handle_key_event(KeyCode::Right.into());
panel.handle_key_event(KeyCode::Down.into());
insta::assert_snapshot!("config_notifications_off", render(&panel, /*width*/ 100));
}
#[test]
fn search_finds_settings_across_groups_and_preserves_the_selected_group() {
let (mut panel, mut rx) = panel();
panel.handle_key_event(KeyEvent::from(KeyCode::Char('/')));
assert!(panel.handle_paste("notify when".to_string()));
insta::assert_snapshot!("config_global_search", render(&panel, /*width*/ 100));
panel.handle_key_event(KeyEvent::from(KeyCode::Right));
assert_eq!(panel.picker.active_tab_id(), Some("Notifications"));
assert_eq!(panel.picker.search_query(), Some("notify when"));
panel.handle_key_event(KeyEvent::from(KeyCode::Esc));
assert_eq!(panel.picker.active_tab_id(), Some("Notifications"));
assert_eq!(panel.picker.search_query(), None);
panel.handle_key_event(KeyEvent::from(KeyCode::Char('/')));
assert!(panel.handle_paste("composer stars".to_string()));
panel.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(matches!(
rx.try_recv().expect("open editor event"),
AppEvent::OpenConfigEditor(handoff) if handoff.editor == ConfigEditor::Effects
));
assert!(rx.try_recv().is_err());
assert!(!panel.is_complete());
}
#[test]
fn on_demand_search_preserves_printable_list_bindings() {
let (tx, mut rx) = unbounded_channel();
let mut keymap = RuntimeKeymap::defaults().list;
keymap.accept = vec![crate::key_hint::plain(KeyCode::Char('t'))];
keymap.cancel = vec![crate::key_hint::plain(KeyCode::Char('h'))];
let mut panel = ConfigPanel::new(
&Tui::default(),
AppEventSender::new(tx),
keymap.clone(),
STATUS,
);
panel.handle_key_event(KeyEvent::from(KeyCode::Char('t')));
assert!(matches!(
rx.try_recv().expect("configured accept binding"),
AppEvent::OpenConfigEditor(handoff) if handoff.editor == ConfigEditor::Theme
));
let (tx, mut rx) = unbounded_channel();
let mut panel = ConfigPanel::new(&Tui::default(), AppEventSender::new(tx), keymap, STATUS);
panel.handle_key_event(KeyEvent::from(KeyCode::Char('/')));
for character in "theme".chars() {
panel.handle_key_event(KeyEvent::from(KeyCode::Char(character)));
}
assert_eq!(panel.picker.search_query(), Some("theme"));
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
/*width*/ 84,
panel.desired_height(/*width*/ 84),
);
let mut buffer = Buffer::empty(area);
panel.render(area, &mut buffer);
assert!(panel.cursor_pos(area).is_some());
assert!(render(&panel, /*width*/ 84).contains("enter open · esc clear search"));
panel.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(matches!(
rx.try_recv().expect("open theme editor event"),
AppEvent::OpenConfigEditor(handoff) if handoff.editor == ConfigEditor::Theme
));
}
#[test]
fn search_matches_displayed_values() {
let (tx, mut rx) = unbounded_channel();
let mut panel = ConfigPanel::new(
&Tui {
theme: Some("Dracula".to_string()),
..Default::default()
},
AppEventSender::new(tx),
RuntimeKeymap::defaults().list,
STATUS,
);
panel.handle_key_event(KeyEvent::from(KeyCode::Char('/')));
assert!(panel.handle_paste("Dracula".to_string()));
panel.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(matches!(
rx.try_recv().expect("open displayed theme editor event"),
AppEvent::OpenConfigEditor(handoff) if handoff.editor == ConfigEditor::Theme
));
}
#[test]
fn session_picker_layout_uses_editor_handoff_and_saves_choice() {
let (mut panel, mut rx) = panel();
for _ in 0..3 {
panel.handle_key_event(KeyCode::Right.into());
}
panel.handle_key_event(KeyCode::Char('/').into());
assert!(panel.handle_paste("session picker layout".to_string()));
panel.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("open editor event"),
AppEvent::OpenConfigEditor(handoff)
if handoff.editor == ConfigEditor::SessionPickerLayout
));
let (tx, mut rx) = unbounded_channel();
let keymap = RuntimeKeymap::defaults().list;
let mut picker = ListSelectionView::new(
session_picker_layout(&Tui::default(), &keymap),
AppEventSender::new(tx),
keymap,
);
insta::assert_snapshot!(
"config_session_picker_layout_choice",
render(&picker, /*width*/ 100)
);
picker.handle_key_event(KeyCode::Down.into());
picker.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("save choice event"),
AppEvent::SaveConfigPreference(ConfigPreference::SessionPickerLayout(
SessionPickerViewMode::Comfortable,
))
));
}
#[test]
fn copy_on_select_uses_editor_handoff_and_saves_choice() {
let (mut panel, mut rx) = panel();
for _ in 0..4 {
panel.handle_key_event(KeyCode::Right.into());
}
panel.handle_key_event(KeyCode::Char('/').into());
assert!(panel.handle_paste("copy on select".to_string()));
panel.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("open editor event"),
AppEvent::OpenConfigEditor(handoff) if handoff.editor == ConfigEditor::CopyOnSelect
));
let (tx, mut rx) = unbounded_channel();
let keymap = RuntimeKeymap::defaults().list;
let mut picker = ListSelectionView::new(
copy_on_select(&Tui::default(), &keymap),
AppEventSender::new(tx),
keymap,
);
insta::assert_snapshot!(
"config_copy_on_select_choice",
render(&picker, /*width*/ 100)
);
picker.handle_key_event(KeyCode::Down.into());
picker.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("save choice event"),
AppEvent::SaveConfigPreference(ConfigPreference::CopyOnSelect(CopyOnSelect::Always))
));
}
#[test]
fn unavailable_right_click_paste_remains_editable() {
let (tx, mut rx) = unbounded_channel();
let mut panel = ConfigPanel::new(
&Tui {
right_click_paste: RightClickPaste::On,
..Tui::default()
},
AppEventSender::new(tx),
RuntimeKeymap::defaults().list,
ConfigPanelStatus {
right_click_paste: Err("Unavailable in inline mode; use your terminal's paste command"),
..STATUS
},
);
for _ in 0..4 {
panel.handle_key_event(KeyCode::Right.into());
}
panel.handle_key_event(KeyCode::Down.into());
panel.handle_key_event(KeyCode::Down.into());
insta::assert_snapshot!(
"config_right_click_paste_unavailable",
render(&panel, /*width*/ 140)
);
panel.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("open editor event"),
AppEvent::OpenConfigEditor(handoff) if handoff.editor == ConfigEditor::RightClickPaste
));
let (tx, mut rx) = unbounded_channel();
let keymap = RuntimeKeymap::defaults().list;
let mut picker = ListSelectionView::new(
right_click_paste(&Tui::default(), &keymap),
AppEventSender::new(tx),
keymap,
);
insta::assert_snapshot!(
"config_right_click_paste_choice",
render(&picker, /*width*/ 100)
);
picker.handle_key_event(KeyCode::Down.into());
picker.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("save choice event"),
AppEvent::SaveConfigPreference(ConfigPreference::RightClickPaste(RightClickPaste::On))
));
}
#[test]
fn resume_directory_disables_current_without_remote_cwd_override() {
let (tx, mut rx) = unbounded_channel();
let keymap = RuntimeKeymap::defaults().list;
let mut picker = ListSelectionView::new(
resume_directory(
&Tui::default(),
&keymap,
ResumeCurrentAvailability::RequiresCwdOverride,
),
AppEventSender::new(tx),
keymap,
);
insta::assert_snapshot!(
"config_resume_directory_remote",
render(&picker, /*width*/ 100)
);
picker.handle_key_event(KeyCode::Down.into());
picker.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().expect("save resume directory event"),
AppEvent::SaveConfigPreference(ConfigPreference::ResumeDirectory(Some(
ResumeCwdMode::Session,
)))
));
}
#[test]
fn refresh_preserves_search_and_updates_visible_state() {
let (mut panel, mut rx) = panel();
panel.handle_key_event(KeyEvent::from(KeyCode::Char('/')));
assert!(panel.handle_paste("tips".to_string()));
panel.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(matches!(
rx.try_recv().expect("save toggle event"),
AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
setting: ConfigToggle::Tips,
enabled: true,
})
));
assert!(panel.saving);
let mut keymap = RuntimeKeymap::defaults().list;
keymap.move_left.clear();
keymap.move_right.clear();
panel.update_config_panel(&ConfigPanelUpdate {
tui: Tui {
show_tooltips: true,
..Default::default()
},
keymap,
status: STATUS,
notice: Some("Test sent · check terminal/system settings".to_string()),
});
assert_eq!(panel.picker.search_query(), Some("tips"));
assert!(!panel.saving);
panel.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(matches!(
rx.try_recv().expect("immediate second press saves again"),
AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
setting: ConfigToggle::Tips,
enabled: false,
})
));
insta::assert_snapshot!(render(&panel, /*width*/ 140));
}
#[test]
fn config_panel_wraps_complete_save_error() {
let (mut panel, _rx) = panel();
panel.update_config_panel(&ConfigPanelUpdate {
tui: Tui::default(),
keymap: RuntimeKeymap::defaults().list,
status: STATUS,
notice: Some(
"Failed to save status line settings: permission denied while writing config.toml"
.to_string(),
),
});
insta::assert_snapshot!(render(&panel, /*width*/ 50));
}
#[test]
fn editor_handoff_blocks_input_until_acknowledged() {
let (tx, mut rx) = unbounded_channel();
let mut keymap = RuntimeKeymap::defaults().list;
keymap.accept = vec![crate::key_hint::plain(KeyCode::BackTab)];
let mut panel = ConfigPanel::new(&Tui::default(), AppEventSender::new(tx), keymap, STATUS);
panel.handle_key_event(KeyEvent::from(KeyCode::Char('/')));
assert!(panel.handle_paste("terminal title".to_string()));
panel.handle_key_event(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
let AppEvent::OpenConfigEditor(handoff) = rx.try_recv().expect("open editor event") else {
panic!("expected config editor handoff");
};
assert_eq!(
(handoff.editor, handoff.activation_key),
(
ConfigEditor::TerminalTitle,
crate::key_hint::plain(KeyCode::BackTab)
)
);
let activated_at = handoff.active_at().expect("active handoff");
panel.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Tab,
KeyModifiers::NONE,
KeyEventKind::Repeat,
));
assert!(
handoff
.active_at()
.is_some_and(|seen_at| seen_at > activated_at)
);
panel.handle_key_release(KeyEvent::new_with_kind(
KeyCode::Tab,
KeyModifiers::NONE,
KeyEventKind::Release,
));
assert_eq!(handoff.active_at(), None);
panel.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert_eq!(panel.on_ctrl_c(), CancellationEvent::Handled);
assert!(!panel.handle_paste(" ignored".to_string()));
assert!(!panel.is_complete());
assert!(rx.try_recv().is_err());
panel.update_config_panel(&ConfigPanelUpdate {
tui: Tui::default(),
keymap: RuntimeKeymap::defaults().list,
status: STATUS,
notice: None,
});
panel.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(rx.try_recv().is_err());
panel.config_editor_opened();
panel.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(matches!(
rx.try_recv().expect("reopened editor event"),
AppEvent::OpenConfigEditor(handoff) if handoff.editor == ConfigEditor::TerminalTitle
));
}

View File

@@ -0,0 +1,193 @@
//! Delegate navigation and selection to the shared list picker.
use super::ConfigEditorHandoff;
use super::ConfigPanel;
use super::ConfigPanelUpdate;
use super::ConfigPreference;
use super::ConfigSection;
use super::ConfigSettingValue;
use super::PickerState;
use super::settings;
use crate::app_event::AppEvent;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::CancellationEvent;
use crate::keymap::KeymapContext;
use crate::keymap::KeymapContextSet;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
impl ConfigPanel {
fn setting_index(&self, selected: usize) -> Option<usize> {
if self
.picker
.search_query()
.is_some_and(|query| !query.is_empty())
{
return self.settings.get(selected).map(|_| selected);
}
let tab = self
.picker
.active_tab_id()
.unwrap_or(ConfigSection::Appearance.title());
self.settings
.iter()
.enumerate()
.filter(|(_, setting)| setting.section.title() == tab)
.nth(selected)
.map(|(index, _)| index)
}
fn activate(&mut self, selected: usize, activation_key: crate::key_hint::KeyBinding) {
if self.saving || self.editor_opening.is_some() {
return;
}
let Some(index) = self.setting_index(selected) else {
return;
};
match &self.settings[index].value {
ConfigSettingValue::Toggle { setting, enabled }
| ConfigSettingValue::DependentToggle {
setting,
enabled,
dependency_met: true,
..
} => {
self.saving = true;
self.app_event_tx
.send(AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
setting: *setting,
enabled: !*enabled,
}));
}
ConfigSettingValue::Editor { editor, .. } => {
let handoff = ConfigEditorHandoff::new(*editor, activation_key);
self.editor_opening = Some(handoff.clone());
self.app_event_tx.send(AppEvent::OpenConfigEditor(handoff));
}
ConfigSettingValue::NotificationTest => {
self.app_event_tx.send(AppEvent::TestConfigNotification);
}
ConfigSettingValue::DependentToggle {
dependency_met: false,
..
}
| ConfigSettingValue::Unavailable { .. } => {}
}
}
fn observe_pending_handoff_key(&self, activation_key: crate::key_hint::KeyBinding) -> bool {
let Some(handoff) = &self.editor_opening else {
return false;
};
if handoff.activation_key.is_same_physical_key(activation_key) {
handoff.mark_activation_seen();
} else {
handoff.mark_activation_inactive();
}
true
}
}
impl BottomPaneView for ConfigPanel {
fn update_config_panel(&mut self, update: &ConfigPanelUpdate) -> bool {
let state = PickerState {
tab: self.picker.active_tab_id().map(str::to_string),
selected: self.picker.selected_index(),
query: self.picker.search_query().map(str::to_string),
notice: update.notice.clone(),
};
self.settings = settings(&update.tui, update.status);
self.saving = false;
self.picker = super::render::picker(
&self.settings,
self.app_event_tx.clone(),
update.keymap.clone(),
state,
);
true
}
fn keymap_contexts(&self) -> KeymapContextSet {
KeymapContextSet::new(KeymapContext::List)
}
fn accepts_input_when_disconnected(&self) -> bool {
true
}
fn config_editor_opened(&mut self) {
self.editor_opening = None;
}
fn interrupt_config_editor_transition(&mut self) {
if let Some(handoff) = &self.editor_opening {
handoff.mark_activation_inactive();
}
}
fn handle_key_event(&mut self, key: KeyEvent) {
self.handle_key_event_with_activation_key(key, /*activation_key*/ None);
}
fn handle_key_event_with_activation_key(
&mut self,
key: KeyEvent,
activation_key: Option<crate::key_hint::KeyBinding>,
) {
let activation_key =
activation_key.unwrap_or_else(|| crate::key_hint::KeyBinding::from_event(key));
if key.kind == KeyEventKind::Release {
return;
}
if self.observe_pending_handoff_key(activation_key) {
return;
}
self.picker.handle_key_event(key);
if let Some(selected) = self.picker.take_last_selected_index() {
self.activate(selected, activation_key);
}
}
fn handle_key_release(&mut self, key: KeyEvent) {
let activation_key = crate::key_hint::KeyBinding::from_event(key);
if let Some(handoff) = &self.editor_opening
&& handoff.activation_key.is_same_physical_key(activation_key)
{
handoff.mark_activation_inactive();
}
}
fn observe_key_event_while_covered(
&mut self,
_key: KeyEvent,
activation_key: crate::key_hint::KeyBinding,
) {
self.observe_pending_handoff_key(activation_key);
}
fn handle_paste(&mut self, text: String) -> bool {
if let Some(handoff) = &self.editor_opening {
handoff.mark_activation_inactive();
false
} else {
self.picker.handle_paste(text)
}
}
fn prefer_esc_to_handle_key_event(&self) -> bool {
true
}
fn is_complete(&self) -> bool {
self.picker.is_complete()
}
fn on_ctrl_c(&mut self) -> CancellationEvent {
if let Some(handoff) = &self.editor_opening {
handoff.mark_activation_inactive();
CancellationEvent::Handled
} else {
self.picker.on_ctrl_c()
}
}
}

View File

@@ -0,0 +1,481 @@
//! Catalog of TUI configuration editors and directly editable preferences shown by `/config`.
//!
//! This module defines the stable grouping, copy, search terms, and displayed values. Rendering
//! and interaction live in later modules so they can consume one ordered catalog.
mod input;
mod render;
mod toggle;
pub(crate) use render::EFFECTS_VIEW_ID;
pub(crate) use render::copy_on_select;
pub(crate) use render::effects;
pub(crate) use render::effects_with_toggle_states;
pub(crate) use render::notification_condition;
pub(crate) use render::resume_directory;
pub(crate) use render::right_click_paste;
pub(crate) use render::session_picker_layout;
pub(crate) use toggle::ConfigPreference;
pub(crate) use toggle::ConfigToggle;
#[cfg(test)]
#[path = "config_panel_tests.rs"]
mod tests;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::ListSelectionView;
use crate::key_hint::KeyBinding;
use crate::keymap::ListKeymap;
use codex_config::types::CopyOnSelect;
use codex_config::types::NotificationCondition;
use codex_config::types::Notifications;
use codex_config::types::RightClickPaste;
use codex_config::types::Tui;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Instant;
const RIGHT_CLICK_PASTE_DESCRIPTION: &str = "Paste when nothing is selected, with Auto following platform defaults and On also enabling macOS";
pub(crate) struct ConfigPanelUpdate {
pub(crate) tui: Tui,
pub(crate) keymap: ListKeymap,
pub(crate) status: ConfigPanelStatus,
pub(crate) notice: Option<String>,
}
#[derive(Default)]
struct PickerState {
tab: Option<String>,
selected: Option<usize>,
query: Option<String>,
notice: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConfigEditor {
Theme,
Effects,
StatusLine,
TerminalTitle,
Keyboard,
ModelProviders,
SessionPickerLayout,
ResumeDirectory,
CopyOnSelect,
RightClickPaste,
NotificationCondition,
}
#[derive(Clone, Copy)]
pub(crate) enum ResumeCurrentAvailability {
Available,
RequiresCwdOverride,
}
/// Effective state the panel cannot derive from the `Tui` preferences alone.
#[derive(Clone, Copy)]
pub(crate) struct ConfigPanelStatus {
pub(crate) copy_on_select: bool,
pub(crate) right_click_paste: Result<bool, &'static str>,
pub(crate) custom_notification_filters: bool,
}
/// State shared by the panel that queued an editor and the event that will open it.
#[derive(Clone, Debug)]
pub(crate) struct ConfigEditorHandoff {
pub(crate) editor: ConfigEditor,
pub(crate) activation_key: KeyBinding,
activation: Arc<Mutex<ConfigEditorActivation>>,
}
#[derive(Debug)]
struct ConfigEditorActivation {
active: bool,
last_seen_at: Instant,
}
impl ConfigEditorHandoff {
pub(crate) fn new(editor: ConfigEditor, activation_key: KeyBinding) -> Self {
Self {
editor,
activation_key,
activation: Arc::new(Mutex::new(ConfigEditorActivation {
active: true,
last_seen_at: Instant::now(),
})),
}
}
pub(crate) fn mark_activation_seen(&self) {
self.mark_activation_seen_at(Instant::now());
}
fn mark_activation_seen_at(&self, seen_at: Instant) {
let mut activation = self
.activation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if activation.active {
activation.last_seen_at = activation.last_seen_at.max(seen_at);
}
}
pub(crate) fn mark_activation_inactive(&self) {
self.activation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.active = false;
}
pub(crate) fn active_at(&self) -> Option<Instant> {
let activation = self
.activation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
activation.active.then_some(activation.last_seen_at)
}
}
impl ConfigEditor {
fn value(self, tui: &Tui, status: ConfigPanelStatus) -> ConfigSettingValue {
let label = match self {
Self::ModelProviders => "Choose".to_string(),
Self::Theme => tui.theme.clone().unwrap_or_else(|| "Automatic".to_string()),
Self::SessionPickerLayout => match tui.session_picker_view.unwrap_or_default() {
codex_config::types::SessionPickerViewMode::Comfortable => "Comfortable",
codex_config::types::SessionPickerViewMode::Dense => "Dense",
}
.to_string(),
Self::ResumeDirectory => match tui.resume_cwd {
None => "Ask",
Some(codex_config::types::ResumeCwdMode::Current) => "Current directory",
Some(codex_config::types::ResumeCwdMode::Session) => "Session directory",
}
.to_string(),
Self::CopyOnSelect => match tui.copy_on_select {
CopyOnSelect::Auto => format!(
"Auto · {}",
if status.copy_on_select { "On" } else { "Off" }
),
CopyOnSelect::Always => "On".to_string(),
CopyOnSelect::Never => "Off".to_string(),
},
Self::RightClickPaste => {
let preference = match tui.right_click_paste {
RightClickPaste::Auto => "Auto",
RightClickPaste::On => "On",
RightClickPaste::Off => "Off",
};
match status.right_click_paste {
Ok(enabled) if tui.right_click_paste == RightClickPaste::Auto => {
format!("Auto · {}", if enabled { "On" } else { "Off" })
}
Ok(_) => preference.to_string(),
Err(_) => format!("{preference} · Unavailable"),
}
}
Self::NotificationCondition => match tui.notification_settings.condition {
NotificationCondition::Unfocused => "Unfocused",
NotificationCondition::Always => "Always",
}
.to_string(),
Self::Effects | Self::StatusLine | Self::TerminalTitle | Self::Keyboard => {
"Configure".to_string()
}
};
ConfigSettingValue::Editor {
label,
editor: self,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ConfigSection {
Appearance,
Notifications,
Input,
Sessions,
TextSelection,
}
impl ConfigSection {
const ALL: [Self; 5] = [
Self::Appearance,
Self::Notifications,
Self::Input,
Self::Sessions,
Self::TextSelection,
];
fn title(self) -> &'static str {
match self {
Self::Appearance => "Appearance",
Self::Notifications => "Notifications",
Self::Input => "Input",
Self::Sessions => "Sessions",
Self::TextSelection => "Text selection",
}
}
}
struct ConfigSetting {
section: ConfigSection,
label: &'static str,
description: &'static str,
keywords: &'static str,
value: ConfigSettingValue,
}
enum ConfigSettingValue {
Toggle {
setting: ConfigToggle,
enabled: bool,
},
Editor {
label: String,
editor: ConfigEditor,
},
DependentToggle {
setting: ConfigToggle,
enabled: bool,
dependency_met: bool,
unavailable_reason: &'static str,
},
NotificationTest,
Unavailable {
reason: &'static str,
},
}
impl ConfigSettingValue {
fn label(&self) -> String {
match self {
Self::Toggle { enabled, .. }
| Self::DependentToggle {
enabled,
dependency_met: true,
..
} => if *enabled { "[x] On" } else { "[ ] Off" }.to_string(),
Self::Editor { label, .. } => format!("{label} ›"),
Self::NotificationTest => "Send in 5s".to_string(),
Self::DependentToggle {
dependency_met: false,
..
}
| Self::Unavailable { .. } => "Unavailable".to_string(),
}
}
}
fn settings(tui: &Tui, status: ConfigPanelStatus) -> Vec<ConfigSetting> {
let notifications_enabled = !matches!(
tui.notification_settings.notifications,
Notifications::Enabled(false)
);
vec![
ConfigSetting {
section: ConfigSection::Appearance,
label: "Theme",
description: "Choose a syntax color palette with a live preview",
keywords: "colors dark light palette",
value: ConfigEditor::Theme.value(tui, status),
},
ConfigSetting {
section: ConfigSection::Appearance,
label: "Effects",
description: "Configure animations and composer effects",
keywords: "animations motion accessibility spinner starfield stars composer stars",
value: ConfigEditor::Effects.value(tui, status),
},
ConfigSetting {
section: ConfigSection::Appearance,
label: "Tips",
description: "Show helpful shortcuts and suggestions",
keywords: "welcome hints tooltips",
value: ConfigSettingValue::Toggle {
setting: ConfigToggle::Tips,
enabled: ConfigToggle::Tips.enabled(tui),
},
},
ConfigSetting {
section: ConfigSection::Appearance,
label: "Status line colors",
description: "Use theme colors for the model, branch, and other status line details",
keywords: "statusline footer colour",
value: ConfigSettingValue::Toggle {
setting: ConfigToggle::StatusLineColors,
enabled: ConfigToggle::StatusLineColors.enabled(tui),
},
},
ConfigSetting {
section: ConfigSection::Appearance,
label: "Status line display",
description: "Choose and reorder the information below the composer",
keywords: "statusline footer model branch context",
value: ConfigEditor::StatusLine.value(tui, status),
},
ConfigSetting {
section: ConfigSection::Appearance,
label: "Terminal title display",
description: "Choose and reorder the information in your terminal tab or window title",
keywords: "title tab window name",
value: ConfigEditor::TerminalTitle.value(tui, status),
},
ConfigSetting {
section: ConfigSection::Notifications,
label: "Notifications",
description: "Let your terminal notify you when a turn finishes or approval is needed",
keywords: "alerts bell completion approval",
value: if status.custom_notification_filters {
ConfigSettingValue::Unavailable {
reason: "Event-specific notifications are configured in config.toml",
}
} else {
ConfigSettingValue::Toggle {
setting: ConfigToggle::Notifications,
enabled: notifications_enabled,
}
},
},
ConfigSetting {
section: ConfigSection::Notifications,
label: "Notify when",
description: "Notify only while you are away or while this terminal is focused too",
keywords: "focus alerts background always unfocused",
value: if notifications_enabled {
ConfigEditor::NotificationCondition.value(tui, status)
} else {
ConfigSettingValue::Unavailable {
reason: "Turn on notifications to choose when they appear",
}
},
},
ConfigSetting {
section: ConfigSection::Notifications,
label: "Test notification",
description: "Send in 5 seconds so you can switch apps before the notification appears",
keywords: "alerts bell sound test",
value: ConfigSettingValue::NotificationTest,
},
ConfigSetting {
section: ConfigSection::Input,
label: "Keyboard shortcuts",
description: "Browse actions and remap their keys",
keywords: "keymap bindings hotkeys",
value: ConfigEditor::Keyboard.value(tui, status),
},
ConfigSetting {
section: ConfigSection::Input,
label: "Start in Vim mode",
description: "Start new composers in Vim mode and use /vim for the current composer",
keywords: "editor modal normal",
value: ConfigSettingValue::Toggle {
setting: ConfigToggle::StartInVimMode,
enabled: ConfigToggle::StartInVimMode.enabled(tui),
},
},
ConfigSetting {
section: ConfigSection::Input,
label: "Paste detection",
description: "Recognize pasted-text bursts and keep multiline input together",
keywords: "burst clipboard multiline",
value: ConfigSettingValue::Toggle {
setting: ConfigToggle::PasteDetection,
enabled: ConfigToggle::PasteDetection.enabled(tui),
},
},
ConfigSetting {
section: ConfigSection::Sessions,
label: "Automatic recaps",
description: "Prepare recaps while the terminal is unfocused",
keywords: "summary background",
value: ConfigSettingValue::Toggle {
setting: ConfigToggle::AutomaticRecaps,
enabled: ConfigToggle::AutomaticRecaps.enabled(tui),
},
},
ConfigSetting {
section: ConfigSection::Sessions,
label: "Session picker layout",
description: "Choose tighter rows or a roomier list when resuming and forking conversations",
keywords: "dense comfortable spacing resume fork",
value: ConfigEditor::SessionPickerLayout.value(tui, status),
},
ConfigSetting {
section: ConfigSection::Sessions,
label: "Resume directory",
description: "Choose which working directory to use when the current directory and saved session differ",
keywords: "cwd folder path fork ask",
value: ConfigEditor::ResumeDirectory.value(tui, status),
},
ConfigSetting {
section: ConfigSection::Sessions,
label: "Model providers",
description: "Choose the default provider for new chats on the connected server",
keywords: "provider gateway endpoint model default",
value: ConfigEditor::ModelProviders.value(tui, status),
},
ConfigSetting {
section: ConfigSection::TextSelection,
label: "Copy on select",
description: "Copy transcript, footer, and composer selections on release; Auto follows terminal defaults",
keywords: "clipboard mouse selection automatic drag",
value: ConfigEditor::CopyOnSelect.value(tui, status),
},
ConfigSetting {
section: ConfigSection::TextSelection,
label: "Deselect after copy",
description: "Remove read-only transcript and footer highlights after automatic copy succeeds",
keywords: "clipboard deselect clear highlight automatic mouse selection",
value: ConfigSettingValue::DependentToggle {
setting: ConfigToggle::CopyOnSelectClearSelection,
enabled: ConfigToggle::CopyOnSelectClearSelection.enabled(tui),
dependency_met: status.copy_on_select,
unavailable_reason: "Turn on Copy on select to deselect after copying",
},
},
ConfigSetting {
section: ConfigSection::TextSelection,
label: "Right-click paste",
description: status
.right_click_paste
.err()
.unwrap_or(RIGHT_CLICK_PASTE_DESCRIPTION),
keywords: "clipboard mouse paste automatic",
value: ConfigEditor::RightClickPaste.value(tui, status),
},
]
}
pub(crate) struct ConfigPanel {
settings: Vec<ConfigSetting>,
picker: ListSelectionView,
saving: bool,
editor_opening: Option<ConfigEditorHandoff>,
app_event_tx: AppEventSender,
}
impl ConfigPanel {
pub(crate) fn new(
tui: &Tui,
app_event_tx: AppEventSender,
keymap: ListKeymap,
status: ConfigPanelStatus,
) -> Self {
let settings = settings(tui, status);
let picker = render::picker(
&settings,
app_event_tx.clone(),
keymap,
PickerState::default(),
);
Self {
settings,
picker,
saving: false,
editor_opening: None,
app_event_tx,
}
}
}

View File

@@ -0,0 +1,520 @@
//! Render the configuration catalog and its child choice picker.
use super::ConfigPanel;
use super::ConfigPreference;
use super::ConfigSection;
use super::ConfigSetting;
use super::ConfigSettingValue;
use super::ConfigToggle;
use super::PickerState;
use super::ResumeCurrentAvailability;
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::ColumnWidthMode;
use crate::bottom_pane::ListSelectionView;
use crate::bottom_pane::PickerSurface;
use crate::bottom_pane::SELECTION_TOGGLE_UNAVAILABLE_PREFIX;
use crate::bottom_pane::SearchMode;
use crate::bottom_pane::SelectionDescriptionLayout;
use crate::bottom_pane::SelectionItem;
use crate::bottom_pane::SelectionRowDisplay;
use crate::bottom_pane::SelectionTab;
use crate::bottom_pane::SelectionToggle;
use crate::bottom_pane::SelectionToggleState;
use crate::bottom_pane::SelectionViewParams;
use crate::bottom_pane::footer_hint_items_line;
use crate::bottom_pane::popup_consts::picker_hint_line_for_keymap;
use crate::key_hint::KeyBinding;
use crate::keymap::ListAction;
use crate::keymap::ListKeymap;
use crate::render::renderable::Renderable;
use crate::wrapping::word_wrap_lines;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use unicode_width::UnicodeWidthStr;
pub(crate) const EFFECTS_VIEW_ID: &str = "config-effects";
pub(crate) fn effects(tui: &codex_config::types::Tui, keymap: &ListKeymap) -> SelectionViewParams {
effects_with_toggle_states(tui, keymap, &[])
}
pub(crate) fn effects_with_toggle_states(
tui: &codex_config::types::Tui,
keymap: &ListKeymap,
toggle_states: &[Option<SelectionToggleState>],
) -> SelectionViewParams {
let footer_hint = [(ListAction::Accept, "toggle"), (ListAction::Cancel, "back")]
.into_iter()
.filter_map(|(action, label)| {
keymap
.primary_hint(action)
.map(|hint| (hint.display_label(), label.into()))
})
.collect::<Vec<_>>();
let settings = [
(
"Animations",
"Animate the welcome screen, working indicator, and transitions",
ConfigToggle::Animations,
),
(
"Composer stars",
"Show stars briefly for new Astra tasks",
ConfigToggle::ComposerStars,
),
];
let animations_enabled = toggle_states
.first()
.copied()
.flatten()
.map(|state| state.is_on)
.unwrap_or(tui.animations);
SelectionViewParams {
view_id: Some(EFFECTS_VIEW_ID),
title: Some("Effects".to_string()),
subtitle: Some("Configure visual effects".to_string()),
footer_hint: Some(footer_hint_items_line(&footer_hint)),
allow_input_when_disconnected: true,
items: settings
.into_iter()
.enumerate()
.map(|(index, (label, description, setting))| {
let toggle_state = toggle_states.get(index).copied().flatten();
let enabled = toggle_state
.map(|state| state.is_on)
.unwrap_or_else(|| setting.enabled(tui));
let available = setting != ConfigToggle::ComposerStars || animations_enabled;
SelectionItem {
name: label.to_string(),
toggle: Some(SelectionToggle {
is_on: enabled,
action: Box::new(move |enabled, tx| {
tx.send(AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
setting,
enabled,
}));
}),
}),
pending_toggle_actions: toggle_state
.map(|state| state.pending_actions)
.unwrap_or_default(),
checkbox_toggle: available,
toggle_placeholder: (!available).then_some(SELECTION_TOGGLE_UNAVAILABLE_PREFIX),
description: available.then(|| description.to_string()),
disabled_reason: (!available)
.then(|| "Turn on Animations to show Astra task stars".to_string()),
dismiss_on_select: false,
..Default::default()
}
})
.collect(),
..SelectionViewParams::picker()
}
}
pub(crate) fn notification_condition(
tui: &codex_config::types::Tui,
keymap: &ListKeymap,
) -> SelectionViewParams {
use codex_config::types::NotificationCondition;
let current = tui.notification_settings.condition;
let conditions = [
("Unfocused", NotificationCondition::Unfocused),
("Always", NotificationCondition::Always),
];
SelectionViewParams {
title: Some("Notify when".to_string()),
subtitle: Some(
"Notify only while you are away or while this terminal is focused too".to_string(),
),
footer_hint: Some(picker_hint_line_for_keymap(keymap)),
initial_selected_idx: conditions
.iter()
.position(|(_, condition)| *condition == current),
allow_input_when_disconnected: true,
items: conditions
.into_iter()
.map(|(label, condition)| SelectionItem {
name: label.to_string(),
is_current: condition == current,
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::SaveConfigPreference(
ConfigPreference::NotificationCondition(condition),
));
})],
dismiss_on_select: true,
..Default::default()
})
.collect(),
..SelectionViewParams::picker()
}
}
pub(crate) fn copy_on_select(
tui: &codex_config::types::Tui,
keymap: &ListKeymap,
) -> SelectionViewParams {
use codex_config::types::CopyOnSelect;
let current = tui.copy_on_select;
let modes = [
("Auto (default)", CopyOnSelect::Auto),
("On", CopyOnSelect::Always),
("Off", CopyOnSelect::Never),
];
SelectionViewParams {
title: Some("Copy on select".to_string()),
subtitle: Some(
"Copy transcript, footer, and composer selections on release; Auto follows terminal defaults"
.to_string(),
),
footer_hint: Some(picker_hint_line_for_keymap(keymap)),
initial_selected_idx: modes.iter().position(|(_, mode)| *mode == current),
allow_input_when_disconnected: true,
items: modes
.into_iter()
.map(|(label, mode)| SelectionItem {
name: label.to_string(),
is_current: mode == current,
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::SaveConfigPreference(
ConfigPreference::CopyOnSelect(mode),
));
})],
dismiss_on_select: true,
..Default::default()
})
.collect(),
..SelectionViewParams::picker()
}
}
pub(crate) fn right_click_paste(
tui: &codex_config::types::Tui,
keymap: &ListKeymap,
) -> SelectionViewParams {
use codex_config::types::RightClickPaste;
let current = tui.right_click_paste;
let modes = [
("Auto (default)", RightClickPaste::Auto),
("On", RightClickPaste::On),
("Off", RightClickPaste::Off),
];
SelectionViewParams {
title: Some("Right-click paste".to_string()),
subtitle: Some(super::RIGHT_CLICK_PASTE_DESCRIPTION.to_string()),
footer_hint: Some(picker_hint_line_for_keymap(keymap)),
initial_selected_idx: modes.iter().position(|(_, mode)| *mode == current),
allow_input_when_disconnected: true,
items: modes
.into_iter()
.map(|(label, mode)| SelectionItem {
name: label.to_string(),
is_current: mode == current,
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::SaveConfigPreference(
ConfigPreference::RightClickPaste(mode),
));
})],
dismiss_on_select: true,
..Default::default()
})
.collect(),
..SelectionViewParams::picker()
}
}
pub(crate) fn session_picker_layout(
tui: &codex_config::types::Tui,
keymap: &ListKeymap,
) -> SelectionViewParams {
use codex_config::types::SessionPickerViewMode;
let current = tui.session_picker_view.unwrap_or_default();
let modes = [
("Dense", SessionPickerViewMode::Dense),
("Comfortable", SessionPickerViewMode::Comfortable),
];
SelectionViewParams {
title: Some("Session picker layout".to_string()),
subtitle: Some(
"Choose tighter rows or a roomier list when resuming and forking conversations"
.to_string(),
),
footer_hint: Some(picker_hint_line_for_keymap(keymap)),
initial_selected_idx: modes.iter().position(|(_, mode)| *mode == current),
allow_input_when_disconnected: true,
items: modes
.into_iter()
.map(|(label, mode)| SelectionItem {
name: label.to_string(),
is_current: mode == current,
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::SaveConfigPreference(
ConfigPreference::SessionPickerLayout(mode),
));
})],
dismiss_on_select: true,
..Default::default()
})
.collect(),
..SelectionViewParams::picker()
}
}
pub(crate) fn resume_directory(
tui: &codex_config::types::Tui,
keymap: &ListKeymap,
current_availability: ResumeCurrentAvailability,
) -> SelectionViewParams {
use codex_config::types::ResumeCwdMode;
let current = tui.resume_cwd;
let modes = [
("Ask", None),
("Current directory", Some(ResumeCwdMode::Current)),
("Session directory", Some(ResumeCwdMode::Session)),
];
SelectionViewParams {
title: Some("Resume directory".to_string()),
subtitle: Some(
"Choose the working directory when resuming, with --cd taking precedence for this session"
.to_string(),
),
footer_hint: Some(picker_hint_line_for_keymap(keymap)),
initial_selected_idx: modes.iter().position(|(_, mode)| *mode == current),
allow_input_when_disconnected: true,
items: modes
.into_iter()
.map(|(label, mode)| SelectionItem {
name: label.to_string(),
is_current: mode == current,
disabled_reason: if mode == Some(ResumeCwdMode::Current)
&& matches!(
current_availability,
ResumeCurrentAvailability::RequiresCwdOverride
)
{
Some("Requires --cd for remote sessions".to_string())
} else {
None
},
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::SaveConfigPreference(
ConfigPreference::ResumeDirectory(mode),
));
})],
dismiss_on_select: true,
..Default::default()
})
.collect(),
..SelectionViewParams::picker()
}
}
struct ConfigPanelHeader(Vec<Line<'static>>);
impl Renderable for ConfigPanelHeader {
fn render(&self, area: Rect, buf: &mut Buffer) {
Renderable::render(
&Paragraph::new(word_wrap_lines(&self.0, usize::from(area.width))),
area,
buf,
);
}
fn desired_height(&self, width: u16) -> u16 {
word_wrap_lines(&self.0, usize::from(width)).len() as u16
}
}
fn header(notice: Option<String>) -> Box<dyn Renderable> {
let subtitle = notice.unwrap_or_else(|| "Changes save automatically".to_string());
Box::new(ConfigPanelHeader(vec![
Line::from("Configuration".bold()),
Line::from(subtitle.dim()),
]))
}
fn hint(
keymap: &ListKeymap,
search: Option<KeyBinding>,
accept_label: Option<&str>,
) -> Line<'static> {
let key_label = |action| {
keymap.primary_hint(action).map(|hint| {
hint.display_label()
.replace('←', "left")
.replace('→', "right")
})
};
let mut items = Vec::new();
let keys = [ListAction::MoveLeft, ListAction::MoveRight]
.into_iter()
.filter_map(key_label)
.collect::<Vec<_>>()
.join("/");
if !keys.is_empty() {
items.push((keys, "group".into()));
}
if let Some(search) = search {
items.push((search.display_label(), "search".into()));
}
items.extend(
accept_label
.map(|label| (ListAction::Accept, label))
.into_iter()
.chain([(ListAction::Cancel, "clear search/close")])
.filter_map(|(action, label)| key_label(action).map(|key| (key, label.into()))),
);
footer_hint_items_line(&items)
}
#[derive(Clone, Copy)]
enum SettingItemContext {
Group,
Search,
}
fn setting_item(
setting: &ConfigSetting,
keymap: &ListKeymap,
search_hint: Option<KeyBinding>,
context: SettingItemContext,
) -> SelectionItem {
let (unavailable, accept_label) = match &setting.value {
ConfigSettingValue::DependentToggle {
dependency_met: false,
unavailable_reason,
..
} => (Some(*unavailable_reason), None),
ConfigSettingValue::Unavailable { reason } => (Some(*reason), None),
ConfigSettingValue::Toggle { .. } | ConfigSettingValue::DependentToggle { .. } => {
(None, Some("toggle"))
}
ConfigSettingValue::Editor { .. } => (None, Some("open")),
ConfigSettingValue::NotificationTest => (None, Some("test")),
};
let value_label = setting.value.label();
let description = unavailable.unwrap_or(setting.description);
let search_footer_hint = footer_hint_items_line(
&accept_label
.map(|label| ("enter".to_string(), label.to_string()))
.into_iter()
.chain([("esc".to_string(), "clear search".to_string())])
.collect::<Vec<_>>(),
);
let description = match context {
SettingItemContext::Group => description.to_string(),
SettingItemContext::Search => {
format!("{} · {description}", setting.section.title())
}
};
SelectionItem {
name: setting.label.to_string(),
category_tag: Some(format!("{value_label:<20}")),
description: Some(description),
is_disabled: unavailable.is_some(),
footer_hint: Some(hint(keymap, search_hint, accept_label)),
search_footer_hint: Some(search_footer_hint),
search_value: Some(format!(
"{} {} {} {} {}",
setting.section.title(),
setting.label,
value_label,
setting.keywords,
setting.description
)),
..Default::default()
}
}
pub(super) fn picker(
settings: &[ConfigSetting],
app_event_tx: AppEventSender,
keymap: ListKeymap,
state: PickerState,
) -> ListSelectionView {
let search = crate::key_hint::plain(KeyCode::Char('/'));
let (search_code, search_modifiers) = search.parts();
let search_event = KeyEvent::new(search_code, search_modifiers);
let search_hint = (keymap.action_for(search_event).is_none()
&& !keymap.has_chord_prefix(search_event))
.then_some(search);
let mut params = SelectionViewParams {
picker_surface: PickerSurface::Panel,
max_visible_rows: ConfigSection::ALL
.iter()
.map(|section| {
settings
.iter()
.filter(|setting| setting.section == *section)
.count()
})
.max()
.unwrap_or_default(),
reserve_result_rows: true,
row_display: SelectionRowDisplay::SingleLine,
col_width_mode: ColumnWidthMode::AutoAllRows,
description_layout: SelectionDescriptionLayout::SelectedBelowWhenNarrow {
min_description_width: 45,
},
footer_hint: Some(hint(&keymap, search_hint, /*accept_label*/ None)),
is_searchable: true,
search_mode: SearchMode::OnDemand(search),
search_placeholder: Some("Type to search settings".to_string()),
search_items: settings
.iter()
.map(|setting| setting_item(setting, &keymap, search_hint, SettingItemContext::Search))
.collect(),
name_column_width: settings
.iter()
.map(|setting| UnicodeWidthStr::width(setting.label))
.max(),
tabs: ConfigSection::ALL
.iter()
.map(|section| {
let title = section.title();
SelectionTab {
id: title.to_string(),
label: title.to_string(),
header: header(state.notice.clone()),
items: settings
.iter()
.filter(|setting| setting.section == *section)
.map(|setting| {
setting_item(setting, &keymap, search_hint, SettingItemContext::Group)
})
.collect(),
}
})
.collect(),
..Default::default()
};
params.initial_selected_idx = state.selected;
params.initial_search_query = state.query;
params.initial_tab_id = state.tab;
ListSelectionView::new(params, app_event_tx, keymap)
}
impl Renderable for ConfigPanel {
fn desired_height(&self, width: u16) -> u16 {
self.picker.desired_height(width)
}
fn render(&self, area: Rect, buf: &mut Buffer) {
self.picker.render(area, buf);
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
self.picker.cursor_pos(area)
}
}

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 140)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
› Theme Automatic › Choose a syntax color palette with a live preview
Effects Configure › Configure animations and composer effects
Tips [ ] Off Show helpful shortcuts and suggestions
Status line colors [ ] Off Use theme colors for the model, branch, and other status line details
Status line display Configure › Choose and reorder the information below the composer
Terminal title display Configure › Choose and reorder the information in your terminal tab or window title
left/right group · / search · enter open · esc clear search/close

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 140)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
› Keyboard shortcuts Configure › Browse actions and remap their keys
Start in Vim mode [ ] Off Start new composers in Vim mode and use /vim for the current composer
Paste detection [x] On Recognize pasted-text bursts and keep multiline input together
left/right group · / search · enter open · esc clear search/close

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 140)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
› Notifications [x] On Let your terminal notify you when a turn finishes or approval is needed
Notify when Unfocused › Notify only while you are away or while this terminal is focused too
Test notification Send in 5s Send in 5 seconds so you can switch apps before the notification appears
left/right group · / search · enter toggle · esc clear search/close

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 140)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
› Automatic recaps [ ] Off Prepare recaps while the terminal is unfocused
Session picker layout Dense › Choose tighter rows or a roomier list when resuming and forking conversations
Resume directory Ask › Choose which working directory to use when the current directory and saved session differ
Model providers Choose › Choose the default provider for new chats on the connected server
left/right group · / search · enter toggle · esc clear search/close

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 140)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
› Copy on select Auto · On › Copy transcript, footer, and composer selections on release; Auto follows terminal defaults
Deselect after copy [ ] Off Remove read-only transcript and footer highlights after automatic copy succeeds
Right-click paste Auto · Off › Paste when nothing is selected, with Auto following platform defaults and On also enabling mac…
left/right group · / search · enter open · esc clear search/close

View File

@@ -0,0 +1,14 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&picker, 100)"
---
Copy on select
Copy transcript, footer, and composer selections on release; Auto follows terminal defaults
› 1. Auto (default) (current)
2. On
3. Off
enter select · esc back

View File

@@ -0,0 +1,21 @@
---
source: tui/src/config_panel/config_panel_tests.rs
assertion_line: 206
expression: "render(&panel, 100)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
Search › notify when
› Notify when Unfocused › Notifications · Notify only while you are away or whil…
enter open · esc clear search

View File

@@ -0,0 +1,13 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&picker, 100)"
---
Notify when
Notify only while you are away or while this terminal is focused too
› 1. Unfocused (current)
2. Always
enter select · esc back

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 100)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
Notifications Unavailable Event-specific notifications are configured in config.…
› Notify when Unfocused › Notify only while you are away or while this terminal …
Test notification Send in 5s Send in 5 seconds so you can switch apps before the no…
left/right group · / search · enter open · esc clear search/close

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 100)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
Notifications [ ] Off Let your terminal notify you when a turn finishes or a…
Notify when Unavailable Turn on notifications to choose when they appear
› Test notification Send in 5s Send in 5 seconds so you can switch apps before the no…
left/right group · / search · enter test · esc clear search/close

View File

@@ -0,0 +1,23 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 50)"
---
Configuration
Failed to save status line settings:
permission denied while writing config.toml
Appearance Notifications Input ›
› Theme Automatic ›
Effects Configure ›
Tips [ ] Off
Status line colors [ ] Off
Status line display Configure ›
Terminal title display Configure ›
Choose a syntax color palette with a live
preview
left/right group · / search · enter open · esc
clear search/close

View File

@@ -0,0 +1,14 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&picker, 100)"
---
Resume directory
Choose the working directory when resuming, with --cd taking precedence for this session
› 1. Ask (current)
Current directory (disabled) Requires --cd for remote sessions
2. Session directory
enter select · esc back

View File

@@ -0,0 +1,14 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&picker, 100)"
---
Right-click paste
Paste when nothing is selected, with Auto following platform defaults and On also enabling macOS
› 1. Auto (default) (current)
2. On
3. Off
enter select · esc back

View File

@@ -0,0 +1,18 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&panel, 140)"
---
Configuration
Changes save automatically
Appearance Notifications Input Sessions Text selection
Copy on select Auto · On › Copy transcript, footer, and composer selections on release; Auto follows terminal defaults
Deselect after copy [ ] Off Remove read-only transcript and footer highlights after automatic copy succeeds
› Right-click paste On · Unavailable › Unavailable in inline mode; use your terminal's paste command
left/right group · / search · enter open · esc clear search/close

View File

@@ -0,0 +1,13 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&picker, 100)"
---
Session picker layout
Choose tighter rows or a roomier list when resuming and forking conversations
› 1. Dense (current)
2. Comfortable
enter select · esc back

View File

@@ -0,0 +1,24 @@
---
source: tui/src/config_panel/config_panel_tests.rs
assertion_line: 128
expression: "render(&panel, 50)"
---
Configuration
Changes save automatically
‹ Input Sessions Text selection
Search › deselect after copy
› Deselect after copy Unavailable
Text selection · Turn on Copy on select to
deselect after copying
esc clear search

View File

@@ -0,0 +1,14 @@
---
source: tui/src/config_panel/config_panel_tests.rs
expression: "render(&view, 80)"
---
Effects
Configure visual effects
› 1. [ ] Animations Animate the welcome screen, working
indicator, and transitions
[-] Composer stars (disabled) Turn on Animations to show Astra task stars
enter toggle · esc back

View File

@@ -0,0 +1,21 @@
---
source: tui/src/config_panel/config_panel_tests.rs
assertion_line: 477
expression: "render(&panel, 140)"
---
Configuration
Test sent · check terminal/system settings
Appearance Notifications Input Sessions Text selection
Search › tips
› Tips [x] On Appearance · Show helpful shortcuts and suggestions
enter toggle · esc clear search

View File

@@ -0,0 +1,155 @@
//! Maps config-panel preference changes to persisted and effective TUI values.
use crate::legacy_core::config::edit::ConfigEdit;
use crate::legacy_core::config::edit::session_picker_view_edit;
use codex_config::types::CopyOnSelect;
use codex_config::types::NotificationCondition;
use codex_config::types::Notifications;
use codex_config::types::ResumeCwdMode;
use codex_config::types::RightClickPaste;
use codex_config::types::SessionPickerViewMode;
use codex_config::types::Tui;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConfigToggle {
Animations,
AutomaticRecaps,
ComposerStars,
CopyOnSelectClearSelection,
Notifications,
PasteDetection,
StartInVimMode,
StatusLineColors,
Tips,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConfigPreference {
Toggle {
setting: ConfigToggle,
enabled: bool,
},
CopyOnSelect(CopyOnSelect),
NotificationCondition(NotificationCondition),
RightClickPaste(RightClickPaste),
SessionPickerLayout(SessionPickerViewMode),
ResumeDirectory(Option<ResumeCwdMode>),
}
impl ConfigPreference {
pub(crate) fn edit(self) -> ConfigEdit {
match self {
Self::Toggle { setting, enabled } => setting.edit(enabled),
Self::CopyOnSelect(mode) => ConfigEdit::SetPath {
segments: vec!["tui".to_string(), "copy_on_select".to_string()],
value: toml_edit::value(match mode {
CopyOnSelect::Auto => "auto",
CopyOnSelect::Always => "always",
CopyOnSelect::Never => "never",
}),
},
Self::NotificationCondition(condition) => ConfigEdit::SetPath {
segments: vec!["tui".to_string(), "notification_condition".to_string()],
value: toml_edit::value(condition.to_string()),
},
Self::RightClickPaste(mode) => ConfigEdit::SetPath {
segments: vec!["tui".to_string(), "right_click_paste".to_string()],
value: toml_edit::value(match mode {
RightClickPaste::Auto => "auto",
RightClickPaste::On => "on",
RightClickPaste::Off => "off",
}),
},
Self::SessionPickerLayout(mode) => session_picker_view_edit(mode),
Self::ResumeDirectory(None) => ConfigEdit::ClearPath {
segments: vec!["tui".to_string(), "resume_cwd".to_string()],
},
Self::ResumeDirectory(Some(mode)) => ConfigEdit::SetPath {
segments: vec!["tui".to_string(), "resume_cwd".to_string()],
value: toml_edit::value(mode.as_str()),
},
}
}
/// Copies only this preference, leaving unrelated settings unchanged.
pub(crate) fn adopt(self, target: &mut Tui, source: &Tui) {
match self {
Self::Toggle { setting, .. } => setting.adopt(target, source),
Self::CopyOnSelect(_) => target.copy_on_select = source.copy_on_select,
Self::NotificationCondition(_) => {
target.notification_settings.condition = source.notification_settings.condition;
}
Self::RightClickPaste(_) => target.right_click_paste = source.right_click_paste,
Self::SessionPickerLayout(_) => {
target.session_picker_view = source.session_picker_view;
}
Self::ResumeDirectory(_) => target.resume_cwd = source.resume_cwd,
}
}
}
impl ConfigToggle {
pub(crate) fn edit(self, enabled: bool) -> ConfigEdit {
let (key, value) = match self {
Self::ComposerStars => {
return ConfigEdit::SetPath {
segments: vec!["tui".into(), "effects".into(), "starfield".into()],
value: toml_edit::value(enabled),
};
}
Self::Notifications => {
return ConfigEdit::SetTuiNotificationsEnabled { enabled };
}
Self::Animations => ("animations", enabled),
Self::AutomaticRecaps => ("auto_recap", enabled),
Self::CopyOnSelectClearSelection => ("copy_on_select_clear_selection", enabled),
Self::PasteDetection => ("disable_paste_burst", !enabled),
Self::StartInVimMode => ("vim_mode_default", enabled),
Self::StatusLineColors => ("status_line_use_colors", enabled),
Self::Tips => ("show_tooltips", enabled),
};
ConfigEdit::SetPath {
segments: vec!["tui".into(), key.into()],
value: toml_edit::value(value),
}
}
pub(crate) fn enabled(self, tui: &Tui) -> bool {
match self {
Self::Animations => tui.animations,
Self::AutomaticRecaps => tui.auto_recap,
Self::ComposerStars => tui.effects.starfield,
Self::CopyOnSelectClearSelection => tui.copy_on_select_clear_selection,
Self::Notifications => !matches!(
tui.notification_settings.notifications,
Notifications::Enabled(false)
),
Self::PasteDetection => !tui.disable_paste_burst.unwrap_or(/*default*/ false),
Self::StartInVimMode => tui.vim_mode_default,
Self::StatusLineColors => tui.status_line_use_colors,
Self::Tips => tui.show_tooltips,
}
}
/// Copies only this preference, leaving unrelated settings unchanged.
pub(crate) fn adopt(self, target: &mut Tui, source: &Tui) {
match self {
Self::Animations => target.animations = source.animations,
Self::AutomaticRecaps => target.auto_recap = source.auto_recap,
Self::ComposerStars => target.effects.starfield = source.effects.starfield,
Self::CopyOnSelectClearSelection => {
target.copy_on_select_clear_selection = source.copy_on_select_clear_selection;
}
Self::Notifications => {
target.notification_settings.notifications =
source.notification_settings.notifications.clone();
}
Self::PasteDetection => target.disable_paste_burst = source.disable_paste_burst,
Self::StartInVimMode => target.vim_mode_default = source.vim_mode_default,
Self::StatusLineColors => {
target.status_line_use_colors = source.status_line_use_colors;
}
Self::Tips => target.show_tooltips = source.show_tooltips,
}
}
}