Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(backends): 4 OpenCode follow-ups (server lookup, auto-restart, remove-staleness, active-source badge)

cyhfbfe0288013f
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 1d253f826..ae8750d92 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -1638,25 +1638,36 @@ class AgentAuthService:
async def _opencode_server(self):
"""Lazy lookup of the live OpenCode server client.
- The web auth service runs in the UI process (no controller-level
- ``agent_service``), so we go through ``OpenCodeServer.get_instance``
- rather than ``self.controller.agent_service.agents['opencode']``.
- Falls back to ``None`` if OpenCode is disabled in V2Config — the
- caller then surfaces a ``failed`` flow state with a clear reason.
+ Mirrors ``vibe.api._opencode_get_server`` rather than the IM
+ controller's ``agent_service.agents['opencode']`` (the web auth
+ service runs in the UI process — there is no controller-level
+ agent_service). Returns ``None`` when OpenCode is disabled in
+ V2Config so the caller can surface a typed error.
"""
try:
- from modules.agents.opencode.server import OpenCodeServer
+ from config.v2_compat import to_app_config
+ from config.v2_config import V2Config
+ from modules.agents.opencode import OpenCodeServerManager
except ImportError:
return None
- config = getattr(self.controller, "config", None)
- agents_cfg = getattr(config, "agents", None) if config is not None else None
- opencode_cfg = getattr(agents_cfg, "opencode", None) if agents_cfg is not None else None
- if opencode_cfg is None or not getattr(opencode_cfg, "enabled", False):
+ try:
+ compat = to_app_config(V2Config.load())
+ except Exception as err: # noqa: BLE001
+ logger.warning("V2Config.load failed in web OAuth path: %s", err)
+ return None
+ opencode_cfg = getattr(compat, "opencode", None)
+ if opencode_cfg is None:
return None
try:
- return await OpenCodeServer.get_instance(opencode_cfg)
+ server = await OpenCodeServerManager.get_instance(
+ binary=opencode_cfg.binary,
+ port=opencode_cfg.port,
+ request_timeout_seconds=opencode_cfg.request_timeout_seconds,
+ )
+ await server.ensure_running()
+ return server
except Exception as err: # noqa: BLE001
- logger.warning("OpenCodeServer.get_instance failed for web OAuth: %s", err)
+ logger.warning("OpenCodeServerManager.get_instance failed for web OAuth: %s", err)
return None
async def _resolve_opencode_oauth_method(
diff --git a/tests/test_save_opencode_provider_auth.py b/tests/test_save_opencode_provider_auth.py
index 1f19b4479..2c6c0aa00 100644
--- a/tests/test_save_opencode_provider_auth.py
+++ b/tests/test_save_opencode_provider_auth.py
@@ -68,7 +68,10 @@ 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"})
- assert result == {"ok": True}
+ # 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 (
read_opencode_provider_base_url("openai", home=home)
@@ -86,7 +89,10 @@ def test_base_url_explicit_empty_clears_stored_value(fake_save_env) -> None:
upsert_opencode_provider_base_url("openai", "https://stale.example", home=home)
result = _save("openai", {"api_key": "sk-new", "base_url": ""})
- assert result == {"ok": True}
+ # 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 read_opencode_provider_base_url("openai", home=home) is None
@@ -100,7 +106,10 @@ def test_base_url_explicit_whitespace_clears_stored_value(fake_save_env) -> None
upsert_opencode_provider_base_url("openai", "https://stale.example", home=home)
result = _save("openai", {"api_key": "sk-new", "base_url": " "})
- assert result == {"ok": True}
+ # 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 read_opencode_provider_base_url("openai", home=home) is None
@@ -112,7 +121,10 @@ def test_base_url_persists_when_provided(fake_save_env) -> None:
"openai",
{"api_key": "sk-new", "base_url": "https://relay.example/v1"},
)
- assert result == {"ok": True}
+ # 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 (
read_opencode_provider_base_url("openai", home=home)
== "https://relay.example/v1"
@@ -157,7 +169,10 @@ def test_base_url_null_clears_stored_value(fake_save_env) -> None:
server, home = fake_save_env
upsert_opencode_provider_base_url("openai", "https://stale.example", home=home)
result = _save("openai", {"api_key": "sk-new", "base_url": None})
- assert result == {"ok": True}
+ # 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 read_opencode_provider_base_url("openai", home=home) is None
diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
index 836cd8cd7..215b26638 100644
--- a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
@@ -554,10 +554,20 @@ export const SettingsOpencodeProviderPage: React.FC = () => {
// signal first.
const renderProviderBadge = (provider: OpencodeProvider) => {
if (provider.configured) {
+ // Show *which* auth source is live so the user can distinguish
+ // OAuth-signed-in from API-key-saved without expanding the card.
+ // Dual-mode providers (openai supports both) carry only one entry
+ // in auth.json at a time, so this matches what OpenCode uses.
+ const activeLabel =
+ provider.active_auth_type === 'oauth'
+ ? t('settings.backends.opencodeBadgeConfiguredOauth')
+ : provider.active_auth_type === 'api'
+ ? t('settings.backends.opencodeBadgeConfiguredApiKey')
+ : t('settings.backends.opencodeBadgeConfigured');
return (
<Badge variant="success" className="gap-1">
<Check className="size-3" />
- {t('settings.backends.opencodeBadgeConfigured')}
+ {activeLabel}
</Badge>
);
}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index fbdadf617..5fde6260c 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -333,6 +333,12 @@ export type OpencodeProvider = {
// user can see at a glance which providers have a stored key without
// having to expand each card.
api_key_masked?: string | null;
+ // ``api`` / ``oauth`` / null — the auth type currently stored for the
+ // provider. OpenCode's ``auth.json`` only carries ONE entry per
+ // provider at a time, so this is also the type that will be used at
+ // launch. Lets the UI badge dual-mode providers (e.g. openai) with
+ // which source is live, instead of leaving the user guessing.
+ active_auth_type?: 'api' | 'oauth' | string | null;
};
export type OpencodeProviderListResult = {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index aa2f4a8d2..7f2911d06 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -224,6 +224,8 @@
"opencodeFilterOauth": "OAuth available",
"opencodeFilterLocal": "Local",
"opencodeBadgeConfigured": "Configured",
+ "opencodeBadgeConfiguredApiKey": "API Key",
+ "opencodeBadgeConfiguredOauth": "OAuth",
"opencodeBadgeOauth": "OAuth available",
"opencodeBadgeLocal": "Local",
"opencodeBadgeUnset": "Not set",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 21063bb1d..573c36a12 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -224,6 +224,8 @@
"opencodeFilterOauth": "支持 OAuth",
"opencodeFilterLocal": "本地",
"opencodeBadgeConfigured": "已配置",
+ "opencodeBadgeConfiguredApiKey": "API Key",
+ "opencodeBadgeConfiguredOauth": "OAuth",
"opencodeBadgeOauth": "支持 OAuth",
"opencodeBadgeLocal": "本地",
"opencodeBadgeUnset": "未配置",
diff --git a/vibe/api.py b/vibe/api.py
index 46b1265ec..558355633 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2831,34 +2831,39 @@ async def _get_opencode_providers_async() -> dict:
if isinstance(candidate, str) and candidate.strip():
base_url_index[pid_key] = candidate.strip()
- # Per-provider stored API keys, masked server-side so the Settings UI
- # can pre-fill the input ("sk-proj-•••H8mN") without leaking plaintext.
- # OAuth-type providers map to ``None`` and the UI skips the mask
- # block in that case.
- #
- # Reading auth.json directly also doubles as the source of truth for
- # the "configured" badge: OpenCode 1.14.48 caches its in-memory
- # ``connected`` list at server startup, so a freshly-saved provider
- # stays absent from ``/provider``'s ``connected`` until the daemon
- # restarts. Our ``configured`` flag therefore unions ``connected``
- # with "has an entry in auth.json" (regardless of api vs oauth type),
- # giving the user immediate feedback after Save without waiting for
- # an OpenCode restart.
+ # 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").
try:
- from vibe.opencode_config import read_opencode_provider_keys
+ from vibe.opencode_config import read_opencode_provider_auth_entries
- provider_keys = await asyncio.to_thread(
- read_opencode_provider_keys, logger_instance=logger
+ auth_entries = await asyncio.to_thread(
+ read_opencode_provider_auth_entries, logger_instance=logger
)
except Exception as exc:
logger.debug("Could not read OpenCode auth.json for masked keys: %s", exc)
- provider_keys = {}
+ auth_entries = {}
api_key_mask_index: dict = {}
- for pid_key, raw_key in provider_keys.items():
- masked = _mask_api_key(raw_key) if raw_key else None
- if masked:
- api_key_mask_index[pid_key] = masked
- auth_file_provider_set: set = set(provider_keys.keys())
+ active_auth_type_index: dict = {}
+ for pid_key, entry in auth_entries.items():
+ entry_type = entry.get("type") if isinstance(entry, dict) else None
+ if entry_type == "api":
+ raw_key = entry.get("key") if isinstance(entry, dict) else None
+ masked = _mask_api_key(raw_key) if raw_key else None
+ if masked:
+ api_key_mask_index[pid_key] = masked
+ active_auth_type_index[pid_key] = "api"
+ elif entry_type == "oauth":
+ active_auth_type_index[pid_key] = "oauth"
+ elif entry_type:
+ active_auth_type_index[pid_key] = entry_type
+ auth_file_provider_set: set = set(auth_entries.keys())
out_providers = []
for pid, entry in all_providers.items():
@@ -2871,11 +2876,19 @@ async def _get_opencode_providers_async() -> dict:
for method in auth_methods_list
)
local = _is_local_provider(pid, auth_methods_list)
- # Union OpenCode's runtime ``connected`` list with auth.json
- # presence so a fresh PUT /auth/<id> immediately reflects as
- # configured — OpenCode caches ``connected`` and won't refresh
- # without a daemon restart.
- configured = pid in connected_set or pid in auth_file_provider_set
+ # Authoritative source for the "configured" badge:
+ # - If auth.json carries an entry → configured (user explicitly
+ # set it up, even if OpenCode's cache hasn't caught up yet).
+ # - If auth.json is empty AND ``connected`` lists it → configured
+ # only when ``local`` (Ollama / LM Studio don't need keys).
+ # Otherwise treat ``connected`` as stale — the user just
+ # removed the key and the daemon hasn't restarted yet.
+ if pid in auth_file_provider_set:
+ configured = True
+ elif local and pid in connected_set:
+ configured = True
+ else:
+ configured = False
models_for_provider = model_index.get(pid, {})
provider_models = models_for_provider.get("models")
if isinstance(provider_models, dict):
@@ -2903,6 +2916,11 @@ async def _get_opencode_providers_async() -> dict:
"default_model": default_model,
"base_url": base_url_index.get(pid),
"api_key_masked": api_key_mask_index.get(pid),
+ # ``api`` / ``oauth`` / null — the type the daemon will
+ # actually use at launch. Lets the UI badge the right
+ # source for dual-mode providers (e.g. openai supports
+ # both, but only one entry lives in auth.json at a time).
+ "active_auth_type": active_auth_type_index.get(pid),
}
)
@@ -3055,13 +3073,27 @@ def save_opencode_provider_auth(provider_id: str, payload: dict) -> dict:
return {"ok": False, "message": "base_url must be a string"}
try:
- return asyncio.run(
+ result = asyncio.run(
_save_opencode_provider_auth_async(provider_id.strip(), api_key, base_url)
)
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)}
+ # Ask the live controller to refresh the OpenCode server so the
+ # daemon's in-memory ``connected`` cache picks up the new auth.
+ # Without this, ``GET /provider`` keeps returning the pre-save
+ # state until OpenCode restarts on its own (typically next idle
+ # cleanup cycle). The restart is best-effort: we report it under a
+ # separate ``restart`` key so the UI can show "saved, but daemon
+ # refresh failed" when applicable.
+ try:
+ result["restart"] = restart_backend("opencode")
+ except Exception as exc:
+ logger.warning("OpenCode auto-restart after save failed for %s: %s", provider_id, exc)
+ result["restart"] = {"ok": False, "message": str(exc)}
+ return result
+
async def _delete_opencode_provider_auth_async(provider_id: str) -> dict:
server = await _opencode_get_server()
@@ -3076,14 +3108,28 @@ async def _delete_opencode_provider_auth_async(provider_id: str) -> dict:
def delete_opencode_provider_auth(provider_id: str) -> dict:
- """Drop a single provider's stored credentials."""
+ """Drop a single provider's stored credentials.
+
+ Same restart pattern as save: the daemon caches ``connected`` at
+ startup, so a fresh DELETE on ``/auth/<id>`` doesn't flip the
+ runtime state until the daemon restarts. We trigger
+ ``restart_backend("opencode")`` so the UI's next refresh reflects
+ reality. The restart status comes back under ``restart`` so the
+ page can warn on "removed, but daemon refresh failed".
+ """
if not isinstance(provider_id, str) or not provider_id.strip():
return {"ok": False, "message": "provider_id is required"}
try:
- return asyncio.run(_delete_opencode_provider_auth_async(provider_id.strip()))
+ result = asyncio.run(_delete_opencode_provider_auth_async(provider_id.strip()))
except Exception as exc:
logger.warning("OpenCode delete-auth failed for %s: %s", provider_id, exc, exc_info=True)
return {"ok": False, "message": str(exc)}
+ try:
+ result["restart"] = restart_backend("opencode")
+ except Exception as exc:
+ logger.warning("OpenCode auto-restart after delete failed for %s: %s", provider_id, exc)
+ result["restart"] = {"ok": False, "message": str(exc)}
+ return result
def set_opencode_default_provider(payload: dict) -> dict:
diff --git a/vibe/opencode_config.py b/vibe/opencode_config.py
index f75dcb4d6..3591b5ddb 100644
--- a/vibe/opencode_config.py
+++ b/vibe/opencode_config.py
@@ -607,6 +607,32 @@ def read_opencode_provider_keys(
not treat that as an error since OpenCode lazily creates the file
on first ``PUT /auth/<id>`` call.
"""
+ entries = read_opencode_provider_auth_entries(
+ home=home, logger_instance=logger_instance
+ )
+ out: Dict[str, Optional[str]] = {}
+ for provider_id, entry in entries.items():
+ if entry.get("type") == "api":
+ key = entry.get("key")
+ out[provider_id] = key if isinstance(key, str) and key else None
+ else:
+ out[provider_id] = None
+ return out
+
+
+def read_opencode_provider_auth_entries(
+ *,
+ home: Path | None = None,
+ logger_instance: Optional[logging.Logger] = None,
+) -> Dict[str, Dict[str, Any]]:
+ """Return the raw ``auth.json`` entries keyed by provider_id.
+
+ Useful when callers need both the ``type`` (``"api"`` / ``"oauth"`` /
+ other) AND the optional key — the Settings UI surfaces "currently
+ active: OAuth" / "API key" badges from the ``type`` field. Plaintext
+ secrets stay in process; ``vibe.api.get_opencode_providers`` masks
+ or strips before serialising.
+ """
active_logger = logger_instance or logger
path = get_opencode_auth_path(home)
if not path.exists():
@@ -618,15 +644,11 @@ def read_opencode_provider_keys(
return {}
if not isinstance(data, dict):
return {}
- out: Dict[str, Optional[str]] = {}
+ out: Dict[str, Dict[str, Any]] = {}
for provider_id, entry in data.items():
if not isinstance(provider_id, str) or not isinstance(entry, dict):
continue
- if entry.get("type") == "api":
- key = entry.get("key")
- out[provider_id] = key if isinstance(key, str) and key else None
- else:
- out[provider_id] = None
+ out[provider_id] = entry
return out