Skip to content

ACP model switcher fails with OPENROUTER_API_KEY not found when the active provider is a catalog OpenAI-compatible profile (e.g. opencode-go) #849

Closed

Description

@sergiomeneses

Summary

When jcode is used as a Zed external agent over ACP, the model selector exposed via
configOptions / session/set_config_option lists models from the active
OpenAI-compatible profile's catalog, but switching to any of them fails with
OPENROUTER_API_KEY not found in environment or ~/.config/jcode/openrouter.env.
The session silently stays on the fallback model (deepseek-v4-pro). The advertised
models are unselectable, and the host receives a JSON-RPC error instead of a model change.

Environment

  • jcode v0.71.1 (dd8755f), Linux x86_64
  • Host: Zed via ACP (client_instance_id=acp)
  • Active provider: opencode-go catalog profile → https://opencode.ai/zen/go/v1,
    auth OPENCODE_GO_API_KEY (in ~/.config/jcode/opencode-go.env); [providers]
    empty in config.toml
  • OPENROUTER_API_KEY is not configured anywhere (no env var, no
    ~/.config/jcode/openrouter.env)

Steps to reproduce

  1. Configure only the opencode-go profile (jcode login --provider opencode-go)
    and no OpenRouter key.
  2. Start a session in Zed with jcode acp as the external agent. The default model
    deepseek-v4-pro works (streams to https://opencode.ai/zen/go/v1).
  3. Open the agent panel model selector (populated from ACP configOptions) and pick
    deepseek-v4-flash.
  4. Zed sends session/set_config_option (configId: "model", value: "deepseek-v4-flash");
    jcode logs server_model_change_failed and the model stays deepseek-v4-pro.

Expected behavior

Switching to a model that the active profile's own catalog already serves should
select it on that same profile (same endpoint and credentials). The selector should
only present models that can actually be activated.

Actual behavior

Every switch to a non-default model fails:

[ERROR] EVENT event=server_model_change_failed error="OPENROUTER_API_KEY not found in environment or /home/xxx/.config/jcode/openrouter.env (retried after reloading auth from disk: OPENROUTER_API_KEY not fou..." fallback_model=deepseek-v4-pro

The ACP client receives a JSON-RPC error (Failed to set model: ...) and the session
keeps running deepseek-v4-pro.

Root cause

The ACP layer sends bare model ids. session_config_options
(src/cli/acp.rs:1015) builds option values from available_models (deduped bare
ids from listable_model_names_from_routes), and handle_set_config_option
(src/cli/acp.rs:506) forwards Request::SetModel { model: "deepseek-v4-flash" }
verbatim.

In MultiProvider::set_model (crates/jcode-base/src/provider/mod.rs), the
unprefixed id first hits the "keep unprefixed names on that active endpoint" branch
(~L1922):

if self.active_provider() == ActiveProvider::OpenRouter
    && self.active_openrouter_execution_provider()
        .is_some_and(|provider| !provider.supports_provider_routing_features())
{
    return self.set_model_on_provider(ActiveProvider::OpenRouter, requested_model);
}

That branch intends to keep bare ids on the active OpenAI-compatible endpoint, but
the OpenRouter arm it calls then computes needs_rebind
(provider/mod.rs:1138) as true whenever the slot is an OpenAI-compatible
catalog profile runtime whose profile id is not the generic openai-compatible
profile (only OPENAI_COMPAT_PROFILE.id is exempt):

profile.id != crate::provider_catalog::OPENAI_COMPAT_PROFILE.id

The slot is therefore rebound to the real OpenRouter API-key runtime via
new_openrouter_api_key_runtime() (crates/jcode-provider-openrouter-runtime/src/lib.rs:1582),
which fails when OPENROUTER_API_KEY is absent, even though the requested model is
already served by the active profile's own catalog. set_model_with_auth_refresh
retries once after reloading auth from disk, fails again, and send_model_changed_result
logs server_model_change_failed with the previous model as fallback.

The TUI picker avoids this by emitting route-qualified specs (<profile>:<model>,
see issue #444); the ACP path, /model <bare-id> and session-resume paths send bare
ids and hit the rebind. Confirmed present on both master and v0.71.1.

Suggested fix

  1. Resolver (recommended, B1): in the OpenRouter arm of
    set_model_on_provider_with_credential_modes, skip the rebind when the active
    profile's own route catalog already serves the requested model
    (route.model == model with api_method == "openai-compatible:<active profile>"
    and available), and just call set_model on the existing slot. This matches the
    intent of the "keep unprefixed names on the active endpoint" branch and fixes every
    bare-id path (ACP, /model <id>, session resume), not just the ACP surface.
  2. ACP layer (B2): build configOptions model values as profile-qualified specs
    (<profile>:<model>, e.g. opencode-go:deepseek-v4-flash) with the bare id as
    display name, deduplicating in favor of the active profile (same preference rule as
    openai_compatible_profile_owning_model). This is the server-side analog of the
    workaround used in ACP layer: no model catalog, no session/set_model, no reasoning-effort control #813.

Related issues

Activity

  1. added
    bug
    triage: reproducible
    autonomous: clear
    priority: high
    on Aug 9, 2026
  2. 1jehuang commented on Aug 9, 2026

    @1jehuang
    Owner

    Confirmed from the resolver path. A bare model ID already served by the active named catalog profile can incorrectly trigger a native OpenRouter rebind. I am preparing a focused resolver fix that preserves the active profile, with regression coverage.

    --- — Jcode agent (automated triage), on behalf of @1jehuang

  3. added
    triage: fixed-pending-release
    on Aug 9, 2026
  4. 1jehuang commented on Aug 9, 2026

    @1jehuang
    Owner

    The verified fix is now in PR #856. Focused regressions passed, and the combined TUI build completed successfully.

    --- — Jcode agent (automated triage), on behalf of @1jehuang

  5. added a commit that references this issue on Aug 9, 2026
    13cc579
  6. added a commit that references this issue on Aug 15, 2026
    a8e0afd
  7. maxivillus commented on Aug 18, 2026

    @maxivillus

    Thanks for the fix in #856 — the session/set_config_option model-switch path is fixed.
    One related path is still broken on v0.77.1 though:

    Resumed ACP sessions. When an ACP session is resumed and its provider context is still
    an OpenAI-compatible runtime (e.g. a proxy profile), a bare model ID from the gpt-* family
    is still resolved back to the generic native-OpenRouter slot — the session then fails with
    OPENROUTER_API_KEY not found (or hits the wrong backend) instead of routing to the
    configured native OpenAI OAuth runtime that owns the model family.

    The reverse-check of the #856 fix against v0.77.1 confirms it only covers the switcher
    path, not session resume. We carry a small local patch for it (bare gpt-* → native OAuth
    runtime on resume; ~60 lines incl. regression tests) — happy to open a PR if the fix shape
    is acceptable.

    Reference patch (applies cleanly on v0.77.1, diff inline):

    diff --git a/crates/jcode-base/src/provider/mod.rs b/crates/jcode-base/src/provider/mod.rs
    index 90cb3df..14327c9 100644
    --- a/crates/jcode-base/src/provider/mod.rs
    +++ b/crates/jcode-base/src/provider/mod.rs
    @@ -1924,11 +1924,25 @@ impl Provider for MultiProvider {
             // resemble a globally known model family. Picker and slash-command
             // route specs carry explicit prefixes, so the branch above can switch
             // to any configured provider at any time.
    -        if self.active_provider() == ActiveProvider::OpenRouter
    +        //
    +        // ACP clients, however, commonly send bare model IDs. A resumed
    +        // session can still be attached to a custom endpoint (for example
    +        // DeepSeek) while the requested ID is a known model from a configured
    +        // native provider. In that case preserving the stale endpoint shadows
    +        // the native route and can turn an OpenAI OAuth model into an
    +        // OpenRouter API-key lookup. Let known OpenAI models reach the native
    +        // provider when that runtime is available; an explicit profile prefix
    +        // remains the way to select the compatible endpoint deliberately.
    +        let active_compatible_provider_owns_model = self.active_provider()
    +            == ActiveProvider::OpenRouter
                 && self
                     .active_openrouter_execution_provider()
                     .is_some_and(|provider| !provider.supports_provider_routing_features())
    -        {
    +            && !(self.openai_provider().is_some()
    +                && known_openai_model_ids()
    +                    .iter()
    +                    .any(|known| known == requested_model));
    +        if active_compatible_provider_owns_model {
                 return self.set_model_on_provider(ActiveProvider::OpenRouter, requested_model);
             }
     
    diff --git a/crates/jcode-base/src/provider/tests/model_resolution.rs b/crates/jcode-base/src/provider/tests/model_resolution.rs
    index 7b449dd..75504dd 100644
    --- a/crates/jcode-base/src/provider/tests/model_resolution.rs
    +++ b/crates/jcode-base/src/provider/tests/model_resolution.rs
    @@ -740,6 +740,50 @@ fn test_active_compatible_route_treats_claude_like_bare_model_as_provider_local(
         });
     }
     
    +#[test]
    +fn test_active_compatible_route_yields_to_known_openai_model_when_openai_is_configured() {
    +    // A resumed ACP session may still hold a direct DeepSeek runtime while the
    +    // task asks for a bare OpenAI model id. The native OpenAI runtime must win
    +    // when that model is known and OpenAI is configured, otherwise the shared
    +    // OpenRouter slot attempts an unrelated OPENROUTER_API_KEY route.
    +    with_clean_provider_test_env(|| {
    +        let runtime = enter_test_runtime();
    +        let _runtime_guard = runtime.enter();
    +        with_env_var("DEEPSEEK_API_KEY", "test-deepseek-key", || {
    +            let deepseek = crate::provider_catalog::openai_compatible_profile_by_id("deepseek")
    +                .expect("DeepSeek profile exists");
    +            crate::provider_catalog::force_apply_openai_compatible_profile_env(Some(deepseek));
    +            let openrouter =
    +                test_openrouter_runtime().expect("DeepSeek-compatible runtime should initialize");
    +            let provider = MultiProvider {
    +                claude: RwLock::new(None),
    +                anthropic: RwLock::new(None),
    +                openai: RwLock::new(Some(test_openai_runtime() as Arc<dyn Provider>)),
    +                copilot_api: RwLock::new(None),
    +                antigravity: RwLock::new(None),
    +                gemini: RwLock::new(None),
    +                cursor: RwLock::new(None),
    +                bedrock: RwLock::new(None),
    +                openrouter: RwLock::new(Some(openrouter)),
    +                openai_compatible_profiles: RwLock::new(std::collections::HashMap::new()),
    +                active_openai_compatible_profile: RwLock::new(None),
    +                active: RwLock::new(ActiveProvider::OpenRouter),
    +                use_claude_cli: false,
    +                startup_notices: RwLock::new(Vec::new()),
    +                initial_provider: Some(ActiveProvider::OpenRouter),
    +                routes_memo: std::sync::Mutex::new(None),
    +                post_auth_refreshes_pending: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
    +            };
    +
    +            provider
    +                .set_model("gpt-5.6-luna")
    +                .expect("known OpenAI model should leave stale DeepSeek runtime");
    +            assert_eq!(provider.active_provider(), ActiveProvider::OpenAI);
    +            assert_eq!(provider.model(), "gpt-5.6-luna");
    +        })
    +    });
    +}
    +
     #[test]
     fn test_active_compatible_route_preserves_custom_at_sign_model_ids() {
         with_clean_provider_test_env(|| {
  8. added 5 commits that reference this issue on Aug 30, 2026
    24ed3a6
    4f6cdf4
    bb4530b
    21bcc5b
    5aaba9f
  9. added a commit that references this issue on Sep 18, 2026
    fa4c401
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    autonomous: clearbugpriority: hightriage: fixed-pending-releasetriage: reproducible

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions