adding /model

This commit is contained in:
pap
2025-07-28 23:06:30 +01:00
parent 19bef7659f
commit b294004ea9
14 changed files with 720 additions and 18 deletions
+8
View File
@@ -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"
+9 -15
View File
@@ -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,
+27
View File
@@ -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<String>,
user_instructions: Option<String>,
) -> 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
+1 -1
View File
@@ -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;
+44
View File
@@ -69,3 +69,47 @@ pub(crate) fn get_model_info(name: &str) -> Option<ModelInfo> {
_ => 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))
}
+1
View File
@@ -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"
+103
View File
@@ -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<AppEvent>,
@@ -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);
}
}
}
+7
View File
@@ -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<Line<'static>>),
/// User selected a model from the model-selection dropdown.
SelectModel(String),
}
@@ -43,4 +43,10 @@ pub(crate) trait BottomPaneView<'a> {
) -> Option<ApprovalRequest> {
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<String>) -> bool {
false
}
}
+20 -2
View File
@@ -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();
+11
View File
@@ -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<String>) {
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() {
@@ -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<String>,
/// 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<DisplayRow> {
// 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<DisplayRow> = 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<DisplayRow> = 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<usize>, 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<String> {
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<usize> {
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<Vec<usize>>, // 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<usize>, 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<usize> = Vec::with_capacity(n_lower.len());
let mut h_iter = h_lower.char_indices();
let mut last_pos: Option<usize> = 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<Vec<usize>> {
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<Row> = 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<Span> = 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<String>) -> 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<String> = 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
}
}
+55
View File
@@ -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::<Vec<_>>();
// 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::<ConfigToml>(&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(&current, 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<'_> {
+2
View File
@@ -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)"
}