From b294004ea90d50d6594bfa3d852064c7fd904eda Mon Sep 17 00:00:00 2001 From: pap Date: Mon, 28 Jul 2025 23:06:30 +0100 Subject: [PATCH 01/18] adding /model --- codex-rs/Cargo.lock | 8 + codex-rs/core/src/codex.rs | 24 +- codex-rs/core/src/config.rs | 27 ++ codex-rs/core/src/lib.rs | 2 +- codex-rs/core/src/openai_model_info.rs | 44 ++ codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/app.rs | 103 +++++ codex-rs/tui/src/app_event.rs | 7 + .../tui/src/bottom_pane/bottom_pane_view.rs | 6 + codex-rs/tui/src/bottom_pane/chat_composer.rs | 22 +- codex-rs/tui/src/bottom_pane/mod.rs | 11 + .../src/bottom_pane/model_selection_view.rs | 426 ++++++++++++++++++ codex-rs/tui/src/chatwidget.rs | 55 +++ codex-rs/tui/src/slash_command.rs | 2 + 14 files changed, 720 insertions(+), 18 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/model_selection_view.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 653c3e4ef2..f32b19200c 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -861,6 +861,7 @@ dependencies = [ "strum 0.27.2", "strum_macros 0.27.2", "tokio", + "toml 0.8.23", "tracing", "tracing-appender", "tracing-subscriber", @@ -4760,6 +4761,7 @@ dependencies = [ "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", + "toml_write", "winnow", ] @@ -4772,6 +4774,12 @@ dependencies = [ "winnow", ] +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "toml_writer" version = "1.0.2" diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 3ab3e8d780..f61d45f5ec 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -111,20 +111,7 @@ impl Codex { let user_instructions = get_user_instructions(&config).await; - let configure_session = Op::ConfigureSession { - provider: config.model_provider.clone(), - model: config.model.clone(), - model_reasoning_effort: config.model_reasoning_effort, - model_reasoning_summary: config.model_reasoning_summary, - user_instructions, - base_instructions: config.base_instructions.clone(), - approval_policy: config.approval_policy, - sandbox_policy: config.sandbox_policy.clone(), - disable_response_storage: config.disable_response_storage, - notify: config.notify.clone(), - cwd: config.cwd.clone(), - resume_path: resume_path.clone(), - }; + let configure_session = config.to_configure_session_op(Some(config.model.clone()), user_instructions); let config = Arc::new(config); @@ -633,8 +620,15 @@ async fn submission_loop( } }; + // Create a session-specific Config that only overrides the model. + let client_config = { + let mut c = (*config).clone(); + c.model = model.clone(); + Arc::new(c) + }; + let client = ModelClient::new( - config.clone(), + client_config, provider.clone(), model_reasoning_effort, model_reasoning_summary, diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index 2dfd3e55fe..9fd253c79c 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -15,6 +15,7 @@ use crate::model_provider_info::built_in_model_providers; use crate::openai_model_info::get_model_info; use crate::protocol::AskForApproval; use crate::protocol::SandboxPolicy; +use crate::protocol::Op; use dirs::home_dir; use serde::Deserialize; use std::collections::HashMap; @@ -179,6 +180,32 @@ impl Config { // Step 4: merge with the strongly-typed overrides. Self::load_from_base_config_with_overrides(cfg, overrides, codex_home) } + + /// Construct an Op::ConfigureSession from this Config. + /// + /// - `override_model`: when Some, use this model instead of `self.model`. + /// - `user_instructions`: pass-through instructions to embed in the session. + pub fn to_configure_session_op( + &self, + override_model: Option, + user_instructions: Option, + ) -> Op { + let model = override_model.unwrap_or_else(|| self.model.clone()); + Op::ConfigureSession { + provider: self.model_provider.clone(), + model, + model_reasoning_effort: self.model_reasoning_effort, + model_reasoning_summary: self.model_reasoning_summary, + user_instructions, + base_instructions: self.base_instructions.clone(), + approval_policy: self.approval_policy, + sandbox_policy: self.sandbox_policy.clone(), + disable_response_storage: self.disable_response_storage, + notify: self.notify.clone(), + cwd: self.cwd.clone(), + resume_path: self.experimental_resume.clone(), + } + } } /// Read `CODEX_HOME/config.toml` and return it as a generic TOML value. Returns diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 6cb6aaa629..7b7c12754a 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -32,7 +32,7 @@ pub use model_provider_info::ModelProviderInfo; pub use model_provider_info::WireApi; mod models; pub mod openai_api_key; -mod openai_model_info; +pub mod openai_model_info; mod openai_tools; mod project_doc; pub mod protocol; diff --git a/codex-rs/core/src/openai_model_info.rs b/codex-rs/core/src/openai_model_info.rs index 9ffd831a91..1dcd7c19b5 100644 --- a/codex-rs/core/src/openai_model_info.rs +++ b/codex-rs/core/src/openai_model_info.rs @@ -69,3 +69,47 @@ pub(crate) fn get_model_info(name: &str) -> Option { _ => None, } } + +/// Return a curated list of commonly-used OpenAI model names for selection UIs. +pub fn get_all_model_names() -> Vec<&'static str> { + vec![ + // codex models + "codex-mini-latest", + // reasoning models + "o3", + "o4-mini", + // GPT-4.1 family + "gpt-4.1", + // GPT-4o family (canonical plus a few snapshots) + "gpt-4o", + ] +} + +/// Sort order by preference groups, then alphabetically. +pub fn preference_rank(name: &str) -> u8 { + // Lower is more preferred. + if name == "codex-mini-latest" { + return 0; + } + if name.starts_with("o4-mini") { + return 1; + } + if name == "o3" || name.starts_with("o3") { + return 2; + } + if name == "gpt-4.1" || name.starts_with("gpt-4.1") { + return 3; + } + // Handle both spellings just in case. + if name == "gpt4-o" || name.starts_with("gpt-4o") { + return 4; + } + 5 +} + +/// Compare two model names by preference ranking. +pub fn compare_models_by_preference(a: &str, b: &str) -> std::cmp::Ordering { + preference_rank(a) + .cmp(&preference_rank(b)) + .then_with(|| a.cmp(b)) +} diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 2f150921fb..ade84087ac 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -61,6 +61,7 @@ tui-textarea = "0.7.0" unicode-segmentation = "1.12.0" unicode-width = "0.1" uuid = "1" +toml = "0.8" [dev-dependencies] insta = "1.43.1" diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index e7097e6af0..9c7d3d9d9c 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -43,6 +43,32 @@ enum AppState<'a> { GitWarning { screen: GitWarningScreen }, } +/// Strip a single pair of surrounding quotes from the provided string if present. +/// Supports straight and common curly quotes: '…', "…", ‘…’, “…”. +fn strip_surrounding_quotes(s: &str) -> String { + let trimmed = s.trim(); + if trimmed.len() < 2 { + return trimmed.to_string(); + } + + let mut chars = trimmed.chars(); + let first = chars.next().unwrap(); + let last = trimmed.chars().last().unwrap(); + + let is_valid_quote = match first { + '"' | '\'' | '“' | '‘' => first == last, + _ => false, + }; + + if is_valid_quote { + let start = first.len_utf8(); + let end = trimmed.len() - last.len_utf8(); + trimmed[start..end].to_string() + } else { + trimmed.to_string() + } +} + pub(crate) struct App<'a> { app_event_tx: AppEventSender, app_event_rx: Receiver, @@ -286,6 +312,11 @@ impl App<'_> { AppEvent::ExitRequest => { break; } + AppEvent::SelectModel(model) => { + if let AppState::Chat { widget } = &mut self.app_state { + widget.update_model_and_reconfigure(model); + } + } AppEvent::CodexOp(op) => match &mut self.app_state { AppState::Chat { widget } => widget.submit_op(op), AppState::Login { .. } | AppState::GitWarning { .. } => {} @@ -329,6 +360,36 @@ impl App<'_> { widget.add_diff_output(text); } } + SlashCommand::Model => { + // No explicit args were provided; open the selector. + if let AppState::Chat { widget } = &mut self.app_state { + widget.show_model_selector(); + } + // Models are populated from a curated list; no network fetch. + }, + }, + AppEvent::DispatchCommandWithArgs(command, args) => match command { + SlashCommand::Model => { + let arg = args.trim(); + if arg.is_empty() { + // Same as `/model` without args. + if let AppState::Chat { widget } = &mut self.app_state { + widget.show_model_selector(); + } + // Models are populated from a curated list; no network fetch. + } else if let AppState::Chat { widget } = &mut self.app_state { + // Normalize commonly quoted inputs like \"o3\" or 'o3' or “o3”. + let normalized = strip_surrounding_quotes(arg).trim().to_string(); + if !normalized.is_empty() { + widget.update_model_and_reconfigure(normalized); + } + } + } + SlashCommand::New | SlashCommand::Quit | SlashCommand::Diff => { + // For other commands, fall back to existing handling. + // We can ignore args for now. + self.app_event_tx.send(AppEvent::DispatchCommand(command)); + } }, AppEvent::StartFileSearch(query) => { self.file_search.on_user_query(query); @@ -427,3 +488,45 @@ impl App<'_> { } } } + + +#[cfg(test)] +mod tests { + use super::strip_surrounding_quotes; + + #[test] + fn strip_surrounding_quotes_cases() { + let cases = vec![ + ("o3", "o3"), + ("\"codex-mini-latest\"", "codex-mini-latest"), + ("another_model", "another_model"), + ]; + for (input, expected) in cases { + assert_eq!(strip_surrounding_quotes(input), expected.to_string()); + } + } + + #[test] + fn model_command_args_extraction_and_normalization() { + let cases = vec![ + ("/model", "", ""), + ("/model o3", "o3", "o3"), + ("/model another_model", "another_model", "another_model"), + ]; + for (line, raw_expected, norm_expected) in cases { + // Extract raw args as in chat_composer + let raw = if let Some(stripped) = line.strip_prefix('/') { + let token = stripped.trim_start(); + let cmd_token = token.split_whitespace().next().unwrap_or(""); + let rest = &token[cmd_token.len()..]; + rest.trim_start().to_string() + } else { + String::new() + }; + assert_eq!(raw, raw_expected, "raw args for '{}'", line); + // Normalize as in app dispatch logic + let normalized = strip_surrounding_quotes(&raw).trim().to_string(); + assert_eq!(normalized, norm_expected, "normalized args for '{}'", line); + } + } +} \ No newline at end of file diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index a1f304fe42..75a15b0646 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -38,6 +38,10 @@ pub(crate) enum AppEvent { /// layer so it can be handled centrally. DispatchCommand(SlashCommand), + /// Dispatch a recognized slash command along with the raw argument string + /// following the command on the first line. + DispatchCommandWithArgs(SlashCommand, String), + /// Kick off an asynchronous file search for the given query (text after /// the `@`). Previous searches may be cancelled by the app layer so there /// is at most one in-flight search. @@ -52,4 +56,7 @@ pub(crate) enum AppEvent { }, InsertHistory(Vec>), + + /// User selected a model from the model-selection dropdown. + SelectModel(String), } diff --git a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs index 677d6db95b..f3e704141b 100644 --- a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs +++ b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs @@ -43,4 +43,10 @@ pub(crate) trait BottomPaneView<'a> { ) -> Option { Some(request) } + + /// Optional hook: if this view is a model selector, update the options. + /// Returns true if options were applied and a redraw is desired. + fn set_model_options(&mut self, _current_model: &str, _options: Vec) -> bool { + false + } } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 6a1bb526ce..1583577979 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -225,8 +225,26 @@ impl ChatComposer<'_> { ctrl: false, } => { if let Some(cmd) = popup.selected_command() { - // Send command to the app layer. - self.app_event_tx.send(AppEvent::DispatchCommand(*cmd)); + // Extract arguments after the command from the first line. + let first_line = self + .textarea + .lines() + .first() + .map(|s| s.as_str()) + .unwrap_or(""); + + let args = if let Some(stripped) = first_line.strip_prefix('/') { + let token = stripped.trim_start(); + let cmd_token = token.split_whitespace().next().unwrap_or(""); + let rest = &token[cmd_token.len()..]; + rest.trim_start().to_string() + } else { + String::new() + }; + + // Send command + args to the app layer. + self.app_event_tx + .send(AppEvent::DispatchCommandWithArgs(*cmd, args)); // Clear textarea so no residual text remains. self.textarea.select_all(); diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 0ddb36f635..b9e950d888 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -19,12 +19,14 @@ mod chat_composer_history; mod command_popup; mod file_search_popup; mod status_indicator_view; +mod model_selection_view; pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::InputResult; use approval_modal_view::ApprovalModalView; use status_indicator_view::StatusIndicatorView; +use model_selection_view::ModelSelectionView; /// Pane displayed in the lower half of the chat UI. pub(crate) struct BottomPane<'a> { @@ -58,6 +60,15 @@ impl BottomPane<'_> { } } + /// Show the model-selection dropdown view. + pub(crate) fn show_model_selector(&mut self, current_model: &str, options: Vec) { + let mut view = ModelSelectionView::new(current_model, self.app_event_tx.clone()); + // Apply options so the view starts populated and not in a loading state. + let _ = view.set_model_options(current_model, options); + self.active_view = Some(Box::new(view)); + self.request_redraw(); + } + /// Forward a key event to the active view or the composer. pub fn handle_key_event(&mut self, key_event: KeyEvent) -> InputResult { if let Some(mut view) = self.active_view.take() { diff --git a/codex-rs/tui/src/bottom_pane/model_selection_view.rs b/codex-rs/tui/src/bottom_pane/model_selection_view.rs new file mode 100644 index 0000000000..15714c2b45 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/model_selection_view.rs @@ -0,0 +1,426 @@ +use crossterm::event::KeyCode; +use crossterm::event::KeyEvent; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::Color; +use ratatui::style::Modifier; +use ratatui::style::Style; +use ratatui::text::Line; +use ratatui::text::Span; +use ratatui::widgets::Block; +use ratatui::widgets::BorderType; +use ratatui::widgets::Borders; +use ratatui::widgets::Cell; +use ratatui::widgets::Row; +use ratatui::widgets::Table; +use ratatui::widgets::Widget; +use ratatui::widgets::Clear; + +use crate::app_event::AppEvent; +use crate::app_event_sender::AppEventSender; + +use super::BottomPane; +use super::BottomPaneView; +use codex_core::openai_model_info::compare_models_by_preference; + +/// Simple dropdown to select a model. +pub(crate) struct ModelSelectionView { + /// Full list of models from provider (deduplicated). + options: Vec, + /// Current model pinned at the top of the list. + current_model: String, + /// Current zero-based selection index among rendered rows. + selected_idx: usize, + /// Query used to filter models via fuzzy match. + query: String, + is_complete: bool, + app_event_tx: AppEventSender, +} + +impl ModelSelectionView { + pub fn new(current_model: &str, app_event_tx: AppEventSender) -> Self { + // Initially no options; will be populated asynchronously. + Self { + options: Vec::new(), + current_model: current_model.to_string(), + selected_idx: 0, + query: String::new(), + is_complete: false, + app_event_tx, + } + } + + /// Produce the sequence of display rows respecting pinned current model, + /// sort preference, and search filter. + fn build_display_rows(&self) -> Vec { + // Determine candidate list excluding the current model (it is always pinned first). + let mut others: Vec<&str> = self + .options + .iter() + .map(|s| s.as_str()) + .filter(|m| *m != self.current_model) + .collect(); + + // If not searching, apply preference sort; otherwise, we'll score by fuzzy match. + if self.query.is_empty() { + others.sort_by(|a, b| compare_models_by_preference(a, b)); + let mut rows: Vec = Vec::new(); + // Pinned current model always first. + rows.push(DisplayRow::Model { + name: self.current_model.clone(), + match_indices: None, + is_current: true, + }); + if !others.is_empty() { + for name in others { + rows.push(DisplayRow::Model { + name: name.to_string(), + match_indices: None, + is_current: false, + }); + } + } + return rows; + } + + // Searching: include pinned current model first (even if it doesn't match), + // then fuzzy-matched models sorted by score. + let mut rows: Vec = Vec::new(); + rows.push(DisplayRow::Model { + name: self.current_model.clone(), + match_indices: fuzzy_indices(&self.current_model, &self.query), + is_current: true, + }); + + // Build list of matches among others. + let mut matches: Vec<(String, Vec, i32)> = Vec::new(); + for name in others { + if let Some((indices, score)) = fuzzy_match(name, &self.query) { + matches.push((name.to_string(), indices, score)); + } + } + // Sort by score (ascending => better). If equal, fall back to preference then alphabetical. + matches.sort_by(|(a_name, a_idx, a_score), (b_name, b_idx, b_score)| { + a_score + .cmp(b_score) + .then_with(|| compare_models_by_preference(a_name, b_name)) + .then_with(|| a_name.cmp(b_name)) + .then_with(|| a_idx.len().cmp(&b_idx.len())) + }); + + for (name, indices, _score) in matches { + rows.push(DisplayRow::Model { + name, + match_indices: Some(indices), + is_current: false, + }); + } + + rows + } + + /// Count how many rows will be rendered (excluding the bottom stats line). + fn row_count(&self) -> usize { + let mut count = 0usize; + if self.query.is_empty() { + // current model + others + count += 1; // current + // Others count (excluding current) + let others = self + .options + .iter() + .filter(|m| m.as_str() != self.current_model) + .count(); + count + others + } else { + // searching: pinned current + matches + let mut matches = 1; // current always present + for name in self.options.iter().filter(|m| m.as_str() != self.current_model) { + if fuzzy_match(name, &self.query).is_some() { + matches += 1; + } + } + matches + } + } + + /// Map selected_idx to a selected model name, if any. + fn selected_model(&self) -> Option { + if self.row_count() == 0 { + return None; + } + let rows = self.build_display_rows(); + match rows.get(self.selected_idx) { + Some(DisplayRow::Model { name, .. }) => Some(name.clone()), + _ => None, // no other placeholder rows are not selectable + } + } + + /// Compute the 1-based index of the selected model among all visible models (after filter). + fn selected_model_position(&self) -> Option { + let rows = self.build_display_rows(); + if self.selected_idx >= rows.len() { + return None; + } + let mut pos = 0usize; + for (i, row) in rows.iter().enumerate() { + if matches!(row, DisplayRow::Model { .. }) { + pos += 1; + } + if i == self.selected_idx { + return Some(pos); + } + } + None + } + +} + +/// Row that can be rendered in the selector. +enum DisplayRow { + Model { + name: String, + match_indices: Option>, // indices to bold (char positions) + is_current: bool, + }, +} + + +/// Return indices for a simple case-insensitive subsequence match and a score. +/// Smaller score is better. +fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec, i32)> { + if needle.is_empty() { + return Some((Vec::new(), i32::MAX)); + } + let h_lower = haystack.to_lowercase(); + let n_lower = needle.to_lowercase(); + let mut indices: Vec = Vec::with_capacity(n_lower.len()); + let mut h_iter = h_lower.char_indices(); + let mut last_pos: Option = None; + + for ch in n_lower.chars() { + let mut found = None; + while let Some((i, hc)) = h_iter.next() { + if hc == ch { + found = Some(i); + break; + } + } + if let Some(pos) = found { + indices.push(pos); + last_pos = Some(pos); + } else { + return None; + } + } + + // Score: window length minus needle length (tighter is better), with a bonus for prefix match. + let first = *indices.first().unwrap_or(&0); + let last = last_pos.unwrap_or(first); + let window = (last as i32 - first as i32 + 1) - (n_lower.len() as i32); + let mut score = window.max(0); + if first == 0 { + score -= 100; // strong bonus for prefix match + } + Some((indices, score)) +} + +fn fuzzy_indices(haystack: &str, needle: &str) -> Option> { + fuzzy_match(haystack, needle).map(|(idx, _)| idx) +} + +impl<'a> BottomPaneView<'a> for ModelSelectionView { + fn handle_key_event(&mut self, _pane: &mut BottomPane<'a>, key_event: KeyEvent) { + match key_event.code { + KeyCode::Up => { + if self.selected_idx > 0 { + self.selected_idx -= 1; + } + } + KeyCode::Down => { + let max_idx = self.row_count().saturating_sub(1); + if self.selected_idx < max_idx { + self.selected_idx += 1; + } + } + KeyCode::Home => { + self.selected_idx = 0; + } + KeyCode::End => { + self.selected_idx = self.row_count().saturating_sub(1); + } + KeyCode::Enter => { + if let Some(model) = self.selected_model() { + self.app_event_tx.send(AppEvent::SelectModel(model)); + self.is_complete = true; + } + } + KeyCode::Esc => { + if self.query.is_empty() { + self.is_complete = true; + } else { + self.query.clear(); + self.selected_idx = 0; // reset on clear + } + } + KeyCode::Backspace => { + self.query.pop(); + // After editing, snap to first match if searching; otherwise clamp. + if self.query.is_empty() { + self.selected_idx = self.selected_idx.min(self.row_count().saturating_sub(1)); + } else { + self.selected_idx = if self.row_count() > 1 { 1 } else { 0 }; + } + } + KeyCode::Char(c) => { + // Append printable characters to the query. + if !c.is_control() { + self.query.push(c); + // When typing, move selection to first match (index 1 because 0 is pinned current). + self.selected_idx = if self.row_count() > 1 { 1 } else { 0 }; + } + } + _ => {} + } + } + + fn is_complete(&self) -> bool { + self.is_complete + } + + fn render(&self, area: Rect, buf: &mut Buffer) { + // Clear the area to prevent ghosting when the list height/width changes between frames. + Clear.render(area, buf); + + // Compute rows and counts. + let rows_all = self.build_display_rows(); + let total_rows = rows_all.len(); + let total_models = rows_all + .iter() + .filter(|r| matches!(r, DisplayRow::Model { .. })) + .count(); + let selected_model_pos = self.selected_model_position(); + + // Determine content height and rows available for the list (leave one row for stats). + let content_height = area.height.saturating_sub(2) as usize; // minus borders + let stats_rows = 1usize; // persistent status line at bottom + let list_window = content_height.saturating_sub(stats_rows); + + // Mutable self required to adjust scroll_offset; work with a local mutable copy via interior mutability + // is not necessary; instead compute desired offset and then render using that offset only. + let mut scroll_offset = 0usize; + if list_window > 0 { + // Ensure selected row is visible within [scroll_offset, scroll_offset + list_window) + if self.selected_idx < scroll_offset { + scroll_offset = self.selected_idx; + } else if self.selected_idx >= scroll_offset + list_window { + scroll_offset = self.selected_idx + 1 - list_window; + } + // Clamp to range. + if total_rows > list_window { + let max_offset = total_rows - list_window; + if scroll_offset > max_offset { + scroll_offset = max_offset; + } + } else { + scroll_offset = 0; + } + } else { + scroll_offset = 0; // no space for list; still show stats + } + + // Prepare visible rows slice for list portion. + let mut visible_rows: Vec = Vec::new(); + if list_window > 0 { + let end = (scroll_offset + list_window).min(total_rows); + for (abs_idx, row) in rows_all.iter().enumerate().take(end).skip(scroll_offset) { + match row { + DisplayRow::Model { + name, + match_indices, + is_current, + } => { + // Build spans for optional fuzzy highlight. + let mut spans: Vec = Vec::with_capacity(name.len()); + if let Some(idxs) = match_indices { + let mut idx_iter = idxs.iter().peekable(); + for (char_idx, ch) in name.chars().enumerate() { + let mut style = Style::default(); + if idx_iter.peek().is_some_and(|next| **next == char_idx) { + idx_iter.next(); + style = style.add_modifier(Modifier::BOLD); + } + spans.push(Span::styled(ch.to_string(), style)); + } + } else { + spans.push(Span::raw(name.clone())); + } + + let mut cell = Cell::from(Line::from(spans)); + // Selected row style takes precedence. + if abs_idx == self.selected_idx { + cell = cell + .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)); + } else if *is_current { + // Special color for the current model when not selected. + cell = cell.style(Style::default().fg(Color::Cyan)); + } + visible_rows.push(Row::new(vec![cell])); + } + } + } + + // Fill with blank rows if we have fewer rows than window size, so the stats line stays at bottom. + while visible_rows.len() < list_window { + visible_rows.push(Row::new(vec![Cell::from(" ")])); + } + } + + // Stats line text: selected position / total models. + let stats_text = match selected_model_pos { + Some(pos) => format!(" {pos}/{total_models} models "), + None => format!(" -/{total_models} models "), + }; + let mut stats_row = Row::new(vec![Cell::from(stats_text)]); + stats_row = stats_row.style(Style::default().fg(Color::DarkGray)); + visible_rows.push(stats_row); + + let mut title = String::from(" Select model "); + if !self.query.is_empty() { + title.push(' '); + title.push('('); + title.push_str(&self.query); + title.push(')'); + } + + let table = Table::new(visible_rows, vec![ratatui::prelude::Constraint::Percentage(100)]) + .block( + Block::default() + .title(title) + .borders(Borders::ALL) + .border_type(BorderType::Rounded), + ) + .widths([ratatui::prelude::Constraint::Percentage(100)]); + + table.render(area, buf); + } + + fn set_model_options(&mut self, current_model: &str, options: Vec) -> bool { + self.current_model = current_model.to_string(); + // Deduplicate while preserving first occurrence order. + let mut seen = std::collections::HashSet::new(); + let mut unique: Vec = Vec::with_capacity(options.len()); + for m in options.into_iter() { + if seen.insert(m.clone()) { + unique.push(m); + } + } + // Sort by preference for stable display when query is empty. + unique.sort_by(|a, b| compare_models_by_preference(a, b)); + self.options = unique; + + // Clamp selection to available rows. + self.selected_idx = self.selected_idx.min(self.row_count().saturating_sub(1)); + true + } +} diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 5e839d1419..eaad5c5036 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use codex_core::codex_wrapper::CodexConversation; use codex_core::codex_wrapper::init_codex; use codex_core::config::Config; +use codex_core::config::ConfigToml; use codex_core::protocol::AgentMessageDeltaEvent; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::AgentReasoningDeltaEvent; @@ -485,6 +486,60 @@ impl ChatWidget<'_> { pub(crate) fn token_usage(&self) -> &TokenUsage { &self.token_usage } + + /// Open the model selection view in the bottom pane. + pub(crate) fn show_model_selector(&mut self) { + let current = self.config.model.clone(); + + // Start with curated OpenAI models. + let mut options = codex_core::openai_model_info::get_all_model_names() + .into_iter() + .map(|s| s.to_string()) + .collect::>(); + + // Always include the currently configured model (covers custom values). + options.push(current.clone()); + + // Append any models found in config.toml profiles and top-level model. + let config_path = self.config.codex_home.join("config.toml"); + if let Ok(contents) = std::fs::read_to_string(&config_path) { + if let Ok(cfg) = toml::from_str::(&contents) { + if let Some(m) = cfg.model { + options.push(m); + } + for (_name, profile) in cfg.profiles.into_iter() { + if let Some(m) = profile.model { + options.push(m); + } + } + } + } + + self.bottom_pane.show_model_selector(¤t, options); + } + + /// Update the current model and reconfigure the running Codex session. + pub(crate) fn update_model_and_reconfigure(&mut self, model: String) { + // Update local config so UI reflects the new model. + let changed = self.config.model != model; + self.config.model = model.clone(); + + // Emit a lightweight event in the conversation log so the change is visible. + if changed { + self.conversation_history + .add_background_event(format!("Set model to {}.", model)); + self.emit_last_history_entry(); + } + + // Reconfigure the agent session with the same provider and policies. + // Build the op from the config to avoid drift when fields are added. + let op = self + .config + .to_configure_session_op(None, self.config.user_instructions.clone()); + self.submit_op(op); + self.request_redraw(); + } + } impl WidgetRef for &ChatWidget<'_> { diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 603eb721cd..c30c85c423 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -14,6 +14,7 @@ pub enum SlashCommand { // more frequently used commands should be listed first. New, Diff, + Model, Quit, } @@ -23,6 +24,7 @@ impl SlashCommand { match self { SlashCommand::New => "Start a new chat.", SlashCommand::Quit => "Exit the application.", + SlashCommand::Model => "Select the model to use.", SlashCommand::Diff => { "Show git diff of the working directory (including untracked files)" } From 9db5c7af9ee06693f9c77475b5f0393766877cd5 Mon Sep 17 00:00:00 2001 From: pap Date: Mon, 28 Jul 2025 23:21:49 +0100 Subject: [PATCH 02/18] remove preference ranking as we don't get models dynamically --- codex-rs/core/src/openai_model_info.rs | 31 ------------------- .../src/bottom_pane/model_selection_view.rs | 12 +++---- codex-rs/tui/src/chatwidget.rs | 10 +++--- 3 files changed, 10 insertions(+), 43 deletions(-) diff --git a/codex-rs/core/src/openai_model_info.rs b/codex-rs/core/src/openai_model_info.rs index 1dcd7c19b5..f0e4355305 100644 --- a/codex-rs/core/src/openai_model_info.rs +++ b/codex-rs/core/src/openai_model_info.rs @@ -73,43 +73,12 @@ pub(crate) fn get_model_info(name: &str) -> Option { /// Return a curated list of commonly-used OpenAI model names for selection UIs. pub fn get_all_model_names() -> Vec<&'static str> { vec![ - // codex models "codex-mini-latest", - // reasoning models "o3", "o4-mini", - // GPT-4.1 family "gpt-4.1", - // GPT-4o family (canonical plus a few snapshots) "gpt-4o", ] } -/// Sort order by preference groups, then alphabetically. -pub fn preference_rank(name: &str) -> u8 { - // Lower is more preferred. - if name == "codex-mini-latest" { - return 0; - } - if name.starts_with("o4-mini") { - return 1; - } - if name == "o3" || name.starts_with("o3") { - return 2; - } - if name == "gpt-4.1" || name.starts_with("gpt-4.1") { - return 3; - } - // Handle both spellings just in case. - if name == "gpt4-o" || name.starts_with("gpt-4o") { - return 4; - } - 5 -} -/// Compare two model names by preference ranking. -pub fn compare_models_by_preference(a: &str, b: &str) -> std::cmp::Ordering { - preference_rank(a) - .cmp(&preference_rank(b)) - .then_with(|| a.cmp(b)) -} diff --git a/codex-rs/tui/src/bottom_pane/model_selection_view.rs b/codex-rs/tui/src/bottom_pane/model_selection_view.rs index 15714c2b45..4ed2675a48 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_view.rs @@ -21,7 +21,6 @@ use crate::app_event_sender::AppEventSender; use super::BottomPane; use super::BottomPaneView; -use codex_core::openai_model_info::compare_models_by_preference; /// Simple dropdown to select a model. pub(crate) struct ModelSelectionView { @@ -54,16 +53,15 @@ impl ModelSelectionView { /// sort preference, and search filter. fn build_display_rows(&self) -> Vec { // Determine candidate list excluding the current model (it is always pinned first). - let mut others: Vec<&str> = self + let others: Vec<&str> = self .options .iter() .map(|s| s.as_str()) .filter(|m| *m != self.current_model) .collect(); - // If not searching, apply preference sort; otherwise, we'll score by fuzzy match. + // If not searching, maintain provided ordering; otherwise, we'll score by fuzzy match. if self.query.is_empty() { - others.sort_by(|a, b| compare_models_by_preference(a, b)); let mut rows: Vec = Vec::new(); // Pinned current model always first. rows.push(DisplayRow::Model { @@ -99,11 +97,10 @@ impl ModelSelectionView { matches.push((name.to_string(), indices, score)); } } - // Sort by score (ascending => better). If equal, fall back to preference then alphabetical. + // Sort by score (ascending => better). If equal, fall back to alphabetical and match tightness. matches.sort_by(|(a_name, a_idx, a_score), (b_name, b_idx, b_score)| { a_score .cmp(b_score) - .then_with(|| compare_models_by_preference(a_name, b_name)) .then_with(|| a_name.cmp(b_name)) .then_with(|| a_idx.len().cmp(&b_idx.len())) }); @@ -415,8 +412,7 @@ impl<'a> BottomPaneView<'a> for ModelSelectionView { unique.push(m); } } - // Sort by preference for stable display when query is empty. - unique.sort_by(|a, b| compare_models_by_preference(a, b)); + // Preserve provided ordering without applying preference ranking. self.options = unique; // Clamp selection to available rows. diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index eaad5c5036..4dc9459f07 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -504,14 +504,16 @@ impl ChatWidget<'_> { let config_path = self.config.codex_home.join("config.toml"); if let Ok(contents) = std::fs::read_to_string(&config_path) { if let Ok(cfg) = toml::from_str::(&contents) { - if let Some(m) = cfg.model { - options.push(m); - } + let mut config_models: Vec = Vec::new(); + if let Some(m) = cfg.model { config_models.push(m); } for (_name, profile) in cfg.profiles.into_iter() { if let Some(m) = profile.model { - options.push(m); + config_models.push(m); } } + // Keep it simple and deterministic: alphabetical ordering for config models. + config_models.sort(); + options.extend(config_models); } } From 1836614c063e9d56fae08bedb07aeb842d5e6f25 Mon Sep 17 00:00:00 2001 From: pap Date: Mon, 28 Jul 2025 23:25:35 +0100 Subject: [PATCH 03/18] remove current model if search doesn't match --- .../src/bottom_pane/model_selection_view.rs | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/model_selection_view.rs b/codex-rs/tui/src/bottom_pane/model_selection_view.rs index 4ed2675a48..afde21e5c6 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_view.rs @@ -81,14 +81,15 @@ impl ModelSelectionView { return rows; } - // Searching: include pinned current model first (even if it doesn't match), - // then fuzzy-matched models sorted by score. + // Searching: only include current model if it matches the query. let mut rows: Vec = Vec::new(); - rows.push(DisplayRow::Model { - name: self.current_model.clone(), - match_indices: fuzzy_indices(&self.current_model, &self.query), - is_current: true, - }); + if let Some(indices) = fuzzy_indices(&self.current_model, &self.query) { + rows.push(DisplayRow::Model { + name: self.current_model.clone(), + match_indices: Some(indices), + is_current: true, + }); + } // Build list of matches among others. let mut matches: Vec<(String, Vec, i32)> = Vec::new(); @@ -106,11 +107,14 @@ impl ModelSelectionView { }); for (name, indices, _score) in matches { - rows.push(DisplayRow::Model { - name, - match_indices: Some(indices), - is_current: false, - }); + // Don't duplicate the current model if it matched above + if name != self.current_model { + rows.push(DisplayRow::Model { + name, + match_indices: Some(indices), + is_current: false, + }); + } } rows From f78f8d8c7c370721286ca7b90e80b2bf1d7664c0 Mon Sep 17 00:00:00 2001 From: pap Date: Tue, 29 Jul 2025 23:20:24 +0100 Subject: [PATCH 04/18] fmt --- codex-rs/core/src/codex.rs | 3 +- codex-rs/core/src/config.rs | 2 +- codex-rs/core/src/openai_model_info.rs | 10 +---- codex-rs/tui/src/app.rs | 5 +-- codex-rs/tui/src/bottom_pane/mod.rs | 4 +- .../src/bottom_pane/model_selection_view.rs | 38 +++++++++++-------- codex-rs/tui/src/chatwidget.rs | 5 ++- 7 files changed, 34 insertions(+), 33 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index f61d45f5ec..48572e31df 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -111,7 +111,8 @@ impl Codex { let user_instructions = get_user_instructions(&config).await; - let configure_session = config.to_configure_session_op(Some(config.model.clone()), user_instructions); + let configure_session = + config.to_configure_session_op(Some(config.model.clone()), user_instructions); let config = Arc::new(config); diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index 9fd253c79c..0fcad44fc3 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -14,8 +14,8 @@ use crate::model_provider_info::ModelProviderInfo; use crate::model_provider_info::built_in_model_providers; use crate::openai_model_info::get_model_info; use crate::protocol::AskForApproval; -use crate::protocol::SandboxPolicy; use crate::protocol::Op; +use crate::protocol::SandboxPolicy; use dirs::home_dir; use serde::Deserialize; use std::collections::HashMap; diff --git a/codex-rs/core/src/openai_model_info.rs b/codex-rs/core/src/openai_model_info.rs index f0e4355305..0f97c1334d 100644 --- a/codex-rs/core/src/openai_model_info.rs +++ b/codex-rs/core/src/openai_model_info.rs @@ -72,13 +72,5 @@ pub(crate) fn get_model_info(name: &str) -> Option { /// Return a curated list of commonly-used OpenAI model names for selection UIs. pub fn get_all_model_names() -> Vec<&'static str> { - vec![ - "codex-mini-latest", - "o3", - "o4-mini", - "gpt-4.1", - "gpt-4o", - ] + vec!["codex-mini-latest", "o3", "o4-mini", "gpt-4.1", "gpt-4o"] } - - diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 9c7d3d9d9c..56f185486e 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -366,7 +366,7 @@ impl App<'_> { widget.show_model_selector(); } // Models are populated from a curated list; no network fetch. - }, + } }, AppEvent::DispatchCommandWithArgs(command, args) => match command { SlashCommand::Model => { @@ -489,7 +489,6 @@ impl App<'_> { } } - #[cfg(test)] mod tests { use super::strip_surrounding_quotes; @@ -529,4 +528,4 @@ mod tests { assert_eq!(normalized, norm_expected, "normalized args for '{}'", line); } } -} \ No newline at end of file +} diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index b9e950d888..4ca7cb692c 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -18,15 +18,15 @@ mod chat_composer; mod chat_composer_history; mod command_popup; mod file_search_popup; -mod status_indicator_view; mod model_selection_view; +mod status_indicator_view; pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::InputResult; use approval_modal_view::ApprovalModalView; -use status_indicator_view::StatusIndicatorView; use model_selection_view::ModelSelectionView; +use status_indicator_view::StatusIndicatorView; /// Pane displayed in the lower half of the chat UI. pub(crate) struct BottomPane<'a> { diff --git a/codex-rs/tui/src/bottom_pane/model_selection_view.rs b/codex-rs/tui/src/bottom_pane/model_selection_view.rs index afde21e5c6..cf40dba68e 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_view.rs @@ -11,10 +11,10 @@ use ratatui::widgets::Block; use ratatui::widgets::BorderType; use ratatui::widgets::Borders; use ratatui::widgets::Cell; +use ratatui::widgets::Clear; use ratatui::widgets::Row; use ratatui::widgets::Table; use ratatui::widgets::Widget; -use ratatui::widgets::Clear; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; @@ -136,7 +136,11 @@ impl ModelSelectionView { } else { // searching: pinned current + matches let mut matches = 1; // current always present - for name in self.options.iter().filter(|m| m.as_str() != self.current_model) { + for name in self + .options + .iter() + .filter(|m| m.as_str() != self.current_model) + { if fuzzy_match(name, &self.query).is_some() { matches += 1; } @@ -174,7 +178,6 @@ impl ModelSelectionView { } None } - } /// Row that can be rendered in the selector. @@ -186,7 +189,6 @@ enum DisplayRow { }, } - /// Return indices for a simple case-insensitive subsequence match and a score. /// Smaller score is better. fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec, i32)> { @@ -360,8 +362,11 @@ impl<'a> BottomPaneView<'a> for ModelSelectionView { let mut cell = Cell::from(Line::from(spans)); // Selected row style takes precedence. if abs_idx == self.selected_idx { - cell = cell - .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)); + cell = cell.style( + Style::default() + .fg(Color::Yellow) + .add_modifier(Modifier::BOLD), + ); } else if *is_current { // Special color for the current model when not selected. cell = cell.style(Style::default().fg(Color::Cyan)); @@ -394,14 +399,17 @@ impl<'a> BottomPaneView<'a> for ModelSelectionView { title.push(')'); } - let table = Table::new(visible_rows, vec![ratatui::prelude::Constraint::Percentage(100)]) - .block( - Block::default() - .title(title) - .borders(Borders::ALL) - .border_type(BorderType::Rounded), - ) - .widths([ratatui::prelude::Constraint::Percentage(100)]); + let table = Table::new( + visible_rows, + vec![ratatui::prelude::Constraint::Percentage(100)], + ) + .block( + Block::default() + .title(title) + .borders(Borders::ALL) + .border_type(BorderType::Rounded), + ) + .widths([ratatui::prelude::Constraint::Percentage(100)]); table.render(area, buf); } @@ -423,4 +431,4 @@ impl<'a> BottomPaneView<'a> for ModelSelectionView { self.selected_idx = self.selected_idx.min(self.row_count().saturating_sub(1)); true } -} +} diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 4dc9459f07..65609c7863 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -505,7 +505,9 @@ impl ChatWidget<'_> { if let Ok(contents) = std::fs::read_to_string(&config_path) { if let Ok(cfg) = toml::from_str::(&contents) { let mut config_models: Vec = Vec::new(); - if let Some(m) = cfg.model { config_models.push(m); } + if let Some(m) = cfg.model { + config_models.push(m); + } for (_name, profile) in cfg.profiles.into_iter() { if let Some(m) = profile.model { config_models.push(m); @@ -541,7 +543,6 @@ impl ChatWidget<'_> { self.submit_op(op); self.request_redraw(); } - } impl WidgetRef for &ChatWidget<'_> { From 34edf573d7198766c5c9aaf782287e24a720b3fb Mon Sep 17 00:00:00 2001 From: pap Date: Wed, 30 Jul 2025 18:06:11 +0100 Subject: [PATCH 05/18] linter --- codex-rs/tui/src/app.rs | 12 +++++++++--- codex-rs/tui/src/bottom_pane/model_selection_view.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 56f185486e..65e41af94c 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -51,9 +51,15 @@ fn strip_surrounding_quotes(s: &str) -> String { return trimmed.to_string(); } - let mut chars = trimmed.chars(); - let first = chars.next().unwrap(); - let last = trimmed.chars().last().unwrap(); + // Safely obtain the first and last characters without unwraps. + let (first, last) = { + let mut chs = trimmed.chars(); + match (chs.next(), chs.next_back()) { + (Some(f), Some(l)) => (f, l), + (Some(f), None) => (f, f), + _ => return trimmed.to_string(), + } + }; let is_valid_quote = match first { '"' | '\'' | '“' | '‘' => first == last, diff --git a/codex-rs/tui/src/bottom_pane/model_selection_view.rs b/codex-rs/tui/src/bottom_pane/model_selection_view.rs index cf40dba68e..e7f1c12ce6 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_view.rs @@ -203,7 +203,7 @@ fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec, i32)> { for ch in n_lower.chars() { let mut found = None; - while let Some((i, hc)) = h_iter.next() { + for (i, hc) in h_iter.by_ref() { if hc == ch { found = Some(i); break; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 65609c7863..24ab2e9bb9 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -531,7 +531,7 @@ impl ChatWidget<'_> { // Emit a lightweight event in the conversation log so the change is visible. if changed { self.conversation_history - .add_background_event(format!("Set model to {}.", model)); + .add_background_event(format!("Set model to {model}.")); self.emit_last_history_entry(); } From 661a4ff3f9bb1c0bd05bdeaaee4bde7cbfeb5d6c Mon Sep 17 00:00:00 2001 From: pap Date: Wed, 30 Jul 2025 20:07:14 +0100 Subject: [PATCH 06/18] fix: self.emit_last_history_entry() --- codex-rs/tui/src/chatwidget.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index f782efe3e1..2368ebbfa8 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -522,9 +522,9 @@ impl ChatWidget<'_> { // Emit a lightweight event in the conversation log so the change is visible. if changed { - self.conversation_history - .add_background_event(format!("Set model to {model}.")); - self.emit_last_history_entry(); + self.add_to_history(HistoryCell::new_background_event(format!( + "Set model to {model}." + ))); } // Reconfigure the agent session with the same provider and policies. From 9dce0d78825e0ecf7fe397e79014fc4bbedfa45e Mon Sep 17 00:00:00 2001 From: pap Date: Wed, 30 Jul 2025 20:32:01 +0100 Subject: [PATCH 07/18] don't show session information at each reconfiguration --- codex-rs/tui/src/chatwidget.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 2368ebbfa8..63d9aedd41 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -57,6 +57,7 @@ pub(crate) struct ChatWidget<'a> { // We wait for the final AgentMessage event and then emit the full text // at once into scrollback so the history contains a single message. answer_buffer: String, + new_session: bool, } struct UserMessage { @@ -141,6 +142,7 @@ impl ChatWidget<'_> { token_usage: TokenUsage::default(), reasoning_buffer: String::new(), answer_buffer: String::new(), + new_session: true, } } @@ -207,8 +209,12 @@ impl ChatWidget<'_> { EventMsg::SessionConfigured(event) => { self.bottom_pane .set_history_metadata(event.history_log_id, event.history_entry_count); + // Record session information at the top of the conversation. - self.add_to_history(HistoryCell::new_session_info(&self.config, event, true)); + if self.new_session { + self.add_to_history(HistoryCell::new_session_info(&self.config, event, true)); + self.new_session = false; + } if let Some(user_message) = self.initial_user_message.take() { // If the user provided an initial message, add it to the From 91aa683ae9170759b9aa2b065ba340407aee300b Mon Sep 17 00:00:00 2001 From: pap Date: Wed, 30 Jul 2025 20:43:31 +0100 Subject: [PATCH 08/18] cleaner code --- codex-rs/tui/src/app.rs | 40 ++++++++++++---------------------- codex-rs/tui/src/chatwidget.rs | 5 ++--- 2 files changed, 16 insertions(+), 29 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 299455f0ae..d0b6b60ec1 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -39,34 +39,24 @@ enum AppState<'a> { /// Strip a single pair of surrounding quotes from the provided string if present. /// Supports straight and common curly quotes: '…', "…", ‘…’, “…”. -fn strip_surrounding_quotes(s: &str) -> String { - let trimmed = s.trim(); - if trimmed.len() < 2 { - return trimmed.to_string(); +pub fn strip_surrounding_quotes(s: &str) -> &str { + // Opening/closing pairs (note curly quotes differ on each side) + const QUOTE_PAIRS: &[(char, char)] = &[('"', '"'), ('\'', '\''), ('“', '”'), ('‘', '’')]; + + let t = s.trim(); + if t.len() < 2 { + return t; } - // Safely obtain the first and last characters without unwraps. - let (first, last) = { - let mut chs = trimmed.chars(); - match (chs.next(), chs.next_back()) { - (Some(f), Some(l)) => (f, l), - (Some(f), None) => (f, f), - _ => return trimmed.to_string(), + for &(open, close) in QUOTE_PAIRS { + if t.starts_with(open) && t.ends_with(close) { + let start = open.len_utf8(); + let end = t.len() - close.len_utf8(); + return &t[start..end]; } - }; - - let is_valid_quote = match first { - '"' | '\'' | '“' | '‘' => first == last, - _ => false, - }; - - if is_valid_quote { - let start = first.len_utf8(); - let end = trimmed.len() - last.len_utf8(); - trimmed[start..end].to_string() - } else { - trimmed.to_string() } + + t } pub(crate) struct App<'a> { @@ -337,7 +327,6 @@ impl App<'_> { if let AppState::Chat { widget } = &mut self.app_state { widget.show_model_selector(); } - // Models are populated from a curated list; no network fetch. } }, AppEvent::DispatchCommandWithArgs(command, args) => match command { @@ -348,7 +337,6 @@ impl App<'_> { if let AppState::Chat { widget } = &mut self.app_state { widget.show_model_selector(); } - // Models are populated from a curated list; no network fetch. } else if let AppState::Chat { widget } = &mut self.app_state { // Normalize commonly quoted inputs like \"o3\" or 'o3' or “o3”. let normalized = strip_surrounding_quotes(arg).trim().to_string(); diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 63d9aedd41..95a599318e 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -489,7 +489,6 @@ impl ChatWidget<'_> { pub(crate) fn show_model_selector(&mut self) { let current = self.config.model.clone(); - // Start with curated OpenAI models. let mut options = codex_core::openai_model_info::get_all_model_names() .into_iter() .map(|s| s.to_string()) @@ -511,7 +510,7 @@ impl ChatWidget<'_> { config_models.push(m); } } - // Keep it simple and deterministic: alphabetical ordering for config models. + // Alphabetical ordering for config models. config_models.sort(); options.extend(config_models); } @@ -526,7 +525,7 @@ impl ChatWidget<'_> { let changed = self.config.model != model; self.config.model = model.clone(); - // Emit a lightweight event in the conversation log so the change is visible. + // Emit an event in the conversation log so the change is visible. if changed { self.add_to_history(HistoryCell::new_background_event(format!( "Set model to {model}." From 55659e351cc741bd8e1d1182140c53edf7b2de87 Mon Sep 17 00:00:00 2001 From: pap Date: Wed, 30 Jul 2025 22:00:13 +0100 Subject: [PATCH 09/18] fixing merge --- codex-rs/core/src/codex.rs | 3 +-- codex-rs/core/src/lib.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 3 ++- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index f166185361..730d3eb12c 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -628,7 +628,6 @@ async fn submission_loop( } }; - // Create a session-specific Config that only overrides the model. let client_config = { let mut c = (*config).clone(); c.model = model.clone(); @@ -636,7 +635,7 @@ async fn submission_loop( }; let client = ModelClient::new( - config.clone(), + client_config, auth.clone(), provider.clone(), model_reasoning_effort, diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index ffe64d7c90..2b7126f394 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -32,7 +32,7 @@ pub use model_provider_info::ModelProviderInfo; pub use model_provider_info::WireApi; pub use model_provider_info::built_in_model_providers; mod models; -mod openai_model_info; +pub mod openai_model_info; mod openai_tools; pub mod plan_tool; mod project_doc; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 95a599318e..8ec927a671 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -6,6 +6,7 @@ use codex_core::codex_wrapper::CodexConversation; use codex_core::codex_wrapper::init_codex; use codex_core::config::Config; use codex_core::config::ConfigToml; +use codex_core::openai_model_info::get_all_model_names; use codex_core::protocol::AgentMessageDeltaEvent; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::AgentReasoningDeltaEvent; @@ -489,7 +490,7 @@ impl ChatWidget<'_> { pub(crate) fn show_model_selector(&mut self) { let current = self.config.model.clone(); - let mut options = codex_core::openai_model_info::get_all_model_names() + let mut options = get_all_model_names() .into_iter() .map(|s| s.to_string()) .collect::>(); From 40cf8a819c1488065f36fe536a8b87136fa7fa93 Mon Sep 17 00:00:00 2001 From: pap Date: Wed, 30 Jul 2025 22:28:02 +0100 Subject: [PATCH 10/18] lint test --- codex-rs/tui/src/app.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index d0b6b60ec1..cd7792e03c 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -469,10 +469,10 @@ mod tests { } else { String::new() }; - assert_eq!(raw, raw_expected, "raw args for '{}'", line); + assert_eq!(raw, raw_expected, "raw args for '{line}'"); // Normalize as in app dispatch logic let normalized = strip_surrounding_quotes(&raw).trim().to_string(); - assert_eq!(normalized, norm_expected, "normalized args for '{}'", line); + assert_eq!(normalized, norm_expected, "normalized args for '{line}'"); } } } From f8e5b02320a982770fad33c03a416c48203148aa Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 31 Jul 2025 13:35:59 +0100 Subject: [PATCH 11/18] desired_height for model selection --- codex-rs/tui/src/bottom_pane/model_selection_view.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/codex-rs/tui/src/bottom_pane/model_selection_view.rs b/codex-rs/tui/src/bottom_pane/model_selection_view.rs index e7f1c12ce6..ed6d945008 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_view.rs @@ -291,6 +291,14 @@ impl<'a> BottomPaneView<'a> for ModelSelectionView { self.is_complete } + fn desired_height(&self, _width: u16) -> u16 { + const MAX_VISIBLE_ROWS: usize = 10; + let list_rows = self.row_count().min(MAX_VISIBLE_ROWS) as u16; + let stats_rows = 1u16; // persistent status line at bottom + let border_rows = 2u16; // top + bottom borders + list_rows + stats_rows + border_rows + } + fn render(&self, area: Rect, buf: &mut Buffer) { // Clear the area to prevent ghosting when the list height/width changes between frames. Clear.render(area, buf); From fbc1ee7d62cbea19b169d7b61f8ef6b70382ddc2 Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 31 Jul 2025 15:00:08 +0100 Subject: [PATCH 12/18] new model popup --- codex-rs/tui/src/app.rs | 17 +- codex-rs/tui/src/app_event.rs | 3 + .../tui/src/bottom_pane/bottom_pane_view.rs | 6 - codex-rs/tui/src/bottom_pane/chat_composer.rs | 178 ++++++- codex-rs/tui/src/bottom_pane/mod.rs | 10 +- .../src/bottom_pane/model_selection_popup.rs | 271 +++++++++++ .../src/bottom_pane/model_selection_view.rs | 442 ------------------ 7 files changed, 453 insertions(+), 474 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/model_selection_popup.rs delete mode 100644 codex-rs/tui/src/bottom_pane/model_selection_view.rs diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index d44f5617da..e870dab8f3 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -284,6 +284,11 @@ impl App<'_> { widget.update_model_and_reconfigure(model); } } + AppEvent::OpenModelSelector => { + if let AppState::Chat { widget } = &mut self.app_state { + widget.show_model_selector(); + } + } AppEvent::CodexOp(op) => match &mut self.app_state { AppState::Chat { widget } => widget.submit_op(op), AppState::GitWarning { .. } => {} @@ -340,21 +345,13 @@ impl App<'_> { })); } SlashCommand::Model => { - // No explicit args were provided; open the selector. - if let AppState::Chat { widget } = &mut self.app_state { - widget.show_model_selector(); - } + // Disallow `/model` without arguments; no action. } }, AppEvent::DispatchCommandWithArgs(command, args) => match command { SlashCommand::Model => { let arg = args.trim(); - if arg.is_empty() { - // Same as `/model` without args. - if let AppState::Chat { widget } = &mut self.app_state { - widget.show_model_selector(); - } - } else if let AppState::Chat { widget } = &mut self.app_state { + if let AppState::Chat { widget } = &mut self.app_state { // Normalize commonly quoted inputs like \"o3\" or 'o3' or “o3”. let normalized = strip_surrounding_quotes(arg).trim().to_string(); if !normalized.is_empty() { diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 42b146a48d..8b60a12815 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -55,4 +55,7 @@ pub(crate) enum AppEvent { /// User selected a model from the model-selection dropdown. SelectModel(String), + + /// Request the app to open the model selector (populate options and show popup). + OpenModelSelector, } diff --git a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs index 537f0ead00..a5616371d2 100644 --- a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs +++ b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs @@ -52,10 +52,4 @@ pub(crate) trait BottomPaneView<'a> { ) -> Option { Some(request) } - - /// Optional hook: if this view is a model selector, update the options. - /// Returns true if options were applied and a redraw is desired. - fn set_model_options(&mut self, _current_model: &str, _options: Vec) -> bool { - false - } } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 66a8547946..0e7108311d 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -19,10 +19,12 @@ use tui_textarea::TextArea; use super::chat_composer_history::ChatComposerHistory; use super::command_popup::CommandPopup; use super::file_search_popup::FileSearchPopup; +use super::model_selection_popup::ModelSelectionPopup; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use codex_file_search::FileMatch; +use crate::slash_command::SlashCommand; const BASE_PLACEHOLDER_TEXT: &str = "..."; /// If the pasted content exceeds this number of characters, replace it with a @@ -51,6 +53,7 @@ enum ActivePopup { None, Command(CommandPopup), File(FileSearchPopup), + Model(ModelSelectionPopup), } impl ChatComposer<'_> { @@ -79,6 +82,7 @@ impl ChatComposer<'_> { ActivePopup::None => 1u16, ActivePopup::Command(c) => c.calculate_required_height(), ActivePopup::File(c) => c.calculate_required_height(), + ActivePopup::Model(c) => c.calculate_required_height(), } } @@ -174,20 +178,46 @@ impl ChatComposer<'_> { self.update_border(has_focus); } + /// Open or update the model-selection popup with the provided options. + pub(crate) fn open_model_selector(&mut self, current_model: &str, options: Vec) { + match &mut self.active_popup { + ActivePopup::Model(popup) => { + popup.set_options(current_model, options); + } + _ => { + self.active_popup = ActivePopup::Model(ModelSelectionPopup::new(current_model, options)); + } + } + // Initialize/update the query from the composer. + self.sync_model_popup(); + } + /// Handle a key event coming from the main UI. pub fn handle_key_event(&mut self, key_event: KeyEvent) -> (InputResult, bool) { let result = match &mut self.active_popup { ActivePopup::Command(_) => self.handle_key_event_with_slash_popup(key_event), ActivePopup::File(_) => self.handle_key_event_with_file_popup(key_event), + ActivePopup::Model(_) => self.handle_key_event_with_model_popup(key_event), ActivePopup::None => self.handle_key_event_without_popup(key_event), }; // Update (or hide/show) popup after processing the key. - self.sync_command_popup(); - if matches!(self.active_popup, ActivePopup::Command(_)) { - self.dismissed_file_popup_token = None; - } else { - self.sync_file_search_popup(); + match &self.active_popup { + ActivePopup::Model(_) => { + // Only keep model popup in sync when active; do not interfere with other popups. + self.sync_model_popup(); + } + ActivePopup::Command(_) => { + self.sync_command_popup(); + // When slash popup active, suppress file popup. + self.dismissed_file_popup_token = None; + } + _ => { + self.sync_command_popup(); + if !matches!(self.active_popup, ActivePopup::Command(_)) { + self.sync_file_search_popup(); + } + } } result @@ -253,11 +283,21 @@ impl ChatComposer<'_> { String::new() }; + // If `/model` has no args, autocomplete to "/model " and open the model selector. + if *cmd == SlashCommand::Model && args.trim().is_empty() { + self.textarea.select_all(); + self.textarea.cut(); + let _ = self.textarea.insert_str(format!("/{} ", cmd.command())); + // Hide the command popup; model popup will be shown by sync_command_popup. + self.active_popup = ActivePopup::None; + return (InputResult::None, true); + } + // Send command + args to the app layer. self.app_event_tx .send(AppEvent::DispatchCommandWithArgs(*cmd, args)); - // Clear textarea so no residual text remains. + // Clear textarea so no residual text remains (default behavior). self.textarea.select_all(); self.textarea.cut(); @@ -315,6 +355,47 @@ impl ChatComposer<'_> { } } + /// Handle key events when model selection popup is visible. + fn handle_key_event_with_model_popup(&mut self, key_event: KeyEvent) -> (InputResult, bool) { + let ActivePopup::Model(popup) = &mut self.active_popup else { + unreachable!(); + }; + + match key_event.into() { + Input { key: Key::Up, .. } => { + popup.move_up(); + (InputResult::None, true) + } + Input { key: Key::Down, .. } => { + popup.move_down(); + (InputResult::None, true) + } + Input { key: Key::Esc, .. } => { + // Hide model popup; keep composer content unchanged. + self.active_popup = ActivePopup::None; + (InputResult::None, true) + } + Input { + key: Key::Enter, + ctrl: false, + alt: false, + shift: false, + } => { + if let Some(model) = popup.selected_model() { + self.app_event_tx.send(AppEvent::SelectModel(model)); + // Clear composer input and close the popup. + self.textarea.select_all(); + self.textarea.cut(); + self.pending_pastes.clear(); + self.active_popup = ActivePopup::None; + return (InputResult::None, true); + } + (InputResult::None, false) + } + input => self.handle_input_basic(input), + } + } + /// Extract the `@token` that the cursor is currently positioned on, if any. /// /// The returned string **does not** include the leading `@`. @@ -600,9 +681,32 @@ impl ChatComposer<'_> { .unwrap_or(""); let input_starts_with_slash = first_line.starts_with('/'); + + // Special handling: if the user typed `/model ` (with a space), open the model selector + // and do not show the slash-command popup. + let should_open_model_selector = if let Some(stripped) = first_line.strip_prefix('/') { + let token = stripped.trim_start(); + let cmd_token = token.split_whitespace().next().unwrap_or(""); + if cmd_token == SlashCommand::Model.command() { + let rest = &token[cmd_token.len()..]; + // Show model popup as soon as a whitespace after the command is present. + rest.chars().next().is_some_and(|c| c.is_whitespace()) + } else { + false + } + } else { + false + }; + match &mut self.active_popup { ActivePopup::Command(popup) => { if input_starts_with_slash { + if should_open_model_selector { + // Switch away from command popup and request opening the model selector. + self.active_popup = ActivePopup::None; + self.app_event_tx.send(AppEvent::OpenModelSelector); + return; + } popup.on_composer_text_change(first_line.to_string()); } else { self.active_popup = ActivePopup::None; @@ -610,9 +714,15 @@ impl ChatComposer<'_> { } _ => { if input_starts_with_slash { - let mut command_popup = CommandPopup::new(); - command_popup.on_composer_text_change(first_line.to_string()); - self.active_popup = ActivePopup::Command(command_popup); + if should_open_model_selector { + // Request the app to open the model selector; popup will render once options arrive. + self.app_event_tx.send(AppEvent::OpenModelSelector); + return; + } else { + let mut command_popup = CommandPopup::new(); + command_popup.on_composer_text_change(first_line.to_string()); + self.active_popup = ActivePopup::Command(command_popup); + } } } } @@ -654,6 +764,36 @@ impl ChatComposer<'_> { self.dismissed_file_popup_token = None; } + /// Synchronize the model-selection popup filter with the current composer text. + /// When the first line starts with `/model`, everything after the command becomes the query. + fn sync_model_popup(&mut self) { + let first_line = self + .textarea + .lines() + .first() + .map(|s| s.as_str()) + .unwrap_or(""); + + // Expect `/model` as the first token on the first line. + if let Some(stripped) = first_line.strip_prefix('/') { + let token = stripped.trim_start(); + let cmd_token = token.split_whitespace().next().unwrap_or(""); + if cmd_token == SlashCommand::Model.command() { + let rest = &token[cmd_token.len()..]; + let args = rest.trim_start(); + if let ActivePopup::Model(popup) = &mut self.active_popup { + popup.set_query(args); + } + return; + } + } + + // Not a `/model` line anymore; hide the model popup if visible. + if matches!(self.active_popup, ActivePopup::Model(_)) { + self.active_popup = ActivePopup::None; + } + } + fn update_border(&mut self, has_focus: bool) { let border_style = if has_focus { Style::default().fg(Color::Cyan) @@ -715,6 +855,26 @@ impl WidgetRef for &ChatComposer<'_> { popup.render(popup_rect, buf); self.textarea.render(textarea_rect, buf); } + ActivePopup::Model(popup) => { + let popup_height = popup.calculate_required_height(); + + let popup_height = popup_height.min(area.height); + let textarea_rect = Rect { + x: area.x, + y: area.y, + width: area.width, + height: area.height.saturating_sub(popup_height), + }; + let popup_rect = Rect { + x: area.x, + y: area.y + textarea_rect.height, + width: area.width, + height: popup_height, + }; + + popup.render(popup_rect, buf); + self.textarea.render(textarea_rect, buf); + } ActivePopup::None => { let mut textarea_rect = area; textarea_rect.height = textarea_rect.height.saturating_sub(1); diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 1a0320af89..e019a19cf2 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -18,7 +18,7 @@ mod chat_composer; mod chat_composer_history; mod command_popup; mod file_search_popup; -mod model_selection_view; +mod model_selection_popup; mod status_indicator_view; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -31,7 +31,6 @@ pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::InputResult; use approval_modal_view::ApprovalModalView; -use model_selection_view::ModelSelectionView; use status_indicator_view::StatusIndicatorView; /// Pane displayed in the lower half of the chat UI. @@ -66,12 +65,9 @@ impl BottomPane<'_> { } } - /// Show the model-selection dropdown view. + /// Show the model-selection popup in the composer. pub(crate) fn show_model_selector(&mut self, current_model: &str, options: Vec) { - let mut view = ModelSelectionView::new(current_model, self.app_event_tx.clone()); - // Apply options so the view starts populated and not in a loading state. - let _ = view.set_model_options(current_model, options); - self.active_view = Some(Box::new(view)); + self.composer.open_model_selector(current_model, options); self.request_redraw(); } diff --git a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs new file mode 100644 index 0000000000..258cd8d757 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs @@ -0,0 +1,271 @@ +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::prelude::Constraint; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, BorderType, Borders, Cell, Row, Table, Widget, WidgetRef}; + +/// Maximum number of options shown in the popup. +const MAX_RESULTS: usize = 8; + +/// Visual state for the model-selection popup. +pub(crate) struct ModelSelectionPopup { + /// The current model (pinned and color-coded when visible). + current_model: String, + /// All available model options (deduplicated externally as needed). + options: Vec, + /// Current filter query (derived from the composer, e.g. after `/model`). + query: String, + /// Currently selected index among the visible rows (if any). + selected_idx: Option, +} + +impl ModelSelectionPopup { + pub(crate) fn new(current_model: &str, options: Vec) -> Self { + Self { + current_model: current_model.to_string(), + options, + query: String::new(), + selected_idx: None, + } + } + + /// Update the current model and option list. Resets/clamps selection as needed. + pub(crate) fn set_options(&mut self, current_model: &str, options: Vec) { + self.current_model = current_model.to_string(); + self.options = options; + let visible_len = self.visible_rows().len(); + self.selected_idx = match visible_len { + 0 => None, + _ => Some(self.selected_idx.unwrap_or(0).min(visible_len - 1)), + }; + } + + /// Update the fuzzy filter query. + pub(crate) fn set_query(&mut self, query: &str) { + if self.query == query { return; } + self.query.clear(); + self.query.push_str(query); + // Reset/clamp selection based on new filtered list. + let visible_len = self.visible_rows().len(); + self.selected_idx = match visible_len { + 0 => None, + _ => Some(0), + }; + } + + /// Move selection cursor up. + pub(crate) fn move_up(&mut self) { + if let Some(idx) = self.selected_idx { + if idx > 0 { + self.selected_idx = Some(idx - 1); + } + } else if !self.visible_rows().is_empty() { + self.selected_idx = Some(0); + } + } + + /// Move selection cursor down. + pub(crate) fn move_down(&mut self) { + let len = self.visible_rows().len(); + if len == 0 { self.selected_idx = None; return; } + match self.selected_idx { + Some(idx) if idx + 1 < len => self.selected_idx = Some(idx + 1), + None => self.selected_idx = Some(0), + _ => {} + } + } + + /// Currently selected model name, if any. + pub(crate) fn selected_model(&self) -> Option { + let rows = self.visible_rows(); + self.selected_idx.and_then(|idx| match rows.get(idx) { + Some(DisplayRow::Model { name, .. }) => Some(name.clone()), + None => None, + }) + } + + /// Preferred height (rows) including border. + pub(crate) fn calculate_required_height(&self) -> u16 { + self.visible_rows().len().clamp(1, MAX_RESULTS) as u16 + } + + /// Compute rows to display applying fuzzy filtering and pinning current model. + fn visible_rows(&self) -> Vec { + // Build candidate list excluding the current model. + let mut others: Vec<&str> = self + .options + .iter() + .map(|s| s.as_str()) + .filter(|m| *m != self.current_model) + .collect(); + + // Keep original ordering for non-search. + if self.query.trim().is_empty() { + let mut rows: Vec = Vec::new(); + // Current model first. + rows.push(DisplayRow::Model { + name: self.current_model.clone(), + match_indices: None, + is_current: true, + }); + for name in others.drain(..) { + rows.push(DisplayRow::Model { + name: name.to_string(), + match_indices: None, + is_current: false, + }); + } + return rows; + } + + // Searching: include current model only if it matches. + let mut rows: Vec = Vec::new(); + if let Some(indices) = fuzzy_indices(&self.current_model, &self.query) { + rows.push(DisplayRow::Model { + name: self.current_model.clone(), + match_indices: Some(indices), + is_current: true, + }); + } + + // Fuzzy-match the rest and sort by score, then name, then match tightness. + let mut matches: Vec<(String, Vec, i32)> = Vec::new(); + for name in others.into_iter() { + if let Some((indices, score)) = fuzzy_match(name, &self.query) { + matches.push((name.to_string(), indices, score)); + } + } + matches.sort_by(|(a_name, a_idx, a_score), (b_name, b_idx, b_score)| { + a_score + .cmp(b_score) + .then_with(|| a_name.cmp(b_name)) + .then_with(|| a_idx.len().cmp(&b_idx.len())) + }); + + for (name, indices, _score) in matches.into_iter() { + if name != self.current_model { + rows.push(DisplayRow::Model { + name, + match_indices: Some(indices), + is_current: false, + }); + } + } + + rows + } +} + +/// Row in the model popup. +enum DisplayRow { + Model { + name: String, + match_indices: Option>, // indices to bold (char positions) + is_current: bool, + }, +} + +/// Return indices for a simple case-insensitive subsequence match and a score. +/// Smaller score is better. +fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec, i32)> { + if needle.is_empty() { + return Some((Vec::new(), i32::MAX)); + } + let h_lower = haystack.to_lowercase(); + let n_lower = needle.to_lowercase(); + let mut indices: Vec = Vec::with_capacity(n_lower.len()); + let mut h_iter = h_lower.char_indices(); + let mut last_pos: Option = None; + + for ch in n_lower.chars() { + let mut found = None; + for (i, hc) in h_iter.by_ref() { + if hc == ch { + found = Some(i); + break; + } + } + if let Some(pos) = found { + indices.push(pos); + last_pos = Some(pos); + } else { + return None; + } + } + + // Score: window length minus needle length (tighter is better), with a bonus for prefix match. + let first = *indices.first().unwrap_or(&0); + let last = last_pos.unwrap_or(first); + let window = (last as i32 - first as i32 + 1) - (n_lower.len() as i32); + let mut score = window.max(0); + if first == 0 { + score -= 100; // strong bonus for prefix match + } + Some((indices, score)) +} + +fn fuzzy_indices(haystack: &str, needle: &str) -> Option> { + fuzzy_match(haystack, needle).map(|(idx, _)| idx) +} + +impl WidgetRef for &ModelSelectionPopup { + fn render_ref(&self, area: Rect, buf: &mut Buffer) { + let rows_all = self.visible_rows(); + + let mut rows: Vec = Vec::new(); + if rows_all.is_empty() { + rows.push(Row::new(vec![Cell::from( + Line::from(Span::styled( + "no matches", + Style::default().add_modifier(Modifier::ITALIC | Modifier::DIM), + )), + )])); + } else { + for (i, row) in rows_all.into_iter().take(MAX_RESULTS).enumerate() { + match row { + DisplayRow::Model { + name, + match_indices, + is_current, + } => { + // Highlight fuzzy indices when present. + let mut spans: Vec = Vec::with_capacity(name.len()); + if let Some(idxs) = match_indices.as_ref() { + let mut idx_iter = idxs.iter().peekable(); + for (char_idx, ch) in name.chars().enumerate() { + let mut style = Style::default(); + if idx_iter.peek().is_some_and(|next| **next == char_idx) { + idx_iter.next(); + style = style.add_modifier(Modifier::BOLD); + } + spans.push(Span::styled(ch.to_string(), style)); + } + } else { + spans.push(Span::raw(name.clone())); + } + + let mut cell = Cell::from(Line::from(spans)); + if Some(i) == self.selected_idx { + cell = cell.style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)); + } else if is_current { + cell = cell.style(Style::default().fg(Color::Cyan)); + } + rows.push(Row::new(vec![cell])); + } + } + } + } + + let table = Table::new(rows, vec![Constraint::Percentage(100)]) + .block( + Block::default() + .borders(Borders::LEFT) + .border_type(BorderType::QuadrantOutside) + .border_style(Style::default().fg(Color::DarkGray)), + ) + .widths([Constraint::Percentage(100)]); + + table.render(area, buf); + } +} \ No newline at end of file diff --git a/codex-rs/tui/src/bottom_pane/model_selection_view.rs b/codex-rs/tui/src/bottom_pane/model_selection_view.rs deleted file mode 100644 index ed6d945008..0000000000 --- a/codex-rs/tui/src/bottom_pane/model_selection_view.rs +++ /dev/null @@ -1,442 +0,0 @@ -use crossterm::event::KeyCode; -use crossterm::event::KeyEvent; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use ratatui::style::Color; -use ratatui::style::Modifier; -use ratatui::style::Style; -use ratatui::text::Line; -use ratatui::text::Span; -use ratatui::widgets::Block; -use ratatui::widgets::BorderType; -use ratatui::widgets::Borders; -use ratatui::widgets::Cell; -use ratatui::widgets::Clear; -use ratatui::widgets::Row; -use ratatui::widgets::Table; -use ratatui::widgets::Widget; - -use crate::app_event::AppEvent; -use crate::app_event_sender::AppEventSender; - -use super::BottomPane; -use super::BottomPaneView; - -/// Simple dropdown to select a model. -pub(crate) struct ModelSelectionView { - /// Full list of models from provider (deduplicated). - options: Vec, - /// Current model pinned at the top of the list. - current_model: String, - /// Current zero-based selection index among rendered rows. - selected_idx: usize, - /// Query used to filter models via fuzzy match. - query: String, - is_complete: bool, - app_event_tx: AppEventSender, -} - -impl ModelSelectionView { - pub fn new(current_model: &str, app_event_tx: AppEventSender) -> Self { - // Initially no options; will be populated asynchronously. - Self { - options: Vec::new(), - current_model: current_model.to_string(), - selected_idx: 0, - query: String::new(), - is_complete: false, - app_event_tx, - } - } - - /// Produce the sequence of display rows respecting pinned current model, - /// sort preference, and search filter. - fn build_display_rows(&self) -> Vec { - // Determine candidate list excluding the current model (it is always pinned first). - let others: Vec<&str> = self - .options - .iter() - .map(|s| s.as_str()) - .filter(|m| *m != self.current_model) - .collect(); - - // If not searching, maintain provided ordering; otherwise, we'll score by fuzzy match. - if self.query.is_empty() { - let mut rows: Vec = Vec::new(); - // Pinned current model always first. - rows.push(DisplayRow::Model { - name: self.current_model.clone(), - match_indices: None, - is_current: true, - }); - if !others.is_empty() { - for name in others { - rows.push(DisplayRow::Model { - name: name.to_string(), - match_indices: None, - is_current: false, - }); - } - } - return rows; - } - - // Searching: only include current model if it matches the query. - let mut rows: Vec = Vec::new(); - if let Some(indices) = fuzzy_indices(&self.current_model, &self.query) { - rows.push(DisplayRow::Model { - name: self.current_model.clone(), - match_indices: Some(indices), - is_current: true, - }); - } - - // Build list of matches among others. - let mut matches: Vec<(String, Vec, i32)> = Vec::new(); - for name in others { - if let Some((indices, score)) = fuzzy_match(name, &self.query) { - matches.push((name.to_string(), indices, score)); - } - } - // Sort by score (ascending => better). If equal, fall back to alphabetical and match tightness. - matches.sort_by(|(a_name, a_idx, a_score), (b_name, b_idx, b_score)| { - a_score - .cmp(b_score) - .then_with(|| a_name.cmp(b_name)) - .then_with(|| a_idx.len().cmp(&b_idx.len())) - }); - - for (name, indices, _score) in matches { - // Don't duplicate the current model if it matched above - if name != self.current_model { - rows.push(DisplayRow::Model { - name, - match_indices: Some(indices), - is_current: false, - }); - } - } - - rows - } - - /// Count how many rows will be rendered (excluding the bottom stats line). - fn row_count(&self) -> usize { - let mut count = 0usize; - if self.query.is_empty() { - // current model + others - count += 1; // current - // Others count (excluding current) - let others = self - .options - .iter() - .filter(|m| m.as_str() != self.current_model) - .count(); - count + others - } else { - // searching: pinned current + matches - let mut matches = 1; // current always present - for name in self - .options - .iter() - .filter(|m| m.as_str() != self.current_model) - { - if fuzzy_match(name, &self.query).is_some() { - matches += 1; - } - } - matches - } - } - - /// Map selected_idx to a selected model name, if any. - fn selected_model(&self) -> Option { - if self.row_count() == 0 { - return None; - } - let rows = self.build_display_rows(); - match rows.get(self.selected_idx) { - Some(DisplayRow::Model { name, .. }) => Some(name.clone()), - _ => None, // no other placeholder rows are not selectable - } - } - - /// Compute the 1-based index of the selected model among all visible models (after filter). - fn selected_model_position(&self) -> Option { - let rows = self.build_display_rows(); - if self.selected_idx >= rows.len() { - return None; - } - let mut pos = 0usize; - for (i, row) in rows.iter().enumerate() { - if matches!(row, DisplayRow::Model { .. }) { - pos += 1; - } - if i == self.selected_idx { - return Some(pos); - } - } - None - } -} - -/// Row that can be rendered in the selector. -enum DisplayRow { - Model { - name: String, - match_indices: Option>, // indices to bold (char positions) - is_current: bool, - }, -} - -/// Return indices for a simple case-insensitive subsequence match and a score. -/// Smaller score is better. -fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec, i32)> { - if needle.is_empty() { - return Some((Vec::new(), i32::MAX)); - } - let h_lower = haystack.to_lowercase(); - let n_lower = needle.to_lowercase(); - let mut indices: Vec = Vec::with_capacity(n_lower.len()); - let mut h_iter = h_lower.char_indices(); - let mut last_pos: Option = None; - - for ch in n_lower.chars() { - let mut found = None; - for (i, hc) in h_iter.by_ref() { - if hc == ch { - found = Some(i); - break; - } - } - if let Some(pos) = found { - indices.push(pos); - last_pos = Some(pos); - } else { - return None; - } - } - - // Score: window length minus needle length (tighter is better), with a bonus for prefix match. - let first = *indices.first().unwrap_or(&0); - let last = last_pos.unwrap_or(first); - let window = (last as i32 - first as i32 + 1) - (n_lower.len() as i32); - let mut score = window.max(0); - if first == 0 { - score -= 100; // strong bonus for prefix match - } - Some((indices, score)) -} - -fn fuzzy_indices(haystack: &str, needle: &str) -> Option> { - fuzzy_match(haystack, needle).map(|(idx, _)| idx) -} - -impl<'a> BottomPaneView<'a> for ModelSelectionView { - fn handle_key_event(&mut self, _pane: &mut BottomPane<'a>, key_event: KeyEvent) { - match key_event.code { - KeyCode::Up => { - if self.selected_idx > 0 { - self.selected_idx -= 1; - } - } - KeyCode::Down => { - let max_idx = self.row_count().saturating_sub(1); - if self.selected_idx < max_idx { - self.selected_idx += 1; - } - } - KeyCode::Home => { - self.selected_idx = 0; - } - KeyCode::End => { - self.selected_idx = self.row_count().saturating_sub(1); - } - KeyCode::Enter => { - if let Some(model) = self.selected_model() { - self.app_event_tx.send(AppEvent::SelectModel(model)); - self.is_complete = true; - } - } - KeyCode::Esc => { - if self.query.is_empty() { - self.is_complete = true; - } else { - self.query.clear(); - self.selected_idx = 0; // reset on clear - } - } - KeyCode::Backspace => { - self.query.pop(); - // After editing, snap to first match if searching; otherwise clamp. - if self.query.is_empty() { - self.selected_idx = self.selected_idx.min(self.row_count().saturating_sub(1)); - } else { - self.selected_idx = if self.row_count() > 1 { 1 } else { 0 }; - } - } - KeyCode::Char(c) => { - // Append printable characters to the query. - if !c.is_control() { - self.query.push(c); - // When typing, move selection to first match (index 1 because 0 is pinned current). - self.selected_idx = if self.row_count() > 1 { 1 } else { 0 }; - } - } - _ => {} - } - } - - fn is_complete(&self) -> bool { - self.is_complete - } - - fn desired_height(&self, _width: u16) -> u16 { - const MAX_VISIBLE_ROWS: usize = 10; - let list_rows = self.row_count().min(MAX_VISIBLE_ROWS) as u16; - let stats_rows = 1u16; // persistent status line at bottom - let border_rows = 2u16; // top + bottom borders - list_rows + stats_rows + border_rows - } - - fn render(&self, area: Rect, buf: &mut Buffer) { - // Clear the area to prevent ghosting when the list height/width changes between frames. - Clear.render(area, buf); - - // Compute rows and counts. - let rows_all = self.build_display_rows(); - let total_rows = rows_all.len(); - let total_models = rows_all - .iter() - .filter(|r| matches!(r, DisplayRow::Model { .. })) - .count(); - let selected_model_pos = self.selected_model_position(); - - // Determine content height and rows available for the list (leave one row for stats). - let content_height = area.height.saturating_sub(2) as usize; // minus borders - let stats_rows = 1usize; // persistent status line at bottom - let list_window = content_height.saturating_sub(stats_rows); - - // Mutable self required to adjust scroll_offset; work with a local mutable copy via interior mutability - // is not necessary; instead compute desired offset and then render using that offset only. - let mut scroll_offset = 0usize; - if list_window > 0 { - // Ensure selected row is visible within [scroll_offset, scroll_offset + list_window) - if self.selected_idx < scroll_offset { - scroll_offset = self.selected_idx; - } else if self.selected_idx >= scroll_offset + list_window { - scroll_offset = self.selected_idx + 1 - list_window; - } - // Clamp to range. - if total_rows > list_window { - let max_offset = total_rows - list_window; - if scroll_offset > max_offset { - scroll_offset = max_offset; - } - } else { - scroll_offset = 0; - } - } else { - scroll_offset = 0; // no space for list; still show stats - } - - // Prepare visible rows slice for list portion. - let mut visible_rows: Vec = Vec::new(); - if list_window > 0 { - let end = (scroll_offset + list_window).min(total_rows); - for (abs_idx, row) in rows_all.iter().enumerate().take(end).skip(scroll_offset) { - match row { - DisplayRow::Model { - name, - match_indices, - is_current, - } => { - // Build spans for optional fuzzy highlight. - let mut spans: Vec = Vec::with_capacity(name.len()); - if let Some(idxs) = match_indices { - let mut idx_iter = idxs.iter().peekable(); - for (char_idx, ch) in name.chars().enumerate() { - let mut style = Style::default(); - if idx_iter.peek().is_some_and(|next| **next == char_idx) { - idx_iter.next(); - style = style.add_modifier(Modifier::BOLD); - } - spans.push(Span::styled(ch.to_string(), style)); - } - } else { - spans.push(Span::raw(name.clone())); - } - - let mut cell = Cell::from(Line::from(spans)); - // Selected row style takes precedence. - if abs_idx == self.selected_idx { - cell = cell.style( - Style::default() - .fg(Color::Yellow) - .add_modifier(Modifier::BOLD), - ); - } else if *is_current { - // Special color for the current model when not selected. - cell = cell.style(Style::default().fg(Color::Cyan)); - } - visible_rows.push(Row::new(vec![cell])); - } - } - } - - // Fill with blank rows if we have fewer rows than window size, so the stats line stays at bottom. - while visible_rows.len() < list_window { - visible_rows.push(Row::new(vec![Cell::from(" ")])); - } - } - - // Stats line text: selected position / total models. - let stats_text = match selected_model_pos { - Some(pos) => format!(" {pos}/{total_models} models "), - None => format!(" -/{total_models} models "), - }; - let mut stats_row = Row::new(vec![Cell::from(stats_text)]); - stats_row = stats_row.style(Style::default().fg(Color::DarkGray)); - visible_rows.push(stats_row); - - let mut title = String::from(" Select model "); - if !self.query.is_empty() { - title.push(' '); - title.push('('); - title.push_str(&self.query); - title.push(')'); - } - - let table = Table::new( - visible_rows, - vec![ratatui::prelude::Constraint::Percentage(100)], - ) - .block( - Block::default() - .title(title) - .borders(Borders::ALL) - .border_type(BorderType::Rounded), - ) - .widths([ratatui::prelude::Constraint::Percentage(100)]); - - table.render(area, buf); - } - - fn set_model_options(&mut self, current_model: &str, options: Vec) -> bool { - self.current_model = current_model.to_string(); - // Deduplicate while preserving first occurrence order. - let mut seen = std::collections::HashSet::new(); - let mut unique: Vec = Vec::with_capacity(options.len()); - for m in options.into_iter() { - if seen.insert(m.clone()) { - unique.push(m); - } - } - // Preserve provided ordering without applying preference ranking. - self.options = unique; - - // Clamp selection to available rows. - self.selected_idx = self.selected_idx.min(self.row_count().saturating_sub(1)); - true - } -} From 56e95f7ec7fc0b37f860abfd07182dd307ca82f8 Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 31 Jul 2025 21:54:42 +0100 Subject: [PATCH 13/18] scrollable model list --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 13 ++++++----- .../src/bottom_pane/model_selection_popup.rs | 22 +++++++++++-------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 0e7108311d..60e6aae813 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -23,8 +23,8 @@ use super::model_selection_popup::ModelSelectionPopup; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; -use codex_file_search::FileMatch; use crate::slash_command::SlashCommand; +use codex_file_search::FileMatch; const BASE_PLACEHOLDER_TEXT: &str = "..."; /// If the pasted content exceeds this number of characters, replace it with a @@ -185,7 +185,8 @@ impl ChatComposer<'_> { popup.set_options(current_model, options); } _ => { - self.active_popup = ActivePopup::Model(ModelSelectionPopup::new(current_model, options)); + self.active_popup = + ActivePopup::Model(ModelSelectionPopup::new(current_model, options)); } } // Initialize/update the query from the composer. @@ -380,7 +381,8 @@ impl ChatComposer<'_> { ctrl: false, alt: false, shift: false, - } => { + } + | Input { key: Key::Tab, .. } => { if let Some(model) = popup.selected_model() { self.app_event_tx.send(AppEvent::SelectModel(model)); // Clear composer input and close the popup. @@ -705,9 +707,9 @@ impl ChatComposer<'_> { // Switch away from command popup and request opening the model selector. self.active_popup = ActivePopup::None; self.app_event_tx.send(AppEvent::OpenModelSelector); - return; + } else { + popup.on_composer_text_change(first_line.to_string()); } - popup.on_composer_text_change(first_line.to_string()); } else { self.active_popup = ActivePopup::None; } @@ -717,7 +719,6 @@ impl ChatComposer<'_> { if should_open_model_selector { // Request the app to open the model selector; popup will render once options arrive. self.app_event_tx.send(AppEvent::OpenModelSelector); - return; } else { let mut command_popup = CommandPopup::new(); command_popup.on_composer_text_change(first_line.to_string()); diff --git a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs index 258cd8d757..980c337e5f 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs @@ -43,7 +43,9 @@ impl ModelSelectionPopup { /// Update the fuzzy filter query. pub(crate) fn set_query(&mut self, query: &str) { - if self.query == query { return; } + if self.query == query { + return; + } self.query.clear(); self.query.push_str(query); // Reset/clamp selection based on new filtered list. @@ -215,12 +217,10 @@ impl WidgetRef for &ModelSelectionPopup { let mut rows: Vec = Vec::new(); if rows_all.is_empty() { - rows.push(Row::new(vec![Cell::from( - Line::from(Span::styled( - "no matches", - Style::default().add_modifier(Modifier::ITALIC | Modifier::DIM), - )), - )])); + rows.push(Row::new(vec![Cell::from(Line::from(Span::styled( + "no matches", + Style::default().add_modifier(Modifier::ITALIC | Modifier::DIM), + )))])); } else { for (i, row) in rows_all.into_iter().take(MAX_RESULTS).enumerate() { match row { @@ -247,7 +247,11 @@ impl WidgetRef for &ModelSelectionPopup { let mut cell = Cell::from(Line::from(spans)); if Some(i) == self.selected_idx { - cell = cell.style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)); + cell = cell.style( + Style::default() + .fg(Color::Yellow) + .add_modifier(Modifier::BOLD), + ); } else if is_current { cell = cell.style(Style::default().fg(Color::Cyan)); } @@ -268,4 +272,4 @@ impl WidgetRef for &ModelSelectionPopup { table.render(area, buf); } -} \ No newline at end of file +} From 4e2cf0bb7a84cad8858f6953aaec2a0f697b32c6 Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 31 Jul 2025 22:28:54 +0100 Subject: [PATCH 14/18] can set non default models --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 43 +++++++++++++++++++ .../src/bottom_pane/model_selection_popup.rs | 10 +++-- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 60e6aae813..5f6a189ffe 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -256,6 +256,16 @@ impl ChatComposer<'_> { self.textarea.select_all(); self.textarea.cut(); let _ = self.textarea.insert_str(format!("/{} ", cmd.command())); + } else { + // Special case: if the command is `/model` and the line is exactly "/model" + // (no trailing space), add a space to trigger the model dropdown. + if *cmd == SlashCommand::Model { + let trimmed = first_line.trim_start(); + let expected = format!("/{}", cmd.command()); + if trimmed == expected { + let _ = self.textarea.insert_str(" "); + } + } } } (InputResult::None, true) @@ -392,6 +402,39 @@ impl ChatComposer<'_> { self.active_popup = ActivePopup::None; return (InputResult::None, true); } + // No selection in the list: treat the typed argument as the model name. + // Extract arguments after `/model` from the first line. + let first_line = self + .textarea + .lines() + .first() + .map(|s| s.as_str()) + .unwrap_or(""); + + let args = if let Some(stripped) = first_line.strip_prefix('/') { + let token = stripped.trim_start(); + let cmd_token = token.split_whitespace().next().unwrap_or(""); + if cmd_token == SlashCommand::Model.command() { + let rest = &token[cmd_token.len()..]; + rest.trim_start().to_string() + } else { + String::new() + } + } else { + String::new() + }; + + if !args.trim().is_empty() { + // Dispatch as a command with args so normalization is applied centrally. + self.app_event_tx + .send(AppEvent::DispatchCommandWithArgs(SlashCommand::Model, args)); + // Clear composer input and close the popup. + self.textarea.select_all(); + self.textarea.cut(); + self.pending_pastes.clear(); + self.active_popup = ActivePopup::None; + return (InputResult::None, true); + } (InputResult::None, false) } input => self.handle_input_basic(input), diff --git a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs index 980c337e5f..27aec5abc3 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs @@ -70,7 +70,10 @@ impl ModelSelectionPopup { /// Move selection cursor down. pub(crate) fn move_down(&mut self) { let len = self.visible_rows().len(); - if len == 0 { self.selected_idx = None; return; } + if len == 0 { + self.selected_idx = None; + return; + } match self.selected_idx { Some(idx) if idx + 1 < len => self.selected_idx = Some(idx + 1), None => self.selected_idx = Some(0), @@ -81,9 +84,8 @@ impl ModelSelectionPopup { /// Currently selected model name, if any. pub(crate) fn selected_model(&self) -> Option { let rows = self.visible_rows(); - self.selected_idx.and_then(|idx| match rows.get(idx) { - Some(DisplayRow::Model { name, .. }) => Some(name.clone()), - None => None, + self.selected_idx.and_then(|idx| { + rows.get(idx).map(|DisplayRow::Model { name, .. }| name.clone()) }) } From 507f79deac2ebdb876225379653f739b5c2d95ca Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 31 Jul 2025 22:34:12 +0100 Subject: [PATCH 15/18] linter --- codex-rs/tui/src/bottom_pane/model_selection_popup.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs index 27aec5abc3..9c31c5bf49 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs @@ -85,7 +85,8 @@ impl ModelSelectionPopup { pub(crate) fn selected_model(&self) -> Option { let rows = self.visible_rows(); self.selected_idx.and_then(|idx| { - rows.get(idx).map(|DisplayRow::Model { name, .. }| name.clone()) + rows.get(idx) + .map(|DisplayRow::Model { name, .. }| name.clone()) }) } From 1afa537148f943195dc86fba35086aa1bfc54e39 Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 31 Jul 2025 22:48:51 +0100 Subject: [PATCH 16/18] remove useless code --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 64 ++++++++----------- 1 file changed, 27 insertions(+), 37 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 5f6a189ffe..3c61a27bf8 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -256,16 +256,6 @@ impl ChatComposer<'_> { self.textarea.select_all(); self.textarea.cut(); let _ = self.textarea.insert_str(format!("/{} ", cmd.command())); - } else { - // Special case: if the command is `/model` and the line is exactly "/model" - // (no trailing space), add a space to trigger the model dropdown. - if *cmd == SlashCommand::Model { - let trimmed = first_line.trim_start(); - let expected = format!("/{}", cmd.command()); - if trimmed == expected { - let _ = self.textarea.insert_str(" "); - } - } } } (InputResult::None, true) @@ -285,30 +275,19 @@ impl ChatComposer<'_> { .map(|s| s.as_str()) .unwrap_or(""); - let args = if let Some(stripped) = first_line.strip_prefix('/') { - let token = stripped.trim_start(); - let cmd_token = token.split_whitespace().next().unwrap_or(""); - let rest = &token[cmd_token.len()..]; - rest.trim_start().to_string() + let args = if let Some((_, args)) = + Self::parse_slash_command_and_args_from_line(first_line) + { + args } else { String::new() }; - // If `/model` has no args, autocomplete to "/model " and open the model selector. - if *cmd == SlashCommand::Model && args.trim().is_empty() { - self.textarea.select_all(); - self.textarea.cut(); - let _ = self.textarea.insert_str(format!("/{} ", cmd.command())); - // Hide the command popup; model popup will be shown by sync_command_popup. - self.active_popup = ActivePopup::None; - return (InputResult::None, true); - } - // Send command + args to the app layer. self.app_event_tx .send(AppEvent::DispatchCommandWithArgs(*cmd, args)); - // Clear textarea so no residual text remains (default behavior). + // Clear textarea so no residual text remains self.textarea.select_all(); self.textarea.cut(); @@ -411,12 +390,11 @@ impl ChatComposer<'_> { .map(|s| s.as_str()) .unwrap_or(""); - let args = if let Some(stripped) = first_line.strip_prefix('/') { - let token = stripped.trim_start(); - let cmd_token = token.split_whitespace().next().unwrap_or(""); + let args = if let Some((cmd_token, args)) = + Self::parse_slash_command_and_args_from_line(first_line) + { if cmd_token == SlashCommand::Model.command() { - let rest = &token[cmd_token.len()..]; - rest.trim_start().to_string() + args } else { String::new() } @@ -819,14 +797,10 @@ impl ChatComposer<'_> { .unwrap_or(""); // Expect `/model` as the first token on the first line. - if let Some(stripped) = first_line.strip_prefix('/') { - let token = stripped.trim_start(); - let cmd_token = token.split_whitespace().next().unwrap_or(""); + if let Some((cmd_token, args)) = Self::parse_slash_command_and_args_from_line(first_line) { if cmd_token == SlashCommand::Model.command() { - let rest = &token[cmd_token.len()..]; - let args = rest.trim_start(); if let ActivePopup::Model(popup) = &mut self.active_popup { - popup.set_query(args); + popup.set_query(&args); } return; } @@ -838,6 +812,22 @@ impl ChatComposer<'_> { } } + /// Parse a leading "/command" and return (command_token, args_trimmed_left). + /// Returns None if the line does not start with a slash or the command is empty. + fn parse_slash_command_and_args_from_line(line: &str) -> Option<(String, String)> { + if let Some(stripped) = line.strip_prefix('/') { + let token = stripped.trim_start(); + let cmd_token = token.split_whitespace().next().unwrap_or(""); + if cmd_token.is_empty() { + return None; + } + let rest = &token[cmd_token.len()..]; + Some((cmd_token.to_string(), rest.trim_start().to_string())) + } else { + None + } + } + fn update_border(&mut self, has_focus: bool) { let border_style = if has_focus { Style::default().fg(Color::Cyan) From 145688f019739930e6d3b6368234a12d8ecebad1 Mon Sep 17 00:00:00 2001 From: pap Date: Thu, 31 Jul 2025 23:09:55 +0100 Subject: [PATCH 17/18] linter --- .../tui/src/bottom_pane/model_selection_popup.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs index 9c31c5bf49..b220cad59c 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs @@ -1,9 +1,19 @@ use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::prelude::Constraint; -use ratatui::style::{Color, Modifier, Style}; -use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, BorderType, Borders, Cell, Row, Table, Widget, WidgetRef}; +use ratatui::style::Color; +use ratatui::style::Modifier; +use ratatui::style::Style; +use ratatui::text::Line; +use ratatui::text::Span; +use ratatui::widgets::Block; +use ratatui::widgets::BorderType; +use ratatui::widgets::Borders; +use ratatui::widgets::Cell; +use ratatui::widgets::Row; +use ratatui::widgets::Table; +use ratatui::widgets::Widget; +use ratatui::widgets::WidgetRef; /// Maximum number of options shown in the popup. const MAX_RESULTS: usize = 8; From 8dea0e4cd253a8e7f42263e34c3a60e0651a42b0 Mon Sep 17 00:00:00 2001 From: pap Date: Fri, 1 Aug 2025 00:04:24 +0100 Subject: [PATCH 18/18] fuzzy is now a common lib + toml alphabetical order --- codex-rs/Cargo.lock | 12 +- codex-rs/common/src/fuzzy_match.rs | 49 +++++++ codex-rs/common/src/lib.rs | 2 + codex-rs/file-search/Cargo.toml | 2 +- codex-rs/file-search/src/lib.rs | 120 +++++------------- codex-rs/tui/Cargo.toml | 2 +- .../src/bottom_pane/model_selection_popup.rs | 45 +------ 7 files changed, 91 insertions(+), 141 deletions(-) create mode 100644 codex-rs/common/src/fuzzy_match.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 90e02e3670..7755e254fe 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -763,8 +763,8 @@ version = "0.0.0" dependencies = [ "anyhow", "clap", + "codex-common", "ignore", - "nucleo-matcher", "serde", "serde_json", "tokio", @@ -2798,16 +2798,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "nucleo-matcher" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf33f538733d1a5a3494b836ba913207f14d9d4a1d3cd67030c5061bdd2cac85" -dependencies = [ - "memchr", - "unicode-segmentation", -] - [[package]] name = "num-bigint" version = "0.4.6" diff --git a/codex-rs/common/src/fuzzy_match.rs b/codex-rs/common/src/fuzzy_match.rs new file mode 100644 index 0000000000..986f6cefe2 --- /dev/null +++ b/codex-rs/common/src/fuzzy_match.rs @@ -0,0 +1,49 @@ +/// Simple case-insensitive subsequence matcher used for fuzzy filtering. +/// +/// Returns the indices (positions) of the matched characters in `haystack` +/// and a score where smaller is better. Currently, indices are byte offsets +/// from `char_indices()` of a lowercased copy of `haystack`. +/// +/// Note: For ASCII inputs these indices align with character positions. If +/// extended Unicode inputs are used, be mindful of byte vs char indices. +pub fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec, i32)> { + if needle.is_empty() { + return Some((Vec::new(), i32::MAX)); + } + let h_lower = haystack.to_lowercase(); + let n_lower = needle.to_lowercase(); + let mut indices: Vec = Vec::with_capacity(n_lower.len()); + let mut h_iter = h_lower.char_indices(); + let mut last_pos: Option = None; + + for ch in n_lower.chars() { + let mut found = None; + for (i, hc) in h_iter.by_ref() { + if hc == ch { + found = Some(i); + break; + } + } + if let Some(pos) = found { + indices.push(pos); + last_pos = Some(pos); + } else { + return None; + } + } + + // Score: window length minus needle length (tighter is better), with a bonus for prefix match. + let first = *indices.first().unwrap_or(&0); + let last = last_pos.unwrap_or(first); + let window = (last as i32 - first as i32 + 1) - (n_lower.len() as i32); + let mut score = window.max(0); + if first == 0 { + score -= 100; // strong bonus for prefix match + } + Some((indices, score)) +} + +/// Convenience wrapper to get only the indices for a fuzzy match. +pub fn fuzzy_indices(haystack: &str, needle: &str) -> Option> { + fuzzy_match(haystack, needle).map(|(idx, _)| idx) +} diff --git a/codex-rs/common/src/lib.rs b/codex-rs/common/src/lib.rs index 3d498a8e2c..c6c71d2f62 100644 --- a/codex-rs/common/src/lib.rs +++ b/codex-rs/common/src/lib.rs @@ -23,3 +23,5 @@ mod sandbox_summary; #[cfg(feature = "sandbox_summary")] pub use sandbox_summary::summarize_sandbox_policy; + +pub mod fuzzy_match; diff --git a/codex-rs/file-search/Cargo.toml b/codex-rs/file-search/Cargo.toml index 3f70377183..2d2a51f53f 100644 --- a/codex-rs/file-search/Cargo.toml +++ b/codex-rs/file-search/Cargo.toml @@ -14,8 +14,8 @@ path = "src/lib.rs" [dependencies] anyhow = "1" clap = { version = "4", features = ["derive"] } +codex-common = { path = "../common" } ignore = "0.4.23" -nucleo-matcher = "0.3.1" serde = { version = "1", features = ["derive"] } serde_json = "1.0.110" tokio = { version = "1", features = ["full"] } diff --git a/codex-rs/file-search/src/lib.rs b/codex-rs/file-search/src/lib.rs index e0eb87656b..8c439dddf1 100644 --- a/codex-rs/file-search/src/lib.rs +++ b/codex-rs/file-search/src/lib.rs @@ -1,14 +1,9 @@ +use codex_common::fuzzy_match::fuzzy_indices as common_fuzzy_indices; +use codex_common::fuzzy_match::fuzzy_match as common_fuzzy_match; use ignore::WalkBuilder; use ignore::overrides::OverrideBuilder; -use nucleo_matcher::Matcher; -use nucleo_matcher::Utf32Str; -use nucleo_matcher::pattern::AtomKind; -use nucleo_matcher::pattern::CaseMatching; -use nucleo_matcher::pattern::Normalization; -use nucleo_matcher::pattern::Pattern; use serde::Serialize; use std::cell::UnsafeCell; -use std::cmp::Reverse; use std::collections::BinaryHeap; use std::num::NonZero; use std::path::Path; @@ -24,17 +19,13 @@ pub use cli::Cli; /// A single match result returned from the search. /// -/// * `score` – Relevance score returned by `nucleo_matcher`. +/// * `score` – Relevance score from the fuzzy matcher (smaller is better). /// * `path` – Path to the matched file (relative to the search directory). -/// * `indices` – Optional list of character indices that matched the query. -/// These are only filled when the caller of [`run`] sets -/// `compute_indices` to `true`. The indices vector follows the -/// guidance from `nucleo_matcher::Pattern::indices`: they are -/// unique and sorted in ascending order so that callers can use -/// them directly for highlighting. +/// * `indices` – Optional list of character positions that matched the query. +/// These are unique and sorted so callers can use them directly for highlighting. #[derive(Debug, Clone, Serialize)] pub struct FileMatch { - pub score: u32, + pub score: i32, pub path: String, #[serde(skip_serializing_if = "Option::is_none")] pub indices: Option>, // Sorted & deduplicated when present @@ -130,7 +121,6 @@ pub fn run( cancel_flag: Arc, compute_indices: bool, ) -> anyhow::Result { - let pattern = create_pattern(pattern_text); // Create one BestMatchesList per worker thread so that each worker can // operate independently. The results across threads will be merged when // the traversal is complete. @@ -139,13 +129,7 @@ pub fn run( num_best_matches_lists, } = create_worker_count(threads); let best_matchers_per_worker: Vec> = (0..num_best_matches_lists) - .map(|_| { - UnsafeCell::new(BestMatchesList::new( - limit.get(), - pattern.clone(), - Matcher::new(nucleo_matcher::Config::DEFAULT), - )) - }) + .map(|_| UnsafeCell::new(BestMatchesList::new(limit.get(), pattern_text.to_string()))) .collect(); // Use the same tree-walker library that ripgrep uses. We use it directly so @@ -220,47 +204,33 @@ pub fn run( } // Merge results across best_matchers_per_worker. - let mut global_heap: BinaryHeap> = BinaryHeap::new(); + let mut global_heap: BinaryHeap<(i32, String)> = BinaryHeap::new(); let mut total_match_count = 0; for best_list_cell in best_matchers_per_worker.iter() { let best_list = unsafe { &*best_list_cell.get() }; total_match_count += best_list.num_matches; - for &Reverse((score, ref line)) in best_list.binary_heap.iter() { + for &(score, ref line) in best_list.binary_heap.iter() { if global_heap.len() < limit.get() { - global_heap.push(Reverse((score, line.clone()))); - } else if let Some(min_element) = global_heap.peek() { - if score > min_element.0.0 { + global_heap.push((score, line.clone())); + } else if let Some(&(worst_score, _)) = global_heap.peek() { + if score < worst_score { global_heap.pop(); - global_heap.push(Reverse((score, line.clone()))); + global_heap.push((score, line.clone())); } } } } - let mut raw_matches: Vec<(u32, String)> = global_heap.into_iter().map(|r| r.0).collect(); + let mut raw_matches: Vec<(i32, String)> = global_heap.into_iter().collect(); sort_matches(&mut raw_matches); // Transform into `FileMatch`, optionally computing indices. - let mut matcher = if compute_indices { - Some(Matcher::new(nucleo_matcher::Config::DEFAULT)) - } else { - None - }; - let matches: Vec = raw_matches .into_iter() .map(|(score, path)| { let indices = if compute_indices { - let mut buf = Vec::::new(); - let haystack: Utf32Str<'_> = Utf32Str::new(&path, &mut buf); - let mut idx_vec: Vec = Vec::new(); - if let Some(ref mut m) = matcher { - // Ignore the score returned from indices – we already have `score`. - pattern.indices(haystack, m, &mut idx_vec); - } - idx_vec.sort_unstable(); - idx_vec.dedup(); - Some(idx_vec) + common_fuzzy_indices(&path, pattern_text) + .map(|v| v.into_iter().map(|i| i as u32).collect()) } else { None }; @@ -279,9 +249,9 @@ pub fn run( }) } -/// Sort matches in-place by descending score, then ascending path. -fn sort_matches(matches: &mut [(u32, String)]) { - matches.sort_by(|a, b| match b.0.cmp(&a.0) { +/// Sort matches in-place by ascending score, then ascending path. +fn sort_matches(matches: &mut [(i32, String)]) { + matches.sort_by(|a, b| match a.0.cmp(&b.0) { std::cmp::Ordering::Equal => a.1.cmp(&b.1), other => other, }); @@ -291,39 +261,31 @@ fn sort_matches(matches: &mut [(u32, String)]) { struct BestMatchesList { max_count: usize, num_matches: usize, - pattern: Pattern, - matcher: Matcher, - binary_heap: BinaryHeap>, - - /// Internal buffer for converting strings to UTF-32. - utf32buf: Vec, + pattern: String, + binary_heap: BinaryHeap<(i32, String)>, } impl BestMatchesList { - fn new(max_count: usize, pattern: Pattern, matcher: Matcher) -> Self { + fn new(max_count: usize, pattern: String) -> Self { Self { max_count, num_matches: 0, pattern, - matcher, binary_heap: BinaryHeap::new(), - utf32buf: Vec::::new(), } } fn insert(&mut self, line: &str) { - let haystack: Utf32Str<'_> = Utf32Str::new(line, &mut self.utf32buf); - if let Some(score) = self.pattern.score(haystack, &mut self.matcher) { - // In the tests below, we verify that score() returns None for a - // non-match, so we can categorically increment the count here. + if let Some((_indices, score)) = common_fuzzy_match(line, &self.pattern) { + // Count all matches; non-matches return None above. self.num_matches += 1; if self.binary_heap.len() < self.max_count { - self.binary_heap.push(Reverse((score, line.to_string()))); - } else if let Some(min_element) = self.binary_heap.peek() { - if score > min_element.0.0 { + self.binary_heap.push((score, line.to_string())); + } else if let Some(&(worst_score, _)) = self.binary_heap.peek() { + if score < worst_score { self.binary_heap.pop(); - self.binary_heap.push(Reverse((score, line.to_string()))); + self.binary_heap.push((score, line.to_string())); } } } @@ -354,28 +316,16 @@ fn create_worker_count(num_workers: NonZero) -> WorkerCount { } } -fn create_pattern(pattern: &str) -> Pattern { - Pattern::new( - pattern, - CaseMatching::Smart, - Normalization::Smart, - AtomKind::Fuzzy, - ) -} - #[cfg(test)] mod tests { use super::*; #[test] - fn verify_score_is_none_for_non_match() { - let mut utf32buf = Vec::::new(); - let line = "hello"; - let mut matcher = Matcher::new(nucleo_matcher::Config::DEFAULT); - let haystack: Utf32Str<'_> = Utf32Str::new(line, &mut utf32buf); - let pattern = create_pattern("zzz"); - let score = pattern.score(haystack, &mut matcher); - assert_eq!(score, None); + fn verify_no_match_does_not_increment_or_push() { + let mut list = BestMatchesList::new(5, "zzz".to_string()); + list.insert("hello"); + assert_eq!(list.num_matches, 0); + assert_eq!(list.binary_heap.len(), 0); } #[test] @@ -388,11 +338,11 @@ mod tests { sort_matches(&mut matches); - // Highest score first; ties broken alphabetically. + // Lowest score first; ties broken alphabetically. let expected = vec![ + (90, "zzz".to_string()), (100, "a_path".to_string()), (100, "b_path".to_string()), - (90, "zzz".to_string()), ]; assert_eq!(matches, expected); diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 31a0705f6c..5f0250ffce 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -52,6 +52,7 @@ tokio = { version = "1", features = [ "rt-multi-thread", "signal", ] } +toml = "0.8" tracing = { version = "0.1.41", features = ["log"] } tracing-appender = "0.2.3" tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } @@ -61,7 +62,6 @@ tui-textarea = "0.7.0" unicode-segmentation = "1.12.0" unicode-width = "0.1" uuid = "1" -toml = "0.8" [dev-dependencies] insta = "1.43.1" diff --git a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs index b220cad59c..c20d5d8100 100644 --- a/codex-rs/tui/src/bottom_pane/model_selection_popup.rs +++ b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs @@ -1,3 +1,5 @@ +use codex_common::fuzzy_match::fuzzy_indices; +use codex_common::fuzzy_match::fuzzy_match; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::prelude::Constraint; @@ -181,49 +183,6 @@ enum DisplayRow { }, } -/// Return indices for a simple case-insensitive subsequence match and a score. -/// Smaller score is better. -fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec, i32)> { - if needle.is_empty() { - return Some((Vec::new(), i32::MAX)); - } - let h_lower = haystack.to_lowercase(); - let n_lower = needle.to_lowercase(); - let mut indices: Vec = Vec::with_capacity(n_lower.len()); - let mut h_iter = h_lower.char_indices(); - let mut last_pos: Option = None; - - for ch in n_lower.chars() { - let mut found = None; - for (i, hc) in h_iter.by_ref() { - if hc == ch { - found = Some(i); - break; - } - } - if let Some(pos) = found { - indices.push(pos); - last_pos = Some(pos); - } else { - return None; - } - } - - // Score: window length minus needle length (tighter is better), with a bonus for prefix match. - let first = *indices.first().unwrap_or(&0); - let last = last_pos.unwrap_or(first); - let window = (last as i32 - first as i32 + 1) - (n_lower.len() as i32); - let mut score = window.max(0); - if first == 0 { - score -= 100; // strong bonus for prefix match - } - Some((indices, score)) -} - -fn fuzzy_indices(haystack: &str, needle: &str) -> Option> { - fuzzy_match(haystack, needle).map(|(idx, _)| idx) -} - impl WidgetRef for &ModelSelectionPopup { fn render_ref(&self, area: Rect, buf: &mut Buffer) { let rows_all = self.visible_rows();