| 1 | //! Live local Ollama catalog facts and unconfigured first-run adoption. |
| 2 | //! |
| 3 | //! Virgin sessions default to the DeepSeek costume (`deepseek-flash`). When a |
| 4 | //! real local daemon answers `GET /api/tags` (or the OpenAI-compat |
| 5 | //! `GET /v1/models` roster), the painted route must switch to a tag that |
| 6 | //! actually exists. Discovery never replaces an explicit provider/model, |
| 7 | //! including a configured route whose credentials need repair. |
| 8 | |
| 9 | use crate::client::ollama_catalog::{ |
| 10 | OllamaTagProfile, fetch_tag_profile, fetch_tag_profiles, fetch_text, ollama_catalog_delta, |
| 11 | ollama_native_origin, parse_ollama_tags_with_profiles, |
| 12 | }; |
| 13 | use codewhale_config::ProviderKind; |
| 14 | use codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL; |
| 15 | use codewhale_runtime::config::Config; |
| 16 | |
| 17 | /// Result of a successful local Ollama tags/models probe. |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub struct LiveLocalOllamaCatalog { |
| 20 | pub endpoint_v1: String, |
| 21 | pub tags: Vec<String>, |
| 22 | pub ticket: crate::provider_catalog_live::ProviderCatalogRefreshTicket, |
| 23 | /// The tag adoption may switch to: a model that can hold a conversation. |
| 24 | /// `None` when every live tag is an embedding/reranker model — adopting |
| 25 | /// one of those would make every first message fail. |
| 26 | pub chat_tag: Option<String>, |
| 27 | } |
| 28 | |
| 29 | impl LiveLocalOllamaCatalog { |
| 30 | /// The chat-capable tag to adopt, if the catalog has one. |
| 31 | pub fn preferred_tag(&self) -> Option<&str> { |
| 32 | self.chat_tag.as_deref() |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// True when this session should adopt a live local catalog into chrome. |
| 37 | /// |
| 38 | /// An unconfigured first run paints DeepSeek by default; a live local |
| 39 | /// roster can replace that default. Explicit routes are left alone, |
| 40 | /// and so is a provider picker the person has already started using: the |
| 41 | /// probe answers late, and switching provider under them would close the |
| 42 | /// picker mid-choice or mid-key. |
| 43 | #[must_use] |
| 44 | pub fn should_adopt_live_local_ollama( |
| 45 | startup_route_configured: bool, |
| 46 | provider: ProviderKind, |
| 47 | picker_interacted: bool, |
| 48 | onboarding_needs_key: bool, |
| 49 | ) -> bool { |
| 50 | if startup_route_configured { |
| 51 | return false; |
| 52 | } |
| 53 | if provider == ProviderKind::Ollama { |
| 54 | // Already on Ollama — route_runtime + #5795 own the tag; don't fight it. |
| 55 | return false; |
| 56 | } |
| 57 | if picker_interacted { |
| 58 | return false; |
| 59 | } |
| 60 | onboarding_needs_key |
| 61 | } |
| 62 | |
| 63 | #[must_use] |
| 64 | pub fn startup_route_configured(config: &Config) -> bool { |
| 65 | // First launch writes `default_text_model = DEFAULT_TEXT_MODEL` into |
| 66 | // the generated config.toml; that line is the template, not a choice, |
| 67 | // so it must not turn off local discovery on a later launch. |
| 68 | let generated_default_model = config.provider.is_none() |
| 69 | && config.default_text_model.as_deref() == Some(DEFAULT_TEXT_MODEL); |
| 70 | config.provider.is_some() |
| 71 | || (config.default_text_model.is_some() && !generated_default_model) |
| 72 | || config.legacy_model.is_some() |
| 73 | || codewhale_runtime::config::explicit_launch_provider_override().is_some() |
| 74 | || codewhale_runtime::config::explicit_launch_model_override().is_some() |
| 75 | || config |
| 76 | .active_provider_identity() |
| 77 | .ok() |
| 78 | .as_ref() |
| 79 | .and_then(|identity| config.provider_config_for(identity)) |
| 80 | .is_some_and(|entry| entry.model.is_some()) |
| 81 | || config.active_route_endpoint_configured() |
| 82 | } |
| 83 | |
| 84 | pub async fn adopt_live_local_ollama_for_run( |
| 85 | config: &mut Config, |
| 86 | read_only: bool, |
| 87 | ) -> Option<String> { |
| 88 | let provider = config.active_provider_identity().ok()?.provider; |
| 89 | if !should_adopt_live_local_ollama(startup_route_configured(config), provider, false, true) { |
| 90 | return None; |
| 91 | } |
| 92 | let has_key = if read_only { |
| 93 | config.active_route_api_key_read_only().is_ok() |
| 94 | } else { |
| 95 | crate::provider_readiness::has_api_key(config) |
| 96 | }; |
| 97 | if has_key { |
| 98 | return None; |
| 99 | } |
| 100 | let catalog = spawn_local_ollama_adoption_probe(config, true)? |
| 101 | .await |
| 102 | .ok()??; |
| 103 | let tag = catalog.preferred_tag()?.to_string(); |
| 104 | config.provider = Some(ProviderKind::Ollama.as_str().to_string()); |
| 105 | config.default_text_model = Some(tag.clone()); |
| 106 | Some(tag) |
| 107 | } |
| 108 | |
| 109 | /// Resolve the OpenAI-compat Ollama base URL (`…/v1`) from config defaults. |
| 110 | pub fn ollama_v1_base_url(config: &Config) -> String { |
| 111 | config |
| 112 | .resolve_provider_pin_identity("ollama") |
| 113 | .ok() |
| 114 | .filter(|identity| identity.provider == ProviderKind::Ollama) |
| 115 | .map(|identity| config.base_url_for_route(&identity)) |
| 116 | .unwrap_or_default() |
| 117 | } |
| 118 | |
| 119 | fn record_ollama_tags_into_lake( |
| 120 | ticket: &crate::provider_catalog_live::ProviderCatalogRefreshTicket, |
| 121 | endpoint_v1: &str, |
| 122 | tags: &[String], |
| 123 | profiles: &std::collections::HashMap<String, OllamaTagProfile>, |
| 124 | running_body: Option<&str>, |
| 125 | ) -> Option<String> { |
| 126 | let delta = ollama_catalog_delta("ollama", endpoint_v1, tags, profiles, running_body); |
| 127 | let chat_tag = delta |
| 128 | .offerings |
| 129 | .iter() |
| 130 | .find(|offering| offering.default_for_provider) |
| 131 | .map(|offering| offering.wire_model_id.clone()); |
| 132 | if matches!( |
| 133 | crate::provider_catalog_live::record_success_if_current(ticket, delta), |
| 134 | Some(codewhale_config::catalog::CatalogStatus::Fresh) |
| 135 | ) { |
| 136 | chat_tag |
| 137 | } else { |
| 138 | None |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// Probe local Ollama for a live catalog. Prefers native `/api/tags`, falls |
| 143 | /// back to OpenAI-compat `/v1/models`. Returns `None` when nothing useful |
| 144 | /// answered — never invents a tag. |
| 145 | pub async fn probe_live_local_ollama_catalog(config: &Config) -> Option<LiveLocalOllamaCatalog> { |
| 146 | let endpoint_v1 = ollama_v1_base_url(config); |
| 147 | let origin = ollama_native_origin(&endpoint_v1); |
| 148 | let identity = config |
| 149 | .builtin_provider_identity(ProviderKind::Ollama) |
| 150 | .ok()?; |
| 151 | let ticket = |
| 152 | crate::provider_catalog_live::begin_scoped_refresh(config, &identity, &endpoint_v1).ok()?; |
| 153 | let tags_url = format!("{origin}/api/tags"); |
| 154 | let (tags, mut profiles) = match fetch_text(&tags_url).await { |
| 155 | Ok(body) => match parse_ollama_tags_with_profiles(&body) { |
| 156 | Ok((tags, profiles)) if !tags.is_empty() => (tags, profiles), |
| 157 | Ok((tags, profiles)) => { |
| 158 | record_ollama_tags_into_lake(&ticket, &endpoint_v1, &tags, &profiles, None); |
| 159 | return Some(LiveLocalOllamaCatalog { |
| 160 | endpoint_v1, |
| 161 | tags, |
| 162 | ticket, |
| 163 | chat_tag: None, |
| 164 | }); |
| 165 | } |
| 166 | Err(err) => { |
| 167 | tracing::debug!(target: "local_ollama", error = %err, "GET /api/tags returned unusable body"); |
| 168 | (Vec::new(), std::collections::HashMap::new()) |
| 169 | } |
| 170 | }, |
| 171 | Err(err) => { |
| 172 | tracing::debug!(target: "local_ollama", error = %err, url = %tags_url, "GET /api/tags probe failed"); |
| 173 | (Vec::new(), std::collections::HashMap::new()) |
| 174 | } |
| 175 | }; |
| 176 | let tags = if tags.is_empty() { |
| 177 | let models_url = format!("{}/models", endpoint_v1.trim_end_matches('/')); |
| 178 | match fetch_text(&models_url).await { |
| 179 | Ok(body) => match crate::client::parse_models_response(&body) { |
| 180 | Ok(models) if !models.is_empty() => { |
| 181 | models.into_iter().map(|model| model.id).collect() |
| 182 | } |
| 183 | Ok(_) => { |
| 184 | record_ollama_tags_into_lake(&ticket, &endpoint_v1, &[], &profiles, None); |
| 185 | return Some(LiveLocalOllamaCatalog { |
| 186 | endpoint_v1, |
| 187 | tags: Vec::new(), |
| 188 | ticket, |
| 189 | chat_tag: None, |
| 190 | }); |
| 191 | } |
| 192 | Err(_) => return None, |
| 193 | }, |
| 194 | Err(_) => return None, |
| 195 | } |
| 196 | } else { |
| 197 | tags |
| 198 | }; |
| 199 | let fetched = tokio::time::timeout( |
| 200 | crate::client::NON_STREAMING_HTTP_TIMEOUT, |
| 201 | fetch_tag_profiles(&tags, &profiles, |tag| { |
| 202 | let origin = &origin; |
| 203 | async move { fetch_tag_profile(origin, &tag).await } |
| 204 | }), |
| 205 | ) |
| 206 | .await |
| 207 | .ok()?; |
| 208 | for (tag, profile) in fetched { |
| 209 | profiles |
| 210 | .entry(tag) |
| 211 | .and_modify(|known| { |
| 212 | if known.capabilities.is_none() { |
| 213 | known.capabilities = profile.capabilities.clone(); |
| 214 | } |
| 215 | if known.context_length.is_none() { |
| 216 | known.context_length = profile.context_length; |
| 217 | } |
| 218 | }) |
| 219 | .or_insert(profile); |
| 220 | } |
| 221 | if tags.iter().any(|tag| { |
| 222 | profiles |
| 223 | .get(tag) |
| 224 | .is_none_or(|profile| profile.capabilities.is_none()) |
| 225 | }) { |
| 226 | let delta = ollama_catalog_delta("ollama", &endpoint_v1, &tags, &profiles, None); |
| 227 | let chat_tag = delta |
| 228 | .offerings |
| 229 | .iter() |
| 230 | .find(|offering| offering.default_for_provider) |
| 231 | .map(|offering| offering.wire_model_id.clone())?; |
| 232 | return Some(LiveLocalOllamaCatalog { |
| 233 | endpoint_v1, |
| 234 | tags, |
| 235 | ticket, |
| 236 | chat_tag: Some(chat_tag), |
| 237 | }); |
| 238 | } |
| 239 | let running_body = fetch_text(&format!("{origin}/api/ps")).await.ok(); |
| 240 | let chat_tag = record_ollama_tags_into_lake( |
| 241 | &ticket, |
| 242 | &endpoint_v1, |
| 243 | &tags, |
| 244 | &profiles, |
| 245 | running_body.as_deref(), |
| 246 | ); |
| 247 | Some(LiveLocalOllamaCatalog { |
| 248 | endpoint_v1, |
| 249 | tags, |
| 250 | ticket, |
| 251 | chat_tag, |
| 252 | }) |
| 253 | } |
| 254 | |
| 255 | /// Env opt-out for harnesses that must not see the developer's machine. |
| 256 | /// |
| 257 | /// `spawn_local_ollama_adoption_probe` is already inert under `cfg(test)`, but |
| 258 | /// the PTY suites spawn the real binary, so that guard never reaches them. A |
| 259 | /// developer running Ollama on :11434 therefore gets the launch screen replaced |
| 260 | /// by a "Provider switched: deepseek -> ollama" notice, and the PTY tests that |
| 261 | /// wait for launch text fail on their machine while CI stays green. Sealing the |
| 262 | /// HOME is not enough, because this leak arrives over the loopback network |
| 263 | /// rather than through the filesystem. |
| 264 | pub const DISABLE_LOCAL_OLLAMA_PROBE_ENV: &str = "CODEWHALE_DISABLE_LOCAL_OLLAMA_PROBE"; |
| 265 | |
| 266 | fn local_ollama_probe_disabled() -> bool { |
| 267 | std::env::var_os(DISABLE_LOCAL_OLLAMA_PROBE_ENV).is_some_and(|value| !value.is_empty()) |
| 268 | } |
| 269 | |
| 270 | /// Background probe used by the event loop (mirrors `spawn_startup_version_check`). |
| 271 | pub fn spawn_local_ollama_adoption_probe( |
| 272 | config: &Config, |
| 273 | should_probe: bool, |
| 274 | ) -> Option<tokio::task::JoinHandle<Option<LiveLocalOllamaCatalog>>> { |
| 275 | if !should_probe || local_ollama_probe_disabled() { |
| 276 | return None; |
| 277 | } |
| 278 | #[cfg(any( |
| 279 | test, |
| 280 | feature = "test-support", |
| 281 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 282 | ))] |
| 283 | { |
| 284 | let _ = config; |
| 285 | None |
| 286 | } |
| 287 | #[cfg(not(any( |
| 288 | test, |
| 289 | feature = "test-support", |
| 290 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 291 | )))] |
| 292 | { |
| 293 | let config = config.clone(); |
| 294 | Some(tokio::spawn(async move { |
| 295 | probe_live_local_ollama_catalog(&config).await |
| 296 | })) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | #[cfg(test)] |
| 301 | mod tests { |
| 302 | use super::*; |
| 303 | use crate::client::ollama_catalog::{ |
| 304 | choose_chat_tag, parse_ollama_show_response, parse_ollama_tags_response, |
| 305 | }; |
| 306 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 307 | use std::collections::HashMap; |
| 308 | |
| 309 | #[test] |
| 310 | fn parse_ollama_tags_response_reads_name_field() { |
| 311 | let body = r#"{"models":[{"name":"qwen2.5:0.5b","model":"qwen2.5:0.5b","size":0}]}"#; |
| 312 | let tags = parse_ollama_tags_response(body).expect("parse"); |
| 313 | assert_eq!(tags, vec!["qwen2.5:0.5b".to_string()]); |
| 314 | } |
| 315 | |
| 316 | #[test] |
| 317 | fn parse_ollama_tags_response_sorts_and_dedups() { |
| 318 | let body = r#"{"models":[ |
| 319 | {"name":"zeta:tag"}, |
| 320 | {"name":"alpha:tag"}, |
| 321 | {"name":"alpha:tag"} |
| 322 | ]}"#; |
| 323 | let tags = parse_ollama_tags_response(body).expect("parse"); |
| 324 | assert_eq!(tags, vec!["alpha:tag".to_string(), "zeta:tag".to_string()]); |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn ollama_native_origin_strips_v1() { |
| 329 | assert_eq!( |
| 330 | ollama_native_origin("http://localhost:11434/v1"), |
| 331 | "http://localhost:11434" |
| 332 | ); |
| 333 | assert_eq!( |
| 334 | ollama_native_origin("http://127.0.0.1:11434/v1/"), |
| 335 | "http://127.0.0.1:11434" |
| 336 | ); |
| 337 | } |
| 338 | |
| 339 | fn tags(names: &[&str]) -> Vec<String> { |
| 340 | let mut tags: Vec<String> = names.iter().map(|name| (*name).to_string()).collect(); |
| 341 | tags.sort(); |
| 342 | tags |
| 343 | } |
| 344 | |
| 345 | #[test] |
| 346 | fn chat_tag_never_picks_an_embedding_model() { |
| 347 | // The installed-0.10.0 re-run adopted `nomic-embed-text:latest` |
| 348 | // because it sorted first; with no /api/show facts the name decides. |
| 349 | let tags = tags(&["qwen2.5-coder:7b", "qwen3:4b", "nomic-embed-text:latest"]); |
| 350 | let chosen = choose_chat_tag(&tags, &HashMap::new()); |
| 351 | assert_eq!(chosen.as_deref(), Some("qwen2.5-coder:7b")); |
| 352 | } |
| 353 | |
| 354 | #[test] |
| 355 | fn embed_only_catalog_adopts_nothing() { |
| 356 | let tags = tags(&[ |
| 357 | "nomic-embed-text:latest", |
| 358 | "bge-m3:latest", |
| 359 | "all-minilm:l6-v2", |
| 360 | "qllama/bge-reranker-v2-m3:latest", |
| 361 | ]); |
| 362 | assert_eq!(choose_chat_tag(&tags, &HashMap::new()), None); |
| 363 | let catalog = LiveLocalOllamaCatalog { |
| 364 | endpoint_v1: "http://localhost:11434/v1".into(), |
| 365 | ticket: crate::provider_catalog_live::begin_refresh_for_identity( |
| 366 | ProviderKind::Ollama, |
| 367 | "ollama", |
| 368 | "http://localhost:11434/v1", |
| 369 | ), |
| 370 | chat_tag: choose_chat_tag(&tags, &HashMap::new()), |
| 371 | tags, |
| 372 | }; |
| 373 | assert_eq!(catalog.preferred_tag(), None); |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn reported_capabilities_outrank_the_name_heuristic() { |
| 378 | let tags = tags(&["alpha:1b", "mystery:latest", "zeta:8b"]); |
| 379 | let mut profiles = HashMap::new(); |
| 380 | // An embedding model with an innocent name is excluded by its facts. |
| 381 | profiles.insert( |
| 382 | "alpha:1b".to_string(), |
| 383 | OllamaTagProfile { |
| 384 | capabilities: Some(vec!["embedding".into()]), |
| 385 | context_length: Some(8_192), |
| 386 | }, |
| 387 | ); |
| 388 | // Tool support is preferred over a larger context without it. |
| 389 | profiles.insert( |
| 390 | "mystery:latest".to_string(), |
| 391 | OllamaTagProfile { |
| 392 | capabilities: Some(vec!["completion".into(), "tools".into()]), |
| 393 | context_length: Some(32_768), |
| 394 | }, |
| 395 | ); |
| 396 | profiles.insert( |
| 397 | "zeta:8b".to_string(), |
| 398 | OllamaTagProfile { |
| 399 | capabilities: Some(vec!["completion".into()]), |
| 400 | context_length: Some(131_072), |
| 401 | }, |
| 402 | ); |
| 403 | assert_eq!( |
| 404 | choose_chat_tag(&tags, &profiles).as_deref(), |
| 405 | Some("mystery:latest") |
| 406 | ); |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn larger_context_then_name_breaks_ties_among_equals() { |
| 411 | let tags = tags(&["b-model:7b", "a-model:7b", "c-model:7b"]); |
| 412 | let mut profiles = HashMap::new(); |
| 413 | profiles.insert( |
| 414 | "c-model:7b".to_string(), |
| 415 | OllamaTagProfile { |
| 416 | capabilities: Some(vec!["completion".into()]), |
| 417 | context_length: Some(65_536), |
| 418 | }, |
| 419 | ); |
| 420 | assert_eq!( |
| 421 | choose_chat_tag(&tags, &profiles).as_deref(), |
| 422 | Some("c-model:7b") |
| 423 | ); |
| 424 | assert_eq!( |
| 425 | choose_chat_tag(&tags, &HashMap::new()).as_deref(), |
| 426 | Some("a-model:7b"), |
| 427 | "without facts the first chat tag wins, as before" |
| 428 | ); |
| 429 | } |
| 430 | |
| 431 | #[test] |
| 432 | fn parse_ollama_show_response_reads_capabilities_and_context() { |
| 433 | let body = r#"{ |
| 434 | "capabilities": ["completion", "tools"], |
| 435 | "model_info": {"general.architecture": "qwen2", "qwen2.context_length": 32768} |
| 436 | }"#; |
| 437 | let profile = parse_ollama_show_response(body).expect("parse"); |
| 438 | assert_eq!( |
| 439 | profile.capabilities, |
| 440 | Some(vec!["completion".to_string(), "tools".to_string()]) |
| 441 | ); |
| 442 | assert_eq!(profile.context_length, Some(32_768)); |
| 443 | let legacy = parse_ollama_show_response(r#"{"modelfile":""}"#).expect("parse"); |
| 444 | assert_eq!(legacy, OllamaTagProfile::default()); |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn ollama_catalog_delta_preserves_show_context_and_tolerates_missing_caps() { |
| 449 | let mut profiles = HashMap::new(); |
| 450 | profiles.insert( |
| 451 | "qwen3:32b".to_string(), |
| 452 | OllamaTagProfile { |
| 453 | capabilities: Some(vec!["completion".into(), "tools".into(), "thinking".into()]), |
| 454 | context_length: Some(131_072), |
| 455 | }, |
| 456 | ); |
| 457 | profiles.insert( |
| 458 | "legacy-llama:8b".to_string(), |
| 459 | OllamaTagProfile { |
| 460 | capabilities: None, |
| 461 | context_length: Some(32_768), |
| 462 | }, |
| 463 | ); |
| 464 | profiles.insert( |
| 465 | "nomic-embed-text:latest".to_string(), |
| 466 | OllamaTagProfile { |
| 467 | capabilities: None, |
| 468 | context_length: None, |
| 469 | }, |
| 470 | ); |
| 471 | let tags = vec![ |
| 472 | "legacy-llama:8b".to_string(), |
| 473 | "nomic-embed-text:latest".to_string(), |
| 474 | "qwen3:32b".to_string(), |
| 475 | ]; |
| 476 | |
| 477 | let without_ps = ollama_catalog_delta( |
| 478 | "ollama", |
| 479 | "http://127.0.0.1:11434/v1", |
| 480 | &tags, |
| 481 | &profiles, |
| 482 | None, |
| 483 | ); |
| 484 | assert_eq!(without_ps.offerings.len(), 2); |
| 485 | let qwen = without_ps |
| 486 | .offerings |
| 487 | .iter() |
| 488 | .find(|row| row.wire_model_id == "qwen3:32b") |
| 489 | .expect("qwen3 offering"); |
| 490 | assert_eq!( |
| 491 | qwen.limit.as_ref().and_then(|limit| limit.context), |
| 492 | Some(131_072) |
| 493 | ); |
| 494 | assert_eq!( |
| 495 | qwen.limit.as_ref().and_then(|limit| limit.input), |
| 496 | Some(131_072) |
| 497 | ); |
| 498 | assert!(!qwen.fact_sources.contains_key("limit.context.ps")); |
| 499 | let legacy = without_ps |
| 500 | .offerings |
| 501 | .iter() |
| 502 | .find(|row| row.wire_model_id == "legacy-llama:8b") |
| 503 | .expect("legacy offering kept without capabilities"); |
| 504 | assert_eq!( |
| 505 | legacy.limit.as_ref().and_then(|limit| limit.context), |
| 506 | Some(32_768) |
| 507 | ); |
| 508 | |
| 509 | let running = r#"{"models":[{"name":"qwen3:32b","context_length":16384}]}"#; |
| 510 | let with_ps = ollama_catalog_delta( |
| 511 | "ollama", |
| 512 | "http://127.0.0.1:11434/v1", |
| 513 | &tags, |
| 514 | &profiles, |
| 515 | Some(running), |
| 516 | ); |
| 517 | let qwen_ps = with_ps |
| 518 | .offerings |
| 519 | .iter() |
| 520 | .find(|row| row.wire_model_id == "qwen3:32b") |
| 521 | .expect("qwen3 ps offering"); |
| 522 | assert_eq!( |
| 523 | qwen_ps.limit.as_ref().and_then(|limit| limit.context), |
| 524 | Some(16_384) |
| 525 | ); |
| 526 | assert_eq!( |
| 527 | qwen_ps.limit.as_ref().and_then(|limit| limit.input), |
| 528 | Some(131_072) |
| 529 | ); |
| 530 | assert!(qwen_ps.fact_sources.contains_key("limit.context.ps")); |
| 531 | } |
| 532 | |
| 533 | #[tokio::test] |
| 534 | async fn probe_live_local_ollama_catalog_reads_api_tags() { |
| 535 | let _lock = lock_test_env(); |
| 536 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 537 | let home = tempfile::tempdir().unwrap(); |
| 538 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 539 | crate::provider_catalog_live::reset_cache_for_test(); |
| 540 | crate::provider_lake::clear_live_snapshot(); |
| 541 | |
| 542 | let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); |
| 543 | let addr = listener.local_addr().unwrap(); |
| 544 | std::thread::spawn(move || { |
| 545 | let (mut stream, _) = listener.accept().unwrap(); |
| 546 | use std::io::{Read, Write}; |
| 547 | let mut buf = [0u8; 1024]; |
| 548 | let _ = stream.read(&mut buf); |
| 549 | let body = br#"{"models":[{"name":"qwen2.5:0.5b","model":"qwen2.5:0.5b","capabilities":["completion"]}]}"#; |
| 550 | let header = format!( |
| 551 | "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", |
| 552 | body.len() |
| 553 | ); |
| 554 | stream.write_all(header.as_bytes()).unwrap(); |
| 555 | stream.write_all(body).unwrap(); |
| 556 | }); |
| 557 | |
| 558 | let endpoint = format!("http://{addr}/v1"); |
| 559 | let mut config = Config::default(); |
| 560 | config |
| 561 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Ollama)) |
| 562 | .unwrap() |
| 563 | .base_url = Some(endpoint.clone()); |
| 564 | |
| 565 | let catalog = probe_live_local_ollama_catalog(&config) |
| 566 | .await |
| 567 | .expect("tags probe should succeed"); |
| 568 | assert_eq!(catalog.endpoint_v1, endpoint); |
| 569 | assert_eq!(catalog.tags, vec!["qwen2.5:0.5b".to_string()]); |
| 570 | assert_eq!(catalog.preferred_tag(), Some("qwen2.5:0.5b")); |
| 571 | |
| 572 | let server = wiremock::MockServer::start().await; |
| 573 | wiremock::Mock::given(wiremock::matchers::method("GET")) |
| 574 | .and(wiremock::matchers::path("/api/tags")) |
| 575 | .respond_with( |
| 576 | wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({ |
| 577 | "models": [ |
| 578 | {"name": "confirmed:tag", "capabilities": ["completion"]}, |
| 579 | {"name": "unknown:tag"} |
| 580 | ] |
| 581 | })), |
| 582 | ) |
| 583 | .mount(&server) |
| 584 | .await; |
| 585 | wiremock::Mock::given(wiremock::matchers::method("POST")) |
| 586 | .and(wiremock::matchers::path("/api/show")) |
| 587 | .respond_with(wiremock::ResponseTemplate::new(503)) |
| 588 | .mount(&server) |
| 589 | .await; |
| 590 | let partial_endpoint = format!("{}/v1", server.uri()); |
| 591 | config |
| 592 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Ollama)) |
| 593 | .unwrap() |
| 594 | .base_url = Some(partial_endpoint.clone()); |
| 595 | let partial = probe_live_local_ollama_catalog(&config) |
| 596 | .await |
| 597 | .expect("confirmed tag is available for this session"); |
| 598 | assert_eq!(partial.preferred_tag(), Some("confirmed:tag")); |
| 599 | assert!( |
| 600 | crate::provider_catalog_live::cached_entry_for_route( |
| 601 | ProviderKind::Ollama, |
| 602 | "ollama", |
| 603 | &partial_endpoint, |
| 604 | ) |
| 605 | .unwrap() |
| 606 | .is_none() |
| 607 | ); |
| 608 | |
| 609 | let server = wiremock::MockServer::start().await; |
| 610 | let models: Vec<_> = (0..12) |
| 611 | .map(|index| serde_json::json!({"name": format!("model-{index:02}:tag")})) |
| 612 | .collect(); |
| 613 | wiremock::Mock::given(wiremock::matchers::method("GET")) |
| 614 | .and(wiremock::matchers::path("/api/tags")) |
| 615 | .respond_with( |
| 616 | wiremock::ResponseTemplate::new(200) |
| 617 | .set_body_json(serde_json::json!({"models": models})), |
| 618 | ) |
| 619 | .mount(&server) |
| 620 | .await; |
| 621 | wiremock::Mock::given(wiremock::matchers::method("POST")) |
| 622 | .and(wiremock::matchers::path("/api/show")) |
| 623 | .respond_with(|request: &wiremock::Request| { |
| 624 | let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap(); |
| 625 | let capability = if body["model"] == "model-00:tag" { |
| 626 | "embedding" |
| 627 | } else { |
| 628 | "completion" |
| 629 | }; |
| 630 | wiremock::ResponseTemplate::new(200) |
| 631 | .set_body_json(serde_json::json!({"capabilities": [capability]})) |
| 632 | }) |
| 633 | .mount(&server) |
| 634 | .await; |
| 635 | let endpoint = format!("{}/v1", server.uri()); |
| 636 | config |
| 637 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Ollama)) |
| 638 | .unwrap() |
| 639 | .base_url = Some(endpoint.clone()); |
| 640 | let complete = probe_live_local_ollama_catalog(&config).await.unwrap(); |
| 641 | assert!(complete.preferred_tag().is_some()); |
| 642 | let cached = crate::provider_catalog_live::cached_entry_for_route( |
| 643 | ProviderKind::Ollama, |
| 644 | "ollama", |
| 645 | &endpoint, |
| 646 | ) |
| 647 | .unwrap() |
| 648 | .unwrap(); |
| 649 | assert_eq!(cached.offerings.len(), 11); |
| 650 | assert!( |
| 651 | cached |
| 652 | .offerings |
| 653 | .iter() |
| 654 | .all(|row| row.wire_model_id != "model-00:tag") |
| 655 | ); |
| 656 | } |
| 657 | } |
| 658 |