Skip to main content

vtcode_core/config/
validator.rs

1//! Configuration validation utilities
2//!
3//! Validates VTCodeConfig against actual provider models and API keys.
4
5use anyhow::{Context, Result, bail};
6use hashbrown::HashMap;
7use serde_json::Value as JsonValue;
8use std::path::Path;
9
10use crate::config::api_keys::ApiKeySources;
11use crate::config::api_keys::get_api_key_with_mode;
12use crate::config::constants::models::openai::RESPONSES_API_MODELS;
13use crate::config::loader::VTCodeConfig;
14use crate::config::models::{Provider, model_catalog_entry, supported_models_for_provider};
15use crate::utils::file_utils::read_file_with_context_sync;
16use vtcode_commons::provider::CODEX_PROVIDER_ID;
17use vtcode_config::PromptCacheRetention;
18
19/// Loaded models database from docs/models.json
20#[derive(Debug, Clone)]
21enum ModelsDatabase {
22    Generated,
23    File { providers: HashMap<String, ProviderModels> },
24}
25
26#[derive(Debug, Clone)]
27struct ProviderModels {
28    models: HashMap<String, ModelInfo>,
29}
30
31#[derive(Debug, Clone)]
32struct ModelInfo {
33    context_window: usize,
34}
35
36impl ModelsDatabase {
37    pub fn generated() -> Self {
38        Self::Generated
39    }
40
41    /// Load models database from docs/models.json
42    #[must_use = "models database load failure is silently ignored"]
43    pub fn from_file(path: &Path) -> Result<Self> {
44        let content = read_file_with_context_sync(path, "models database")?;
45
46        let json: JsonValue = serde_json::from_str(&content).context("Failed to parse models database JSON")?;
47
48        let mut providers = HashMap::new();
49
50        if let Some(obj) = json.as_object() {
51            for (provider_id, provider_data) in obj {
52                if let Some(provider_obj) = provider_data.as_object() {
53                    let mut models = HashMap::new();
54
55                    if let Some(models_obj) = provider_obj.get("models").and_then(|v| v.as_object()) {
56                        for (model_id, model_data) in models_obj {
57                            let context_window =
58                                model_data.get("context").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
59
60                            models.insert(model_id.clone(), ModelInfo { context_window });
61                        }
62                    }
63
64                    providers.insert(provider_id.clone(), ProviderModels { models });
65                }
66            }
67        }
68
69        Ok(Self::File { providers })
70    }
71
72    /// Check if model exists for provider
73    pub fn model_exists(&self, provider: &str, model: &str) -> bool {
74        match self {
75            Self::Generated => supported_models_for_provider(provider)
76                .map(|models| models.contains(&model))
77                .unwrap_or(false),
78            Self::File { providers } => providers.get(provider).map(|p| p.models.contains_key(model)).unwrap_or(false),
79        }
80    }
81
82    /// Get context window size for model
83    pub fn get_context_window(&self, provider: &str, model: &str) -> Option<usize> {
84        match self {
85            Self::Generated => model_catalog_entry(provider, model)
86                .map(|entry| entry.context_window)
87                .filter(|context_window| *context_window > 0),
88            Self::File { providers } => providers
89                .get(provider)
90                .and_then(|p| p.models.get(model))
91                .map(|m| m.context_window),
92        }
93    }
94}
95
96/// Configuration validator
97pub struct ConfigValidator {
98    models_db: ModelsDatabase,
99}
100
101impl ConfigValidator {
102    /// Create a validator backed by the build-generated model catalog.
103    pub fn generated() -> Self {
104        Self { models_db: ModelsDatabase::generated() }
105    }
106
107    /// Create a new validator from models database file
108    pub fn new(models_db_path: &Path) -> Result<Self> {
109        Ok(Self {
110            models_db: ModelsDatabase::from_file(models_db_path)?,
111        })
112    }
113
114    /// Validate entire configuration
115    #[must_use = "validation errors go unnoticed"]
116    pub fn validate(&self, config: &VTCodeConfig) -> Result<ValidationResult> {
117        let mut result = ValidationResult::default();
118        let managed_auth_provider = configured_managed_auth_provider(config);
119        let custom_provider = config.custom_provider(&config.agent.provider);
120        let is_custom_provider = custom_provider.is_some();
121        let is_codex_provider = config.agent.provider.eq_ignore_ascii_case(CODEX_PROVIDER_ID);
122        // Built-in OpenAI supports multi-source auth (ChatGPT OAuth, Codex
123        // fallback, API key). The static API-key check below is only meaningful
124        // for providers that require an API key as their sole credential.
125        let is_openai_provider = Provider::OpenAI.name_matches(&config.agent.provider);
126
127        // Check if configured model exists
128        if let Some(custom) = custom_provider {
129            if !custom
130                .effective_models()
131                .iter()
132                .any(|model| model == &config.agent.default_model)
133            {
134                result.errors.push(format!(
135                    "Model '{}' not found for custom provider '{}'.",
136                    config.agent.default_model, custom.display_name
137                ));
138            }
139        } else if !is_codex_provider
140            && !is_managed_auth_model(managed_auth_provider, &config.agent.default_model)
141            && !self.models_db.model_exists(&config.agent.provider, &config.agent.default_model)
142        {
143            // Check for known deprecated OpenAI models and suggest replacements.
144            if Provider::OpenAI.name_matches(&config.agent.provider)
145                && let Some((replacement, reason)) =
146                    vtcode_config::constants::models::openai::deprecated_model_replacement(&config.agent.default_model)
147            {
148                result.errors.push(format!(
149                    "{reason}. Update your config to use '{replacement}' or run /model to pick a current model."
150                ));
151            } else {
152                result.errors.push(format!(
153                    "Model '{}' not found for provider '{}'. Check docs/models.json.",
154                    config.agent.default_model, config.agent.provider
155                ));
156            }
157        }
158
159        // Check if API key is available — skip for built-in OpenAI which
160        // supports ChatGPT OAuth and Codex fallback in addition to API keys.
161        // The runtime auth resolver validates OpenAI's multi-source credentials.
162        if !is_custom_provider
163            && !is_codex_provider
164            && !is_openai_provider
165            && managed_auth_provider.is_none()
166            && let Err(e) = get_api_key_with_mode(
167                &config.agent.provider,
168                &ApiKeySources::default(),
169                config.agent.credential_storage_mode,
170            )
171        {
172            result.errors.push(format!(
173                "API key not found for provider '{}': {}. Set {} environment variable.",
174                config.agent.provider,
175                e,
176                config.agent.provider.to_uppercase()
177            ));
178        }
179
180        // Check context window configuration
181        let model_context_window = if let Some(custom) = custom_provider {
182            custom
183                .effective_models()
184                .iter()
185                .any(|model| model == &config.agent.default_model)
186                .then(|| custom.resolved_profile(&config.agent.default_model).context_window)
187                .flatten()
188        } else {
189            self.models_db
190                .get_context_window(&config.agent.provider, &config.agent.default_model)
191        };
192        if let Some(max_tokens) = model_context_window {
193            let configured_context = config.context.max_context_tokens;
194            if configured_context > 0 && configured_context > max_tokens {
195                result.warnings.push(format!(
196                    "Configured session context safety budget ({} tokens) exceeds provider limit ({} tokens) for {} on {}",
197                    configured_context, max_tokens, config.agent.default_model, config.agent.provider
198                ));
199            }
200        }
201
202        if let Some(message) =
203            check_openai_hosted_shell_compat(config, &config.agent.default_model, &config.agent.provider)
204        {
205            result.warnings.push(message);
206        }
207
208        if let Some(message) = config
209            .provider
210            .anthropic
211            .fallbacks
212            .validation_error("provider.anthropic.fallbacks")
213        {
214            result
215                .warnings
216                .push(format!("{message} VT Code will not request server-side fallbacks until this is corrected."));
217        }
218
219        // Check if workspace exists (if specified)
220        if let Ok(cwd) = std::env::current_dir() {
221            // Basic check only, actual workspace validation happens in StartupContext
222            if !cwd.exists() {
223                result.warnings.push("Current working directory does not exist".to_owned());
224            }
225        }
226
227        Ok(result)
228    }
229
230    /// Quick validation - only critical checks
231    pub fn quick_validate(&self, config: &VTCodeConfig) -> Result<()> {
232        let managed_auth_provider = configured_managed_auth_provider(config);
233        let custom_provider = config.custom_provider(&config.agent.provider);
234        let is_custom_provider = custom_provider.is_some();
235        let is_codex_provider = config.agent.provider.eq_ignore_ascii_case(CODEX_PROVIDER_ID);
236        let is_openai_provider = Provider::OpenAI.name_matches(&config.agent.provider);
237
238        // Check model exists
239        let model_is_valid = custom_provider.is_some_and(|custom| {
240            custom
241                .effective_models()
242                .iter()
243                .any(|model| model == &config.agent.default_model)
244        }) || (!is_custom_provider
245            && (is_codex_provider
246                || is_managed_auth_model(managed_auth_provider, &config.agent.default_model)
247                || self.models_db.model_exists(&config.agent.provider, &config.agent.default_model)));
248        if !model_is_valid {
249            bail!(
250                "Model '{}' not found for provider '{}'. Check docs/models.json.",
251                config.agent.default_model,
252                config.agent.provider
253            );
254        }
255
256        // Check API key — skip for built-in OpenAI (multi-source auth).
257        if !is_custom_provider && !is_codex_provider && !is_openai_provider && managed_auth_provider.is_none() {
258            get_api_key_with_mode(
259                &config.agent.provider,
260                &ApiKeySources::default(),
261                config.agent.credential_storage_mode,
262            )
263            .with_context(|| {
264                format!(
265                    "API key not found for provider '{}'. Set {} environment variable.",
266                    config.agent.provider,
267                    config.agent.provider.to_uppercase()
268                )
269            })?;
270        }
271
272        Ok(())
273    }
274}
275
276fn configured_managed_auth_provider(config: &VTCodeConfig) -> Option<Provider> {
277    config
278        .agent
279        .provider
280        .parse::<Provider>()
281        .ok()
282        .filter(|provider| provider.uses_managed_auth())
283}
284
285fn is_managed_auth_model(provider: Option<Provider>, model: &str) -> bool {
286    matches!(provider, Some(Provider::Copilot)) && !model.trim().is_empty()
287}
288
289/// Results from configuration validation
290#[derive(Debug, Default, Clone)]
291pub struct ValidationResult {
292    pub errors: Vec<String>,
293    pub warnings: Vec<String>,
294}
295
296pub fn check_prompt_cache_retention_compat(config: &VTCodeConfig, model: &str, provider: &str) -> Option<String> {
297    if !Provider::OpenAI.name_matches(provider) {
298        return None;
299    }
300
301    if let Some(retention) = config.prompt_cache.providers.openai.prompt_cache_retention {
302        if retention == PromptCacheRetention::Unknown {
303            return Some("prompt_cache_retention must be one of: in_memory, 24h".to_string());
304        }
305        if !RESPONSES_API_MODELS.contains(&model) {
306            return Some(format!(
307                "`prompt_cache_retention` is set but the selected model '{model}' does not use the OpenAI Responses API. The setting will be ignored for this model. Run `vtcode models list --provider openai` to see supported Responses API models."
308            ));
309        }
310    }
311
312    None
313}
314
315pub fn check_openai_hosted_shell_compat(config: &VTCodeConfig, model: &str, provider: &str) -> Option<String> {
316    if !Provider::OpenAI.name_matches(provider) {
317        return None;
318    }
319
320    let hosted_shell = &config.provider.openai.hosted_shell;
321    if !hosted_shell.enabled {
322        return None;
323    }
324
325    if !RESPONSES_API_MODELS.contains(&model) {
326        return Some(format!(
327            "`provider.openai.hosted_shell.enabled` is set but the selected model '{model}' does not use the OpenAI Responses API. VT Code will ignore hosted shell and keep the local shell tool for this model."
328        ));
329    }
330
331    if !hosted_shell.has_valid_reference_target() {
332        return Some(
333            "`provider.openai.hosted_shell.environment = \"container_reference\"` requires a non-empty `provider.openai.hosted_shell.container_id`. VT Code will ignore hosted shell until a container ID is configured."
334                .to_string(),
335        );
336    }
337
338    if hosted_shell.uses_container_reference()
339        && (!hosted_shell.file_ids.is_empty()
340            || !hosted_shell.skills.is_empty()
341            || hosted_shell.network_policy.is_allowlist())
342    {
343        return Some(
344            "`provider.openai.hosted_shell.file_ids`, `provider.openai.hosted_shell.skills`, and allowlist `provider.openai.hosted_shell.network_policy` settings are only used with `container_auto`. VT Code will ignore those fields while `container_reference` is selected."
345                .to_string(),
346        );
347    }
348
349    if let Some(message) = hosted_shell.first_invalid_skill_message() {
350        return Some(format!("{message} VT Code will ignore hosted shell until the mounted skills are corrected."));
351    }
352
353    if let Some(message) = hosted_shell.first_invalid_network_policy_message() {
354        return Some(format!(
355            "{message} VT Code will ignore hosted shell until the hosted shell network policy is corrected."
356        ));
357    }
358
359    None
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365    use serial_test::serial;
366    use std::fs;
367    use tempfile::TempDir;
368
369    fn create_test_models_db() -> TempDir {
370        let dir = TempDir::new().unwrap();
371        let models_json = r#"{
372  "google": {
373    "id": "google",
374    "default_model": "gemini-3-flash-preview",
375    "models": {
376      "gemini-3-flash-preview": {
377        "context": 1048576
378      }
379    }
380  },
381  "openai": {
382    "id": "openai",
383    "default_model": "gpt-5",
384    "models": {
385      "gpt-5": {
386        "context": 128000
387      }
388    }
389  }
390}"#;
391        fs::write(dir.path().join("models.json"), models_json).unwrap();
392        dir
393    }
394
395    #[test]
396    fn loads_models_database() {
397        let dir = create_test_models_db();
398        let db = ModelsDatabase::from_file(&dir.path().join("models.json")).unwrap();
399
400        assert!(db.model_exists("google", "gemini-3-flash-preview"));
401        assert!(db.model_exists("openai", "gpt-5"));
402        assert!(!db.model_exists("google", "nonexistent"));
403    }
404
405    #[test]
406    fn gets_context_window() {
407        let dir = create_test_models_db();
408        let db = ModelsDatabase::from_file(&dir.path().join("models.json")).unwrap();
409
410        assert_eq!(db.get_context_window("google", "gemini-3-flash-preview"), Some(1048576));
411        assert_eq!(db.get_context_window("openai", "gpt-5"), Some(128000));
412        assert_eq!(db.get_context_window("google", "nonexistent"), None);
413    }
414
415    #[test]
416    fn validates_model_exists() {
417        let dir = create_test_models_db();
418        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
419        let mut config = VTCodeConfig::default();
420        config.agent.provider = "google".to_owned();
421        config.agent.default_model = "gemini-3-flash-preview".to_owned();
422
423        let result = validator.validate(&config).unwrap();
424        // Model exists, so there should be no model-specific lookup error.
425        assert!(
426            !result
427                .errors
428                .iter()
429                .any(|e| { e.contains("Model 'gemini-3-flash-preview' not found for provider 'google'") })
430        );
431    }
432
433    #[test]
434    fn custom_provider_skips_builtin_model_catalog_checks() {
435        let dir = create_test_models_db();
436        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
437        let mut config = VTCodeConfig::default();
438        config.agent.provider = "mycorp".to_owned();
439        config.agent.default_model = "totally-custom-model".to_owned();
440        config.custom_providers.push(vtcode_config::core::CustomProviderConfig {
441            name: "mycorp".to_string(),
442            display_name: "MyCorporateName".to_string(),
443            base_url: "https://llm.example/v1".to_string(),
444            context_window: None,
445            api_key_env: "MYCORP_API_KEY".to_string(),
446            auth: None,
447            model: "totally-custom-model".to_string(),
448            models: Vec::new(),
449            ..vtcode_config::core::CustomProviderConfig::default()
450        });
451
452        let result = validator.validate(&config).unwrap();
453
454        assert!(result.errors.is_empty());
455    }
456
457    #[test]
458    fn codex_provider_skips_builtin_model_and_api_key_checks() {
459        let dir = create_test_models_db();
460        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
461        let mut config = VTCodeConfig::default();
462        config.agent.provider = "codex".to_owned();
463        config.agent.default_model = "managed-by-codex".to_owned();
464
465        let result = validator.validate(&config).unwrap();
466
467        assert!(result.errors.is_empty());
468    }
469
470    #[test]
471    fn copilot_managed_auth_model_accepts_live_raw_ids() {
472        assert!(is_managed_auth_model(Some(Provider::Copilot), "gpt-5-codex"));
473        assert!(!is_managed_auth_model(Some(Provider::Copilot), "   "));
474    }
475
476    #[test]
477    fn detects_missing_model() {
478        let dir = create_test_models_db();
479        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
480        let mut config = VTCodeConfig::default();
481        config.agent.provider = "google".to_owned();
482        config.agent.default_model = "nonexistent-model".to_owned();
483
484        let result = validator.validate(&config).unwrap();
485        assert!(result.errors.iter().any(|e| e.contains("not found")));
486    }
487
488    #[test]
489    fn detects_context_window_exceeded() {
490        let dir = create_test_models_db();
491        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
492        let mut config = VTCodeConfig::default();
493        config.agent.provider = "google".to_owned();
494        config.agent.default_model = "gemini-3-flash-preview".to_owned();
495        config.context.max_context_tokens = 2000000; // Exceeds 1048576 limit
496
497        let result = validator.validate(&config).unwrap();
498        assert!(result.warnings.iter().any(|w| w.contains("exceeds")));
499    }
500
501    #[test]
502    fn retention_warning_for_non_responses_model() {
503        let mut cfg = VTCodeConfig::default();
504        cfg.prompt_cache.providers.openai.prompt_cache_retention = Some(PromptCacheRetention::H24);
505        let msg = check_prompt_cache_retention_compat(&cfg, "gpt-oss-20b", "openai");
506        assert!(msg.is_some());
507    }
508
509    #[test]
510    fn retention_ok_for_responses_model() {
511        let mut cfg = VTCodeConfig::default();
512        cfg.prompt_cache.providers.openai.prompt_cache_retention = Some(PromptCacheRetention::H24);
513        let msg =
514            check_prompt_cache_retention_compat(&cfg, crate::config::constants::models::openai::GPT_5_6, "openai");
515        assert!(msg.is_none());
516    }
517
518    #[test]
519    fn retention_ok_for_gpt_alias() {
520        let mut cfg = VTCodeConfig::default();
521        cfg.prompt_cache.providers.openai.prompt_cache_retention = Some(PromptCacheRetention::H24);
522        let msg = check_prompt_cache_retention_compat(&cfg, crate::config::constants::models::openai::GPT, "openai");
523        assert!(msg.is_none());
524    }
525
526    #[test]
527    fn hosted_shell_warning_for_non_responses_model() {
528        let mut cfg = VTCodeConfig::default();
529        cfg.provider.openai.hosted_shell.enabled = true;
530
531        let msg = check_openai_hosted_shell_compat(&cfg, "gpt-oss-20b", "openai");
532        assert!(msg.is_some());
533    }
534
535    #[test]
536    fn hosted_shell_warning_for_missing_container_reference_id() {
537        let mut cfg = VTCodeConfig::default();
538        cfg.provider.openai.hosted_shell.enabled = true;
539        cfg.provider.openai.hosted_shell.environment =
540            crate::config::core::OpenAIHostedShellEnvironment::ContainerReference;
541
542        let msg = check_openai_hosted_shell_compat(&cfg, crate::config::constants::models::openai::GPT_5, "openai");
543        assert!(msg.is_some());
544    }
545
546    #[test]
547    fn hosted_shell_warning_for_auto_only_fields_on_container_reference() {
548        let mut cfg = VTCodeConfig::default();
549        cfg.provider.openai.hosted_shell.enabled = true;
550        cfg.provider.openai.hosted_shell.environment =
551            crate::config::core::OpenAIHostedShellEnvironment::ContainerReference;
552        cfg.provider.openai.hosted_shell.container_id = Some("cntr_123".to_string());
553        cfg.provider.openai.hosted_shell.file_ids = vec!["file_123".to_string()];
554        cfg.provider.openai.hosted_shell.network_policy.policy_type =
555            vtcode_config::core::OpenAIHostedShellNetworkPolicyType::Allowlist;
556        cfg.provider.openai.hosted_shell.network_policy.allowed_domains = vec!["httpbin.org".to_string()];
557
558        let msg = check_openai_hosted_shell_compat(&cfg, crate::config::constants::models::openai::GPT_5, "openai");
559        assert!(msg.is_some());
560    }
561
562    #[test]
563    fn hosted_shell_ok_for_valid_responses_config() {
564        let mut cfg = VTCodeConfig::default();
565        cfg.provider.openai.hosted_shell.enabled = true;
566
567        let msg = check_openai_hosted_shell_compat(&cfg, crate::config::constants::models::openai::GPT_5_6, "openai");
568        assert!(msg.is_none());
569    }
570
571    #[test]
572    fn hosted_shell_ok_for_gpt_alias() {
573        let mut cfg = VTCodeConfig::default();
574        cfg.provider.openai.hosted_shell.enabled = true;
575
576        let msg = check_openai_hosted_shell_compat(&cfg, crate::config::constants::models::openai::GPT, "openai");
577        assert!(msg.is_none());
578    }
579
580    #[test]
581    fn hosted_shell_warning_for_empty_skill_reference_id() {
582        let mut cfg = VTCodeConfig::default();
583        cfg.provider.openai.hosted_shell.enabled = true;
584        cfg.provider.openai.hosted_shell.skills = vec![vtcode_config::core::OpenAIHostedSkill::SkillReference {
585            skill_id: "   ".to_string(),
586            version: vtcode_config::core::OpenAIHostedSkillVersion::default(),
587        }];
588
589        let msg = check_openai_hosted_shell_compat(&cfg, "gpt-5.6-sol", "openai");
590
591        assert!(
592            msg.as_deref()
593                .unwrap_or_default()
594                .contains("provider.openai.hosted_shell.skills[0].skill_id")
595        );
596    }
597
598    #[test]
599    fn hosted_shell_warning_for_empty_inline_bundle() {
600        let mut cfg = VTCodeConfig::default();
601        cfg.provider.openai.hosted_shell.enabled = true;
602        cfg.provider.openai.hosted_shell.skills =
603            vec![vtcode_config::core::OpenAIHostedSkill::Inline { bundle_b64: " ".to_string(), sha256: None }];
604
605        let msg = check_openai_hosted_shell_compat(&cfg, "gpt-5.6-sol", "openai");
606
607        assert!(
608            msg.as_deref()
609                .unwrap_or_default()
610                .contains("provider.openai.hosted_shell.skills[0].bundle_b64")
611        );
612    }
613
614    #[test]
615    fn hosted_shell_warning_for_empty_allowlist_domains() {
616        let mut cfg = VTCodeConfig::default();
617        cfg.provider.openai.hosted_shell.enabled = true;
618        cfg.provider.openai.hosted_shell.network_policy.policy_type =
619            vtcode_config::core::OpenAIHostedShellNetworkPolicyType::Allowlist;
620
621        let msg = check_openai_hosted_shell_compat(&cfg, "gpt-5.6-sol", "openai");
622
623        assert!(msg.as_deref().unwrap_or_default().contains("network_policy.allowed_domains"));
624    }
625
626    #[test]
627    fn hosted_shell_warning_for_secret_domain_outside_allowlist() {
628        let mut cfg = VTCodeConfig::default();
629        cfg.provider.openai.hosted_shell.enabled = true;
630        cfg.provider.openai.hosted_shell.network_policy.policy_type =
631            vtcode_config::core::OpenAIHostedShellNetworkPolicyType::Allowlist;
632        cfg.provider.openai.hosted_shell.network_policy.allowed_domains = vec!["pypi.org".to_string()];
633        cfg.provider.openai.hosted_shell.network_policy.domain_secrets =
634            vec![vtcode_config::core::OpenAIHostedShellDomainSecret {
635                domain: "httpbin.org".to_string(),
636                name: "API_KEY".to_string(),
637                value: "secret".to_string(),
638            }];
639
640        let msg = check_openai_hosted_shell_compat(&cfg, "gpt-5.6-sol", "openai");
641
642        assert!(msg.as_deref().unwrap_or_default().contains("domain_secrets[0].domain"));
643    }
644
645    #[test]
646    fn validate_surfaces_hosted_shell_warning() {
647        let dir = create_test_models_db();
648        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
649        let mut config = VTCodeConfig::default();
650        config.agent.provider = "openai".to_owned();
651        config.agent.default_model = "gpt-5.6".to_owned();
652        config.provider.openai.hosted_shell.enabled = true;
653        config.provider.openai.hosted_shell.skills = vec![vtcode_config::core::OpenAIHostedSkill::SkillReference {
654            skill_id: "   ".to_string(),
655            version: vtcode_config::core::OpenAIHostedSkillVersion::default(),
656        }];
657
658        let result = validator.validate(&config).unwrap();
659
660        assert!(
661            result
662                .warnings
663                .iter()
664                .any(|warning| { warning.contains("provider.openai.hosted_shell.skills[0].skill_id") })
665        );
666    }
667
668    #[test]
669    fn validate_surfaces_invalid_anthropic_fallbacks_warning() {
670        let dir = create_test_models_db();
671        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
672        let mut config = VTCodeConfig::default();
673        let target = vtcode_config::core::AnthropicFallbackTarget {
674            model: "claude-opus-4-8".to_string(),
675            max_tokens: None,
676        };
677        config.provider.anthropic.fallbacks =
678            vtcode_config::core::AnthropicFallbacks::Models(vec![target.clone(), target]);
679
680        let result = validator.validate(&config).unwrap();
681
682        assert!(
683            result
684                .warnings
685                .iter()
686                .any(|warning| warning.contains("provider.anthropic.fallbacks") && warning.contains("distinct"))
687        );
688    }
689
690    // ── OpenAI multi-source auth: static validation skip ──
691
692    #[test]
693    fn openai_without_api_key_does_not_emit_static_warning() {
694        // Built-in OpenAI supports ChatGPT OAuth + Codex fallback + API key.
695        // The static API-key check must be skipped so users with only a
696        // ChatGPT subscription don't see a false "API key not found" error.
697        let dir = create_test_models_db();
698        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
699        let mut config = VTCodeConfig::default();
700        config.agent.provider = "openai".to_owned();
701        config.agent.default_model = "gpt-5".to_owned();
702
703        let result = validator.validate(&config).unwrap();
704        assert!(
705            !result
706                .errors
707                .iter()
708                .any(|e| e.contains("API key not found for provider 'openai'")),
709            "OpenAI should not emit a static API-key warning: errors={:?}",
710            result.errors
711        );
712    }
713
714    #[test]
715    fn openai_quick_validate_without_api_key_does_not_fail() {
716        // Same check for quick_validate — OpenAI should not bail on missing API key.
717        let dir = create_test_models_db();
718        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
719        let mut config = VTCodeConfig::default();
720        config.agent.provider = "openai".to_owned();
721        config.agent.default_model = "gpt-5".to_owned();
722
723        // Should succeed (no API key error) even without OPENAI_API_KEY set.
724        let result = validator.quick_validate(&config);
725        assert!(result.is_ok(), "quick_validate should not fail for OpenAI without API key: {result:?}");
726    }
727
728    #[test]
729    #[serial]
730    fn non_openai_provider_still_requires_api_key() {
731        // A non-OpenAI, non-Codex provider without an API key must still
732        // produce a static API-key error. Use a fictional provider that is
733        // very unlikely to have an env var set on the developer's machine.
734        let dir = TempDir::new().unwrap();
735        let models_json = r#"{
736          "ztestprov": {
737            "id": "ztestprov",
738            "default_model": "zmodel",
739            "models": { "zmodel": { "context": 128000 } }
740          }
741        }"#;
742        fs::write(dir.path().join("models.json"), models_json).unwrap();
743        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
744        let mut config = VTCodeConfig::default();
745        config.agent.provider = "ztestprov".to_owned();
746        config.agent.default_model = "zmodel".to_owned();
747        // Ensure no env var is set for this fictional provider.
748        let prev = std::env::var("ZTESTPROV_API_KEY").ok();
749        vtcode_commons::env_lock::set_var("ZTESTPROV_API_KEY", "");
750
751        let result = validator.validate(&config).unwrap();
752        vtcode_commons::env_lock::lock().restore_var("ZTESTPROV_API_KEY", prev.as_deref());
753
754        assert!(
755            result
756                .errors
757                .iter()
758                .any(|e| e.contains("API key not found for provider 'ztestprov'")),
759            "non-OpenAI provider should still require an API key: errors={:?}",
760            result.errors
761        );
762    }
763
764    #[test]
765    fn deprecated_openai_model_diagnostic_is_present() {
766        // A deprecated OpenAI model that is not in the model DB should produce
767        // the deprecation diagnostic with a replacement suggestion.
768        let dir = create_test_models_db();
769        let validator = ConfigValidator::new(&dir.path().join("models.json")).unwrap();
770        let mut config = VTCodeConfig::default();
771        config.agent.provider = "openai".to_owned();
772        config.agent.default_model = "o3".to_owned(); // deprecated → gpt-5.6-sol
773
774        let result = validator.validate(&config).unwrap();
775        assert!(
776            result
777                .errors
778                .iter()
779                .any(|e| e.contains("gpt-5.6-sol") || e.contains("deprecated") || e.contains("Update your config")),
780            "deprecated OpenAI model should produce a replacement diagnostic: errors={:?}",
781            result.errors
782        );
783    }
784}