vtcode-config 0.185.4

Config loader components shared across VT Code and downstream adopters
Documentation
use super::*;

/// Serialize-test helper mirroring `root/tests.rs::with_env_var`.
fn with_env_var<F>(key: &str, value: Option<&str>, f: F)
where
    F: FnOnce(),
{
    let previous = crate::env_helpers::test_env_overrides::get(key);
    crate::env_helpers::test_env_overrides::set(key, value);
    f();
    crate::env_helpers::test_env_overrides::restore(key, previous);
}

#[test]
fn tools_config_defaults_to_vt_code_profile() {
    assert_eq!(ToolsConfig::default().profile, ToolProfile::VtCode);
}

#[test]
fn code_mode_defaults_off_without_env() {
    with_env_var(crate::constants::env_vars::VTCODE_EXPERIMENTAL_CODE_MODE, None, || {
        assert!(!ToolsConfig::default().code_mode.enabled);
    });
}

#[test]
fn code_mode_env_enables_when_config_unset() {
    with_env_var(crate::constants::env_vars::VTCODE_EXPERIMENTAL_CODE_MODE, Some("1"), || {
        // Missing key falls back to the env-aware serde default.
        let config: ToolsConfig = toml::from_str("profile = \"vt_code\"").expect("should parse");
        assert!(config.code_mode.enabled);
    });
}

#[test]
fn code_mode_env_overrides_explicit_config() {
    with_env_var(crate::constants::env_vars::VTCODE_EXPERIMENTAL_CODE_MODE, Some("0"), || {
        // Serde `default` only fills missing keys: an explicit
        // `[code_mode] enabled` always survives parsing. The
        // documented env-wins contract is resolved post-load in
        // `ToolRegistry::apply_config_policies`; parsing keeps the
        // file value verbatim.
        let config: ToolsConfig = toml::from_str("[code_mode]\nenabled = true").expect("should parse");
        assert!(config.code_mode.enabled);
    });
}

#[test]
fn code_mode_explicit_config_wins_without_env() {
    with_env_var(crate::constants::env_vars::VTCODE_EXPERIMENTAL_CODE_MODE, None, || {
        let config: ToolsConfig = toml::from_str("[code_mode]\nenabled = true").expect("should parse");
        assert!(config.code_mode.enabled);
    });
}

#[test]
fn vt_code_profile_round_trips_through_toml() {
    let config: ToolsConfig = toml::from_str("profile = \"vt_code\"").expect("vt_code tool profile should parse");
    assert_eq!(config.profile, ToolProfile::VtCode);

    let serialised = toml::to_string(&config).expect("tools config should serialise");
    assert!(serialised.contains("profile = \"vt_code\""));

    let round_tripped: ToolsConfig = toml::from_str(&serialised).expect("serialised tools config should parse");
    assert_eq!(round_tripped.profile, ToolProfile::VtCode);
}

#[test]
fn tool_profile_round_trips_through_toml() {
    let config: ToolsConfig =
        toml::from_str("profile = \"advanced_vtcode\"").expect("advanced tool profile should parse");
    assert_eq!(config.profile, ToolProfile::AdvancedVtCode);

    let serialised = toml::to_string(&config).expect("tools config should serialise");
    assert!(serialised.contains("profile = \"advanced_vtcode\""));

    let round_tripped: ToolsConfig = toml::from_str(&serialised).expect("serialised tools config should parse");
    assert_eq!(round_tripped.profile, ToolProfile::AdvancedVtCode);
}

#[test]
fn tool_profile_rejects_unintended_derived_spelling() {
    let error = toml::from_str::<ToolsConfig>("profile = \"advanced_vt_code\"")
        .expect_err("unintended spelling should fail")
        .to_string();

    assert!(error.contains("unknown variant `advanced_vt_code`"), "{error}");
    assert!(error.contains("`advanced_vtcode`"), "{error}");
}

