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.

feat(backends): per-provider Test connectivity for OpenCode

cyhdb40162a0400
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 16717862a..a3c08ebb8 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -1728,6 +1728,228 @@ class AgentAuthService:
"excerpt": excerpt,
}
+ async def test_opencode_provider(
+ self,
+ provider_id: str,
+ *,
+ model: str | None = None,
+ timeout: float = 60.0,
+ ) -> dict[str, Any]:
+ """Probe a single OpenCode provider via the live ``opencode serve`` HTTP API.
+
+ Unlike Claude / Codex (each have one global credential), OpenCode
+ ships with N providers and the user typically configures only a
+ few. A single backend-wide test button would either fail when one
+ provider is unhealthy or silently mask which provider works — so
+ each provider card gets its own probe.
+
+ Flow: create a temp session → ``send_message("Hi", model=...)``
+ → poll messages until the assistant message either completes
+ with text or surfaces an ``info.error`` block → abort the
+ session. The session record stays on disk (OpenCode doesn't
+ expose ``DELETE /session``), but ``abort`` releases the run
+ slot, which is what matters for the probe.
+
+ ``model`` is the model id (e.g. ``"gpt-4o-mini"``); we wrap it
+ into the ``{providerID, modelID}`` shape OpenCode expects. When
+ ``None``, OpenCode uses the provider's configured default.
+ """
+ provider_id = (provider_id or "").strip()
+ if not provider_id:
+ return {"ok": False, "error": "missing_provider"}
+
+ server = await self._opencode_server()
+ if server is None:
+ return {"ok": False, "error": "opencode_server_unavailable"}
+
+ # Resolve the model id: caller-supplied wins; otherwise look up
+ # the provider's default from the live catalog so the probe
+ # doesn't fail with "model is required" on providers that don't
+ # carry a config-level default.
+ chosen_model = (model or "").strip()
+ if not chosen_model:
+ try:
+ catalog = await server.get_available_models(os.path.expanduser("~"))
+ except Exception: # noqa: BLE001
+ catalog = None
+ if isinstance(catalog, dict):
+ default_map = catalog.get("default") or {}
+ if isinstance(default_map, dict):
+ raw_default = default_map.get(provider_id)
+ if isinstance(raw_default, str) and raw_default.strip():
+ chosen_model = raw_default.strip()
+ if not chosen_model:
+ providers = catalog.get("providers") or []
+ if isinstance(providers, list):
+ for entry in providers:
+ if not isinstance(entry, dict):
+ continue
+ if entry.get("id") != provider_id:
+ continue
+ models_field = entry.get("models")
+ if isinstance(models_field, dict):
+ keys = sorted(models_field.keys())
+ if keys:
+ chosen_model = keys[0]
+ elif isinstance(models_field, list):
+ for m in models_field:
+ if isinstance(m, dict) and isinstance(m.get("id"), str):
+ chosen_model = m["id"]
+ break
+ if isinstance(m, str):
+ chosen_model = m
+ break
+ break
+ if not chosen_model:
+ return {"ok": False, "error": "no_models_available"}
+
+ # OpenCode picks a workdir per request; the probe doesn't touch
+ # files so the home dir is fine and matches what the IM /setup
+ # flow uses.
+ directory = os.path.expanduser("~")
+ started = time.monotonic()
+ session_id: str | None = None
+ try:
+ try:
+ created = await server.create_session(directory, title="vibe-test-probe")
+ except Exception as err: # noqa: BLE001
+ detail = str(err)
+ return {
+ "ok": False,
+ "error": _classify_test_failure("", detail),
+ "detail": detail[:600],
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
+ session_id = None
+ if isinstance(created, dict):
+ info = created.get("info") if isinstance(created.get("info"), dict) else created
+ session_id = info.get("id") if isinstance(info, dict) else None
+ if not session_id:
+ return {
+ "ok": False,
+ "error": "session_create_failed",
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
+
+ baseline_ids: set[str] = set()
+ try:
+ pre_msgs = await server.list_messages(session_id, directory)
+ for msg in pre_msgs:
+ mid = msg.get("info", {}).get("id") if isinstance(msg, dict) else None
+ if mid:
+ baseline_ids.add(mid)
+ except Exception: # noqa: BLE001
+ pass
+
+ try:
+ await server.send_message(
+ session_id,
+ directory,
+ "Hi",
+ model={"providerID": provider_id, "modelID": chosen_model},
+ )
+ except Exception as err: # noqa: BLE001
+ detail = str(err)
+ return {
+ "ok": False,
+ "error": _classify_test_failure("", detail),
+ "detail": detail[:600],
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
+
+ # Poll until the assistant message completes (``info.time.completed``
+ # is set) or carries an ``info.error`` block — both are
+ # terminal. Cap on ``timeout`` so a hung provider never wedges
+ # the request.
+ deadline = started + timeout
+ final_text = ""
+ error_payload: dict[str, Any] | None = None
+ poll_interval = 1.5
+ while time.monotonic() < deadline:
+ try:
+ messages = await server.list_messages(session_id, directory)
+ except Exception as poll_err: # noqa: BLE001
+ detail = str(poll_err)
+ return {
+ "ok": False,
+ "error": _classify_test_failure("", detail),
+ "detail": detail[:600],
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
+ terminal = None
+ for msg in messages or []:
+ if not isinstance(msg, dict):
+ continue
+ info = msg.get("info") or {}
+ mid = info.get("id")
+ if not mid or mid in baseline_ids:
+ continue
+ if info.get("role") != "assistant":
+ continue
+ if info.get("error"):
+ terminal = msg
+ error_payload = info.get("error")
+ break
+ completed = (info.get("time") or {}).get("completed")
+ if completed and info.get("finish") != "tool-calls":
+ terminal = msg
+ break
+ if terminal is not None:
+ if error_payload:
+ break
+ parts = terminal.get("parts") or []
+ pieces: list[str] = []
+ for part in parts:
+ if not isinstance(part, dict):
+ continue
+ if part.get("type") == "text":
+ text_val = part.get("text") or ""
+ if isinstance(text_val, str) and text_val.strip():
+ pieces.append(text_val.strip())
+ final_text = "\n\n".join(pieces).strip()
+ break
+ await asyncio.sleep(poll_interval)
+ else:
+ return {
+ "ok": False,
+ "error": "timed_out",
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
+
+ duration_ms = int((time.monotonic() - started) * 1000)
+ if error_payload:
+ error_name = ""
+ error_msg = ""
+ if isinstance(error_payload, dict):
+ error_name = str(error_payload.get("name") or "")
+ data = error_payload.get("data")
+ if isinstance(data, dict):
+ error_msg = str(data.get("message") or "")
+ elif isinstance(data, str):
+ error_msg = data
+ blob = f"{error_name} {error_msg}".strip() or "OpenCode reported an error"
+ classified = _classify_test_failure("", blob)
+ return {
+ "ok": False,
+ "error": classified,
+ "detail": blob[:600],
+ "duration_ms": duration_ms,
+ }
+
+ excerpt = _pick_probe_response_excerpt(final_text) if final_text else ""
+ return {
+ "ok": True,
+ "duration_ms": duration_ms,
+ "excerpt": excerpt or final_text[:240],
+ "model": chosen_model,
+ }
+ finally:
+ if session_id:
+ try:
+ await server.abort_session(session_id, directory)
+ except Exception: # noqa: BLE001
+ pass
+
async def cancel_web_flow(self, flow_id: str) -> dict[str, Any]:
async with self._web_flow_lock:
flow = self._web_flows.pop(flow_id, None)
diff --git a/ui/src/components/settings/OpencodeProviderTestPanel.tsx b/ui/src/components/settings/OpencodeProviderTestPanel.tsx
new file mode 100644
index 000000000..6d250986a
--- /dev/null
+++ b/ui/src/components/settings/OpencodeProviderTestPanel.tsx
@@ -0,0 +1,201 @@
+import React, { useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Play, Zap } from 'lucide-react';
+import clsx from 'clsx';
+
+import { Button } from '../ui/button';
+import { useApi } from '@/context/ApiContext';
+import type { BackendAuthTestResult } from '@/context/ApiContext';
+import { useToast } from '@/context/ToastContext';
+
+export type OpencodeProviderTestPanelProps = {
+ providerId: string;
+ providerName: string;
+ models: string[];
+ defaultModel?: string | null;
+};
+
+/**
+ * Per-provider Test connectivity panel for OpenCode. Slots inside each
+ * provider card alongside the OAuth panel + API Key field. Mirrors
+ * ``BackendTestPanel`` (Claude / Codex) but probes a single OpenCode
+ * provider through ``opencode serve``'s HTTP API rather than spawning
+ * a CLI subprocess — multiple providers can be tested independently
+ * without serializing one slow request behind another.
+ */
+export const OpencodeProviderTestPanel: React.FC<OpencodeProviderTestPanelProps> = ({
+ providerId,
+ providerName,
+ models,
+ defaultModel,
+}) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [testing, setTesting] = useState(false);
+ const [lastResult, setLastResult] = useState<BackendAuthTestResult | null>(null);
+ // Default the dropdown to the provider's default model so first-time
+ // testers don't have to scroll a long list to pick something.
+ const initialModel = useMemo(() => {
+ if (defaultModel && models.includes(defaultModel)) return defaultModel;
+ return '';
+ }, [defaultModel, models]);
+ const [selectedModel, setSelectedModel] = useState<string>(initialModel);
+
+ // Reset selected model when the catalog changes (provider remount /
+ // model list refresh after save).
+ useEffect(() => {
+ setSelectedModel(initialModel);
+ }, [initialModel]);
+
+ // Reuse the shared classifier → i18n keys. Anything the backend
+ // didn't classify lands on the generic ``cli_failed`` fallback and
+ // the raw ``detail`` still rides in the toast.
+ const failureSentence = (result: BackendAuthTestResult): string => {
+ const detail = (result.detail || '').trim();
+ const code = (result.error || '').trim();
+ const map: Record<string, string> = {
+ invalid_credentials: 'settings.backends.testFailureInvalidCredentials',
+ forbidden: 'settings.backends.testFailureForbidden',
+ model_not_found: 'settings.backends.testFailureModelNotFound',
+ rate_limited: 'settings.backends.testFailureRateLimited',
+ endpoint_unreachable: 'settings.backends.testFailureEndpointUnreachable',
+ server_error: 'settings.backends.testFailureServerError',
+ timed_out: 'settings.backends.testFailureTimedOut',
+ cli_failed: 'settings.backends.testFailureCliFailed',
+ // OpenCode-specific codes (added below in i18n).
+ opencode_server_unavailable: 'settings.backends.testFailureOpencodeServerUnavailable',
+ no_models_available: 'settings.backends.testFailureNoModels',
+ session_create_failed: 'settings.backends.testFailureSessionCreate',
+ missing_provider: 'settings.backends.testFailureMissingProvider',
+ };
+ const key = map[code];
+ if (key) {
+ return t(key, { detail: detail || code });
+ }
+ return t('settings.backends.testConnectionFailedToast', {
+ detail: detail || code || 'unknown',
+ });
+ };
+
+ const runTest = async () => {
+ setTesting(true);
+ try {
+ const result = await api.testOpencodeProvider(providerId, {
+ model: selectedModel || undefined,
+ });
+ setLastResult(result);
+ if (result.ok) {
+ showToast(
+ t('settings.backends.testConnectionSuccessToast', { ms: result.duration_ms ?? '?' }),
+ 'success',
+ );
+ } else {
+ showToast(failureSentence(result), 'error');
+ }
+ } catch (err: any) {
+ const fallback = { ok: false, error: err?.message || 'test_failed' } as BackendAuthTestResult;
+ setLastResult(fallback);
+ showToast(
+ t('settings.backends.testConnectionFailedToast', { detail: fallback.error }),
+ 'error',
+ );
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ const resultLine = (() => {
+ if (!lastResult) return null;
+ if (lastResult.ok) {
+ return t('settings.backends.testConnectionLastOk', {
+ ms: lastResult.duration_ms ?? '?',
+ });
+ }
+ return t('settings.backends.testConnectionLastFail', {
+ detail: failureSentence(lastResult),
+ });
+ })();
+
+ return (
+ <div className="flex flex-col gap-2.5 rounded-xl border border-border bg-foreground/[0.025] p-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-2.5">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-[8px] border border-mint/30 bg-mint-soft">
+ <Zap size={14} className="text-mint" />
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <p className="text-[13px] font-bold text-foreground">
+ {t('settings.backends.opencodeTestTitle', { name: providerName })}
+ </p>
+ <p className="text-[11px] text-muted">
+ {t('settings.backends.opencodeTestSubtitle')}
+ </p>
+ </div>
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <select
+ value={selectedModel}
+ onChange={(e) => setSelectedModel(e.target.value)}
+ disabled={testing || models.length === 0}
+ className={clsx(
+ 'h-8 rounded-md border border-border bg-background px-2 font-mono text-[11px]',
+ 'text-foreground transition-colors hover:border-border-strong',
+ 'disabled:opacity-60',
+ )}
+ aria-label={t('settings.backends.testConnectionModelLabel') as string}
+ >
+ <option value="">
+ {t('settings.backends.opencodeTestModelDefault')}
+ </option>
+ {models.map((m) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ <Button
+ type="button"
+ variant="brand"
+ size="sm"
+ onClick={() => void runTest()}
+ disabled={testing}
+ >
+ <Play className="size-3" />
+ {testing ? t('common.testing') : t('settings.backends.testConnectionRun')}
+ </Button>
+ </div>
+ {resultLine && (
+ <p
+ className={clsx(
+ 'font-mono text-[11px] font-semibold',
+ lastResult?.ok ? 'text-mint' : 'text-destructive',
+ )}
+ >
+ {resultLine}
+ </p>
+ )}
+ {lastResult?.ok && lastResult.excerpt && (
+ <div className="rounded-md border border-border bg-background px-3 py-2">
+ <p className="font-mono text-[10px] uppercase tracking-wide text-muted">
+ {t('settings.backends.testConnectionResponseLabel')}
+ </p>
+ <p className="mt-1 break-words font-mono text-[12px] leading-relaxed text-foreground">
+ {lastResult.excerpt}
+ </p>
+ </div>
+ )}
+ {lastResult && !lastResult.ok && lastResult.detail && (
+ <details className="rounded-md border border-destructive/30 bg-destructive/[0.04] px-3 py-2 [&[open]>summary]:mb-2">
+ <summary className="cursor-pointer font-mono text-[10px] uppercase tracking-wide text-destructive">
+ {t('settings.backends.testConnectionRawOutputLabel')}
+ </summary>
+ <pre className="max-h-48 overflow-auto whitespace-pre-wrap break-all rounded bg-background px-3 py-2 font-mono text-[11px] leading-relaxed text-muted">
+ {lastResult.detail}
+ </pre>
+ </details>
+ )}
+ </div>
+ );
+};
diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
index d6f33777e..83d6bcd2d 100644
--- a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
@@ -34,6 +34,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { SettingsPageShell } from './SettingsPageShell';
import { BackendLifecycleChip } from './BackendLifecycleChip';
import { BackendOAuthPanel } from './BackendOAuthPanel';
+import { OpencodeProviderTestPanel } from './OpencodeProviderTestPanel';
import { ToggleSwitch } from './SettingsPrimitives';
import { useApi } from '@/context/ApiContext';
import type { OpencodeProvider } from '@/context/ApiContext';
@@ -1319,6 +1320,23 @@ export const SettingsOpencodeProviderPage: React.FC = () => {
</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">
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index d774ac68e..0a9418d38 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -54,6 +54,10 @@ export type ApiContextType = {
backend: 'claude' | 'codex',
options?: { model?: string },
) => Promise<BackendAuthTestResult>;
+ testOpencodeProvider: (
+ providerId: string,
+ options?: { model?: string },
+ ) => Promise<BackendAuthTestResult>;
getOpencodeProviders: () => Promise<OpencodeProviderListResult>;
setOpencodeProviderAuth: (
providerId: string,
@@ -493,6 +497,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
postJson(`/backend/${encodeURIComponent(backend)}/auth/test`, {
...(options?.model ? { model: options.model } : {}),
}),
+ testOpencodeProvider: (providerId, options) =>
+ postJson(`/backend/opencode/provider/${encodeURIComponent(providerId)}/test`, {
+ ...(options?.model ? { model: options.model } : {}),
+ }),
getOpencodeProviders: () => getJson('/backend/opencode/providers'),
setOpencodeProviderAuth: (providerId, apiKey, baseUrl) =>
// Forward ``base_url`` only when the caller passed something
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 068ff9529..f991059ed 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -281,7 +281,14 @@
"opencodeProviderRemoveOauthConfirm": "Sign out of {{name}}? This removes the stored OAuth credentials.",
"opencodeProviderRemoved": "Provider credentials removed.",
"opencodeProviderRemoveFailed": "Could not remove provider credentials.",
- "opencodeProviderCollapse": "Collapse"
+ "opencodeProviderCollapse": "Collapse",
+ "opencodeTestTitle": "Test {{name}}",
+ "opencodeTestSubtitle": "Send a one-token \"Hi\" through OpenCode using this provider only.",
+ "opencodeTestModelDefault": "Provider default",
+ "testFailureOpencodeServerUnavailable": "OpenCode's local server is not reachable. Start it from the Runtime page and retry.",
+ "testFailureNoModels": "This provider has not reported any models yet. Save a key first, or open the provider catalog.",
+ "testFailureSessionCreate": "OpenCode rejected the test session — check the server logs for a deeper error.",
+ "testFailureMissingProvider": "Provider id is missing — reload the page and try again."
},
"messagingTitle": "Messaging",
"messagingSubtitle": "Tune global reply behavior, acknowledgements, and message visibility defaults.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 9c5ebe7c6..3fdf9e6b4 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -281,7 +281,14 @@
"opencodeProviderRemoveOauthConfirm": "确定要退出 {{name}} 的登录吗?这会移除已保存的 OAuth 凭据。",
"opencodeProviderRemoved": "服务商凭据已删除。",
"opencodeProviderRemoveFailed": "移除服务商凭据失败。",
- "opencodeProviderCollapse": "收起"
+ "opencodeProviderCollapse": "收起",
+ "opencodeTestTitle": "测试 {{name}}",
+ "opencodeTestSubtitle": "通过 OpenCode 向当前服务商发送一句 \"Hi\",验证凭据与 Base URL 是否可达。",
+ "opencodeTestModelDefault": "服务商默认",
+ "testFailureOpencodeServerUnavailable": "本地 OpenCode 服务未启动。请到 Runtime 页面启动后再试。",
+ "testFailureNoModels": "该服务商当前没有可用模型。请先保存 API Key,或重新刷新服务商列表。",
+ "testFailureSessionCreate": "OpenCode 拒绝创建测试会话——请查看 OpenCode 服务日志获取详细错误。",
+ "testFailureMissingProvider": "服务商 ID 缺失,请刷新页面后重试。"
},
"messagingTitle": "消息",
"messagingSubtitle": "统一配置全局回复行为、ACK 策略以及消息显示默认值。",
diff --git a/vibe/api.py b/vibe/api.py
index 188c7b18e..21c6ba072 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2347,6 +2347,34 @@ def test_backend_auth(backend: str, model: Optional[str] = None) -> dict:
return {"ok": False, "error": "test_failed", "detail": str(exc)}
+def test_opencode_provider(provider_id: str, model: Optional[str] = None) -> dict:
+ """Probe a single OpenCode provider over the live ``opencode serve`` HTTP API.
+
+ OpenCode users typically wire up multiple providers (OpenAI, Poe,
+ Anthropic, ...) but only a few will be active at any time. A single
+ backend-wide button would either spuriously fail when one is broken
+ or hide which one works. Per-provider probes echo the model's
+ response so the user knows the round-trip actually returned text.
+ """
+ provider_id = (provider_id or "").strip()
+ if not provider_id:
+ return {"ok": False, "error": "missing_provider"}
+ service = _get_oauth_service()
+ try:
+ return _submit_oauth_coro(
+ service.test_opencode_provider(provider_id, model=model),
+ timeout=90.0,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.error(
+ "OpenCode provider test failed for %s: %s",
+ provider_id,
+ exc,
+ exc_info=True,
+ )
+ return {"ok": False, "error": "test_failed", "detail": str(exc)}
+
+
def cancel_oauth_web(flow_id: str) -> dict:
flow_id = (flow_id or "").strip()
if not flow_id:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index f1c31bf57..0880bd2be 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1743,6 +1743,21 @@ def backend_opencode_provider_auth_delete(provider_id: str):
return jsonify(api.delete_opencode_provider_auth(provider_id))
[email protected]("/backend/opencode/provider/<provider_id>/test", methods=["POST"])
+def backend_opencode_provider_test(provider_id: str):
+ """Run a per-provider connectivity probe through OpenCode's HTTP API.
+
+ Body: ``{model?: string}``. The model id is wrapped server-side
+ into the ``{providerID, modelID}`` shape OpenCode expects.
+ """
+ from vibe import api
+
+ payload = request.json or {}
+ raw_model = payload.get("model")
+ model = raw_model.strip() if isinstance(raw_model, str) and raw_model.strip() else None
+ return jsonify(api.test_opencode_provider(provider_id, model=model))
+
+
@app.route("/backend/opencode/default-provider", methods=["POST"])
def backend_opencode_default_provider():
"""Persist the user's default OpenCode provider into V2Config.