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
feat(backends): masked API-key preview per OpenCode provider
cyh397bb4c4aa83
diff --git a/tests/test_opencode_provider_keys_reader.py b/tests/test_opencode_provider_keys_reader.pynew file mode 100644index 000000000..4b4422bde--- /dev/null+++ b/tests/test_opencode_provider_keys_reader.py@@ -0,0 +1,118 @@+"""Regression tests for the OpenCode per-provider auth.json reader.++Powers the Settings → Backends → OpenCode page's masked-key preview+("``sk-proj-•••H8mN``") for each provider that has an api-type entry+in ``~/.local/share/opencode/auth.json``. Plaintext keys are returned+to in-process callers (``vibe.api.get_opencode_providers`` masks them+before serialising); OAuth-type providers map to ``None`` so the UI+can switch affordances accordingly.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from vibe.opencode_config import (+ get_opencode_auth_path,+ read_opencode_provider_keys,+)+++def _write_auth(home: Path, payload: dict) -> Path:+ auth_path = home / ".local" / "share" / "opencode" / "auth.json"+ auth_path.parent.mkdir(parents=True, exist_ok=True)+ auth_path.write_text(json.dumps(payload), encoding="utf-8")+ return auth_path+++def test_missing_file_returns_empty_dict(tmp_path: Path) -> None:+ # OpenCode lazily creates auth.json on first PUT /auth/<id>; absence+ # should not be treated as an error.+ assert read_opencode_provider_keys(home=tmp_path) == {}+++def test_api_type_provider_yields_plaintext_key(tmp_path: Path) -> None:+ _write_auth(+ tmp_path,+ {+ "anthropic": {"type": "api", "key": "sk-ant-aBcDeFgHiJkLmNoPqRsTuV12cd34"},+ "openai": {"type": "api", "key": "sk-proj-zyxw9876v_5432"},+ },+ )+ result = read_opencode_provider_keys(home=tmp_path)+ assert result["anthropic"] == "sk-ant-aBcDeFgHiJkLmNoPqRsTuV12cd34"+ assert result["openai"] == "sk-proj-zyxw9876v_5432"+++def test_oauth_type_provider_yields_none(tmp_path: Path) -> None:+ """OAuth entries carry no static key; map to ``None`` so the UI+ drops the masked-preview affordance and shows the OAuth status+ instead."""+ _write_auth(+ tmp_path,+ {"google": {"type": "oauth", "access_token": "ya29.abc", "refresh_token": "rt-x"}},+ )+ result = read_opencode_provider_keys(home=tmp_path)+ assert result == {"google": None}+++def test_api_type_with_missing_or_blank_key_yields_none(tmp_path: Path) -> None:+ _write_auth(+ tmp_path,+ {+ "missing": {"type": "api"},+ "blank": {"type": "api", "key": ""},+ "non_string": {"type": "api", "key": 12345},+ },+ )+ result = read_opencode_provider_keys(home=tmp_path)+ assert result == {"missing": None, "blank": None, "non_string": None}+++def test_malformed_entries_are_skipped(tmp_path: Path) -> None:+ _write_auth(+ tmp_path,+ {+ "valid": {"type": "api", "key": "sk-keepme1234"},+ 123: {"type": "api", "key": "wrong-id-type"},+ "bad_shape": "not-a-dict",+ },+ )+ # JSON serialises integer keys back to strings, so verify by content:+ result = read_opencode_provider_keys(home=tmp_path)+ assert result.get("valid") == "sk-keepme1234"+ # Non-dict entries are skipped silently.+ assert "bad_shape" not in result+++def test_invalid_json_returns_empty_dict(tmp_path: Path) -> None:+ auth_path = tmp_path / ".local" / "share" / "opencode" / "auth.json"+ auth_path.parent.mkdir(parents=True, exist_ok=True)+ auth_path.write_text("not-actually-json{", encoding="utf-8")+ assert read_opencode_provider_keys(home=tmp_path) == {}+++def test_auth_path_helper_resolves_under_home(tmp_path: Path) -> None:+ assert get_opencode_auth_path(home=tmp_path) == (+ tmp_path / ".local" / "share" / "opencode" / "auth.json"+ )+++def test_top_level_array_is_rejected(tmp_path: Path) -> None:+ """OpenCode's auth file is always an object map; defensive coverage."""+ auth_path = tmp_path / ".local" / "share" / "opencode" / "auth.json"+ auth_path.parent.mkdir(parents=True, exist_ok=True)+ auth_path.write_text(json.dumps(["not", "a", "dict"]), encoding="utf-8")+ assert read_opencode_provider_keys(home=tmp_path) == {}+++def test_called_with_no_home_uses_real_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """``home=None`` defaults to ``Path.home()``; smoke-test the codepath+ without overwriting the real user's auth.json by mocking ``Path.home``."""+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)+ _write_auth(tmp_path, {"anthropic": {"type": "api", "key": "sk-fakeAB12cd34"}})+ result = read_opencode_provider_keys()+ assert result == {"anthropic": "sk-fakeAB12cd34"}diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsxindex aa2435434..6930dc471 100644--- a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx@@ -11,6 +11,7 @@ import {Download,Info,KeyRound,+ Pencil,RefreshCw,RotateCcw,Save,@@ -49,6 +50,11 @@ type ProviderEditState = {saving: boolean;removing: boolean;error: string | null;+ // Mirrors the Codex / Claude pattern: false = show ``api_key_masked``+ // read-only with a Replace button; true = empty editable input ready+ // for a fresh key. Toggled by the pencil button next to the masked+ // preview. Reset to false on successful save / remove / reload.+ editingKey: boolean;};const BACKEND_ID = 'opencode';@@ -67,6 +73,7 @@ const emptyEdit = (): ProviderEditState => ({saving: false,removing: false,error: null,+ editingKey: false,});const providerMatchesFilter = (provider: OpencodeProvider, mode: FilterMode): boolean => {@@ -407,7 +414,12 @@ export const SettingsOpencodeProviderPage: React.FC = () => {});return;}- updateEdit(provider.id, { saving: false, apiKey: '', error: null });+ updateEdit(provider.id, {+ saving: false,+ apiKey: '',+ editingKey: false,+ error: null,+ });showToast(t('settings.backends.opencodeProviderSaved'), 'success');await loadProviders();} catch (e: any) {@@ -1090,35 +1102,83 @@ export const SettingsOpencodeProviderPage: React.FC = () => {>{t('settings.backends.opencodeProviderApiKey')}</Label>- <div className="relative">- <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />- <Input- id={`opencode-key-${provider.id}`}- type="password"- autoComplete="off"- spellCheck={false}- placeholder={- provider.configured- ? (t(- 'settings.backends.opencodeProviderApiKeyPlaceholderStored'- ) as string)- : (t(- 'settings.backends.opencodeProviderApiKeyPlaceholder'- ) as string)- }- value={edit.apiKey}- onChange={(e) =>- updateEdit(provider.id, { apiKey: e.target.value })- }- className="pl-9 font-mono"- disabled={edit.saving}- />+ {provider.configured && provider.api_key_masked && !edit.editingKey ? (+ // Masked-preview affordance ported from+ // the Claude / Codex pages: show the+ // saved key as a read-only mono-typed+ // value with a pencil to swap in a+ // fresh one. Saves the user from+ // re-typing the secret on baseURL-only+ // edits.+ <div className="flex items-center gap-2 rounded-md border border-border bg-foreground/[0.04] px-3 py-2">+ <KeyRound className="size-4 shrink-0 text-muted" />+ <code className="flex-1 truncate font-mono text-[12px] text-foreground">+ {provider.api_key_masked}+ </code>+ <Button+ type="button"+ variant="ghost"+ size="xs"+ onClick={() =>+ updateEdit(provider.id, {+ editingKey: true,+ apiKey: '',+ })+ }+ disabled={edit.saving || edit.removing}+ >+ <Pencil className="size-3" />+ {t('settings.backends.replaceApiKey')}+ </Button>+ </div>+ ) : (+ <div className="relative">+ <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />+ <Input+ id={`opencode-key-${provider.id}`}+ type="password"+ autoComplete="off"+ spellCheck={false}+ placeholder={+ provider.configured+ ? (t(+ 'settings.backends.opencodeProviderApiKeyPlaceholderStored'+ ) as string)+ : (t(+ 'settings.backends.opencodeProviderApiKeyPlaceholder'+ ) as string)+ }+ value={edit.apiKey}+ onChange={(e) =>+ updateEdit(provider.id, { apiKey: e.target.value })+ }+ className="pl-9 font-mono"+ disabled={edit.saving}+ autoFocus={edit.editingKey}+ />+ </div>+ )}+ <div className="flex items-center justify-between gap-2">+ <p className="text-[11px] text-muted">+ {provider.configured+ ? t('settings.backends.opencodeProviderApiKeyStored')+ : t('settings.backends.opencodeProviderApiKeyMissing')}+ </p>+ {provider.configured && edit.editingKey && (+ <button+ type="button"+ className="text-[11px] text-muted underline-offset-2 transition hover:text-foreground hover:underline"+ onClick={() =>+ updateEdit(provider.id, {+ editingKey: false,+ apiKey: '',+ })+ }+ >+ {t('common.cancel')}+ </button>+ )}</div>- <p className="text-[11px] text-muted">- {provider.configured- ? t('settings.backends.opencodeProviderApiKeyStored')- : t('settings.backends.opencodeProviderApiKeyMissing')}- </p></div><div className="flex flex-col gap-1.5">diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex cf589a64f..136778b14 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -316,6 +316,13 @@ export type OpencodeProvider = {// the Settings page can pre-populate the Base URL input with the last// saved value instead of starting empty on every reload.base_url?: string | null;+ // Server-masked preview of the api-type credential stored in+ // ``~/.local/share/opencode/auth.json`` (e.g. ``sk-proj-•••H8mN``).+ // ``null``/missing when the provider uses OAuth or hasn't been+ // configured yet. Mirrors Claude / Codex's ``api_key_masked`` so the+ // user can see at a glance which providers have a stored key without+ // having to expand each card.+ api_key_masked?: string | null;};export type OpencodeProviderListResult = {diff --git a/vibe/api.py b/vibe/api.pyindex ee5c256ca..54c915ba3 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -2820,6 +2820,25 @@ 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.+ try:+ from vibe.opencode_config import read_opencode_provider_keys++ provider_keys = await asyncio.to_thread(+ read_opencode_provider_keys, logger_instance=logger+ )+ except Exception as exc:+ logger.debug("Could not read OpenCode auth.json for masked keys: %s", exc)+ provider_keys = {}+ 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+out_providers = []for pid, entry in all_providers.items():if not isinstance(entry, dict):@@ -2858,6 +2877,7 @@ async def _get_opencode_providers_async() -> dict:"models": model_ids,"default_model": default_model,"base_url": base_url_index.get(pid),+ "api_key_masked": api_key_mask_index.get(pid),})diff --git a/vibe/opencode_config.py b/vibe/opencode_config.pyindex 0f37e2d49..f75dcb4d6 100644--- a/vibe/opencode_config.py+++ b/vibe/opencode_config.py@@ -575,6 +575,61 @@ def remove_opencode_provider_base_url(return probe.path+def get_opencode_auth_path(home: Path | None = None) -> Path:+ """Return the absolute path to OpenCode's per-provider auth bundle.++ OpenCode stores ``{providerId: {type: "api"|"oauth", key?, ...}}`` at+ ``~/.local/share/opencode/auth.json``. The Settings UI uses this to+ render a masked preview ("``sk-proj-•••H8mN``") for each configured+ cloud provider — mirroring the Claude / Codex pages so the user can+ see at a glance which providers carry a stored key without having to+ expand each card.+ """+ resolved_home = home or Path.home()+ return resolved_home / ".local" / "share" / "opencode" / "auth.json"+++def read_opencode_provider_keys(+ *,+ home: Path | None = None,+ logger_instance: Optional[logging.Logger] = None,+) -> Dict[str, Optional[str]]:+ """Return ``{provider_id: plaintext_key | None}`` from auth.json.++ Plaintext keys never leave the server: ``vibe.api.get_opencode_providers``+ pipes each value through ``_mask_api_key`` before forwarding to the+ Settings UI. ``None`` entries mark OAuth-type providers (or any+ other ``type`` that doesn't carry a static key) — the UI can use+ presence-vs-None to decide whether to show a masked preview vs the+ "signed in via OAuth" affordance.++ A missing or unparseable file returns an empty dict; callers should+ not treat that as an error since OpenCode lazily creates the file+ on first ``PUT /auth/<id>`` call.+ """+ active_logger = logger_instance or logger+ path = get_opencode_auth_path(home)+ if not path.exists():+ return {}+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ active_logger.debug("OpenCode auth.json read failed: %s", exc)+ return {}+ if not isinstance(data, dict):+ return {}+ out: Dict[str, Optional[str]] = {}+ 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+ return out++def read_opencode_provider_base_url(provider_id: str,*,