#[test]
fn invalid_tool_profile_reports_allowed_values() {
    let error = toml::from_str::<ToolsConfig>("profile = \"experimental\"")
        .expect_err("unknown tool profile should fail")
        .to_string();

    assert!(error.contains("unknown variant `experimental`"), "{error}");
    assert!(error.contains("`vt_code`"), "{error}");
    assert!(error.contains("`advanced_vtcode`"), "{error}");
}

#[cfg(feature = "schema")]
#[test]
fn tools_config_schema_includes_profile_values() {
    let schema = schemars::schema_for!(ToolsConfig);
    let schema_json = serde_json::to_value(schema).expect("schema should serialise");
    let schema_text = serde_json::to_string(&schema_json).expect("schema should stringify");

    assert!(schema_json["properties"].get("profile").is_some());
    assert!(schema_text.contains("vt_code"));
    assert!(schema_text.contains("advanced_vtcode"));
}

#[test]
fn editor_config_defaults_are_enabled() {
    let config = ToolsConfig::default();
    assert!(config.editor.enabled);
    assert!(config.editor.preferred_editor.is_empty());
    assert!(config.editor.suspend_tui);
}

#[test]
fn tools_config_ignores_removed_tool_loop_budget_key() {
    // `max_tool_loops` was removed; stale configs carrying it must still
    // parse (the key is pruned on the next save with a warning).
    let parsed: ToolsConfig = toml::from_str("max_tool_loops = 20").expect("stale loop-budget key must parse");
    assert_eq!(parsed.max_repeated_tool_calls, defaults::DEFAULT_MAX_REPEATED_TOOL_CALLS);
}

#[test]
fn tool_call_delay_for_rate_ignores_unset_or_zero_limits() {
    assert_eq!(tool_call_delay_for_rate(None), None);
    assert_eq!(tool_call_delay_for_rate(Some(0)), None);
}

#[test]
fn tool_call_delay_for_rate_uses_per_second_interval() {
    assert_eq!(tool_call_delay_for_rate(Some(4)), Some(Duration::from_millis(250)));
}

#[test]
fn default_tool_policies_only_seed_current_public_surface() {
    let config = ToolsConfig::default();

    assert_eq!(config.policies.get(tools::EXEC_COMMAND), Some(&ToolPolicy::Allow));
    assert_eq!(config.policies.get(tools::WRITE_STDIN), Some(&ToolPolicy::Allow));
    assert_eq!(config.policies.get(tools::CODE_SEARCH), Some(&ToolPolicy::Allow));
    assert_eq!(config.policies.get(tools::APPLY_PATCH), Some(&ToolPolicy::Prompt));
    for legacy_tool in [
        tools::UNIFIED_EXEC,
        tools::UNIFIED_SEARCH,
        tools::UNIFIED_FILE,
        tools::READ_FILE,
        tools::WRITE_FILE,
        tools::EDIT_FILE,
        tools::RUN_PTY_CMD,
        tools::READ_PTY_SESSION,
        tools::LIST_PTY_SESSIONS,
        tools::SEND_PTY_INPUT,
        tools::CLOSE_PTY_SESSION,
        tools::EXECUTE_CODE,
    ] {
        assert!(!config.policies.contains_key(legacy_tool));
    }
}

#[test]
fn client_tool_search_defaults_to_enabled() {
    let config = ToolsConfig::default();
    assert!(config.client_tool_search);

    let deserialized: ToolsConfig =
        toml::from_str("default_policy = \"prompt\"\n").expect("tools config should parse without client_tool_search");
    assert!(deserialized.client_tool_search);

    let disabled: ToolsConfig = toml::from_str(
        r#"
default_policy = "prompt"
client_tool_search = false
"#,
    )
    .expect("tools config should parse with client_tool_search disabled");
    assert!(!disabled.client_tool_search);
}

