diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 9123bd6374..b88048f66c 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", @@ -865,6 +865,7 @@ dependencies = [ "strum 0.27.2", "strum_macros 0.27.2", "tokio", + "toml 0.8.23", "tracing", "tracing-appender", "tracing-subscriber", @@ -2799,16 +2800,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" @@ -4766,6 +4757,7 @@ dependencies = [ "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", + "toml_write", "winnow", ] @@ -4778,6 +4770,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/README.md b/codex-rs/README.md index b25b5cf2cc..81fda73d58 100644 --- a/codex-rs/README.md +++ b/codex-rs/README.md @@ -43,6 +43,10 @@ To run Codex non-interactively, run `codex exec PROMPT` (you can also pass the p Typing `@` triggers a fuzzy-filename search over the workspace root. Use up/down to select among the results and Tab or Enter to replace the `@` with the selected path. You can use Esc to cancel the search. +### Slash commands and model selection + +Type `/` in the composer to open a command menu. Navigate with Up/Down and press Tab or Enter to apply a command. The list supports filtering by typing after the slash. Use `/model` to select or change the active model; after typing `/model ` (note the space), a model selector appears with fuzzy filtering and keyboard navigation. Press Enter or Tab to apply the selection. + ### `--cd`/`-C` flag Sometimes it is not convenient to `cd` to the directory you want Codex to use as the "working root" before running Codex. Fortunately, `codex` supports a `--cd` option so you can specify whatever folder you want. You can confirm that Codex is honoring `--cd` by double-checking the **workdir** it reports in the TUI at the start of a new session. 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/core/src/codex.rs b/codex-rs/core/src/codex.rs index 5d48cd457f..391394eb5a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -124,20 +124,8 @@ 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); @@ -720,8 +708,14 @@ async fn submission_loop( } }; + let client_config = { + let mut c = (*config).clone(); + c.model = model.clone(); + Arc::new(c) + }; + let client = ModelClient::new( - config.clone(), + client_config, auth.clone(), provider.clone(), model_reasoning_effort, diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index 1b8da89419..63ed9d64e4 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -14,6 +14,7 @@ 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::Op; use crate::protocol::SandboxPolicy; use dirs::home_dir; use serde::Deserialize; @@ -185,6 +186,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 a33e185afb..9320cf3f76 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/core/src/openai_model_info.rs b/codex-rs/core/src/openai_model_info.rs index 9ffd831a91..0f97c1334d 100644 --- a/codex-rs/core/src/openai_model_info.rs +++ b/codex-rs/core/src/openai_model_info.rs @@ -69,3 +69,8 @@ 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-mini-latest", "o3", "o4-mini", "gpt-4.1", "gpt-4o"] +} 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 468f2f3be6..f51b5bc169 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"] } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index efaec7f19a..8981afa493 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -45,6 +45,28 @@ 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: '…', "…", ‘…’, “…”. +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; + } + + 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]; + } + } + + t +} + pub(crate) struct App<'a> { app_event_tx: AppEventSender, app_event_rx: Receiver, @@ -279,6 +301,16 @@ impl App<'_> { AppEvent::ExitRequest => { break; } + AppEvent::SelectModel(model) => { + if let AppState::Chat { widget } = &mut self.app_state { + 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 { .. } => {} @@ -368,6 +400,34 @@ impl App<'_> { ), })); } + SlashCommand::Model => { + // Disallow `/model` without arguments; no action. + } + }, + AppEvent::DispatchCommandWithArgs(command, args) => match command { + SlashCommand::Model => { + let arg = args.trim(); + 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); + } + } + } + #[cfg(debug_assertions)] + SlashCommand::TestApproval => { + // Ignore args; forward to the existing no-args handler + self.app_event_tx.send(AppEvent::DispatchCommand(command)); + } + SlashCommand::New + | SlashCommand::Quit + | SlashCommand::Diff + | SlashCommand::Compact => { + // 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); @@ -498,3 +558,44 @@ 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}'"); + } + } +} diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 77a600d304..8b60a12815 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -34,6 +34,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. @@ -48,4 +52,10 @@ pub(crate) enum AppEvent { }, InsertHistory(Vec>), + + /// 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/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 2498154b5f..7bbf615776 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -19,9 +19,11 @@ 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 crate::slash_command::SlashCommand; use codex_file_search::FileMatch; const BASE_PLACEHOLDER_TEXT: &str = "..."; @@ -53,6 +55,7 @@ enum ActivePopup { None, Command(CommandPopup), File(FileSearchPopup), + Model(ModelSelectionPopup), } impl ChatComposer<'_> { @@ -178,6 +181,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(), } } @@ -272,15 +276,62 @@ 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)); + } + } + // If the composer currently contains a `/model` command, initialize the + // popup's query from its arguments. Otherwise, leave the popup visible + // with an empty query. + let first_line = self + .textarea + .lines() + .first() + .map(|s| s.as_str()) + .unwrap_or(""); + if let Some((cmd_token, args)) = Self::parse_slash_command_and_args_from_line(first_line) { + if cmd_token == SlashCommand::Model.command() { + if let ActivePopup::Model(popup) = &mut self.active_popup { + popup.set_query(&args); + } + } + } + } + /// 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), }; - self.sync_popups(); + // Update (or hide/show) popup after processing the key. + 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 } @@ -329,7 +380,32 @@ impl ChatComposer<'_> { ctrl: false, } => { if let Some(cmd) = popup.selected_command() { - 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((_, args)) = + Self::parse_slash_command_and_args_from_line(first_line) + { + args + } else { + String::new() + }; + + // Special case: selecting `/model` without args should open the model selector. + if *cmd == SlashCommand::Model && args.trim().is_empty() { + self.app_event_tx.send(AppEvent::OpenModelSelector); + } else { + // 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(); self.textarea.cut(); self.active_popup = ActivePopup::None; @@ -388,6 +464,80 @@ 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, + } + | 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. + self.textarea.select_all(); + self.textarea.cut(); + self.pending_pastes.clear(); + 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((cmd_token, args)) = + Self::parse_slash_command_and_args_from_line(first_line) + { + if cmd_token == SlashCommand::Model.command() { + args + } 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), + } + } + /// Extract the `@token` that the cursor is currently positioned on, if any. /// /// The returned string **does not** include the leading `@`. @@ -614,10 +764,33 @@ impl ChatComposer<'_> { self.dismissed_slash_token = None; } let current_cmd_token: Option<&str> = Self::slash_token_from_first_line(&first_line); + + // 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 { - popup.on_composer_text_change(first_line.clone()); + 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); + } else { + popup.on_composer_text_change(first_line.clone()); + } } else { self.active_popup = ActivePopup::None; self.dismissed_slash_token = None; @@ -625,12 +798,20 @@ impl ChatComposer<'_> { } _ => { if input_starts_with_slash { - if self.dismissed_slash_token.as_deref() == current_cmd_token { - return; + if should_open_model_selector { + // Always allow opening the model selector even if the user previously + // dismissed the slash popup for this token. + self.app_event_tx.send(AppEvent::OpenModelSelector); + } else { + // Avoid immediate reopen of the slash popup if it was just dismissed for + // this exact command token. + if self.dismissed_slash_token.as_deref() == current_cmd_token { + return; + } + let mut command_popup = CommandPopup::new(); + command_popup.on_composer_text_change(first_line); + self.active_popup = ActivePopup::Command(command_popup); } - let mut command_popup = CommandPopup::new(); - command_popup.on_composer_text_change(first_line); - self.active_popup = ActivePopup::Command(command_popup); } } } @@ -672,6 +853,45 @@ 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((cmd_token, args)) = Self::parse_slash_command_and_args_from_line(first_line) { + if cmd_token == SlashCommand::Model.command() { + if let ActivePopup::Model(popup) = &mut self.active_popup { + popup.set_query(&args); + } + return; + } + } + // If the line is not `/model`, do nothing – keep the model popup open + // when it was opened programmatically via the slash menu. + } + + /// 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) @@ -705,6 +925,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); @@ -1112,6 +1352,144 @@ mod tests { assert!(matches!(composer.active_popup, ActivePopup::Command(_))); } + #[test] + fn esc_dismiss_on_model_then_space_requests_model_selector() { + use crate::app_event::AppEvent; + use crate::bottom_pane::chat_composer::ActivePopup; + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + use std::sync::mpsc::TryRecvError; + + let (tx, rx) = std::sync::mpsc::channel(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new(true, sender, false); + + // Type '/model' + composer.handle_paste("/model".to_string()); + // Ensure command popup present + assert!(matches!(composer.active_popup, ActivePopup::Command(_))); + + // Dismiss with Esc, which records dismissed_slash_token = "model" + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(matches!(composer.active_popup, ActivePopup::None)); + + // Type a space to make it '/model ' + composer.handle_paste(" ".to_string()); + + // We should emit OpenModelSelector even though the slash token was dismissed. + let mut saw_open = false; + loop { + match rx.try_recv() { + Ok(AppEvent::OpenModelSelector) => { + saw_open = true; + break; + } + Ok(_) => continue, + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => break, + } + } + assert!( + saw_open, + "expected OpenModelSelector event after '/model ' characters" + ); + } + + #[test] + fn selecting_model_in_slash_menu_opens_model_selector() { + use crate::app_event::AppEvent; + use std::sync::mpsc::TryRecvError; + + let (tx, rx) = std::sync::mpsc::channel(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new(true, sender, false); + + // Type a prefix that uniquely selects the model command in slash popup + composer.handle_paste("/mo".to_string()); + + // Press Enter to select the command (no args) + use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + // We should emit OpenModelSelector + let mut saw_open = false; + loop { + match rx.try_recv() { + Ok(AppEvent::OpenModelSelector) => { + saw_open = true; + break; + } + Ok(_) => continue, + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => break, + } + } + assert!(saw_open, "pressing Enter on /model should open model selector"); + } + + #[test] + fn enter_on_model_selector_selects_current_row() { + use crate::app_event::AppEvent; + use std::sync::mpsc::TryRecvError; + use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + + let (tx, rx) = std::sync::mpsc::channel(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new(true, sender, false); + + // Open the model selector directly with a few options and a current model. + let options = vec![ + "codex-mini-latest".to_string(), + "o3".to_string(), + "gpt-4o".to_string(), + ]; + composer.open_model_selector("o3", options); + + // Press Enter to select the currently highlighted row (should default to first visible). + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + // We should receive a SelectModel event. + let mut saw_select = false; + loop { + match rx.try_recv() { + Ok(AppEvent::SelectModel(_m)) => { + saw_select = true; + break; + } + Ok(_) => continue, + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => break, + } + } + assert!(saw_select, "Enter on model selector should emit SelectModel"); + } + + #[test] + fn model_selector_stays_open_on_up_down() { + use crate::bottom_pane::chat_composer::ActivePopup; + use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + + let (tx, _rx) = std::sync::mpsc::channel(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new(true, sender, false); + + let options = vec![ + "codex-mini-latest".to_string(), + "o3".to_string(), + "gpt-4o".to_string(), + ]; + composer.open_model_selector("o3", options); + + // Press Down; popup should remain visible + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + assert!(matches!(composer.active_popup, ActivePopup::Model(_))); + + // Press Up; popup should remain visible + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + assert!(matches!(composer.active_popup, ActivePopup::Model(_))); + } + #[test] fn test_multiple_pastes_submission() { use crossterm::event::KeyCode; diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 18f3201dd2..14e96ae744 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -19,14 +19,13 @@ const MAX_POPUP_ROWS: usize = 5; /// Ideally this is enough to show the longest command name. const FIRST_COLUMN_WIDTH: u16 = 20; +use super::scroll_state::ScrollState; use ratatui::style::Modifier; pub(crate) struct CommandPopup { command_filter: String, all_commands: Vec<(&'static str, SlashCommand)>, - selected_idx: Option, - // Index of the first visible row in the filtered list. - scroll_top: usize, + state: ScrollState, } impl CommandPopup { @@ -34,8 +33,7 @@ impl CommandPopup { Self { command_filter: String::new(), all_commands: built_in_slash_commands(), - selected_idx: None, - scroll_top: 0, + state: ScrollState::new(), } } @@ -65,12 +63,9 @@ impl CommandPopup { // Reset or clamp selected index based on new filtered list. let matches_len = self.filtered_commands().len(); - self.selected_idx = match matches_len { - 0 => None, - _ => Some(self.selected_idx.unwrap_or(0).min(matches_len - 1)), - }; - - self.adjust_scroll(matches_len); + self.state.clamp_selection(matches_len); + self.state + .ensure_visible(matches_len, MAX_POPUP_ROWS.min(matches_len)); } /// Determine the preferred height of the popup. This is the number of @@ -103,70 +98,25 @@ impl CommandPopup { pub(crate) fn move_up(&mut self) { let matches = self.filtered_commands(); let len = matches.len(); - if len == 0 { - self.selected_idx = None; - self.scroll_top = 0; - return; - } - - match self.selected_idx { - Some(idx) if idx > 0 => self.selected_idx = Some(idx - 1), - Some(_) => self.selected_idx = Some(len - 1), // wrap to last - None => self.selected_idx = Some(0), - } - - self.adjust_scroll(len); + self.state.move_up_wrap(len); + self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len)); } /// Move the selection cursor one step down. pub(crate) fn move_down(&mut self) { let matches = self.filtered_commands(); let matches_len = matches.len(); - if matches_len == 0 { - self.selected_idx = None; - self.scroll_top = 0; - return; - } - - match self.selected_idx { - Some(idx) if idx + 1 < matches_len => { - self.selected_idx = Some(idx + 1); - } - Some(_idx_last) => { - self.selected_idx = Some(0); - } - None => { - self.selected_idx = Some(0); - } - } - - self.adjust_scroll(matches_len); + self.state.move_down_wrap(matches_len); + self.state + .ensure_visible(matches_len, MAX_POPUP_ROWS.min(matches_len)); } /// Return currently selected command, if any. pub(crate) fn selected_command(&self) -> Option<&SlashCommand> { let matches = self.filtered_commands(); - self.selected_idx.and_then(|idx| matches.get(idx).copied()) - } - - fn adjust_scroll(&mut self, matches_len: usize) { - if matches_len == 0 { - self.scroll_top = 0; - return; - } - let visible_rows = MAX_POPUP_ROWS.min(matches_len); - if let Some(sel) = self.selected_idx { - if sel < self.scroll_top { - self.scroll_top = sel; - } else { - let bottom = self.scroll_top + visible_rows - 1; - if sel > bottom { - self.scroll_top = sel + 1 - visible_rows; - } - } - } else { - self.scroll_top = 0; - } + self.state + .selected_idx + .and_then(|idx| matches.get(idx).copied()) } } @@ -188,9 +138,9 @@ impl WidgetRef for CommandPopup { let visible_rows = MAX_POPUP_ROWS .min(matches.len()) .min(max_rows_from_area.max(1)); - - let mut start_idx = self.scroll_top.min(matches.len().saturating_sub(1)); - if let Some(sel) = self.selected_idx { + // Ensure the window is consistent with current area and selection + let mut start_idx = self.state.scroll_top.min(matches.len().saturating_sub(1)); + if let Some(sel) = self.state.selected_idx { if sel < start_idx { start_idx = sel; } else if visible_rows > 0 { @@ -209,7 +159,7 @@ impl WidgetRef for CommandPopup { { rows.push(Row::new(vec![ Cell::from(Line::from(vec![ - if Some(global_idx) == self.selected_idx { + if Some(global_idx) == self.state.selected_idx { Span::styled( "›", Style::default().bg(Color::DarkGray).fg(Color::LightCyan), @@ -262,7 +212,7 @@ mod tests { } // Next move_down should wrap to index 0. popup.move_down(); - assert_eq!(popup.selected_idx, Some(0)); + assert_eq!(popup.state.selected_idx, Some(0)); } #[test] @@ -274,7 +224,7 @@ mod tests { // Initial selection is 0; moving up should wrap to last. popup.move_up(); - assert_eq!(popup.selected_idx, Some(len - 1)); + assert_eq!(popup.state.selected_idx, Some(len - 1)); } #[test] diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 281f0859a5..fb3b5c720f 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -18,6 +18,8 @@ mod chat_composer; mod chat_composer_history; mod command_popup; mod file_search_popup; +mod model_selection_popup; +mod scroll_state; mod status_indicator_view; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -70,6 +72,12 @@ impl BottomPane<'_> { } } + /// Show the model-selection popup in the composer. + pub(crate) fn show_model_selector(&mut self, current_model: &str, options: Vec) { + self.composer.open_model_selector(current_model, options); + self.request_redraw(); + } + pub fn desired_height(&self, width: u16) -> u16 { self.active_view .as_ref() 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..c331eb6e12 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/model_selection_popup.rs @@ -0,0 +1,268 @@ +use super::scroll_state::ScrollState; +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; +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; + +/// 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, + /// Selection/scroll state across the visible rows. + state: ScrollState, +} + +impl ModelSelectionPopup { + pub(crate) fn new(current_model: &str, options: Vec) -> Self { + let mut this = Self { + current_model: current_model.to_string(), + options, + query: String::new(), + state: ScrollState::new(), + }; + // Initialize selection to the first visible row if any, so Enter works immediately. + let visible_len = this.visible_rows().len(); + this.state.clamp_selection(visible_len); + this.state + .ensure_visible(visible_len, MAX_RESULTS.min(visible_len)); + this + } + + /// 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.state.clamp_selection(visible_len); + self.state + .ensure_visible(visible_len, MAX_RESULTS.min(visible_len)); + } + + /// 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(); + if visible_len == 0 { + self.state.reset(); + } else { + self.state.selected_idx = Some(0); + self.state + .ensure_visible(visible_len, MAX_RESULTS.min(visible_len)); + } + } + + /// Move selection cursor up. + pub(crate) fn move_up(&mut self) { + let len = self.visible_rows().len(); + self.state.move_up_wrap(len); + self.state.ensure_visible(len, MAX_RESULTS.min(len)); + } + + /// Move selection cursor down. + pub(crate) fn move_down(&mut self) { + let len = self.visible_rows().len(); + self.state.move_down_wrap(len); + self.state.ensure_visible(len, MAX_RESULTS.min(len)); + } + + /// Currently selected model name, if any. + pub(crate) fn selected_model(&self) -> Option { + let rows = self.visible_rows(); + self.state.selected_idx.and_then(|idx| { + rows.get(idx) + .map(|DisplayRow::Model { name, .. }| name.clone()) + }) + } + + /// 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, + }, +} + +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 { + let max_rows_from_area = area.height as usize; + let visible_rows = MAX_RESULTS + .min(rows_all.len()) + .min(max_rows_from_area.max(1)); + + // Compute starting index based on scroll state and selection. + let mut start_idx = self.state.scroll_top.min(rows_all.len().saturating_sub(1)); + if let Some(sel) = self.state.selected_idx { + if sel < start_idx { + start_idx = sel; + } else if visible_rows > 0 { + let bottom = start_idx + visible_rows - 1; + if sel > bottom { + start_idx = sel + 1 - visible_rows; + } + } + } + + for (i, row) in rows_all + .into_iter() + .enumerate() + .skip(start_idx) + .take(visible_rows) + { + 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.state.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); + } +} diff --git a/codex-rs/tui/src/bottom_pane/scroll_state.rs b/codex-rs/tui/src/bottom_pane/scroll_state.rs new file mode 100644 index 0000000000..58837fa05a --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/scroll_state.rs @@ -0,0 +1,114 @@ +/// Generic scroll/selection state for a vertical list menu. +/// +/// Encapsulates the common behavior of a selectable list that supports: +/// - Optional selection (None when list is empty) +/// - Wrap-around navigation on Up/Down +/// - Maintaining a scroll window (`scroll_top`) so the selected row stays visible +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct ScrollState { + pub selected_idx: Option, + pub scroll_top: usize, +} + +impl ScrollState { + pub fn new() -> Self { + Self { + selected_idx: None, + scroll_top: 0, + } + } + + /// Reset selection and scroll. + pub fn reset(&mut self) { + self.selected_idx = None; + self.scroll_top = 0; + } + + /// Clamp selection to be within the [0, len-1] range, or None when empty. + pub fn clamp_selection(&mut self, len: usize) { + self.selected_idx = match len { + 0 => None, + _ => Some(self.selected_idx.unwrap_or(0).min(len - 1)), + }; + if len == 0 { + self.scroll_top = 0; + } + } + + /// Move selection up by one, wrapping to the bottom when necessary. + pub fn move_up_wrap(&mut self, len: usize) { + if len == 0 { + self.selected_idx = None; + self.scroll_top = 0; + return; + } + self.selected_idx = Some(match self.selected_idx { + Some(idx) if idx > 0 => idx - 1, + Some(_) => len - 1, + None => 0, + }); + } + + /// Move selection down by one, wrapping to the top when necessary. + pub fn move_down_wrap(&mut self, len: usize) { + if len == 0 { + self.selected_idx = None; + self.scroll_top = 0; + return; + } + self.selected_idx = Some(match self.selected_idx { + Some(idx) if idx + 1 < len => idx + 1, + _ => 0, + }); + } + + /// Adjust `scroll_top` so that the current `selected_idx` is visible within + /// the window of `visible_rows`. + pub fn ensure_visible(&mut self, len: usize, visible_rows: usize) { + if len == 0 || visible_rows == 0 { + self.scroll_top = 0; + return; + } + if let Some(sel) = self.selected_idx { + if sel < self.scroll_top { + self.scroll_top = sel; + } else { + let bottom = self.scroll_top + visible_rows - 1; + if sel > bottom { + self.scroll_top = sel + 1 - visible_rows; + } + } + } else { + self.scroll_top = 0; + } + } +} + +#[cfg(test)] +mod tests { + use super::ScrollState; + + #[test] + fn wrap_navigation_and_visibility() { + let mut s = ScrollState::new(); + let len = 10; + let vis = 5; + + s.clamp_selection(len); + assert_eq!(s.selected_idx, Some(0)); + s.ensure_visible(len, vis); + assert_eq!(s.scroll_top, 0); + + // Move up wraps to end + s.move_up_wrap(len); + s.ensure_visible(len, vis); + assert_eq!(s.selected_idx, Some(len - 1)); + assert!(s.scroll_top <= s.selected_idx.unwrap()); + + // Move down wraps to start + s.move_down_wrap(len); + s.ensure_visible(len, vis); + assert_eq!(s.selected_idx, Some(0)); + assert_eq!(s.scroll_top, 0); + } +} diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index c777af5264..4808358533 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -6,6 +6,8 @@ use std::time::Duration; 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; @@ -64,6 +66,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, running_commands: HashMap, } @@ -151,6 +154,7 @@ impl ChatWidget<'_> { token_usage: TokenUsage::default(), reasoning_buffer: String::new(), answer_buffer: String::new(), + new_session: true, running_commands: HashMap::new(), } } @@ -224,8 +228,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 @@ -508,6 +516,62 @@ impl ChatWidget<'_> { self.bottom_pane .set_token_usage(self.token_usage.clone(), self.config.model_context_window); } + + /// Open the model selection view in the bottom pane. + pub(crate) fn show_model_selector(&mut self) { + let current = self.config.model.clone(); + + let mut options = 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) { + 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 { + config_models.push(m); + } + } + // Alphabetical ordering for config models. + config_models.sort(); + options.extend(config_models); + } + } + + 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 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}." + ))); + } + + // 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 d82a16608f..0d25f35e66 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -15,6 +15,7 @@ pub enum SlashCommand { New, Compact, Diff, + Model, Quit, #[cfg(debug_assertions)] TestApproval, @@ -27,6 +28,7 @@ impl SlashCommand { SlashCommand::New => "Start a new chat.", SlashCommand::Compact => "Compact the chat history.", SlashCommand::Quit => "Exit the application.", + SlashCommand::Model => "Select the model to use.", SlashCommand::Diff => { "Show git diff of the working directory (including untracked files)" }