Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(opencode): mirror provider keys into config options (#477)
Call Whitec15db8ebb046
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 381dfd255..203eaf2a1 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -1351,7 +1351,24 @@ class AgentAuthService:logger_instance=logger,)except Exception as err: # noqa: BLE001- logger.warning("Failed to clean legacy OpenCode provider config for %s: %s", provider, err)+ logger.warning("Failed to clean OpenCode provider option apiKey for %s: %s", provider, err)++ async def _clear_opencode_provider_options_key_for_oauth(self, provider: str) -> None:+ """Remove a Vibe-managed API key after OpenCode OAuth succeeds.++ OpenCode builds SDK options from ``opencode.json`` before falling back+ to auth entries, so leaving ``provider.<id>.options.apiKey`` in place+ would make a successful OAuth login non-authoritative at runtime.+ """++ try:+ await asyncio.to_thread(+ remove_opencode_provider_api_key,+ provider,+ logger_instance=logger,+ )+ except Exception as err: # noqa: BLE001+ logger.warning("Failed to clear OpenCode provider option apiKey after OAuth for %s: %s", provider, err)async def _refresh_opencode_server(self) -> None:agent_service = getattr(self.controller, "agent_service", None)@@ -2344,10 +2361,12 @@ class AgentAuthService:timeout=self.setup_timeout_seconds,)flow.state = "verifying"- # OpenCode persists into auth.json itself; no extra subprocess- # verifier needed. We still ping the controller-refresh hook so- # the running OpenCode agent (and the Settings page on the- # next poll) sees the new auth state.+ # OpenCode persists into auth.json itself. Clear any Vibe-managed+ # provider option key so the new OAuth entry becomes the effective+ # credential, then ping the controller-refresh hook so the running+ # OpenCode agent (and the Settings page on the next poll) sees the+ # new auth state.+ await self._clear_opencode_provider_options_key_for_oauth(provider_id)await self._invoke_post_web_success_hook(flow.backend)flow.state = "success"except asyncio.TimeoutError:diff --git a/tests/test_save_opencode_provider_auth.py b/tests/test_save_opencode_provider_auth.pyindex 90364438c..269957c93 100644--- a/tests/test_save_opencode_provider_auth.py+++ b/tests/test_save_opencode_provider_auth.py@@ -144,6 +144,13 @@ def _save(provider_id: str, payload: dict) -> dict:return api.save_opencode_provider_auth(provider_id, payload)+def _read_opencode_config(home: Path) -> dict:+ from vibe.opencode_config import get_opencode_config_paths++ path = get_opencode_config_paths(home)[0]+ return json.loads(path.read_text(encoding="utf-8"))++def _save_model(provider_id: str, payload: dict) -> dict:return asyncio.run(api.save_opencode_provider_model_async(provider_id, payload))@@ -172,17 +179,59 @@ def test_base_url_absent_leaves_existing_value_untouched(fake_save_env) -> None:# Caller re-saves just the api_key: this used to wipe baseURL because# the server treated "absent" the same as "empty".result = _save("openai", {"api_key": "sk-new"})- # Save now also triggers ``restart_backend("opencode")`` so the- # daemon's in-memory cache picks up the new auth; ignore the- # ``restart`` key for the per-field assertions below.assert result.get("ok") is True- assert ("openai", "sk-new") in server.set_calls+ assert server.set_calls == []+ config = _read_opencode_config(home)+ assert config["provider"]["openai"]["options"]["apiKey"] == "sk-new"assert (read_opencode_provider_base_url("openai", home=home)== "https://existing.example")+def test_save_provider_auth_persists_api_key_in_provider_options(fake_save_env) -> None:+ """Keys entered in Vibe Remote are OpenCode provider options."""++ server, home = fake_save_env++ result = _save("deepseek", {"api_key": "sk-deepseek"})++ assert result.get("ok") is True+ assert server.set_calls == []+ config = _read_opencode_config(home)+ assert config["provider"]["deepseek"]["options"]["apiKey"] == "sk-deepseek"+++def test_save_provider_auth_cleans_stale_api_auth_entry(fake_save_env) -> None:+ from vibe.opencode_config import read_opencode_provider_auth_entries++ server, home = fake_save_env+ server._write_auth({"deepseek": {"type": "api", "key": "sk-stale"}})++ result = _save("deepseek", {"api_key": "sk-deepseek"})++ assert result.get("ok") is True+ assert server.remove_calls == ["deepseek"]+ assert read_opencode_provider_auth_entries(home=home) == {}+ config = _read_opencode_config(home)+ assert config["provider"]["deepseek"]["options"]["apiKey"] == "sk-deepseek"+++def test_save_provider_auth_replaces_oauth_auth_entry(fake_save_env) -> None:+ from vibe.opencode_config import read_opencode_provider_auth_entries++ server, home = fake_save_env+ server._write_auth({"openai": {"type": "oauth", "access_token": "old-token"}})++ result = _save("openai", {"api_key": "sk-openai"})++ assert result.get("ok") is True+ assert server.remove_calls == ["openai"]+ assert read_opencode_provider_auth_entries(home=home) == {}+ config = _read_opencode_config(home)+ assert config["provider"]["openai"]["options"]["apiKey"] == "sk-openai"++def test_save_provider_auth_returns_refreshed_catalog_and_clears_options_cache(fake_save_env, monkeypatch) -> None:@@ -248,7 +297,7 @@ def test_save_provider_auth_clears_options_cache(fake_save_env) -> None:assert api._OPENCODE_OPTIONS_CACHE == {}-def test_base_url_only_save_accepts_legacy_opencode_json_key(fake_save_env) -> None:+def test_base_url_only_save_accepts_opencode_json_options_key(fake_save_env) -> None:from vibe.opencode_config import (read_opencode_provider_base_url,upsert_opencode_provider_api_key,@@ -264,6 +313,51 @@ def test_base_url_only_save_accepts_legacy_opencode_json_key(fake_save_env) -> Nassert read_opencode_provider_base_url("poe", home=home) == "https://poe-relay.example/v1"+def test_base_url_only_save_repairs_missing_provider_options_key(fake_save_env) -> None:+ from vibe.opencode_config import (+ read_opencode_provider_base_url,+ read_opencode_provider_auth_entries,+ )++ server, home = fake_save_env+ # Simulate a provider saved by the older path: OpenCode auth.json has+ # the key, but opencode.json is missing provider.<id>.options.apiKey,+ # so some providers fail at invocation time with 401.+ server._write_auth({"deepseek": {"type": "api", "key": "sk-deepseek"}})++ result = _save("deepseek", {"base_url": "https://api.deepseek.com"})++ assert result["ok"] is True+ assert server.set_calls == []+ assert server.remove_calls == ["deepseek"]+ assert read_opencode_provider_auth_entries(home=home) == {}+ assert read_opencode_provider_base_url("deepseek", home=home) == "https://api.deepseek.com"+ config = _read_opencode_config(home)+ assert config["provider"]["deepseek"]["options"]["apiKey"] == "sk-deepseek"+++def test_base_url_only_save_keeps_existing_config_key_over_auth_key(fake_save_env) -> None:+ from vibe.opencode_config import (+ read_opencode_provider_base_url,+ read_opencode_provider_auth_entries,+ upsert_opencode_provider_api_key,+ )++ server, home = fake_save_env+ upsert_opencode_provider_api_key("deepseek", "sk-config-active", home=home)+ server._write_auth({"deepseek": {"type": "api", "key": "sk-stale-auth"}})++ result = _save("deepseek", {"base_url": "https://api.deepseek.com"})++ assert result["ok"] is True+ assert server.set_calls == []+ assert server.remove_calls == ["deepseek"]+ assert read_opencode_provider_auth_entries(home=home) == {}+ assert read_opencode_provider_base_url("deepseek", home=home) == "https://api.deepseek.com"+ config = _read_opencode_config(home)+ assert config["provider"]["deepseek"]["options"]["apiKey"] == "sk-config-active"++def test_base_url_only_save_accepts_keyless_custom_provider(fake_save_env) -> None:from vibe.opencode_config import (read_opencode_provider_base_url,@@ -289,7 +383,7 @@ def test_base_url_only_save_accepts_keyless_custom_provider(fake_save_env) -> No)-def test_delete_provider_auth_removes_legacy_opencode_json_key(fake_save_env) -> None:+def test_delete_provider_auth_removes_opencode_json_options_key(fake_save_env) -> None:from vibe.opencode_config import (read_opencode_provider_base_url,read_opencode_provider_keys,@@ -447,8 +541,10 @@ def test_save_custom_provider_persists_config_and_key(fake_save_env) -> None:assert result["ok"] is Trueassert result["provider_id"] == "my-relay"- assert ("my-relay", "sk-relay") in server.set_calls+ assert server.set_calls == []assert "my-relay" in read_opencode_custom_providers(home=home)+ config = _read_opencode_config(home)+ assert config["provider"]["my-relay"]["options"]["apiKey"] == "sk-relay"def test_save_custom_provider_rejects_clearing_base_url(fake_save_env) -> None:@@ -524,7 +620,7 @@ def test_delete_custom_provider_removes_config_and_auth(fake_save_env) -> None:result = _delete_custom("my-relay")assert result["ok"] is True- assert server.remove_calls == ["my-relay"]+ assert server.remove_calls == []assert read_opencode_custom_providers(home=home) == {}@@ -562,11 +658,11 @@ def test_delete_custom_provider_clears_matching_default_provider(fake_save_env)result = _delete_custom("my-relay")assert result["ok"] is True- assert server.remove_calls == ["my-relay"]+ assert server.remove_calls == []assert V2Config.load().agents.opencode.default_provider is None-def test_delete_custom_provider_keeps_config_when_auth_delete_fails(fake_save_env) -> None:+def test_delete_custom_provider_removes_config_without_auth_entry(fake_save_env) -> None:from vibe.opencode_config import read_opencode_custom_providersserver, home = fake_save_env@@ -579,13 +675,11 @@ def test_delete_custom_provider_keeps_config_when_auth_delete_fails(fake_save_en"api_key": "sk-relay",})- server.remove_error = RuntimeError("daemon unavailable")-result = _delete_custom("my-relay")- assert result["ok"] is False- assert "daemon unavailable" in result["message"]- assert "my-relay" in read_opencode_custom_providers(home=home)+ assert result["ok"] is True+ assert server.remove_calls == []+ assert read_opencode_custom_providers(home=home) == {}def test_save_provider_model_persists_user_model_and_clears_cache(fake_model_env) -> None:@@ -755,6 +849,6 @@ def test_base_url_persist_failure_surfaces_to_caller(monkeypatch, tmp_path) -> N)assert result["ok"] is Falseassert "disk full" in result["message"]- # Daemon call happened — the partial state is documented in the- # error message so the UI can prompt the user.- assert ("openai", "sk-new") in server.set_calls+ # Credential persistence is config-file based; the daemon auth API+ # is not called for Settings-entered API keys.+ assert server.set_calls == []diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex 69f0414cc..dd3f35b0c 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -364,6 +364,34 @@ def test_start_web_setup_opencode_surfaces_server_failure(assert flow.error == "opencode_server_unavailable"+def test_opencode_oauth_success_clears_provider_options_key(+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch+) -> None:+ fake = _FakeOpencodeServer()+ fake.auth_map = {"openai": [{"type": "oauth", "label": "ChatGPT Pro/Plus"}]}+ fake.next_authorize = {+ "url": "https://auth.openai.com/codex/device",+ "instructions": "Enter code: YR8I-QJJUH",+ }+ fake.wait_provider_oauth = AsyncMock(return_value=True)+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))+ clear_key = AsyncMock()+ monkeypatch.setattr(service, "_clear_opencode_provider_options_key_for_oauth", clear_key)+ hook_calls: list[str] = []+ service._post_web_success_hook = lambda b: hook_calls.append(b)++ async def run_flow():+ flow = await service.start_web_setup("opencode", provider_id="openai")+ await flow.waiter_task+ return flow++ flow = _run(run_flow())++ clear_key.assert_awaited_once_with("openai")+ assert hook_calls == ["opencode"]+ assert flow.state == "success"++def test_remove_web_auth_rejects_unsupported_backend(service: AgentAuthService) -> None:# OpenCode joined ``WEB_BACKENDS`` for OAuth, but ``remove_web_auth``# is claude / codex specific — opencode providers use thediff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsxindex e68d0559a..244f5b0ab 100644--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx@@ -1532,6 +1532,25 @@ export const OpencodeProviderConfig: React.FC<{);})()}+ {/* Per-provider connectivity probe.+ Gated on ``configured`` because+ testing an unconfigured provider+ always fails with+ ``invalid_credentials`` — adds+ noise without signal. Each card+ owns its own panel so users can+ debug providers independently. */}+ {provider.configured && (+ <OpencodeProviderTestPanel+ providerId={provider.id}+ providerName={provider.name}+ models={provider.models}+ defaultModel={provider.default_model}+ />+ )}+ </div>++ <div className="flex flex-col gap-3"><div className="flex flex-col gap-3 rounded-lg border border-border bg-surface px-3 py-3"><div className="flex flex-wrap items-center justify-between gap-2"><Label@@ -1612,88 +1631,71 @@ export const OpencodeProviderConfig: React.FC<{</div></div>- {/* Per-provider connectivity probe.- Gated on ``configured`` because- testing an unconfigured provider- always fails with- ``invalid_credentials`` — adds- noise without signal. Each card- owns its own panel so users can- debug providers independently. */}- {provider.configured && (- <OpencodeProviderTestPanel- providerId={provider.id}- providerName={provider.name}- models={provider.models}- defaultModel={provider.default_model}- />- )}- </div>-- <div className="flex flex-col gap-2">- <Label className="text-[11px] font-medium uppercase text-muted">- {t('settings.backends.opencodeProviderModels')}- </Label>- <div className="max-h-56 overflow-y-auto rounded-md border border-border bg-surface px-3 py-2">- {provider.models.length === 0 ? (- <p className="text-[12px] text-muted">- {t('settings.backends.opencodeProviderModelsEmpty')}- </p>- ) : (- <ul className="flex flex-col gap-1">- {provider.models.map((model) => {- const entry = provider.model_entries?.find(- (item) => item.id === model,- );- const reasoningEfforts = entry?.reasoning_efforts || [];- return (- <li- key={model}- className="flex items-center gap-2 font-mono text-[12px] text-foreground"- >- <Cpu className="size-3 text-muted" />- <span className="truncate">{model}</span>- {entry?.user_managed && (- <Badge variant="info" className="ml-auto">- {t('settings.backends.opencodeProviderUserModel')}- </Badge>- )}- {reasoningEfforts.length > 0 && (- <span className="text-[10px] text-muted">- {reasoningEfforts.join('/')}- </span>- )}- {provider.default_model === model && (- <Badge- variant="success"- className={entry?.user_managed ? undefined : 'ml-auto'}- >- {t(- 'settings.backends.opencodeProviderDefaultModel'- )}- </Badge>- )}- {entry?.user_managed && (- <Button- type="button"- variant="ghost"- size="icon"- className="size-6"- onClick={() => void onDeleteProviderModel(provider, model)}- disabled={edit.removingModelId === model}- >- {edit.removingModelId === model ? (- <RefreshCw className="size-3 animate-spin" />- ) : (- <Trash2 className="size-3 text-destructive" />- )}- </Button>- )}- </li>- );- })}- </ul>- )}+ <div className="flex flex-col gap-2">+ <Label className="text-[11px] font-medium uppercase text-muted">+ {t('settings.backends.opencodeProviderModels')}+ </Label>+ <div className="max-h-56 overflow-y-auto rounded-md border border-border bg-surface px-3 py-2">+ {provider.models.length === 0 ? (+ <p className="text-[12px] text-muted">+ {t('settings.backends.opencodeProviderModelsEmpty')}+ </p>+ ) : (+ <ul className="flex flex-col gap-1">+ {provider.models.map((model) => {+ const entry = provider.model_entries?.find(+ (item) => item.id === model,+ );+ const reasoningEfforts = entry?.reasoning_efforts || [];+ return (+ <li+ key={model}+ className="flex items-center gap-2 font-mono text-[12px] text-foreground"+ >+ <Cpu className="size-3 text-muted" />+ <span className="truncate">{model}</span>+ {entry?.user_managed && (+ <Badge variant="info" className="ml-auto">+ {t('settings.backends.opencodeProviderUserModel')}+ </Badge>+ )}+ {reasoningEfforts.length > 0 && (+ <span className="text-[10px] text-muted">+ {reasoningEfforts.join('/')}+ </span>+ )}+ {provider.default_model === model && (+ <Badge+ variant="success"+ className={entry?.user_managed ? undefined : 'ml-auto'}+ >+ {t(+ 'settings.backends.opencodeProviderDefaultModel'+ )}+ </Badge>+ )}+ {entry?.user_managed && (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-6"+ onClick={() => void onDeleteProviderModel(provider, model)}+ disabled={edit.removingModelId === model}+ >+ {edit.removingModelId === model ? (+ <RefreshCw className="size-3 animate-spin" />+ ) : (+ <Trash2 className="size-3 text-destructive" />+ )}+ </Button>+ )}+ </li>+ );+ })}+ </ul>+ )}+ </div></div></div></div>diff --git a/vibe/api.py b/vibe/api.pyindex 9f89cf3d1..f34b3a35b 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1636,19 +1636,19 @@ async def opencode_options_async(cwd: str) -> dict:auth_entries = {}allowed_provider_ids: set[str] | None = Noneif provider_catalog_available:- legacy_config_provider_ids = await _read_opencode_legacy_api_key_provider_ids()+ config_api_key_provider_ids = await _read_opencode_config_api_key_provider_ids()custom_config_provider_ids = await _read_opencode_custom_provider_ids()allowed_provider_ids = _configured_opencode_provider_ids(providers_raw=providers_raw,auth_entries=auth_entries,- legacy_config_provider_ids=legacy_config_provider_ids,+ config_api_key_provider_ids=config_api_key_provider_ids,custom_config_provider_ids=custom_config_provider_ids,)models = _filter_opencode_models_to_configured_providers(models,providers_raw=providers_raw,auth_entries=auth_entries,- legacy_config_provider_ids=legacy_config_provider_ids,+ config_api_key_provider_ids=config_api_key_provider_ids,custom_config_provider_ids=custom_config_provider_ids,)user_model_index = await _read_opencode_user_model_index()@@ -4440,11 +4440,13 @@ def save_claude_auth(payload: dict) -> dict:# merge the responses into a per-card view with ``configured`` /# ``oauth_available`` / ``local`` flags.#-# Writes go through OpenCode's own ``PUT /auth/<id>`` /-# ``DELETE /auth/<id>`` endpoints (already wrapped by-# ``OpenCodeServer.set_api_key_auth`` / ``remove_provider_auth``); we-# also persist ``default_provider`` into ``V2Config`` so the chip and-# routing layers stay in sync across restarts.+# Provider config writes update ``opencode.json`` directly because OpenCode+# stores custom providers, base URLs, user models, and provider option API keys+# there. ``auth.json`` remains OpenCode-owned: when we need to remove a stale+# or conflicting entry, we go through OpenCode's ``DELETE /auth/<id>`` wrapper+# instead of editing the auth file ourselves. We also persist+# ``default_provider`` into ``V2Config`` so the chip and routing layers stay in+# sync across restarts.async def _opencode_get_server():@@ -4517,14 +4519,14 @@ def _configured_opencode_provider_ids(*,providers_raw: dict,auth_entries: dict,- legacy_config_provider_ids: set[str] | None = None,+ config_api_key_provider_ids: set[str] | None = None,custom_config_provider_ids: set[str] | None = None,) -> set[str]:connected = providers_raw.get("connected") if isinstance(providers_raw, dict) else Noneconnected_set = {pid for pid in connected if isinstance(pid, str)} if isinstance(connected, list) else set()all_providers = _coerce_opencode_provider_catalog(providers_raw)configured = {pid for pid in auth_entries.keys() if isinstance(pid, str)}- configured.update(legacy_config_provider_ids or set())+ configured.update(config_api_key_provider_ids or set())configured.update(custom_config_provider_ids or set())for pid in connected_set:if _is_local_provider(pid, []):@@ -4540,7 +4542,7 @@ def _filter_opencode_models_to_configured_providers(*,providers_raw: dict,auth_entries: dict,- legacy_config_provider_ids: set[str] | None = None,+ config_api_key_provider_ids: set[str] | None = None,custom_config_provider_ids: set[str] | None = None,) -> dict:"""Drop unconfigured cloud providers from OpenCode model options.@@ -4548,7 +4550,8 @@ def _filter_opencode_models_to_configured_providers(OpenCode's ``/config/providers`` returns catalog models for providerseven after the user removes credentials. Settings/Agents model pickersshould only offer models the runtime can actually use: providers with- auth.json entries plus known local providers that are connected.+ auth.json entries, provider option API keys, custom provider config,+ plus known local providers that are connected."""if not isinstance(models, dict):@@ -4556,7 +4559,7 @@ def _filter_opencode_models_to_configured_providers(allowed = _configured_opencode_provider_ids(providers_raw=providers_raw,auth_entries=auth_entries,- legacy_config_provider_ids=legacy_config_provider_ids,+ config_api_key_provider_ids=config_api_key_provider_ids,custom_config_provider_ids=custom_config_provider_ids,)if not allowed:@@ -4696,13 +4699,13 @@ async def _read_opencode_custom_provider_ids() -> set[str]:return {pid for pid in custom_providers if isinstance(pid, str)}-async def _read_opencode_legacy_api_key_provider_ids() -> set[str]:+async def _read_opencode_config_api_key_provider_ids() -> set[str]:try:opencode_probe = await asyncio.to_thread(load_first_opencode_user_config, logger_instance=logger)except Exception as exc:- logger.debug("Could not read opencode.json for legacy provider auth: %s", exc)+ logger.debug("Could not read opencode.json for provider apiKey options: %s", exc)return set()if opencode_probe is None or not isinstance(opencode_probe.config, dict):@@ -4724,6 +4727,36 @@ async def _read_opencode_legacy_api_key_provider_ids() -> set[str]:return provider_ids+async def _read_opencode_config_api_key(provider_id: str) -> str | None:+ """Return provider.<id>.options.apiKey from opencode.json, if present."""++ if not isinstance(provider_id, str) or not provider_id.strip():+ return None+ pid = provider_id.strip()+ try:+ opencode_probe = await asyncio.to_thread(+ load_first_opencode_user_config, logger_instance=logger+ )+ except Exception as exc:+ logger.debug("Could not read opencode.json for provider apiKey: %s", exc)+ return None+ if opencode_probe is None or not isinstance(opencode_probe.config, dict):+ return None+ provider_block = opencode_probe.config.get("provider")+ if not isinstance(provider_block, dict):+ return None+ provider_config = provider_block.get(pid)+ if not isinstance(provider_config, dict):+ return None+ options = provider_config.get("options")+ if not isinstance(options, dict):+ return None+ api_key = options.get("apiKey")+ if isinstance(api_key, str) and api_key.strip():+ return api_key.strip()+ return None++def _custom_opencode_provider_row(provider_id: str, provider_config: dict) -> dict:meta = provider_config.get("vibe_remote")adapter_label = ""@@ -4831,7 +4864,7 @@ async def _get_opencode_providers_async() -> dict:base_url_index: dict = {}user_model_index: dict[str, dict[str, dict]] = {}custom_provider_index: dict[str, dict] = {}- legacy_api_key_mask_index: dict[str, str] = {}+ config_api_key_mask_index: dict[str, str] = {}if opencode_probe is not None and isinstance(opencode_probe.config, dict):provider_block = opencode_probe.config.get("provider")if isinstance(provider_block, dict):@@ -4858,19 +4891,15 @@ async def _get_opencode_providers_async() -> dict:if isinstance(api_key, str) and api_key.strip():masked = _mask_api_key(api_key.strip())if masked:- legacy_api_key_mask_index[pid_key] = masked+ config_api_key_mask_index[pid_key] = maskedfor pid_key, pid_config in custom_provider_index.items():all_providers.setdefault(pid_key, _custom_opencode_provider_row(pid_key, pid_config))# Per-provider stored credentials, masked server-side so the- # Settings UI can pre-fill the API Key input- # ("sk-proj-•••H8mN") without leaking plaintext, and badge each- # provider with the *active* auth source (``api`` / ``oauth`` /- # absent). OpenCode 1.14 caches its in-memory ``connected`` list- # at server startup so we treat auth.json as authoritative for- # what the user has explicitly configured — both for save (cache- # is stale → auth.json wins as "yes") and remove (cache is stale- # → auth.json absence wins as "no, the user removed it").+ # Settings UI can show a masked preview without leaking plaintext.+ # API keys managed by Vibe Remote live in opencode.json provider+ # options; auth.json is reserved for OpenCode's own connect/OAuth+ # flows and older installs that have not been repaired yet.try:from vibe.opencode_config import read_opencode_provider_auth_entries@@ -4895,15 +4924,15 @@ async def _get_opencode_providers_async() -> dict:elif entry_type:active_auth_type_index[pid_key] = entry_typeauth_file_provider_set: set = set(auth_entries.keys())- legacy_config_provider_set: set = set(legacy_api_key_mask_index.keys())+ config_api_key_provider_set: set = set(config_api_key_mask_index.keys())configured_provider_set = (auth_file_provider_set- | legacy_config_provider_set+ | config_api_key_provider_set| set(custom_provider_index.keys()))- for pid_key, masked in legacy_api_key_mask_index.items():- api_key_mask_index.setdefault(pid_key, masked)- active_auth_type_index.setdefault(pid_key, "api")+ for pid_key, masked in config_api_key_mask_index.items():+ api_key_mask_index[pid_key] = masked+ active_auth_type_index[pid_key] = "api"out_providers = []for pid, entry in all_providers.items():@@ -4978,7 +5007,7 @@ async def _get_opencode_providers_async() -> dict:"name": entry.get("name") or pid,"description": entry.get("description") or "","configured": configured,- "has_auth": pid in auth_file_provider_set or pid in legacy_config_provider_set,+ "has_auth": pid in auth_file_provider_set or pid in config_api_key_provider_set,"oauth_available": oauth_available,"local": local,"custom": custom,@@ -5184,9 +5213,13 @@ async def save_opencode_custom_provider_async(payload: dict) -> dict:restart = {"ok": False, "message": str(exc)}_OPENCODE_OPTIONS_CACHE.clear()- auth_result: dict | None = Noneif api_key:- auth_result = await _save_opencode_provider_auth_async(provider_id.strip().lower(), api_key, _BASE_URL_UNCHANGED)+ auth_result = await _save_opencode_provider_auth_async(+ provider_id.strip().lower(),+ None,+ _BASE_URL_UNCHANGED,+ config_api_key=api_key,+ )_OPENCODE_OPTIONS_CACHE.clear()try:restart = restart_backend("opencode")@@ -5426,39 +5459,72 @@ async def _save_opencode_provider_auth_async(provider_id: str,api_key: str | None,base_url: Any = _BASE_URL_UNCHANGED,+ *,+ config_api_key: str | None = None,) -> dict:- server = await _opencode_get_server()- if server is None:- return {"ok": False, "message": "OpenCode is disabled in V2Config"}- request_loop = asyncio.get_running_loop()- try:- # Only upsert auth when the caller provided a fresh key. The- # base-URL-only edit path reuses the existing key on disk- # (already validated upstream), so re-PUTting it would be- # redundant and could even churn the daemon's connected cache.- if api_key:- await server.set_api_key_auth(provider_id, api_key)- finally:- await server.close_http_session(loop=request_loop)-from vibe.opencode_config import (- remove_opencode_provider_api_key,remove_opencode_provider_base_url,+ read_opencode_provider_auth_entries,+ upsert_opencode_provider_api_key,upsert_opencode_provider_base_url,)- # Two-source-of-truth pruning: drop the legacy ``opencode.json``- # ``apiKey`` entry only when we just wrote a fresh daemon auth key.- # Base-URL-only saves can be valid because that same legacy key is- # still the active credential source, so removing it here would turn- # a URL edit into an implicit credential delete.- if api_key:+ # Treat API keys entered through Vibe Remote's Settings UI as OpenCode+ # config provider options, not OpenCode daemon auth entries. The+ # daemon's /auth store is still used by OpenCode's own connect/OAuth+ # flow, but provider options are the source OpenCode-compatible+ # providers consistently use at invocation time.+ config_key = config_api_key or api_key+ if config_key:try:await asyncio.to_thread(- remove_opencode_provider_api_key, provider_id, logger_instance=logger+ upsert_opencode_provider_api_key,+ provider_id,+ config_key,+ logger_instance=logger,)except Exception as exc:- logger.debug("Legacy opencode.json apiKey cleanup skipped for %s: %s", provider_id, exc)+ logger.warning(+ "OpenCode provider apiKey mirror persist failed for %s: %s",+ provider_id,+ exc,+ exc_info=True,+ )+ return {+ "ok": False,+ "message": (+ "Provider credential persistence failed: "+ f"{exc}"+ ),+ }++ try:+ auth_entries = await asyncio.to_thread(+ read_opencode_provider_auth_entries,+ logger_instance=logger,+ )+ if provider_id in auth_entries:+ auth_cleanup = await _delete_opencode_provider_auth_async(provider_id)+ if not auth_cleanup.get("ok"):+ return {+ "ok": False,+ "message": auth_cleanup.get("message")+ or "API key saved, but stale OpenCode auth cleanup failed",+ }+ except Exception as exc:+ logger.warning(+ "OpenCode stale auth cleanup failed for %s: %s",+ provider_id,+ exc,+ exc_info=True,+ )+ return {+ "ok": False,+ "message": (+ "API key saved, but stale OpenCode auth cleanup failed: "+ f"{exc}"+ ),+ }# ``baseURL`` is different: OpenCode's auth endpoint has no field for# it, so this write is the *only* place it gets persisted. A silent@@ -5505,11 +5571,11 @@ def save_opencode_provider_auth(provider_id: str, payload: dict) -> dict:async def save_opencode_provider_auth_async(provider_id: str, payload: dict) -> dict:"""Persist a single OpenCode provider's API key (and optional base URL).- The api key is forwarded to OpenCode's own ``PUT /auth`` endpoint so- the daemon's auth store remains the source of truth. The optional- ``base_url`` override is persisted into ``opencode.json`` because- OpenCode's auth endpoint has no field for it — without this fan-out- the Settings UI's Base URL input would be a no-op.+ The API key is persisted into ``opencode.json`` under+ ``provider.<id>.options.apiKey``. ``auth.json`` remains OpenCode's+ own connect/OAuth store and is touched only through the OpenCode auth+ API when we need to clear a conflicting entry. The optional+ ``base_url`` override is also persisted into ``opencode.json``.``base_url`` field semantics in the payload:* absent → leave the stored value untouched@@ -5525,21 +5591,30 @@ async def save_opencode_provider_auth_async(provider_id: str, payload: dict) -># UI's "Replace" flow hides the plaintext and only sends ``base_url``# for relay-URL fixes. Without this, base-URL-only edits fail unless# the user retypes the secret. We detect "already configured" by- # consulting both supported credential stores: OpenCode's auth.json- # and legacy provider.<id>.options.apiKey in opencode.json. This- # mirrors the Settings catalog badge, so a masked key shown in the- # UI can always save a base URL without requiring replacement.+ # consulting provider.<id>.options.apiKey in opencode.json first,+ # then falling back to OpenCode auth.json only to repair older+ # split-store installs. This mirrors the Settings catalog badge, so a+ # masked key shown in the UI can always save a base URL without+ # requiring replacement.api_key: str | None = raw_key.strip() if isinstance(raw_key, str) and raw_key.strip() else Nonehas_existing_key = False+ existing_api_key: str | None = Noneif api_key is None:try:- from vibe.opencode_config import read_opencode_provider_keys+ existing_api_key = await _read_opencode_config_api_key(provider_id.strip())+ if existing_api_key:+ has_existing_key = True+ if not has_existing_key:+ from vibe.opencode_config import read_opencode_provider_keys- existing_keys = read_opencode_provider_keys(logger_instance=logger)- has_existing_key = bool(existing_keys.get(provider_id.strip()))+ existing_keys = read_opencode_provider_keys(logger_instance=logger)+ maybe_existing_key = existing_keys.get(provider_id.strip())+ if isinstance(maybe_existing_key, str) and maybe_existing_key:+ has_existing_key = True+ existing_api_key = maybe_existing_keyif not has_existing_key:- legacy_ids = await _read_opencode_legacy_api_key_provider_ids()- has_existing_key = provider_id.strip() in legacy_ids+ config_key_ids = await _read_opencode_config_api_key_provider_ids()+ has_existing_key = provider_id.strip() in config_key_idsif not has_existing_key:custom_provider_ids = await _read_opencode_custom_provider_ids()has_existing_key = provider_id.strip() in custom_provider_ids@@ -5577,7 +5652,12 @@ async def save_opencode_provider_auth_async(provider_id: str, payload: dict) ->return {"ok": False, "message": "base_url is required for custom providers"}try:- result = await _save_opencode_provider_auth_async(provider_id.strip(), api_key, base_url)+ result = await _save_opencode_provider_auth_async(+ provider_id.strip(),+ None,+ base_url,+ config_api_key=api_key or existing_api_key,+ )except Exception as exc:logger.warning("OpenCode set-auth failed for %s: %s", provider_id, exc, exc_info=True)return {"ok": False, "message": str(exc)}@@ -5668,13 +5748,13 @@ async def delete_opencode_provider_auth_async(provider_id: str) -> dict:read_opencode_provider_auth_entries,logger_instance=logger,)- legacy_provider_ids = await _read_opencode_legacy_api_key_provider_ids()+ config_api_key_provider_ids = await _read_opencode_config_api_key_provider_ids()result = {"ok": True}removed_auth = Falseif pid in auth_entries:result = await _delete_opencode_provider_auth_async(pid)removed_auth = bool(result.get("ok"))- if pid in legacy_provider_ids:+ if pid in config_api_key_provider_ids:await asyncio.to_thread(remove_opencode_provider_api_key,pid,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 63607278d..4a20dd2cd 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2897,8 +2897,10 @@ async def backend_opencode_provider_oauth_start(provider_id: str):async def backend_opencode_provider_auth_post(provider_id: str):"""Persist an API key for a single OpenCode provider.- Body: ``{api_key: string}``. The key is forwarded to OpenCode via- its ``PUT /auth/<id>`` endpoint.+ Body: ``{api_key: string}``. Vibe Remote writes API keys to+ ``opencode.json`` provider options so provider config and runtime+ invocation share the same source of truth. OpenCode's auth endpoint+ is used only when clearing conflicting auth.json entries."""from vibe import api