#[test]
fn editor_config_deserializes_from_toml() {
    let config: ToolsConfig = toml::from_str(
        r#"
default_policy = "prompt"

[editor]
enabled = false
preferred_editor = "code --wait"
suspend_tui = false
"#,
    )
    .expect("tools config should parse");

    assert!(!config.editor.enabled);
    assert_eq!(config.editor.preferred_editor, "code --wait");
    assert!(!config.editor.suspend_tui);
}

#[test]
fn web_search_config_deserializes_from_toml() {
    let config: ToolsConfig = toml::from_str(
        r#"
default_policy = "prompt"

[web_search]
provider = "duckduckgo"
max_results = 12
timeout_secs = 25
cooldown_ms = 1500
cache_ttl_secs = 120
session_max_requests = 5
"#,
    )
    .expect("tools config should parse");

    assert_eq!(config.web_search.provider, WebSearchProvider::Duckduckgo);
    assert_eq!(config.web_search.max_results, 12);
    assert_eq!(config.web_search.timeout_secs, 25);
    assert_eq!(config.web_search.cooldown_ms, 1500);
    assert_eq!(config.web_search.cache_ttl_secs, 120);
    assert_eq!(config.web_search.session_max_requests, 5);
}

#[test]
fn web_search_config_defaults_are_polite() {
    let config = WebSearchConfig::default();
    assert_eq!(config.provider, WebSearchProvider::Auto);
    assert_eq!(config.max_results, 8);
    assert_eq!(config.timeout_secs, 20);
    assert!(config.cooldown_ms >= 1_000);
    assert!(config.cache_ttl_secs >= 60);
    assert!(config.session_max_requests > 0);
}

#[test]
fn web_search_provider_serializes_lowercase() {
    // Serde rename_all = "snake_case" means enum variants serialize
    // lowercase, matching the LLM-facing schema strings.
    let json = serde_json::to_value(WebSearchProvider::Duckduckgo).unwrap();
    assert_eq!(json, serde_json::json!("duckduckgo"));
}

#[test]
fn web_search_provider_backend_id_is_canonical() {
    assert_eq!(WebSearchProvider::Auto.backend_id(), "duckduckgo");
    assert_eq!(WebSearchProvider::Auto.backend_id(), WebSearchProvider::Duckduckgo.backend_id());
}

#[test]
fn web_search_unsupported_provider_uses_generic_error() {
    let error = serde_json::from_value::<WebSearchProvider>(serde_json::json!("unsupported-provider"))
        .unwrap_err()
        .to_string();
    assert!(error.contains("unknown variant"));
    assert!(error.contains("auto"));
    assert!(error.contains("duckduckgo"));
}

#[test]
fn web_fetch_default_allowed_domains_seed_common_dev_sites() {
    // The defaults should include the sites the agent most commonly
    // needs (looking up a user, fetching a crate's README, etc.).
    // This is a regression test for the "who is vinhnx?" case where
    // the default `Restricted` mode blocked github.com / npmjs.com /
    // crates.io even though none of them are on the blocklist.
    //
    // After H1: the inline list was removed in favour of the TOML
    // allowlist, filtered to web-fetch-relevant categories. Hosts
    // that aren't in the TOML (`npmjs.com`, `www.npmjs.com`,
    // `docs.rs`, etc.) are no longer in the defaults — that's
    // intentional, see the allowlist policy in
    // `NetworkAllowlist::web_fetch_relevant_domains`.
    let allowed = WebFetchConfig::default().allowed_domains;
    for host in [
        "github.com",
        "api.github.com",
        "raw.githubusercontent.com",
        "crates.io",
        "index.crates.io",
        "registry.npmjs.org",
        "pypi.org",
    ] {
        assert!(allowed.iter().any(|d| d == host), "default allowed_domains should include {host}; got {allowed:?}");
    }
}

