| 1 | //! `/model` picker modal: pick a model and thinking-effort tier (#39, #2026). |
| 2 | //! |
| 3 | //! The picker intentionally presents model and thinking as independent choices |
| 4 | //! instead of collapsing them into preset route names. The "auto" option is |
| 5 | //! always available; custom (unrecognized) model ids appear as a separate row. |
| 6 | //! Pass-through providers fall back to only "auto" plus the current custom row. |
| 7 | //! |
| 8 | //! On apply we emit a [`ViewEvent::ModelPickerApplied`] with the resolved |
| 9 | //! model id and effort tier. |
| 10 | |
| 11 | use std::cell::{Ref, RefCell}; |
| 12 | use std::collections::BTreeMap; |
| 13 | |
| 14 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; |
| 15 | use ratatui::{ |
| 16 | buffer::Buffer, |
| 17 | layout::Rect, |
| 18 | style::{Modifier, Style}, |
| 19 | text::{Line, Span}, |
| 20 | widgets::{Paragraph, Widget}, |
| 21 | }; |
| 22 | |
| 23 | use codewhale_config::catalog::{CatalogSource, CatalogStatus}; |
| 24 | use codewhale_config::model_reference::ModelReferenceCard; |
| 25 | use codewhale_config::pricing::OfferingPricing; |
| 26 | |
| 27 | use crate::tui::app::{App, StatusToastLevel}; |
| 28 | use crate::tui::provider_picker::{ |
| 29 | model_connection_name, provider_search_aliases, suggested_provider_rank, |
| 30 | }; |
| 31 | use crate::tui::views::fleet_detail::{FleetRouteSelection, FleetRouteTarget}; |
| 32 | use crate::tui::views::{ |
| 33 | ActionHint, ListDetailLayout, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent, |
| 34 | active_modal_accent_color, active_modal_border_color, render_modal_footer, render_modal_rule, |
| 35 | render_panel_scroll_rail, render_surface_frame, |
| 36 | }; |
| 37 | use codewhale_config::ProviderKind; |
| 38 | use codewhale_config::catalog::reviewed::constants::DEEPSEEK_ALIAS_REPLACEMENT; |
| 39 | use codewhale_engine::codex_model_cache::{self}; |
| 40 | use codewhale_engine::model_profile::{ |
| 41 | CapabilityOverride, SupportState, resolved_capability_profile_for_route_with_overrides, |
| 42 | resolved_capability_profile_with_overrides, |
| 43 | }; |
| 44 | use codewhale_engine::models_dev_live::{self, ModelsDevFreshness}; |
| 45 | use codewhale_engine::provider_lake::{catalog_offering_for_model_identity, configured_providers}; |
| 46 | use codewhale_engine::reasoning_preference::ReasoningEffort; |
| 47 | use codewhale_localization::{Locale, MessageId, tr}; |
| 48 | use codewhale_palette as palette; |
| 49 | use codewhale_runtime::codex_model_roster::{ |
| 50 | CodexModelCacheFreshness, CodexModelMetadata, CodexModelRoster, |
| 51 | }; |
| 52 | use codewhale_runtime::config::Config; |
| 53 | use codewhale_runtime::settings::PinnedModel; |
| 54 | use codewhale_tui_kit::menu_style; |
| 55 | use codewhale_util::utils::format_context_window; |
| 56 | |
| 57 | /// Thinking-effort rows shown for DeepSeek-style providers, in the order |
| 58 | /// DeepSeek behaviorally distinguishes them. |
| 59 | const DEFAULT_PICKER_EFFORTS: &[ReasoningEffort] = &[ |
| 60 | ReasoningEffort::Auto, |
| 61 | ReasoningEffort::Off, |
| 62 | ReasoningEffort::High, |
| 63 | ReasoningEffort::Max, |
| 64 | ]; |
| 65 | /// First-party DeepSeek routes document a real `low` wire tier alongside |
| 66 | /// `high`/`max` (#52), so their picker exposes the cheaper tier the generic |
| 67 | /// default list cannot claim for routes where low collapses onto high. |
| 68 | const DEEPSEEK_PICKER_EFFORTS: &[ReasoningEffort] = &[ |
| 69 | ReasoningEffort::Auto, |
| 70 | ReasoningEffort::Off, |
| 71 | ReasoningEffort::Low, |
| 72 | ReasoningEffort::High, |
| 73 | ReasoningEffort::Max, |
| 74 | ]; |
| 75 | /// Kimi Code K3 accepts route-specific low and medium controls at the |
| 76 | /// official membership endpoint. Medium becomes K3's nested high wire effort, |
| 77 | /// but keeping the selected intent visible is important for recovery and |
| 78 | /// route receipts. K3 is always-thinking, so `off` would only land on `low` |
| 79 | /// and is not offered. |
| 80 | const KIMI_CODE_K3_PICKER_EFFORTS: &[ReasoningEffort] = &[ |
| 81 | ReasoningEffort::Auto, |
| 82 | ReasoningEffort::Low, |
| 83 | ReasoningEffort::Medium, |
| 84 | ReasoningEffort::High, |
| 85 | ReasoningEffort::Max, |
| 86 | ]; |
| 87 | const CODEX_PICKER_EFFORTS: &[ReasoningEffort] = &[ |
| 88 | ReasoningEffort::Low, |
| 89 | ReasoningEffort::Medium, |
| 90 | ReasoningEffort::High, |
| 91 | ReasoningEffort::Max, |
| 92 | ]; |
| 93 | const OLLAMA_CLOUD_PICKER_EFFORTS: &[ReasoningEffort] = &[ |
| 94 | ReasoningEffort::Auto, |
| 95 | ReasoningEffort::Off, |
| 96 | ReasoningEffort::Low, |
| 97 | ReasoningEffort::Medium, |
| 98 | ReasoningEffort::High, |
| 99 | ReasoningEffort::Max, |
| 100 | ]; |
| 101 | /// Auto model routing has no concrete provider dialect yet, so retain the |
| 102 | /// complete preference vocabulary and defer normalization to dispatch. |
| 103 | const AUTO_MODEL_PICKER_EFFORTS: &[ReasoningEffort] = &[ |
| 104 | ReasoningEffort::Auto, |
| 105 | ReasoningEffort::Off, |
| 106 | ReasoningEffort::Low, |
| 107 | ReasoningEffort::Medium, |
| 108 | ReasoningEffort::High, |
| 109 | ReasoningEffort::Max, |
| 110 | ]; |
| 111 | |
| 112 | /// `/model` catalog views (#4115). |
| 113 | /// |
| 114 | /// Configured stays the calm default: the current route, pins and Fleet |
| 115 | /// models, recently used routes, and one default per credentialed provider |
| 116 | /// (#6533). Typing searches every provider and a cross-provider selection |
| 117 | /// switches its route transactionally, so `/provider` is never a |
| 118 | /// prerequisite. Discoverability views (New / Coding / Cheap / Long context) |
| 119 | /// never auto-select a surprising route — the active model remains the |
| 120 | /// selection until the operator moves. "New" sorts by catalog refresh time; |
| 121 | /// recency of *use* lives in the default view. |
| 122 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 123 | enum ModelListView { |
| 124 | Configured, |
| 125 | Catalog, |
| 126 | New, |
| 127 | Coding, |
| 128 | Cheap, |
| 129 | LongContext, |
| 130 | } |
| 131 | |
| 132 | impl ModelListView { |
| 133 | const ALL: [Self; 6] = [ |
| 134 | Self::Configured, |
| 135 | Self::Catalog, |
| 136 | Self::New, |
| 137 | Self::Coding, |
| 138 | Self::Cheap, |
| 139 | Self::LongContext, |
| 140 | ]; |
| 141 | |
| 142 | fn next(self) -> Self { |
| 143 | let idx = Self::ALL.iter().position(|view| *view == self).unwrap_or(0); |
| 144 | Self::ALL[(idx + 1) % Self::ALL.len()] |
| 145 | } |
| 146 | |
| 147 | fn from_memory_name(name: &str) -> Option<Self> { |
| 148 | match name { |
| 149 | "configured" => Some(Self::Configured), |
| 150 | "catalog" => Some(Self::Catalog), |
| 151 | // `recent` is the pre-#6533 name of the same view. |
| 152 | "new" | "recent" => Some(Self::New), |
| 153 | "coding" => Some(Self::Coding), |
| 154 | "cheap" => Some(Self::Cheap), |
| 155 | "long_context" => Some(Self::LongContext), |
| 156 | _ => None, |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn memory_name(self) -> &'static str { |
| 161 | match self { |
| 162 | Self::Configured => "configured", |
| 163 | Self::Catalog => "catalog", |
| 164 | Self::New => "new", |
| 165 | Self::Coding => "coding", |
| 166 | Self::Cheap => "cheap", |
| 167 | Self::LongContext => "long_context", |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Short chrome / action label for this view. |
| 172 | fn title_label(self) -> &'static str { |
| 173 | match self { |
| 174 | Self::Configured => "configured", |
| 175 | Self::Catalog => "catalog", |
| 176 | Self::New => "new", |
| 177 | Self::Coding => "coding", |
| 178 | Self::Cheap => "cheap", |
| 179 | Self::LongContext => "long ctx", |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// Views that browse beyond the conservative configured-provider set. |
| 184 | fn is_discoverability(self) -> bool { |
| 185 | !matches!(self, Self::Configured) |
| 186 | } |
| 187 | |
| 188 | fn browses_all_providers(self) -> bool { |
| 189 | self.is_discoverability() |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 194 | enum Pane { |
| 195 | Model, |
| 196 | Effort, |
| 197 | Context, |
| 198 | } |
| 199 | |
| 200 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 201 | enum ContextChoice { |
| 202 | Auto, |
| 203 | Tokens(u32), |
| 204 | Custom, |
| 205 | } |
| 206 | |
| 207 | const CONTEXT_CHOICES: &[ContextChoice] = &[ |
| 208 | ContextChoice::Auto, |
| 209 | ContextChoice::Tokens(128_000), |
| 210 | ContextChoice::Tokens(200_000), |
| 211 | ContextChoice::Tokens(256_000), |
| 212 | ContextChoice::Tokens(500_000), |
| 213 | ContextChoice::Tokens(1_000_000), |
| 214 | ContextChoice::Tokens(2_000_000), |
| 215 | ContextChoice::Custom, |
| 216 | ]; |
| 217 | |
| 218 | const CONTEXT_WARNING_LINE: &str = "Saved per model (model_context_windows). Too high can cause API errors or truncated replies; too low compacts early."; |
| 219 | |
| 220 | /// What applying a row means: the session's own route (`/model`), or a pin |
| 221 | /// on one Fleet editor row, where Enter hands the absolute route back to the |
| 222 | /// editor instead of switching the session. |
| 223 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 224 | pub(crate) enum ModelPickerPurpose { |
| 225 | Session, |
| 226 | FleetProfileRoute { |
| 227 | editor_id: uuid::Uuid, |
| 228 | initial_reasoning: Option<ReasoningEffort>, |
| 229 | }, |
| 230 | FleetRoute { |
| 231 | target: FleetRouteTarget, |
| 232 | editor_id: uuid::Uuid, |
| 233 | initial_reasoning: Option<ReasoningEffort>, |
| 234 | allow_inherit: bool, |
| 235 | }, |
| 236 | } |
| 237 | |
| 238 | #[derive(Debug, Clone, Copy)] |
| 239 | struct PaneRenderState { |
| 240 | pane: Pane, |
| 241 | selected: usize, |
| 242 | focused: bool, |
| 243 | } |
| 244 | |
| 245 | pub struct ModelPickerView { |
| 246 | initial_model: String, |
| 247 | /// Exact runtime value before the picker opened. Keep this raw so choosing |
| 248 | /// the canonical replacement for a retired alias performs a real migration |
| 249 | /// instead of being misclassified as "unchanged". |
| 250 | previous_model: String, |
| 251 | initial_provider: ProviderKind, |
| 252 | initial_provider_identity: String, |
| 253 | initial_identity: Option<codewhale_runtime::config::ProviderIdentity>, |
| 254 | initial_external_agent_id: Option<String>, |
| 255 | /// Raw preference before the picker opened. An absent explicit preference |
| 256 | /// is represented by Auto so applying a visible fixed-route tier is still |
| 257 | /// recognized as an intentional picker choice. |
| 258 | initial_effort: ReasoningEffort, |
| 259 | /// Working raw preference. Model-row navigation only changes how this is |
| 260 | /// projected into the visible route-specific effort rows. |
| 261 | selected_effort_request: ReasoningEffort, |
| 262 | active_accepts_custom_model_ids: bool, |
| 263 | query: String, |
| 264 | provider_filter: Option<String>, |
| 265 | /// Working selection (separate from the initial values so we can offer a |
| 266 | /// clean Esc-to-cancel without mutating App state). |
| 267 | selected_model_idx: usize, |
| 268 | selected_effort_idx: usize, |
| 269 | selected_context_idx: usize, |
| 270 | initial_context_override: Option<u32>, |
| 271 | custom_context_input: String, |
| 272 | custom_context_error: Option<String>, |
| 273 | focus: Pane, |
| 274 | /// True when the active model is one we don't list — we still show it |
| 275 | /// so the picker doesn't quietly forget the user's chosen IDs. |
| 276 | show_custom_model_row: bool, |
| 277 | model_rows: Vec<ModelPickerRow>, |
| 278 | /// Static route facts used to validate custom/current rows at apply time. |
| 279 | route_config: Config, |
| 280 | /// Session-local provider checks used by custom/current rows. Catalog rows |
| 281 | /// resolve the same snapshot during construction. |
| 282 | provider_health: codewhale_engine::provider_readiness::ProviderReadinessSnapshot, |
| 283 | view: ModelListView, |
| 284 | /// Other providers considered "configured" (#3830), shown by default |
| 285 | /// alongside `initial_provider`'s own rows without requiring the user to |
| 286 | /// type a search query first. Uses the same definition as the |
| 287 | /// `/provider` manager's default view |
| 288 | /// (`codewhale_engine::provider_readiness::provider_is_configured_for_active`): active |
| 289 | /// provider, working credentials/OAuth, or an explicit |
| 290 | /// `[providers.<name>]` entry. Self-hosted providers (Ollama/Sglang/ |
| 291 | /// Vllm) don't qualify just because routing to them doesn't require a |
| 292 | /// key. |
| 293 | configured_providers: Vec<codewhale_runtime::config::ProviderIdentity>, |
| 294 | row_hitboxes: RefCell<Vec<(Rect, Pane, usize)>>, |
| 295 | last_mouse_selected: Option<(Pane, usize)>, |
| 296 | hovered_row: Option<(Pane, usize)>, |
| 297 | /// UI locale captured from the app at construction (#4057 wave 2). |
| 298 | locale: Locale, |
| 299 | pinned_models: Vec<PinnedModel>, |
| 300 | // Navigation only changes selection. Catalog projections are rebuilt when |
| 301 | // the query, view, sort, pins or readiness/catalog snapshot changes. |
| 302 | projection: RefCell<Option<ModelPickerProjection>>, |
| 303 | sort: Option<ModelSort>, |
| 304 | column_hitboxes: RefCell<Vec<(Rect, ModelSortColumn)>>, |
| 305 | pane_hitboxes: RefCell<Vec<(Rect, Pane)>>, |
| 306 | catalog_action_hitbox: RefCell<Option<Rect>>, |
| 307 | catalog_action_hovered: bool, |
| 308 | purpose: ModelPickerPurpose, |
| 309 | assignment_context: Option<(String, String)>, |
| 310 | /// Receipt of the last ⇧P / ⇧F / refresh with its typed toast level. The |
| 311 | /// picker covers the status line, so this line is the only place those |
| 312 | /// actions can confirm or refuse (#6500). Cleared by the next key. |
| 313 | notice: Option<(String, StatusToastLevel)>, |
| 314 | /// Theme the notice resolves its semantic ink through. |
| 315 | theme: codewhale_palette::UiTheme, |
| 316 | } |
| 317 | |
| 318 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 319 | enum ModelSortColumn { |
| 320 | Model, |
| 321 | Provider, |
| 322 | Context, |
| 323 | } |
| 324 | |
| 325 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 326 | struct ModelSort { |
| 327 | column: ModelSortColumn, |
| 328 | descending: bool, |
| 329 | } |
| 330 | |
| 331 | struct ModelPickerProjection { |
| 332 | query: String, |
| 333 | provider_filter: Option<String>, |
| 334 | view: ModelListView, |
| 335 | sort: Option<ModelSort>, |
| 336 | indices: Vec<usize>, |
| 337 | rows: Vec<PaneRow>, |
| 338 | custom: Option<(String, codewhale_runtime::config::ProviderIdentity)>, |
| 339 | } |
| 340 | |
| 341 | struct VisibleModelRows<'a> { |
| 342 | catalog: &'a [ModelPickerRow], |
| 343 | indices: Ref<'a, [usize]>, |
| 344 | } |
| 345 | |
| 346 | impl<'a> VisibleModelRows<'a> { |
| 347 | fn len(&self) -> usize { |
| 348 | self.indices.len() |
| 349 | } |
| 350 | fn get(&self, index: usize) -> Option<&'a ModelPickerRow> { |
| 351 | self.indices.get(index).map(|index| &self.catalog[*index]) |
| 352 | } |
| 353 | fn iter(&self) -> impl ExactSizeIterator<Item = &'a ModelPickerRow> + '_ { |
| 354 | self.indices.iter().map(|index| &self.catalog[*index]) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | impl std::ops::Index<usize> for VisibleModelRows<'_> { |
| 359 | type Output = ModelPickerRow; |
| 360 | fn index(&self, index: usize) -> &Self::Output { |
| 361 | &self.catalog[self.indices[index]] |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 366 | struct ExternalAgentRowInfo { |
| 367 | agent_id: String, |
| 368 | agent_name: String, |
| 369 | state: String, |
| 370 | runnable: bool, |
| 371 | needs_update: bool, |
| 372 | version: Option<String>, |
| 373 | reason_code: Option<String>, |
| 374 | reason: Option<String>, |
| 375 | login: Option<String>, |
| 376 | upgrade: Option<String>, |
| 377 | website: String, |
| 378 | cached_model_count: Option<usize>, |
| 379 | thinking_levels: Vec<String>, |
| 380 | } |
| 381 | |
| 382 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 383 | struct ModelPickerRow { |
| 384 | id: String, |
| 385 | provider: Option<ProviderKind>, |
| 386 | /// Concrete persistence identity. `Custom` alone cannot identify a named |
| 387 | /// custom route, so pins must carry this exact key when present. |
| 388 | provider_identity: Option<String>, |
| 389 | admitted_identity: Option<codewhale_runtime::config::ProviderIdentity>, |
| 390 | route_selection: Option<codewhale_engine::model_inventory::RouteSelection>, |
| 391 | hint: String, |
| 392 | metadata: EffectivePickerMetadata, |
| 393 | selectable: bool, |
| 394 | /// Why this route cannot be attempted, kept structured so the scannable |
| 395 | /// row can show the reason without re-parsing the prose `hint`. `None` |
| 396 | /// whenever the route is attemptable. |
| 397 | blocked_reason: Option<String>, |
| 398 | /// Where this row sits in the default view (#6533); `None` keeps it |
| 399 | /// behind search and the catalog views. |
| 400 | default_rank: Option<(DefaultSection, usize)>, |
| 401 | /// The route holds a credential (saved key, imported token, or an |
| 402 | /// observed success), as opposed to merely being routable. |
| 403 | credentialed: bool, |
| 404 | /// The route's fresh live roster does not list this id. |
| 405 | not_listed: Option<NotListed>, |
| 406 | external_agent: Option<ExternalAgentRowInfo>, |
| 407 | } |
| 408 | |
| 409 | /// Sections of the default view, in display order (#6533). |
| 410 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 411 | enum DefaultSection { |
| 412 | Current, |
| 413 | Pinned, |
| 414 | Recent, |
| 415 | ProviderDefault, |
| 416 | ExternalAgent, |
| 417 | Roster, |
| 418 | } |
| 419 | |
| 420 | /// Most rows the default view's recent section shows. |
| 421 | const RECENT_ROW_LIMIT: usize = 8; |
| 422 | |
| 423 | /// Most rows the current route's roster, or one custom relay's roster, |
| 424 | /// contributes to the default view. |
| 425 | /// |
| 426 | /// Hiding all of a route's roster but the configured default is what made |
| 427 | /// `/model` show one row for a route the provider panel had just listed a |
| 428 | /// dozen for. The bound keeps a gateway fronting a thousand models from taking |
| 429 | /// the view over. |
| 430 | const ROUTE_ROSTER_ROWS_IN_DEFAULT_VIEW: usize = 20; |
| 431 | |
| 432 | /// A fresh live roster for the row's exact route omits its id. Only a fresh |
| 433 | /// roster may say so: a stale one lags the provider (and would condemn ids it |
| 434 | /// simply never saw). The row stays selectable and nothing is rewritten. |
| 435 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 436 | struct NotListed { |
| 437 | provider: String, |
| 438 | /// `YYYY-MM-DD` of the roster fetch. |
| 439 | checked: String, |
| 440 | } |
| 441 | |
| 442 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 443 | struct EffectivePickerMetadata { |
| 444 | display_name: Option<String>, |
| 445 | declared_usd_input_price: Option<String>, |
| 446 | context_window: Option<u32>, |
| 447 | context_window_override: bool, |
| 448 | /// The context window came through the legacy provider fallback rather |
| 449 | /// than an offering, catalog row, roster, or operator override — shown, |
| 450 | /// but never as a verified capability (#5239, #5441). |
| 451 | context_window_unverified: bool, |
| 452 | max_output: Option<u32>, |
| 453 | /// The output ceiling is an assumed floor for a route that publishes no |
| 454 | /// ceiling we can stand behind (unknown Anthropic-family models), |
| 455 | /// clamped but never labeled "documented" (#5440). |
| 456 | max_output_unverified: bool, |
| 457 | tool_calls: Option<bool>, |
| 458 | reasoning: bool, |
| 459 | reasoning_unknown: bool, |
| 460 | vision: SupportState, |
| 461 | pricing: PickerPricing, |
| 462 | price_basis: Option<PriceBasis>, |
| 463 | wire_model_id: Option<String>, |
| 464 | canonical_model: Option<String>, |
| 465 | source: Option<CatalogSource>, |
| 466 | model_type: Option<String>, |
| 467 | codex_efforts: Vec<String>, |
| 468 | } |
| 469 | |
| 470 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 471 | struct PriceBasis { |
| 472 | short: &'static str, |
| 473 | detail: String, |
| 474 | } |
| 475 | |
| 476 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 477 | enum PickerPricing { |
| 478 | /// The route explicitly does not expose authoritative token pricing. |
| 479 | Unavailable, |
| 480 | Known(String), |
| 481 | Status(&'static str), |
| 482 | #[default] |
| 483 | Unknown, |
| 484 | } |
| 485 | |
| 486 | impl ModelPickerView { |
| 487 | #[must_use] |
| 488 | /// The same picker, opened by the Fleet editor for one of its rows: Enter |
| 489 | /// hands the absolute route to the editor (`FleetRoutePicked`) instead of |
| 490 | /// switching the session. |
| 491 | pub fn new_for_fleet_route( |
| 492 | app: &App, |
| 493 | config: &Config, |
| 494 | target: FleetRouteTarget, |
| 495 | editor_id: uuid::Uuid, |
| 496 | selection: FleetRouteSelection, |
| 497 | ) -> Self { |
| 498 | Self::new_for_assignment( |
| 499 | app, |
| 500 | config, |
| 501 | ModelPickerPurpose::FleetRoute { |
| 502 | target, |
| 503 | editor_id, |
| 504 | initial_reasoning: selection.reasoning, |
| 505 | allow_inherit: selection.allow_inherit, |
| 506 | }, |
| 507 | selection, |
| 508 | ) |
| 509 | } |
| 510 | |
| 511 | pub fn new_for_fleet_profile( |
| 512 | app: &App, |
| 513 | config: &Config, |
| 514 | editor_id: uuid::Uuid, |
| 515 | selection: FleetRouteSelection, |
| 516 | ) -> Self { |
| 517 | Self::new_for_assignment( |
| 518 | app, |
| 519 | config, |
| 520 | ModelPickerPurpose::FleetProfileRoute { |
| 521 | editor_id, |
| 522 | initial_reasoning: selection.reasoning, |
| 523 | }, |
| 524 | selection, |
| 525 | ) |
| 526 | } |
| 527 | |
| 528 | pub fn with_assignment_context( |
| 529 | mut self, |
| 530 | title: impl Into<String>, |
| 531 | scope: impl Into<String>, |
| 532 | ) -> Self { |
| 533 | self.assignment_context = Some((title.into(), scope.into())); |
| 534 | self |
| 535 | } |
| 536 | |
| 537 | fn new_for_assignment( |
| 538 | app: &App, |
| 539 | config: &Config, |
| 540 | purpose: ModelPickerPurpose, |
| 541 | selection: FleetRouteSelection, |
| 542 | ) -> Self { |
| 543 | let mut picker = Self::new(app, config); |
| 544 | picker.purpose = purpose; |
| 545 | // Session browsing memory is unrelated to the row being edited. |
| 546 | picker.query.clear(); |
| 547 | picker.view = ModelListView::Configured; |
| 548 | picker.sort = None; |
| 549 | picker.initial_provider_identity = selection |
| 550 | .provider |
| 551 | .unwrap_or_else(|| app.provider_identity_for_persistence().to_string()); |
| 552 | picker.initial_identity = config |
| 553 | .legacy_selection_identity(&picker.initial_provider_identity) |
| 554 | .ok(); |
| 555 | picker.initial_provider = picker |
| 556 | .initial_identity |
| 557 | .as_ref() |
| 558 | .map_or(ProviderKind::Custom, |identity| identity.provider); |
| 559 | picker.initial_model = selection.model.unwrap_or_else(|| "auto".to_string()); |
| 560 | picker.previous_model = picker.initial_model.clone(); |
| 561 | picker.initial_effort = selection.reasoning.unwrap_or(ReasoningEffort::Auto); |
| 562 | picker.selected_effort_request = picker.initial_effort; |
| 563 | picker.apply_fleet_route_rows(app, config); |
| 564 | *picker.projection.borrow_mut() = None; |
| 565 | picker.selected_model_idx = { |
| 566 | let rows = picker.visible_model_rows(); |
| 567 | rows.iter() |
| 568 | .position(|row| { |
| 569 | row.id == picker.initial_model |
| 570 | && model_row_matches_route( |
| 571 | row, |
| 572 | picker.initial_provider, |
| 573 | &picker.initial_provider_identity, |
| 574 | ) |
| 575 | }) |
| 576 | .unwrap_or(rows.len()) |
| 577 | }; |
| 578 | let visible_len = picker.visible_model_rows().len(); |
| 579 | picker.show_custom_model_row = picker.selected_model_idx >= visible_len; |
| 580 | *picker.projection.borrow_mut() = None; |
| 581 | picker.select_effort_for_current_model(); |
| 582 | picker |
| 583 | } |
| 584 | |
| 585 | fn apply_fleet_route_rows(&mut self, app: &App, config: &Config) { |
| 586 | let allow_inherit = match self.purpose { |
| 587 | ModelPickerPurpose::Session => return, |
| 588 | ModelPickerPurpose::FleetRoute { allow_inherit, .. } => allow_inherit, |
| 589 | ModelPickerPurpose::FleetProfileRoute { .. } => true, |
| 590 | }; |
| 591 | if let Some(identity) = self.initial_identity.as_ref() |
| 592 | && self |
| 593 | .route_config |
| 594 | .scope_to_provider_identity(identity) |
| 595 | .is_err() |
| 596 | { |
| 597 | self.initial_identity = None; |
| 598 | } |
| 599 | self.configured_providers = configured_providers(config) |
| 600 | .into_iter() |
| 601 | .filter(|identity| Some(identity) != self.initial_identity.as_ref()) |
| 602 | .collect(); |
| 603 | self.active_accepts_custom_model_ids = self |
| 604 | .initial_identity |
| 605 | .as_ref() |
| 606 | .is_some_and(|identity| config.model_ids_pass_through_for_provider(identity)); |
| 607 | if self.initial_model != "auto" |
| 608 | && let Some(identity) = self.initial_identity.as_ref() |
| 609 | { |
| 610 | push_provider_model_rows( |
| 611 | &mut self.model_rows, |
| 612 | identity, |
| 613 | vec![self.initial_model.clone()], |
| 614 | self.initial_provider, |
| 615 | config, |
| 616 | &codex_model_cache::model_roster_for(config), |
| 617 | &app.provider_health, |
| 618 | ); |
| 619 | } |
| 620 | self.model_rows |
| 621 | .retain(|row| row.external_agent.is_none() && (allow_inherit || row.id != "auto")); |
| 622 | for row in &mut self.model_rows { |
| 623 | if row.id == "auto" && row.provider.is_none() { |
| 624 | row.hint = format!("{}/{}", app.provider_identity_for_persistence(), app.model); |
| 625 | row.selectable = true; |
| 626 | row.blocked_reason = None; |
| 627 | } |
| 628 | } |
| 629 | // Same sections as the session picker, anchored on the row being |
| 630 | // edited rather than on the session's own route. |
| 631 | let current = (self.initial_model != "auto").then_some(( |
| 632 | self.initial_provider_identity.as_str(), |
| 633 | self.initial_model.as_str(), |
| 634 | )); |
| 635 | assign_default_sections( |
| 636 | &mut self.model_rows, |
| 637 | app, |
| 638 | config, |
| 639 | current, |
| 640 | &self.pinned_models, |
| 641 | ); |
| 642 | } |
| 643 | |
| 644 | pub fn new(app: &App, config: &Config) -> Self { |
| 645 | let initial_model = if app.auto_model { |
| 646 | "auto".to_string() |
| 647 | } else { |
| 648 | picker_visible_model_id(app.api_provider, &app.model, app.accepts_custom_model_ids()) |
| 649 | .to_string() |
| 650 | }; |
| 651 | let previous_model = if app.auto_model { |
| 652 | "auto".to_string() |
| 653 | } else { |
| 654 | app.model.clone() |
| 655 | }; |
| 656 | let model_rows = picker_model_rows_for_app(app, config); |
| 657 | let configured_providers: Vec<_> = configured_providers(config) |
| 658 | .into_iter() |
| 659 | .filter(|identity| app.admitted_provider_identity().ok() != Some(identity)) |
| 660 | .collect(); |
| 661 | let mut default_visible_rows: Vec<_> = model_rows |
| 662 | .iter() |
| 663 | .filter(|row| model_row_visible_in_view(row, ModelListView::Configured)) |
| 664 | .collect(); |
| 665 | // Selection indices must be calculated in the same order that the |
| 666 | // configured view renders. Pinned rows are sorted to the top by |
| 667 | // `visible_model_rows`; using the unsorted construction order here |
| 668 | // made the cursor land on a different row (or look unselected) after |
| 669 | // a pin reordered the list. |
| 670 | let pins = picker_pins_for_app(app); |
| 671 | sort_model_rows_for_view( |
| 672 | &mut default_visible_rows, |
| 673 | |row| *row, |
| 674 | ModelListView::Configured, |
| 675 | &pins, |
| 676 | ); |
| 677 | let initial_external_agent_id = app |
| 678 | .external_agent |
| 679 | .as_ref() |
| 680 | .map(|session| session.agent_id.clone()); |
| 681 | let mut selected_model_idx = |
| 682 | if let Some(active_agent) = initial_external_agent_id.as_deref() { |
| 683 | default_visible_rows.iter().position(|row| { |
| 684 | row.external_agent |
| 685 | .as_ref() |
| 686 | .is_some_and(|agent| agent.agent_id == active_agent) |
| 687 | }) |
| 688 | } else { |
| 689 | default_visible_rows.iter().position(|row| { |
| 690 | row.external_agent.is_none() |
| 691 | && row.id == initial_model |
| 692 | && model_row_matches_route( |
| 693 | row, |
| 694 | app.api_provider, |
| 695 | app.provider_identity_for_persistence(), |
| 696 | ) |
| 697 | }) |
| 698 | }; |
| 699 | let show_custom_model_row = |
| 700 | initial_external_agent_id.is_none() && selected_model_idx.is_none(); |
| 701 | if show_custom_model_row { |
| 702 | selected_model_idx = Some(default_visible_rows.len()); |
| 703 | } |
| 704 | let selected_model_idx = selected_model_idx.unwrap_or(0); |
| 705 | |
| 706 | let initial_effort = app |
| 707 | .reasoning_effort_preference |
| 708 | .unwrap_or(ReasoningEffort::Auto); |
| 709 | let selected_effort_request = app |
| 710 | .reasoning_effort_preference |
| 711 | .unwrap_or(app.reasoning_effort); |
| 712 | let effort_rows = picker_efforts_for_route( |
| 713 | app.api_provider, |
| 714 | &config.active_route_base_url(), |
| 715 | &initial_model, |
| 716 | app.auto_model, |
| 717 | ); |
| 718 | let normalized = normalize_picker_effort( |
| 719 | selected_effort_request, |
| 720 | app.api_provider, |
| 721 | &config.active_route_base_url(), |
| 722 | &initial_model, |
| 723 | app.auto_model, |
| 724 | ); |
| 725 | let selected_effort_idx = effort_rows |
| 726 | .iter() |
| 727 | .position(|e| *e == normalized) |
| 728 | .unwrap_or_else(|| { |
| 729 | default_picker_effort_idx( |
| 730 | app.api_provider, |
| 731 | &config.active_route_base_url(), |
| 732 | &initial_model, |
| 733 | app.auto_model, |
| 734 | ) |
| 735 | }); |
| 736 | |
| 737 | let mut view = Self { |
| 738 | initial_model, |
| 739 | previous_model, |
| 740 | initial_provider: app.api_provider, |
| 741 | initial_provider_identity: app.provider_identity_for_persistence().to_string(), |
| 742 | initial_identity: app.admitted_provider_identity().ok().cloned(), |
| 743 | initial_external_agent_id, |
| 744 | initial_effort, |
| 745 | selected_effort_request, |
| 746 | active_accepts_custom_model_ids: app.accepts_custom_model_ids(), |
| 747 | query: String::new(), |
| 748 | provider_filter: None, |
| 749 | selected_model_idx, |
| 750 | selected_effort_idx, |
| 751 | selected_context_idx: 0, |
| 752 | initial_context_override: None, |
| 753 | custom_context_input: String::new(), |
| 754 | custom_context_error: None, |
| 755 | focus: Pane::Model, |
| 756 | show_custom_model_row, |
| 757 | model_rows, |
| 758 | route_config: config.clone(), |
| 759 | provider_health: app.provider_health.clone(), |
| 760 | view: ModelListView::Configured, |
| 761 | configured_providers, |
| 762 | row_hitboxes: RefCell::new(Vec::new()), |
| 763 | last_mouse_selected: None, |
| 764 | hovered_row: None, |
| 765 | locale: app.ui_locale, |
| 766 | pinned_models: pins, |
| 767 | projection: RefCell::new(None), |
| 768 | sort: None, |
| 769 | column_hitboxes: RefCell::new(Vec::new()), |
| 770 | pane_hitboxes: RefCell::new(Vec::new()), |
| 771 | catalog_action_hitbox: RefCell::new(None), |
| 772 | catalog_action_hovered: false, |
| 773 | purpose: ModelPickerPurpose::Session, |
| 774 | assignment_context: None, |
| 775 | notice: None, |
| 776 | theme: app.ui_theme, |
| 777 | }; |
| 778 | view.restore_memory(app.model_picker_memory.as_ref()); |
| 779 | view.select_context_for_current_model(); |
| 780 | view |
| 781 | } |
| 782 | |
| 783 | /// Restore the browsing context from the last dismissed picker (#4109): |
| 784 | /// the named catalog view and, when the remembered row still exists in |
| 785 | /// that view, the highlighted row. The active model remains the selection |
| 786 | /// when nothing was remembered or the row is gone. |
| 787 | fn restore_memory(&mut self, memory: Option<&crate::tui::app::ModelPickerMemory>) { |
| 788 | let Some(memory) = memory else { |
| 789 | return; |
| 790 | }; |
| 791 | if let Some(view_name) = memory.view.as_deref() { |
| 792 | if let Some(view) = ModelListView::from_memory_name(view_name) { |
| 793 | self.view = view; |
| 794 | } |
| 795 | } else if memory.catalog_view { |
| 796 | self.view = ModelListView::Catalog; |
| 797 | } |
| 798 | // Older picker memory stores only a model id. An ambiguous id must |
| 799 | // not move the selection onto a different configured route. Resolve |
| 800 | // the active row again because a restored view can change row order. |
| 801 | let position = { |
| 802 | let rows = self.visible_model_rows(); |
| 803 | let remembered = memory.selected_row_id.as_deref().and_then(|remembered_id| { |
| 804 | let mut matches = rows |
| 805 | .iter() |
| 806 | .enumerate() |
| 807 | .filter(|(_, row)| row.id == remembered_id); |
| 808 | let first = matches.next().map(|(index, _)| index); |
| 809 | first.filter(|_| matches.next().is_none()) |
| 810 | }); |
| 811 | remembered.or_else(|| { |
| 812 | rows.iter().position(|row| { |
| 813 | row.id == self.initial_model |
| 814 | && model_row_matches_route( |
| 815 | row, |
| 816 | self.initial_provider, |
| 817 | &self.initial_provider_identity, |
| 818 | ) |
| 819 | }) |
| 820 | }) |
| 821 | }; |
| 822 | if let Some(position) = position { |
| 823 | self.selected_model_idx = position; |
| 824 | self.select_effort_for_current_model(); |
| 825 | } |
| 826 | self.clamp_model_selection(); |
| 827 | } |
| 828 | |
| 829 | fn ensure_projection(&self) { |
| 830 | if self.projection.borrow().as_ref().is_some_and(|cached| { |
| 831 | cached.query == self.query |
| 832 | && cached.provider_filter == self.provider_filter |
| 833 | && cached.view == self.view |
| 834 | && cached.sort == self.sort |
| 835 | }) { |
| 836 | return; |
| 837 | } |
| 838 | let query = self.query.trim(); |
| 839 | let mut indices: Vec<usize> = |
| 840 | self.model_rows |
| 841 | .iter() |
| 842 | .enumerate() |
| 843 | .filter_map(|(index, row)| { |
| 844 | let visible = if query.is_empty() { |
| 845 | model_row_visible_in_view(row, self.effective_view()) |
| 846 | } else { |
| 847 | model_row_matches_query(row, query, self.initial_provider) |
| 848 | }; |
| 849 | let provider_matches = self.provider_filter.as_deref().is_none_or(|filter| { |
| 850 | row_provider_filter_key(row).as_deref() == Some(filter) |
| 851 | }); |
| 852 | (visible && provider_matches).then_some(index) |
| 853 | }) |
| 854 | .collect(); |
| 855 | if let Some(sort) = self.sort { |
| 856 | sort_model_indices(&mut indices, &self.model_rows, sort); |
| 857 | } else if query.is_empty() { |
| 858 | sort_model_rows_for_view( |
| 859 | &mut indices, |
| 860 | |index| &self.model_rows[*index], |
| 861 | self.view, |
| 862 | &self.pinned_models, |
| 863 | ); |
| 864 | } else { |
| 865 | let query_lower = query.to_ascii_lowercase(); |
| 866 | let query_tokens: Vec<&str> = query_lower.split_whitespace().collect(); |
| 867 | let agents_first = indices.iter().any(|index| { |
| 868 | self.model_rows[*index] |
| 869 | .external_agent |
| 870 | .as_ref() |
| 871 | .is_some_and(|agent| { |
| 872 | agent.agent_id.eq_ignore_ascii_case(query) |
| 873 | || agent.agent_name.eq_ignore_ascii_case(query) |
| 874 | }) |
| 875 | }); |
| 876 | indices.sort_by_cached_key(|index| { |
| 877 | let row = &self.model_rows[*index]; |
| 878 | let provider_matches = provider_matches_query_token(row, &query_lower) |
| 879 | || (query_tokens.len() > 1 |
| 880 | && query_tokens |
| 881 | .iter() |
| 882 | .any(|token| provider_matches_query_token(row, token))); |
| 883 | let id = row.id.to_ascii_lowercase(); |
| 884 | let id_rank = if id == query_lower { |
| 885 | 0 |
| 886 | } else if id.starts_with(&query_lower) { |
| 887 | 1 |
| 888 | } else { |
| 889 | 2 |
| 890 | }; |
| 891 | ( |
| 892 | row.external_agent.is_some() != agents_first, |
| 893 | !provider_matches, |
| 894 | id_rank, |
| 895 | row.provider.is_some() && row.provider != Some(self.initial_provider), |
| 896 | row.external_agent.as_ref().map(external_agent_order), |
| 897 | id, |
| 898 | ) |
| 899 | }); |
| 900 | } |
| 901 | let visible: Vec<_> = indices |
| 902 | .iter() |
| 903 | .map(|index| &self.model_rows[*index]) |
| 904 | .collect(); |
| 905 | let route_labels = route_labels_for_rows(&visible); |
| 906 | let mut route_base_counts: BTreeMap<(String, String), usize> = BTreeMap::new(); |
| 907 | for row in &self.model_rows { |
| 908 | if row.external_agent.is_some() || row.provider.is_none() { |
| 909 | continue; |
| 910 | } |
| 911 | let route_key = row_provider_identity(row) |
| 912 | .unwrap_or_default() |
| 913 | .to_ascii_lowercase(); |
| 914 | let base = parse_trailing_release_date(&row.id) |
| 915 | .map(|(base, _)| base) |
| 916 | .unwrap_or(row.id.as_str()) |
| 917 | .to_ascii_lowercase(); |
| 918 | *route_base_counts.entry((route_key, base)).or_insert(0) += 1; |
| 919 | } |
| 920 | let grouped = |
| 921 | self.sort.is_none() && query.is_empty() && self.view == ModelListView::Catalog; |
| 922 | let provider_groups = self |
| 923 | .sort |
| 924 | .is_some_and(|sort| sort.column == ModelSortColumn::Provider); |
| 925 | let configured_sections = |
| 926 | if self.sort.is_none() && query.is_empty() && self.view == ModelListView::Configured { |
| 927 | let mut distinct: Vec<DefaultSection> = Vec::new(); |
| 928 | for row in &visible { |
| 929 | if let Some((section, _)) = row.default_rank |
| 930 | && !distinct.contains(§ion) |
| 931 | { |
| 932 | distinct.push(section); |
| 933 | } |
| 934 | } |
| 935 | distinct.len() >= 2 |
| 936 | } else { |
| 937 | false |
| 938 | }; |
| 939 | let mut rows: Vec<_> = visible |
| 940 | .iter() |
| 941 | .map(|row| (row, pin_for_row(&self.pinned_models, row))) |
| 942 | .map(|(row, pin)| { |
| 943 | let route = if row.external_agent.is_some() { |
| 944 | tr(self.locale, MessageId::ModelPickerExternalAgentRoute).into_owned() |
| 945 | } else { |
| 946 | row.provider |
| 947 | .map(|provider| { |
| 948 | route_labels |
| 949 | .get(row_provider_identity(row).unwrap_or(provider.as_str())) |
| 950 | .cloned() |
| 951 | .unwrap_or_else(|| row_provider_label(row).to_string()) |
| 952 | }) |
| 953 | .unwrap_or_default() |
| 954 | }; |
| 955 | let (group, group_scoped_by_route) = if provider_groups { |
| 956 | (Some(route.clone()), true) |
| 957 | } else if configured_sections { |
| 958 | let label = row.default_rank.map(|(section, _)| match section { |
| 959 | DefaultSection::Current => MessageId::ModelPickerSectionCurrent, |
| 960 | DefaultSection::Pinned => MessageId::ModelPickerSectionPinned, |
| 961 | DefaultSection::Recent => MessageId::ModelPickerSectionRecent, |
| 962 | DefaultSection::ProviderDefault => MessageId::ModelPickerSectionProviders, |
| 963 | DefaultSection::Roster => MessageId::ModelPickerSectionMore, |
| 964 | DefaultSection::ExternalAgent => { |
| 965 | MessageId::ModelPickerSectionExternalAgents |
| 966 | } |
| 967 | }); |
| 968 | let label = label.map(|id| tr(self.locale, id).into_owned()); |
| 969 | (label, false) |
| 970 | } else if self.sort.is_none() && !query.is_empty() && row.external_agent.is_some() { |
| 971 | ( |
| 972 | Some( |
| 973 | tr(self.locale, MessageId::ModelPickerSectionExternalAgents) |
| 974 | .into_owned(), |
| 975 | ), |
| 976 | false, |
| 977 | ) |
| 978 | } else { |
| 979 | ( |
| 980 | (grouped && pin.is_none()) |
| 981 | .then(|| { |
| 982 | if row.external_agent.is_some() { |
| 983 | Some( |
| 984 | tr( |
| 985 | self.locale, |
| 986 | MessageId::ModelPickerSectionExternalAgents, |
| 987 | ) |
| 988 | .into_owned(), |
| 989 | ) |
| 990 | } else { |
| 991 | row.provider.and_then(|provider| { |
| 992 | catalog_family_for_identity( |
| 993 | provider, |
| 994 | row.provider_identity.as_deref(), |
| 995 | &row.id, |
| 996 | ) |
| 997 | }) |
| 998 | } |
| 999 | }) |
| 1000 | .flatten(), |
| 1001 | row.external_agent.is_none(), |
| 1002 | ) |
| 1003 | }; |
| 1004 | let humanized_release = if row.external_agent.is_none() && row.provider.is_some() { |
| 1005 | parse_trailing_release_date(&row.id).filter(|(base, _)| { |
| 1006 | let route_key = row_provider_identity(row) |
| 1007 | .unwrap_or_default() |
| 1008 | .to_ascii_lowercase(); |
| 1009 | route_base_counts |
| 1010 | .get(&(route_key, base.to_ascii_lowercase())) |
| 1011 | .copied() |
| 1012 | .unwrap_or(0) |
| 1013 | <= 1 |
| 1014 | }) |
| 1015 | } else { |
| 1016 | None |
| 1017 | }; |
| 1018 | PaneRow { |
| 1019 | primary: if self.purpose != ModelPickerPurpose::Session |
| 1020 | && row.id == "auto" |
| 1021 | && row.provider.is_none() |
| 1022 | { |
| 1023 | tr(self.locale, MessageId::FleetRouteInherited).into_owned() |
| 1024 | } else { |
| 1025 | let display_id = humanized_release |
| 1026 | .as_ref() |
| 1027 | .map(|(base, _)| *base) |
| 1028 | .unwrap_or(row.id.as_str()); |
| 1029 | row.metadata |
| 1030 | .display_name |
| 1031 | .as_ref() |
| 1032 | .map(|label| format!("{label} ({display_id})")) |
| 1033 | .unwrap_or_else(|| display_id.to_string()) |
| 1034 | }, |
| 1035 | route, |
| 1036 | meta: if let Some(agent) = row.external_agent.as_ref() { |
| 1037 | external_agent_meta_chips(row, agent) |
| 1038 | } else if row.provider.is_none() { |
| 1039 | vec![row.hint.clone()] |
| 1040 | } else { |
| 1041 | let mut chips = model_row_meta_chips(row); |
| 1042 | if let Some((_, updated)) = humanized_release { |
| 1043 | chips.push(updated); |
| 1044 | } |
| 1045 | if let Some(not_listed) = &row.not_listed { |
| 1046 | chips.insert( |
| 1047 | 0, |
| 1048 | tr(self.locale, MessageId::ModelPickerNotListed) |
| 1049 | .replace("{provider}", ¬_listed.provider) |
| 1050 | .replace("{date}", ¬_listed.checked), |
| 1051 | ); |
| 1052 | } |
| 1053 | if let Some(pin) = pin { |
| 1054 | chips.insert( |
| 1055 | 0, |
| 1056 | pin.label.clone().unwrap_or_else(|| { |
| 1057 | tr(self.locale, MessageId::ModelPickerPinnedChip).into_owned() |
| 1058 | }), |
| 1059 | ); |
| 1060 | } |
| 1061 | chips |
| 1062 | }, |
| 1063 | group, |
| 1064 | group_scoped_by_route, |
| 1065 | active: if let Some(agent) = row.external_agent.as_ref() { |
| 1066 | self.initial_external_agent_id.as_deref() == Some(agent.agent_id.as_str()) |
| 1067 | } else { |
| 1068 | self.initial_external_agent_id.is_none() |
| 1069 | && row.id == self.initial_model |
| 1070 | && model_row_matches_route( |
| 1071 | row, |
| 1072 | self.initial_provider, |
| 1073 | &self.initial_provider_identity, |
| 1074 | ) |
| 1075 | }, |
| 1076 | locked: !row.selectable, |
| 1077 | dim: row.not_listed.is_some(), |
| 1078 | } |
| 1079 | }) |
| 1080 | .collect(); |
| 1081 | let custom = self.custom_model_row_for_visible(&visible); |
| 1082 | if let Some((model, provider)) = custom.as_ref() { |
| 1083 | rows.push(PaneRow { |
| 1084 | primary: model.clone(), |
| 1085 | route: provider |
| 1086 | .compatibility() |
| 1087 | .map(|row| row.label) |
| 1088 | .unwrap_or(provider.key.as_str()) |
| 1089 | .to_string(), |
| 1090 | meta: vec![ |
| 1091 | if query.is_empty() { |
| 1092 | "current (custom)" |
| 1093 | } else { |
| 1094 | "custom route" |
| 1095 | } |
| 1096 | .to_string(), |
| 1097 | ], |
| 1098 | ..PaneRow::default() |
| 1099 | }); |
| 1100 | } |
| 1101 | *self.projection.borrow_mut() = Some(ModelPickerProjection { |
| 1102 | query: self.query.clone(), |
| 1103 | provider_filter: self.provider_filter.clone(), |
| 1104 | view: self.view, |
| 1105 | sort: self.sort, |
| 1106 | indices, |
| 1107 | rows, |
| 1108 | custom, |
| 1109 | }); |
| 1110 | } |
| 1111 | |
| 1112 | fn visible_model_rows(&self) -> VisibleModelRows<'_> { |
| 1113 | self.ensure_projection(); |
| 1114 | VisibleModelRows { |
| 1115 | catalog: &self.model_rows, |
| 1116 | indices: Ref::map(self.projection.borrow(), |projection| { |
| 1117 | projection.as_ref().unwrap().indices.as_slice() |
| 1118 | }), |
| 1119 | } |
| 1120 | } |
| 1121 | |
| 1122 | fn model_row_count(&self) -> usize { |
| 1123 | self.ensure_projection(); |
| 1124 | self.projection.borrow().as_ref().unwrap().rows.len() |
| 1125 | } |
| 1126 | |
| 1127 | /// Resolve the currently highlighted row to a model id. |
| 1128 | fn resolved_model(&self) -> String { |
| 1129 | let rows = self.visible_model_rows(); |
| 1130 | if self.selected_model_idx < rows.len() { |
| 1131 | return rows[self.selected_model_idx].id.clone(); |
| 1132 | } |
| 1133 | self.custom_model_row() |
| 1134 | .map(|(model, _)| model) |
| 1135 | .unwrap_or_else(|| self.initial_model.clone()) |
| 1136 | } |
| 1137 | |
| 1138 | fn selected_model_is_selectable(&self) -> bool { |
| 1139 | if matches!( |
| 1140 | self.purpose, |
| 1141 | ModelPickerPurpose::FleetRoute { |
| 1142 | allow_inherit: false, |
| 1143 | .. |
| 1144 | } |
| 1145 | ) && self.resolved_model() == "auto" |
| 1146 | { |
| 1147 | return false; |
| 1148 | } |
| 1149 | let rows = self.visible_model_rows(); |
| 1150 | if let Some(row) = rows.get(self.selected_model_idx) { |
| 1151 | if let Some(agent) = row.external_agent.as_ref() { |
| 1152 | return agent.runnable; |
| 1153 | } |
| 1154 | return row.selectable |
| 1155 | && row.admitted_identity.as_ref().is_some_and(|identity| { |
| 1156 | self.route_config.verify_provider_identity(identity).is_ok() |
| 1157 | }); |
| 1158 | } |
| 1159 | self.custom_model_row().is_some_and(|(model, provider)| { |
| 1160 | codewhale_engine::provider_readiness::resolve_for_model( |
| 1161 | &self.route_config, |
| 1162 | &provider, |
| 1163 | &model, |
| 1164 | &self.provider_health, |
| 1165 | ) |
| 1166 | .can_attempt() |
| 1167 | }) |
| 1168 | } |
| 1169 | |
| 1170 | /// Feedback when Enter/apply is pressed on a locked (unauthenticated) model. |
| 1171 | /// Surfaces the readiness reason instead of a silent no-op, and routes the |
| 1172 | /// user toward provider authentication/setup when possible. |
| 1173 | fn explain_unselectable_selection(&mut self) -> ViewAction { |
| 1174 | let rows = self.visible_model_rows(); |
| 1175 | let Some(row) = rows.get(self.selected_model_idx) else { |
| 1176 | return ViewAction::None; |
| 1177 | }; |
| 1178 | if let Some(agent) = row.external_agent.as_ref() { |
| 1179 | let not_ready = tr(self.locale, MessageId::ModelPickerExternalAgentNotReady); |
| 1180 | let mut detail = agent |
| 1181 | .reason |
| 1182 | .as_deref() |
| 1183 | .map(str::trim) |
| 1184 | .filter(|s| !s.is_empty()) |
| 1185 | .unwrap_or(not_ready.as_ref()) |
| 1186 | .to_string(); |
| 1187 | if agent.needs_update |
| 1188 | && let Some(upgrade) = agent |
| 1189 | .upgrade |
| 1190 | .as_deref() |
| 1191 | .map(str::trim) |
| 1192 | .filter(|s| !s.is_empty()) |
| 1193 | && !detail.contains(upgrade) |
| 1194 | { |
| 1195 | detail.push_str(&format!(" · {upgrade}")); |
| 1196 | } else if agent.state == "not_installed" |
| 1197 | && !agent.website.trim().is_empty() |
| 1198 | && !detail.contains(agent.website.trim()) |
| 1199 | { |
| 1200 | detail.push_str(&format!(" · {}", agent.website.trim())); |
| 1201 | } else if agent.state == "installed" |
| 1202 | && !agent.needs_update |
| 1203 | && agent.reason_code.as_deref() != Some("adapter_missing") |
| 1204 | && let Some(login) = agent |
| 1205 | .login |
| 1206 | .as_deref() |
| 1207 | .map(str::trim) |
| 1208 | .filter(|s| !s.is_empty()) |
| 1209 | && !detail.contains(login) |
| 1210 | { |
| 1211 | let sign_in = tr(self.locale, MessageId::ModelPickerExternalAgentSignInHint) |
| 1212 | .replace("{command}", login); |
| 1213 | detail.push_str(&format!(" · {sign_in}")); |
| 1214 | } |
| 1215 | let message = tr( |
| 1216 | self.locale, |
| 1217 | MessageId::ModelPickerExternalAgentBlockedNotice, |
| 1218 | ) |
| 1219 | .replace("{agent}", &agent.agent_name) |
| 1220 | .replace("{reason}", &detail); |
| 1221 | drop(rows); |
| 1222 | self.notice = Some((message.clone(), StatusToastLevel::Warning)); |
| 1223 | return ViewAction::Emit(ViewEvent::StatusToast { |
| 1224 | message, |
| 1225 | level: StatusToastLevel::Warning, |
| 1226 | }); |
| 1227 | } |
| 1228 | let reason = if row.hint.trim().is_empty() { |
| 1229 | "This model is not available with the current provider credentials.".to_string() |
| 1230 | } else { |
| 1231 | row.hint.clone() |
| 1232 | }; |
| 1233 | let route = row.provider_identity.as_deref().unwrap_or( |
| 1234 | row.provider |
| 1235 | .map(ProviderKind::as_str) |
| 1236 | .unwrap_or("unknown route"), |
| 1237 | ); |
| 1238 | let message = format!( |
| 1239 | "! {route}/{} is locked — {reason}. Open /provider and select {route} to authenticate, then refresh.", |
| 1240 | row.id |
| 1241 | ); |
| 1242 | // The ordinary setup wizard switches the session after auth. A |
| 1243 | // Fleet edit must keep that session route intact. |
| 1244 | if self.purpose != ModelPickerPurpose::Session { |
| 1245 | return ViewAction::Emit(ViewEvent::StatusToast { |
| 1246 | message, |
| 1247 | level: crate::tui::app::StatusToastLevel::Error, |
| 1248 | }); |
| 1249 | } |
| 1250 | // Prefer opening provider setup so the user can remediate in one step. |
| 1251 | if let Some(identity) = row |
| 1252 | .admitted_identity |
| 1253 | .as_ref() |
| 1254 | .filter(|identity| self.route_config.verify_provider_identity(identity).is_ok()) |
| 1255 | { |
| 1256 | return ViewAction::Emit(ViewEvent::ModelPickerNeedsAuth { |
| 1257 | identity: identity.clone(), |
| 1258 | model: row.id.clone(), |
| 1259 | reason: message, |
| 1260 | }); |
| 1261 | } |
| 1262 | ViewAction::Emit(ViewEvent::StatusToast { |
| 1263 | message, |
| 1264 | level: crate::tui::app::StatusToastLevel::Error, |
| 1265 | }) |
| 1266 | } |
| 1267 | |
| 1268 | /// Exact route identity of the highlighted row, when it names one. |
| 1269 | #[cfg(test)] |
| 1270 | fn resolved_provider_identity(&self) -> Option<String> { |
| 1271 | self.resolved_admitted_identity() |
| 1272 | .map(|identity| identity.key.to_string()) |
| 1273 | } |
| 1274 | |
| 1275 | fn resolved_admitted_identity(&self) -> Option<codewhale_runtime::config::ProviderIdentity> { |
| 1276 | let rows = self.visible_model_rows(); |
| 1277 | let identity = if let Some(row) = rows.get(self.selected_model_idx) { |
| 1278 | row.admitted_identity.clone() |
| 1279 | } else { |
| 1280 | self.custom_model_row().map(|(_, identity)| identity) |
| 1281 | }?; |
| 1282 | self.route_config.verify_provider_identity(&identity).ok()?; |
| 1283 | Some(identity) |
| 1284 | } |
| 1285 | |
| 1286 | fn resolved_provider(&self) -> Option<ProviderKind> { |
| 1287 | let rows = self.visible_model_rows(); |
| 1288 | if self.selected_model_idx < rows.len() { |
| 1289 | return rows[self.selected_model_idx].provider; |
| 1290 | } |
| 1291 | self.custom_model_row() |
| 1292 | .map(|(_, identity)| identity.provider) |
| 1293 | .or(Some(self.initial_provider)) |
| 1294 | } |
| 1295 | |
| 1296 | fn resolved_effort(&self) -> ReasoningEffort { |
| 1297 | let efforts = self.current_efforts(); |
| 1298 | efforts[self |
| 1299 | .selected_effort_idx |
| 1300 | .min(efforts.len().saturating_sub(1))] |
| 1301 | } |
| 1302 | |
| 1303 | fn current_efforts(&self) -> Vec<ReasoningEffort> { |
| 1304 | if matches!( |
| 1305 | self.purpose, |
| 1306 | ModelPickerPurpose::FleetRoute { |
| 1307 | allow_inherit: false, |
| 1308 | .. |
| 1309 | } |
| 1310 | ) { |
| 1311 | return vec![ReasoningEffort::Auto]; |
| 1312 | } |
| 1313 | if let ModelPickerPurpose::FleetRoute { |
| 1314 | initial_reasoning, .. |
| 1315 | } |
| 1316 | | ModelPickerPurpose::FleetProfileRoute { |
| 1317 | initial_reasoning, .. |
| 1318 | } = self.purpose |
| 1319 | && self.resolved_model() == "auto" |
| 1320 | { |
| 1321 | return vec![initial_reasoning.unwrap_or(ReasoningEffort::Auto)]; |
| 1322 | } |
| 1323 | let provider = self.resolved_provider().unwrap_or(self.initial_provider); |
| 1324 | let model = self.resolved_model(); |
| 1325 | let base_url = self.resolved_base_url_for_provider(provider, &model); |
| 1326 | let model_is_auto = model.trim().eq_ignore_ascii_case("auto"); |
| 1327 | if !model_is_auto |
| 1328 | && provider == ProviderKind::OpenaiCodex |
| 1329 | && let Some(row) = self.visible_model_rows().get(self.selected_model_idx) |
| 1330 | && !row.metadata.codex_efforts.is_empty() |
| 1331 | { |
| 1332 | let mut efforts = vec![ReasoningEffort::Auto]; |
| 1333 | for token in &row.metadata.codex_efforts { |
| 1334 | if let Some(effort) = ReasoningEffort::from_catalog_token(token) |
| 1335 | && !efforts.contains(&effort) |
| 1336 | { |
| 1337 | efforts.push(effort); |
| 1338 | } |
| 1339 | } |
| 1340 | if efforts.len() > 1 { |
| 1341 | return distinct_effective_efforts(efforts, provider, &base_url, &model); |
| 1342 | } |
| 1343 | } |
| 1344 | picker_efforts_for_route(provider, &base_url, &model, model_is_auto) |
| 1345 | } |
| 1346 | |
| 1347 | fn resolved_base_url_for_provider(&self, _provider: ProviderKind, model: &str) -> String { |
| 1348 | let Some(identity) = self.resolved_admitted_identity() else { |
| 1349 | return String::new(); |
| 1350 | }; |
| 1351 | codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 1352 | &self.route_config, |
| 1353 | &identity, |
| 1354 | Some(model), |
| 1355 | ) |
| 1356 | .map(|route| route.candidate.endpoint().base_url.clone()) |
| 1357 | .unwrap_or_else(|_| self.route_config.base_url_for_route(&identity)) |
| 1358 | } |
| 1359 | |
| 1360 | fn custom_model_row(&self) -> Option<(String, codewhale_runtime::config::ProviderIdentity)> { |
| 1361 | self.ensure_projection(); |
| 1362 | self.projection.borrow().as_ref().unwrap().custom.clone() |
| 1363 | } |
| 1364 | |
| 1365 | fn custom_model_row_for_visible( |
| 1366 | &self, |
| 1367 | visible_rows: &[&ModelPickerRow], |
| 1368 | ) -> Option<(String, codewhale_runtime::config::ProviderIdentity)> { |
| 1369 | let query = self.query.trim(); |
| 1370 | if query.is_empty() { |
| 1371 | return self |
| 1372 | .show_custom_model_row |
| 1373 | .then(|| self.initial_identity.clone()) |
| 1374 | .flatten() |
| 1375 | .map(|identity| (self.initial_model.clone(), identity)); |
| 1376 | } |
| 1377 | if let Some((provider, model)) = self.provider_qualified_custom_query(query) { |
| 1378 | if visible_rows.iter().any(|row| { |
| 1379 | row.admitted_identity.as_ref() == Some(&provider) && row.id == model.trim() |
| 1380 | }) { |
| 1381 | return None; |
| 1382 | } |
| 1383 | if self.provider_accepts_custom_model(&provider, &model) { |
| 1384 | return Some((model, provider)); |
| 1385 | } |
| 1386 | return None; |
| 1387 | } |
| 1388 | if !self.active_accepts_custom_model_ids { |
| 1389 | return None; |
| 1390 | } |
| 1391 | if visible_rows.iter().any(|row| { |
| 1392 | row.admitted_identity.as_ref() == self.initial_identity.as_ref() && row.id == query |
| 1393 | }) { |
| 1394 | return None; |
| 1395 | } |
| 1396 | self.initial_identity |
| 1397 | .clone() |
| 1398 | .map(|identity| (query.to_string(), identity)) |
| 1399 | } |
| 1400 | |
| 1401 | fn provider_qualified_custom_query( |
| 1402 | &self, |
| 1403 | query: &str, |
| 1404 | ) -> Option<(codewhale_runtime::config::ProviderIdentity, String)> { |
| 1405 | for (provider_key, model) in provider_query_splits(query) { |
| 1406 | let Ok(provider) = self.route_config.legacy_selection_identity(provider_key) else { |
| 1407 | continue; |
| 1408 | }; |
| 1409 | if Some(&provider) != self.initial_identity.as_ref() |
| 1410 | && !self.view.browses_all_providers() |
| 1411 | && !self.configured_providers.contains(&provider) |
| 1412 | { |
| 1413 | continue; |
| 1414 | } |
| 1415 | let model = model.trim(); |
| 1416 | if model.is_empty() { |
| 1417 | continue; |
| 1418 | } |
| 1419 | return Some((provider, model.to_string())); |
| 1420 | } |
| 1421 | None |
| 1422 | } |
| 1423 | |
| 1424 | fn provider_accepts_custom_model( |
| 1425 | &self, |
| 1426 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 1427 | model: &str, |
| 1428 | ) -> bool { |
| 1429 | (Some(identity) == self.initial_identity.as_ref() && self.active_accepts_custom_model_ids) |
| 1430 | || (Some(identity) != self.initial_identity.as_ref() |
| 1431 | && self |
| 1432 | .route_config |
| 1433 | .model_ids_pass_through_for_provider(identity)) |
| 1434 | || codewhale_config::route::resolve_model(identity.provider, model, None).is_ok() |
| 1435 | } |
| 1436 | |
| 1437 | fn clamp_model_selection(&mut self) { |
| 1438 | let count = self.model_row_count(); |
| 1439 | if count == 0 { |
| 1440 | self.selected_model_idx = 0; |
| 1441 | } else if self.selected_model_idx >= count { |
| 1442 | self.selected_model_idx = count - 1; |
| 1443 | } |
| 1444 | } |
| 1445 | |
| 1446 | fn update_query(&mut self, next: String) { |
| 1447 | self.query = next; |
| 1448 | self.selected_model_idx = 0; |
| 1449 | self.clamp_model_selection(); |
| 1450 | self.select_effort_for_current_model(); |
| 1451 | } |
| 1452 | |
| 1453 | fn select_effort_for_current_model(&mut self) { |
| 1454 | let provider = self.resolved_provider().unwrap_or(self.initial_provider); |
| 1455 | let model = self.resolved_model(); |
| 1456 | let model_is_auto = model.trim().eq_ignore_ascii_case("auto"); |
| 1457 | let base_url = self.resolved_base_url_for_provider(provider, &model); |
| 1458 | let normalized = normalize_picker_effort( |
| 1459 | self.selected_effort_request, |
| 1460 | provider, |
| 1461 | &base_url, |
| 1462 | &model, |
| 1463 | model_is_auto, |
| 1464 | ); |
| 1465 | self.selected_effort_idx = self |
| 1466 | .current_efforts() |
| 1467 | .iter() |
| 1468 | .position(|candidate| *candidate == normalized) |
| 1469 | .unwrap_or_else(|| { |
| 1470 | default_picker_effort_idx(provider, &base_url, &model, model_is_auto) |
| 1471 | }); |
| 1472 | self.select_context_for_current_model(); |
| 1473 | } |
| 1474 | |
| 1475 | fn select_context_for_current_model(&mut self) { |
| 1476 | let model = self.resolved_model(); |
| 1477 | let per_model = self.resolved_admitted_identity().and_then(|identity| { |
| 1478 | self.route_config |
| 1479 | .model_context_windows_for(&identity) |
| 1480 | .and_then(|windows| windows.get(model.trim()).copied()) |
| 1481 | }); |
| 1482 | self.initial_context_override = per_model; |
| 1483 | self.custom_context_error = None; |
| 1484 | match per_model { |
| 1485 | None => { |
| 1486 | self.selected_context_idx = 0; |
| 1487 | self.custom_context_input.clear(); |
| 1488 | } |
| 1489 | Some(tokens) => { |
| 1490 | if let Some(pos) = CONTEXT_CHOICES |
| 1491 | .iter() |
| 1492 | .position(|choice| *choice == ContextChoice::Tokens(tokens)) |
| 1493 | { |
| 1494 | self.selected_context_idx = pos; |
| 1495 | self.custom_context_input.clear(); |
| 1496 | } else { |
| 1497 | self.selected_context_idx = CONTEXT_CHOICES.len() - 1; |
| 1498 | self.custom_context_input = tokens.to_string(); |
| 1499 | } |
| 1500 | } |
| 1501 | } |
| 1502 | } |
| 1503 | |
| 1504 | fn can_edit_context(&self) -> bool { |
| 1505 | if self.purpose != ModelPickerPurpose::Session { |
| 1506 | return false; |
| 1507 | } |
| 1508 | if self |
| 1509 | .visible_model_rows() |
| 1510 | .get(self.selected_model_idx) |
| 1511 | .is_some_and(|row| row.external_agent.is_some()) |
| 1512 | { |
| 1513 | return false; |
| 1514 | } |
| 1515 | let model = self.resolved_model(); |
| 1516 | !model.trim().is_empty() && !model.trim().eq_ignore_ascii_case("auto") |
| 1517 | } |
| 1518 | |
| 1519 | fn editing_custom_context(&self) -> bool { |
| 1520 | self.focus == Pane::Context |
| 1521 | && CONTEXT_CHOICES.get(self.selected_context_idx) == Some(&ContextChoice::Custom) |
| 1522 | } |
| 1523 | |
| 1524 | fn selected_context_override(&self) -> Result<Option<u32>, String> { |
| 1525 | match CONTEXT_CHOICES |
| 1526 | .get(self.selected_context_idx) |
| 1527 | .copied() |
| 1528 | .unwrap_or(ContextChoice::Auto) |
| 1529 | { |
| 1530 | ContextChoice::Auto => Ok(None), |
| 1531 | ContextChoice::Tokens(tokens) => Ok(Some(tokens)), |
| 1532 | ContextChoice::Custom |
| 1533 | if self.initial_context_override.is_some_and(|tokens| { |
| 1534 | self.custom_context_input.trim() == tokens.to_string() |
| 1535 | }) => |
| 1536 | { |
| 1537 | Ok(self.initial_context_override) |
| 1538 | } |
| 1539 | ContextChoice::Custom => { |
| 1540 | codewhale_command_contract::outcome::parse_context_window_limit( |
| 1541 | &self.custom_context_input, |
| 1542 | ) |
| 1543 | .map(Some) |
| 1544 | } |
| 1545 | } |
| 1546 | } |
| 1547 | |
| 1548 | fn resolved_context_override_change(&mut self) -> Result<Option<Option<u32>>, ()> { |
| 1549 | if !self.can_edit_context() { |
| 1550 | return Ok(None); |
| 1551 | } |
| 1552 | let choice = CONTEXT_CHOICES |
| 1553 | .get(self.selected_context_idx) |
| 1554 | .copied() |
| 1555 | .unwrap_or(ContextChoice::Auto); |
| 1556 | if choice == ContextChoice::Custom && self.custom_context_input.trim().is_empty() { |
| 1557 | self.custom_context_error = |
| 1558 | Some("Enter a token count (e.g. 1000000, 1m, 272k) or choose auto.".to_string()); |
| 1559 | return Err(()); |
| 1560 | } |
| 1561 | match self.selected_context_override() { |
| 1562 | Ok(next) => { |
| 1563 | self.custom_context_error = None; |
| 1564 | Ok((next != self.initial_context_override).then_some(next)) |
| 1565 | } |
| 1566 | Err(err) => { |
| 1567 | self.custom_context_error = Some(err); |
| 1568 | Err(()) |
| 1569 | } |
| 1570 | } |
| 1571 | } |
| 1572 | |
| 1573 | /// Both panes rotate rather than stop at the ends. Thinking is four to six |
| 1574 | /// rows, so a hard stop at the bottom reads as a dead key rather than as a |
| 1575 | /// boundary; the model list wraps for the same reason. |
| 1576 | fn move_up(&mut self) -> bool { |
| 1577 | match self.focus { |
| 1578 | Pane::Model => { |
| 1579 | let count = self.model_row_count(); |
| 1580 | if count == 0 { |
| 1581 | return false; |
| 1582 | } |
| 1583 | self.selected_model_idx = wrapping_prev(self.selected_model_idx, count); |
| 1584 | self.select_effort_for_current_model(); |
| 1585 | true |
| 1586 | } |
| 1587 | Pane::Effort => { |
| 1588 | let count = self.current_efforts().len(); |
| 1589 | if count == 0 { |
| 1590 | return false; |
| 1591 | } |
| 1592 | self.selected_effort_idx = wrapping_prev(self.selected_effort_idx, count); |
| 1593 | self.selected_effort_request = self.resolved_effort(); |
| 1594 | true |
| 1595 | } |
| 1596 | Pane::Context => { |
| 1597 | let count = CONTEXT_CHOICES.len(); |
| 1598 | self.selected_context_idx = wrapping_prev(self.selected_context_idx, count); |
| 1599 | self.custom_context_error = None; |
| 1600 | true |
| 1601 | } |
| 1602 | } |
| 1603 | } |
| 1604 | |
| 1605 | fn move_down(&mut self) -> bool { |
| 1606 | match self.focus { |
| 1607 | Pane::Model => { |
| 1608 | let count = self.model_row_count(); |
| 1609 | if count == 0 { |
| 1610 | return false; |
| 1611 | } |
| 1612 | self.selected_model_idx = wrapping_next(self.selected_model_idx, count); |
| 1613 | self.select_effort_for_current_model(); |
| 1614 | true |
| 1615 | } |
| 1616 | Pane::Effort => { |
| 1617 | let count = self.current_efforts().len(); |
| 1618 | if count == 0 { |
| 1619 | return false; |
| 1620 | } |
| 1621 | self.selected_effort_idx = wrapping_next(self.selected_effort_idx, count); |
| 1622 | self.selected_effort_request = self.resolved_effort(); |
| 1623 | true |
| 1624 | } |
| 1625 | Pane::Context => { |
| 1626 | let count = CONTEXT_CHOICES.len(); |
| 1627 | self.selected_context_idx = wrapping_next(self.selected_context_idx, count); |
| 1628 | self.custom_context_error = None; |
| 1629 | true |
| 1630 | } |
| 1631 | } |
| 1632 | } |
| 1633 | |
| 1634 | /// Apply one [`list_nav`](codewhale_tui_kit::list_nav) motion (#6290), returning |
| 1635 | /// whether it was consumed. Steps wrap; pages travel [`MODEL_PAGE`] rows |
| 1636 | /// and clamp. The region axis toggles between the model and effort panes. |
| 1637 | fn apply_motion(&mut self, motion: codewhale_tui_kit::list_nav::Motion) -> bool { |
| 1638 | use codewhale_tui_kit::list_nav::Motion; |
| 1639 | if matches!(motion, Motion::RegionPrev | Motion::RegionNext) { |
| 1640 | if self.can_edit_effort() || self.can_edit_context() { |
| 1641 | if motion == Motion::RegionPrev { |
| 1642 | self.toggle_focus_reverse(); |
| 1643 | } else { |
| 1644 | self.toggle_focus(); |
| 1645 | } |
| 1646 | } |
| 1647 | return true; |
| 1648 | } |
| 1649 | let (current, len) = match self.focus { |
| 1650 | Pane::Model => (self.selected_model_idx, self.model_row_count()), |
| 1651 | Pane::Effort => (self.selected_effort_idx, self.current_efforts().len()), |
| 1652 | Pane::Context => (self.selected_context_idx, CONTEXT_CHOICES.len()), |
| 1653 | }; |
| 1654 | if len == 0 { |
| 1655 | return false; |
| 1656 | } |
| 1657 | let Some(next) = codewhale_tui_kit::list_nav::apply(current, len, MODEL_PAGE, motion) |
| 1658 | else { |
| 1659 | return false; |
| 1660 | }; |
| 1661 | match self.focus { |
| 1662 | Pane::Model => { |
| 1663 | self.selected_model_idx = next; |
| 1664 | self.select_effort_for_current_model(); |
| 1665 | } |
| 1666 | Pane::Effort => { |
| 1667 | self.selected_effort_idx = next; |
| 1668 | self.selected_effort_request = self.resolved_effort(); |
| 1669 | } |
| 1670 | Pane::Context => { |
| 1671 | self.selected_context_idx = next; |
| 1672 | self.custom_context_error = None; |
| 1673 | } |
| 1674 | } |
| 1675 | true |
| 1676 | } |
| 1677 | |
| 1678 | fn toggle_focus(&mut self) { |
| 1679 | self.focus = match self.focus { |
| 1680 | Pane::Model if self.can_edit_effort() => Pane::Effort, |
| 1681 | Pane::Model if self.can_edit_context() => Pane::Context, |
| 1682 | Pane::Effort if self.can_edit_context() => Pane::Context, |
| 1683 | Pane::Effort | Pane::Context | Pane::Model => Pane::Model, |
| 1684 | }; |
| 1685 | } |
| 1686 | |
| 1687 | fn toggle_focus_reverse(&mut self) { |
| 1688 | self.focus = match self.focus { |
| 1689 | Pane::Model if self.can_edit_context() => Pane::Context, |
| 1690 | Pane::Model if self.can_edit_effort() => Pane::Effort, |
| 1691 | Pane::Context if self.can_edit_effort() => Pane::Effort, |
| 1692 | Pane::Effort | Pane::Context | Pane::Model => Pane::Model, |
| 1693 | }; |
| 1694 | } |
| 1695 | |
| 1696 | fn toggle_view(&mut self) { |
| 1697 | self.view = self.view.next(); |
| 1698 | self.selected_model_idx = 0; |
| 1699 | self.clamp_model_selection(); |
| 1700 | self.select_effort_for_current_model(); |
| 1701 | } |
| 1702 | |
| 1703 | fn build_event_with_startup_default( |
| 1704 | &self, |
| 1705 | save_as_startup_default: bool, |
| 1706 | context_window_override: Option<Option<u32>>, |
| 1707 | ) -> ViewEvent { |
| 1708 | ViewEvent::ModelPickerApplied { |
| 1709 | model: self.resolved_model(), |
| 1710 | identity: self.resolved_admitted_identity(), |
| 1711 | route_selection: self |
| 1712 | .visible_model_rows() |
| 1713 | .get(self.selected_model_idx) |
| 1714 | .and_then(|row| row.route_selection.clone()), |
| 1715 | effort: self.selected_effort_request, |
| 1716 | previous_model: self.previous_model.clone(), |
| 1717 | previous_effort: self.initial_effort, |
| 1718 | context_window_override, |
| 1719 | save_as_startup_default, |
| 1720 | } |
| 1721 | } |
| 1722 | |
| 1723 | /// The event Enter (or the startup-default chord) emits, by purpose. A |
| 1724 | /// Fleet row gets its absolute route — provider resolved, `Custom` named |
| 1725 | /// by its exact identity — and has no startup default to save. |
| 1726 | fn build_apply_event(&self, save_as_startup_default: bool) -> ViewEvent { |
| 1727 | let context_window_override = if self.can_edit_context() { |
| 1728 | self.selected_context_override() |
| 1729 | .ok() |
| 1730 | .and_then(|next| (next != self.initial_context_override).then_some(next)) |
| 1731 | } else { |
| 1732 | None |
| 1733 | }; |
| 1734 | let (initial_reasoning, allow_inherit) = match self.purpose { |
| 1735 | ModelPickerPurpose::Session => { |
| 1736 | if let Some(agent) = self |
| 1737 | .visible_model_rows() |
| 1738 | .get(self.selected_model_idx) |
| 1739 | .and_then(|row| row.external_agent.as_ref()) |
| 1740 | { |
| 1741 | return ViewEvent::ExternalAgentSelected { |
| 1742 | agent_id: agent.agent_id.clone(), |
| 1743 | agent_name: agent.agent_name.clone(), |
| 1744 | }; |
| 1745 | } |
| 1746 | return self.build_event_with_startup_default( |
| 1747 | save_as_startup_default, |
| 1748 | context_window_override, |
| 1749 | ); |
| 1750 | } |
| 1751 | ModelPickerPurpose::FleetRoute { |
| 1752 | initial_reasoning, |
| 1753 | allow_inherit, |
| 1754 | .. |
| 1755 | } => (initial_reasoning, allow_inherit), |
| 1756 | ModelPickerPurpose::FleetProfileRoute { |
| 1757 | initial_reasoning, .. |
| 1758 | } => (initial_reasoning, true), |
| 1759 | }; |
| 1760 | let captured = self.resolved_admitted_identity(); |
| 1761 | let provider = captured |
| 1762 | .as_ref() |
| 1763 | .map_or(self.initial_provider, |identity| identity.provider); |
| 1764 | let provider_id = captured.as_ref().map(|identity| identity.key.to_string()); |
| 1765 | let model = self.resolved_model(); |
| 1766 | let reasoning = if !allow_inherit { |
| 1767 | None |
| 1768 | } else if model == "auto" || self.selected_effort_request == self.initial_effort { |
| 1769 | initial_reasoning |
| 1770 | } else { |
| 1771 | Some(self.selected_effort_request) |
| 1772 | }; |
| 1773 | match self.purpose { |
| 1774 | ModelPickerPurpose::FleetRoute { |
| 1775 | target, editor_id, .. |
| 1776 | } => ViewEvent::FleetRoutePicked { |
| 1777 | target, |
| 1778 | editor_id, |
| 1779 | provider, |
| 1780 | provider_id, |
| 1781 | model, |
| 1782 | reasoning, |
| 1783 | }, |
| 1784 | ModelPickerPurpose::FleetProfileRoute { editor_id, .. } => { |
| 1785 | ViewEvent::FleetProfileRoutePicked { |
| 1786 | editor_id, |
| 1787 | provider, |
| 1788 | provider_id, |
| 1789 | model, |
| 1790 | reasoning, |
| 1791 | } |
| 1792 | } |
| 1793 | ModelPickerPurpose::Session => unreachable!("session handled above"), |
| 1794 | } |
| 1795 | } |
| 1796 | |
| 1797 | /// Footer label for Enter: apply to the session, or assign to a Fleet row. |
| 1798 | fn apply_action_id(&self) -> MessageId { |
| 1799 | match self.purpose { |
| 1800 | ModelPickerPurpose::Session => MessageId::PickerActionApply, |
| 1801 | ModelPickerPurpose::FleetRoute { .. } |
| 1802 | | ModelPickerPurpose::FleetProfileRoute { .. } => MessageId::PickerActionAssignRoute, |
| 1803 | } |
| 1804 | } |
| 1805 | |
| 1806 | fn can_edit_effort(&self) -> bool { |
| 1807 | if self |
| 1808 | .visible_model_rows() |
| 1809 | .get(self.selected_model_idx) |
| 1810 | .is_some_and(|row| row.external_agent.is_some()) |
| 1811 | { |
| 1812 | return false; |
| 1813 | } |
| 1814 | match self.purpose { |
| 1815 | ModelPickerPurpose::Session => true, |
| 1816 | ModelPickerPurpose::FleetProfileRoute { .. } => self.resolved_model() != "auto", |
| 1817 | // Shortlisted rows pin a model only; inherited routes retain |
| 1818 | // their existing reasoning until a concrete model is selected. |
| 1819 | ModelPickerPurpose::FleetRoute { allow_inherit, .. } => { |
| 1820 | allow_inherit && self.resolved_model() != "auto" |
| 1821 | } |
| 1822 | } |
| 1823 | } |
| 1824 | |
| 1825 | fn set_sort(&mut self, sort: Option<ModelSort>) { |
| 1826 | let selected = self |
| 1827 | .visible_model_rows() |
| 1828 | .indices |
| 1829 | .get(self.selected_model_idx) |
| 1830 | .copied(); |
| 1831 | let was_custom = selected.is_none() && self.custom_model_row().is_some(); |
| 1832 | self.sort = sort; |
| 1833 | self.last_mouse_selected = None; |
| 1834 | self.ensure_projection(); |
| 1835 | if let Some(selected) = selected { |
| 1836 | let position = self |
| 1837 | .visible_model_rows() |
| 1838 | .indices |
| 1839 | .iter() |
| 1840 | .position(|index| *index == selected); |
| 1841 | if let Some(position) = position { |
| 1842 | self.selected_model_idx = position; |
| 1843 | } |
| 1844 | } else if was_custom { |
| 1845 | let visible_len = self.visible_model_rows().len(); |
| 1846 | self.selected_model_idx = visible_len; |
| 1847 | } |
| 1848 | self.clamp_model_selection(); |
| 1849 | self.select_effort_for_current_model(); |
| 1850 | } |
| 1851 | |
| 1852 | fn sort_column(&mut self, column: ModelSortColumn) { |
| 1853 | let descending = self |
| 1854 | .sort |
| 1855 | .is_some_and(|sort| sort.column == column && !sort.descending); |
| 1856 | self.set_sort(Some(ModelSort { column, descending })); |
| 1857 | } |
| 1858 | |
| 1859 | fn cycle_sort(&mut self) { |
| 1860 | use ModelSortColumn::{Context, Model, Provider}; |
| 1861 | let next = match self.sort { |
| 1862 | None => Some(ModelSort { |
| 1863 | column: Model, |
| 1864 | descending: false, |
| 1865 | }), |
| 1866 | Some(ModelSort { |
| 1867 | column, |
| 1868 | descending: false, |
| 1869 | }) => Some(ModelSort { |
| 1870 | column, |
| 1871 | descending: true, |
| 1872 | }), |
| 1873 | Some(ModelSort { |
| 1874 | column: Model, |
| 1875 | descending: true, |
| 1876 | }) => Some(ModelSort { |
| 1877 | column: Provider, |
| 1878 | descending: false, |
| 1879 | }), |
| 1880 | Some(ModelSort { |
| 1881 | column: Provider, |
| 1882 | descending: true, |
| 1883 | }) => Some(ModelSort { |
| 1884 | column: Context, |
| 1885 | descending: false, |
| 1886 | }), |
| 1887 | Some(ModelSort { |
| 1888 | column: Context, |
| 1889 | descending: true, |
| 1890 | }) => None, |
| 1891 | }; |
| 1892 | self.set_sort(next); |
| 1893 | } |
| 1894 | |
| 1895 | fn effective_view(&self) -> ModelListView { |
| 1896 | if self.view == ModelListView::Configured |
| 1897 | && self |
| 1898 | .sort |
| 1899 | .is_some_and(|sort| sort.column == ModelSortColumn::Provider) |
| 1900 | { |
| 1901 | ModelListView::Catalog |
| 1902 | } else { |
| 1903 | self.view |
| 1904 | } |
| 1905 | } |
| 1906 | |
| 1907 | fn cycle_provider_filter(&mut self) { |
| 1908 | let choices = self.provider_filter_choices(); |
| 1909 | let next = match self.provider_filter.as_deref() { |
| 1910 | None => choices.first().cloned(), |
| 1911 | Some(current) => choices |
| 1912 | .iter() |
| 1913 | .position(|key| key == current) |
| 1914 | .and_then(|index| choices.get(index + 1).cloned()), |
| 1915 | }; |
| 1916 | self.set_provider_filter(next); |
| 1917 | } |
| 1918 | |
| 1919 | fn provider_filter_choices(&self) -> Vec<String> { |
| 1920 | let mut keys: Vec<String> = self |
| 1921 | .model_rows |
| 1922 | .iter() |
| 1923 | .filter(|row| model_row_visible_in_view(row, self.effective_view())) |
| 1924 | .filter_map(row_provider_filter_key) |
| 1925 | .collect(); |
| 1926 | keys.sort(); |
| 1927 | keys.dedup(); |
| 1928 | keys.sort_by_cached_key(|key| (provider_filter_label(key).to_lowercase(), key.clone())); |
| 1929 | keys |
| 1930 | } |
| 1931 | |
| 1932 | fn set_provider_filter(&mut self, next: Option<String>) { |
| 1933 | if self.provider_filter == next { |
| 1934 | return; |
| 1935 | } |
| 1936 | self.provider_filter = next; |
| 1937 | self.selected_model_idx = 0; |
| 1938 | self.clamp_model_selection(); |
| 1939 | self.select_effort_for_current_model(); |
| 1940 | } |
| 1941 | |
| 1942 | fn render_sort_columns(&self, area: Rect, buf: &mut Buffer, columns: ModelRowColumns) { |
| 1943 | let label = |name: &str, column| match self.sort.filter(|sort| sort.column == column) { |
| 1944 | Some(sort) => format!("{name} {}", if sort.descending { "↓" } else { "↑" }), |
| 1945 | None => name.to_string(), |
| 1946 | }; |
| 1947 | let row = PaneRow { |
| 1948 | primary: label("Model", ModelSortColumn::Model), |
| 1949 | route: label("Provider", ModelSortColumn::Provider), |
| 1950 | meta: vec![label("Context", ModelSortColumn::Context)], |
| 1951 | ..PaneRow::default() |
| 1952 | }; |
| 1953 | let style = Style::default().fg(palette::TEXT_MUTED).bold(); |
| 1954 | Paragraph::new(Line::from(picker_row_spans( |
| 1955 | &row, |
| 1956 | " ", |
| 1957 | " ", |
| 1958 | usize::from(area.width), |
| 1959 | columns, |
| 1960 | style, |
| 1961 | style, |
| 1962 | style, |
| 1963 | ))) |
| 1964 | .render(area, buf); |
| 1965 | let fitted = columns.resolve(usize::from(area.width)); |
| 1966 | let mut x = usize::from(area.x) + ROW_PREFIX_WIDTH; |
| 1967 | let right = usize::from(area.right()); |
| 1968 | for (width, column) in [ |
| 1969 | (fitted.primary, ModelSortColumn::Model), |
| 1970 | (fitted.route, ModelSortColumn::Provider), |
| 1971 | (fitted.meta, ModelSortColumn::Context), |
| 1972 | ] { |
| 1973 | if width > 0 { |
| 1974 | if x < right { |
| 1975 | self.column_hitboxes.borrow_mut().push(( |
| 1976 | Rect::new(x as u16, area.y, width.min(right - x) as u16, 1), |
| 1977 | column, |
| 1978 | )); |
| 1979 | } |
| 1980 | x += width + COLUMN_GAP; |
| 1981 | } |
| 1982 | } |
| 1983 | } |
| 1984 | |
| 1985 | fn render_pane( |
| 1986 | &self, |
| 1987 | area: Rect, |
| 1988 | buf: &mut Buffer, |
| 1989 | title: &str, |
| 1990 | rows: &[PaneRow], |
| 1991 | state: PaneRenderState, |
| 1992 | ) { |
| 1993 | self.pane_hitboxes.borrow_mut().push((area, state.pane)); |
| 1994 | if area.height == 1 && !state.focused { |
| 1995 | let summary = rows.get(state.selected).map_or_else( |
| 1996 | || title.to_string(), |
| 1997 | |row| format!("{title}: {}", row.primary), |
| 1998 | ); |
| 1999 | Paragraph::new(codewhale_tui_kit::ui_text::semantic_truncate( |
| 2000 | &summary, |
| 2001 | usize::from(area.width), |
| 2002 | )) |
| 2003 | .style(Style::default().fg(palette::TEXT_MUTED)) |
| 2004 | .render(area, buf); |
| 2005 | if !rows.is_empty() { |
| 2006 | self.row_hitboxes |
| 2007 | .borrow_mut() |
| 2008 | .push((area, state.pane, state.selected)); |
| 2009 | } |
| 2010 | return; |
| 2011 | } |
| 2012 | let header_height = if state.pane == Pane::Model && area.height >= 3 { |
| 2013 | 2 |
| 2014 | } else { |
| 2015 | 1 |
| 2016 | }; |
| 2017 | let visible_height = usize::from(area.height.saturating_sub(header_height)); |
| 2018 | let (start, end) = pane_row_window(state.selected, rows, visible_height); |
| 2019 | let title_badge = if rows.len() > visible_height && visible_height > 0 { |
| 2020 | if start + 1 == end { |
| 2021 | format!("{}/{}", end, rows.len()) |
| 2022 | } else { |
| 2023 | format!("{}-{}/{}", start + 1, end, rows.len()) |
| 2024 | } |
| 2025 | } else { |
| 2026 | String::new() |
| 2027 | }; |
| 2028 | let accent = active_modal_accent_color(); |
| 2029 | let title_area = Rect { height: 1, ..area }; |
| 2030 | let mut title_spans = vec![ |
| 2031 | Span::styled( |
| 2032 | if state.focused { |
| 2033 | format!(" {} ", codewhale_tui_kit::glyphs::SELECTION) |
| 2034 | } else { |
| 2035 | " ".to_string() |
| 2036 | }, |
| 2037 | Style::default().fg(accent), |
| 2038 | ), |
| 2039 | Span::styled( |
| 2040 | title.to_string(), |
| 2041 | Style::default() |
| 2042 | .fg(if state.focused { |
| 2043 | accent |
| 2044 | } else { |
| 2045 | palette::TEXT_MUTED |
| 2046 | }) |
| 2047 | .bold(), |
| 2048 | ), |
| 2049 | ]; |
| 2050 | if !title_badge.is_empty() { |
| 2051 | title_spans.push(Span::styled( |
| 2052 | format!(" {title_badge}"), |
| 2053 | Style::default().fg(palette::TEXT_DIM), |
| 2054 | )); |
| 2055 | } |
| 2056 | Paragraph::new(Line::from(title_spans)).render(title_area, buf); |
| 2057 | let raw_inner = Rect { |
| 2058 | y: area.y.saturating_add(header_height), |
| 2059 | height: area.height.saturating_sub(header_height), |
| 2060 | ..area |
| 2061 | }; |
| 2062 | let inner = render_panel_scroll_rail( |
| 2063 | raw_inner, |
| 2064 | buf, |
| 2065 | rows.len(), |
| 2066 | start, |
| 2067 | visible_height, |
| 2068 | state.focused, |
| 2069 | ); |
| 2070 | |
| 2071 | let mut columns = ModelRowColumns::for_rows(rows); |
| 2072 | if header_height == 2 { |
| 2073 | columns.primary = columns.primary.max(7); |
| 2074 | columns.route = columns.route.max(10); |
| 2075 | columns.meta = columns.meta.max(9); |
| 2076 | self.render_sort_columns(Rect::new(inner.x, area.y + 1, inner.width, 1), buf, columns); |
| 2077 | } |
| 2078 | |
| 2079 | let mut lines = Vec::with_capacity(end.saturating_sub(start)); |
| 2080 | let pane_height = usize::from(inner.height); |
| 2081 | for (idx, row) in rows.iter().enumerate().skip(start).take(end - start) { |
| 2082 | if lines.len() >= pane_height { |
| 2083 | break; |
| 2084 | } |
| 2085 | let is_selected = idx == state.selected; |
| 2086 | let locked = row.locked; |
| 2087 | let focused = is_selected && state.focused; |
| 2088 | let pointer = codewhale_tui_kit::glyphs::selection_marker(focused); |
| 2089 | let status_glyph = if locked { |
| 2090 | codewhale_tui_kit::glyphs::ATTENTION |
| 2091 | } else if row.active { |
| 2092 | codewhale_tui_kit::glyphs::CURRENT |
| 2093 | } else { |
| 2094 | " " |
| 2095 | }; |
| 2096 | let hovered = self.hovered_row == Some((state.pane, idx)) && !focused; |
| 2097 | let label_style = if focused { |
| 2098 | menu_style::selected_row_style() |
| 2099 | } else if hovered { |
| 2100 | menu_style::hovered_row_style().fg(if locked { |
| 2101 | palette::TEXT_MUTED |
| 2102 | } else { |
| 2103 | palette::TEXT_PRIMARY |
| 2104 | }) |
| 2105 | } else if is_selected { |
| 2106 | Style::default() |
| 2107 | .fg(palette::TEXT_PRIMARY) |
| 2108 | .bg(palette::SURFACE_ELEVATED) |
| 2109 | } else if locked || row.dim { |
| 2110 | Style::default() |
| 2111 | .fg(palette::TEXT_MUTED) |
| 2112 | .add_modifier(Modifier::DIM) |
| 2113 | } else { |
| 2114 | Style::default().fg(palette::TEXT_PRIMARY) |
| 2115 | }; |
| 2116 | let route_style = if focused { |
| 2117 | menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 2118 | } else if locked || row.dim { |
| 2119 | label_style.fg(palette::TEXT_MUTED) |
| 2120 | } else if hovered { |
| 2121 | menu_style::hovered_row_style().fg(accent) |
| 2122 | } else if is_selected { |
| 2123 | Style::default().fg(accent).bg(palette::SURFACE_ELEVATED) |
| 2124 | } else { |
| 2125 | Style::default().fg(palette::TEXT_SOFT) |
| 2126 | }; |
| 2127 | let hint_style = if focused { |
| 2128 | menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 2129 | } else if locked || row.dim { |
| 2130 | label_style.fg(palette::TEXT_MUTED) |
| 2131 | } else if hovered { |
| 2132 | menu_style::hovered_row_style().fg(palette::TEXT_MUTED) |
| 2133 | } else if is_selected { |
| 2134 | Style::default() |
| 2135 | .fg(palette::TEXT_MUTED) |
| 2136 | .bg(palette::SURFACE_ELEVATED) |
| 2137 | } else { |
| 2138 | Style::default().fg(palette::TEXT_MUTED) |
| 2139 | }; |
| 2140 | if group_header_before(rows, idx) && pane_height > 1 { |
| 2141 | lines.push(Line::from(Span::styled( |
| 2142 | format!(" {}", row.group.as_deref().unwrap_or_default()), |
| 2143 | Style::default().fg(palette::TEXT_MUTED).bold(), |
| 2144 | ))); |
| 2145 | if lines.len() >= pane_height { |
| 2146 | break; |
| 2147 | } |
| 2148 | } |
| 2149 | let row_y = inner.y.saturating_add(lines.len() as u16); |
| 2150 | self.row_hitboxes.borrow_mut().push(( |
| 2151 | Rect::new(inner.x, row_y, inner.width, 1), |
| 2152 | state.pane, |
| 2153 | idx, |
| 2154 | )); |
| 2155 | if focused || hovered || is_selected { |
| 2156 | buf.set_style(Rect::new(inner.x, row_y, inner.width, 1), label_style); |
| 2157 | } |
| 2158 | let spans = picker_row_spans( |
| 2159 | row, |
| 2160 | pointer, |
| 2161 | status_glyph, |
| 2162 | usize::from(inner.width), |
| 2163 | columns, |
| 2164 | label_style, |
| 2165 | route_style, |
| 2166 | hint_style, |
| 2167 | ); |
| 2168 | lines.push( |
| 2169 | Line::from(spans).style(if focused || hovered || is_selected { |
| 2170 | label_style |
| 2171 | } else { |
| 2172 | Style::default() |
| 2173 | }), |
| 2174 | ); |
| 2175 | } |
| 2176 | if rows.is_empty() { |
| 2177 | let message = if self.query.is_empty() { |
| 2178 | tr(self.locale, MessageId::RouteNoModels).into_owned() |
| 2179 | } else { |
| 2180 | tr(self.locale, MessageId::RouteNoModelMatch).replace("{query}", &self.query) |
| 2181 | }; |
| 2182 | lines.push(Line::from(Span::styled( |
| 2183 | format!(" {message}"), |
| 2184 | Style::default().fg(palette::TEXT_PRIMARY).bold(), |
| 2185 | ))); |
| 2186 | if !self.query.is_empty() && pane_height >= 3 { |
| 2187 | lines.push(Line::from(Span::styled( |
| 2188 | format!(" {}", tr(self.locale, MessageId::ModelPickerFilterHint)), |
| 2189 | Style::default().fg(palette::TEXT_MUTED), |
| 2190 | ))); |
| 2191 | } |
| 2192 | } |
| 2193 | if lines.len() > usize::from(inner.height) { |
| 2194 | lines.truncate(usize::from(inner.height)); |
| 2195 | } |
| 2196 | Paragraph::new(lines).render(inner, buf); |
| 2197 | } |
| 2198 | } |
| 2199 | |
| 2200 | fn group_header_before(rows: &[PaneRow], index: usize) -> bool { |
| 2201 | let row = &rows[index]; |
| 2202 | row.group.as_deref().is_some_and(|group| { |
| 2203 | !group.trim().is_empty() |
| 2204 | && rows.get(index.wrapping_sub(1)).is_none_or(|previous| { |
| 2205 | previous.group.as_deref() != Some(group) |
| 2206 | || (row.group_scoped_by_route && previous.route != row.route) |
| 2207 | }) |
| 2208 | }) |
| 2209 | } |
| 2210 | |
| 2211 | fn pane_row_window(selected: usize, rows: &[PaneRow], height: usize) -> (usize, usize) { |
| 2212 | if rows.is_empty() || height == 0 { |
| 2213 | return (0, 0); |
| 2214 | } |
| 2215 | let selected = selected.min(rows.len() - 1); |
| 2216 | let cost = |index| 1 + usize::from(height > 1 && group_header_before(rows, index)); |
| 2217 | // Keep the selection near the middle, counting actual painted lines. |
| 2218 | let mut start = selected; |
| 2219 | let mut above = 0; |
| 2220 | while start > 0 && above + cost(start - 1) <= height.saturating_sub(cost(selected)) / 2 { |
| 2221 | start -= 1; |
| 2222 | above += cost(start); |
| 2223 | } |
| 2224 | let mut end = start; |
| 2225 | let mut used = 0; |
| 2226 | while end < rows.len() && used + cost(end) <= height { |
| 2227 | used += cost(end); |
| 2228 | end += 1; |
| 2229 | } |
| 2230 | // Fill the space above when we reach the end of the list. |
| 2231 | while start > 0 && used + cost(start - 1) <= height { |
| 2232 | start -= 1; |
| 2233 | used += cost(start); |
| 2234 | } |
| 2235 | (start, end) |
| 2236 | } |
| 2237 | |
| 2238 | /// Widest Thinking row plus its marker: `max (extra-high reasoning)`. |
| 2239 | const EFFORT_PANE_WIDTH: u16 = 30; |
| 2240 | |
| 2241 | /// Give the model list the width the Thinking pane cannot use. |
| 2242 | /// |
| 2243 | /// The generic list/detail split caps the list at 52 columns and hands the |
| 2244 | /// remainder to the detail pane. Thinking rows are a fixed, short vocabulary, |
| 2245 | /// so on a wide terminal most of the row went to a pane with nothing to put |
| 2246 | /// there while the model rows — which carry the id, route and metadata that |
| 2247 | /// tell near-identical routes apart — were squeezed into half a screen. |
| 2248 | fn widen_model_pane(layout: ListDetailLayout) -> ListDetailLayout { |
| 2249 | if layout.stacked { |
| 2250 | return layout; |
| 2251 | } |
| 2252 | let gap = layout |
| 2253 | .detail |
| 2254 | .x |
| 2255 | .saturating_sub(layout.list.x.saturating_add(layout.list.width)); |
| 2256 | let total = layout.list.width + gap + layout.detail.width; |
| 2257 | let detail_width = layout.detail.width.min(EFFORT_PANE_WIDTH); |
| 2258 | let list_width = total.saturating_sub(gap + detail_width); |
| 2259 | ListDetailLayout { |
| 2260 | list: Rect { |
| 2261 | width: list_width, |
| 2262 | ..layout.list |
| 2263 | }, |
| 2264 | detail: Rect { |
| 2265 | x: layout.list.x + list_width + gap, |
| 2266 | width: detail_width, |
| 2267 | ..layout.detail |
| 2268 | }, |
| 2269 | stacked: false, |
| 2270 | } |
| 2271 | } |
| 2272 | |
| 2273 | /// One rendered row in either picker pane, split into the columns the row is |
| 2274 | /// laid out from. |
| 2275 | /// |
| 2276 | /// Model rows fill all three: the wire id (`primary`), the route identity that |
| 2277 | /// separates same-named models on different endpoints (`route`), and the facts |
| 2278 | /// that actually vary between neighbouring rows (`meta`). Thinking-effort rows |
| 2279 | /// leave `route` empty and keep their descriptive `meta`. |
| 2280 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 2281 | struct PaneRow { |
| 2282 | primary: String, |
| 2283 | route: String, |
| 2284 | meta: Vec<String>, |
| 2285 | group: Option<String>, |
| 2286 | group_scoped_by_route: bool, |
| 2287 | active: bool, |
| 2288 | locked: bool, |
| 2289 | dim: bool, |
| 2290 | } |
| 2291 | |
| 2292 | impl PaneRow { |
| 2293 | fn effort(primary: String, meta: String) -> Self { |
| 2294 | Self { |
| 2295 | primary, |
| 2296 | route: String::new(), |
| 2297 | meta: if meta.is_empty() { |
| 2298 | Vec::new() |
| 2299 | } else { |
| 2300 | vec![meta] |
| 2301 | }, |
| 2302 | group: None, |
| 2303 | group_scoped_by_route: true, |
| 2304 | active: false, |
| 2305 | locked: false, |
| 2306 | dim: false, |
| 2307 | } |
| 2308 | } |
| 2309 | |
| 2310 | fn meta_width(&self) -> usize { |
| 2311 | self.meta |
| 2312 | .iter() |
| 2313 | .map(|chip| unicode_width::UnicodeWidthStr::width(chip.as_str())) |
| 2314 | .sum::<usize>() |
| 2315 | + self.meta.len().saturating_sub(1) * 3 |
| 2316 | } |
| 2317 | } |
| 2318 | |
| 2319 | /// Per-page column offsets for a picker pane. |
| 2320 | /// |
| 2321 | /// Rows used to render as `label (one long parenthesised hint)`, which meant |
| 2322 | /// the hint was dropped whole whenever it did not fit — and at every real |
| 2323 | /// terminal width it never fit, so a dozen DeepSeek routes all rendered as |
| 2324 | /// nothing but their near-identical ids. Fixed columns fix that: each field |
| 2325 | /// gets a measured share of the row and is truncated on its own, so the |
| 2326 | /// distinguishing token is always on screen at a predictable offset. |
| 2327 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 2328 | struct ModelRowColumns { |
| 2329 | primary: usize, |
| 2330 | route: usize, |
| 2331 | meta: usize, |
| 2332 | } |
| 2333 | |
| 2334 | const ROW_PREFIX_WIDTH: usize = 5; |
| 2335 | /// Blank cells between two columns. |
| 2336 | const COLUMN_GAP: usize = 2; |
| 2337 | /// Below this a route column tells the user nothing, so the space goes to the |
| 2338 | /// id instead. |
| 2339 | const MIN_ROUTE_WIDTH: usize = 6; |
| 2340 | /// Below this the metadata column cannot hold even a context-window token. |
| 2341 | const MIN_META_WIDTH: usize = 4; |
| 2342 | |
| 2343 | impl ModelRowColumns { |
| 2344 | /// Measure the natural width each column wants, over the supplied rows. |
| 2345 | fn for_rows(rows: &[PaneRow]) -> Self { |
| 2346 | let widest = |pick: fn(&PaneRow) -> usize| rows.iter().map(pick).max().unwrap_or(0); |
| 2347 | Self { |
| 2348 | primary: widest(|row| unicode_width::UnicodeWidthStr::width(row.primary.as_str())), |
| 2349 | route: widest(|row| unicode_width::UnicodeWidthStr::width(row.route.as_str())), |
| 2350 | meta: widest(PaneRow::meta_width), |
| 2351 | } |
| 2352 | } |
| 2353 | |
| 2354 | /// Fit the measured widths into the width actually available. |
| 2355 | /// |
| 2356 | /// When everything fits, every column keeps its natural width. When it does |
| 2357 | /// not, the scarce space is divided rather than handed to whichever column |
| 2358 | /// comes first: the id used to take everything and the metadata was dropped |
| 2359 | /// whole, which is precisely how a dozen near-identical routes ended up |
| 2360 | /// rendering as nothing but their shared prefix. |
| 2361 | fn resolve(self, width: usize) -> Self { |
| 2362 | let available = width.saturating_sub(ROW_PREFIX_WIDTH); |
| 2363 | if available == 0 { |
| 2364 | return Self::default(); |
| 2365 | } |
| 2366 | let gaps = COLUMN_GAP * (usize::from(self.route > 0) + usize::from(self.meta > 0)); |
| 2367 | let content = available.saturating_sub(gaps); |
| 2368 | if content == 0 { |
| 2369 | return Self { |
| 2370 | primary: available, |
| 2371 | route: 0, |
| 2372 | meta: 0, |
| 2373 | }; |
| 2374 | } |
| 2375 | if self.primary + self.route + self.meta <= content { |
| 2376 | return self; |
| 2377 | } |
| 2378 | // With no route column there is nothing to protect from a long id, so |
| 2379 | // the id keeps its natural width and the trailing metadata yields — a |
| 2380 | // clipped model id is worse than a hidden hint. |
| 2381 | if self.route == 0 { |
| 2382 | let primary = self.primary.min(content); |
| 2383 | let meta = self.meta.min(content.saturating_sub(primary)); |
| 2384 | return Self { |
| 2385 | primary, |
| 2386 | route: 0, |
| 2387 | meta: if meta < MIN_META_WIDTH { 0 } else { meta }, |
| 2388 | }; |
| 2389 | } |
| 2390 | |
| 2391 | // Floors first, so no column that has something to say disappears |
| 2392 | // entirely; then each takes the smaller of its natural width and its |
| 2393 | // share. Metadata is the densest per column and gets the tightest cap. |
| 2394 | let mut meta = if self.meta == 0 { |
| 2395 | 0 |
| 2396 | } else { |
| 2397 | self.meta |
| 2398 | .min((content / 4).max(MIN_META_WIDTH.min(content))) |
| 2399 | }; |
| 2400 | let after_meta = content.saturating_sub(meta); |
| 2401 | let mut route = if self.route == 0 { |
| 2402 | 0 |
| 2403 | } else { |
| 2404 | self.route |
| 2405 | .min((after_meta / 3).max(MIN_ROUTE_WIDTH.min(after_meta))) |
| 2406 | }; |
| 2407 | let mut primary = after_meta.saturating_sub(route); |
| 2408 | |
| 2409 | // The id's share is whatever the other two did not take, which can |
| 2410 | // exceed the longest id on the page. Hand that surplus back rather than |
| 2411 | // padding blank space next to a metadata column that is shedding facts. |
| 2412 | if primary > self.primary { |
| 2413 | let mut slack = primary - self.primary; |
| 2414 | primary = self.primary; |
| 2415 | for (column, natural) in [(&mut meta, self.meta), (&mut route, self.route)] { |
| 2416 | let gain = slack.min(natural.saturating_sub(*column)); |
| 2417 | *column += gain; |
| 2418 | slack -= gain; |
| 2419 | } |
| 2420 | primary += slack; |
| 2421 | } |
| 2422 | |
| 2423 | Self { |
| 2424 | primary, |
| 2425 | route, |
| 2426 | meta, |
| 2427 | } |
| 2428 | } |
| 2429 | } |
| 2430 | |
| 2431 | /// Truncate an identifier from the middle, keeping both ends. |
| 2432 | /// |
| 2433 | /// Model ids and route names share their heads and differ in their tails: |
| 2434 | /// `deepseek-ai/DeepSeek-V4-Pro` and `deepseek-ai/DeepSeek-V4-Flash` are |
| 2435 | /// identical for twenty characters and only separate at the very end. Clipping |
| 2436 | /// the tail therefore deletes the one token that tells them apart — both rows |
| 2437 | /// render as `deepseek-ai/DeepSee...`. Keeping a slice of each end costs one |
| 2438 | /// column for the ellipsis and preserves the variant. |
| 2439 | fn fit_identifier(text: &str, width: usize) -> String { |
| 2440 | use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; |
| 2441 | |
| 2442 | if UnicodeWidthStr::width(text) <= width { |
| 2443 | return text.to_string(); |
| 2444 | } |
| 2445 | // Too narrow to seat a head, an ellipsis and a meaningful tail; fall back |
| 2446 | // to the plain head-first form rather than emit punctuation soup. |
| 2447 | if width < 8 { |
| 2448 | return fit_text(text, width); |
| 2449 | } |
| 2450 | |
| 2451 | let budget = width - 1; |
| 2452 | // The tail is the discriminating end, so it gets the larger share. |
| 2453 | let tail_budget = (budget * 3) / 5; |
| 2454 | let head_budget = budget - tail_budget; |
| 2455 | |
| 2456 | let mut head = String::new(); |
| 2457 | let mut used = 0usize; |
| 2458 | for ch in text.chars() { |
| 2459 | let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0); |
| 2460 | if used + ch_width > head_budget { |
| 2461 | break; |
| 2462 | } |
| 2463 | used += ch_width; |
| 2464 | head.push(ch); |
| 2465 | } |
| 2466 | |
| 2467 | let mut tail: Vec<char> = Vec::new(); |
| 2468 | let mut used = 0usize; |
| 2469 | for ch in text.chars().rev() { |
| 2470 | let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0); |
| 2471 | if used + ch_width > tail_budget { |
| 2472 | break; |
| 2473 | } |
| 2474 | used += ch_width; |
| 2475 | tail.push(ch); |
| 2476 | } |
| 2477 | tail.reverse(); |
| 2478 | |
| 2479 | let mut out = head; |
| 2480 | out.push('…'); |
| 2481 | out.extend(tail); |
| 2482 | out |
| 2483 | } |
| 2484 | |
| 2485 | fn picker_row_spans<'a>( |
| 2486 | row: &'a PaneRow, |
| 2487 | pointer: &'static str, |
| 2488 | status_glyph: &'static str, |
| 2489 | width: usize, |
| 2490 | columns: ModelRowColumns, |
| 2491 | label_style: Style, |
| 2492 | route_style: Style, |
| 2493 | hint_style: Style, |
| 2494 | ) -> Vec<Span<'a>> { |
| 2495 | use unicode_width::UnicodeWidthStr; |
| 2496 | |
| 2497 | let columns = columns.resolve(width); |
| 2498 | let accent = active_modal_accent_color(); |
| 2499 | let pointer_style = if pointer == codewhale_tui_kit::glyphs::SELECTION { |
| 2500 | label_style.fg(accent) |
| 2501 | } else { |
| 2502 | label_style |
| 2503 | }; |
| 2504 | let status_style = if row.locked { |
| 2505 | label_style.fg(palette::STATUS_WARNING) |
| 2506 | } else if row.active { |
| 2507 | label_style.fg(palette::STATUS_SUCCESS) |
| 2508 | } else { |
| 2509 | label_style |
| 2510 | }; |
| 2511 | let mut spans = vec![ |
| 2512 | Span::styled(" ", label_style), |
| 2513 | Span::styled(pointer, pointer_style), |
| 2514 | Span::styled(" ", label_style), |
| 2515 | Span::styled(status_glyph, status_style), |
| 2516 | Span::styled(" ", label_style), |
| 2517 | ]; |
| 2518 | let mut used = ROW_PREFIX_WIDTH; |
| 2519 | |
| 2520 | let primary = fit_identifier(&row.primary, columns.primary.max(1)); |
| 2521 | used += UnicodeWidthStr::width(primary.as_str()); |
| 2522 | spans.push(Span::styled(primary, label_style)); |
| 2523 | |
| 2524 | let pad_to = |spans: &mut Vec<Span<'a>>, used: &mut usize, target: usize| { |
| 2525 | if *used < target { |
| 2526 | spans.push(Span::styled(" ".repeat(target - *used), label_style)); |
| 2527 | *used = target; |
| 2528 | } |
| 2529 | }; |
| 2530 | |
| 2531 | if columns.route > 0 && !row.route.is_empty() { |
| 2532 | pad_to(&mut spans, &mut used, ROW_PREFIX_WIDTH + columns.primary); |
| 2533 | spans.push(Span::styled(" ".repeat(COLUMN_GAP), label_style)); |
| 2534 | used += COLUMN_GAP; |
| 2535 | let route = fit_identifier(&row.route, columns.route); |
| 2536 | used += UnicodeWidthStr::width(route.as_str()); |
| 2537 | spans.push(Span::styled(route, route_style)); |
| 2538 | } |
| 2539 | |
| 2540 | if !row.meta.is_empty() { |
| 2541 | let column_edge = if columns.route > 0 && !row.route.is_empty() { |
| 2542 | ROW_PREFIX_WIDTH + columns.primary + COLUMN_GAP + columns.route |
| 2543 | } else { |
| 2544 | ROW_PREFIX_WIDTH + columns.primary |
| 2545 | }; |
| 2546 | let remaining = width |
| 2547 | .saturating_sub(column_edge) |
| 2548 | .saturating_sub(COLUMN_GAP) |
| 2549 | .min(columns.meta.max(MIN_META_WIDTH)); |
| 2550 | let meta = fit_meta_chips(&row.meta, remaining); |
| 2551 | if !meta.is_empty() { |
| 2552 | pad_to(&mut spans, &mut used, column_edge); |
| 2553 | spans.push(Span::styled(" ".repeat(COLUMN_GAP), label_style)); |
| 2554 | spans.push(Span::styled(meta, hint_style)); |
| 2555 | } |
| 2556 | } |
| 2557 | |
| 2558 | spans |
| 2559 | } |
| 2560 | |
| 2561 | fn fit_text(text: &str, width: usize) -> String { |
| 2562 | use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; |
| 2563 | |
| 2564 | if UnicodeWidthStr::width(text) <= width { |
| 2565 | return text.to_string(); |
| 2566 | } |
| 2567 | if width == 0 { |
| 2568 | return String::new(); |
| 2569 | } |
| 2570 | if width <= 3 { |
| 2571 | return ".".repeat(width); |
| 2572 | } |
| 2573 | |
| 2574 | let mut out = String::new(); |
| 2575 | let target = width - 3; |
| 2576 | let mut used = 0usize; |
| 2577 | for ch in text.chars() { |
| 2578 | let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0); |
| 2579 | if used + ch_width > target { |
| 2580 | break; |
| 2581 | } |
| 2582 | used += ch_width; |
| 2583 | out.push(ch); |
| 2584 | } |
| 2585 | out.push_str("..."); |
| 2586 | out |
| 2587 | } |
| 2588 | |
| 2589 | pub(crate) fn provider_scoped_model_completion_ids(app: &App) -> Vec<String> { |
| 2590 | // Slash completions inline the current custom model so `/model <current>` |
| 2591 | // stays visible even when it is outside the provider catalog. |
| 2592 | provider_scoped_model_ids_for_app(app, true) |
| 2593 | } |
| 2594 | |
| 2595 | /// The pin (Fleet model or the person's own) naming this exact row, if any. |
| 2596 | fn pin_for_row<'a>(pins: &'a [PinnedModel], row: &ModelPickerRow) -> Option<&'a PinnedModel> { |
| 2597 | pins.iter().find(|pin| pin_names_row(pin, row)) |
| 2598 | } |
| 2599 | |
| 2600 | /// One route match for sorting, marking and labelling alike. Built-in |
| 2601 | /// provider slugs are case-insensitive aliases; a named custom provider's |
| 2602 | /// identity is its exact config key, so `TeamA` and `teama` stay two routes. |
| 2603 | /// Model ids are exact. |
| 2604 | fn pin_names_row(pin: &PinnedModel, row: &ModelPickerRow) -> bool { |
| 2605 | let named_custom = row.provider == Some(ProviderKind::Custom); |
| 2606 | row_provider_identity(row).is_some_and(|provider| { |
| 2607 | if named_custom { |
| 2608 | provider == pin.provider |
| 2609 | } else { |
| 2610 | provider.eq_ignore_ascii_case(&pin.provider) |
| 2611 | } |
| 2612 | }) && row.id == pin.model |
| 2613 | } |
| 2614 | |
| 2615 | /// The pins the picker sorts and labels by: the fleet's models first (the |
| 2616 | /// selected Fleet's operator and every pinned member, labelled with the roles |
| 2617 | /// each fills — design §10 F1), then the person's own pins. |
| 2618 | fn picker_pins_for_app(app: &App) -> Vec<PinnedModel> { |
| 2619 | // A selected fleet that cannot be read contributes no pins; ⇧F on any |
| 2620 | // row then surfaces that store error instead of writing past it. |
| 2621 | codewhale_engine::fleet::members::fleet_models(&app.workspace) |
| 2622 | .unwrap_or_default() |
| 2623 | .into_iter() |
| 2624 | .map(|member| PinnedModel { |
| 2625 | provider: member.provider.clone(), |
| 2626 | model: member.model.clone(), |
| 2627 | label: Some(format!("fleet · {}", member.roles_label())), |
| 2628 | }) |
| 2629 | .chain(app.pinned_models.iter().cloned()) |
| 2630 | .collect() |
| 2631 | } |
| 2632 | |
| 2633 | fn picker_model_rows_for_app(app: &App, config: &Config) -> Vec<ModelPickerRow> { |
| 2634 | let mut rows = Vec::new(); |
| 2635 | let auto_hint = auto_picker_hint(app, config); |
| 2636 | push_auto_model_row(&mut rows, app, config, &auto_hint); |
| 2637 | // One snapshot supplies both IDs, capabilities, and freshness so a cache |
| 2638 | // replacement cannot produce mixed-generation picker rows. |
| 2639 | let codex_roster = codex_model_cache::model_roster_for(config); |
| 2640 | let mut active_model_ids = if app.api_provider == ProviderKind::OpenaiCodex { |
| 2641 | let mut models = vec!["auto".to_string()]; |
| 2642 | for id in codex_roster.model_ids() { |
| 2643 | push_model_id(&mut models, &id); |
| 2644 | } |
| 2645 | if let Some(model) = app |
| 2646 | .provider_models |
| 2647 | .get(app.provider_identity_for_persistence()) |
| 2648 | .map(|model| model.trim()) |
| 2649 | .filter(|model| !model.is_empty()) |
| 2650 | { |
| 2651 | push_model_id( |
| 2652 | &mut models, |
| 2653 | picker_visible_model_id(app.api_provider, model, app.accepts_custom_model_ids()), |
| 2654 | ); |
| 2655 | } |
| 2656 | models |
| 2657 | } else { |
| 2658 | provider_scoped_model_ids_for_app(app, false) |
| 2659 | }; |
| 2660 | push_recent_model_ids( |
| 2661 | &mut active_model_ids, |
| 2662 | app, |
| 2663 | app.provider_identity_for_persistence(), |
| 2664 | ); |
| 2665 | push_configured_provider_model( |
| 2666 | &mut active_model_ids, |
| 2667 | config, |
| 2668 | app.api_provider, |
| 2669 | app.provider_identity_for_persistence(), |
| 2670 | ); |
| 2671 | if let Ok(identity) = app.admitted_provider_identity() { |
| 2672 | push_provider_model_rows( |
| 2673 | &mut rows, |
| 2674 | identity, |
| 2675 | active_model_ids, |
| 2676 | app.api_provider, |
| 2677 | config, |
| 2678 | &codex_roster, |
| 2679 | &app.provider_health, |
| 2680 | ); |
| 2681 | } |
| 2682 | |
| 2683 | for identity in config.provider_identities() { |
| 2684 | if app.admitted_provider_identity().ok() == Some(&identity) { |
| 2685 | continue; |
| 2686 | } |
| 2687 | push_inactive_route_rows(&mut rows, app, config, &identity, &codex_roster); |
| 2688 | } |
| 2689 | |
| 2690 | // The fleet comes first (design §10 F1): every model the person added |
| 2691 | // to the selected Fleet rides the pin machinery ahead of their own pins, |
| 2692 | // labelled with the roles it fills, so the list leads with what they |
| 2693 | // chose rather than with a provider's alphabet. |
| 2694 | let pins = picker_pins_for_app(app); |
| 2695 | for row in &mut rows { |
| 2696 | if let Some(pin) = pin_for_row(&pins, row) { |
| 2697 | let pinned = tr(app.ui_locale, MessageId::ModelPickerPinnedChip); |
| 2698 | let label = pin.label.as_deref().unwrap_or(&pinned); |
| 2699 | row.hint = format!( |
| 2700 | "{label} · exact {} / {} · {}", |
| 2701 | pin.provider, pin.model, row.hint |
| 2702 | ); |
| 2703 | } |
| 2704 | } |
| 2705 | |
| 2706 | for pin in &pins { |
| 2707 | let provider = ProviderKind::parse(&pin.provider).unwrap_or(ProviderKind::Custom); |
| 2708 | if rows.iter().any(|row| { |
| 2709 | row_provider_identity(row).is_some_and(|identity| identity == pin.provider) |
| 2710 | && row.id == pin.model |
| 2711 | }) { |
| 2712 | continue; |
| 2713 | } |
| 2714 | let metadata = effective_picker_metadata_for_identity( |
| 2715 | config, |
| 2716 | Some(provider), |
| 2717 | Some(&pin.provider), |
| 2718 | &pin.model, |
| 2719 | ); |
| 2720 | // Bypass the ordinary `(enum provider, model)` de-duplication here: |
| 2721 | // two named Custom routes may intentionally expose the same model id. |
| 2722 | rows.push(ModelPickerRow { |
| 2723 | id: pin.model.clone(), |
| 2724 | provider: Some(provider), |
| 2725 | provider_identity: Some(pin.provider.clone()), |
| 2726 | admitted_identity: None, |
| 2727 | route_selection: None, |
| 2728 | hint: format!( |
| 2729 | "stale pinned · exact {} / {} · unavailable; repair or remove", |
| 2730 | pin.provider, pin.model |
| 2731 | ), |
| 2732 | metadata, |
| 2733 | selectable: false, |
| 2734 | blocked_reason: Some("stale pin".to_string()), |
| 2735 | default_rank: None, |
| 2736 | credentialed: false, |
| 2737 | not_listed: None, |
| 2738 | external_agent: None, |
| 2739 | }); |
| 2740 | } |
| 2741 | |
| 2742 | let current = (!app.auto_model).then(|| { |
| 2743 | ( |
| 2744 | app.provider_identity_for_persistence(), |
| 2745 | picker_visible_model_id(app.api_provider, &app.model, app.accepts_custom_model_ids()), |
| 2746 | ) |
| 2747 | }); |
| 2748 | assign_default_sections(&mut rows, app, config, current, &pins); |
| 2749 | push_external_agent_rows(&mut rows, app, &codex_roster); |
| 2750 | rows |
| 2751 | } |
| 2752 | |
| 2753 | fn push_external_agent_rows( |
| 2754 | rows: &mut Vec<ModelPickerRow>, |
| 2755 | app: &App, |
| 2756 | codex_roster: &CodexModelRoster, |
| 2757 | ) { |
| 2758 | let active_agent_id = app |
| 2759 | .external_agent |
| 2760 | .as_ref() |
| 2761 | .map(|session| session.agent_id.as_str()); |
| 2762 | if active_agent_id.is_some() { |
| 2763 | for row in rows.iter_mut() { |
| 2764 | if matches!(row.default_rank, Some((DefaultSection::Current, _))) { |
| 2765 | row.default_rank = Some((DefaultSection::ProviderDefault, 0)); |
| 2766 | } |
| 2767 | } |
| 2768 | } |
| 2769 | for (idx, agent) in app.external_agents.iter().enumerate() { |
| 2770 | let is_active = active_agent_id == Some(agent.id.as_str()); |
| 2771 | let is_installed = agent.state == "installed" || agent.runnable || agent.custom; |
| 2772 | let (cached_model_count, thinking_levels) = |
| 2773 | external_agent_cached_capabilities(&agent.id, codex_roster); |
| 2774 | let mut hint_parts = Vec::new(); |
| 2775 | if let Some(version) = agent |
| 2776 | .version |
| 2777 | .as_deref() |
| 2778 | .map(str::trim) |
| 2779 | .filter(|s| !s.is_empty()) |
| 2780 | { |
| 2781 | hint_parts.push(format!("v{version}")); |
| 2782 | } |
| 2783 | if let Some(count) = cached_model_count.filter(|&count| count > 0) { |
| 2784 | hint_parts.push(format!( |
| 2785 | "{count} cached model{}", |
| 2786 | if count == 1 { "" } else { "s" } |
| 2787 | )); |
| 2788 | } |
| 2789 | if !thinking_levels.is_empty() { |
| 2790 | hint_parts.push(format!("thinking: {}", thinking_levels.join("/"))); |
| 2791 | } |
| 2792 | let not_ready = tr(app.ui_locale, MessageId::ModelPickerExternalAgentNotReady); |
| 2793 | if agent.runnable { |
| 2794 | hint_parts.push( |
| 2795 | tr( |
| 2796 | app.ui_locale, |
| 2797 | MessageId::ModelPickerExternalAgentRunnableHint, |
| 2798 | ) |
| 2799 | .into_owned(), |
| 2800 | ); |
| 2801 | if let Some(login) = agent |
| 2802 | .login |
| 2803 | .as_deref() |
| 2804 | .map(str::trim) |
| 2805 | .filter(|s| !s.is_empty()) |
| 2806 | && !hint_parts.iter().any(|part| part.contains(login)) |
| 2807 | { |
| 2808 | hint_parts.push( |
| 2809 | tr(app.ui_locale, MessageId::ModelPickerExternalAgentSignInHint) |
| 2810 | .replace("{command}", login), |
| 2811 | ); |
| 2812 | } |
| 2813 | } else { |
| 2814 | if let Some(reason) = agent |
| 2815 | .reason |
| 2816 | .as_deref() |
| 2817 | .map(str::trim) |
| 2818 | .filter(|s| !s.is_empty()) |
| 2819 | { |
| 2820 | hint_parts.push(reason.to_string()); |
| 2821 | } else { |
| 2822 | hint_parts.push(not_ready.to_string()); |
| 2823 | } |
| 2824 | if agent.needs_update |
| 2825 | && let Some(upgrade) = agent |
| 2826 | .upgrade |
| 2827 | .as_deref() |
| 2828 | .map(str::trim) |
| 2829 | .filter(|s| !s.is_empty()) |
| 2830 | && !hint_parts.iter().any(|part| part.contains(upgrade)) |
| 2831 | { |
| 2832 | hint_parts.push(upgrade.to_string()); |
| 2833 | } else if agent.state == "not_installed" |
| 2834 | && !agent.website.trim().is_empty() |
| 2835 | && !hint_parts |
| 2836 | .iter() |
| 2837 | .any(|part| part.contains(agent.website.trim())) |
| 2838 | { |
| 2839 | hint_parts.push(agent.website.trim().to_string()); |
| 2840 | } else if agent.state == "installed" |
| 2841 | && !agent.needs_update |
| 2842 | && agent.reason_code.as_deref() != Some("adapter_missing") |
| 2843 | && let Some(login) = agent |
| 2844 | .login |
| 2845 | .as_deref() |
| 2846 | .map(str::trim) |
| 2847 | .filter(|s| !s.is_empty()) |
| 2848 | && !hint_parts.iter().any(|part| part.contains(login)) |
| 2849 | { |
| 2850 | hint_parts.push( |
| 2851 | tr(app.ui_locale, MessageId::ModelPickerExternalAgentSignInHint) |
| 2852 | .replace("{command}", login), |
| 2853 | ); |
| 2854 | } |
| 2855 | } |
| 2856 | let default_rank = if is_active { |
| 2857 | Some((DefaultSection::Current, 0)) |
| 2858 | } else if is_installed { |
| 2859 | Some((DefaultSection::ExternalAgent, idx)) |
| 2860 | } else { |
| 2861 | None |
| 2862 | }; |
| 2863 | let blocked_reason = if agent.runnable { |
| 2864 | None |
| 2865 | } else { |
| 2866 | agent |
| 2867 | .reason |
| 2868 | .clone() |
| 2869 | .or_else(|| Some(not_ready.into_owned())) |
| 2870 | }; |
| 2871 | rows.push(ModelPickerRow { |
| 2872 | id: agent.id.clone(), |
| 2873 | provider: None, |
| 2874 | provider_identity: None, |
| 2875 | admitted_identity: None, |
| 2876 | route_selection: None, |
| 2877 | hint: hint_parts.join(" · "), |
| 2878 | metadata: EffectivePickerMetadata { |
| 2879 | display_name: Some(agent.name.clone()), |
| 2880 | ..EffectivePickerMetadata::default() |
| 2881 | }, |
| 2882 | selectable: agent.runnable, |
| 2883 | blocked_reason, |
| 2884 | default_rank, |
| 2885 | credentialed: agent.runnable, |
| 2886 | not_listed: None, |
| 2887 | external_agent: Some(ExternalAgentRowInfo { |
| 2888 | agent_id: agent.id.clone(), |
| 2889 | agent_name: agent.name.clone(), |
| 2890 | state: agent.state.clone(), |
| 2891 | runnable: agent.runnable, |
| 2892 | needs_update: agent.needs_update, |
| 2893 | version: agent.version.clone(), |
| 2894 | reason_code: agent.reason_code.clone(), |
| 2895 | reason: agent.reason.clone(), |
| 2896 | login: agent.login.clone(), |
| 2897 | upgrade: agent.upgrade.clone(), |
| 2898 | website: agent.website.clone(), |
| 2899 | cached_model_count, |
| 2900 | thinking_levels, |
| 2901 | }), |
| 2902 | }); |
| 2903 | } |
| 2904 | } |
| 2905 | |
| 2906 | fn external_agent_cached_capabilities( |
| 2907 | agent_id: &str, |
| 2908 | codex_roster: &CodexModelRoster, |
| 2909 | ) -> (Option<usize>, Vec<String>) { |
| 2910 | if agent_id.eq_ignore_ascii_case("codex") && !codex_roster.models.is_empty() { |
| 2911 | let mut thinking_levels = Vec::new(); |
| 2912 | for model in &codex_roster.models { |
| 2913 | for effort in &model.efforts { |
| 2914 | let normalized = effort.trim(); |
| 2915 | if !normalized.is_empty() |
| 2916 | && !thinking_levels |
| 2917 | .iter() |
| 2918 | .any(|existing: &String| existing.eq_ignore_ascii_case(normalized)) |
| 2919 | { |
| 2920 | thinking_levels.push(normalized.to_string()); |
| 2921 | } |
| 2922 | } |
| 2923 | } |
| 2924 | return (Some(codex_roster.models.len()), thinking_levels); |
| 2925 | } |
| 2926 | (None, Vec::new()) |
| 2927 | } |
| 2928 | |
| 2929 | fn external_agent_meta_chips(row: &ModelPickerRow, agent: &ExternalAgentRowInfo) -> Vec<String> { |
| 2930 | let mut chips = Vec::new(); |
| 2931 | if let Some(version) = agent |
| 2932 | .version |
| 2933 | .as_deref() |
| 2934 | .map(str::trim) |
| 2935 | .filter(|s| !s.is_empty()) |
| 2936 | { |
| 2937 | chips.push(format!("v{version}")); |
| 2938 | } |
| 2939 | if let Some(count) = agent.cached_model_count.filter(|&count| count > 0) { |
| 2940 | chips.push(format!( |
| 2941 | "{count} cached model{}", |
| 2942 | if count == 1 { "" } else { "s" } |
| 2943 | )); |
| 2944 | } |
| 2945 | if !agent.thinking_levels.is_empty() { |
| 2946 | chips.push(format!("thinking: {}", agent.thinking_levels.join("/"))); |
| 2947 | } |
| 2948 | for part in row |
| 2949 | .hint |
| 2950 | .split(" · ") |
| 2951 | .map(str::trim) |
| 2952 | .filter(|part| !part.is_empty()) |
| 2953 | { |
| 2954 | if !chips |
| 2955 | .iter() |
| 2956 | .any(|existing| existing.eq_ignore_ascii_case(part)) |
| 2957 | { |
| 2958 | chips.push(part.to_string()); |
| 2959 | } |
| 2960 | } |
| 2961 | if chips.is_empty() { |
| 2962 | chips.push(row.hint.clone()); |
| 2963 | } |
| 2964 | chips |
| 2965 | } |
| 2966 | |
| 2967 | /// Place rows into the default view's sections (#6533): the current route, |
| 2968 | /// then pins and Fleet models, then up to [`RECENT_ROW_LIMIT`] recently used |
| 2969 | /// routes by decayed use, then one default per credentialed route. A leftover |
| 2970 | /// `[providers.X].model` is that default only when the route is current or |
| 2971 | /// recently used; an unused route offers its built-in default instead, so a |
| 2972 | /// test model saved months ago no longer rides along. User-declared |
| 2973 | /// `[[models]]` rows keep their place. Everything else stays behind search. |
| 2974 | fn assign_default_sections( |
| 2975 | rows: &mut [ModelPickerRow], |
| 2976 | app: &App, |
| 2977 | config: &Config, |
| 2978 | current: Option<(&str, &str)>, |
| 2979 | pins: &[PinnedModel], |
| 2980 | ) { |
| 2981 | let now = chrono::Utc::now(); |
| 2982 | let guard = app.route_usage.read().ok(); |
| 2983 | let empty = codewhale_engine::model_relevance::RouteUsageIndex::default(); |
| 2984 | let usage = guard.as_deref().unwrap_or(&empty); |
| 2985 | let find = |rows: &[ModelPickerRow], identity: &str, model: &str| { |
| 2986 | rows.iter() |
| 2987 | .position(|row| row_provider_identity(row) == Some(identity) && row.id == model) |
| 2988 | }; |
| 2989 | for row in rows.iter_mut() { |
| 2990 | row.default_rank = None; |
| 2991 | // `auto` is the current route when auto routing is on; otherwise it |
| 2992 | // follows the pins, ahead of recent use. |
| 2993 | if row.provider.is_none() { |
| 2994 | row.default_rank = Some(if current.is_none() { |
| 2995 | (DefaultSection::Current, 0) |
| 2996 | } else { |
| 2997 | (DefaultSection::Pinned, usize::MAX) |
| 2998 | }); |
| 2999 | } |
| 3000 | } |
| 3001 | if let Some((identity, model)) = current |
| 3002 | && let Some(index) = find(rows, identity, model) |
| 3003 | { |
| 3004 | rows[index].default_rank = Some((DefaultSection::Current, 0)); |
| 3005 | } |
| 3006 | for (rank, pin) in pins.iter().enumerate() { |
| 3007 | // Exact, as the pin labels match: a pin names one wire spelling. |
| 3008 | if let Some(row) = rows.iter_mut().find(|row| { |
| 3009 | row_provider_identity(row) == Some(pin.provider.as_str()) && row.id == pin.model |
| 3010 | }) { |
| 3011 | row.default_rank |
| 3012 | .get_or_insert((DefaultSection::Pinned, rank)); |
| 3013 | } |
| 3014 | } |
| 3015 | let mut recent = 0; |
| 3016 | for route in usage.ranked(now) { |
| 3017 | if recent >= RECENT_ROW_LIMIT { |
| 3018 | break; |
| 3019 | } |
| 3020 | if let Some(index) = find(rows, &route.identity, &route.model) |
| 3021 | && rows[index].default_rank.is_none() |
| 3022 | { |
| 3023 | rows[index].default_rank = Some((DefaultSection::Recent, recent)); |
| 3024 | recent += 1; |
| 3025 | } |
| 3026 | } |
| 3027 | let mut routes: Vec<(String, ProviderKind)> = Vec::new(); |
| 3028 | for row in rows.iter() { |
| 3029 | if let (Some(provider), Some(identity)) = (row.provider, row_provider_identity(row)) |
| 3030 | && !routes.iter().any(|(seen, _)| seen == identity) |
| 3031 | { |
| 3032 | routes.push((identity.to_string(), provider)); |
| 3033 | } |
| 3034 | } |
| 3035 | for (order, (identity, provider)) in routes.iter().enumerate() { |
| 3036 | let Ok(admitted) = config.legacy_selection_identity(identity) else { |
| 3037 | continue; |
| 3038 | }; |
| 3039 | if admitted.provider != *provider { |
| 3040 | continue; |
| 3041 | } |
| 3042 | let in_use = current.is_some_and(|(current, _)| current == identity) |
| 3043 | || usage.identity_used(identity, now); |
| 3044 | let configured = || { |
| 3045 | app.provider_models |
| 3046 | .get(identity) |
| 3047 | .map(String::as_str) |
| 3048 | .or_else(|| { |
| 3049 | route_provider_config(config, *provider, identity) |
| 3050 | .and_then(|entry| entry.model.as_deref()) |
| 3051 | }) |
| 3052 | .map(str::to_string) |
| 3053 | }; |
| 3054 | let default = if in_use || *provider == ProviderKind::Custom { |
| 3055 | configured() |
| 3056 | } else { |
| 3057 | codewhale_config::descriptors::compatibility_for_id(identity) |
| 3058 | .filter(|row| row.kind == *provider) |
| 3059 | .map(|row| row.default_model.to_string()) |
| 3060 | }; |
| 3061 | let Some(default) = default |
| 3062 | .as_deref() |
| 3063 | .map(str::trim) |
| 3064 | .filter(|model| !model.is_empty() && !model.eq_ignore_ascii_case("auto")) |
| 3065 | .map(|model| { |
| 3066 | picker_visible_model_id( |
| 3067 | *provider, |
| 3068 | model, |
| 3069 | config.model_ids_pass_through_for_provider(&admitted), |
| 3070 | ) |
| 3071 | .to_string() |
| 3072 | }) |
| 3073 | else { |
| 3074 | continue; |
| 3075 | }; |
| 3076 | if let Some(index) = find(rows, identity, &default) |
| 3077 | && rows[index].default_rank.is_none() |
| 3078 | && rows[index].credentialed |
| 3079 | { |
| 3080 | rows[index].default_rank = Some((DefaultSection::ProviderDefault, order)); |
| 3081 | } |
| 3082 | } |
| 3083 | for row in rows.iter_mut() { |
| 3084 | if row.default_rank.is_none() |
| 3085 | && matches!(row.metadata.source, Some(CatalogSource::ConfigOverride)) |
| 3086 | { |
| 3087 | row.default_rank = Some((DefaultSection::ProviderDefault, usize::MAX)); |
| 3088 | } |
| 3089 | } |
| 3090 | // The current route's roster and a custom relay's roster are what the |
| 3091 | // user came to choose from, and the default view used to hide every row |
| 3092 | // but the provider default -- the panel listed a dozen models and `/model` |
| 3093 | // showed one. Surface each such route's own rows, bounded per route so a |
| 3094 | // large gateway cannot take the view over: newest first for a built-in |
| 3095 | // provider, the relay's own listing order for a custom relay. |
| 3096 | let current_identity = current.map(|(identity, _)| identity); |
| 3097 | let mut roster: Vec<usize> = rows |
| 3098 | .iter() |
| 3099 | .enumerate() |
| 3100 | .filter(|(_, row)| { |
| 3101 | row.default_rank.is_none() |
| 3102 | && row.not_listed.is_none() |
| 3103 | && !model_is_non_language(row) |
| 3104 | && row_provider_identity(row).is_some_and(|identity| { |
| 3105 | current_identity == Some(identity) |
| 3106 | || (row.provider == Some(ProviderKind::Custom) |
| 3107 | && matches!(row.metadata.source, Some(CatalogSource::Live { .. }))) |
| 3108 | }) |
| 3109 | }) |
| 3110 | .map(|(index, _)| index) |
| 3111 | .collect(); |
| 3112 | roster.sort_by_cached_key(|&index| { |
| 3113 | let row = &rows[index]; |
| 3114 | (row.provider != Some(ProviderKind::Custom)) |
| 3115 | .then(|| std::cmp::Reverse(model_version_key(&row.id))) |
| 3116 | }); |
| 3117 | let mut shown_per_route: BTreeMap<String, usize> = BTreeMap::new(); |
| 3118 | for index in roster { |
| 3119 | let Some(identity) = row_provider_identity(&rows[index]).map(str::to_string) else { |
| 3120 | continue; |
| 3121 | }; |
| 3122 | let shown = shown_per_route.entry(identity).or_default(); |
| 3123 | if *shown >= ROUTE_ROSTER_ROWS_IN_DEFAULT_VIEW { |
| 3124 | continue; |
| 3125 | } |
| 3126 | *shown += 1; |
| 3127 | rows[index].default_rank = Some((DefaultSection::Roster, usize::MAX)); |
| 3128 | } |
| 3129 | } |
| 3130 | |
| 3131 | /// Model ids this exact route was used with recently, so a model picked |
| 3132 | /// through `--model` or another client still has a row to rank. |
| 3133 | fn push_recent_model_ids(models: &mut Vec<String>, app: &App, identity: &str) { |
| 3134 | if let Ok(usage) = app.route_usage.read() { |
| 3135 | for model in usage.models_for_identity(identity, chrono::Utc::now()) { |
| 3136 | push_model_id(models, &model); |
| 3137 | } |
| 3138 | } |
| 3139 | } |
| 3140 | |
| 3141 | /// Rows for one route that is not the session's active route. |
| 3142 | /// |
| 3143 | /// `identity` is the exact persistence key — the `[providers.<name>]` table |
| 3144 | /// for a named custom route, the provider slug otherwise — and every lookup |
| 3145 | /// here is made against it, so two routes that expose the same model id keep |
| 3146 | /// separate rows, separate remembered choices, and separate enablement. |
| 3147 | fn push_inactive_route_rows( |
| 3148 | rows: &mut Vec<ModelPickerRow>, |
| 3149 | app: &App, |
| 3150 | config: &Config, |
| 3151 | admitted: &codewhale_runtime::config::ProviderIdentity, |
| 3152 | codex_roster: &CodexModelRoster, |
| 3153 | ) { |
| 3154 | if config.verify_provider_identity(admitted).is_err() { |
| 3155 | return; |
| 3156 | } |
| 3157 | let provider = admitted.provider; |
| 3158 | let identity = admitted.key.as_str(); |
| 3159 | let mut model_ids = if provider == ProviderKind::OpenaiCodex { |
| 3160 | codex_roster.model_ids() |
| 3161 | } else { |
| 3162 | provider_catalog_model_ids(provider, identity, &config.base_url_for_route(admitted)) |
| 3163 | }; |
| 3164 | if let Some(model) = app |
| 3165 | .provider_models |
| 3166 | .get(identity) |
| 3167 | .map(|model| model.trim()) |
| 3168 | .filter(|model| !model.is_empty()) |
| 3169 | { |
| 3170 | push_model_id( |
| 3171 | &mut model_ids, |
| 3172 | picker_visible_model_id( |
| 3173 | provider, |
| 3174 | model, |
| 3175 | config.model_ids_pass_through_for_provider(admitted), |
| 3176 | ), |
| 3177 | ); |
| 3178 | } |
| 3179 | push_recent_model_ids(&mut model_ids, app, identity); |
| 3180 | push_configured_provider_model(&mut model_ids, config, provider, identity); |
| 3181 | push_provider_model_rows( |
| 3182 | rows, |
| 3183 | admitted, |
| 3184 | model_ids, |
| 3185 | app.api_provider, |
| 3186 | config, |
| 3187 | codex_roster, |
| 3188 | &app.provider_health, |
| 3189 | ); |
| 3190 | } |
| 3191 | |
| 3192 | /// The `[providers.…]` table that owns this exact route. |
| 3193 | /// |
| 3194 | /// [`Config::provider_config_for`] resolves `Custom` through the *selected* |
| 3195 | /// `provider = "<name>"`, which cannot describe a custom route the session is |
| 3196 | /// not on — and must never answer for one (#6016). |
| 3197 | fn route_provider_config<'a>( |
| 3198 | config: &'a Config, |
| 3199 | provider: ProviderKind, |
| 3200 | key: &str, |
| 3201 | ) -> Option<&'a codewhale_runtime::config::ProviderConfig> { |
| 3202 | let identity = config.legacy_selection_identity(key).ok()?; |
| 3203 | (identity.provider == provider).then_some(())?; |
| 3204 | config.provider_config_for(&identity) |
| 3205 | } |
| 3206 | |
| 3207 | fn push_provider_model_rows( |
| 3208 | rows: &mut Vec<ModelPickerRow>, |
| 3209 | admitted: &codewhale_runtime::config::ProviderIdentity, |
| 3210 | model_ids: Vec<String>, |
| 3211 | active_provider: ProviderKind, |
| 3212 | config: &Config, |
| 3213 | codex_roster: &CodexModelRoster, |
| 3214 | provider_health: &codewhale_engine::provider_readiness::ProviderReadinessSnapshot, |
| 3215 | ) { |
| 3216 | if config.verify_provider_identity(admitted).is_err() { |
| 3217 | return; |
| 3218 | } |
| 3219 | let provider = admitted.provider; |
| 3220 | let identity = admitted.key.to_string(); |
| 3221 | let inventory = match codewhale_engine::model_inventory::exact_route_inventory( |
| 3222 | config, |
| 3223 | admitted, |
| 3224 | provider_health, |
| 3225 | &model_ids, |
| 3226 | ) { |
| 3227 | Ok(inventory) => inventory, |
| 3228 | Err(reason) => { |
| 3229 | for id in model_ids.into_iter().filter(|id| id != "auto") { |
| 3230 | let metadata = effective_picker_metadata_for_identity( |
| 3231 | config, |
| 3232 | Some(provider), |
| 3233 | Some(&identity), |
| 3234 | &id, |
| 3235 | ); |
| 3236 | push_model_row( |
| 3237 | rows, |
| 3238 | id, |
| 3239 | Some(provider), |
| 3240 | Some(identity.clone()), |
| 3241 | reason.clone(), |
| 3242 | metadata, |
| 3243 | false, |
| 3244 | Some(reason.clone()), |
| 3245 | ); |
| 3246 | } |
| 3247 | return; |
| 3248 | } |
| 3249 | }; |
| 3250 | let base_url = config.base_url_for_route(admitted); |
| 3251 | let live_catalog_fingerprint = |
| 3252 | codewhale_engine::provider_catalog_live::provider_owns_live_catalog(provider, &base_url) |
| 3253 | .then(|| codewhale_config::catalog::base_url_fingerprint(&base_url)); |
| 3254 | let checked = inventory |
| 3255 | .fetched_at |
| 3256 | .and_then(|time| i64::try_from(time).ok()) |
| 3257 | .and_then(|time| chrono::DateTime::from_timestamp(time, 0)) |
| 3258 | .map(|time| time.format("%Y-%m-%d").to_string()); |
| 3259 | for route in inventory.models { |
| 3260 | let id = route.model; |
| 3261 | let readiness = route.readiness; |
| 3262 | let selectable = readiness.can_attempt(); |
| 3263 | let readiness_label = readiness.label(); |
| 3264 | let roster_entry = if provider == ProviderKind::OpenaiCodex { |
| 3265 | codex_roster.metadata_for(&id) |
| 3266 | } else { |
| 3267 | None |
| 3268 | }; |
| 3269 | let codex_metadata = if codex_roster.freshness == CodexModelCacheFreshness::Fresh { |
| 3270 | roster_entry |
| 3271 | } else { |
| 3272 | None |
| 3273 | }; |
| 3274 | let codex_freshness = roster_entry.map(|_| codex_roster.freshness); |
| 3275 | let metadata = effective_picker_metadata_with_codex( |
| 3276 | config, |
| 3277 | Some(provider), |
| 3278 | Some(identity.as_str()), |
| 3279 | &id, |
| 3280 | codex_metadata, |
| 3281 | ); |
| 3282 | let provider_catalog_receipt = live_catalog_fingerprint.as_ref().map(|fingerprint| { |
| 3283 | let endpoint_matches = match metadata.source.as_ref() { |
| 3284 | Some(CatalogSource::Live { |
| 3285 | base_url_fingerprint, |
| 3286 | .. |
| 3287 | }) => base_url_fingerprint == fingerprint, |
| 3288 | _ => true, |
| 3289 | }; |
| 3290 | (inventory.status.clone(), endpoint_matches) |
| 3291 | }); |
| 3292 | let mut hint = render_picker_model_hint( |
| 3293 | &id, |
| 3294 | Some(provider), |
| 3295 | &metadata, |
| 3296 | codex_freshness, |
| 3297 | provider_catalog_receipt.as_ref(), |
| 3298 | ); |
| 3299 | if metadata.display_name.is_some() { |
| 3300 | hint = format!("{id} · {hint}"); |
| 3301 | } |
| 3302 | hint = format!("{readiness_label} · {hint}"); |
| 3303 | if provider != active_provider { |
| 3304 | hint = format!("switch route · {hint}"); |
| 3305 | } |
| 3306 | let blocked_reason = (!selectable).then(|| readiness_label.to_string()); |
| 3307 | let credentialed = matches!( |
| 3308 | readiness, |
| 3309 | codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedUnchecked |
| 3310 | | codewhale_engine::provider_readiness::ResolvedProviderReadiness::ImportedTokenUnchecked |
| 3311 | | codewhale_engine::provider_readiness::ResolvedProviderReadiness::Ready |
| 3312 | | codewhale_engine::provider_readiness::ResolvedProviderReadiness::ConnectionCheckedModelUnchecked |
| 3313 | | codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedLastCheckFailed { .. } |
| 3314 | ); |
| 3315 | let not_listed = checked |
| 3316 | .as_ref() |
| 3317 | .filter(|_| { |
| 3318 | route.evidence == codewhale_engine::model_inventory::InventoryEvidence::Absent |
| 3319 | }) |
| 3320 | .map(|checked| NotListed { |
| 3321 | provider: if provider == ProviderKind::Custom { |
| 3322 | identity.clone() |
| 3323 | } else { |
| 3324 | provider.provider().display_name().to_string() |
| 3325 | }, |
| 3326 | checked: checked.clone(), |
| 3327 | }); |
| 3328 | let before = rows.len(); |
| 3329 | push_model_row( |
| 3330 | rows, |
| 3331 | id.clone(), |
| 3332 | Some(provider), |
| 3333 | Some(identity.clone()), |
| 3334 | hint, |
| 3335 | metadata, |
| 3336 | selectable, |
| 3337 | blocked_reason, |
| 3338 | ); |
| 3339 | if rows.len() > before |
| 3340 | && let Some(row) = rows.last_mut() |
| 3341 | { |
| 3342 | row.admitted_identity = Some(admitted.clone()); |
| 3343 | row.route_selection = Some(route.selection); |
| 3344 | row.credentialed = credentialed; |
| 3345 | row.not_listed = not_listed; |
| 3346 | } |
| 3347 | } |
| 3348 | } |
| 3349 | |
| 3350 | fn push_auto_model_row(rows: &mut Vec<ModelPickerRow>, app: &App, config: &Config, hint: &str) { |
| 3351 | let captured = app.admitted_provider_identity().ok(); |
| 3352 | let readiness = captured.map_or( |
| 3353 | codewhale_engine::provider_readiness::ResolvedProviderReadiness::Legacy, |
| 3354 | |identity| { |
| 3355 | codewhale_engine::provider_readiness::resolve_for_model( |
| 3356 | config, |
| 3357 | identity, |
| 3358 | "auto", |
| 3359 | &app.provider_health, |
| 3360 | ) |
| 3361 | }, |
| 3362 | ); |
| 3363 | let metadata = effective_picker_metadata(config, None, "auto"); |
| 3364 | let selectable = captured.is_some() && readiness.can_attempt(); |
| 3365 | let blocked_reason = (!selectable).then(|| readiness.label().to_string()); |
| 3366 | push_model_row( |
| 3367 | rows, |
| 3368 | "auto".to_string(), |
| 3369 | None, |
| 3370 | None, |
| 3371 | format!("{} · {hint}", readiness.label()), |
| 3372 | metadata, |
| 3373 | selectable, |
| 3374 | blocked_reason, |
| 3375 | ); |
| 3376 | if let Some(row) = rows.last_mut() { |
| 3377 | row.admitted_identity = captured.cloned(); |
| 3378 | } |
| 3379 | } |
| 3380 | |
| 3381 | fn auto_picker_hint(app: &App, config: &Config) -> String { |
| 3382 | let inventory = |
| 3383 | match codewhale_engine::model_inventory::ModelInventory::auto_router_only(config) { |
| 3384 | Ok(inventory) => inventory, |
| 3385 | Err(reason) => { |
| 3386 | return format!("{} · {reason}", app.tr(MessageId::ModelPickerAutoLocalHint)); |
| 3387 | } |
| 3388 | }; |
| 3389 | // #4411: the classifier only sees other providers under the persisted |
| 3390 | // `[auto] cross_provider` opt-in, so the default hint says active provider |
| 3391 | // only and names the classifier route it will actually call. |
| 3392 | let hint_id = match (inventory.router_available, inventory.cross_provider_auto) { |
| 3393 | (true, true) => MessageId::ModelPickerAutoNetworkHint, |
| 3394 | (true, false) => MessageId::ModelPickerAutoNetworkActiveProviderHint, |
| 3395 | (false, _) => MessageId::ModelPickerAutoLocalHint, |
| 3396 | }; |
| 3397 | let mut hint = app |
| 3398 | .tr(hint_id) |
| 3399 | .into_owned() |
| 3400 | .replace( |
| 3401 | "{provider}", |
| 3402 | inventory.router_provider.provider().display_name(), |
| 3403 | ) |
| 3404 | .replace("{model}", &inventory.router_model); |
| 3405 | if let (Some(provider), Some(model)) = ( |
| 3406 | app.last_effective_provider, |
| 3407 | app.last_effective_model.as_deref(), |
| 3408 | ) { |
| 3409 | let provider_label = if provider == ProviderKind::Custom { |
| 3410 | app.last_effective_provider_identity |
| 3411 | .as_deref() |
| 3412 | .unwrap_or_else(|| app.provider_identity_for_persistence()) |
| 3413 | } else { |
| 3414 | provider.provider().display_name() |
| 3415 | }; |
| 3416 | let last = app |
| 3417 | .tr(MessageId::ModelPickerAutoLastRoute) |
| 3418 | .replace("{provider}", provider_label) |
| 3419 | .replace("{model}", model); |
| 3420 | hint.push_str(" · "); |
| 3421 | hint.push_str(&last); |
| 3422 | } |
| 3423 | hint |
| 3424 | } |
| 3425 | |
| 3426 | fn push_configured_provider_model( |
| 3427 | models: &mut Vec<String>, |
| 3428 | config: &Config, |
| 3429 | provider: ProviderKind, |
| 3430 | identity: &str, |
| 3431 | ) { |
| 3432 | let Ok(admitted) = config.legacy_selection_identity(identity) else { |
| 3433 | return; |
| 3434 | }; |
| 3435 | if admitted.provider != provider { |
| 3436 | return; |
| 3437 | } |
| 3438 | if let Some(model) = route_provider_config(config, provider, identity) |
| 3439 | .and_then(|entry| entry.model.as_deref()) |
| 3440 | .map(str::trim) |
| 3441 | .filter(|model| !model.is_empty()) |
| 3442 | { |
| 3443 | push_model_id( |
| 3444 | models, |
| 3445 | picker_visible_model_id( |
| 3446 | provider, |
| 3447 | model, |
| 3448 | config.model_ids_pass_through_for_provider(&admitted), |
| 3449 | ), |
| 3450 | ); |
| 3451 | } |
| 3452 | } |
| 3453 | |
| 3454 | fn provider_catalog_model_ids( |
| 3455 | provider: ProviderKind, |
| 3456 | identity: &str, |
| 3457 | base_url: &str, |
| 3458 | ) -> Vec<String> { |
| 3459 | let mut models = Vec::new(); |
| 3460 | for id in |
| 3461 | codewhale_engine::provider_lake::catalog_models_for_route(provider, identity, base_url) |
| 3462 | { |
| 3463 | // Cached IDs belong to this exact endpoint. The configured/current |
| 3464 | // model is appended separately so users can still select saved IDs. |
| 3465 | push_model_id(&mut models, picker_visible_model_id(provider, &id, false)); |
| 3466 | } |
| 3467 | models |
| 3468 | } |
| 3469 | |
| 3470 | fn provider_scoped_model_ids_for_app(app: &App, include_current_model: bool) -> Vec<String> { |
| 3471 | // `include_current_model` is for completion surfaces that do not have a |
| 3472 | // separate custom/current-model row. |
| 3473 | let mut models = Vec::new(); |
| 3474 | push_model_id(&mut models, "auto"); |
| 3475 | for id in provider_catalog_model_ids( |
| 3476 | app.api_provider, |
| 3477 | app.provider_identity_for_persistence(), |
| 3478 | &app.active_route_base_url, |
| 3479 | ) { |
| 3480 | push_model_id(&mut models, &id); |
| 3481 | } |
| 3482 | |
| 3483 | if app.api_provider != ProviderKind::OpenaiCodex |
| 3484 | && codewhale_config::catalog::configured::validate_configured_models(&app.configured_models) |
| 3485 | .is_ok() |
| 3486 | { |
| 3487 | for declaration in app.configured_models.iter().filter(|declaration| { |
| 3488 | declaration.matches_route( |
| 3489 | app.provider_identity_for_persistence(), |
| 3490 | &app.active_route_base_url, |
| 3491 | ) |
| 3492 | }) { |
| 3493 | if !models.contains(&declaration.id) { |
| 3494 | models.push(declaration.id.clone()); |
| 3495 | } |
| 3496 | } |
| 3497 | } |
| 3498 | |
| 3499 | if let Some(model) = app |
| 3500 | .provider_models |
| 3501 | .get(app.provider_identity_for_persistence()) |
| 3502 | .map(|model| model.trim()) |
| 3503 | .filter(|model| !model.is_empty()) |
| 3504 | { |
| 3505 | push_model_id( |
| 3506 | &mut models, |
| 3507 | picker_visible_model_id(app.api_provider, model, app.accepts_custom_model_ids()), |
| 3508 | ); |
| 3509 | } |
| 3510 | |
| 3511 | if include_current_model && !app.auto_model { |
| 3512 | push_model_id( |
| 3513 | &mut models, |
| 3514 | picker_visible_model_id( |
| 3515 | app.api_provider, |
| 3516 | app.model.trim(), |
| 3517 | app.accepts_custom_model_ids(), |
| 3518 | ), |
| 3519 | ); |
| 3520 | } |
| 3521 | |
| 3522 | models |
| 3523 | } |
| 3524 | |
| 3525 | fn push_model_id(models: &mut Vec<String>, model: &str) { |
| 3526 | let model = model.trim(); |
| 3527 | if model.is_empty() { |
| 3528 | return; |
| 3529 | } |
| 3530 | let reserved = model.eq_ignore_ascii_case("auto"); |
| 3531 | if !models |
| 3532 | .iter() |
| 3533 | .any(|existing| existing == model || (reserved && existing.eq_ignore_ascii_case("auto"))) |
| 3534 | { |
| 3535 | models.push(model.to_string()); |
| 3536 | } |
| 3537 | } |
| 3538 | |
| 3539 | /// Migrate retired aliases out of first-party DeepSeek model choices. Custom |
| 3540 | /// endpoints and aggregators own their namespaces, where `deepseek-reasoner` |
| 3541 | /// can remain a native wire id. |
| 3542 | fn picker_visible_model_id( |
| 3543 | provider: ProviderKind, |
| 3544 | model: &str, |
| 3545 | preserve_endpoint_model_ids: bool, |
| 3546 | ) -> &str { |
| 3547 | if !preserve_endpoint_model_ids |
| 3548 | && matches!( |
| 3549 | provider, |
| 3550 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 3551 | ) |
| 3552 | && (model.eq_ignore_ascii_case("deepseek-chat") |
| 3553 | || model.eq_ignore_ascii_case("deepseek-reasoner")) |
| 3554 | { |
| 3555 | DEEPSEEK_ALIAS_REPLACEMENT |
| 3556 | } else { |
| 3557 | model |
| 3558 | } |
| 3559 | } |
| 3560 | |
| 3561 | fn provider_query_splits(query: &str) -> Vec<(&str, &str)> { |
| 3562 | let trimmed = query.trim(); |
| 3563 | let mut splits = Vec::new(); |
| 3564 | if let Some((provider, model)) = trimmed.split_once(':') { |
| 3565 | splits.push((provider.trim(), model.trim())); |
| 3566 | } |
| 3567 | if let Some(idx) = trimmed.find(char::is_whitespace) { |
| 3568 | let (provider, model) = trimmed.split_at(idx); |
| 3569 | splits.push((provider.trim(), model.trim())); |
| 3570 | } |
| 3571 | splits |
| 3572 | } |
| 3573 | |
| 3574 | fn push_model_row( |
| 3575 | rows: &mut Vec<ModelPickerRow>, |
| 3576 | id: String, |
| 3577 | provider: Option<ProviderKind>, |
| 3578 | provider_identity: Option<String>, |
| 3579 | hint: String, |
| 3580 | metadata: EffectivePickerMetadata, |
| 3581 | selectable: bool, |
| 3582 | blocked_reason: Option<String>, |
| 3583 | ) { |
| 3584 | if rows.iter().any(|row| { |
| 3585 | row.id == id |
| 3586 | && row.provider == provider |
| 3587 | && match ( |
| 3588 | row.provider_identity.as_deref(), |
| 3589 | provider_identity.as_deref(), |
| 3590 | ) { |
| 3591 | (Some(left), Some(right)) => left == right, |
| 3592 | (None, None) => true, |
| 3593 | _ => false, |
| 3594 | } |
| 3595 | }) { |
| 3596 | return; |
| 3597 | } |
| 3598 | rows.push(ModelPickerRow { |
| 3599 | id, |
| 3600 | provider, |
| 3601 | provider_identity, |
| 3602 | admitted_identity: None, |
| 3603 | route_selection: None, |
| 3604 | hint, |
| 3605 | metadata, |
| 3606 | selectable, |
| 3607 | blocked_reason, |
| 3608 | default_rank: None, |
| 3609 | credentialed: false, |
| 3610 | not_listed: None, |
| 3611 | external_agent: None, |
| 3612 | }); |
| 3613 | } |
| 3614 | |
| 3615 | /// Compact Models.dev freshness chip for the picker chrome (#4139). |
| 3616 | /// |
| 3617 | /// Fresh/live rows stay unmarked; stale and failed caches get an explicit |
| 3618 | /// suffix so users know the live layer is still visible but not current. |
| 3619 | fn catalog_freshness_title_suffix() -> &'static str { |
| 3620 | catalog_freshness_title_suffix_for(models_dev_live::status().freshness) |
| 3621 | } |
| 3622 | |
| 3623 | fn catalog_freshness_title_suffix_for(freshness: ModelsDevFreshness) -> &'static str { |
| 3624 | match freshness { |
| 3625 | ModelsDevFreshness::Stale => " · cached catalog", |
| 3626 | ModelsDevFreshness::Failed => " · refresh failed; catalog available", |
| 3627 | ModelsDevFreshness::Bundled | ModelsDevFreshness::Live => "", |
| 3628 | } |
| 3629 | } |
| 3630 | |
| 3631 | /// Cross-field search (#4141): match a query against the provider name |
| 3632 | /// (provider key + display name), the display model name, and the wire model |
| 3633 | /// id, mirroring `ProviderDashboardRow::matches_query` so the two pickers behave |
| 3634 | /// consistently. `row.id` is both the model's display name and the id it is |
| 3635 | /// sent to the provider as, so matching it covers the display model name and |
| 3636 | /// the wire model id. The compact hint is only searched for the active |
| 3637 | /// provider / `auto` rows, preserving the existing cross-provider behavior. |
| 3638 | fn parse_trailing_release_date(model_id: &str) -> Option<(&str, String)> { |
| 3639 | const MONTHS: [&str; 12] = [ |
| 3640 | "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", |
| 3641 | ]; |
| 3642 | let max_day = |month: u32| -> u32 { |
| 3643 | match month { |
| 3644 | 2 => 29, |
| 3645 | 4 | 6 | 9 | 11 => 30, |
| 3646 | _ => 31, |
| 3647 | } |
| 3648 | }; |
| 3649 | let bytes = model_id.as_bytes(); |
| 3650 | let len = bytes.len(); |
| 3651 | if len > 11 && bytes[len - 11] == b'-' && bytes[len - 6] == b'-' && bytes[len - 3] == b'-' { |
| 3652 | let base = &model_id[..len - 11]; |
| 3653 | let y_str = &model_id[len - 10..len - 6]; |
| 3654 | let m_str = &model_id[len - 5..len - 3]; |
| 3655 | let d_str = &model_id[len - 2..]; |
| 3656 | if !base.is_empty() |
| 3657 | && !base.ends_with("-expires-on") |
| 3658 | && y_str.bytes().all(|b| b.is_ascii_digit()) |
| 3659 | && m_str.bytes().all(|b| b.is_ascii_digit()) |
| 3660 | && d_str.bytes().all(|b| b.is_ascii_digit()) |
| 3661 | { |
| 3662 | let year: u32 = y_str.parse().ok()?; |
| 3663 | let month: u32 = m_str.parse().ok()?; |
| 3664 | let day: u32 = d_str.parse().ok()?; |
| 3665 | if (2020..=2099).contains(&year) |
| 3666 | && (1..=12).contains(&month) |
| 3667 | && (1..=max_day(month)).contains(&day) |
| 3668 | { |
| 3669 | return Some(( |
| 3670 | base, |
| 3671 | format!("Updated {} {}, {}", MONTHS[(month - 1) as usize], day, year), |
| 3672 | )); |
| 3673 | } |
| 3674 | } |
| 3675 | } |
| 3676 | if len > 9 && bytes[len - 9] == b'-' { |
| 3677 | let base = &model_id[..len - 9]; |
| 3678 | let digits = &model_id[len - 8..]; |
| 3679 | if !base.is_empty() |
| 3680 | && !base.ends_with("-expires-on") |
| 3681 | && digits.bytes().all(|b| b.is_ascii_digit()) |
| 3682 | { |
| 3683 | let year: u32 = digits[0..4].parse().ok()?; |
| 3684 | let month: u32 = digits[4..6].parse().ok()?; |
| 3685 | let day: u32 = digits[6..8].parse().ok()?; |
| 3686 | if (2020..=2099).contains(&year) |
| 3687 | && (1..=12).contains(&month) |
| 3688 | && (1..=max_day(month)).contains(&day) |
| 3689 | { |
| 3690 | return Some(( |
| 3691 | base, |
| 3692 | format!("Updated {} {}, {}", MONTHS[(month - 1) as usize], day, year), |
| 3693 | )); |
| 3694 | } |
| 3695 | } |
| 3696 | } |
| 3697 | if len > 5 && bytes[len - 5] == b'-' { |
| 3698 | let base = &model_id[..len - 5]; |
| 3699 | let digits = &model_id[len - 4..]; |
| 3700 | if !base.is_empty() |
| 3701 | && !base.ends_with("-expires-on") |
| 3702 | && digits.bytes().all(|b| b.is_ascii_digit()) |
| 3703 | { |
| 3704 | let month: u32 = digits[0..2].parse().ok()?; |
| 3705 | let day: u32 = digits[2..4].parse().ok()?; |
| 3706 | if (1..=12).contains(&month) && (1..=max_day(month)).contains(&day) { |
| 3707 | return Some(( |
| 3708 | base, |
| 3709 | format!("Updated {} {}", MONTHS[(month - 1) as usize], day), |
| 3710 | )); |
| 3711 | } |
| 3712 | } |
| 3713 | } |
| 3714 | None |
| 3715 | } |
| 3716 | |
| 3717 | fn provider_matches_query_token(row: &ModelPickerRow, token_lower: &str) -> bool { |
| 3718 | let Some(provider) = row.provider else { |
| 3719 | return false; |
| 3720 | }; |
| 3721 | let check = |needle: &str| { |
| 3722 | row.provider_identity |
| 3723 | .as_deref() |
| 3724 | .is_some_and(|identity| identity.to_ascii_lowercase().contains(needle)) |
| 3725 | || provider.as_str().to_ascii_lowercase().contains(needle) |
| 3726 | || row_provider_label(row) |
| 3727 | .to_ascii_lowercase() |
| 3728 | .contains(needle) |
| 3729 | }; |
| 3730 | check(token_lower) |
| 3731 | || provider_search_aliases(token_lower) |
| 3732 | .iter() |
| 3733 | .any(|alias| check(alias)) |
| 3734 | } |
| 3735 | |
| 3736 | fn model_row_matches_single_term( |
| 3737 | row: &ModelPickerRow, |
| 3738 | term: &str, |
| 3739 | initial_provider: ProviderKind, |
| 3740 | ) -> bool { |
| 3741 | let normalized_query = normalize_picker_search_text(term); |
| 3742 | let compact = |text: &str| { |
| 3743 | text.chars() |
| 3744 | .filter(char::is_ascii_alphanumeric) |
| 3745 | .collect::<String>() |
| 3746 | }; |
| 3747 | let compact_query = compact(term); |
| 3748 | let matches = |candidate: &str| { |
| 3749 | let candidate = candidate.to_ascii_lowercase(); |
| 3750 | candidate.contains(term) |
| 3751 | || normalize_picker_search_text(&candidate).contains(&normalized_query) |
| 3752 | || (!compact_query.is_empty() && compact(&candidate).contains(&compact_query)) |
| 3753 | }; |
| 3754 | if let Some(agent) = row.external_agent.as_ref() { |
| 3755 | let brand = match agent.agent_id.as_str() { |
| 3756 | "codex" => Some("OpenAI"), |
| 3757 | "antigravity" => Some("Google Gemini"), |
| 3758 | _ => None, |
| 3759 | }; |
| 3760 | return matches(&agent.agent_id) |
| 3761 | || matches(&agent.agent_name) |
| 3762 | || brand.is_some_and(matches) |
| 3763 | || matches("acp") |
| 3764 | || matches("external agent") |
| 3765 | || agent.reason.as_deref().is_some_and(matches) |
| 3766 | || agent.login.as_deref().is_some_and(matches) |
| 3767 | || agent.thinking_levels.iter().any(|level| matches(level)) |
| 3768 | || matches(&row.hint); |
| 3769 | } |
| 3770 | let provider_matches = row.provider.is_some_and(|provider| { |
| 3771 | row.provider_identity.as_deref().is_some_and(matches) |
| 3772 | || matches(provider.as_str()) |
| 3773 | || matches(row_provider_label(row)) |
| 3774 | || provider_search_aliases(term).iter().any(|alias| { |
| 3775 | row.provider_identity |
| 3776 | .as_deref() |
| 3777 | .is_some_and(|identity| identity.to_ascii_lowercase().contains(alias)) |
| 3778 | || provider.as_str().to_ascii_lowercase().contains(alias) |
| 3779 | || row_provider_label(row).to_ascii_lowercase().contains(alias) |
| 3780 | }) |
| 3781 | }); |
| 3782 | provider_matches |
| 3783 | || row.metadata.display_name.as_deref().is_some_and(matches) |
| 3784 | || matches(&row.id) |
| 3785 | || ((row.provider.is_none() || row.provider == Some(initial_provider)) |
| 3786 | && matches(&row.hint)) |
| 3787 | } |
| 3788 | |
| 3789 | fn model_row_matches_query( |
| 3790 | row: &ModelPickerRow, |
| 3791 | query: &str, |
| 3792 | initial_provider: ProviderKind, |
| 3793 | ) -> bool { |
| 3794 | let query = query.trim().to_ascii_lowercase(); |
| 3795 | if query.is_empty() { |
| 3796 | return true; |
| 3797 | } |
| 3798 | if model_row_matches_single_term(row, &query, initial_provider) { |
| 3799 | return true; |
| 3800 | } |
| 3801 | let tokens: Vec<&str> = query.split_whitespace().collect(); |
| 3802 | tokens.len() > 1 |
| 3803 | && tokens |
| 3804 | .iter() |
| 3805 | .all(|token| model_row_matches_single_term(row, token, initial_provider)) |
| 3806 | } |
| 3807 | |
| 3808 | fn normalize_picker_search_text(text: &str) -> String { |
| 3809 | text.chars() |
| 3810 | .map(|ch| { |
| 3811 | if ch.is_ascii_alphanumeric() { |
| 3812 | ch.to_ascii_lowercase() |
| 3813 | } else { |
| 3814 | ' ' |
| 3815 | } |
| 3816 | }) |
| 3817 | .collect::<String>() |
| 3818 | .split_whitespace() |
| 3819 | .collect::<Vec<_>>() |
| 3820 | .join(" ") |
| 3821 | } |
| 3822 | |
| 3823 | /// Route-identity labels for a set of rows, disambiguated where two providers |
| 3824 | /// answer to the same display name. |
| 3825 | /// |
| 3826 | /// `Deepseek` and `DeepseekAnthropic` are both spelled "DeepSeek", so a picker |
| 3827 | /// listing both showed two rows of literally identical text for two genuinely |
| 3828 | /// different endpoints. When a display name is not unique among the rows on |
| 3829 | /// offer, the provider's own id — the `[providers.<id>]` key the user would |
| 3830 | /// edit — supplies the discriminator, with the leading run it already shares |
| 3831 | /// with the display name removed so the suffix is the part that differs. |
| 3832 | fn route_labels_for_rows(rows: &[&ModelPickerRow]) -> BTreeMap<String, String> { |
| 3833 | let mut by_display: BTreeMap<&'static str, Vec<ProviderKind>> = BTreeMap::new(); |
| 3834 | for provider in rows |
| 3835 | .iter() |
| 3836 | .filter_map(|row| row.provider) |
| 3837 | .filter(|provider| *provider != ProviderKind::Custom) |
| 3838 | { |
| 3839 | let label = model_connection_name(provider, provider.as_str()) |
| 3840 | .unwrap_or_else(|| provider.provider().display_name()); |
| 3841 | let bucket = by_display.entry(label).or_default(); |
| 3842 | if !bucket.contains(&provider) { |
| 3843 | bucket.push(provider); |
| 3844 | } |
| 3845 | } |
| 3846 | let mut labels = BTreeMap::new(); |
| 3847 | for (display, providers) in by_display { |
| 3848 | let ambiguous = providers.len() > 1; |
| 3849 | for provider in providers { |
| 3850 | let label = match ambiguous.then(|| route_discriminator(display, provider.as_str())) { |
| 3851 | Some(Some(suffix)) => format!("{display} {suffix}"), |
| 3852 | // The canonical route — the one whose id is just the display |
| 3853 | // name — keeps the bare name; provider ids are unique, so at |
| 3854 | // most one member of a group can land here and the labels stay |
| 3855 | // distinct. |
| 3856 | Some(None) | None => display.to_string(), |
| 3857 | }; |
| 3858 | labels.insert(provider.as_str().to_string(), label); |
| 3859 | } |
| 3860 | } |
| 3861 | for row in rows |
| 3862 | .iter() |
| 3863 | .filter(|row| row.provider == Some(ProviderKind::Custom)) |
| 3864 | { |
| 3865 | let Some(identity) = row_provider_identity(row) else { |
| 3866 | continue; |
| 3867 | }; |
| 3868 | // Custom tables are labeled by their `[providers.<id>]` key: there |
| 3869 | // are no compiled display names anymore (#6289). |
| 3870 | labels |
| 3871 | .entry(identity.to_string()) |
| 3872 | .or_insert_with(|| identity.to_string()); |
| 3873 | } |
| 3874 | labels |
| 3875 | } |
| 3876 | |
| 3877 | /// The part of a provider id that is not already carried by its display name. |
| 3878 | fn route_discriminator(display: &str, provider_id: &str) -> Option<String> { |
| 3879 | let squash = |text: &str| -> String { |
| 3880 | text.chars() |
| 3881 | .filter(|c| c.is_alphanumeric()) |
| 3882 | .collect::<String>() |
| 3883 | }; |
| 3884 | let display_key = squash(display).to_ascii_lowercase(); |
| 3885 | let id_key = squash(provider_id).to_ascii_lowercase(); |
| 3886 | if display_key.is_empty() || !id_key.starts_with(&display_key) { |
| 3887 | return None; |
| 3888 | } |
| 3889 | // Walk the raw id until the display name's alphanumerics are consumed; what |
| 3890 | // remains is the endpoint-specific tail (`-anthropic`, `-CN`, …). |
| 3891 | // Count CHARACTERS, not bytes: `display_key.len()` is a byte length, and |
| 3892 | // for a non-ASCII display name it exceeds the alphanumeric char count, so |
| 3893 | // the loop would over-consume and the discriminator would be wrong or |
| 3894 | // empty (2026-08-04 review). |
| 3895 | let display_key_chars = display_key.chars().count(); |
| 3896 | let mut consumed = 0usize; |
| 3897 | let mut tail = provider_id; |
| 3898 | for (offset, ch) in provider_id.char_indices() { |
| 3899 | if consumed == display_key_chars { |
| 3900 | tail = &provider_id[offset..]; |
| 3901 | break; |
| 3902 | } |
| 3903 | if ch.is_alphanumeric() { |
| 3904 | consumed += 1; |
| 3905 | } |
| 3906 | tail = &provider_id[offset + ch.len_utf8()..]; |
| 3907 | } |
| 3908 | let tail = tail.trim_matches(|c: char| !c.is_alphanumeric()); |
| 3909 | (!tail.is_empty()).then(|| tail.to_string()) |
| 3910 | } |
| 3911 | |
| 3912 | /// The handful of facts that actually differ between neighbouring model rows, |
| 3913 | /// in the order they earn their space. |
| 3914 | /// |
| 3915 | /// Everything the old prose hint carried but that reads the same on nearly |
| 3916 | /// every row — `tools`, `no vision`, `price unknown`, `bundled` — is dropped |
| 3917 | /// here: a token repeated on forty rows cannot tell them apart, and it is what |
| 3918 | /// pushed the differentiating tokens off the end of the line. Facts the |
| 3919 | /// registry does not know are omitted rather than guessed. |
| 3920 | /// The picker section label for a provider/model row. |
| 3921 | /// |
| 3922 | /// Catalog families are useful grouping metadata, but they are not model names. |
| 3923 | /// DeepSeek has published both `deepseek` and `deepseek-thinking` as family |
| 3924 | /// values for its current V4 models, so keep its picker heading stable and |
| 3925 | /// provider-facing rather than exposing either implementation detail. |
| 3926 | fn catalog_family_for_identity( |
| 3927 | provider: ProviderKind, |
| 3928 | provider_identity: Option<&str>, |
| 3929 | model_id: &str, |
| 3930 | ) -> Option<String> { |
| 3931 | if provider == ProviderKind::Deepseek { |
| 3932 | return Some(provider.provider().display_name().to_string()); |
| 3933 | } |
| 3934 | catalog_offering_for_model_identity(provider, provider_identity, model_id) |
| 3935 | .and_then(|offering| offering.family) |
| 3936 | } |
| 3937 | |
| 3938 | fn model_row_meta_chips(row: &ModelPickerRow) -> Vec<String> { |
| 3939 | if row.metadata.source == Some(CatalogSource::ConfigOverride) { |
| 3940 | // The qualifier comes first so compact rows cannot shed it while |
| 3941 | // keeping an unverified declaration visible as a provider fact. |
| 3942 | return vec![ |
| 3943 | "user declared (unverified)".to_string(), |
| 3944 | row.metadata |
| 3945 | .context_window |
| 3946 | .map(|value| format_context_window(u64::from(value))) |
| 3947 | .unwrap_or_else(|| "context unknown".into()), |
| 3948 | row.metadata |
| 3949 | .max_output |
| 3950 | .map(|value| format!("{} out", format_context_window(u64::from(value)))) |
| 3951 | .unwrap_or_else(|| "output unknown".into()), |
| 3952 | match &row.metadata.pricing { |
| 3953 | PickerPricing::Known(price) => match row.metadata.price_basis.as_ref() { |
| 3954 | Some(basis) => format!("estimate {price} ({})", basis.short), |
| 3955 | None => format!("estimate {price}"), |
| 3956 | }, |
| 3957 | _ => "price unknown".into(), |
| 3958 | }, |
| 3959 | if row.metadata.reasoning_unknown { |
| 3960 | "reasoning unknown" |
| 3961 | } else if row.metadata.reasoning { |
| 3962 | "reasoning" |
| 3963 | } else { |
| 3964 | "no reasoning" |
| 3965 | } |
| 3966 | .into(), |
| 3967 | match row.metadata.tool_calls { |
| 3968 | Some(true) => "tools declared", |
| 3969 | Some(false) => "no tools", |
| 3970 | None => "tools unknown", |
| 3971 | } |
| 3972 | .into(), |
| 3973 | match row.metadata.vision { |
| 3974 | SupportState::Supported => "vision declared", |
| 3975 | SupportState::Unsupported => "text only", |
| 3976 | SupportState::Unknown => "vision unknown", |
| 3977 | } |
| 3978 | .into(), |
| 3979 | ]; |
| 3980 | } |
| 3981 | let mut chips = Vec::new(); |
| 3982 | if let Some(context_window) = row.metadata.context_window { |
| 3983 | let label = format_context_window(u64::from(context_window)); |
| 3984 | if row.metadata.context_window_override { |
| 3985 | chips.push(format!("{label} · set")); |
| 3986 | } else if row.metadata.context_window_unverified { |
| 3987 | chips.push(format!("{label} · fallback")); |
| 3988 | } else { |
| 3989 | chips.push(label); |
| 3990 | } |
| 3991 | } |
| 3992 | // The reasoning stance is the most decision-relevant fact for a coding |
| 3993 | // harness, so it sits before the limits/modality chips — the chip budget |
| 3994 | // sheds from the tail, and a squeezed row must never lose the stance. |
| 3995 | chips.push( |
| 3996 | if row.metadata.reasoning_unknown { |
| 3997 | "reasoning unknown" |
| 3998 | } else if row.metadata.reasoning { |
| 3999 | "reasoning" |
| 4000 | } else { |
| 4001 | "no reasoning" |
| 4002 | } |
| 4003 | .to_string(), |
| 4004 | ); |
| 4005 | if let PickerPricing::Status(status) = row.metadata.pricing { |
| 4006 | chips.push(format!("price {status}")); |
| 4007 | } else if let PickerPricing::Known(price) = &row.metadata.pricing { |
| 4008 | if price != "priced" { |
| 4009 | let chip = match row.metadata.price_basis.as_ref() { |
| 4010 | Some(basis) if basis.short != "live" => format!("{price} ({})", basis.short), |
| 4011 | _ => price.clone(), |
| 4012 | }; |
| 4013 | chips.push(chip); |
| 4014 | } else if let Some(basis) = row.metadata.price_basis.as_ref() |
| 4015 | && basis.short != "live" |
| 4016 | { |
| 4017 | chips.push(format!("price {}", basis.short)); |
| 4018 | } |
| 4019 | } else if matches!( |
| 4020 | row.provider, |
| 4021 | Some(ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm) |
| 4022 | ) { |
| 4023 | chips.push("local".to_string()); |
| 4024 | } |
| 4025 | // #5239/#5441: an unverified window still drives budgets, but the chip |
| 4026 | // must not lend it a verified reading. Honesty rides as its own chip |
| 4027 | // *after* the stance so a squeezed row sheds the marker before it ever |
| 4028 | // sheds the stance; the full "(unverified)" prose lives in the hint |
| 4029 | // line, which always renders it. |
| 4030 | if row.metadata.context_window_unverified && row.metadata.context_window.is_none() { |
| 4031 | chips.push("unverified ctx".to_string()); |
| 4032 | } |
| 4033 | if let Some(max_output) = row.metadata.max_output { |
| 4034 | // #5440: an assumed floor is shown as such, never as a documented |
| 4035 | // ceiling. |
| 4036 | let suffix = if row.metadata.max_output_unverified { |
| 4037 | " (assumed floor)" |
| 4038 | } else { |
| 4039 | "" |
| 4040 | }; |
| 4041 | chips.push(format!( |
| 4042 | "{} out{suffix}", |
| 4043 | format_context_window(u64::from(max_output)) |
| 4044 | )); |
| 4045 | } |
| 4046 | // Modality and tool facts are shown only when the catalog genuinely knows |
| 4047 | // them — an unknown is never rendered as a claim. |
| 4048 | match row.metadata.vision { |
| 4049 | SupportState::Supported => chips.push("vision".to_string()), |
| 4050 | SupportState::Unsupported => chips.push("text only".to_string()), |
| 4051 | SupportState::Unknown => {} |
| 4052 | } |
| 4053 | if let Some(tool_calls) = row.metadata.tool_calls { |
| 4054 | chips.push(if tool_calls { |
| 4055 | "tools".to_string() |
| 4056 | } else { |
| 4057 | "no tools".to_string() |
| 4058 | }); |
| 4059 | } |
| 4060 | if let Some(reason) = row.blocked_reason.as_deref() { |
| 4061 | chips.push(reason.to_string()); |
| 4062 | } |
| 4063 | chips |
| 4064 | } |
| 4065 | |
| 4066 | /// Join metadata chips, dropping the lowest-priority ones until the result |
| 4067 | /// fits. Truncating mid-chip would render a half-word fact, so whole chips are |
| 4068 | /// shed instead. |
| 4069 | fn fit_meta_chips(chips: &[String], width: usize) -> String { |
| 4070 | for take in (1..=chips.len()).rev() { |
| 4071 | let joined = chips[..take].join(" · "); |
| 4072 | if unicode_width::UnicodeWidthStr::width(joined.as_str()) <= width { |
| 4073 | return joined; |
| 4074 | } |
| 4075 | } |
| 4076 | // A single chip that still does not fit is prose (an `auto` explanation or |
| 4077 | // an effort description) rather than a fact token, so it is truncated |
| 4078 | // instead of dropped — but only when the column can hold something worth |
| 4079 | // reading. |
| 4080 | match chips.first() { |
| 4081 | Some(first) if width >= MIN_META_WIDTH => fit_text(first, width), |
| 4082 | _ => String::new(), |
| 4083 | } |
| 4084 | } |
| 4085 | |
| 4086 | /// Whether a model row shows in the active catalog view (#3830 / #4115). |
| 4087 | fn model_row_visible_in_view(row: &ModelPickerRow, view: ModelListView) -> bool { |
| 4088 | match view { |
| 4089 | ModelListView::Configured => model_row_visible_by_default(row), |
| 4090 | ModelListView::Catalog if model_is_non_language(row) => false, |
| 4091 | ModelListView::Catalog => true, |
| 4092 | ModelListView::New |
| 4093 | | ModelListView::Coding |
| 4094 | | ModelListView::Cheap |
| 4095 | | ModelListView::LongContext => { |
| 4096 | row.external_agent.is_none() |
| 4097 | && (row.provider.is_some() || row.id != "auto") |
| 4098 | && !model_is_non_language(row) |
| 4099 | } |
| 4100 | } |
| 4101 | } |
| 4102 | |
| 4103 | fn model_is_non_language(row: &ModelPickerRow) -> bool { |
| 4104 | matches!( |
| 4105 | row.metadata.model_type.as_deref(), |
| 4106 | Some( |
| 4107 | "image" | "embedding" | "video" | "speech" | "transcription" | "reranking" | "realtime" |
| 4108 | ) |
| 4109 | ) |
| 4110 | } |
| 4111 | |
| 4112 | fn model_row_visible_by_default(row: &ModelPickerRow) -> bool { |
| 4113 | if row.external_agent.is_some() { |
| 4114 | return row.default_rank.is_some(); |
| 4115 | } |
| 4116 | row.provider.is_none() || row.default_rank.is_some() |
| 4117 | } |
| 4118 | |
| 4119 | fn model_row_matches_route(row: &ModelPickerRow, provider: ProviderKind, identity: &str) -> bool { |
| 4120 | row.provider.is_none() |
| 4121 | || (row.provider == Some(provider) && row_provider_identity(row) == Some(identity)) |
| 4122 | } |
| 4123 | |
| 4124 | fn sort_model_rows_for_view<'a, T>( |
| 4125 | rows: &mut [T], |
| 4126 | model_row: impl Fn(&T) -> &'a ModelPickerRow, |
| 4127 | view: ModelListView, |
| 4128 | pins: &[PinnedModel], |
| 4129 | ) { |
| 4130 | use std::cmp::Reverse; |
| 4131 | // Same route match as marking and labelling (`pin_names_row`), so a row |
| 4132 | // never sorts into the pinned block without carrying its pin. |
| 4133 | let pin_rank = |row: &ModelPickerRow| { |
| 4134 | pins.iter() |
| 4135 | .position(|pin| pin_names_row(pin, row)) |
| 4136 | .unwrap_or(usize::MAX) |
| 4137 | }; |
| 4138 | match view { |
| 4139 | // Sections in order; within one, a row a fresh roster no longer lists |
| 4140 | // goes last, then the section's own rank. |
| 4141 | ModelListView::Configured => rows.sort_by_cached_key(|item| { |
| 4142 | let row = model_row(item); |
| 4143 | ( |
| 4144 | row.default_rank.map(|(section, _)| section), |
| 4145 | row.not_listed.is_some(), |
| 4146 | row.external_agent.as_ref().map(external_agent_order), |
| 4147 | row.default_rank.map(|(_, rank)| rank), |
| 4148 | row_group_key(row), |
| 4149 | Reverse(model_version_key(&row.id)), |
| 4150 | row.id.clone(), |
| 4151 | ) |
| 4152 | }), |
| 4153 | ModelListView::Catalog => rows.sort_by_cached_key(|item| { |
| 4154 | let row = model_row(item); |
| 4155 | ( |
| 4156 | pin_rank(row), |
| 4157 | catalog_connection_order(row), |
| 4158 | row_group_key(row), |
| 4159 | Reverse(model_version_key(&row.id)), |
| 4160 | row.id.clone(), |
| 4161 | ) |
| 4162 | }), |
| 4163 | ModelListView::New => rows.sort_by_cached_key(|item| { |
| 4164 | let row = model_row(item); |
| 4165 | (Reverse(offering_fetched_at(row)), row.id.clone()) |
| 4166 | }), |
| 4167 | ModelListView::Coding => rows.sort_by_cached_key(|item| { |
| 4168 | let row = model_row(item); |
| 4169 | (Reverse(coding_score(row)), row.id.clone()) |
| 4170 | }), |
| 4171 | ModelListView::Cheap => { |
| 4172 | // Catalog lookup/pricing parsing happens once per row. Unknown |
| 4173 | // prices stay last; f64 retains its existing partial-order behavior. |
| 4174 | let prices: BTreeMap<_, _> = rows |
| 4175 | .iter() |
| 4176 | .map(|item| { |
| 4177 | let row = model_row(item); |
| 4178 | ( |
| 4179 | ( |
| 4180 | row_provider_identity(row).unwrap_or_default().to_string(), |
| 4181 | row.id.clone(), |
| 4182 | ), |
| 4183 | input_price_per_million(row), |
| 4184 | ) |
| 4185 | }) |
| 4186 | .collect(); |
| 4187 | rows.sort_by(|left, right| { |
| 4188 | let left = model_row(left); |
| 4189 | let right = model_row(right); |
| 4190 | let price = |row: &ModelPickerRow| { |
| 4191 | prices[&( |
| 4192 | row_provider_identity(row).unwrap_or_default().to_string(), |
| 4193 | row.id.clone(), |
| 4194 | )] |
| 4195 | }; |
| 4196 | match (price(left), price(right)) { |
| 4197 | (Some(l), Some(r)) => l.partial_cmp(&r).unwrap_or(std::cmp::Ordering::Equal), |
| 4198 | (Some(_), None) => std::cmp::Ordering::Less, |
| 4199 | (None, Some(_)) => std::cmp::Ordering::Greater, |
| 4200 | (None, None) => std::cmp::Ordering::Equal, |
| 4201 | } |
| 4202 | .then_with(|| left.id.cmp(&right.id)) |
| 4203 | }); |
| 4204 | } |
| 4205 | ModelListView::LongContext => rows.sort_by_cached_key(|item| { |
| 4206 | let row = model_row(item); |
| 4207 | (Reverse(context_tokens(row)), row.id.clone()) |
| 4208 | }), |
| 4209 | } |
| 4210 | } |
| 4211 | |
| 4212 | fn external_agent_order(agent: &ExternalAgentRowInfo) -> (u8, usize) { |
| 4213 | let readiness = if agent.runnable { |
| 4214 | 0 |
| 4215 | } else if agent.state == "installed" { |
| 4216 | 1 |
| 4217 | } else { |
| 4218 | 2 |
| 4219 | }; |
| 4220 | let registry_rank = codewhale_engine::fleet::agents::AGENTS |
| 4221 | .iter() |
| 4222 | .position(|entry| entry.id == agent.agent_id) |
| 4223 | .unwrap_or(usize::MAX); |
| 4224 | (readiness, registry_rank) |
| 4225 | } |
| 4226 | |
| 4227 | fn catalog_connection_order(row: &ModelPickerRow) -> (u8, u8, usize) { |
| 4228 | if let Some(agent) = row.external_agent.as_ref() { |
| 4229 | let (readiness, rank) = external_agent_order(agent); |
| 4230 | return (1, readiness, rank); |
| 4231 | } |
| 4232 | if row.provider.is_none() { |
| 4233 | return (0, 0, 0); |
| 4234 | } |
| 4235 | let rank = row_provider_identity(row) |
| 4236 | .and_then(suggested_provider_rank) |
| 4237 | .unwrap_or(usize::MAX); |
| 4238 | (2, 0, rank) |
| 4239 | } |
| 4240 | |
| 4241 | fn sort_model_indices(indices: &mut [usize], rows: &[ModelPickerRow], sort: ModelSort) { |
| 4242 | // Precompute owned text once, keeping navigation independent of catalog size. |
| 4243 | let keys: BTreeMap<_, _> = indices |
| 4244 | .iter() |
| 4245 | .map(|index| { |
| 4246 | let row = &rows[*index]; |
| 4247 | ( |
| 4248 | *index, |
| 4249 | ( |
| 4250 | row.id.to_ascii_lowercase(), |
| 4251 | row_provider_identity(row) |
| 4252 | .unwrap_or_default() |
| 4253 | .to_ascii_lowercase(), |
| 4254 | ), |
| 4255 | ) |
| 4256 | }) |
| 4257 | .collect(); |
| 4258 | indices.sort_by(|left, right| { |
| 4259 | let a = &rows[*left]; |
| 4260 | let b = &rows[*right]; |
| 4261 | let order = match sort.column { |
| 4262 | ModelSortColumn::Model => keys[left].0.cmp(&keys[right].0), |
| 4263 | ModelSortColumn::Provider => keys[left].1.cmp(&keys[right].1), |
| 4264 | ModelSortColumn::Context => a.metadata.context_window.cmp(&b.metadata.context_window), |
| 4265 | }; |
| 4266 | let order = if sort.descending { |
| 4267 | order.reverse() |
| 4268 | } else { |
| 4269 | order |
| 4270 | }; |
| 4271 | // Auto remains reachable at the top; missing context stays last in |
| 4272 | // either direction rather than pretending to be a zero-sized model. |
| 4273 | a.provider |
| 4274 | .is_some() |
| 4275 | .cmp(&b.provider.is_some()) |
| 4276 | .then_with(|| { |
| 4277 | if sort.column == ModelSortColumn::Context { |
| 4278 | a.metadata |
| 4279 | .context_window |
| 4280 | .is_none() |
| 4281 | .cmp(&b.metadata.context_window.is_none()) |
| 4282 | } else { |
| 4283 | std::cmp::Ordering::Equal |
| 4284 | } |
| 4285 | }) |
| 4286 | .then(order) |
| 4287 | .then_with(|| keys[left].cmp(&keys[right])) |
| 4288 | }); |
| 4289 | } |
| 4290 | |
| 4291 | /// Stable grouping key so a provider's families render as one contiguous |
| 4292 | /// block each, which is what the family-header logic already assumes when it |
| 4293 | /// only compares against the previous row. |
| 4294 | fn row_group_key(row: &ModelPickerRow) -> (String, String) { |
| 4295 | let provider = row_provider_identity(row) |
| 4296 | .map(str::to_ascii_lowercase) |
| 4297 | .or_else(|| { |
| 4298 | row.provider |
| 4299 | .map(|provider| provider.as_str().to_ascii_lowercase()) |
| 4300 | }) |
| 4301 | .unwrap_or_default(); |
| 4302 | let family = row |
| 4303 | .provider |
| 4304 | .and_then(|provider| { |
| 4305 | catalog_family_for_identity(provider, row.provider_identity.as_deref(), &row.id) |
| 4306 | }) |
| 4307 | .unwrap_or_default() |
| 4308 | .to_ascii_lowercase(); |
| 4309 | (provider, family) |
| 4310 | } |
| 4311 | |
| 4312 | /// Version ordinal for "newest first" inside a family. |
| 4313 | /// |
| 4314 | /// Model ids carry their version as dotted or dashed numbers (`GLM-5.3`, |
| 4315 | /// `deepseek-v4-pro`, `gpt-5.6-terra`), so the comparison is on the numeric |
| 4316 | /// components in order, not on the string — otherwise `GLM-5.10` would sort |
| 4317 | /// below `GLM-5.2`. Ids with no digits compare equal and fall through to the |
| 4318 | /// alphabetical tiebreak. |
| 4319 | fn model_version_key(id: &str) -> Vec<u32> { |
| 4320 | let mut parts = Vec::new(); |
| 4321 | let mut current: Option<u32> = None; |
| 4322 | for ch in id.chars() { |
| 4323 | if let Some(digit) = ch.to_digit(10) { |
| 4324 | current = Some( |
| 4325 | current |
| 4326 | .unwrap_or(0) |
| 4327 | .saturating_mul(10) |
| 4328 | .saturating_add(digit), |
| 4329 | ); |
| 4330 | } else if let Some(value) = current.take() { |
| 4331 | parts.push(value); |
| 4332 | } |
| 4333 | } |
| 4334 | if let Some(value) = current { |
| 4335 | parts.push(value); |
| 4336 | } |
| 4337 | parts |
| 4338 | } |
| 4339 | |
| 4340 | fn row_provider_label(row: &ModelPickerRow) -> &str { |
| 4341 | let Some(key) = row_provider_identity(row) else { |
| 4342 | return "unavailable"; |
| 4343 | }; |
| 4344 | if row.provider == Some(ProviderKind::Custom) { |
| 4345 | return key; |
| 4346 | } |
| 4347 | if let Some(label) = row |
| 4348 | .provider |
| 4349 | .and_then(|provider| model_connection_name(provider, key)) |
| 4350 | { |
| 4351 | return label; |
| 4352 | } |
| 4353 | codewhale_config::descriptors::compatibility_for_id(key) |
| 4354 | .filter(|metadata| Some(metadata.kind) == row.provider) |
| 4355 | .map_or(key, |metadata| metadata.label) |
| 4356 | } |
| 4357 | |
| 4358 | fn row_provider_filter_key(row: &ModelPickerRow) -> Option<String> { |
| 4359 | row.provider?; |
| 4360 | row_provider_identity(row).map(str::to_string) |
| 4361 | } |
| 4362 | |
| 4363 | fn provider_filter_label(key: &str) -> String { |
| 4364 | codewhale_config::descriptors::compatibility_for_id(key).map_or_else( |
| 4365 | || key.to_string(), |
| 4366 | |metadata| { |
| 4367 | model_connection_name(metadata.kind, key) |
| 4368 | .unwrap_or(metadata.label) |
| 4369 | .to_string() |
| 4370 | }, |
| 4371 | ) |
| 4372 | } |
| 4373 | |
| 4374 | fn row_provider_identity(row: &ModelPickerRow) -> Option<&str> { |
| 4375 | row.provider_identity.as_deref().or_else(|| { |
| 4376 | row.provider |
| 4377 | .filter(|provider| *provider != ProviderKind::Custom) |
| 4378 | .map(ProviderKind::as_str) |
| 4379 | }) |
| 4380 | } |
| 4381 | |
| 4382 | fn offering_for_row(row: &ModelPickerRow) -> Option<codewhale_config::catalog::CatalogOffering> { |
| 4383 | let provider = row.provider?; |
| 4384 | catalog_offering_for_model_identity(provider, row.provider_identity.as_deref(), &row.id) |
| 4385 | } |
| 4386 | |
| 4387 | fn offering_fetched_at(row: &ModelPickerRow) -> u64 { |
| 4388 | match offering_for_row(row).map(|o| o.source) { |
| 4389 | Some( |
| 4390 | CatalogSource::Live { fetched_at, .. } | CatalogSource::CloudFacts { fetched_at, .. }, |
| 4391 | ) => fetched_at, |
| 4392 | _ => 0, |
| 4393 | } |
| 4394 | } |
| 4395 | |
| 4396 | fn context_tokens(row: &ModelPickerRow) -> u64 { |
| 4397 | row.metadata.context_window.map(u64::from).unwrap_or(0) |
| 4398 | } |
| 4399 | |
| 4400 | fn input_price_per_million(row: &ModelPickerRow) -> Option<f64> { |
| 4401 | if matches!(row.metadata.source, Some(CatalogSource::ConfigOverride)) { |
| 4402 | return row |
| 4403 | .metadata |
| 4404 | .declared_usd_input_price |
| 4405 | .as_ref() |
| 4406 | .and_then(|price| price.parse().ok()); |
| 4407 | } |
| 4408 | if matches!( |
| 4409 | row.metadata.pricing, |
| 4410 | PickerPricing::Unavailable | PickerPricing::Status(_) |
| 4411 | ) { |
| 4412 | return None; |
| 4413 | } |
| 4414 | offering_for_row(row) |
| 4415 | .and_then(|offering| OfferingPricing::from_catalog_offering(&offering)) |
| 4416 | .and_then(|pricing| pricing.input_per_million) |
| 4417 | } |
| 4418 | |
| 4419 | fn coding_score(row: &ModelPickerRow) -> u32 { |
| 4420 | let mut score = 0_u32; |
| 4421 | if let Some(offering) = offering_for_row(row) { |
| 4422 | let text_ok = offering.modalities.as_ref().is_none_or(|modalities| { |
| 4423 | modalities.output.is_empty() |
| 4424 | || modalities |
| 4425 | .output |
| 4426 | .iter() |
| 4427 | .any(|m| m.eq_ignore_ascii_case("text")) |
| 4428 | }); |
| 4429 | if text_ok { |
| 4430 | score += 40; |
| 4431 | } |
| 4432 | } |
| 4433 | if row.metadata.tool_calls == Some(true) { |
| 4434 | score += 40; |
| 4435 | } |
| 4436 | if row.metadata.reasoning { |
| 4437 | score += 10; |
| 4438 | } |
| 4439 | if row.metadata.context_window.unwrap_or(0) >= 100_000 { |
| 4440 | score += 10; |
| 4441 | } |
| 4442 | score |
| 4443 | } |
| 4444 | |
| 4445 | fn effective_picker_metadata( |
| 4446 | config: &Config, |
| 4447 | provider: Option<ProviderKind>, |
| 4448 | id: &str, |
| 4449 | ) -> EffectivePickerMetadata { |
| 4450 | effective_picker_metadata_for_identity(config, provider, None, id) |
| 4451 | } |
| 4452 | |
| 4453 | fn effective_picker_metadata_for_identity( |
| 4454 | config: &Config, |
| 4455 | provider: Option<ProviderKind>, |
| 4456 | provider_identity: Option<&str>, |
| 4457 | id: &str, |
| 4458 | ) -> EffectivePickerMetadata { |
| 4459 | effective_picker_metadata_with_codex(config, provider, provider_identity, id, None) |
| 4460 | } |
| 4461 | |
| 4462 | fn effective_picker_metadata_with_codex( |
| 4463 | config: &Config, |
| 4464 | provider: Option<ProviderKind>, |
| 4465 | provider_identity: Option<&str>, |
| 4466 | id: &str, |
| 4467 | codex_metadata: Option<&CodexModelMetadata>, |
| 4468 | ) -> EffectivePickerMetadata { |
| 4469 | let captured = provider.and_then(|kind| { |
| 4470 | let identity = match provider_identity { |
| 4471 | Some(key) => config.legacy_selection_identity(key), |
| 4472 | None => config.builtin_provider_identity(kind), |
| 4473 | } |
| 4474 | .ok()?; |
| 4475 | (identity.provider == kind).then_some(identity) |
| 4476 | }); |
| 4477 | if provider.is_some() && captured.is_none() { |
| 4478 | return EffectivePickerMetadata { |
| 4479 | reasoning_unknown: true, |
| 4480 | ..EffectivePickerMetadata::default() |
| 4481 | }; |
| 4482 | } |
| 4483 | let offering = captured.as_ref().and_then(|identity| { |
| 4484 | let base_url = config.base_url_for_route(identity); |
| 4485 | codewhale_engine::provider_lake::configured_catalog_offering_for_route( |
| 4486 | config, |
| 4487 | identity.provider, |
| 4488 | identity.key.as_str(), |
| 4489 | &base_url, |
| 4490 | id, |
| 4491 | ) |
| 4492 | }); |
| 4493 | let card = offering.as_ref().map(ModelReferenceCard::from_offering); |
| 4494 | let registry = codewhale_config::catalog::reviewed::intrinsic_model(id); |
| 4495 | |
| 4496 | let Some(provider) = provider else { |
| 4497 | return EffectivePickerMetadata { |
| 4498 | context_window: registry.as_ref().and_then(|meta| meta.context_window), |
| 4499 | context_window_unverified: false, |
| 4500 | max_output: registry |
| 4501 | .as_ref() |
| 4502 | .and_then(|meta| meta.generation_default.or(meta.max_output)), |
| 4503 | max_output_unverified: false, |
| 4504 | tool_calls: None, |
| 4505 | reasoning: registry |
| 4506 | .as_ref() |
| 4507 | .is_some_and(|meta| meta.reasoning == Some(true)), |
| 4508 | vision: SupportState::Unknown, |
| 4509 | pricing: if codewhale_engine::pricing::has_pricing_for_model(id) { |
| 4510 | PickerPricing::Known("priced".to_string()) |
| 4511 | } else { |
| 4512 | PickerPricing::Unknown |
| 4513 | }, |
| 4514 | display_name: None, |
| 4515 | reasoning_unknown: registry |
| 4516 | .as_ref() |
| 4517 | .is_none_or(|meta| meta.reasoning.is_none()), |
| 4518 | declared_usd_input_price: None, |
| 4519 | price_basis: None, |
| 4520 | wire_model_id: None, |
| 4521 | canonical_model: None, |
| 4522 | source: None, |
| 4523 | model_type: None, |
| 4524 | ..EffectivePickerMetadata::default() |
| 4525 | }; |
| 4526 | }; |
| 4527 | |
| 4528 | let admitted = captured |
| 4529 | .as_ref() |
| 4530 | .expect("provider metadata admission checked"); |
| 4531 | let identity = admitted.key.as_str(); |
| 4532 | let context_override = config |
| 4533 | .model_context_windows_for(admitted) |
| 4534 | .and_then(|windows| windows.get(id).copied()) |
| 4535 | .or_else(|| config.context_window_for_provider_config(admitted)); |
| 4536 | let base_url = config.base_url_for_route(admitted); |
| 4537 | if let Some(declared) = codewhale_runtime::config::configured_model_for_route( |
| 4538 | config, provider, identity, &base_url, id, |
| 4539 | ) { |
| 4540 | let (wire_model_id, canonical_model) = picker_offering_identity(offering.as_ref(), id); |
| 4541 | return EffectivePickerMetadata { |
| 4542 | display_name: declared.display_name.clone(), |
| 4543 | declared_usd_input_price: declared |
| 4544 | .to_catalog_offering() |
| 4545 | .cost |
| 4546 | .as_ref() |
| 4547 | .and_then(|cost| cost.input) |
| 4548 | .map(|price| price.to_string()), |
| 4549 | context_window: context_override.or_else(|| { |
| 4550 | declared |
| 4551 | .limit |
| 4552 | .as_ref() |
| 4553 | .and_then(|limit| limit.context) |
| 4554 | .and_then(|value| u32::try_from(value).ok()) |
| 4555 | }), |
| 4556 | context_window_override: context_override.is_some(), |
| 4557 | max_output: declared |
| 4558 | .limit |
| 4559 | .as_ref() |
| 4560 | .and_then(|limit| limit.output) |
| 4561 | .and_then(|value| u32::try_from(value).ok()), |
| 4562 | tool_calls: declared.tool_call, |
| 4563 | reasoning: declared.reasoning.unwrap_or(false), |
| 4564 | reasoning_unknown: declared.reasoning.is_none(), |
| 4565 | vision: codewhale_config::models_dev::image_input_support(declared.modalities.as_ref()), |
| 4566 | pricing: card |
| 4567 | .as_ref() |
| 4568 | .filter(|card| card.price_label() != "unknown") |
| 4569 | .map_or(PickerPricing::Unknown, |card| { |
| 4570 | PickerPricing::Known(card.price_label()) |
| 4571 | }), |
| 4572 | price_basis: picker_price_basis(card.as_ref().and_then(|card| card.pricing.as_ref())), |
| 4573 | wire_model_id, |
| 4574 | canonical_model, |
| 4575 | source: Some(CatalogSource::ConfigOverride), |
| 4576 | ..EffectivePickerMetadata::default() |
| 4577 | }; |
| 4578 | } |
| 4579 | if offering.is_none() |
| 4580 | && provider != ProviderKind::OpenaiCodex |
| 4581 | && codewhale_config::provider_preserves_custom_base_url_model(provider, &base_url) |
| 4582 | { |
| 4583 | return EffectivePickerMetadata { |
| 4584 | context_window: context_override, |
| 4585 | context_window_override: context_override.is_some(), |
| 4586 | reasoning_unknown: true, |
| 4587 | ..EffectivePickerMetadata::default() |
| 4588 | }; |
| 4589 | } |
| 4590 | let overrides = CapabilityOverride { |
| 4591 | context_window: context_override, |
| 4592 | ..CapabilityOverride::default() |
| 4593 | }; |
| 4594 | let profile = offering.as_ref().map_or_else( |
| 4595 | || resolved_capability_profile_with_overrides(provider, id, overrides.clone()), |
| 4596 | |offering| { |
| 4597 | let route_offering = offering.to_offering(); |
| 4598 | resolved_capability_profile_for_route_with_overrides( |
| 4599 | provider, |
| 4600 | id, |
| 4601 | route_offering.capabilities, |
| 4602 | route_offering.limits, |
| 4603 | overrides.clone(), |
| 4604 | ) |
| 4605 | }, |
| 4606 | ); |
| 4607 | let card_context = card |
| 4608 | .as_ref() |
| 4609 | .and_then(|card| card.context_window) |
| 4610 | .map(|tokens| tokens.min(u64::from(u32::MAX)) as u32); |
| 4611 | let preserves_unknown_limits = offering.is_some() |
| 4612 | || (provider == ProviderKind::Together |
| 4613 | && id.eq_ignore_ascii_case( |
| 4614 | codewhale_config::catalog::reviewed::constants::TOGETHER_INKLING_MODEL, |
| 4615 | )); |
| 4616 | let context_window = if context_override.is_some() { |
| 4617 | profile.context_window |
| 4618 | } else if provider == ProviderKind::OpenaiCodex { |
| 4619 | codex_metadata.and_then(|metadata| metadata.context_window) |
| 4620 | } else if preserves_unknown_limits { |
| 4621 | card_context |
| 4622 | } else { |
| 4623 | profile.context_window |
| 4624 | }; |
| 4625 | let card_output = card |
| 4626 | .as_ref() |
| 4627 | .and_then(|card| card.max_output) |
| 4628 | .map(|tokens| tokens.min(u64::from(u32::MAX)) as u32); |
| 4629 | // The Codex cache does not publish a route-owned output ceiling. The |
| 4630 | // profile's current value is inherited from the same-id OpenAI API model, |
| 4631 | // so omitting it is more truthful than claiming that API limit for OAuth. |
| 4632 | let max_output = if provider == ProviderKind::OpenaiCodex { |
| 4633 | None |
| 4634 | } else if preserves_unknown_limits { |
| 4635 | card_output |
| 4636 | } else { |
| 4637 | profile.max_output |
| 4638 | }; |
| 4639 | let profile_tool_calls = match profile.native_tool_calls { |
| 4640 | SupportState::Supported => Some(true), |
| 4641 | SupportState::Unsupported => Some(false), |
| 4642 | SupportState::Unknown => None, |
| 4643 | }; |
| 4644 | let tool_calls = if provider == ProviderKind::OpenaiCodex { |
| 4645 | codex_metadata.and(profile_tool_calls) |
| 4646 | } else { |
| 4647 | offering |
| 4648 | .as_ref() |
| 4649 | .and_then(|offering| offering.tool_call) |
| 4650 | .or(profile_tool_calls) |
| 4651 | }; |
| 4652 | let reasoning = if provider == ProviderKind::OpenaiCodex { |
| 4653 | codex_metadata |
| 4654 | .map(|metadata| { |
| 4655 | metadata |
| 4656 | .reasoning |
| 4657 | .unwrap_or_else(|| profile.supports_reasoning()) |
| 4658 | }) |
| 4659 | .unwrap_or(false) |
| 4660 | } else { |
| 4661 | offering |
| 4662 | .as_ref() |
| 4663 | .and_then(|offering| offering.reasoning) |
| 4664 | .unwrap_or_else(|| profile.supports_reasoning()) |
| 4665 | }; |
| 4666 | let vision = profile.image_input; |
| 4667 | let card_price = card.as_ref().and_then(|card| { |
| 4668 | let label = card.price_label(); |
| 4669 | (label != "unknown").then_some(label) |
| 4670 | }); |
| 4671 | let pricing_status = card |
| 4672 | .as_ref() |
| 4673 | .and_then(|card| card.pricing.as_ref()) |
| 4674 | .map(|pricing| pricing.status_label_at(codewhale_config::catalog::now_unix())); |
| 4675 | let pricing = if provider == ProviderKind::OpenaiCodex { |
| 4676 | PickerPricing::Unavailable |
| 4677 | } else if let Some(status @ ("stale" | "unverified" | "unavailable")) = pricing_status { |
| 4678 | PickerPricing::Status(status) |
| 4679 | } else if let Some(label) = card_price { |
| 4680 | PickerPricing::Known(label) |
| 4681 | } else if codewhale_engine::pricing::has_pricing_for_provider(provider, id) { |
| 4682 | PickerPricing::Known("priced".to_string()) |
| 4683 | } else { |
| 4684 | PickerPricing::Unknown |
| 4685 | }; |
| 4686 | let price_basis = picker_price_basis(card.as_ref().and_then(|card| card.pricing.as_ref())) |
| 4687 | .or_else(|| { |
| 4688 | matches!(pricing, PickerPricing::Known(_)).then(|| PriceBasis { |
| 4689 | short: "cached", |
| 4690 | detail: "bundled estimate, no fetch clock".to_string(), |
| 4691 | }) |
| 4692 | }); |
| 4693 | let (wire_model_id, canonical_model) = picker_offering_identity(offering.as_ref(), id); |
| 4694 | |
| 4695 | // Honesty rungs (#5239, #5440, #5441). A window that reached the picker |
| 4696 | // only through the legacy provider fallback — no offering, no catalog |
| 4697 | // row, no Codex roster, no operator override — is a guess (possibly an |
| 4698 | // `_Nk` name-suffix parse), and an unknown Anthropic-family model's |
| 4699 | // output ceiling is an assumed floor. Both still drive budgets; both |
| 4700 | // must say what they are instead of borrowing a verified label. |
| 4701 | let context_window_unverified = context_window.is_some() |
| 4702 | && context_override.is_none() |
| 4703 | && provider != ProviderKind::OpenaiCodex |
| 4704 | && !preserves_unknown_limits |
| 4705 | && codewhale_config::catalog::reviewed::intrinsic_model(id) |
| 4706 | .and_then(|row| row.context_window) |
| 4707 | .is_none(); |
| 4708 | let max_output_unverified = max_output.is_some() |
| 4709 | && matches!( |
| 4710 | provider, |
| 4711 | ProviderKind::Anthropic | ProviderKind::MinimaxAnthropic | ProviderKind::Openmodel |
| 4712 | ) |
| 4713 | && !preserves_unknown_limits |
| 4714 | && codewhale_models::max_output_tokens_for_model(id).is_none(); |
| 4715 | |
| 4716 | EffectivePickerMetadata { |
| 4717 | context_window, |
| 4718 | context_window_override: context_override.is_some(), |
| 4719 | context_window_unverified, |
| 4720 | max_output, |
| 4721 | max_output_unverified, |
| 4722 | tool_calls, |
| 4723 | reasoning, |
| 4724 | vision, |
| 4725 | pricing, |
| 4726 | display_name: codex_metadata.and_then(|model| model.display_name.clone()), |
| 4727 | codex_efforts: codex_metadata |
| 4728 | .map(|model| model.efforts.clone()) |
| 4729 | .unwrap_or_default(), |
| 4730 | reasoning_unknown: if provider == ProviderKind::OpenaiCodex { |
| 4731 | codex_metadata.is_none_or(|metadata| metadata.reasoning.is_none()) |
| 4732 | } else { |
| 4733 | offering |
| 4734 | .as_ref() |
| 4735 | .map_or(profile.reasoning == SupportState::Unknown, |offering| { |
| 4736 | offering.reasoning.is_none() |
| 4737 | }) |
| 4738 | }, |
| 4739 | declared_usd_input_price: None, |
| 4740 | price_basis, |
| 4741 | wire_model_id, |
| 4742 | canonical_model, |
| 4743 | source: card.map(|card| card.source), |
| 4744 | model_type: offering |
| 4745 | .as_ref() |
| 4746 | .and_then(|offering| offering.model_type.clone()), |
| 4747 | } |
| 4748 | } |
| 4749 | |
| 4750 | fn picker_price_basis(pricing: Option<&OfferingPricing>) -> Option<PriceBasis> { |
| 4751 | let pricing = pricing?; |
| 4752 | let now = codewhale_config::catalog::now_unix(); |
| 4753 | let (short, noun) = match pricing.status_label_at(now) { |
| 4754 | "live_estimate" => ("live", "live estimate"), |
| 4755 | "bundled_estimate" => ("cached", "cached estimate"), |
| 4756 | "documented_estimate" => ("documented", "documented estimate"), |
| 4757 | "operator_estimate" => ("operator", "operator estimate"), |
| 4758 | "verified_cloud_estimate" => ("cloud", "verified cloud estimate"), |
| 4759 | "stale" => ("stale", "stale estimate"), |
| 4760 | "unverified" => ("unverified", "unverified estimate"), |
| 4761 | _ => return None, |
| 4762 | }; |
| 4763 | let clock = match pricing.expires_at { |
| 4764 | Some(expires_at) if expires_at > now => { |
| 4765 | format!("expires in {}", format_price_span(expires_at - now)) |
| 4766 | } |
| 4767 | _ => match pricing.fetched_at.or(pricing.effective_at) { |
| 4768 | Some(fetched_at) => format!( |
| 4769 | "fetched {} ago", |
| 4770 | format_price_span(now.saturating_sub(fetched_at)) |
| 4771 | ), |
| 4772 | None => "no fetch clock".to_string(), |
| 4773 | }, |
| 4774 | }; |
| 4775 | Some(PriceBasis { |
| 4776 | short, |
| 4777 | detail: format!("{noun}, {clock}"), |
| 4778 | }) |
| 4779 | } |
| 4780 | |
| 4781 | fn format_price_span(secs: u64) -> String { |
| 4782 | let minutes = secs / 60; |
| 4783 | if minutes == 0 { |
| 4784 | "under a minute".to_string() |
| 4785 | } else if minutes < 60 { |
| 4786 | format!("{minutes}m") |
| 4787 | } else if minutes < 24 * 60 { |
| 4788 | format!("{}h", minutes / 60) |
| 4789 | } else { |
| 4790 | format!("{}d", minutes / (24 * 60)) |
| 4791 | } |
| 4792 | } |
| 4793 | |
| 4794 | fn picker_offering_identity( |
| 4795 | offering: Option<&codewhale_config::catalog::CatalogOffering>, |
| 4796 | id: &str, |
| 4797 | ) -> (Option<String>, Option<String>) { |
| 4798 | let Some(offering) = offering else { |
| 4799 | return (None, None); |
| 4800 | }; |
| 4801 | let differs = |value: &str| !value.eq_ignore_ascii_case(id); |
| 4802 | ( |
| 4803 | differs(&offering.wire_model_id).then(|| offering.wire_model_id.clone()), |
| 4804 | offering |
| 4805 | .canonical_model |
| 4806 | .as_deref() |
| 4807 | .filter(|canonical| differs(canonical)) |
| 4808 | .map(str::to_string), |
| 4809 | ) |
| 4810 | } |
| 4811 | |
| 4812 | fn render_picker_model_hint( |
| 4813 | id: &str, |
| 4814 | provider: Option<ProviderKind>, |
| 4815 | metadata: &EffectivePickerMetadata, |
| 4816 | codex_freshness: Option<CodexModelCacheFreshness>, |
| 4817 | provider_catalog_receipt: Option<&(CatalogStatus, bool)>, |
| 4818 | ) -> String { |
| 4819 | debug_assert_ne!(id, "auto", "Auto rows use the context-aware picker hint"); |
| 4820 | |
| 4821 | let mut parts = Vec::new(); |
| 4822 | |
| 4823 | // `k3` and `kimi-k3` are the same underlying model on two different |
| 4824 | // products, so bare ids read as a confusing duplicate. Name the route: |
| 4825 | // bare `k3` is the Kimi Code membership route (validated pairing with |
| 4826 | // the coding endpoint, #4687), `kimi-k3` is the direct open platform. |
| 4827 | if provider == Some(ProviderKind::Moonshot) { |
| 4828 | match id.trim().to_ascii_lowercase().as_str() { |
| 4829 | "k3" => parts.push("Kimi Code plan route".to_string()), |
| 4830 | "kimi-k3" | "moonshotai/kimi-k3" => parts.push("Moonshot direct route".to_string()), |
| 4831 | _ => {} |
| 4832 | } |
| 4833 | } |
| 4834 | |
| 4835 | if let Some(context_window) = metadata.context_window { |
| 4836 | // The ChatGPT/Codex OAuth roster reports account-scoped windows (e.g. |
| 4837 | // 272K for gpt-5.x) that differ from the API route's limits by |
| 4838 | // deliberate policy. Label the value as route-scoped so it reads as a |
| 4839 | // route fact, not a wrong generic model limit (TUI-DOG-016). |
| 4840 | if provider == Some(ProviderKind::OpenaiCodex) { |
| 4841 | parts.push(format!( |
| 4842 | "{} ctx · ChatGPT route", |
| 4843 | format_context_window(u64::from(context_window)) |
| 4844 | )); |
| 4845 | } else if provider == Some(ProviderKind::Moonshot) |
| 4846 | && id.trim().eq_ignore_ascii_case("k3") |
| 4847 | && context_window == codewhale_models::KIMI_CODE_K3_CONTEXT_WINDOW_TOKENS |
| 4848 | { |
| 4849 | // The membership route's real window is plan-tier dependent |
| 4850 | // (256K on lower tiers, up to 1M on higher ones); this default |
| 4851 | // is the safe floor, raisable via the provider's |
| 4852 | // `context_window` setting when the plan includes 1M. |
| 4853 | parts.push(format!( |
| 4854 | "{} ctx (plan floor; raise via context_window)", |
| 4855 | format_context_window(u64::from(context_window)) |
| 4856 | )); |
| 4857 | } else { |
| 4858 | let suffix = if metadata.context_window_unverified { |
| 4859 | " (unverified)" |
| 4860 | } else { |
| 4861 | "" |
| 4862 | }; |
| 4863 | parts.push(format!( |
| 4864 | "{} ctx{}", |
| 4865 | format_context_window(u64::from(context_window)), |
| 4866 | suffix |
| 4867 | )); |
| 4868 | } |
| 4869 | } |
| 4870 | |
| 4871 | if let Some(max_output) = metadata.max_output { |
| 4872 | let suffix = if metadata.max_output_unverified { |
| 4873 | " (assumed floor)" |
| 4874 | } else { |
| 4875 | "" |
| 4876 | }; |
| 4877 | parts.push(format!( |
| 4878 | "{} out{}", |
| 4879 | format_context_window(u64::from(max_output)), |
| 4880 | suffix |
| 4881 | )); |
| 4882 | } |
| 4883 | |
| 4884 | match metadata.tool_calls { |
| 4885 | Some(true) => parts.push("tools".to_string()), |
| 4886 | Some(false) => parts.push("no tools".to_string()), |
| 4887 | None => {} |
| 4888 | } |
| 4889 | |
| 4890 | if metadata.reasoning_unknown { |
| 4891 | parts.push("reasoning unknown".to_string()); |
| 4892 | } else if metadata.reasoning { |
| 4893 | parts.push("reasoning".to_string()); |
| 4894 | } |
| 4895 | |
| 4896 | match metadata.vision { |
| 4897 | SupportState::Supported => parts.push("vision".to_string()), |
| 4898 | SupportState::Unsupported => parts.push("no vision".to_string()), |
| 4899 | SupportState::Unknown => {} |
| 4900 | } |
| 4901 | |
| 4902 | match &metadata.pricing { |
| 4903 | PickerPricing::Unavailable => {} |
| 4904 | PickerPricing::Known(label) => match metadata.price_basis.as_ref() { |
| 4905 | Some(basis) => parts.push(format!("{label} · {}", basis.detail)), |
| 4906 | None => parts.push(label.clone()), |
| 4907 | }, |
| 4908 | PickerPricing::Status(status) => parts.push( |
| 4909 | metadata |
| 4910 | .price_basis |
| 4911 | .as_ref() |
| 4912 | .map_or_else(|| format!("price {status}"), |basis| basis.detail.clone()), |
| 4913 | ), |
| 4914 | PickerPricing::Unknown => parts.push("price unknown".to_string()), |
| 4915 | } |
| 4916 | if let Some(wire) = metadata.wire_model_id.as_deref() { |
| 4917 | parts.push(format!("wire {wire}")); |
| 4918 | } |
| 4919 | if let Some(canonical) = metadata.canonical_model.as_deref() { |
| 4920 | parts.push(format!("canonical {canonical}")); |
| 4921 | } |
| 4922 | let provider_live_source = matches!(metadata.source.as_ref(), Some(CatalogSource::Live { .. })); |
| 4923 | match metadata.source.as_ref() { |
| 4924 | Some(CatalogSource::Live { .. }) => { |
| 4925 | parts.push(provider_catalog_source_label(provider_catalog_receipt)) |
| 4926 | } |
| 4927 | Some(CatalogSource::ModelsDevLive { fetched_at }) => { |
| 4928 | let now = codewhale_config::catalog::now_unix(); |
| 4929 | let age_secs = now.saturating_sub(*fetched_at); |
| 4930 | if models_dev_live::status().freshness == ModelsDevFreshness::Failed { |
| 4931 | parts.push("refresh failed; cached catalog".to_string()); |
| 4932 | } else { |
| 4933 | let status = if *fetched_at > now { |
| 4934 | CatalogStatus::Unknown |
| 4935 | } else if age_secs >= models_dev_live::DEFAULT_MODELS_DEV_TTL_SECS { |
| 4936 | CatalogStatus::Stale { age_secs } |
| 4937 | } else { |
| 4938 | CatalogStatus::Fresh |
| 4939 | }; |
| 4940 | parts.push(provider_catalog_source_label(Some(&(status, true)))); |
| 4941 | } |
| 4942 | } |
| 4943 | Some(CatalogSource::Bundled | CatalogSource::CodewhaleBundled { .. }) => { |
| 4944 | parts.push("bundled".to_string()) |
| 4945 | } |
| 4946 | Some(CatalogSource::CloudFacts { .. }) => parts.push("signed facts".to_string()), |
| 4947 | Some(CatalogSource::ConfigOverride | CatalogSource::UserOverride) => { |
| 4948 | parts.push("user declared (unverified)".to_string()) |
| 4949 | } |
| 4950 | None => {} |
| 4951 | } |
| 4952 | if !provider_live_source |
| 4953 | && let Some((CatalogStatus::Failed { reason }, _)) = provider_catalog_receipt |
| 4954 | { |
| 4955 | parts.push(format!("refresh failed ({})", reason.label())); |
| 4956 | } |
| 4957 | if provider == Some(ProviderKind::OpenaiCodex) { |
| 4958 | parts.push(match codex_freshness { |
| 4959 | Some(freshness) => freshness.picker_label().to_string(), |
| 4960 | None => "custom · OAuth roster unconfirmed".to_string(), |
| 4961 | }); |
| 4962 | } |
| 4963 | |
| 4964 | if parts.is_empty() { |
| 4965 | "provider model".to_string() |
| 4966 | } else { |
| 4967 | parts.join(" · ") |
| 4968 | } |
| 4969 | } |
| 4970 | |
| 4971 | fn provider_catalog_source_label(receipt: Option<&(CatalogStatus, bool)>) -> String { |
| 4972 | let Some((status, endpoint_matches)) = receipt else { |
| 4973 | return "catalog freshness unknown".to_string(); |
| 4974 | }; |
| 4975 | if !endpoint_matches { |
| 4976 | return "catalog from different endpoint".to_string(); |
| 4977 | } |
| 4978 | match status { |
| 4979 | CatalogStatus::Fresh => "live".to_string(), |
| 4980 | CatalogStatus::Stale { age_secs } => { |
| 4981 | let age_hours = age_secs.saturating_add(3_599) / 3_600; |
| 4982 | format!("stale catalog ({age_hours}h)") |
| 4983 | } |
| 4984 | CatalogStatus::Failed { reason } => { |
| 4985 | format!("refresh failed ({})", reason.label()) |
| 4986 | } |
| 4987 | CatalogStatus::Unknown => "catalog freshness unknown".to_string(), |
| 4988 | } |
| 4989 | } |
| 4990 | |
| 4991 | impl ModelPickerView { |
| 4992 | /// Rebuild model rows from a fresh app/config snapshot (readiness + catalog). |
| 4993 | pub fn re_resolve_from_app(&mut self, app: &App, config: &Config) { |
| 4994 | self.theme = app.ui_theme; |
| 4995 | let selected = self |
| 4996 | .visible_model_rows() |
| 4997 | .get(self.selected_model_idx) |
| 4998 | .map(|row| { |
| 4999 | ( |
| 5000 | row_provider_identity(row).map(str::to_string), |
| 5001 | row.id.clone(), |
| 5002 | ) |
| 5003 | }); |
| 5004 | self.provider_health = app.provider_health.clone(); |
| 5005 | self.route_config = config.clone(); |
| 5006 | self.initial_external_agent_id = app |
| 5007 | .external_agent |
| 5008 | .as_ref() |
| 5009 | .map(|session| session.agent_id.clone()); |
| 5010 | self.pinned_models = picker_pins_for_app(app); |
| 5011 | self.model_rows = picker_model_rows_for_app(app, config); |
| 5012 | self.apply_fleet_route_rows(app, config); |
| 5013 | *self.projection.get_mut() = None; |
| 5014 | self.last_mouse_selected = None; |
| 5015 | self.configured_providers = configured_providers(config) |
| 5016 | .into_iter() |
| 5017 | .filter(|identity| Some(identity) != self.initial_identity.as_ref()) |
| 5018 | .collect(); |
| 5019 | // Re-anchor to the same exact provider/model after pin sorting changes; |
| 5020 | // preserving only the numeric index can select a different model. |
| 5021 | let reanchored = selected.and_then(|(provider, model)| { |
| 5022 | self.visible_model_rows().iter().position(|row| { |
| 5023 | row.id == model && row_provider_identity(row).map(str::to_owned) == provider |
| 5024 | }) |
| 5025 | }); |
| 5026 | if let Some(position) = reanchored { |
| 5027 | self.selected_model_idx = position; |
| 5028 | return; |
| 5029 | } |
| 5030 | // Keep selection stable when the row still exists. |
| 5031 | let visible_len = self.visible_model_rows().len(); |
| 5032 | if self.selected_model_idx >= visible_len + usize::from(self.show_custom_model_row) { |
| 5033 | self.selected_model_idx = visible_len.saturating_sub(1); |
| 5034 | } |
| 5035 | } |
| 5036 | } |
| 5037 | |
| 5038 | impl ModelPickerView { |
| 5039 | /// Exact route of the highlighted catalog row: the target of ⇧P, ⇧F and |
| 5040 | /// Alt+↑↓. `None` on provider-less rows (`auto`) and the custom row. |
| 5041 | fn highlighted_route(&self) -> Option<(ProviderKind, Option<String>, String)> { |
| 5042 | let rows = self.visible_model_rows(); |
| 5043 | let row = rows.get(self.selected_model_idx)?; |
| 5044 | Some((row.provider?, row.provider_identity.clone(), row.id.clone())) |
| 5045 | } |
| 5046 | |
| 5047 | fn emit_pin_move(&self, delta: isize) -> ViewAction { |
| 5048 | let Some((provider, provider_id, model)) = self.highlighted_route() else { |
| 5049 | return ViewAction::None; |
| 5050 | }; |
| 5051 | ViewAction::Emit(ViewEvent::ModelPickerMovePin { |
| 5052 | provider, |
| 5053 | provider_id, |
| 5054 | model, |
| 5055 | delta, |
| 5056 | }) |
| 5057 | } |
| 5058 | |
| 5059 | /// Show an action receipt inside the picker (see `notice`). |
| 5060 | pub fn set_notice(&mut self, text: String, level: StatusToastLevel) { |
| 5061 | self.notice = Some((text, level)); |
| 5062 | } |
| 5063 | } |
| 5064 | |
| 5065 | impl ModalView for ModelPickerView { |
| 5066 | fn kind(&self) -> ModalKind { |
| 5067 | ModalKind::ModelPicker |
| 5068 | } |
| 5069 | |
| 5070 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 5071 | self |
| 5072 | } |
| 5073 | |
| 5074 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 5075 | self.last_mouse_selected = None; |
| 5076 | self.hovered_row = None; |
| 5077 | self.notice = None; |
| 5078 | // Movement keys come from the shared vocabulary (#6290); the match |
| 5079 | // below owns only the picker's own verbs. The live filter means the |
| 5080 | // typing-safe set — no letter aliases to eat the query. |
| 5081 | if let Some(motion) = codewhale_tui_kit::list_nav::motion_while_typing(&key) |
| 5082 | && self.apply_motion(motion) |
| 5083 | { |
| 5084 | return ViewAction::None; |
| 5085 | } |
| 5086 | match key.code { |
| 5087 | KeyCode::Char('s' | 'S') if key.modifiers == KeyModifiers::CONTROL => { |
| 5088 | self.cycle_sort(); |
| 5089 | ViewAction::None |
| 5090 | } |
| 5091 | // Esc carries the browsing context out so the next open can |
| 5092 | // restore it (#4109 picker memory). |
| 5093 | KeyCode::Esc if !self.query.is_empty() => { |
| 5094 | self.update_query(String::new()); |
| 5095 | ViewAction::None |
| 5096 | } |
| 5097 | KeyCode::Esc if self.provider_filter.is_some() => { |
| 5098 | self.set_provider_filter(None); |
| 5099 | ViewAction::None |
| 5100 | } |
| 5101 | KeyCode::Esc if self.purpose != ModelPickerPurpose::Session => { |
| 5102 | let editor_id = match self.purpose { |
| 5103 | ModelPickerPurpose::FleetRoute { editor_id, .. } |
| 5104 | | ModelPickerPurpose::FleetProfileRoute { editor_id, .. } => editor_id, |
| 5105 | ModelPickerPurpose::Session => unreachable!(), |
| 5106 | }; |
| 5107 | ViewAction::EmitAndClose(ViewEvent::FleetAssignmentPickerDismissed { editor_id }) |
| 5108 | } |
| 5109 | KeyCode::Esc => ViewAction::EmitAndClose(ViewEvent::ModelPickerDismissed { |
| 5110 | catalog_view: self.view.browses_all_providers(), |
| 5111 | view: self.view.memory_name().to_string(), |
| 5112 | selected_row_id: { |
| 5113 | let rows = self.visible_model_rows(); |
| 5114 | rows.get(self.selected_model_idx).map(|row| row.id.clone()) |
| 5115 | }, |
| 5116 | }), |
| 5117 | KeyCode::Enter if self.model_row_count() == 0 => ViewAction::None, |
| 5118 | KeyCode::Enter if !self.selected_model_is_selectable() => { |
| 5119 | // Never silently ignore Enter on locked models — surface the |
| 5120 | // readiness reason and offer provider setup. |
| 5121 | self.explain_unselectable_selection() |
| 5122 | } |
| 5123 | KeyCode::Enter => { |
| 5124 | if self.resolved_context_override_change().is_err() { |
| 5125 | return ViewAction::None; |
| 5126 | } |
| 5127 | ViewAction::EmitAndClose(self.build_apply_event(false)) |
| 5128 | } |
| 5129 | // Shift+D makes the visible provider/model pair the startup |
| 5130 | // default. Plain Enter deliberately stays session-local, so a |
| 5131 | // one-off route comparison cannot silently change the next launch. |
| 5132 | // Exactly Shift: this chord persists the next launch's route, so |
| 5133 | // Ctrl/Alt/Super+Shift+D must not save it by accident (U07-12). |
| 5134 | KeyCode::Char(ch) |
| 5135 | if key.modifiers == KeyModifiers::SHIFT |
| 5136 | && self.query.is_empty() |
| 5137 | && ch.eq_ignore_ascii_case(&'d') |
| 5138 | && self.selected_model_is_selectable() => |
| 5139 | { |
| 5140 | if self.resolved_context_override_change().is_err() { |
| 5141 | return ViewAction::None; |
| 5142 | } |
| 5143 | ViewAction::EmitAndClose(self.build_apply_event(true)) |
| 5144 | } |
| 5145 | // Only an empty query explains a locked row. While searching, |
| 5146 | // ⇧D is query text: it used to open provider auth for a row that |
| 5147 | // was not locked at all (#6500). |
| 5148 | KeyCode::Char(ch) |
| 5149 | if key.modifiers == KeyModifiers::SHIFT |
| 5150 | && self.query.is_empty() |
| 5151 | && ch.eq_ignore_ascii_case(&'d') => |
| 5152 | { |
| 5153 | self.explain_unselectable_selection() |
| 5154 | } |
| 5155 | // ⇧P / ⇧F act on the highlighted row while no search is typed; |
| 5156 | // while searching they are query text, so `Step-5-Preview` types |
| 5157 | // its `P` instead of pinning a row. Ctrl+P / Ctrl+F act on the |
| 5158 | // highlighted row either way, so a model found by search can still |
| 5159 | // be pinned or added to Fleet (#6500). Some terminals report the |
| 5160 | // chord as lowercase + SHIFT, hence `eq_ignore_ascii_case`. |
| 5161 | KeyCode::Char(ch) |
| 5162 | if ch.eq_ignore_ascii_case(&'p') |
| 5163 | && ((key.modifiers == KeyModifiers::SHIFT && self.query.is_empty()) |
| 5164 | || key.modifiers == KeyModifiers::CONTROL) => |
| 5165 | { |
| 5166 | let Some((provider, provider_id, model)) = self.highlighted_route() else { |
| 5167 | return ViewAction::None; |
| 5168 | }; |
| 5169 | ViewAction::Emit(ViewEvent::ModelPickerTogglePin { |
| 5170 | provider, |
| 5171 | provider_id, |
| 5172 | model, |
| 5173 | }) |
| 5174 | } |
| 5175 | KeyCode::Char(ch) |
| 5176 | if ch.eq_ignore_ascii_case(&'f') |
| 5177 | && self.purpose == ModelPickerPurpose::Session |
| 5178 | && ((key.modifiers == KeyModifiers::SHIFT && self.query.is_empty()) |
| 5179 | || key.modifiers == KeyModifiers::CONTROL) => |
| 5180 | { |
| 5181 | let Some((provider, provider_id, model)) = self.highlighted_route() else { |
| 5182 | return ViewAction::None; |
| 5183 | }; |
| 5184 | ViewAction::Emit(ViewEvent::ModelPickerToggleFleet { |
| 5185 | provider, |
| 5186 | provider_id, |
| 5187 | model, |
| 5188 | }) |
| 5189 | } |
| 5190 | KeyCode::Up if key.modifiers.contains(KeyModifiers::ALT) && self.query.is_empty() => { |
| 5191 | self.emit_pin_move(-1) |
| 5192 | } |
| 5193 | KeyCode::Down if key.modifiers.contains(KeyModifiers::ALT) && self.query.is_empty() => { |
| 5194 | self.emit_pin_move(1) |
| 5195 | } |
| 5196 | // Cycle catalog views (#4115) without shadowing a typed provider |
| 5197 | // name such as `anthropic` or `azure`. |
| 5198 | KeyCode::Char('A') if key.modifiers == KeyModifiers::SHIFT && self.query.is_empty() => { |
| 5199 | self.toggle_view(); |
| 5200 | ViewAction::None |
| 5201 | } |
| 5202 | KeyCode::Char(ch) |
| 5203 | if key.modifiers == KeyModifiers::SHIFT |
| 5204 | && self.query.is_empty() |
| 5205 | && ch.eq_ignore_ascii_case(&'t') => |
| 5206 | { |
| 5207 | self.cycle_provider_filter(); |
| 5208 | ViewAction::None |
| 5209 | } |
| 5210 | KeyCode::Char(ch) |
| 5211 | if self.focus == Pane::Model |
| 5212 | && !key |
| 5213 | .modifiers |
| 5214 | .contains(crossterm::event::KeyModifiers::CONTROL) => |
| 5215 | { |
| 5216 | let mut query = self.query.clone(); |
| 5217 | query.push(ch); |
| 5218 | self.update_query(query); |
| 5219 | ViewAction::None |
| 5220 | } |
| 5221 | KeyCode::Char(ch) |
| 5222 | if self.editing_custom_context() |
| 5223 | && !key |
| 5224 | .modifiers |
| 5225 | .contains(crossterm::event::KeyModifiers::CONTROL) |
| 5226 | && (ch.is_ascii_alphanumeric() || ch == '.' || ch == '_' || ch == ',') => |
| 5227 | { |
| 5228 | self.custom_context_input.push(ch); |
| 5229 | self.custom_context_error = None; |
| 5230 | ViewAction::None |
| 5231 | } |
| 5232 | KeyCode::Backspace |
| 5233 | if self.editing_custom_context() && !self.custom_context_input.is_empty() => |
| 5234 | { |
| 5235 | self.custom_context_input.pop(); |
| 5236 | self.custom_context_error = None; |
| 5237 | ViewAction::None |
| 5238 | } |
| 5239 | KeyCode::Backspace if self.focus == Pane::Model && !self.query.is_empty() => { |
| 5240 | let mut query = self.query.clone(); |
| 5241 | query.pop(); |
| 5242 | self.update_query(query); |
| 5243 | ViewAction::None |
| 5244 | } |
| 5245 | // Explicit readiness + catalog refresh (safe, non-destructive). |
| 5246 | // Plain `r` remains a route-search character. |
| 5247 | KeyCode::Char('r') | KeyCode::Char('R') |
| 5248 | if key.modifiers == crossterm::event::KeyModifiers::CONTROL => |
| 5249 | { |
| 5250 | ViewAction::Emit(ViewEvent::ModelPickerRefresh) |
| 5251 | } |
| 5252 | _ => ViewAction::None, |
| 5253 | } |
| 5254 | } |
| 5255 | |
| 5256 | fn handle_paste(&mut self, text: &str) -> bool { |
| 5257 | if self.editing_custom_context() { |
| 5258 | let text = text.trim(); |
| 5259 | if !text.is_empty() { |
| 5260 | self.custom_context_input |
| 5261 | .push_str(&text.replace(char::is_control, " ")); |
| 5262 | self.custom_context_error = None; |
| 5263 | } |
| 5264 | return true; |
| 5265 | } |
| 5266 | if self.focus == Pane::Model { |
| 5267 | let sanitized = text |
| 5268 | .trim_end_matches(['\r', '\n']) |
| 5269 | .replace("\r\n", "\n") |
| 5270 | .replace(char::is_control, " "); |
| 5271 | if !sanitized.is_empty() { |
| 5272 | let mut query = self.query.clone(); |
| 5273 | query.push_str(&sanitized); |
| 5274 | self.update_query(query); |
| 5275 | } |
| 5276 | return true; |
| 5277 | } |
| 5278 | false |
| 5279 | } |
| 5280 | |
| 5281 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 5282 | let over_catalog = self |
| 5283 | .catalog_action_hitbox |
| 5284 | .borrow() |
| 5285 | .is_some_and(|rect| rect.contains((mouse.column, mouse.row).into())); |
| 5286 | if mouse.kind == MouseEventKind::Moved { |
| 5287 | self.catalog_action_hovered = over_catalog; |
| 5288 | } |
| 5289 | if over_catalog && mouse.kind == MouseEventKind::Down(MouseButton::Left) { |
| 5290 | self.toggle_view(); |
| 5291 | self.catalog_action_hovered = false; |
| 5292 | self.last_mouse_selected = None; |
| 5293 | return ViewAction::None; |
| 5294 | } |
| 5295 | match mouse.kind { |
| 5296 | MouseEventKind::Moved => { |
| 5297 | self.hovered_row = |
| 5298 | self.row_hitboxes |
| 5299 | .borrow() |
| 5300 | .iter() |
| 5301 | .find_map(|(rect, pane, idx)| { |
| 5302 | rect.contains((mouse.column, mouse.row).into()) |
| 5303 | .then_some((*pane, *idx)) |
| 5304 | }); |
| 5305 | ViewAction::None |
| 5306 | } |
| 5307 | MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => { |
| 5308 | self.last_mouse_selected = None; |
| 5309 | self.hovered_row = None; |
| 5310 | let pane = self.pane_hitboxes.borrow().iter().find_map(|(rect, pane)| { |
| 5311 | rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row)) |
| 5312 | .then_some(*pane) |
| 5313 | }); |
| 5314 | let Some(pane) = pane else { |
| 5315 | return ViewAction::None; |
| 5316 | }; |
| 5317 | self.focus = pane; |
| 5318 | if mouse.kind == MouseEventKind::ScrollUp { |
| 5319 | self.move_up(); |
| 5320 | } else { |
| 5321 | self.move_down(); |
| 5322 | } |
| 5323 | ViewAction::None |
| 5324 | } |
| 5325 | MouseEventKind::Down(MouseButton::Left) => { |
| 5326 | let column = self |
| 5327 | .column_hitboxes |
| 5328 | .borrow() |
| 5329 | .iter() |
| 5330 | .find_map(|(rect, column)| { |
| 5331 | rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row)) |
| 5332 | .then_some(*column) |
| 5333 | }); |
| 5334 | if let Some(column) = column { |
| 5335 | // Sorting acts on the Model pane, so the header click |
| 5336 | // moves focus there too — otherwise the next keystroke or |
| 5337 | // wheel event edits the pane that previously had focus. |
| 5338 | self.focus = Pane::Model; |
| 5339 | self.sort_column(column); |
| 5340 | return ViewAction::None; |
| 5341 | } |
| 5342 | let clicked = self |
| 5343 | .row_hitboxes |
| 5344 | .borrow() |
| 5345 | .iter() |
| 5346 | .find_map(|(rect, pane, idx)| { |
| 5347 | rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row)) |
| 5348 | .then_some((*pane, *idx)) |
| 5349 | }); |
| 5350 | let Some((pane, idx)) = clicked else { |
| 5351 | return ViewAction::None; |
| 5352 | }; |
| 5353 | let apply = self.last_mouse_selected == Some((pane, idx)) |
| 5354 | && self.focus == pane |
| 5355 | && match pane { |
| 5356 | Pane::Model => self.selected_model_idx == idx, |
| 5357 | Pane::Effort => self.selected_effort_idx == idx, |
| 5358 | Pane::Context => self.selected_context_idx == idx, |
| 5359 | }; |
| 5360 | self.focus = pane; |
| 5361 | match pane { |
| 5362 | Pane::Model => { |
| 5363 | self.selected_model_idx = idx.min(self.model_row_count().saturating_sub(1)); |
| 5364 | self.select_effort_for_current_model(); |
| 5365 | } |
| 5366 | Pane::Effort => { |
| 5367 | self.selected_effort_idx = |
| 5368 | idx.min(self.current_efforts().len().saturating_sub(1)); |
| 5369 | self.selected_effort_request = self.resolved_effort(); |
| 5370 | } |
| 5371 | Pane::Context => { |
| 5372 | self.selected_context_idx = |
| 5373 | idx.min(CONTEXT_CHOICES.len().saturating_sub(1)); |
| 5374 | self.custom_context_error = None; |
| 5375 | } |
| 5376 | } |
| 5377 | self.last_mouse_selected = Some((pane, idx)); |
| 5378 | if apply && self.selected_model_is_selectable() { |
| 5379 | if self.resolved_context_override_change().is_err() { |
| 5380 | return ViewAction::None; |
| 5381 | } |
| 5382 | ViewAction::EmitAndClose(self.build_apply_event(false)) |
| 5383 | } else if apply { |
| 5384 | self.explain_unselectable_selection() |
| 5385 | } else { |
| 5386 | ViewAction::None |
| 5387 | } |
| 5388 | } |
| 5389 | _ => ViewAction::None, |
| 5390 | } |
| 5391 | } |
| 5392 | |
| 5393 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 5394 | self.render_route(area, buf); |
| 5395 | } |
| 5396 | } |
| 5397 | |
| 5398 | impl ModelPickerView { |
| 5399 | fn render_route(&self, area: Rect, buf: &mut Buffer) { |
| 5400 | self.row_hitboxes.borrow_mut().clear(); |
| 5401 | self.column_hitboxes.borrow_mut().clear(); |
| 5402 | self.pane_hitboxes.borrow_mut().clear(); |
| 5403 | *self.catalog_action_hitbox.borrow_mut() = None; |
| 5404 | let view = self.effective_view(); |
| 5405 | let view_action: std::borrow::Cow<'static, str> = match view { |
| 5406 | ModelListView::Configured => format!( |
| 5407 | "{} ({})", |
| 5408 | tr(self.locale, MessageId::RouteBrowseCatalog), |
| 5409 | self.model_rows |
| 5410 | .iter() |
| 5411 | .filter(|row| row.provider.is_some()) |
| 5412 | .count() |
| 5413 | ) |
| 5414 | .into(), |
| 5415 | other => other.next().title_label().into(), |
| 5416 | }; |
| 5417 | let title = self |
| 5418 | .assignment_context |
| 5419 | .as_ref() |
| 5420 | .map(|(role, _)| { |
| 5421 | format!( |
| 5422 | "{} · {role}", |
| 5423 | tr(self.locale, MessageId::SettingSubjectModel) |
| 5424 | ) |
| 5425 | }) |
| 5426 | .unwrap_or_else(|| { |
| 5427 | tr(self.locale, MessageId::RouteSurfaceTitle).replace("{view}", view.title_label()) |
| 5428 | }); |
| 5429 | let title = match self.provider_filter.as_deref() { |
| 5430 | Some(key) => format!("{title} · {}", provider_filter_label(key)), |
| 5431 | None => title, |
| 5432 | }; |
| 5433 | let accent = active_modal_accent_color(); |
| 5434 | let action_style = if self.catalog_action_hovered { |
| 5435 | menu_style::hovered_row_style().fg(accent) |
| 5436 | } else { |
| 5437 | Style::default().fg(accent).underlined() |
| 5438 | }; |
| 5439 | let mut frame = SurfaceFrame::new(title); |
| 5440 | let title_fits_beside_pill = self.assignment_context.is_none() |
| 5441 | || unicode_width::UnicodeWidthStr::width(frame.title.as_ref()) |
| 5442 | + unicode_width::UnicodeWidthStr::width(view_action.as_ref()) |
| 5443 | + 12 |
| 5444 | <= usize::from(area.width); |
| 5445 | if area.width >= 28 && area.height > 0 && title_fits_beside_pill { |
| 5446 | frame = frame.right_pill(view_action.clone(), action_style); |
| 5447 | } |
| 5448 | let (inner, pill_hitbox) = render_surface_frame(area, buf, frame); |
| 5449 | *self.catalog_action_hitbox.borrow_mut() = pill_hitbox; |
| 5450 | let searching = !self.query.is_empty(); |
| 5451 | let show_advanced_hints = inner.width >= 88 && inner.height >= 24; |
| 5452 | let mut footer_hints = vec![ActionHint::new( |
| 5453 | "↑↓", |
| 5454 | tr(self.locale, MessageId::PickerActionMove), |
| 5455 | )]; |
| 5456 | if self.can_edit_effort() { |
| 5457 | footer_hints.push(ActionHint::new( |
| 5458 | "Tab", |
| 5459 | tr(self.locale, MessageId::PickerActionSwitch), |
| 5460 | )); |
| 5461 | } |
| 5462 | footer_hints.push(ActionHint::new( |
| 5463 | tr(self.locale, MessageId::RouteActionType), |
| 5464 | tr(self.locale, MessageId::RouteActionSearchAnyModel), |
| 5465 | )); |
| 5466 | footer_hints.push(ActionHint::new( |
| 5467 | "Enter", |
| 5468 | tr(self.locale, self.apply_action_id()), |
| 5469 | )); |
| 5470 | if !searching { |
| 5471 | footer_hints.push(ActionHint::new("⇧A", view_action)); |
| 5472 | } |
| 5473 | footer_hints.push(ActionHint::new( |
| 5474 | "Esc", |
| 5475 | tr(self.locale, MessageId::PickerActionCancel), |
| 5476 | )); |
| 5477 | let content = render_modal_footer(inner, buf, &footer_hints); |
| 5478 | |
| 5479 | self.ensure_projection(); |
| 5480 | let total_models = self |
| 5481 | .model_rows |
| 5482 | .iter() |
| 5483 | .filter(|row| row.provider.is_some()) |
| 5484 | .count(); |
| 5485 | let visible_count = self |
| 5486 | .projection |
| 5487 | .borrow() |
| 5488 | .as_ref() |
| 5489 | .map_or(0, |p| p.rows.len()); |
| 5490 | |
| 5491 | let show_rule = content.height >= 10; |
| 5492 | let show_filter_bar = content.height >= 6; |
| 5493 | let top_rows = 1 + u16::from(show_filter_bar) + u16::from(show_rule); |
| 5494 | let shell = ratatui::layout::Layout::default() |
| 5495 | .direction(ratatui::layout::Direction::Vertical) |
| 5496 | .constraints([ |
| 5497 | ratatui::layout::Constraint::Length(top_rows), |
| 5498 | ratatui::layout::Constraint::Min(1), |
| 5499 | ]) |
| 5500 | .split(content); |
| 5501 | let top = shell[0]; |
| 5502 | let provider_label = self |
| 5503 | .resolved_admitted_identity() |
| 5504 | .as_ref() |
| 5505 | .or(self.initial_identity.as_ref()) |
| 5506 | .map_or("unavailable", |identity| { |
| 5507 | identity |
| 5508 | .compatibility() |
| 5509 | .map_or(identity.key.as_str(), |row| row.label) |
| 5510 | }) |
| 5511 | .to_string(); |
| 5512 | let blocked_suffix = self |
| 5513 | .visible_model_rows() |
| 5514 | .get(self.selected_model_idx) |
| 5515 | .and_then(|row| row.blocked_reason.as_deref()) |
| 5516 | .map(|reason| format!(" · ! {reason}")) |
| 5517 | .unwrap_or_default(); |
| 5518 | let status_row = Rect { height: 1, ..top }; |
| 5519 | Paragraph::new(Line::from(vec![ |
| 5520 | Span::styled( |
| 5521 | self.assignment_context |
| 5522 | .as_ref() |
| 5523 | .map(|(_, scope)| format!("{scope} · ")) |
| 5524 | .unwrap_or_else(|| { |
| 5525 | format!("{} ", tr(self.locale, MessageId::RouteProviderLabel)) |
| 5526 | }), |
| 5527 | Style::default().fg(palette::TEXT_MUTED), |
| 5528 | ), |
| 5529 | Span::styled( |
| 5530 | provider_label, |
| 5531 | Style::default().fg(palette::TEXT_PRIMARY).bold(), |
| 5532 | ), |
| 5533 | Span::styled(blocked_suffix, Style::default().fg(palette::STATUS_WARNING)), |
| 5534 | Span::styled( |
| 5535 | self.notice |
| 5536 | .as_ref() |
| 5537 | .map(|(text, _)| format!(" · {text}")) |
| 5538 | .unwrap_or_default(), |
| 5539 | self.notice |
| 5540 | .as_ref() |
| 5541 | .map(|(_, level)| palette::chrome_style(&self.theme, level.ink())) |
| 5542 | .unwrap_or_default(), |
| 5543 | ), |
| 5544 | Span::styled( |
| 5545 | if self.assignment_context.is_some() { |
| 5546 | "" |
| 5547 | } else { |
| 5548 | catalog_freshness_title_suffix() |
| 5549 | }, |
| 5550 | Style::default().fg(palette::TEXT_MUTED), |
| 5551 | ), |
| 5552 | ])) |
| 5553 | .render(status_row, buf); |
| 5554 | |
| 5555 | if show_filter_bar && top.height >= 2 { |
| 5556 | let filter_row = Rect { |
| 5557 | y: top.y.saturating_add(1), |
| 5558 | height: 1, |
| 5559 | ..top |
| 5560 | }; |
| 5561 | let ascii = crate::tui::color_compat::ascii_safe_enabled(); |
| 5562 | let caret = if ascii { "_" } else { "▏" }; |
| 5563 | let count_text = format!("{visible_count}/{total_models}"); |
| 5564 | let mut filter_spans = if searching { |
| 5565 | vec![ |
| 5566 | Span::styled( |
| 5567 | tr(self.locale, MessageId::HelpFilterPrefix), |
| 5568 | Style::default().fg(accent).bold(), |
| 5569 | ), |
| 5570 | Span::styled( |
| 5571 | self.query.clone(), |
| 5572 | Style::default().fg(palette::TEXT_PRIMARY).bold(), |
| 5573 | ), |
| 5574 | Span::styled(caret, Style::default().fg(accent)), |
| 5575 | ] |
| 5576 | } else { |
| 5577 | vec![ |
| 5578 | Span::styled("/ ", Style::default().fg(palette::TEXT_DIM)), |
| 5579 | Span::styled( |
| 5580 | tr(self.locale, MessageId::ModelPickerFilterPlaceholder), |
| 5581 | Style::default().fg(palette::TEXT_DIM), |
| 5582 | ), |
| 5583 | ] |
| 5584 | }; |
| 5585 | filter_spans.push(Span::styled( |
| 5586 | format!(" ({count_text})"), |
| 5587 | Style::default().fg(palette::TEXT_MUTED), |
| 5588 | )); |
| 5589 | Paragraph::new(Line::from(filter_spans)).render(filter_row, buf); |
| 5590 | } |
| 5591 | if show_rule && top.height >= top_rows { |
| 5592 | render_modal_rule( |
| 5593 | Rect { |
| 5594 | y: top.y.saturating_add(top_rows.saturating_sub(1)), |
| 5595 | height: 1, |
| 5596 | ..top |
| 5597 | }, |
| 5598 | buf, |
| 5599 | ); |
| 5600 | } |
| 5601 | |
| 5602 | let mut layout = widen_model_pane(ListDetailLayout::split(shell[1], 24)); |
| 5603 | if !self.can_edit_effort() { |
| 5604 | layout.list = shell[1]; |
| 5605 | } else if layout.stacked && shell[1].height < 12 { |
| 5606 | let model_height = if self.focus == Pane::Model { |
| 5607 | shell[1].height.saturating_sub(1) |
| 5608 | } else { |
| 5609 | u16::from(shell[1].height > 0) |
| 5610 | }; |
| 5611 | layout.list = Rect::new(shell[1].x, shell[1].y, shell[1].width, model_height); |
| 5612 | layout.detail = Rect::new( |
| 5613 | shell[1].x, |
| 5614 | shell[1].y + model_height, |
| 5615 | shell[1].width, |
| 5616 | shell[1].height.saturating_sub(model_height), |
| 5617 | ); |
| 5618 | } |
| 5619 | |
| 5620 | let projection = self.projection.borrow(); |
| 5621 | let model_rows = &projection.as_ref().unwrap().rows; |
| 5622 | let model_title = if self.query.trim().is_empty() { |
| 5623 | format!("Model · {}", self.effective_view().title_label()) |
| 5624 | } else { |
| 5625 | format!("Model: {}", self.query.trim()) |
| 5626 | }; |
| 5627 | self.render_pane( |
| 5628 | layout.list, |
| 5629 | buf, |
| 5630 | &model_title, |
| 5631 | model_rows, |
| 5632 | PaneRenderState { |
| 5633 | pane: Pane::Model, |
| 5634 | selected: self.selected_model_idx, |
| 5635 | focused: self.focus == Pane::Model, |
| 5636 | }, |
| 5637 | ); |
| 5638 | |
| 5639 | if !self.can_edit_effort() { |
| 5640 | return; |
| 5641 | } |
| 5642 | if !layout.stacked && layout.detail.x > layout.list.right() { |
| 5643 | let div_x = layout.list.right(); |
| 5644 | let div_sym = if crate::tui::color_compat::ascii_safe_enabled() { |
| 5645 | "|" |
| 5646 | } else { |
| 5647 | "│" |
| 5648 | }; |
| 5649 | let div_style = Style::default().fg(active_modal_border_color()); |
| 5650 | for y in shell[1].top()..shell[1].bottom() { |
| 5651 | buf[(div_x, y)].set_symbol(div_sym).set_style(div_style); |
| 5652 | } |
| 5653 | } |
| 5654 | let effort_provider = self.resolved_provider().unwrap_or(self.initial_provider); |
| 5655 | let current_efforts = self.current_efforts(); |
| 5656 | let selected_effort_idx = self |
| 5657 | .selected_effort_idx |
| 5658 | .min(current_efforts.len().saturating_sub(1)); |
| 5659 | let effort_rows: Vec<PaneRow> = current_efforts |
| 5660 | .iter() |
| 5661 | .map(|effort| { |
| 5662 | let label = effort |
| 5663 | .display_label_for_provider(effort_provider) |
| 5664 | .to_string(); |
| 5665 | let hint = match effort { |
| 5666 | ReasoningEffort::Auto => "choose per turn".to_string(), |
| 5667 | ReasoningEffort::Off => "no extra reasoning".to_string(), |
| 5668 | ReasoningEffort::Minimal => "minimal reasoning".to_string(), |
| 5669 | ReasoningEffort::Low => "lighter reasoning".to_string(), |
| 5670 | ReasoningEffort::Medium => "balanced reasoning".to_string(), |
| 5671 | ReasoningEffort::High => "deeper reasoning".to_string(), |
| 5672 | ReasoningEffort::XHigh => "extra-high reasoning".to_string(), |
| 5673 | ReasoningEffort::Ultra => "ultra reasoning".to_string(), |
| 5674 | ReasoningEffort::Max => "maximum reasoning".to_string(), |
| 5675 | }; |
| 5676 | PaneRow::effort(label, hint) |
| 5677 | }) |
| 5678 | .collect(); |
| 5679 | let detail_pane = if show_advanced_hints && layout.detail.height >= 4 { |
| 5680 | let sep = if crate::tui::color_compat::ascii_safe_enabled() { |
| 5681 | " - " |
| 5682 | } else { |
| 5683 | " · " |
| 5684 | }; |
| 5685 | let mut parts = Vec::new(); |
| 5686 | if !searching { |
| 5687 | parts.push(match self.provider_filter.as_deref() { |
| 5688 | Some(filter) => format!( |
| 5689 | "⇧T {}: {}", |
| 5690 | tr(self.locale, MessageId::RouteProviderLabel), |
| 5691 | provider_filter_label(filter) |
| 5692 | ), |
| 5693 | None => format!("⇧T {}", tr(self.locale, MessageId::RouteProviderLabel)), |
| 5694 | }); |
| 5695 | } |
| 5696 | parts.push(format!( |
| 5697 | "Ctrl+S {}", |
| 5698 | tr(self.locale, MessageId::SessionsActionSort) |
| 5699 | )); |
| 5700 | if self.purpose == ModelPickerPurpose::Session && !searching { |
| 5701 | parts.push(format!( |
| 5702 | "⇧D {}", |
| 5703 | tr(self.locale, MessageId::PickerActionSetStartupDefault) |
| 5704 | )); |
| 5705 | } |
| 5706 | if self.highlighted_route().is_some() { |
| 5707 | let (fleet_key, pin_key) = if searching { |
| 5708 | ("Ctrl+F", "Ctrl+P") |
| 5709 | } else { |
| 5710 | ("⇧F", "⇧P") |
| 5711 | }; |
| 5712 | if self.purpose == ModelPickerPurpose::Session { |
| 5713 | parts.push(format!( |
| 5714 | "{fleet_key} {}", |
| 5715 | tr(self.locale, MessageId::PickerActionFleet) |
| 5716 | )); |
| 5717 | } |
| 5718 | parts.push(format!( |
| 5719 | "{pin_key} {}", |
| 5720 | tr(self.locale, MessageId::PickerActionPin) |
| 5721 | )); |
| 5722 | } |
| 5723 | let hint_paragraph = Paragraph::new(Line::from(Span::styled( |
| 5724 | parts.join(sep), |
| 5725 | Style::default().fg(palette::TEXT_DIM), |
| 5726 | ))) |
| 5727 | .wrap(ratatui::widgets::Wrap { trim: true }); |
| 5728 | let max_hint_height = layout.detail.height.saturating_sub(3).min(4); |
| 5729 | let hint_height = u16::try_from(hint_paragraph.line_count(layout.detail.width.max(1))) |
| 5730 | .unwrap_or(max_hint_height) |
| 5731 | .clamp(1, max_hint_height.max(1)); |
| 5732 | if layout.detail.height >= hint_height.saturating_add(2) { |
| 5733 | let body_height = layout.detail.height.saturating_sub(hint_height); |
| 5734 | let hint_area = Rect::new( |
| 5735 | layout.detail.x, |
| 5736 | layout.detail.y.saturating_add(body_height), |
| 5737 | layout.detail.width, |
| 5738 | hint_height, |
| 5739 | ); |
| 5740 | hint_paragraph.render(hint_area, buf); |
| 5741 | Rect { |
| 5742 | height: body_height, |
| 5743 | ..layout.detail |
| 5744 | } |
| 5745 | } else { |
| 5746 | layout.detail |
| 5747 | } |
| 5748 | } else { |
| 5749 | layout.detail |
| 5750 | }; |
| 5751 | if self.can_edit_context() && detail_pane.height >= 10 { |
| 5752 | let effort_height = (effort_rows.len() as u16) |
| 5753 | .saturating_add(2) |
| 5754 | .min(detail_pane.height.saturating_sub(6)) |
| 5755 | .max(3); |
| 5756 | let thinking_area = Rect { |
| 5757 | height: effort_height, |
| 5758 | ..detail_pane |
| 5759 | }; |
| 5760 | let context_area = Rect { |
| 5761 | y: detail_pane.y.saturating_add(effort_height), |
| 5762 | height: detail_pane.height.saturating_sub(effort_height), |
| 5763 | ..detail_pane |
| 5764 | }; |
| 5765 | self.render_pane( |
| 5766 | thinking_area, |
| 5767 | buf, |
| 5768 | "Thinking", |
| 5769 | &effort_rows, |
| 5770 | PaneRenderState { |
| 5771 | pane: Pane::Effort, |
| 5772 | selected: selected_effort_idx, |
| 5773 | focused: self.focus == Pane::Effort, |
| 5774 | }, |
| 5775 | ); |
| 5776 | self.render_context_pane(context_area, buf); |
| 5777 | } else if self.can_edit_context() && self.focus == Pane::Context { |
| 5778 | self.render_context_pane(detail_pane, buf); |
| 5779 | } else { |
| 5780 | self.render_pane( |
| 5781 | detail_pane, |
| 5782 | buf, |
| 5783 | "Thinking", |
| 5784 | &effort_rows, |
| 5785 | PaneRenderState { |
| 5786 | pane: Pane::Effort, |
| 5787 | selected: selected_effort_idx, |
| 5788 | focused: self.focus == Pane::Effort, |
| 5789 | }, |
| 5790 | ); |
| 5791 | } |
| 5792 | } |
| 5793 | |
| 5794 | fn render_context_pane(&self, area: Rect, buf: &mut Buffer) { |
| 5795 | if area.height < 3 || area.width < 12 { |
| 5796 | return; |
| 5797 | } |
| 5798 | let focused = self.focus == Pane::Context; |
| 5799 | let selected_idx = self |
| 5800 | .selected_context_idx |
| 5801 | .min(CONTEXT_CHOICES.len().saturating_sub(1)); |
| 5802 | let warning_text = self |
| 5803 | .custom_context_error |
| 5804 | .as_deref() |
| 5805 | .unwrap_or(CONTEXT_WARNING_LINE); |
| 5806 | let warning_style = if self.custom_context_error.is_some() { |
| 5807 | Style::default().fg(palette::STATUS_ERROR) |
| 5808 | } else { |
| 5809 | Style::default().fg(palette::TEXT_DIM) |
| 5810 | }; |
| 5811 | let warning_para = Paragraph::new(Line::from(Span::styled(warning_text, warning_style))) |
| 5812 | .wrap(ratatui::widgets::Wrap { trim: true }); |
| 5813 | let max_warn_height = area.height.saturating_sub(3).min(3); |
| 5814 | let warn_height = u16::try_from(warning_para.line_count(area.width.max(1))) |
| 5815 | .unwrap_or(max_warn_height) |
| 5816 | .clamp(1, max_warn_height.max(1)); |
| 5817 | let pane_height = area.height.saturating_sub(warn_height); |
| 5818 | let pane_area = Rect { |
| 5819 | height: pane_height, |
| 5820 | ..area |
| 5821 | }; |
| 5822 | let warn_area = Rect { |
| 5823 | y: area.y.saturating_add(pane_height), |
| 5824 | height: warn_height, |
| 5825 | ..area |
| 5826 | }; |
| 5827 | let rows: Vec<PaneRow> = CONTEXT_CHOICES |
| 5828 | .iter() |
| 5829 | .map(|choice| match choice { |
| 5830 | ContextChoice::Auto => { |
| 5831 | PaneRow::effort("auto".to_string(), "catalog/provider limit".to_string()) |
| 5832 | } |
| 5833 | ContextChoice::Tokens(tokens) => PaneRow::effort( |
| 5834 | format_context_window(u64::from(*tokens)), |
| 5835 | format!("{tokens} tokens"), |
| 5836 | ), |
| 5837 | ContextChoice::Custom => { |
| 5838 | let label = if self.custom_context_input.is_empty() { |
| 5839 | "custom".to_string() |
| 5840 | } else { |
| 5841 | format!("custom [{}]", self.custom_context_input) |
| 5842 | }; |
| 5843 | PaneRow::effort(label, "type e.g. 272k, 1m".to_string()) |
| 5844 | } |
| 5845 | }) |
| 5846 | .collect(); |
| 5847 | self.render_pane( |
| 5848 | pane_area, |
| 5849 | buf, |
| 5850 | "Context", |
| 5851 | &rows, |
| 5852 | PaneRenderState { |
| 5853 | pane: Pane::Context, |
| 5854 | selected: selected_idx, |
| 5855 | focused, |
| 5856 | }, |
| 5857 | ); |
| 5858 | warning_para.render(warn_area, buf); |
| 5859 | } |
| 5860 | } |
| 5861 | |
| 5862 | /// Rows one PageUp/PageDown travels. Pages clamp at the ends per the shared |
| 5863 | /// vocabulary instead of wrapping (#6290). |
| 5864 | const MODEL_PAGE: usize = 5; |
| 5865 | |
| 5866 | /// Previous index in a list that rotates: 0 wraps to the last row. |
| 5867 | /// `count` must be non-zero. |
| 5868 | fn wrapping_prev(index: usize, count: usize) -> usize { |
| 5869 | if index == 0 { |
| 5870 | count - 1 |
| 5871 | } else { |
| 5872 | (index - 1).min(count - 1) |
| 5873 | } |
| 5874 | } |
| 5875 | |
| 5876 | /// Next index in a list that rotates: the last row wraps to 0. |
| 5877 | /// `count` must be non-zero. |
| 5878 | fn wrapping_next(index: usize, count: usize) -> usize { |
| 5879 | if index + 1 >= count { 0 } else { index + 1 } |
| 5880 | } |
| 5881 | |
| 5882 | pub(crate) fn picker_efforts_for_route( |
| 5883 | provider: ProviderKind, |
| 5884 | base_url: &str, |
| 5885 | wire_model: &str, |
| 5886 | model_is_auto: bool, |
| 5887 | ) -> Vec<ReasoningEffort> { |
| 5888 | if model_is_auto { |
| 5889 | return AUTO_MODEL_PICKER_EFFORTS.to_vec(); |
| 5890 | } |
| 5891 | distinct_effective_efforts( |
| 5892 | route_picker_efforts(provider, base_url, wire_model), |
| 5893 | provider, |
| 5894 | base_url, |
| 5895 | wire_model, |
| 5896 | ) |
| 5897 | } |
| 5898 | |
| 5899 | /// The tier a concrete route receives for `effort`: the route-constrained |
| 5900 | /// receipt tier when the route's dialect is narrower than the generic |
| 5901 | /// normalization (Z.ai GLM, Kimi Code K3), otherwise |
| 5902 | /// [`ReasoningEffort::normalize_for_route`]. This is the effective tier the |
| 5903 | /// effort status line and Work receipts report, so the ladder and the cycler |
| 5904 | /// dedupe against the same value the operator sees. |
| 5905 | pub(crate) fn effective_tier_for_route( |
| 5906 | effort: ReasoningEffort, |
| 5907 | provider: ProviderKind, |
| 5908 | base_url: &str, |
| 5909 | wire_model: &str, |
| 5910 | ) -> ReasoningEffort { |
| 5911 | match codewhale_engine::work_graph::constrained_effective_reasoning_for_route( |
| 5912 | effort.into(), |
| 5913 | provider, |
| 5914 | base_url, |
| 5915 | wire_model, |
| 5916 | ) |
| 5917 | .map(codewhale_engine::reasoning_preference::EffectiveReasoningEffort::from) |
| 5918 | { |
| 5919 | Some(codewhale_engine::reasoning_preference::EffectiveReasoningEffort::Tier(tier)) => tier, |
| 5920 | _ => effort.normalize_for_route(provider, base_url, wire_model), |
| 5921 | } |
| 5922 | } |
| 5923 | |
| 5924 | /// Drop rungs that resolve to the same effective tier as another rung on the |
| 5925 | /// route (#6650). The picker and the Ctrl+T cycler walk this ladder, so a rung |
| 5926 | /// whose effective tier is already offered would be a row that changes |
| 5927 | /// nothing and a key press that does nothing — DeepSeek's `medium` lands on |
| 5928 | /// `high`, Z.ai GLM-5.2's `low` lands on `high`, an always-thinking route's |
| 5929 | /// `off` lands on its lowest tier, and a catalog `thinking: disabled` value |
| 5930 | /// the effort dialect cannot express lands on the catalog default. When two |
| 5931 | /// rungs collide, the one whose own value is the effective tier wins, so the |
| 5932 | /// row names what the route will receive. `Auto` always stays: it is the |
| 5933 | /// "leave it to the route" preference, not a tier, and is displayed as its |
| 5934 | /// own state. Routes whose effective tier cannot be proven (a custom endpoint, |
| 5935 | /// an enabled-but-untiered toggle) keep their rows. |
| 5936 | fn distinct_effective_efforts( |
| 5937 | efforts: Vec<ReasoningEffort>, |
| 5938 | provider: ProviderKind, |
| 5939 | base_url: &str, |
| 5940 | wire_model: &str, |
| 5941 | ) -> Vec<ReasoningEffort> { |
| 5942 | let effective = |
| 5943 | |effort: ReasoningEffort| effective_tier_for_route(effort, provider, base_url, wire_model); |
| 5944 | let mut seen = Vec::with_capacity(efforts.len()); |
| 5945 | let mut distinct = Vec::with_capacity(efforts.len()); |
| 5946 | for &effort in &efforts { |
| 5947 | if effort == ReasoningEffort::Auto { |
| 5948 | distinct.push(effort); |
| 5949 | continue; |
| 5950 | } |
| 5951 | let tier = effective(effort); |
| 5952 | if (tier != effort && efforts.contains(&tier)) || seen.contains(&tier) { |
| 5953 | continue; |
| 5954 | } |
| 5955 | seen.push(tier); |
| 5956 | distinct.push(effort); |
| 5957 | } |
| 5958 | distinct |
| 5959 | } |
| 5960 | |
| 5961 | fn route_picker_efforts( |
| 5962 | provider: ProviderKind, |
| 5963 | base_url: &str, |
| 5964 | wire_model: &str, |
| 5965 | ) -> Vec<ReasoningEffort> { |
| 5966 | // Exact-route overrides still win over catalog metadata: Kimi Code K3 and |
| 5967 | // OpenAI Codex have wire dialects the generic Models.dev shape does not |
| 5968 | // fully describe. |
| 5969 | if codewhale_runtime::config::is_exact_kimi_code_k3_route(provider, base_url, wire_model) { |
| 5970 | return KIMI_CODE_K3_PICKER_EFFORTS.to_vec(); |
| 5971 | } |
| 5972 | if provider == ProviderKind::OpenaiCodex { |
| 5973 | // Per-account tier metadata is reachable only through |
| 5974 | // `codex_model_cache::model_roster_for(config)`: the roster snapshot is |
| 5975 | // keyed by the signed-in registration, so this signature-only helper |
| 5976 | // cannot read it and keeps the conservative wire ladder. The roster |
| 5977 | // does carry tiers when the account publishes them (#6396). |
| 5978 | return CODEX_PICKER_EFFORTS.to_vec(); |
| 5979 | } |
| 5980 | if provider == ProviderKind::OllamaCloud { |
| 5981 | return OLLAMA_CLOUD_PICKER_EFFORTS.to_vec(); |
| 5982 | } |
| 5983 | if provider == ProviderKind::Vllm |
| 5984 | && let Some(spec) = codewhale_config::local_reasoning::local_reasoning_spec(wire_model) |
| 5985 | { |
| 5986 | return std::iter::once(ReasoningEffort::Auto) |
| 5987 | .chain( |
| 5988 | spec.tiers |
| 5989 | .iter() |
| 5990 | .filter_map(|tier| ReasoningEffort::from_catalog_token(tier)), |
| 5991 | ) |
| 5992 | .collect(); |
| 5993 | } |
| 5994 | if let Some(offering) = ReasoningEffort::offering_for_reasoning(provider, base_url, wire_model) |
| 5995 | && let Some(catalog_efforts) = catalog_picker_efforts(&offering) |
| 5996 | { |
| 5997 | return catalog_efforts; |
| 5998 | } |
| 5999 | // A route that states the model has no reasoning gets no tier rows (#6396). |
| 6000 | // An unstated fact keeps the provider ladder: a tier is a wire dialect, and |
| 6001 | // unknown support is not the same claim as no support. |
| 6002 | if ReasoningEffort::offering_for_reasoning(provider, base_url, wire_model) |
| 6003 | .is_some_and(|offering| offering.reasoning == Some(false)) |
| 6004 | { |
| 6005 | return vec![ReasoningEffort::Auto]; |
| 6006 | } |
| 6007 | if matches!(provider, codewhale_config::ProviderKind::Deepseek) { |
| 6008 | return DEEPSEEK_PICKER_EFFORTS.to_vec(); |
| 6009 | } |
| 6010 | DEFAULT_PICKER_EFFORTS.to_vec() |
| 6011 | } |
| 6012 | |
| 6013 | /// Build thinking-tier rows from Models.dev `reasoning_options` when present. |
| 6014 | /// |
| 6015 | /// Expected shape (already parsed onto the catalog offering): |
| 6016 | /// `[{ "type": "effort", "values": ["high", "max"] }]`. |
| 6017 | /// Non-effort option types (e.g. MiniMax `thinking`) are mapped when their |
| 6018 | /// values collapse cleanly onto our tier vocabulary; unknown values are |
| 6019 | /// skipped. Returns `None` when the catalog has no usable effort list so the |
| 6020 | /// caller can keep the provider default rather than inventing tiers. |
| 6021 | fn catalog_picker_efforts( |
| 6022 | offering: &codewhale_config::catalog::CatalogOffering, |
| 6023 | ) -> Option<Vec<ReasoningEffort>> { |
| 6024 | if let Some(mut efforts) = ReasoningEffort::catalog_effort_values_for_offering(offering) { |
| 6025 | if !efforts.contains(&ReasoningEffort::Auto) { |
| 6026 | efforts.insert(0, ReasoningEffort::Auto); |
| 6027 | } |
| 6028 | return Some(efforts); |
| 6029 | } |
| 6030 | |
| 6031 | let mut efforts = Vec::new(); |
| 6032 | let mut has_toggle = false; |
| 6033 | for option in &offering.reasoning_options { |
| 6034 | let Some(option_type) = option.get("type").and_then(|value| value.as_str()) else { |
| 6035 | continue; |
| 6036 | }; |
| 6037 | if option_type.eq_ignore_ascii_case("toggle") { |
| 6038 | has_toggle = true; |
| 6039 | continue; |
| 6040 | } |
| 6041 | if !option_type.eq_ignore_ascii_case("thinking") { |
| 6042 | continue; |
| 6043 | } |
| 6044 | let Some(values) = option.get("values").and_then(|value| value.as_array()) else { |
| 6045 | continue; |
| 6046 | }; |
| 6047 | for value in values { |
| 6048 | let Some(raw) = value.as_str() else { |
| 6049 | continue; |
| 6050 | }; |
| 6051 | let effort = match raw.trim().to_ascii_lowercase().as_str() { |
| 6052 | "always_on" | "always-on" => Some(ReasoningEffort::Max), |
| 6053 | _ => ReasoningEffort::from_catalog_token(raw), |
| 6054 | }; |
| 6055 | if let Some(effort) = effort |
| 6056 | && !efforts.contains(&effort) |
| 6057 | { |
| 6058 | efforts.push(effort); |
| 6059 | } |
| 6060 | } |
| 6061 | } |
| 6062 | if efforts.is_empty() { |
| 6063 | return None; |
| 6064 | } |
| 6065 | if has_toggle && !efforts.contains(&ReasoningEffort::Off) { |
| 6066 | efforts.insert(0, ReasoningEffort::Off); |
| 6067 | } |
| 6068 | if !efforts.contains(&ReasoningEffort::Auto) { |
| 6069 | efforts.insert(0, ReasoningEffort::Auto); |
| 6070 | } |
| 6071 | Some(efforts) |
| 6072 | } |
| 6073 | |
| 6074 | fn normalize_picker_effort( |
| 6075 | effort: ReasoningEffort, |
| 6076 | provider: ProviderKind, |
| 6077 | base_url: &str, |
| 6078 | wire_model: &str, |
| 6079 | model_is_auto: bool, |
| 6080 | ) -> ReasoningEffort { |
| 6081 | let normalized = if model_is_auto { |
| 6082 | effort |
| 6083 | } else { |
| 6084 | effort.normalize_for_route(provider, base_url, wire_model) |
| 6085 | }; |
| 6086 | let efforts = picker_efforts_for_route(provider, base_url, wire_model, model_is_auto); |
| 6087 | if efforts.contains(&normalized) { |
| 6088 | return normalized; |
| 6089 | } |
| 6090 | // Catalog-driven lists may keep Low/Medium that route normalization would |
| 6091 | // otherwise collapse. Prefer the operator's exact choice when the picker |
| 6092 | // still shows it. |
| 6093 | if efforts.contains(&effort) { |
| 6094 | return effort; |
| 6095 | } |
| 6096 | default_picker_effort(provider, &efforts) |
| 6097 | } |
| 6098 | |
| 6099 | fn default_picker_effort(provider: ProviderKind, efforts: &[ReasoningEffort]) -> ReasoningEffort { |
| 6100 | let preferred = if provider == ProviderKind::OpenaiCodex { |
| 6101 | ReasoningEffort::Medium |
| 6102 | } else { |
| 6103 | ReasoningEffort::High |
| 6104 | }; |
| 6105 | if efforts.contains(&preferred) { |
| 6106 | preferred |
| 6107 | } else { |
| 6108 | efforts |
| 6109 | .iter() |
| 6110 | .copied() |
| 6111 | .find(|effort| *effort != ReasoningEffort::Auto && *effort != ReasoningEffort::Off) |
| 6112 | .or_else(|| efforts.first().copied()) |
| 6113 | .unwrap_or(preferred) |
| 6114 | } |
| 6115 | } |
| 6116 | |
| 6117 | fn default_picker_effort_idx( |
| 6118 | provider: ProviderKind, |
| 6119 | base_url: &str, |
| 6120 | wire_model: &str, |
| 6121 | model_is_auto: bool, |
| 6122 | ) -> usize { |
| 6123 | let efforts = picker_efforts_for_route(provider, base_url, wire_model, model_is_auto); |
| 6124 | let default_effort = default_picker_effort(provider, &efforts); |
| 6125 | efforts |
| 6126 | .iter() |
| 6127 | .position(|effort| *effort == default_effort) |
| 6128 | .unwrap_or(0) |
| 6129 | } |
| 6130 | |
| 6131 | #[cfg(test)] |
| 6132 | mod tests { |
| 6133 | use super::*; |
| 6134 | use codewhale_config::catalog::CatalogRefreshError; |
| 6135 | |
| 6136 | #[test] |
| 6137 | fn picker_ladder_drops_rungs_that_resolve_to_an_offered_tier() { |
| 6138 | use ReasoningEffort::*; |
| 6139 | // DeepSeek collapses minimal/medium/xhigh/ultra onto low/high/max, so |
| 6140 | // a catalog that published every spelling still shows one row per |
| 6141 | // wire tier (#6650). |
| 6142 | assert_eq!( |
| 6143 | distinct_effective_efforts( |
| 6144 | vec![Auto, Off, Minimal, Low, Medium, High, XHigh, Ultra, Max], |
| 6145 | ProviderKind::Deepseek, |
| 6146 | codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL, |
| 6147 | "deepseek-v4.1-flash", |
| 6148 | ), |
| 6149 | vec![Auto, Off, Low, High, Max] |
| 6150 | ); |
| 6151 | // When the alias comes first, the rung that names the tier still wins. |
| 6152 | assert_eq!( |
| 6153 | distinct_effective_efforts( |
| 6154 | vec![Auto, Medium, High, Max], |
| 6155 | ProviderKind::Deepseek, |
| 6156 | codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL, |
| 6157 | "deepseek-v4.1-flash", |
| 6158 | ), |
| 6159 | vec![Auto, High, Max] |
| 6160 | ); |
| 6161 | } |
| 6162 | |
| 6163 | #[test] |
| 6164 | fn configured_model_picker_and_runtime_share_exact_persisted_metadata() { |
| 6165 | let _env = crate::test_support::lock_test_env(); |
| 6166 | let _catalog = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 6167 | let mut config: Config = toml::from_str(include_str!( |
| 6168 | "../../../config/tests/fixtures/custom_models.toml" |
| 6169 | )) |
| 6170 | .unwrap(); |
| 6171 | let id = "deepseek-v4.1-flash-expires-on-0910"; |
| 6172 | let base = "https://models.example.test/v1"; |
| 6173 | let metadata = effective_picker_metadata(&config, Some(ProviderKind::Deepseek), id); |
| 6174 | assert_eq!(metadata.display_name.as_deref(), Some("Temporary preview")); |
| 6175 | assert_eq!(metadata.context_window, Some(96000)); |
| 6176 | assert_eq!(metadata.max_output, Some(8000)); |
| 6177 | assert_eq!(metadata.tool_calls, Some(true)); |
| 6178 | assert_eq!(metadata.source, Some(CatalogSource::ConfigOverride)); |
| 6179 | let mut row = model_row(ProviderKind::Deepseek, true); |
| 6180 | row.id = id.into(); |
| 6181 | row.metadata = metadata.clone(); |
| 6182 | let chips = model_row_meta_chips(&row); |
| 6183 | assert_eq!(chips[0], "user declared (unverified)"); |
| 6184 | assert!(chips.iter().any(|chip| chip.starts_with("estimate "))); |
| 6185 | assert!(fit_meta_chips(&chips, 30).starts_with("user declared")); |
| 6186 | assert!( |
| 6187 | render_picker_model_hint(id, Some(ProviderKind::Deepseek), &metadata, None, None) |
| 6188 | .contains("user declared") |
| 6189 | ); |
| 6190 | assert!( |
| 6191 | codewhale_engine::provider_lake::configured_catalog_models_for_route( |
| 6192 | &config, |
| 6193 | ProviderKind::Deepseek, |
| 6194 | "deepseek", |
| 6195 | base |
| 6196 | ) |
| 6197 | .iter() |
| 6198 | .any(|model| model == id) |
| 6199 | ); |
| 6200 | let route = codewhale_engine::route_runtime::resolve_runtime_route( |
| 6201 | &config, |
| 6202 | ProviderKind::Deepseek, |
| 6203 | Some(id), |
| 6204 | ) |
| 6205 | .unwrap(); |
| 6206 | assert_eq!(route.model, id); |
| 6207 | assert_eq!(Some(route.context_window.tokens), metadata.context_window); |
| 6208 | assert_eq!( |
| 6209 | route.context_window.source, |
| 6210 | codewhale_engine::route_runtime::ContextWindowSource::UserDeclared |
| 6211 | ); |
| 6212 | assert!(!route.context_window.source.is_verified()); |
| 6213 | assert_eq!( |
| 6214 | route.candidate.capabilities().image_input, |
| 6215 | SupportState::Unknown |
| 6216 | ); |
| 6217 | assert_eq!( |
| 6218 | route.candidate.capabilities().native_tool_calls, |
| 6219 | SupportState::Unknown |
| 6220 | ); |
| 6221 | assert_eq!( |
| 6222 | codewhale_engine::route_budget::route_output_limit_tokens(Some( |
| 6223 | route.candidate.limits() |
| 6224 | )), |
| 6225 | metadata.max_output |
| 6226 | ); |
| 6227 | assert_eq!(input_price_per_million(&row), Some(0.4)); |
| 6228 | let mut cny_row = row.clone(); |
| 6229 | config.custom_models.as_mut().unwrap()[0].cost_currency = Some("CNY".into()); |
| 6230 | cny_row.metadata = effective_picker_metadata(&config, Some(ProviderKind::Deepseek), id); |
| 6231 | assert_eq!(input_price_per_million(&cny_row), None); |
| 6232 | assert_eq!(cny_row.metadata.pricing, PickerPricing::Unknown); |
| 6233 | cny_row.id = "a-cny".into(); |
| 6234 | row.id = "z-usd".into(); |
| 6235 | let mut prices = [&cny_row, &row]; |
| 6236 | sort_model_rows_for_view(&mut prices, |row| *row, ModelListView::Cheap, &[]); |
| 6237 | assert_eq!(prices[0].id, "z-usd"); |
| 6238 | assert_eq!(prices[1].id, "a-cny"); |
| 6239 | row.id = id.into(); |
| 6240 | config.custom_models.as_mut().unwrap()[0].cost_currency = None; |
| 6241 | // /load replaces the same metadata alongside the provider route. |
| 6242 | let mut reloaded = config.clone(); |
| 6243 | reloaded.custom_models.as_mut().unwrap()[0].reasoning = None; |
| 6244 | reloaded.custom_models.as_mut().unwrap()[0].limit = None; |
| 6245 | reloaded.custom_models.as_mut().unwrap()[0].cost = None; |
| 6246 | reloaded.custom_models.as_mut().unwrap()[0].tool_call = None; |
| 6247 | reloaded.custom_models.as_mut().unwrap()[0].modalities = None; |
| 6248 | config.refresh_provider_routes_from(&reloaded); |
| 6249 | let unknown = effective_picker_metadata(&config, Some(ProviderKind::Deepseek), id); |
| 6250 | // An automatic request allowance is policy, not discovered metadata. |
| 6251 | // Its limits are covered by route_budget; the picker must stay unknown. |
| 6252 | assert_eq!(unknown.context_window, None); |
| 6253 | assert_eq!(unknown.max_output, None); |
| 6254 | assert_eq!(unknown.tool_calls, None); |
| 6255 | assert_eq!(unknown.vision, SupportState::Unknown); |
| 6256 | assert_eq!(unknown.pricing, PickerPricing::Unknown); |
| 6257 | row.metadata = unknown; |
| 6258 | assert!(model_row_meta_chips(&row).contains(&"reasoning unknown".to_string())); |
| 6259 | } |
| 6260 | |
| 6261 | fn model_row(provider: ProviderKind, in_default_view: bool) -> ModelPickerRow { |
| 6262 | ModelPickerRow { |
| 6263 | id: "model".to_string(), |
| 6264 | provider: Some(provider), |
| 6265 | provider_identity: None, |
| 6266 | admitted_identity: (provider != ProviderKind::Custom) |
| 6267 | .then(|| Config::default().test_identity_for_kind(provider)), |
| 6268 | route_selection: None, |
| 6269 | hint: String::new(), |
| 6270 | metadata: EffectivePickerMetadata::default(), |
| 6271 | selectable: true, |
| 6272 | blocked_reason: None, |
| 6273 | default_rank: in_default_view.then_some((DefaultSection::Current, 0)), |
| 6274 | credentialed: false, |
| 6275 | not_listed: None, |
| 6276 | external_agent: None, |
| 6277 | } |
| 6278 | } |
| 6279 | |
| 6280 | /// #6523 review: named custom providers are exact config keys, so a pin |
| 6281 | /// on `TeamA` must not mark the same model under `teama`; built-in slugs |
| 6282 | /// stay case-insensitive aliases. |
| 6283 | #[test] |
| 6284 | fn pin_matching_is_exact_for_named_custom_providers_only() { |
| 6285 | let pin = |provider: &str| PinnedModel { |
| 6286 | provider: provider.to_string(), |
| 6287 | model: "model".to_string(), |
| 6288 | label: None, |
| 6289 | }; |
| 6290 | let custom = |identity: &str| ModelPickerRow { |
| 6291 | provider_identity: Some(identity.to_string()), |
| 6292 | ..model_row(ProviderKind::Custom, true) |
| 6293 | }; |
| 6294 | assert!(pin_names_row(&pin("TeamA"), &custom("TeamA"))); |
| 6295 | assert!(!pin_names_row(&pin("TeamA"), &custom("teama"))); |
| 6296 | assert!(!pin_names_row(&pin("teama"), &custom("TeamA"))); |
| 6297 | |
| 6298 | let builtin = model_row(ProviderKind::Deepseek, true); |
| 6299 | assert!(pin_names_row(&pin("deepseek"), &builtin)); |
| 6300 | assert!(pin_names_row(&pin("DeepSeek"), &builtin)); |
| 6301 | } |
| 6302 | |
| 6303 | /// The catalog sort ranks pins with the same exact match that marks them: |
| 6304 | /// a `TeamA` pin must not lift an unmarked `teama` row into the pinned |
| 6305 | /// block above the groups. |
| 6306 | #[test] |
| 6307 | fn catalog_sort_ranks_only_rows_the_pin_names() { |
| 6308 | let pins = vec![PinnedModel { |
| 6309 | provider: "TeamA".to_string(), |
| 6310 | model: "model".to_string(), |
| 6311 | label: None, |
| 6312 | }]; |
| 6313 | let custom = |identity: &str| ModelPickerRow { |
| 6314 | provider_identity: Some(identity.to_string()), |
| 6315 | ..model_row(ProviderKind::Custom, true) |
| 6316 | }; |
| 6317 | let owned = [ |
| 6318 | model_row(ProviderKind::Deepseek, true), |
| 6319 | model_row(ProviderKind::Google, true), |
| 6320 | model_row(ProviderKind::Openai, true), |
| 6321 | custom("teama"), |
| 6322 | custom("TeamA"), |
| 6323 | ]; |
| 6324 | let mut rows: Vec<&ModelPickerRow> = owned.iter().collect(); |
| 6325 | sort_model_rows_for_view(&mut rows, |row| *row, ModelListView::Catalog, &pins); |
| 6326 | |
| 6327 | let order: Vec<Option<&str>> = rows.iter().map(|row| row_provider_identity(row)).collect(); |
| 6328 | assert_eq!( |
| 6329 | order, |
| 6330 | vec![ |
| 6331 | Some("TeamA"), |
| 6332 | Some("openai"), |
| 6333 | Some("google"), |
| 6334 | Some("deepseek"), |
| 6335 | Some("teama") |
| 6336 | ] |
| 6337 | ); |
| 6338 | assert!(pin_for_row(&pins, rows[0]).is_some()); |
| 6339 | assert!(pin_for_row(&pins, rows[4]).is_none()); |
| 6340 | } |
| 6341 | |
| 6342 | #[test] |
| 6343 | fn locked_model_keeps_keyboard_focus_visible_without_becoming_selectable() { |
| 6344 | let mut picker = test_picker(); |
| 6345 | picker.model_rows[0].selectable = false; |
| 6346 | picker.model_rows[0].blocked_reason = Some("needs key".to_string()); |
| 6347 | let area = Rect::new(0, 0, 100, 32); |
| 6348 | let mut buf = Buffer::empty(area); |
| 6349 | picker.render(area, &mut buf); |
| 6350 | let hit = picker |
| 6351 | .row_hitboxes |
| 6352 | .borrow() |
| 6353 | .iter() |
| 6354 | .find(|(_, pane, idx)| *pane == Pane::Model && *idx == 0) |
| 6355 | .unwrap() |
| 6356 | .0; |
| 6357 | assert_eq!(buf[(hit.right() - 1, hit.y)].bg, palette::SELECTION_BG); |
| 6358 | assert!(!picker.model_rows[0].selectable); |
| 6359 | } |
| 6360 | |
| 6361 | #[test] |
| 6362 | fn workbench_hover_preserves_model_selection_and_clears_on_keyboard_input() { |
| 6363 | let mut picker = test_picker(); |
| 6364 | picker |
| 6365 | .model_rows |
| 6366 | .push(model_row(ProviderKind::Deepseek, true)); |
| 6367 | let area = Rect::new(0, 0, 100, 32); |
| 6368 | let mut buf = Buffer::empty(area); |
| 6369 | picker.render(area, &mut buf); |
| 6370 | let hit = picker |
| 6371 | .row_hitboxes |
| 6372 | .borrow() |
| 6373 | .iter() |
| 6374 | .find(|(_, pane, idx)| *pane == Pane::Model && *idx == 1) |
| 6375 | .unwrap() |
| 6376 | .0; |
| 6377 | picker.handle_mouse(MouseEvent { |
| 6378 | kind: MouseEventKind::Moved, |
| 6379 | column: hit.x, |
| 6380 | row: hit.y, |
| 6381 | modifiers: KeyModifiers::NONE, |
| 6382 | }); |
| 6383 | assert_eq!(picker.hovered_row, Some((Pane::Model, 1))); |
| 6384 | assert_eq!(picker.selected_model_idx, 0); |
| 6385 | picker.render(area, &mut buf); |
| 6386 | assert_eq!(buf[(hit.right() - 1, hit.y)].bg, palette::SURFACE_ELEVATED); |
| 6387 | picker.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); |
| 6388 | assert_eq!(picker.hovered_row, None); |
| 6389 | } |
| 6390 | |
| 6391 | fn test_picker() -> ModelPickerView { |
| 6392 | ModelPickerView { |
| 6393 | initial_model: "model".to_string(), |
| 6394 | previous_model: "model".to_string(), |
| 6395 | initial_provider: ProviderKind::Openai, |
| 6396 | initial_provider_identity: ProviderKind::Openai.as_str().to_string(), |
| 6397 | initial_identity: Some( |
| 6398 | Config::default() |
| 6399 | .builtin_provider_identity(ProviderKind::Openai) |
| 6400 | .unwrap(), |
| 6401 | ), |
| 6402 | initial_external_agent_id: None, |
| 6403 | initial_effort: ReasoningEffort::Auto, |
| 6404 | selected_effort_request: ReasoningEffort::Auto, |
| 6405 | active_accepts_custom_model_ids: false, |
| 6406 | query: String::new(), |
| 6407 | provider_filter: None, |
| 6408 | selected_model_idx: 0, |
| 6409 | selected_effort_idx: 0, |
| 6410 | selected_context_idx: 0, |
| 6411 | initial_context_override: None, |
| 6412 | custom_context_input: String::new(), |
| 6413 | custom_context_error: None, |
| 6414 | focus: Pane::Model, |
| 6415 | show_custom_model_row: false, |
| 6416 | model_rows: vec![model_row(ProviderKind::Openai, true)], |
| 6417 | route_config: Config::default(), |
| 6418 | provider_health: Default::default(), |
| 6419 | view: ModelListView::Configured, |
| 6420 | configured_providers: Vec::new(), |
| 6421 | row_hitboxes: RefCell::new(Vec::new()), |
| 6422 | last_mouse_selected: None, |
| 6423 | hovered_row: None, |
| 6424 | locale: Locale::En, |
| 6425 | pinned_models: Vec::new(), |
| 6426 | projection: RefCell::new(None), |
| 6427 | sort: None, |
| 6428 | column_hitboxes: RefCell::new(Vec::new()), |
| 6429 | pane_hitboxes: RefCell::new(Vec::new()), |
| 6430 | catalog_action_hitbox: RefCell::new(None), |
| 6431 | catalog_action_hovered: false, |
| 6432 | purpose: ModelPickerPurpose::Session, |
| 6433 | assignment_context: None, |
| 6434 | notice: None, |
| 6435 | theme: codewhale_palette::UI_THEME, |
| 6436 | } |
| 6437 | } |
| 6438 | |
| 6439 | /// Opened for a Fleet row, Enter hands the editor the absolute route |
| 6440 | /// instead of switching the session; the startup-default chord is the |
| 6441 | /// same pick. |
| 6442 | #[test] |
| 6443 | fn catalog_header_click_matches_keyboard_at_compact_and_wide_sizes() { |
| 6444 | for (width, height) in [(40, 12), (80, 24), (140, 40)] { |
| 6445 | let mut mouse_picker = test_picker(); |
| 6446 | let mut key_picker = test_picker(); |
| 6447 | let area = Rect::new(0, 0, width, height); |
| 6448 | mouse_picker.render(area, &mut Buffer::empty(area)); |
| 6449 | let hit = mouse_picker |
| 6450 | .catalog_action_hitbox |
| 6451 | .borrow() |
| 6452 | .expect("catalog action"); |
| 6453 | assert!(area.contains((hit.x, hit.y).into())); |
| 6454 | assert!(hit.right() <= area.right()); |
| 6455 | assert!(matches!( |
| 6456 | mouse_picker.handle_mouse(MouseEvent { |
| 6457 | kind: MouseEventKind::Down(MouseButton::Left), |
| 6458 | column: hit.x, |
| 6459 | row: hit.y, |
| 6460 | modifiers: KeyModifiers::NONE, |
| 6461 | }), |
| 6462 | ViewAction::None |
| 6463 | )); |
| 6464 | key_picker.handle_key(KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT)); |
| 6465 | assert_eq!(mouse_picker.view, key_picker.view); |
| 6466 | assert_eq!( |
| 6467 | mouse_picker.selected_model_idx, |
| 6468 | key_picker.selected_model_idx |
| 6469 | ); |
| 6470 | let empty = Rect::new(0, 0, 0, 0); |
| 6471 | mouse_picker.render(empty, &mut Buffer::empty(empty)); |
| 6472 | assert!(mouse_picker.catalog_action_hitbox.borrow().is_none()); |
| 6473 | } |
| 6474 | } |
| 6475 | |
| 6476 | #[test] |
| 6477 | fn fleet_purpose_enter_hands_the_absolute_route_to_the_editor() { |
| 6478 | let mut picker = test_picker(); |
| 6479 | picker.purpose = ModelPickerPurpose::FleetRoute { |
| 6480 | target: FleetRouteTarget::Member(1), |
| 6481 | editor_id: uuid::Uuid::nil(), |
| 6482 | initial_reasoning: None, |
| 6483 | allow_inherit: true, |
| 6484 | }; |
| 6485 | let action = picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); |
| 6486 | assert!( |
| 6487 | matches!( |
| 6488 | &action, |
| 6489 | ViewAction::EmitAndClose(ViewEvent::FleetRoutePicked { |
| 6490 | target: FleetRouteTarget::Member(1), |
| 6491 | provider: ProviderKind::Openai, |
| 6492 | provider_id: Some(provider_id), |
| 6493 | model, |
| 6494 | editor_id, |
| 6495 | reasoning: None, |
| 6496 | }) if provider_id == "openai" && model == "model" && editor_id.is_nil() |
| 6497 | ), |
| 6498 | "{action:?}" |
| 6499 | ); |
| 6500 | assert!(matches!( |
| 6501 | picker.handle_key(KeyEvent::new(KeyCode::Char('D'), KeyModifiers::SHIFT)), |
| 6502 | ViewAction::EmitAndClose(ViewEvent::FleetRoutePicked { .. }) |
| 6503 | )); |
| 6504 | // The session-purpose picker is untouched by the new purpose. |
| 6505 | let mut session = test_picker(); |
| 6506 | assert!(matches!( |
| 6507 | session.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 6508 | ViewAction::EmitAndClose(ViewEvent::ModelPickerApplied { .. }) |
| 6509 | )); |
| 6510 | } |
| 6511 | |
| 6512 | #[test] |
| 6513 | fn profile_role_picker_assigns_only_its_owner_and_search_cancels_before_closing() { |
| 6514 | let editor_id = uuid::Uuid::new_v4(); |
| 6515 | let mut picker = test_picker().with_assignment_context("reviewer", "Choose where to save"); |
| 6516 | picker.purpose = ModelPickerPurpose::FleetProfileRoute { |
| 6517 | editor_id, |
| 6518 | initial_reasoning: None, |
| 6519 | }; |
| 6520 | assert!( |
| 6521 | matches!(picker.build_apply_event(false), ViewEvent::FleetProfileRoutePicked { |
| 6522 | editor_id: owner, provider: ProviderKind::Openai, model, .. |
| 6523 | } if owner == editor_id && model == "model") |
| 6524 | ); |
| 6525 | for (width, height) in [(40, 12), (80, 24), (140, 40)] { |
| 6526 | let area = Rect::new(0, 0, width, height); |
| 6527 | let mut buf = Buffer::empty(area); |
| 6528 | picker.render(area, &mut buf); |
| 6529 | let text: String = buf.content().iter().map(|cell| cell.symbol()).collect(); |
| 6530 | assert!(text.contains("reviewer"), "{text}"); |
| 6531 | assert!(text.contains("Choose where to save"), "{text}"); |
| 6532 | } |
| 6533 | picker.locale = Locale::ZhHans; |
| 6534 | let area = Rect::new(0, 0, 100, 24); |
| 6535 | let mut buf = Buffer::empty(area); |
| 6536 | picker.render(area, &mut buf); |
| 6537 | let title: String = buf |
| 6538 | .content() |
| 6539 | .iter() |
| 6540 | .map(|cell| cell.symbol()) |
| 6541 | .collect::<String>() |
| 6542 | .split_whitespace() |
| 6543 | .collect(); |
| 6544 | assert!(title.contains("模型·reviewer")); |
| 6545 | picker.update_query("model".into()); |
| 6546 | assert!(matches!( |
| 6547 | picker.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)), |
| 6548 | ViewAction::None |
| 6549 | )); |
| 6550 | assert!(picker.query.is_empty()); |
| 6551 | assert!( |
| 6552 | matches!(picker.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)), ViewAction::EmitAndClose(ViewEvent::FleetAssignmentPickerDismissed { editor_id: owner }) if owner == editor_id) |
| 6553 | ); |
| 6554 | picker.model_rows[0].selectable = false; |
| 6555 | *picker.projection.get_mut() = None; |
| 6556 | assert!(matches!( |
| 6557 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 6558 | ViewAction::Emit(ViewEvent::StatusToast { |
| 6559 | level: crate::tui::app::StatusToastLevel::Error, |
| 6560 | .. |
| 6561 | }) |
| 6562 | )); |
| 6563 | } |
| 6564 | |
| 6565 | #[test] |
| 6566 | fn fleet_locked_builtin_explains_setup_without_switching_the_session() { |
| 6567 | let mut picker = test_picker(); |
| 6568 | picker.purpose = ModelPickerPurpose::FleetRoute { |
| 6569 | target: FleetRouteTarget::Operator, |
| 6570 | editor_id: uuid::Uuid::nil(), |
| 6571 | initial_reasoning: None, |
| 6572 | allow_inherit: true, |
| 6573 | }; |
| 6574 | picker.model_rows[0].selectable = false; |
| 6575 | *picker.projection.get_mut() = None; |
| 6576 | assert!(matches!( |
| 6577 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 6578 | ViewAction::Emit(ViewEvent::StatusToast { |
| 6579 | message, |
| 6580 | level: crate::tui::app::StatusToastLevel::Error, |
| 6581 | }) if message.contains("/provider") |
| 6582 | )); |
| 6583 | } |
| 6584 | |
| 6585 | #[test] |
| 6586 | fn fleet_picker_keeps_the_rows_exact_pin_and_effort_after_refresh() { |
| 6587 | let _env = crate::test_support::lock_test_env(); |
| 6588 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 6589 | let (config, mut app, home, _workspace) = |
| 6590 | resumed_openrouter_session_with_named_custom_routes(); |
| 6591 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 6592 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 6593 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 6594 | app.model_picker_memory = Some(crate::tui::app::ModelPickerMemory { |
| 6595 | catalog_view: true, |
| 6596 | view: Some("catalog".to_string()), |
| 6597 | selected_row_id: Some(app.model.clone()), |
| 6598 | }); |
| 6599 | let session_route = (app.api_provider, app.model.clone()); |
| 6600 | let mut picker = ModelPickerView::new_for_fleet_route( |
| 6601 | &app, |
| 6602 | &config, |
| 6603 | FleetRouteTarget::Member(0), |
| 6604 | uuid::Uuid::nil(), |
| 6605 | FleetRouteSelection { |
| 6606 | provider: Some("command_code".to_string()), |
| 6607 | model: Some("deepseek/deepseek-v4-flash".to_string()), |
| 6608 | reasoning: Some(ReasoningEffort::High), |
| 6609 | allow_inherit: true, |
| 6610 | }, |
| 6611 | ); |
| 6612 | assert_eq!( |
| 6613 | picker.resolved_provider_identity().as_deref(), |
| 6614 | Some("command_code") |
| 6615 | ); |
| 6616 | assert_eq!(picker.resolved_model(), "deepseek/deepseek-v4-flash"); |
| 6617 | assert_eq!(picker.selected_effort_request, ReasoningEffort::High); |
| 6618 | assert!(picker.can_edit_effort()); |
| 6619 | assert_eq!( |
| 6620 | picker |
| 6621 | .visible_model_rows() |
| 6622 | .iter() |
| 6623 | .filter(|row| row.id == "deepseek/deepseek-v4-flash" |
| 6624 | && row_provider_identity(row) == Some("command_code")) |
| 6625 | .count(), |
| 6626 | 1 |
| 6627 | ); |
| 6628 | picker.selected_effort_request = ReasoningEffort::Low; |
| 6629 | picker.re_resolve_from_app(&app, &config); |
| 6630 | assert!(picker.can_edit_effort()); |
| 6631 | assert!(matches!( |
| 6632 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 6633 | ViewAction::EmitAndClose(ViewEvent::FleetRoutePicked { |
| 6634 | provider: ProviderKind::Custom, provider_id: Some(identity), model, |
| 6635 | reasoning: Some(ReasoningEffort::Low), .. |
| 6636 | }) if identity == "command_code" && model == "deepseek/deepseek-v4-flash" |
| 6637 | )); |
| 6638 | assert_eq!((app.api_provider, app.model.clone()), session_route); |
| 6639 | assert!(matches!( |
| 6640 | picker.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)), |
| 6641 | ViewAction::EmitAndClose(ViewEvent::FleetAssignmentPickerDismissed { .. }) |
| 6642 | )); |
| 6643 | for query in [ |
| 6644 | "openrouter:new-fixture-model", |
| 6645 | "openrouter new-fixture-model", |
| 6646 | ] { |
| 6647 | picker.update_query(query.to_string()); |
| 6648 | assert_eq!(picker.resolved_provider(), Some(ProviderKind::Openrouter)); |
| 6649 | assert_eq!(picker.resolved_model(), "new-fixture-model"); |
| 6650 | } |
| 6651 | // A slash is part of a model id, not a provider switch: compatible |
| 6652 | // routes routinely serve names such as openai/gpt-5. |
| 6653 | picker.update_query("openrouter/new-fixture-model".to_string()); |
| 6654 | assert_eq!(picker.resolved_provider(), Some(ProviderKind::Custom)); |
| 6655 | assert_eq!(picker.resolved_model(), "openrouter/new-fixture-model"); |
| 6656 | } |
| 6657 | |
| 6658 | #[test] |
| 6659 | fn fleet_shortlist_picker_has_no_inherit_or_reasoning_edits() { |
| 6660 | let _env = crate::test_support::lock_test_env(); |
| 6661 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 6662 | let (config, app, home, _workspace) = resumed_openrouter_session_with_named_custom_routes(); |
| 6663 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 6664 | let mut picker = ModelPickerView::new_for_fleet_route( |
| 6665 | &app, |
| 6666 | &config, |
| 6667 | FleetRouteTarget::Member(0), |
| 6668 | uuid::Uuid::nil(), |
| 6669 | FleetRouteSelection { |
| 6670 | provider: Some("command_code".to_string()), |
| 6671 | model: Some("deepseek/deepseek-v4-flash".to_string()), |
| 6672 | reasoning: None, |
| 6673 | allow_inherit: false, |
| 6674 | }, |
| 6675 | ); |
| 6676 | for _ in 0..2 { |
| 6677 | assert!(!picker.can_edit_effort()); |
| 6678 | assert!( |
| 6679 | picker |
| 6680 | .visible_model_rows() |
| 6681 | .iter() |
| 6682 | .all(|row| row.id != "auto") |
| 6683 | ); |
| 6684 | picker.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); |
| 6685 | assert_eq!(picker.focus, Pane::Model); |
| 6686 | render_text(&picker, 150, 42); |
| 6687 | assert!( |
| 6688 | picker |
| 6689 | .pane_hitboxes |
| 6690 | .borrow() |
| 6691 | .iter() |
| 6692 | .all(|(_, pane)| *pane == Pane::Model) |
| 6693 | ); |
| 6694 | assert!(matches!( |
| 6695 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 6696 | ViewAction::EmitAndClose(ViewEvent::FleetRoutePicked { |
| 6697 | reasoning: None, |
| 6698 | .. |
| 6699 | }) |
| 6700 | )); |
| 6701 | picker.re_resolve_from_app(&app, &config); |
| 6702 | } |
| 6703 | picker.update_query("auto".to_string()); |
| 6704 | assert!( |
| 6705 | !matches!(picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), ViewAction::EmitAndClose(ViewEvent::FleetRoutePicked { model, .. }) if model == "auto") |
| 6706 | ); |
| 6707 | } |
| 6708 | |
| 6709 | #[test] |
| 6710 | fn fleet_inherited_route_is_selectable_and_named_without_session_autorouting_claims() { |
| 6711 | let _env = crate::test_support::lock_test_env(); |
| 6712 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 6713 | let (config, app, home, _workspace) = resumed_openrouter_session_with_named_custom_routes(); |
| 6714 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 6715 | let mut picker = ModelPickerView::new_for_fleet_route( |
| 6716 | &app, |
| 6717 | &config, |
| 6718 | FleetRouteTarget::Member(0), |
| 6719 | uuid::Uuid::nil(), |
| 6720 | FleetRouteSelection { |
| 6721 | provider: None, |
| 6722 | model: None, |
| 6723 | reasoning: None, |
| 6724 | allow_inherit: true, |
| 6725 | }, |
| 6726 | ); |
| 6727 | assert_eq!(picker.resolved_model(), "auto"); |
| 6728 | assert!(picker.selected_model_is_selectable()); |
| 6729 | assert!( |
| 6730 | render_text(&picker, 150, 42) |
| 6731 | .contains(tr(app.ui_locale, MessageId::FleetRouteInherited).as_ref()) |
| 6732 | ); |
| 6733 | assert_eq!(picker.current_efforts(), vec![ReasoningEffort::Auto]); |
| 6734 | assert!( |
| 6735 | matches!(picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), ViewAction::EmitAndClose(ViewEvent::FleetRoutePicked { model, reasoning: None, .. }) if model == "auto") |
| 6736 | ); |
| 6737 | } |
| 6738 | |
| 6739 | fn render_text(picker: &ModelPickerView, width: u16, height: u16) -> String { |
| 6740 | let area = Rect::new(0, 0, width, height); |
| 6741 | let mut buffer = Buffer::empty(area); |
| 6742 | picker.render(area, &mut buffer); |
| 6743 | (0..height) |
| 6744 | .map(|y| { |
| 6745 | (0..width) |
| 6746 | .map(|x| buffer[(x, y)].symbol()) |
| 6747 | .collect::<String>() |
| 6748 | }) |
| 6749 | .collect::<Vec<_>>() |
| 6750 | .join("\n") |
| 6751 | } |
| 6752 | |
| 6753 | #[test] |
| 6754 | fn deepseek_picker_heading_hides_legacy_family_metadata() { |
| 6755 | assert_eq!( |
| 6756 | catalog_family_for_identity(ProviderKind::Deepseek, None, "deepseek-v4-pro").as_deref(), |
| 6757 | Some("DeepSeek") |
| 6758 | ); |
| 6759 | } |
| 6760 | |
| 6761 | #[test] |
| 6762 | fn default_view_shows_only_sectioned_rows_and_auto() { |
| 6763 | let row = model_row(ProviderKind::Deepseek, false); |
| 6764 | assert!(!model_row_visible_by_default(&row)); |
| 6765 | assert!(model_row_visible_by_default(&model_row( |
| 6766 | ProviderKind::Deepseek, |
| 6767 | true |
| 6768 | ))); |
| 6769 | let mut auto = model_row(ProviderKind::Deepseek, false); |
| 6770 | auto.provider = None; |
| 6771 | assert!(model_row_visible_by_default(&auto)); |
| 6772 | } |
| 6773 | |
| 6774 | #[test] |
| 6775 | fn lowercase_picker_action_letters_begin_a_model_search() { |
| 6776 | for ch in ['a', 'p', 'r'] { |
| 6777 | let mut picker = test_picker(); |
| 6778 | assert!(matches!( |
| 6779 | picker.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)), |
| 6780 | ViewAction::None |
| 6781 | )); |
| 6782 | assert_eq!(picker.query, ch.to_string(), "{ch} must begin a search"); |
| 6783 | assert_eq!(picker.view, ModelListView::Configured); |
| 6784 | } |
| 6785 | } |
| 6786 | |
| 6787 | #[test] |
| 6788 | fn shifted_picker_actions_cycle_views_pin_and_refresh_explicitly() { |
| 6789 | let mut picker = test_picker(); |
| 6790 | |
| 6791 | assert!(matches!( |
| 6792 | picker.handle_key(KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT)), |
| 6793 | ViewAction::None |
| 6794 | )); |
| 6795 | assert_eq!(picker.view, ModelListView::Catalog); |
| 6796 | assert!(picker.query.is_empty()); |
| 6797 | |
| 6798 | assert!(matches!( |
| 6799 | picker.handle_key(KeyEvent::new(KeyCode::Char('P'), KeyModifiers::SHIFT)), |
| 6800 | ViewAction::Emit(ViewEvent::ModelPickerTogglePin { |
| 6801 | provider: ProviderKind::Openai, |
| 6802 | provider_id: None, |
| 6803 | model, |
| 6804 | }) if model == "model" |
| 6805 | )); |
| 6806 | assert!(picker.query.is_empty()); |
| 6807 | |
| 6808 | assert!(matches!( |
| 6809 | picker.handle_key(KeyEvent::new(KeyCode::Char('F'), KeyModifiers::SHIFT)), |
| 6810 | ViewAction::Emit(ViewEvent::ModelPickerToggleFleet { |
| 6811 | provider: ProviderKind::Openai, |
| 6812 | provider_id: None, |
| 6813 | model, |
| 6814 | }) if model == "model" |
| 6815 | )); |
| 6816 | assert!(picker.query.is_empty()); |
| 6817 | |
| 6818 | assert!(matches!( |
| 6819 | picker.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)), |
| 6820 | ViewAction::Emit(ViewEvent::ModelPickerRefresh) |
| 6821 | )); |
| 6822 | } |
| 6823 | |
| 6824 | #[test] |
| 6825 | fn fleet_models_lead_the_pins_the_picker_sorts_by() { |
| 6826 | let _lock = crate::test_support::lock_test_env(); |
| 6827 | let temp = tempfile::tempdir().expect("tempdir"); |
| 6828 | let home = temp.path().join("home"); |
| 6829 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 6830 | let workspace = temp.path().join("repo"); |
| 6831 | std::fs::create_dir_all(&workspace).expect("workspace"); |
| 6832 | codewhale_engine::fleet::members::add_fleet_model( |
| 6833 | &workspace, |
| 6834 | "openrouter", |
| 6835 | "z-ai/glm-5.3-flash", |
| 6836 | &["scout".to_string()], |
| 6837 | ) |
| 6838 | .expect("fleet add"); |
| 6839 | |
| 6840 | let options = crate::tui::app::TuiOptions { |
| 6841 | ..crate::tui::test_support::test_tui_options(workspace.clone()) |
| 6842 | }; |
| 6843 | let mut app = crate::tui::app::App::new(options, &Config::default()); |
| 6844 | app.workspace = workspace; |
| 6845 | app.pinned_models = vec![PinnedModel { |
| 6846 | provider: "anthropic".to_string(), |
| 6847 | model: "claude-haiku-4-5".to_string(), |
| 6848 | label: None, |
| 6849 | }]; |
| 6850 | |
| 6851 | let pins = picker_pins_for_app(&app); |
| 6852 | assert_eq!(pins.len(), 2, "fleet model then the person's pin: {pins:?}"); |
| 6853 | assert_eq!(pins[0].provider, "openrouter"); |
| 6854 | assert_eq!(pins[0].model, "z-ai/glm-5.3-flash"); |
| 6855 | assert_eq!(pins[0].label.as_deref(), Some("fleet · explore")); |
| 6856 | assert_eq!(pins[1].model, "claude-haiku-4-5"); |
| 6857 | } |
| 6858 | |
| 6859 | #[test] |
| 6860 | fn fleet_case_distinct_pins_keep_labels_order_and_refresh_selection() { |
| 6861 | std::thread::Builder::new() |
| 6862 | .stack_size(16 * 1024 * 1024) |
| 6863 | .spawn(|| { |
| 6864 | let _lock = crate::test_support::lock_test_env(); |
| 6865 | let root = tempfile::tempdir().unwrap(); |
| 6866 | let _home = crate::test_support::EnvVarGuard::set( |
| 6867 | "CODEWHALE_HOME", |
| 6868 | root.path().join("home"), |
| 6869 | ); |
| 6870 | let workspace = root.path().join("workspace"); |
| 6871 | std::fs::create_dir_all(&workspace).unwrap(); |
| 6872 | let lower = "preview-fixture"; |
| 6873 | let upper = "Preview-fixture"; |
| 6874 | let mut config: Config = toml::from_str(include_str!( |
| 6875 | "../../../config/tests/fixtures/custom_models.toml" |
| 6876 | )) |
| 6877 | .unwrap(); |
| 6878 | config.default_text_model = Some(lower.into()); |
| 6879 | config |
| 6880 | .set_provider_model_override( |
| 6881 | &config.test_identity_for_kind(ProviderKind::Deepseek), |
| 6882 | Some(lower.into()), |
| 6883 | ) |
| 6884 | .unwrap(); |
| 6885 | config |
| 6886 | .set_provider_api_key_override( |
| 6887 | &config.test_identity_for_kind(ProviderKind::Deepseek), |
| 6888 | Some("fixture-key".into()), |
| 6889 | ) |
| 6890 | .unwrap(); |
| 6891 | config.custom_models.as_mut().unwrap()[0].id = lower.into(); |
| 6892 | let mut second = config.custom_models.as_ref().unwrap()[0].clone(); |
| 6893 | second.id = upper.into(); |
| 6894 | config.custom_models.as_mut().unwrap().push(second); |
| 6895 | codewhale_engine::fleet::members::add_fleet_model( |
| 6896 | &workspace, |
| 6897 | "deepseek", |
| 6898 | lower, |
| 6899 | &["scout".into()], |
| 6900 | ) |
| 6901 | .unwrap(); |
| 6902 | codewhale_engine::fleet::members::add_fleet_model( |
| 6903 | &workspace, |
| 6904 | "deepseek", |
| 6905 | upper, |
| 6906 | &["reviewer".into()], |
| 6907 | ) |
| 6908 | .unwrap(); |
| 6909 | let options = crate::tui::test_support::test_tui_options(workspace.clone()); |
| 6910 | let mut app = App::new(options, &config); |
| 6911 | app.workspace = workspace.clone(); |
| 6912 | let pins = picker_pins_for_app(&app); |
| 6913 | let rows = picker_model_rows_for_app(&app, &config); |
| 6914 | for pin in &pins { |
| 6915 | let row = rows |
| 6916 | .iter() |
| 6917 | .find(|row| { |
| 6918 | row.provider == Some(ProviderKind::Deepseek) && row.id == pin.model |
| 6919 | }) |
| 6920 | .unwrap(); |
| 6921 | assert!(row.hint.starts_with(pin.label.as_deref().unwrap())); |
| 6922 | assert!( |
| 6923 | row.hint |
| 6924 | .contains(&format!("exact deepseek / {}", pin.model)) |
| 6925 | ); |
| 6926 | } |
| 6927 | let mut picker = ModelPickerView::new(&app, &config); |
| 6928 | let visible = picker.visible_model_rows(); |
| 6929 | // The current route leads (#6533); the pins follow it. The |
| 6930 | // configured `default_text_model` is the startup route, so the |
| 6931 | // lower pin is also the current row. |
| 6932 | assert_eq!(app.model, lower); |
| 6933 | assert_eq!(visible[0].id, app.model); |
| 6934 | let lower_index = visible.iter().position(|row| row.id == lower).unwrap(); |
| 6935 | let upper_index = visible.iter().position(|row| row.id == upper).unwrap(); |
| 6936 | assert!( |
| 6937 | lower_index < upper_index, |
| 6938 | "saved pin order precedes lexical order" |
| 6939 | ); |
| 6940 | drop(visible); |
| 6941 | picker.selected_model_idx = upper_index; |
| 6942 | picker.re_resolve_from_app(&app, &config); |
| 6943 | assert_eq!( |
| 6944 | picker.resolved_model(), |
| 6945 | upper, |
| 6946 | "refresh cannot select its case sibling" |
| 6947 | ); |
| 6948 | |
| 6949 | // The still-saved upper route remains a distinct stale row after its |
| 6950 | // declaration disappears; a live lower row cannot hide it. |
| 6951 | config |
| 6952 | .custom_models |
| 6953 | .as_mut() |
| 6954 | .unwrap() |
| 6955 | .retain(|row| row.id == lower); |
| 6956 | let options = crate::tui::test_support::test_tui_options(workspace.clone()); |
| 6957 | let mut reloaded = App::new(options, &config); |
| 6958 | reloaded.workspace = workspace; |
| 6959 | let rows = picker_model_rows_for_app(&reloaded, &config); |
| 6960 | let stale = rows |
| 6961 | .iter() |
| 6962 | .filter(|row| row.provider == Some(ProviderKind::Deepseek) && row.id == upper) |
| 6963 | .collect::<Vec<_>>(); |
| 6964 | assert_eq!(stale.len(), 1); |
| 6965 | assert_eq!(stale[0].blocked_reason.as_deref(), Some("stale pin")); |
| 6966 | assert!( |
| 6967 | rows.iter() |
| 6968 | .any(|row| row.provider == Some(ProviderKind::Deepseek) |
| 6969 | && row.id == lower |
| 6970 | && row.blocked_reason.as_deref() != Some("stale pin")) |
| 6971 | ); |
| 6972 | }) |
| 6973 | .unwrap() |
| 6974 | .join() |
| 6975 | .unwrap(); |
| 6976 | } |
| 6977 | |
| 6978 | #[test] |
| 6979 | fn wide_picker_footer_advertises_shifted_view_and_pin_actions() { |
| 6980 | let picker = test_picker(); |
| 6981 | let text = render_text(&picker, 100, 30); |
| 6982 | |
| 6983 | assert!(text.contains("⇧A"), "missing shifted view hint: {text}"); |
| 6984 | assert!(text.contains("⇧P"), "missing shifted pin hint: {text}"); |
| 6985 | assert!(text.contains("⇧F"), "missing shifted fleet hint: {text}"); |
| 6986 | |
| 6987 | let lines: Vec<&str> = text.lines().collect(); |
| 6988 | let esc_idx = lines |
| 6989 | .iter() |
| 6990 | .rposition(|line| line.contains("Esc")) |
| 6991 | .expect("footer line"); |
| 6992 | let start_idx = lines[..=esc_idx] |
| 6993 | .iter() |
| 6994 | .rposition(|line| line.contains("↑↓")) |
| 6995 | .unwrap_or(esc_idx); |
| 6996 | let footer_block = lines[start_idx..=esc_idx].join("\n"); |
| 6997 | assert!( |
| 6998 | footer_block.contains("↑↓"), |
| 6999 | "footer missing move: {footer_block}" |
| 7000 | ); |
| 7001 | assert!( |
| 7002 | footer_block.contains("Enter"), |
| 7003 | "footer missing apply: {footer_block}" |
| 7004 | ); |
| 7005 | assert!( |
| 7006 | footer_block.contains("⇧A"), |
| 7007 | "footer missing views: {footer_block}" |
| 7008 | ); |
| 7009 | assert!( |
| 7010 | !footer_block.contains("Ctrl+S") && !footer_block.contains("⇧D"), |
| 7011 | "footer must stay calm at 6 core actions: {footer_block}" |
| 7012 | ); |
| 7013 | } |
| 7014 | |
| 7015 | #[test] |
| 7016 | fn full_catalog_navigation_sort_refresh_and_mouse_stay_coherent() { |
| 7017 | const PROBE: &str = "CODEWHALE_PICKER_CATALOG_PROBE"; |
| 7018 | if std::env::var_os(PROBE).is_none() { |
| 7019 | let fixture = tempfile::tempdir().expect("picker fixture"); |
| 7020 | let home = fixture.path().join("home"); |
| 7021 | let workspace = fixture.path().join("workspace"); |
| 7022 | std::fs::create_dir_all(&home).unwrap(); |
| 7023 | std::fs::create_dir_all(&workspace).unwrap(); |
| 7024 | let output = std::process::Command::new(std::env::current_exe().unwrap()) |
| 7025 | .args(["--exact", "tui::model_picker::tests::full_catalog_navigation_sort_refresh_and_mouse_stay_coherent", "--nocapture", "--test-threads=1"]) |
| 7026 | .env_clear() |
| 7027 | .env(PROBE, "1") |
| 7028 | .env("HOME", &home) |
| 7029 | .env("USERPROFILE", &home) |
| 7030 | .env("XDG_CONFIG_HOME", home.join("config")) |
| 7031 | .env("XDG_CACHE_HOME", home.join("cache")) |
| 7032 | .env("XDG_DATA_HOME", home.join("data")) |
| 7033 | .env("CODEWHALE_HOME", home.join(".codewhale")) |
| 7034 | .env("CODEWHALE_DISABLE_MODELS_DEV_FETCH", "1") |
| 7035 | .env("CODEWHALE_NO_UPDATE_CHECK", "1") |
| 7036 | .env("CODEWHALE_TELEMETRY", "0") |
| 7037 | .current_dir(&workspace) |
| 7038 | .output().expect("isolated picker test"); |
| 7039 | assert!( |
| 7040 | output.status.success(), |
| 7041 | "{}\n{}", |
| 7042 | String::from_utf8_lossy(&output.stdout), |
| 7043 | String::from_utf8_lossy(&output.stderr) |
| 7044 | ); |
| 7045 | assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); |
| 7046 | return; |
| 7047 | } |
| 7048 | let config = Config::default(); |
| 7049 | let mut app = App::new( |
| 7050 | crate::tui::test_support::test_tui_options(std::env::current_dir().unwrap()), |
| 7051 | &config, |
| 7052 | ); |
| 7053 | let mut picker = ModelPickerView::new(&app, &config); |
| 7054 | picker.handle_key(KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT)); |
| 7055 | let count = picker.model_row_count(); |
| 7056 | assert!(count >= 200, "use the actual full catalog: {count} rows"); |
| 7057 | let projection_storage = || { |
| 7058 | let projection = picker.projection.borrow(); |
| 7059 | let projection = projection.as_ref().unwrap(); |
| 7060 | (projection.indices.as_ptr(), projection.rows.as_ptr()) |
| 7061 | }; |
| 7062 | let initial_storage = projection_storage(); |
| 7063 | let started = std::time::Instant::now(); |
| 7064 | for _ in 0..30 { |
| 7065 | picker.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); |
| 7066 | render_text(&picker, 150, 42); |
| 7067 | let projection = picker.projection.borrow(); |
| 7068 | let projection = projection.as_ref().unwrap(); |
| 7069 | assert_eq!( |
| 7070 | (projection.indices.as_ptr(), projection.rows.as_ptr()), |
| 7071 | initial_storage, |
| 7072 | "navigation must not rebuild the full catalog or formatted rows" |
| 7073 | ); |
| 7074 | } |
| 7075 | assert!( |
| 7076 | started.elapsed() < std::time::Duration::from_secs(5), |
| 7077 | "30 navigation+render iterations over {count} catalog rows must stay fast" |
| 7078 | ); |
| 7079 | |
| 7080 | // Every catalog entry must remain visible when highlighted, even when |
| 7081 | // adjacent providers each require a separate family heading. |
| 7082 | for (width, height) in [(80, 24), (100, 30), (150, 42)] { |
| 7083 | for selected in 0..count { |
| 7084 | picker.selected_model_idx = selected; |
| 7085 | render_text(&picker, width, height); |
| 7086 | let panes = picker.pane_hitboxes.borrow(); |
| 7087 | let area = panes |
| 7088 | .iter() |
| 7089 | .find(|(_, pane)| *pane == Pane::Model) |
| 7090 | .unwrap() |
| 7091 | .0; |
| 7092 | let hitboxes = picker.row_hitboxes.borrow(); |
| 7093 | assert!( |
| 7094 | hitboxes |
| 7095 | .iter() |
| 7096 | .any(|(_, pane, index)| *pane == Pane::Model && *index == selected), |
| 7097 | "selected row {selected} disappeared at {width}x{height}" |
| 7098 | ); |
| 7099 | for (rect, pane, _) in hitboxes.iter().filter(|(_, pane, _)| *pane == Pane::Model) { |
| 7100 | assert_eq!(*pane, Pane::Model); |
| 7101 | assert!(rect.y >= area.y && rect.bottom() <= area.bottom()); |
| 7102 | } |
| 7103 | } |
| 7104 | } |
| 7105 | |
| 7106 | picker.handle_key(KeyEvent::new(KeyCode::Home, KeyModifiers::NONE)); |
| 7107 | render_text(&picker, 150, 42); |
| 7108 | let (effort_rect, _, _) = *picker |
| 7109 | .row_hitboxes |
| 7110 | .borrow() |
| 7111 | .iter() |
| 7112 | .find(|(_, pane, index)| *pane == Pane::Effort && *index == 1) |
| 7113 | .unwrap(); |
| 7114 | picker.handle_mouse(MouseEvent { |
| 7115 | kind: MouseEventKind::Down(MouseButton::Left), |
| 7116 | column: effort_rect.x + 1, |
| 7117 | row: effort_rect.y, |
| 7118 | modifiers: KeyModifiers::NONE, |
| 7119 | }); |
| 7120 | assert_eq!(picker.focus, Pane::Effort); |
| 7121 | let before = picker.selected_model_idx; |
| 7122 | let requested_effort = picker.selected_effort_request; |
| 7123 | let model_area = picker |
| 7124 | .pane_hitboxes |
| 7125 | .borrow() |
| 7126 | .iter() |
| 7127 | .find(|(_, pane)| *pane == Pane::Model) |
| 7128 | .unwrap() |
| 7129 | .0; |
| 7130 | picker.handle_mouse(MouseEvent { |
| 7131 | kind: MouseEventKind::ScrollDown, |
| 7132 | column: model_area.x + 1, |
| 7133 | row: model_area.y + 3, |
| 7134 | modifiers: KeyModifiers::NONE, |
| 7135 | }); |
| 7136 | assert_eq!(picker.focus, Pane::Model); |
| 7137 | assert_eq!(picker.selected_model_idx, wrapping_next(before, count)); |
| 7138 | assert_eq!(picker.selected_effort_request, requested_effort); |
| 7139 | |
| 7140 | // Actual header hitboxes sort in both directions without changing the |
| 7141 | // selected provider/model; missing context is never treated as zero. |
| 7142 | let selected = (picker.resolved_provider(), picker.resolved_model()); |
| 7143 | for column in [ |
| 7144 | ModelSortColumn::Model, |
| 7145 | ModelSortColumn::Provider, |
| 7146 | ModelSortColumn::Context, |
| 7147 | ] { |
| 7148 | for descending in [false, true] { |
| 7149 | render_text(&picker, 150, 42); |
| 7150 | let rect = picker |
| 7151 | .column_hitboxes |
| 7152 | .borrow() |
| 7153 | .iter() |
| 7154 | .find(|(_, target)| *target == column) |
| 7155 | .unwrap() |
| 7156 | .0; |
| 7157 | picker.handle_mouse(MouseEvent { |
| 7158 | kind: MouseEventKind::Down(MouseButton::Left), |
| 7159 | column: rect.x, |
| 7160 | row: rect.y, |
| 7161 | modifiers: KeyModifiers::NONE, |
| 7162 | }); |
| 7163 | assert_eq!(picker.sort, Some(ModelSort { column, descending })); |
| 7164 | assert_eq!( |
| 7165 | picker.focus, |
| 7166 | Pane::Model, |
| 7167 | "header click must focus the Model pane" |
| 7168 | ); |
| 7169 | assert_eq!( |
| 7170 | (picker.resolved_provider(), picker.resolved_model()), |
| 7171 | selected |
| 7172 | ); |
| 7173 | let visible = picker.visible_model_rows(); |
| 7174 | let rows: Vec<_> = visible |
| 7175 | .iter() |
| 7176 | .filter(|row| row.provider.is_some()) |
| 7177 | .collect(); |
| 7178 | if column == ModelSortColumn::Context { |
| 7179 | let mut unknown = false; |
| 7180 | let mut previous = None; |
| 7181 | for row in rows { |
| 7182 | match row.metadata.context_window { |
| 7183 | None => unknown = true, |
| 7184 | Some(context) => { |
| 7185 | assert!(!unknown, "unknown context must stay last"); |
| 7186 | if let Some(previous) = previous { |
| 7187 | assert!(if descending { |
| 7188 | previous >= context |
| 7189 | } else { |
| 7190 | previous <= context |
| 7191 | }); |
| 7192 | } |
| 7193 | previous = Some(context); |
| 7194 | } |
| 7195 | } |
| 7196 | } |
| 7197 | } |
| 7198 | } |
| 7199 | } |
| 7200 | picker.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); |
| 7201 | assert_eq!(picker.sort, None, "cycle returns to default view/pin order"); |
| 7202 | picker.update_query("openrouter".to_string()); |
| 7203 | assert!( |
| 7204 | picker |
| 7205 | .visible_model_rows() |
| 7206 | .iter() |
| 7207 | .all(|row| row.provider == Some(ProviderKind::Openrouter)) |
| 7208 | ); |
| 7209 | assert_eq!( |
| 7210 | picker.projection.borrow().as_ref().unwrap().query, |
| 7211 | "openrouter" |
| 7212 | ); |
| 7213 | picker.update_query(String::new()); |
| 7214 | assert_eq!(picker.model_row_count(), count); |
| 7215 | let selected = (picker.resolved_provider(), picker.resolved_model()); |
| 7216 | app.pinned_models.push(PinnedModel { |
| 7217 | provider: "openrouter".into(), |
| 7218 | model: "z-ai/glm-5.3-flash".into(), |
| 7219 | label: None, |
| 7220 | }); |
| 7221 | picker.re_resolve_from_app(&app, &config); |
| 7222 | assert_eq!(picker.visible_model_rows()[0].id, "z-ai/glm-5.3-flash"); |
| 7223 | assert_eq!( |
| 7224 | (picker.resolved_provider(), picker.resolved_model()), |
| 7225 | selected |
| 7226 | ); |
| 7227 | |
| 7228 | // A real catalog/readiness refresh replaces cached presentation facts. |
| 7229 | let mut offering = codewhale_engine::provider_lake::catalog_offering_for_model( |
| 7230 | ProviderKind::Deepseek, |
| 7231 | "deepseek-v4-pro", |
| 7232 | ) |
| 7233 | .unwrap(); |
| 7234 | offering.limit.as_mut().unwrap().context = Some(777_000); |
| 7235 | codewhale_engine::provider_lake::set_live_snapshot( |
| 7236 | codewhale_config::catalog::CatalogSnapshot { |
| 7237 | offerings: vec![offering], |
| 7238 | }, |
| 7239 | codewhale_engine::provider_lake::LiveSource::ModelsDev, |
| 7240 | ); |
| 7241 | picker.re_resolve_from_app(&app, &config); |
| 7242 | let visible = picker.visible_model_rows(); |
| 7243 | let row = visible |
| 7244 | .iter() |
| 7245 | .find(|row| row.provider == Some(ProviderKind::Deepseek) && row.id == "deepseek-v4-pro") |
| 7246 | .unwrap(); |
| 7247 | assert_eq!(row.metadata.context_window, Some(777_000)); |
| 7248 | let index = visible |
| 7249 | .iter() |
| 7250 | .position(|row| { |
| 7251 | row.provider == Some(ProviderKind::Deepseek) && row.id == "deepseek-v4-pro" |
| 7252 | }) |
| 7253 | .unwrap(); |
| 7254 | assert!( |
| 7255 | picker.projection.borrow().as_ref().unwrap().rows[index] |
| 7256 | .meta |
| 7257 | .contains(&format_context_window(777_000)) |
| 7258 | ); |
| 7259 | } |
| 7260 | |
| 7261 | #[test] |
| 7262 | fn family_heading_viewport_reserves_the_selected_row_before_hitboxes() { |
| 7263 | let rows: Vec<_> = (0..32) |
| 7264 | .map(|index| PaneRow { |
| 7265 | primary: format!("model-{index}"), |
| 7266 | route: format!("provider-{index}"), |
| 7267 | group: Some(format!("family-{index}")), |
| 7268 | ..PaneRow::default() |
| 7269 | }) |
| 7270 | .collect(); |
| 7271 | for height in 1..12 { |
| 7272 | for selected in 0..rows.len() { |
| 7273 | let (start, end) = pane_row_window(selected, &rows, height); |
| 7274 | assert!( |
| 7275 | start <= selected && selected < end, |
| 7276 | "{start}..{end} omits {selected} at height {height}" |
| 7277 | ); |
| 7278 | let lines: usize = (start..end) |
| 7279 | .map(|index| 1 + usize::from(height > 1 && group_header_before(&rows, index))) |
| 7280 | .sum(); |
| 7281 | assert!(lines <= height); |
| 7282 | } |
| 7283 | } |
| 7284 | } |
| 7285 | |
| 7286 | #[test] |
| 7287 | fn baseten_picker_models_use_exact_identity_and_direct_provider_label() { |
| 7288 | let _env = crate::test_support::lock_test_env(); |
| 7289 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 7290 | let home = tempfile::tempdir().expect("test home"); |
| 7291 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 7292 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7293 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7294 | |
| 7295 | // No compiled seeds: a custom route offers nothing until a live |
| 7296 | // listing lands for its exact endpoint (#6289). |
| 7297 | assert!( |
| 7298 | provider_catalog_model_ids( |
| 7299 | ProviderKind::Custom, |
| 7300 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 7301 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 7302 | ) |
| 7303 | .is_empty() |
| 7304 | ); |
| 7305 | |
| 7306 | let fingerprint = codewhale_config::catalog::base_url_fingerprint( |
| 7307 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 7308 | ); |
| 7309 | codewhale_engine::provider_catalog_live::record_success( |
| 7310 | codewhale_config::catalog::ProviderCatalogDelta { |
| 7311 | provider: codewhale_config::catalog::BASETEN_PROVIDER_ID.to_string(), |
| 7312 | base_url_fingerprint: fingerprint.clone(), |
| 7313 | fetched_at: 1, |
| 7314 | offerings: vec![codewhale_config::catalog::CatalogOffering { |
| 7315 | provider: codewhale_config::catalog::BASETEN_PROVIDER_ID.to_string(), |
| 7316 | wire_model_id: codewhale_config::catalog::BASETEN_DEFAULT_MODEL.to_string(), |
| 7317 | endpoint_key: "chat".to_string(), |
| 7318 | source: CatalogSource::Live { |
| 7319 | base_url_fingerprint: fingerprint, |
| 7320 | fetched_at: 1, |
| 7321 | }, |
| 7322 | ..Default::default() |
| 7323 | }], |
| 7324 | }, |
| 7325 | ); |
| 7326 | |
| 7327 | let models = provider_catalog_model_ids( |
| 7328 | ProviderKind::Custom, |
| 7329 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 7330 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 7331 | ); |
| 7332 | assert_eq!( |
| 7333 | models, |
| 7334 | vec![codewhale_config::catalog::BASETEN_DEFAULT_MODEL.to_string()] |
| 7335 | ); |
| 7336 | |
| 7337 | let row = ModelPickerRow { |
| 7338 | id: codewhale_config::catalog::BASETEN_DEFAULT_MODEL.to_string(), |
| 7339 | provider: Some(ProviderKind::Custom), |
| 7340 | provider_identity: Some(codewhale_config::catalog::BASETEN_PROVIDER_ID.to_string()), |
| 7341 | admitted_identity: None, |
| 7342 | route_selection: None, |
| 7343 | hint: String::new(), |
| 7344 | metadata: EffectivePickerMetadata::default(), |
| 7345 | selectable: true, |
| 7346 | blocked_reason: None, |
| 7347 | default_rank: None, |
| 7348 | credentialed: false, |
| 7349 | not_listed: None, |
| 7350 | external_agent: None, |
| 7351 | }; |
| 7352 | let labels = route_labels_for_rows(&[&row]); |
| 7353 | // No compiled display names: the route label is the table key itself. |
| 7354 | assert_eq!(labels.get("baseten").map(String::as_str), Some("baseten")); |
| 7355 | } |
| 7356 | |
| 7357 | #[test] |
| 7358 | fn provider_catalog_hint_never_calls_failed_or_mismatched_rows_live() { |
| 7359 | assert_eq!( |
| 7360 | provider_catalog_source_label(Some(&(CatalogStatus::Fresh, true))), |
| 7361 | "live" |
| 7362 | ); |
| 7363 | assert_eq!( |
| 7364 | provider_catalog_source_label(Some(&( |
| 7365 | CatalogStatus::Failed { |
| 7366 | reason: CatalogRefreshError::Unauthorized, |
| 7367 | }, |
| 7368 | true, |
| 7369 | ))), |
| 7370 | "refresh failed (unauthorized)" |
| 7371 | ); |
| 7372 | assert_eq!( |
| 7373 | provider_catalog_source_label(Some(&(CatalogStatus::Fresh, false))), |
| 7374 | "catalog from different endpoint" |
| 7375 | ); |
| 7376 | assert_eq!( |
| 7377 | provider_catalog_source_label(None), |
| 7378 | "catalog freshness unknown" |
| 7379 | ); |
| 7380 | } |
| 7381 | |
| 7382 | #[test] |
| 7383 | fn first_provider_catalog_failure_is_visible_on_bundled_fallback_rows() { |
| 7384 | let _env = crate::test_support::lock_test_env(); |
| 7385 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 7386 | let home = tempfile::tempdir().expect("test home"); |
| 7387 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 7388 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7389 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7390 | |
| 7391 | let config = { |
| 7392 | let __cw_config_init_0_0 = Some("openrouter".to_string()); |
| 7393 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 7394 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 7395 | __cw_config_init_0_value |
| 7396 | }; |
| 7397 | let identity = config.test_identity_for_kind(ProviderKind::Openrouter); |
| 7398 | let base_url = config.base_url_for_route(&identity); |
| 7399 | let fingerprint = codewhale_config::catalog::base_url_fingerprint(&base_url); |
| 7400 | let ticket = codewhale_engine::provider_catalog_live::begin_scoped_refresh( |
| 7401 | &config, &identity, &base_url, |
| 7402 | ) |
| 7403 | .expect("bind the OpenRouter refresh"); |
| 7404 | assert_eq!( |
| 7405 | codewhale_engine::provider_catalog_live::record_failure_if_current( |
| 7406 | &ticket, |
| 7407 | identity.key.as_str(), |
| 7408 | &fingerprint, |
| 7409 | CatalogRefreshError::Unauthorized, |
| 7410 | ), |
| 7411 | Some(CatalogStatus::Failed { |
| 7412 | reason: CatalogRefreshError::Unauthorized, |
| 7413 | }) |
| 7414 | ); |
| 7415 | |
| 7416 | let model = provider_catalog_model_ids(identity.provider, identity.key.as_str(), &base_url) |
| 7417 | .into_iter() |
| 7418 | .next() |
| 7419 | .expect("bundled OpenRouter fallback"); |
| 7420 | let mut rows = Vec::new(); |
| 7421 | let codex_roster = CodexModelRoster { |
| 7422 | models: Vec::new(), |
| 7423 | freshness: CodexModelCacheFreshness::Missing, |
| 7424 | fetched_at: None, |
| 7425 | observed_at: None, |
| 7426 | observation_persisted: false, |
| 7427 | source: "codex_cli_cache", |
| 7428 | }; |
| 7429 | push_provider_model_rows( |
| 7430 | &mut rows, |
| 7431 | &identity, |
| 7432 | vec![model.clone()], |
| 7433 | ProviderKind::Openrouter, |
| 7434 | &config, |
| 7435 | &codex_roster, |
| 7436 | &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(), |
| 7437 | ); |
| 7438 | let row = rows.iter().find(|row| row.id == model).unwrap(); |
| 7439 | assert!(row.hint.contains("bundled"), "{}", row.hint); |
| 7440 | assert!( |
| 7441 | row.hint.contains("refresh failed (unauthorized)"), |
| 7442 | "{}", |
| 7443 | row.hint |
| 7444 | ); |
| 7445 | |
| 7446 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7447 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7448 | } |
| 7449 | |
| 7450 | #[test] |
| 7451 | fn same_model_on_distinct_custom_routes_keeps_readiness_and_applied_identity() { |
| 7452 | let _env = crate::test_support::lock_test_env(); |
| 7453 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 7454 | let (config, app, home, _workspace) = resumed_openrouter_session_with_named_custom_routes(); |
| 7455 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 7456 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7457 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7458 | |
| 7459 | const MODEL: &str = "deepseek/deepseek-v4-flash"; |
| 7460 | let mut picker = ModelPickerView::new(&app, &config); |
| 7461 | // The uncredentialed route is outside the default view (#6533); the |
| 7462 | // full catalog lists both. |
| 7463 | picker.view = ModelListView::Catalog; |
| 7464 | *picker.projection.get_mut() = None; |
| 7465 | let shared: Vec<(usize, Option<String>, bool)> = picker |
| 7466 | .visible_model_rows() |
| 7467 | .iter() |
| 7468 | .enumerate() |
| 7469 | .filter(|(_, row)| row.provider == Some(ProviderKind::Custom) && row.id == MODEL) |
| 7470 | .map(|(index, row)| (index, row.provider_identity.clone(), row.selectable)) |
| 7471 | .collect(); |
| 7472 | assert_eq!( |
| 7473 | shared.len(), |
| 7474 | 2, |
| 7475 | "one shared model id on two routes must not collapse: {shared:?}" |
| 7476 | ); |
| 7477 | |
| 7478 | for (index, identity, selectable) in shared { |
| 7479 | let identity = identity.expect("custom rows carry their exact route identity"); |
| 7480 | // Each route is judged by its own table: only the credentialed one |
| 7481 | // can be attempted, even though neither is the selected provider. |
| 7482 | assert_eq!( |
| 7483 | selectable, |
| 7484 | identity == "command_code", |
| 7485 | "{identity} readiness must come from its own route" |
| 7486 | ); |
| 7487 | picker.selected_model_idx = index; |
| 7488 | match picker.build_apply_event(false) { |
| 7489 | ViewEvent::ModelPickerApplied { |
| 7490 | model, |
| 7491 | identity: admitted, |
| 7492 | .. |
| 7493 | } => { |
| 7494 | assert_eq!(model, MODEL); |
| 7495 | let admitted = admitted.expect("selected row carries its exact admitted route"); |
| 7496 | assert_eq!(admitted.provider, ProviderKind::Custom); |
| 7497 | assert_eq!( |
| 7498 | admitted.persisted_id(), |
| 7499 | Some(identity.as_str()), |
| 7500 | "applying a row must switch to the route that row describes" |
| 7501 | ); |
| 7502 | } |
| 7503 | other => panic!("unexpected picker event: {other:?}"), |
| 7504 | } |
| 7505 | } |
| 7506 | |
| 7507 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7508 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7509 | } |
| 7510 | |
| 7511 | #[test] |
| 7512 | fn model_rows_keep_case_distinct_custom_identities() { |
| 7513 | let mut rows = Vec::new(); |
| 7514 | for identity in ["CustomA", "customa"] { |
| 7515 | push_model_row( |
| 7516 | &mut rows, |
| 7517 | "shared-model".to_string(), |
| 7518 | Some(ProviderKind::Custom), |
| 7519 | Some(identity.to_string()), |
| 7520 | String::new(), |
| 7521 | EffectivePickerMetadata::default(), |
| 7522 | true, |
| 7523 | None, |
| 7524 | ); |
| 7525 | } |
| 7526 | assert_eq!(rows.len(), 2); |
| 7527 | } |
| 7528 | |
| 7529 | /// #6016 fixture: a session resumed on OpenRouter while two named custom |
| 7530 | /// routes are configured, neither of them the config's selected provider. |
| 7531 | fn resumed_openrouter_session_with_named_custom_routes() |
| 7532 | -> (Config, App, tempfile::TempDir, tempfile::TempDir) { |
| 7533 | let config: Config = toml::from_str( |
| 7534 | r#" |
| 7535 | provider = "openrouter" |
| 7536 | |
| 7537 | [providers.openrouter] |
| 7538 | api_key = "fixture-openrouter-key" |
| 7539 | |
| 7540 | [providers.command_code] |
| 7541 | kind = "openai-compatible" |
| 7542 | base_url = "https://command.example.test/v1" |
| 7543 | model = "deepseek/deepseek-v4-flash" |
| 7544 | api_key = "fixture-command-key" |
| 7545 | |
| 7546 | # Same model id on a second route, deliberately without credentials: the two |
| 7547 | # routes must stay separate rows with separate readiness. |
| 7548 | [providers.other_code] |
| 7549 | kind = "openai-compatible" |
| 7550 | base_url = "https://other.example.test/v1" |
| 7551 | model = "deepseek/deepseek-v4-flash" |
| 7552 | "#, |
| 7553 | ) |
| 7554 | .expect("named custom fixture"); |
| 7555 | |
| 7556 | let home = tempfile::tempdir().expect("test home"); |
| 7557 | let workspace = tempfile::tempdir().expect("test workspace"); |
| 7558 | let options = crate::tui::test_support::test_tui_options(workspace.path()); |
| 7559 | let mut app = App::new(options, &config); |
| 7560 | // The resumed session stays on the provider it was created with. |
| 7561 | app.api_provider = ProviderKind::Openrouter; |
| 7562 | app.provider_identity = Some( |
| 7563 | config |
| 7564 | .builtin_provider_identity(ProviderKind::Openrouter) |
| 7565 | .unwrap(), |
| 7566 | ); |
| 7567 | app.model = "z-ai/glm-5.3".to_string(); |
| 7568 | app.active_route_base_url = |
| 7569 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL.to_string(); |
| 7570 | (config, app, home, workspace) |
| 7571 | } |
| 7572 | |
| 7573 | /// A custom relay's roster exists only in the listing that route itself |
| 7574 | /// answered, so nothing else can fill its rows in. Filtering every one of |
| 7575 | /// them out of the default view left `/model` showing a single row for a |
| 7576 | /// route the provider panel had just listed a dozen for. |
| 7577 | #[test] |
| 7578 | fn a_custom_relays_live_roster_reaches_the_default_view() { |
| 7579 | let _env = crate::test_support::lock_test_env(); |
| 7580 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 7581 | let (config, app, home, _workspace) = resumed_openrouter_session_with_named_custom_routes(); |
| 7582 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 7583 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7584 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7585 | |
| 7586 | // The listing the relay answered, recorded the way the probe records |
| 7587 | // it. `command_code` is not the session's route, so the row can only |
| 7588 | // reach the default view through the relay-roster rule. |
| 7589 | let identity = config |
| 7590 | .resolve_provider_selection_identity("command_code") |
| 7591 | .expect("custom relay route"); |
| 7592 | let base_url = config.base_url_for_route(&identity); |
| 7593 | let fingerprint = codewhale_config::catalog::base_url_fingerprint(&base_url); |
| 7594 | let ticket = codewhale_engine::provider_catalog_live::begin_scoped_refresh( |
| 7595 | &config, &identity, &base_url, |
| 7596 | ) |
| 7597 | .expect("bind the relay refresh"); |
| 7598 | let offering = |id: &str| codewhale_config::catalog::CatalogOffering { |
| 7599 | provider: "command_code".to_string(), |
| 7600 | wire_model_id: id.to_string(), |
| 7601 | source: codewhale_config::catalog::CatalogSource::Live { |
| 7602 | base_url_fingerprint: fingerprint.clone(), |
| 7603 | fetched_at: 7, |
| 7604 | }, |
| 7605 | ..Default::default() |
| 7606 | }; |
| 7607 | let roster: Vec<_> = (0..ROUTE_ROSTER_ROWS_IN_DEFAULT_VIEW + 5) |
| 7608 | .map(|index| offering(&format!("relay-{index}"))) |
| 7609 | .collect(); |
| 7610 | codewhale_engine::provider_catalog_live::record_success_if_current( |
| 7611 | &ticket, |
| 7612 | codewhale_config::catalog::ProviderCatalogDelta { |
| 7613 | provider: "command_code".to_string(), |
| 7614 | base_url_fingerprint: fingerprint, |
| 7615 | fetched_at: 7, |
| 7616 | offerings: roster, |
| 7617 | }, |
| 7618 | ) |
| 7619 | .expect("the relay listing is recorded"); |
| 7620 | |
| 7621 | let picker = ModelPickerView::new(&app, &config); |
| 7622 | assert_eq!(picker.view, ModelListView::Configured); |
| 7623 | let visible: Vec<_> = picker |
| 7624 | .visible_model_rows() |
| 7625 | .iter() |
| 7626 | .filter(|row| { |
| 7627 | row.provider == Some(ProviderKind::Custom) |
| 7628 | && row_provider_identity(row) == Some("command_code") |
| 7629 | && row.id.starts_with("relay-") |
| 7630 | }) |
| 7631 | .map(|row| row.id.clone()) |
| 7632 | .collect(); |
| 7633 | assert_eq!( |
| 7634 | visible.len(), |
| 7635 | ROUTE_ROSTER_ROWS_IN_DEFAULT_VIEW, |
| 7636 | "the relay's own roster shows in the default view, bounded per route: {visible:?}" |
| 7637 | ); |
| 7638 | assert!( |
| 7639 | visible.contains(&"relay-0".to_string()), |
| 7640 | "the first listed row is offered: {visible:?}" |
| 7641 | ); |
| 7642 | } |
| 7643 | |
| 7644 | #[test] |
| 7645 | fn resumed_session_lists_every_configured_custom_route_by_identity() { |
| 7646 | let _env = crate::test_support::lock_test_env(); |
| 7647 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 7648 | let (config, app, home, _workspace) = resumed_openrouter_session_with_named_custom_routes(); |
| 7649 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 7650 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7651 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7652 | |
| 7653 | let rows = picker_model_rows_for_app(&app, &config); |
| 7654 | let custom: Vec<_> = rows |
| 7655 | .iter() |
| 7656 | .filter(|row| row.provider == Some(ProviderKind::Custom)) |
| 7657 | .collect(); |
| 7658 | let identities: Vec<_> = custom |
| 7659 | .iter() |
| 7660 | .filter_map(|row| row.provider_identity.as_deref()) |
| 7661 | .collect(); |
| 7662 | assert!( |
| 7663 | identities.contains(&"command_code"), |
| 7664 | "configured custom route B must stay visible in a resumed session: {custom:#?}" |
| 7665 | ); |
| 7666 | assert!( |
| 7667 | identities.contains(&"other_code"), |
| 7668 | "every configured custom route keeps its own rows: {custom:#?}" |
| 7669 | ); |
| 7670 | // A credentialed custom route offers its configured model by |
| 7671 | // default; one without credentials stays behind search (#6533). |
| 7672 | for (identity, visible) in [("command_code", true), ("other_code", false)] { |
| 7673 | let row = custom |
| 7674 | .iter() |
| 7675 | .find(|row| { |
| 7676 | row.provider_identity.as_deref() == Some(identity) |
| 7677 | && row.id == "deepseek/deepseek-v4-flash" |
| 7678 | }) |
| 7679 | .unwrap_or_else(|| panic!("{identity} row missing: {custom:#?}")); |
| 7680 | assert_eq!( |
| 7681 | model_row_visible_by_default(row), |
| 7682 | visible, |
| 7683 | "{identity} default-view visibility: {row:#?}" |
| 7684 | ); |
| 7685 | } |
| 7686 | |
| 7687 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7688 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7689 | } |
| 7690 | |
| 7691 | #[test] |
| 7692 | fn shared_custom_model_opens_on_exact_active_route_despite_other_route_pin() { |
| 7693 | let _env = crate::test_support::lock_test_env(); |
| 7694 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 7695 | let (mut config, mut app, home, _workspace) = |
| 7696 | resumed_openrouter_session_with_named_custom_routes(); |
| 7697 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 7698 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7699 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7700 | |
| 7701 | const MODEL: &str = "deepseek/deepseek-v4-flash"; |
| 7702 | config.provider = Some("other_code".to_string()); |
| 7703 | config |
| 7704 | .providers |
| 7705 | .as_mut() |
| 7706 | .unwrap() |
| 7707 | .custom |
| 7708 | .get_mut("other_code") |
| 7709 | .unwrap() |
| 7710 | .api_key = Some("fixture-other-key".to_string()); |
| 7711 | app.set_provider_identity(ProviderKind::Custom, "other_code"); |
| 7712 | app.set_model_selection(MODEL.to_string()); |
| 7713 | app.active_route_base_url = "https://other.example.test/v1".to_string(); |
| 7714 | app.pinned_models = vec![PinnedModel { |
| 7715 | provider: "command_code".to_string(), |
| 7716 | model: MODEL.to_string(), |
| 7717 | label: None, |
| 7718 | }]; |
| 7719 | |
| 7720 | // Opening a picker must keep the current route even if a different |
| 7721 | // credentialed route exposing the same wire model sorts first. |
| 7722 | let mut picker = ModelPickerView::new(&app, &config); |
| 7723 | assert_eq!( |
| 7724 | picker.resolved_provider_identity().as_deref(), |
| 7725 | Some("other_code") |
| 7726 | ); |
| 7727 | picker.ensure_projection(); |
| 7728 | { |
| 7729 | let projection = picker.projection.borrow(); |
| 7730 | let rows = &projection.as_ref().unwrap().rows; |
| 7731 | assert!(rows.iter().any(|row| row.route == "command_code")); |
| 7732 | assert!(rows.iter().any(|row| row.route == "other_code")); |
| 7733 | let active: Vec<_> = rows.iter().filter(|row| row.active).collect(); |
| 7734 | assert_eq!(active.len(), 1); |
| 7735 | assert_eq!(active[0].route, "other_code"); |
| 7736 | } |
| 7737 | let rendered = render_text(&picker, 140, 40); |
| 7738 | assert!(rendered.contains("command_code"), "{rendered}"); |
| 7739 | assert!(rendered.contains("other_code"), "{rendered}"); |
| 7740 | |
| 7741 | // Legacy memory has no route identity; ambiguity must preserve the |
| 7742 | // active route instead of resurrecting the first same-named model. |
| 7743 | picker.restore_memory(Some(&crate::tui::app::ModelPickerMemory { |
| 7744 | catalog_view: true, |
| 7745 | view: Some("catalog".to_string()), |
| 7746 | selected_row_id: Some(MODEL.to_string()), |
| 7747 | })); |
| 7748 | assert!(matches!( |
| 7749 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 7750 | ViewAction::EmitAndClose(ViewEvent::ModelPickerApplied { |
| 7751 | identity: Some(identity), |
| 7752 | model, |
| 7753 | save_as_startup_default: false, |
| 7754 | .. |
| 7755 | }) if identity.persisted_id() == Some("other_code") && model == MODEL |
| 7756 | )); |
| 7757 | assert!(matches!( |
| 7758 | picker.build_event_with_startup_default(true, None), |
| 7759 | ViewEvent::ModelPickerApplied { |
| 7760 | identity: Some(identity), |
| 7761 | save_as_startup_default: true, |
| 7762 | .. |
| 7763 | } if identity.persisted_id() == Some("other_code") |
| 7764 | )); |
| 7765 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7766 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7767 | } |
| 7768 | |
| 7769 | #[test] |
| 7770 | fn locked_custom_model_names_exact_auth_route_without_opening_another_key_editor() { |
| 7771 | let mut picker = test_picker(); |
| 7772 | let mut row = model_row(ProviderKind::Custom, true); |
| 7773 | row.provider_identity = Some("other_code".to_string()); |
| 7774 | row.selectable = false; |
| 7775 | picker.model_rows = vec![row]; |
| 7776 | assert!(matches!( |
| 7777 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 7778 | ViewAction::Emit(ViewEvent::StatusToast { |
| 7779 | message, |
| 7780 | level: crate::tui::app::StatusToastLevel::Error, |
| 7781 | }) if message.contains("other_code/model") |
| 7782 | && message.contains("Open /provider and select other_code") |
| 7783 | )); |
| 7784 | |
| 7785 | // Built-in providers retain their existing guided-auth handoff. |
| 7786 | let mut picker = test_picker(); |
| 7787 | picker.model_rows[0].selectable = false; |
| 7788 | assert!(matches!( |
| 7789 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 7790 | ViewAction::Emit(ViewEvent::ModelPickerNeedsAuth { |
| 7791 | identity, |
| 7792 | .. |
| 7793 | }) if identity.provider == ProviderKind::Openai |
| 7794 | )); |
| 7795 | } |
| 7796 | |
| 7797 | /// #6533 fixture shaped like the founder's state: a legacy |
| 7798 | /// `[enabled_models]` GLM-5.2, a leftover OpenRouter test model, recent |
| 7799 | /// use of models no config names, and a Fleet pin on a provider with no |
| 7800 | /// configured model. |
| 7801 | fn founder_shaped_app(home: &std::path::Path, workspace: &std::path::Path) -> (Config, App) { |
| 7802 | let settings_path = codewhale_runtime::settings::Settings::path().expect("settings path"); |
| 7803 | std::fs::create_dir_all(settings_path.parent().unwrap()).unwrap(); |
| 7804 | std::fs::write( |
| 7805 | &settings_path, |
| 7806 | "[enabled_models]\nzai = [\"GLM-5.2\", \"GLM-5.3\"]\n", |
| 7807 | ) |
| 7808 | .unwrap(); |
| 7809 | assert!(settings_path.starts_with(home)); |
| 7810 | codewhale_engine::fleet::members::add_fleet_model( |
| 7811 | workspace, |
| 7812 | "xai", |
| 7813 | "grok-4.6", |
| 7814 | &["reviewer".to_string()], |
| 7815 | ) |
| 7816 | .expect("fleet add"); |
| 7817 | let config: Config = toml::from_str( |
| 7818 | r#" |
| 7819 | provider = "deepseek" |
| 7820 | |
| 7821 | [providers.deepseek] |
| 7822 | api_key = "fixture-deepseek-key" |
| 7823 | model = "deepseek-flash" |
| 7824 | |
| 7825 | [providers.openrouter] |
| 7826 | api_key = "fixture-openrouter-key" |
| 7827 | model = "stealth/ox-alpha" |
| 7828 | |
| 7829 | [providers.zai] |
| 7830 | api_key = "fixture-zai-key" |
| 7831 | model = "GLM-5.3" |
| 7832 | |
| 7833 | [providers.xai] |
| 7834 | api_key = "fixture-xai-key" |
| 7835 | "#, |
| 7836 | ) |
| 7837 | .expect("founder fixture"); |
| 7838 | let mut app = App::new( |
| 7839 | crate::tui::test_support::test_tui_options(workspace), |
| 7840 | &config, |
| 7841 | ); |
| 7842 | app.workspace = workspace.to_path_buf(); |
| 7843 | app.api_provider = ProviderKind::Deepseek; |
| 7844 | app.provider_identity = Some( |
| 7845 | config |
| 7846 | .builtin_provider_identity(ProviderKind::Deepseek) |
| 7847 | .unwrap(), |
| 7848 | ); |
| 7849 | app.auto_model = false; |
| 7850 | app.model = "deepseek-flash".to_string(); |
| 7851 | app.provider_models |
| 7852 | .insert("deepseek".to_string(), "deepseek-flash".to_string()); |
| 7853 | let now = chrono::Utc::now(); |
| 7854 | let mut usage = app.route_usage.write().unwrap(); |
| 7855 | usage.record("xai", "grok-4.7", now); |
| 7856 | usage.record("zai", "GLM-5.3", now - chrono::Duration::days(8)); |
| 7857 | usage.record("deepseek", "deepseek-flash", now); |
| 7858 | drop(usage); |
| 7859 | (config, app) |
| 7860 | } |
| 7861 | |
| 7862 | fn default_view(picker: &ModelPickerView) -> Vec<(String, String, Option<DefaultSection>)> { |
| 7863 | picker |
| 7864 | .visible_model_rows() |
| 7865 | .iter() |
| 7866 | .filter(|row| row.provider.is_some()) |
| 7867 | .map(|row| { |
| 7868 | ( |
| 7869 | row_provider_identity(row).unwrap_or_default().to_string(), |
| 7870 | row.id.clone(), |
| 7871 | row.default_rank.map(|(section, _)| section), |
| 7872 | ) |
| 7873 | }) |
| 7874 | .collect() |
| 7875 | } |
| 7876 | |
| 7877 | #[test] |
| 7878 | fn default_view_ranks_by_use_and_keeps_the_long_tail_behind_search() { |
| 7879 | std::thread::Builder::new() |
| 7880 | .stack_size(16 * 1024 * 1024) |
| 7881 | .spawn(|| { |
| 7882 | let _env = crate::test_support::lock_test_env(); |
| 7883 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 7884 | let root = tempfile::tempdir().unwrap(); |
| 7885 | let home = root.path().join("home"); |
| 7886 | let workspace = root.path().join("repo"); |
| 7887 | std::fs::create_dir_all(&workspace).unwrap(); |
| 7888 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 7889 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 7890 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 7891 | let (config, app) = founder_shaped_app(&home, &workspace); |
| 7892 | |
| 7893 | let mut picker = ModelPickerView::new(&app, &config); |
| 7894 | assert_eq!(picker.view, ModelListView::Configured); |
| 7895 | let rows = default_view(&picker); |
| 7896 | let sections: Vec<_> = rows.iter().map(|(_, _, section)| *section).collect(); |
| 7897 | let mut sorted = sections.clone(); |
| 7898 | sorted.sort(); |
| 7899 | assert_eq!(sections, sorted, "sections render in order: {rows:#?}"); |
| 7900 | assert_eq!( |
| 7901 | rows[0], |
| 7902 | ( |
| 7903 | "deepseek".to_string(), |
| 7904 | "deepseek-flash".to_string(), |
| 7905 | Some(DefaultSection::Current) |
| 7906 | ), |
| 7907 | "{rows:#?}" |
| 7908 | ); |
| 7909 | assert_eq!( |
| 7910 | rows[1], |
| 7911 | ( |
| 7912 | "xai".to_string(), |
| 7913 | "grok-4.6".to_string(), |
| 7914 | Some(DefaultSection::Pinned) |
| 7915 | ), |
| 7916 | "a Fleet pin shows although xai names no model: {rows:#?}" |
| 7917 | ); |
| 7918 | let grok_46 = picker |
| 7919 | .visible_model_rows() |
| 7920 | .iter() |
| 7921 | .find(|row| row.id == "grok-4.6") |
| 7922 | .unwrap() |
| 7923 | .hint |
| 7924 | .clone(); |
| 7925 | assert!(grok_46.starts_with("fleet · "), "{grok_46}"); |
| 7926 | assert_eq!( |
| 7927 | rows[2], |
| 7928 | ( |
| 7929 | "xai".to_string(), |
| 7930 | "grok-4.7".to_string(), |
| 7931 | Some(DefaultSection::Recent) |
| 7932 | ), |
| 7933 | "{rows:#?}" |
| 7934 | ); |
| 7935 | assert_eq!( |
| 7936 | (rows[3].1.as_str(), rows[3].2), |
| 7937 | ("GLM-5.3", Some(DefaultSection::Recent)), |
| 7938 | "{rows:#?}" |
| 7939 | ); |
| 7940 | for hidden in ["glm-5.2", "stealth/ox-alpha"] { |
| 7941 | assert!( |
| 7942 | !rows |
| 7943 | .iter() |
| 7944 | .any(|(_, id, _)| id.eq_ignore_ascii_case(hidden)), |
| 7945 | "{hidden} has no use and must stay out of the default view: {rows:#?}" |
| 7946 | ); |
| 7947 | } |
| 7948 | for (identity, _, _) in &rows { |
| 7949 | assert!( |
| 7950 | rows.iter() |
| 7951 | .filter(|(other, _, section)| other == identity |
| 7952 | && *section == Some(DefaultSection::ProviderDefault)) |
| 7953 | .count() |
| 7954 | <= 1, |
| 7955 | "at most one default per provider: {rows:#?}" |
| 7956 | ); |
| 7957 | } |
| 7958 | assert!( |
| 7959 | rows.iter() |
| 7960 | .any(|(identity, id, section)| identity == "deepseek" |
| 7961 | && id == "deepseek-v4-pro" |
| 7962 | && *section == Some(DefaultSection::Roster)), |
| 7963 | "the active provider's roster is listed: {rows:#?}" |
| 7964 | ); |
| 7965 | |
| 7966 | picker.update_query("GLM-5.2".to_string()); |
| 7967 | assert!( |
| 7968 | picker |
| 7969 | .visible_model_rows() |
| 7970 | .iter() |
| 7971 | .any(|row| row.provider == Some(ProviderKind::Zai) |
| 7972 | && row.id.eq_ignore_ascii_case("GLM-5.2")), |
| 7973 | "search still finds an unused model" |
| 7974 | ); |
| 7975 | picker.update_query("ox-alpha".to_string()); |
| 7976 | let ox = picker |
| 7977 | .visible_model_rows() |
| 7978 | .iter() |
| 7979 | .find(|row| row.id == "stealth/ox-alpha") |
| 7980 | .cloned() |
| 7981 | .expect("leftover config model is searchable"); |
| 7982 | assert_eq!(ox.not_listed, None, "no roster, no verdict"); |
| 7983 | |
| 7984 | // The Fleet picker shares the builder: the edited row leads, |
| 7985 | // then pins, recent use and defaults in the same order. |
| 7986 | let fleet = ModelPickerView::new_for_fleet_route( |
| 7987 | &app, |
| 7988 | &config, |
| 7989 | FleetRouteTarget::Member(0), |
| 7990 | uuid::Uuid::nil(), |
| 7991 | FleetRouteSelection { |
| 7992 | provider: Some("xai".to_string()), |
| 7993 | model: Some("grok-4.6".to_string()), |
| 7994 | reasoning: None, |
| 7995 | allow_inherit: true, |
| 7996 | }, |
| 7997 | ); |
| 7998 | let fleet_rows = default_view(&fleet); |
| 7999 | let sections: Vec<_> = fleet_rows.iter().map(|(_, _, section)| *section).collect(); |
| 8000 | let mut sorted = sections.clone(); |
| 8001 | sorted.sort(); |
| 8002 | assert_eq!(sections, sorted, "{fleet_rows:#?}"); |
| 8003 | assert_eq!( |
| 8004 | fleet_rows[0], |
| 8005 | ( |
| 8006 | "xai".to_string(), |
| 8007 | "grok-4.6".to_string(), |
| 8008 | Some(DefaultSection::Current) |
| 8009 | ), |
| 8010 | "{fleet_rows:#?}" |
| 8011 | ); |
| 8012 | let recent = |rows: &[(String, String, Option<DefaultSection>)]| { |
| 8013 | rows.iter() |
| 8014 | .filter(|(_, _, section)| *section == Some(DefaultSection::Recent)) |
| 8015 | .map(|(identity, id, _)| (identity.clone(), id.clone())) |
| 8016 | .collect::<Vec<_>>() |
| 8017 | }; |
| 8018 | assert_eq!( |
| 8019 | recent(&fleet_rows), |
| 8020 | [ |
| 8021 | ("deepseek".to_string(), "deepseek-flash".to_string()), |
| 8022 | ("xai".to_string(), "grok-4.7".to_string()), |
| 8023 | ("zai".to_string(), "GLM-5.3".to_string()), |
| 8024 | ], |
| 8025 | "the session's own route is ordinary recent use here: {fleet_rows:#?}" |
| 8026 | ); |
| 8027 | |
| 8028 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 8029 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 8030 | }) |
| 8031 | .unwrap() |
| 8032 | .join() |
| 8033 | .unwrap(); |
| 8034 | } |
| 8035 | |
| 8036 | #[test] |
| 8037 | fn not_listed_needs_a_fresh_roster_and_never_hides_the_row() { |
| 8038 | std::thread::Builder::new() |
| 8039 | .stack_size(16 * 1024 * 1024) |
| 8040 | .spawn(|| { |
| 8041 | let _env = crate::test_support::lock_test_env(); |
| 8042 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 8043 | let root = tempfile::tempdir().unwrap(); |
| 8044 | let home = root.path().join("home"); |
| 8045 | let workspace = root.path().join("repo"); |
| 8046 | std::fs::create_dir_all(&workspace).unwrap(); |
| 8047 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 8048 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 8049 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 8050 | let (config, mut app) = founder_shaped_app(&home, &workspace); |
| 8051 | // OpenRouter was used recently, so its leftover model is its |
| 8052 | // default row and reaches the default view. |
| 8053 | app.note_route_used("openrouter", "stealth/ox-alpha"); |
| 8054 | |
| 8055 | let roster = |provider: ProviderKind, ids: &[&str], fetched_at: u64| { |
| 8056 | let identity = config.test_identity_for_kind(provider); |
| 8057 | let base_url = config.base_url_for_route(&identity); |
| 8058 | let fingerprint = codewhale_config::catalog::base_url_fingerprint(&base_url); |
| 8059 | let ticket = codewhale_engine::provider_catalog_live::begin_scoped_refresh( |
| 8060 | &config, &identity, &base_url, |
| 8061 | ) |
| 8062 | .expect("bind the fixture roster refresh"); |
| 8063 | codewhale_engine::provider_catalog_live::record_success_if_current( |
| 8064 | &ticket, |
| 8065 | codewhale_config::catalog::ProviderCatalogDelta { |
| 8066 | provider: identity.key.to_string(), |
| 8067 | base_url_fingerprint: fingerprint.clone(), |
| 8068 | fetched_at, |
| 8069 | offerings: ids |
| 8070 | .iter() |
| 8071 | .map(|id| codewhale_config::catalog::CatalogOffering { |
| 8072 | provider: identity.key.to_string(), |
| 8073 | wire_model_id: (*id).to_string(), |
| 8074 | endpoint_key: "chat".to_string(), |
| 8075 | source: CatalogSource::Live { |
| 8076 | base_url_fingerprint: fingerprint.clone(), |
| 8077 | fetched_at, |
| 8078 | }, |
| 8079 | ..Default::default() |
| 8080 | }) |
| 8081 | .collect(), |
| 8082 | }, |
| 8083 | ) |
| 8084 | .expect("publish the fixture roster"); |
| 8085 | codewhale_engine::provider_catalog_live::status_for_route( |
| 8086 | provider, |
| 8087 | identity.key.as_str(), |
| 8088 | &base_url, |
| 8089 | ) |
| 8090 | }; |
| 8091 | let observed = chrono::Utc::now(); |
| 8092 | let now = u64::try_from(observed.timestamp()).unwrap(); |
| 8093 | // DeepSeek's roster is 15 days old and lacks the current model. |
| 8094 | assert!(matches!( |
| 8095 | roster( |
| 8096 | ProviderKind::Deepseek, |
| 8097 | &["deepseek-v4-flash", "deepseek-v4-pro"], |
| 8098 | now - 15 * 86_400 |
| 8099 | ), |
| 8100 | CatalogStatus::Stale { .. } |
| 8101 | )); |
| 8102 | let picker = ModelPickerView::new(&app, &config); |
| 8103 | let rows = picker.visible_model_rows(); |
| 8104 | let flash = rows.iter().find(|row| row.id == "deepseek-flash").unwrap(); |
| 8105 | assert_eq!(flash.not_listed, None, "a stale roster gives no verdict"); |
| 8106 | let ox = rows |
| 8107 | .iter() |
| 8108 | .find(|row| row.id == "stealth/ox-alpha") |
| 8109 | .expect("recently used route's model is in the default view"); |
| 8110 | assert_eq!(ox.not_listed, None, "no OpenRouter roster yet"); |
| 8111 | drop(rows); |
| 8112 | |
| 8113 | assert_eq!( |
| 8114 | roster(ProviderKind::Openrouter, &["openai/gpt-5"], now), |
| 8115 | CatalogStatus::Fresh |
| 8116 | ); |
| 8117 | let picker = ModelPickerView::new(&app, &config); |
| 8118 | let rows = picker.visible_model_rows(); |
| 8119 | let ox = rows |
| 8120 | .iter() |
| 8121 | .find(|row| row.id == "stealth/ox-alpha") |
| 8122 | .expect("a not-listed row is dimmed, never hidden"); |
| 8123 | let checked = observed.format("%Y-%m-%d").to_string(); |
| 8124 | assert_eq!( |
| 8125 | ox.not_listed, |
| 8126 | Some(NotListed { |
| 8127 | provider: ProviderKind::Openrouter |
| 8128 | .provider() |
| 8129 | .display_name() |
| 8130 | .to_string(), |
| 8131 | checked: checked.clone(), |
| 8132 | }) |
| 8133 | ); |
| 8134 | assert!( |
| 8135 | !ox.selectable, |
| 8136 | "fresh authoritative absence blocks selection" |
| 8137 | ); |
| 8138 | drop(rows); |
| 8139 | let text = render_text(&picker, 160, 40); |
| 8140 | assert!( |
| 8141 | text.contains(&format!("(checked {checked})")), |
| 8142 | "the reason is rendered: {text}" |
| 8143 | ); |
| 8144 | assert_eq!( |
| 8145 | config |
| 8146 | .provider_config_for( |
| 8147 | &config.test_identity_for_kind(ProviderKind::Openrouter) |
| 8148 | ) |
| 8149 | .and_then(|entry| entry.model.as_deref()), |
| 8150 | Some("stealth/ox-alpha"), |
| 8151 | "config is never rewritten" |
| 8152 | ); |
| 8153 | |
| 8154 | codewhale_engine::provider_catalog_live::reset_cache_for_test(); |
| 8155 | codewhale_engine::provider_lake::clear_live_snapshot(); |
| 8156 | }) |
| 8157 | .unwrap() |
| 8158 | .join() |
| 8159 | .unwrap(); |
| 8160 | } |
| 8161 | |
| 8162 | #[test] |
| 8163 | fn external_agents_appear_in_model_picker_with_runnable_and_blocked_reasons() { |
| 8164 | use codewhale_app_server::runtime_api::ExternalAgentDiscoveryRow; |
| 8165 | let temp = tempfile::tempdir().unwrap(); |
| 8166 | let config: Config = toml::from_str( |
| 8167 | r#"[providers.openai_codex] |
| 8168 | model = "gpt-5-codex" |
| 8169 | "#, |
| 8170 | ) |
| 8171 | .unwrap(); |
| 8172 | let options = crate::tui::app::TuiOptions { |
| 8173 | model: "deepseek-chat".to_string(), |
| 8174 | workspace: temp.path().to_path_buf(), |
| 8175 | config_path: None, |
| 8176 | config_profile: None, |
| 8177 | allow_shell: false, |
| 8178 | use_mouse_capture: false, |
| 8179 | use_bracketed_paste: false, |
| 8180 | max_subagents: 1, |
| 8181 | skills_dir: temp.path().join("skills"), |
| 8182 | memory_path: temp.path().join("memory"), |
| 8183 | mcp_config_path: temp.path().join("mcp.json"), |
| 8184 | use_memory: false, |
| 8185 | start_in_agent_mode: false, |
| 8186 | skip_onboarding: true, |
| 8187 | yolo: false, |
| 8188 | resume_session_id: None, |
| 8189 | initial_input: None, |
| 8190 | startup_notice: None, |
| 8191 | }; |
| 8192 | let mut app = App::new(options, &config); |
| 8193 | app.external_agents = vec![ |
| 8194 | ExternalAgentDiscoveryRow { |
| 8195 | id: "opencode".to_string(), |
| 8196 | name: "OpenCode".to_string(), |
| 8197 | state: "installed".to_string(), |
| 8198 | version: Some("1.20.0".to_string()), |
| 8199 | acp: Some("native".to_string()), |
| 8200 | transport: Some("acp".to_string()), |
| 8201 | transports: vec!["acp".to_string()], |
| 8202 | website: "https://opencode.ai".to_string(), |
| 8203 | min_version: Some("1.15.5".to_string()), |
| 8204 | upgrade: Some("npm i -g opencode-ai@latest".to_string()), |
| 8205 | login: Some("opencode auth login".to_string()), |
| 8206 | adapter: None, |
| 8207 | adapter_installed: false, |
| 8208 | needs_update: false, |
| 8209 | runnable: true, |
| 8210 | custom: false, |
| 8211 | reason_code: None, |
| 8212 | reason: None, |
| 8213 | }, |
| 8214 | ExternalAgentDiscoveryRow { |
| 8215 | id: "claude".to_string(), |
| 8216 | name: "Claude Agent".to_string(), |
| 8217 | state: "installed".to_string(), |
| 8218 | version: Some("2.2.0".to_string()), |
| 8219 | acp: Some("adapter".to_string()), |
| 8220 | transport: None, |
| 8221 | transports: Vec::new(), |
| 8222 | website: "https://github.com/agentclientprotocol/claude-agent-acp".to_string(), |
| 8223 | min_version: Some("2.1.226".to_string()), |
| 8224 | upgrade: None, |
| 8225 | login: Some("claude auth login".to_string()), |
| 8226 | adapter: Some("@agentclientprotocol/claude-agent-acp".to_string()), |
| 8227 | adapter_installed: false, |
| 8228 | needs_update: false, |
| 8229 | runnable: false, |
| 8230 | custom: false, |
| 8231 | reason_code: Some("adapter_missing".to_string()), |
| 8232 | reason: Some( |
| 8233 | "It runs through the ACP adapter @agentclientprotocol/claude-agent-acp, which is not installed." |
| 8234 | .to_string(), |
| 8235 | ), |
| 8236 | }, |
| 8237 | ExternalAgentDiscoveryRow { |
| 8238 | id: "copilot".to_string(), |
| 8239 | name: "GitHub Copilot CLI".to_string(), |
| 8240 | state: "not_installed".to_string(), |
| 8241 | version: None, |
| 8242 | acp: None, |
| 8243 | transport: None, |
| 8244 | transports: Vec::new(), |
| 8245 | website: "https://docs.github.com/copilot".to_string(), |
| 8246 | min_version: None, |
| 8247 | upgrade: None, |
| 8248 | login: Some("copilot login".to_string()), |
| 8249 | adapter: None, |
| 8250 | adapter_installed: false, |
| 8251 | needs_update: false, |
| 8252 | runnable: false, |
| 8253 | custom: false, |
| 8254 | reason_code: Some("not_installed".to_string()), |
| 8255 | reason: Some("GitHub Copilot CLI is not installed.".to_string()), |
| 8256 | }, |
| 8257 | ]; |
| 8258 | |
| 8259 | for (id, name) in [("antigravity", "Antigravity"), ("codex", "Codex")] { |
| 8260 | app.external_agents.push(ExternalAgentDiscoveryRow { |
| 8261 | id: id.into(), |
| 8262 | name: name.into(), |
| 8263 | ..app.external_agents[0].clone() |
| 8264 | }); |
| 8265 | } |
| 8266 | |
| 8267 | let mut picker = ModelPickerView::new(&app, &config); |
| 8268 | let visible_ids: Vec<String> = picker |
| 8269 | .visible_model_rows() |
| 8270 | .iter() |
| 8271 | .map(|row| row.id.clone()) |
| 8272 | .collect(); |
| 8273 | assert!(visible_ids.contains(&"opencode".to_string())); |
| 8274 | assert!(visible_ids.contains(&"claude".to_string())); |
| 8275 | assert!(!visible_ids.contains(&"copilot".to_string())); |
| 8276 | |
| 8277 | let agents: Vec<_> = visible_ids |
| 8278 | .iter() |
| 8279 | .filter(|id| ["opencode", "claude", "codex", "antigravity"].contains(&id.as_str())) |
| 8280 | .map(String::as_str) |
| 8281 | .collect(); |
| 8282 | assert!( |
| 8283 | agents.iter().position(|id| *id == "codex") |
| 8284 | < agents.iter().position(|id| *id == "antigravity") |
| 8285 | ); |
| 8286 | assert_eq!(agents.last(), Some(&"claude")); |
| 8287 | |
| 8288 | let opencode_idx = visible_ids.iter().position(|id| id == "opencode").unwrap(); |
| 8289 | picker.selected_model_idx = opencode_idx; |
| 8290 | assert!(picker.selected_model_is_selectable()); |
| 8291 | assert!(!picker.can_edit_effort()); |
| 8292 | let action = picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); |
| 8293 | assert!(matches!( |
| 8294 | action, |
| 8295 | ViewAction::EmitAndClose(ViewEvent::ExternalAgentSelected { |
| 8296 | ref agent_id, |
| 8297 | ref agent_name, |
| 8298 | }) if agent_id == "opencode" && agent_name == "OpenCode" |
| 8299 | )); |
| 8300 | |
| 8301 | let claude_idx = visible_ids.iter().position(|id| id == "claude").unwrap(); |
| 8302 | picker.selected_model_idx = claude_idx; |
| 8303 | assert!(!picker.selected_model_is_selectable()); |
| 8304 | let blocked = picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); |
| 8305 | match blocked { |
| 8306 | ViewAction::Emit(ViewEvent::StatusToast { |
| 8307 | message, |
| 8308 | level: StatusToastLevel::Warning, |
| 8309 | }) => { |
| 8310 | assert!(message.contains("Claude Agent"), "{message}"); |
| 8311 | assert!( |
| 8312 | message.contains("@agentclientprotocol/claude-agent-acp"), |
| 8313 | "{message}" |
| 8314 | ); |
| 8315 | assert!(!message.contains("claude auth login"), "{message}"); |
| 8316 | } |
| 8317 | other => panic!("expected an error notice for blocked external agent, got {other:?}"), |
| 8318 | } |
| 8319 | |
| 8320 | picker.update_query("codex".to_string()); |
| 8321 | { |
| 8322 | let visible = picker.visible_model_rows(); |
| 8323 | assert_eq!( |
| 8324 | visible[0].external_agent.as_ref().unwrap().agent_id, |
| 8325 | "codex" |
| 8326 | ); |
| 8327 | assert!(visible.iter().any(|row| { |
| 8328 | row.id == "gpt-5-codex" |
| 8329 | && row.provider == Some(ProviderKind::OpenaiCodex) |
| 8330 | && row_provider_identity(row) == Some("openai-codex") |
| 8331 | })); |
| 8332 | } |
| 8333 | picker.update_query("gemini".to_string()); |
| 8334 | { |
| 8335 | let visible = picker.visible_model_rows(); |
| 8336 | assert!( |
| 8337 | visible |
| 8338 | .iter() |
| 8339 | .any(|row| row.id == "antigravity" && row.external_agent.is_some()) |
| 8340 | ); |
| 8341 | assert!( |
| 8342 | visible |
| 8343 | .iter() |
| 8344 | .any(|row| row.provider == Some(ProviderKind::Google)) |
| 8345 | ); |
| 8346 | } |
| 8347 | |
| 8348 | picker.update_query("copilot".to_string()); |
| 8349 | let searched: Vec<String> = picker |
| 8350 | .visible_model_rows() |
| 8351 | .iter() |
| 8352 | .map(|row| row.id.clone()) |
| 8353 | .collect(); |
| 8354 | assert!(searched.contains(&"copilot".to_string())); |
| 8355 | |
| 8356 | let fleet_picker = ModelPickerView::new_for_fleet_route( |
| 8357 | &app, |
| 8358 | &config, |
| 8359 | FleetRouteTarget::Member(0), |
| 8360 | uuid::Uuid::new_v4(), |
| 8361 | FleetRouteSelection { |
| 8362 | provider: None, |
| 8363 | model: None, |
| 8364 | reasoning: None, |
| 8365 | allow_inherit: true, |
| 8366 | }, |
| 8367 | ); |
| 8368 | assert!( |
| 8369 | fleet_picker |
| 8370 | .model_rows |
| 8371 | .iter() |
| 8372 | .all(|row| row.external_agent.is_none()) |
| 8373 | ); |
| 8374 | } |
| 8375 | |
| 8376 | #[test] |
| 8377 | fn context_section_cycles_via_tab_renders_warning_and_applies_override() { |
| 8378 | let mut config = Config::default(); |
| 8379 | config.provider = Some("stepfun".to_string()); |
| 8380 | config |
| 8381 | .providers |
| 8382 | .get_or_insert_with(Default::default) |
| 8383 | .stepfun = codewhale_runtime::config::ProviderConfig { |
| 8384 | api_key: Some("test-stepfun-key".to_string()), |
| 8385 | model: Some("step-5".to_string()), |
| 8386 | ..Default::default() |
| 8387 | }; |
| 8388 | let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")); |
| 8389 | let mut app = App::new(options, &config); |
| 8390 | app.model = "step-5".to_string(); |
| 8391 | let mut picker = ModelPickerView::new(&app, &config); |
| 8392 | assert_eq!(picker.focus, Pane::Model); |
| 8393 | assert!(picker.can_edit_context()); |
| 8394 | picker.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); |
| 8395 | assert_eq!(picker.focus, Pane::Effort); |
| 8396 | picker.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); |
| 8397 | assert_eq!(picker.focus, Pane::Context); |
| 8398 | |
| 8399 | let rendered = render_text(&picker, 150, 42); |
| 8400 | assert!(rendered.contains("Context")); |
| 8401 | assert!(rendered.contains("model_context_windows")); |
| 8402 | |
| 8403 | picker.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); |
| 8404 | assert_eq!(picker.selected_context_idx, 1); |
| 8405 | assert!(matches!( |
| 8406 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 8407 | ViewAction::EmitAndClose(ViewEvent::ModelPickerApplied { |
| 8408 | context_window_override: Some(Some(128_000)), |
| 8409 | .. |
| 8410 | }) |
| 8411 | )); |
| 8412 | } |
| 8413 | |
| 8414 | #[test] |
| 8415 | fn context_section_custom_input_validates_bounds() { |
| 8416 | let mut config = Config::default(); |
| 8417 | config.provider = Some("stepfun".to_string()); |
| 8418 | config |
| 8419 | .providers |
| 8420 | .get_or_insert_with(Default::default) |
| 8421 | .stepfun = codewhale_runtime::config::ProviderConfig { |
| 8422 | api_key: Some("test-stepfun-key".to_string()), |
| 8423 | model: Some("step-5".to_string()), |
| 8424 | ..Default::default() |
| 8425 | }; |
| 8426 | let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")); |
| 8427 | let mut app = App::new(options, &config); |
| 8428 | app.model = "step-5".to_string(); |
| 8429 | let mut picker = ModelPickerView::new(&app, &config); |
| 8430 | picker.focus = Pane::Context; |
| 8431 | picker.selected_context_idx = CONTEXT_CHOICES.len() - 1; |
| 8432 | picker.initial_context_override = Some(2048); |
| 8433 | picker.custom_context_input = "2048".to_string(); |
| 8434 | assert!(matches!( |
| 8435 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 8436 | ViewAction::EmitAndClose(ViewEvent::ModelPickerApplied { |
| 8437 | context_window_override: None, |
| 8438 | .. |
| 8439 | }) |
| 8440 | )); |
| 8441 | picker.custom_context_input.clear(); |
| 8442 | for ch in ['1', '0', '0'] { |
| 8443 | picker.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); |
| 8444 | } |
| 8445 | assert!(matches!( |
| 8446 | picker.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 8447 | ViewAction::None |
| 8448 | )); |
| 8449 | assert!(picker.custom_context_error.is_some()); |
| 8450 | |
| 8451 | picker.custom_context_input.clear(); |
| 8452 | app.view_stack.push(picker); |
| 8453 | crate::tui::paste::handle_paste( |
| 8454 | &mut app, |
| 8455 | crate::tui::paste::PasteSource::Terminal(" 272k\n"), |
| 8456 | ); |
| 8457 | assert!(app.input.is_empty()); |
| 8458 | assert!(matches!( |
| 8459 | app.view_stack |
| 8460 | .handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)) |
| 8461 | .as_slice(), |
| 8462 | [ViewEvent::ModelPickerApplied { |
| 8463 | context_window_override: Some(Some(272_000)), |
| 8464 | .. |
| 8465 | }] |
| 8466 | )); |
| 8467 | } |
| 8468 | |
| 8469 | #[test] |
| 8470 | fn model_row_matches_provider_aliases_and_multi_token_queries() { |
| 8471 | let mut anthropic_row = model_row(ProviderKind::Anthropic, true); |
| 8472 | anthropic_row.id = "custom-sonnet".to_string(); |
| 8473 | assert!(model_row_matches_query( |
| 8474 | &anthropic_row, |
| 8475 | "claude", |
| 8476 | ProviderKind::Deepseek |
| 8477 | )); |
| 8478 | assert!(model_row_matches_query( |
| 8479 | &anthropic_row, |
| 8480 | "claude sonnet", |
| 8481 | ProviderKind::Deepseek |
| 8482 | )); |
| 8483 | assert!(!model_row_matches_query( |
| 8484 | &anthropic_row, |
| 8485 | "grok", |
| 8486 | ProviderKind::Deepseek |
| 8487 | )); |
| 8488 | |
| 8489 | let mut google_row = model_row(ProviderKind::Google, true); |
| 8490 | google_row.id = "experimental-model".to_string(); |
| 8491 | assert!(model_row_matches_query( |
| 8492 | &google_row, |
| 8493 | "gemini", |
| 8494 | ProviderKind::Deepseek |
| 8495 | )); |
| 8496 | |
| 8497 | let mut xai_row = model_row(ProviderKind::Xai, true); |
| 8498 | xai_row.id = "fast-model".to_string(); |
| 8499 | assert!(model_row_matches_query( |
| 8500 | &xai_row, |
| 8501 | "grok", |
| 8502 | ProviderKind::Deepseek |
| 8503 | )); |
| 8504 | |
| 8505 | let mut alibaba_row = model_row(ProviderKind::ModelstudioTokenPlan, true); |
| 8506 | alibaba_row.id = "studio-model".to_string(); |
| 8507 | assert!(model_row_matches_query( |
| 8508 | &alibaba_row, |
| 8509 | "qwen", |
| 8510 | ProviderKind::Deepseek |
| 8511 | )); |
| 8512 | assert!(model_row_matches_query( |
| 8513 | &alibaba_row, |
| 8514 | "dashscope", |
| 8515 | ProviderKind::Deepseek |
| 8516 | )); |
| 8517 | |
| 8518 | let mut moonshot_row = model_row(ProviderKind::Moonshot, true); |
| 8519 | moonshot_row.id = "direct-model".to_string(); |
| 8520 | assert!(model_row_matches_query( |
| 8521 | &moonshot_row, |
| 8522 | "kimi", |
| 8523 | ProviderKind::Deepseek |
| 8524 | )); |
| 8525 | |
| 8526 | let mut zai_row = model_row(ProviderKind::Zai, true); |
| 8527 | zai_row.id = "direct-model".to_string(); |
| 8528 | assert!(model_row_matches_query( |
| 8529 | &zai_row, |
| 8530 | "glm", |
| 8531 | ProviderKind::Deepseek |
| 8532 | )); |
| 8533 | |
| 8534 | let mut openai_row = model_row(ProviderKind::Openai, true); |
| 8535 | openai_row.id = "o-series".to_string(); |
| 8536 | assert!(model_row_matches_query( |
| 8537 | &openai_row, |
| 8538 | "gpt", |
| 8539 | ProviderKind::Deepseek |
| 8540 | )); |
| 8541 | assert!(model_row_matches_query( |
| 8542 | &openai_row, |
| 8543 | "chatgpt", |
| 8544 | ProviderKind::Deepseek |
| 8545 | )); |
| 8546 | } |
| 8547 | |
| 8548 | #[test] |
| 8549 | fn release_date_suffixes_humanize_only_when_non_colliding_and_stay_searchable() { |
| 8550 | assert_eq!( |
| 8551 | parse_trailing_release_date("claude-sonnet-4-20250514"), |
| 8552 | Some(("claude-sonnet-4", "Updated May 14, 2025".to_string())) |
| 8553 | ); |
| 8554 | assert_eq!( |
| 8555 | parse_trailing_release_date("qwen-max-1017"), |
| 8556 | Some(("qwen-max", "Updated Oct 17".to_string())) |
| 8557 | ); |
| 8558 | assert_eq!( |
| 8559 | parse_trailing_release_date("gpt-5-2025-10-17"), |
| 8560 | Some(("gpt-5", "Updated Oct 17, 2025".to_string())) |
| 8561 | ); |
| 8562 | assert_eq!(parse_trailing_release_date("model-2025"), None); |
| 8563 | assert_eq!( |
| 8564 | parse_trailing_release_date("deepseek-v4.1-flash-expires-on-0910"), |
| 8565 | None |
| 8566 | ); |
| 8567 | |
| 8568 | let temp = tempfile::tempdir().unwrap(); |
| 8569 | let config = Config::default(); |
| 8570 | let options = crate::tui::app::TuiOptions { |
| 8571 | model: "deepseek-chat".to_string(), |
| 8572 | workspace: temp.path().to_path_buf(), |
| 8573 | config_path: None, |
| 8574 | config_profile: None, |
| 8575 | allow_shell: false, |
| 8576 | use_mouse_capture: false, |
| 8577 | use_bracketed_paste: false, |
| 8578 | max_subagents: 1, |
| 8579 | skills_dir: temp.path().join("skills"), |
| 8580 | memory_path: temp.path().join("memory"), |
| 8581 | mcp_config_path: temp.path().join("mcp.json"), |
| 8582 | use_memory: false, |
| 8583 | start_in_agent_mode: false, |
| 8584 | skip_onboarding: true, |
| 8585 | yolo: false, |
| 8586 | resume_session_id: None, |
| 8587 | initial_input: None, |
| 8588 | startup_notice: None, |
| 8589 | }; |
| 8590 | let app = App::new(options, &config); |
| 8591 | let mut picker = ModelPickerView::new(&app, &config); |
| 8592 | |
| 8593 | let mut unique_dated = model_row(ProviderKind::Anthropic, true); |
| 8594 | unique_dated.id = "solo-model-20250514".to_string(); |
| 8595 | unique_dated.default_rank = Some((DefaultSection::Roster, 0)); |
| 8596 | |
| 8597 | let mut colliding_a = model_row(ProviderKind::Anthropic, true); |
| 8598 | colliding_a.id = "twin-model-2025-10-17".to_string(); |
| 8599 | colliding_a.default_rank = Some((DefaultSection::Roster, 1)); |
| 8600 | |
| 8601 | let mut colliding_b = model_row(ProviderKind::Anthropic, true); |
| 8602 | colliding_b.id = "twin-model".to_string(); |
| 8603 | colliding_b.default_rank = Some((DefaultSection::Roster, 2)); |
| 8604 | |
| 8605 | picker.model_rows = vec![unique_dated, colliding_a, colliding_b]; |
| 8606 | picker.view = ModelListView::Catalog; |
| 8607 | *picker.projection.borrow_mut() = None; |
| 8608 | picker.ensure_projection(); |
| 8609 | |
| 8610 | let projection = picker.projection.borrow(); |
| 8611 | let proj = projection.as_ref().unwrap(); |
| 8612 | let solo_pos = proj |
| 8613 | .indices |
| 8614 | .iter() |
| 8615 | .position(|&idx| picker.model_rows[idx].id == "solo-model-20250514") |
| 8616 | .unwrap(); |
| 8617 | assert_eq!(proj.rows[solo_pos].primary, "solo-model"); |
| 8618 | assert!( |
| 8619 | proj.rows[solo_pos] |
| 8620 | .meta |
| 8621 | .iter() |
| 8622 | .any(|chip| chip == "Updated May 14, 2025") |
| 8623 | ); |
| 8624 | |
| 8625 | let twin_pos = proj |
| 8626 | .indices |
| 8627 | .iter() |
| 8628 | .position(|&idx| picker.model_rows[idx].id == "twin-model-2025-10-17") |
| 8629 | .unwrap(); |
| 8630 | assert_eq!(proj.rows[twin_pos].primary, "twin-model-2025-10-17"); |
| 8631 | assert!( |
| 8632 | !proj.rows[twin_pos] |
| 8633 | .meta |
| 8634 | .iter() |
| 8635 | .any(|chip| chip.starts_with("Updated ")) |
| 8636 | ); |
| 8637 | drop(projection); |
| 8638 | |
| 8639 | picker.update_query("20250514".to_string()); |
| 8640 | let visible = picker.visible_model_rows(); |
| 8641 | assert_eq!(visible.len(), 1); |
| 8642 | assert_eq!(visible[0].id, "solo-model-20250514"); |
| 8643 | drop(visible); |
| 8644 | picker.selected_model_idx = 0; |
| 8645 | assert_eq!(picker.resolved_model(), "solo-model-20250514"); |
| 8646 | } |
| 8647 | |
| 8648 | #[test] |
| 8649 | fn external_agent_rows_surface_cached_model_count_and_thinking_levels() { |
| 8650 | use codewhale_app_server::runtime_api::ExternalAgentDiscoveryRow; |
| 8651 | let roster = CodexModelRoster { |
| 8652 | models: vec![ |
| 8653 | CodexModelMetadata { |
| 8654 | id: "gpt-5.4-codex".to_string(), |
| 8655 | display_name: None, |
| 8656 | context_window: Some(272_000), |
| 8657 | reasoning: Some(true), |
| 8658 | efforts: vec!["low".to_string(), "medium".to_string(), "high".to_string()], |
| 8659 | }, |
| 8660 | CodexModelMetadata { |
| 8661 | id: "gpt-5.5-codex".to_string(), |
| 8662 | display_name: None, |
| 8663 | context_window: Some(272_000), |
| 8664 | reasoning: Some(true), |
| 8665 | efforts: vec!["medium".to_string(), "high".to_string(), "max".to_string()], |
| 8666 | }, |
| 8667 | ], |
| 8668 | freshness: CodexModelCacheFreshness::Fresh, |
| 8669 | fetched_at: None, |
| 8670 | observed_at: None, |
| 8671 | source: "test", |
| 8672 | observation_persisted: false, |
| 8673 | }; |
| 8674 | let temp = tempfile::tempdir().unwrap(); |
| 8675 | let config = Config::default(); |
| 8676 | let options = crate::tui::app::TuiOptions { |
| 8677 | model: "deepseek-chat".to_string(), |
| 8678 | workspace: temp.path().to_path_buf(), |
| 8679 | config_path: None, |
| 8680 | config_profile: None, |
| 8681 | allow_shell: false, |
| 8682 | use_mouse_capture: false, |
| 8683 | use_bracketed_paste: false, |
| 8684 | max_subagents: 1, |
| 8685 | skills_dir: temp.path().join("skills"), |
| 8686 | memory_path: temp.path().join("memory"), |
| 8687 | mcp_config_path: temp.path().join("mcp.json"), |
| 8688 | use_memory: false, |
| 8689 | start_in_agent_mode: false, |
| 8690 | skip_onboarding: true, |
| 8691 | yolo: false, |
| 8692 | resume_session_id: None, |
| 8693 | initial_input: None, |
| 8694 | startup_notice: None, |
| 8695 | }; |
| 8696 | let mut app = App::new(options, &config); |
| 8697 | app.external_agents = vec![ExternalAgentDiscoveryRow { |
| 8698 | id: "codex".to_string(), |
| 8699 | name: "Codex".to_string(), |
| 8700 | state: "installed".to_string(), |
| 8701 | version: Some("0.50.0".to_string()), |
| 8702 | acp: Some("native".to_string()), |
| 8703 | transport: Some("acp".to_string()), |
| 8704 | transports: vec!["acp".to_string()], |
| 8705 | website: "https://openai.com".to_string(), |
| 8706 | min_version: None, |
| 8707 | upgrade: None, |
| 8708 | login: None, |
| 8709 | adapter: None, |
| 8710 | adapter_installed: false, |
| 8711 | needs_update: false, |
| 8712 | runnable: true, |
| 8713 | custom: false, |
| 8714 | reason_code: None, |
| 8715 | reason: None, |
| 8716 | }]; |
| 8717 | let mut rows = Vec::new(); |
| 8718 | push_external_agent_rows(&mut rows, &app, &roster); |
| 8719 | assert_eq!(rows.len(), 1); |
| 8720 | let agent = rows[0].external_agent.as_ref().unwrap(); |
| 8721 | assert_eq!(agent.cached_model_count, Some(2)); |
| 8722 | assert_eq!(agent.thinking_levels, vec!["low", "medium", "high", "max"]); |
| 8723 | let chips = external_agent_meta_chips(&rows[0], agent); |
| 8724 | assert!(chips.iter().any(|chip| chip == "2 cached models")); |
| 8725 | assert!( |
| 8726 | chips |
| 8727 | .iter() |
| 8728 | .any(|chip| chip == "thinking: low/medium/high/max") |
| 8729 | ); |
| 8730 | assert!(rows[0].hint.contains("2 cached models")); |
| 8731 | assert!(rows[0].hint.contains("thinking: low/medium/high/max")); |
| 8732 | } |
| 8733 | |
| 8734 | #[test] |
| 8735 | fn paste_in_model_pane_updates_query_and_sanitizes_control_chars() { |
| 8736 | let config = Config::default(); |
| 8737 | let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")); |
| 8738 | let app = App::new(options, &config); |
| 8739 | let mut picker = ModelPickerView::new(&app, &config); |
| 8740 | assert_eq!(picker.focus, Pane::Model); |
| 8741 | assert!(picker.handle_paste("deepseek\x07chat\r\n")); |
| 8742 | assert_eq!(picker.query, "deepseek chat"); |
| 8743 | assert!(picker.handle_paste("\n")); |
| 8744 | assert_eq!(picker.query, "deepseek chat"); |
| 8745 | } |
| 8746 | } |
| 8747 | |
| 8748 | #[cfg(test)] |
| 8749 | mod push_model_id_tests { |
| 8750 | use super::push_model_id; |
| 8751 | |
| 8752 | #[test] |
| 8753 | fn case_variant_model_ids_stay_listed_but_auto_stays_reserved() { |
| 8754 | let mut models = Vec::new(); |
| 8755 | push_model_id(&mut models, "auto"); |
| 8756 | push_model_id(&mut models, "Auto"); |
| 8757 | push_model_id(&mut models, "Org/Model-A"); |
| 8758 | push_model_id(&mut models, "org/model-a"); |
| 8759 | push_model_id(&mut models, "org/model-a"); |
| 8760 | assert_eq!(models, ["auto", "Org/Model-A", "org/model-a"]); |
| 8761 | } |
| 8762 | } |
| 8763 |