#[test]
fn web_fetch_default_allowed_domains_include_relevant_categories() {
    // The TOML allowlist is filtered to web-friendly categories for the
    // web_fetch defaults: search engines, package registries, code
    // hosting, web-crawl relays (minus defuddle.md), MCP servers, and
    // specialized knowledge bases. AI provider endpoints and dev
    // infrastructure are explicitly excluded (those need auth or
    // aren't useful as fetch targets).
    let allowed = WebFetchConfig::default().allowed_domains;
    for host in [
        "github.com",
        "crates.io",
        "registry.npmjs.org",
        "pypi.org",
        "en.wikipedia.org",
        "r.jina.ai",
        "api.tavily.com",
    ] {
        assert!(allowed.iter().any(|d| d == host), "default allowed_domains should include {host}; got {allowed:?}");
    }
}

#[test]
fn web_fetch_default_allowed_domains_exclude_ai_and_dev_infra() {
    // H1 (review): the old default merged every category. The new
    // default must not include AI provider endpoints (LLM inference
    // APIs that need auth), OAuth flows, dev infrastructure, OS-update
    // mirrors, or `defuddle.md` (which is a relay, not a fetch
    // target).
    //
    // Search APIs like `api.tavily.com` ARE allowed — those are
    // legitimate fetch targets the agent might query directly.
    let allowed = WebFetchConfig::default().allowed_domains;
    for host in [
        "api.anthropic.com",
        "api.openai.com",
        "api.fireworks.ai",
        "api.deepseek.com",
        "defuddle.md",
        "*.auth0.com",
        "*.workers.dev",
        "*.vercel.app",
        "us.i.posthog.com",
        "security.ubuntu.com",
        "archive.ubuntu.com",
    ] {
        assert!(
            !allowed.iter().any(|d| d == host),
            "default allowed_domains must NOT include {host}; got {allowed:?}"
        );
    }
}

#[test]
fn web_fetch_default_allowed_domains_preserves_wildcards_in_relevant_categories() {
    // The TOML has `*.vercel.app` in dev_infra and `*.clerk.accounts.dev`
    // in auth. After filtering for web_fetch, neither should remain.
    // A future TOML change that moves a wildcard into a web-relevant
    // category will be picked up here.
    let allowed = WebFetchConfig::default().allowed_domains;
    let wildcards: Vec<&str> = allowed.iter().map(|s| s.as_str()).filter(|s| s.starts_with("*.")).collect();
    assert!(
        wildcards.is_empty(),
        "expected no wildcards in web_fetch defaults (dev_infra/auth are excluded); got {wildcards:?}"
    );
}

#[test]
fn web_fetch_default_allowed_domains_returns_fresh_vec() {
    // `default_web_fetch_allowed_domains` is cached in a OnceLock, but
    // each call must return a fresh `Vec` so callers can mutate the
    // returned value without affecting the cached snapshot.
    let mut a = WebFetchConfig::default().allowed_domains;
    a.push("evil.example".to_string());
    let b = WebFetchConfig::default().allowed_domains;
    assert!(!b.iter().any(|d| d == "evil.example"));
}

#[test]
fn blocked_tool_caps_default_to_derived_total() {
    let config = ToolsConfig::default();
    assert!(config.max_total_blocked_tool_calls_per_turn.is_none());
    assert!(config.blocked_tool_thresholds.is_empty());
}

#[test]
fn blocked_tool_caps_deserialize_from_toml() {
    let config: ToolsConfig = toml::from_str(
        r#"
max_consecutive_blocked_tool_calls_per_turn = 3
max_total_blocked_tool_calls_per_turn = 10

[blocked_tool_thresholds]
exec_command = 3
code_search = 6
"#,
    )
    .expect("blocked tool caps should parse");
    assert_eq!(config.max_consecutive_blocked_tool_calls_per_turn, 3);
    assert_eq!(config.max_total_blocked_tool_calls_per_turn, Some(10));
    assert_eq!(config.blocked_tool_thresholds.get("exec_command"), Some(&3));
    assert_eq!(config.blocked_tool_thresholds.get("code_search"), Some(&6));
}