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): make Test connection fast + model-selectable + show response

cyh61d9564ed1d7
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 6e9efa197..9f65f98a3 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -37,6 +37,55 @@ CLAUDE_LOGIN_METHODS = {"claudeai", "console"}
OPENCODE_DIRECT_SETUP_URLS = {"opencode": "https://opencode.ai/auth"}
+def _pick_probe_response_excerpt(stdout_text: str) -> str:
+ """Return the first content-bearing line from Codex/Claude probe stdout.
+
+ The CLIs emit decorations the user doesn't care about: warnings
+ (``warning:``, ``ERROR:``, bubblewrap notices), session
+ bookkeeping (``codex``, ``tokens used``, ``Reconnecting...``),
+ and timestamped headers. Skip those and take the first real
+ response line so the "Last run" status shows what the model
+ actually said.
+ """
+ skip_prefixes = (
+ "warning:",
+ "error:",
+ "info:",
+ "debug:",
+ "trace:",
+ "codex",
+ "claude",
+ "reconnecting",
+ "tokens used",
+ "thinking",
+ "session id",
+ "user instructions",
+ "system",
+ "[", # rich-tty escape sequence remnants like "[1m..."
+ )
+ candidate = ""
+ for line in stdout_text.splitlines():
+ stripped = line.strip()
+ if not stripped:
+ continue
+ lowered = stripped.lower()
+ if any(lowered.startswith(p) for p in skip_prefixes):
+ continue
+ if stripped.startswith(">") or stripped.startswith("#"):
+ continue
+ candidate = stripped[:240]
+ break
+ if not candidate:
+ # Fall back to the first non-blank line even if it looks
+ # decorative — better something than empty.
+ for line in stdout_text.splitlines():
+ stripped = line.strip()
+ if stripped:
+ candidate = stripped[:240]
+ break
+ return candidate
+
+
def _classify_test_failure(stdout: str, stderr: str) -> str:
"""Map a backend CLI's failure output to a specific UI error code.
@@ -1530,13 +1579,26 @@ class AgentAuthService:
logger.warning("post_web_success_hook failed after remove for %s: %s", backend, err)
return {"ok": True}
- async def test_web_auth(self, backend: str, *, timeout: float = 45.0) -> dict[str, Any]:
+ async def test_web_auth(
+ self,
+ backend: str,
+ *,
+ timeout: float = 45.0,
+ model: str | None = None,
+ ) -> dict[str, Any]:
"""Send a 1-token probe ("Hi") through the backend CLI.
Validates both the credentials and the endpoint (when ``base_url``
is configured) by running ``claude --print "Hi"`` /
``codex exec "Hi"``. Returns elapsed milliseconds + a short
response excerpt on success; surfaces stderr on failure.
+
+ ``model`` overrides the CLI's configured default — useful for
+ users whose ``config.toml`` selects a slow reasoning model
+ (e.g. ``gpt-5.4`` with ``model_reasoning_effort=xhigh``) where
+ even "Hi" can take minutes to round-trip. The frontend's Test
+ panel exposes a small select pre-filled from the routing
+ catalog so the user can probe a specific model.
"""
# remove_web_auth and test_web_auth are claude / codex specific
# (single-backend subprocess invocations). OpenCode uses the
@@ -1553,7 +1615,10 @@ class AgentAuthService:
# auto-discovery) so the probe never fails on environment
# quirks; we only care that the auth + endpoint round-trip
# works.
- cmd = [binary, "-p", "--bare", prompt]
+ cmd = [binary, "-p", "--bare"]
+ if isinstance(model, str) and model.strip():
+ cmd.extend(["--model", model.strip()])
+ cmd.append(prompt)
env_override = dict(os.environ)
# Layer V2Config-driven env on top so the test reflects what
# the live IM session would do at launch.
@@ -1570,12 +1635,23 @@ class AgentAuthService:
pass
else:
# Codex single-shot mode. ``--skip-git-repo-check`` bypasses
- # Codex's per-project trust gate — the UI server's cwd is
- # never in the user's trusted-projects list, so without it
- # Codex bails before talking to the API. ``-q`` would silence
- # the rendered response; we want stdout so the UI can show a
- # one-line excerpt as proof the round-trip succeeded.
- cmd = [binary, "exec", "--skip-git-repo-check", prompt]
+ # Codex's per-project trust gate. We also force
+ # ``model_reasoning_effort=minimal`` so a config.toml that
+ # selects ``xhigh`` reasoning (deep thinking + 30 s+ for any
+ # prompt) doesn't blow past our 45 s test timeout — the
+ # probe is "auth + endpoint reachable", not "exercise the
+ # reasoning chain". ``-c key=value`` overrides config.toml
+ # entries per invocation.
+ cmd = [
+ binary,
+ "exec",
+ "--skip-git-repo-check",
+ "-c",
+ "model_reasoning_effort=minimal",
+ ]
+ if isinstance(model, str) and model.strip():
+ cmd.extend(["-c", f"model={model.strip()}"])
+ cmd.append(prompt)
env_override = dict(os.environ)
started = time.monotonic()
@@ -1620,15 +1696,13 @@ class AgentAuthService:
"duration_ms": duration_ms,
}
- # Trim the response to a one-line excerpt — chunked output (Codex
- # in particular emits multi-line markdown) would overflow the
- # toast and isn't the point of the probe.
- excerpt = ""
- for line in stdout_text.splitlines():
- line = line.strip()
- if line:
- excerpt = line[:240]
- break
+ # Pick the model's actual response out of chatty CLI output.
+ # Codex in particular prepends a session header, a "codex"
+ # label line, "tokens used" footer, ``Reconnecting...`` retry
+ # warnings, and bubblewrap notices — the first non-blank line
+ # would always be a warning or label. Skip known non-content
+ # lines and take the first remaining one as the excerpt.
+ excerpt = _pick_probe_response_excerpt(stdout_text)
return {
"ok": True,
"duration_ms": duration_ms,
diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsx
index 803d84803..443d375a2 100644
--- a/ui/src/components/settings/BackendTestPanel.tsx
+++ b/ui/src/components/settings/BackendTestPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState } from 'react';
+import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Play, Zap } from 'lucide-react';
import clsx from 'clsx';
@@ -21,6 +21,12 @@ export type BackendTestPanelProps = {
* and the endpoint (Base URL) round-trip end-to-end. Works in both
* OAuth and API-Key modes — the underlying CLI uses whichever auth
* source is configured at launch.
+ *
+ * The model dropdown lets the user override the backend's default
+ * (important for Codex users whose ``config.toml`` selects
+ * ``model_reasoning_effort=xhigh``; with the override the probe stays
+ * fast). On success we echo the first content line of the model's
+ * response so the user sees real output, not just a duration.
*/
export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) => {
const { t } = useTranslation();
@@ -28,6 +34,29 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
const { showToast } = useToast();
const [testing, setTesting] = useState(false);
const [lastResult, setLastResult] = useState<BackendAuthTestResult | null>(null);
+ const [models, setModels] = useState<string[]>([]);
+ const [selectedModel, setSelectedModel] = useState<string>('');
+
+ // Load the available models catalog once on mount so the dropdown can
+ // pre-populate. Failures fall back to "default-only" — the user can
+ // still test against whatever the backend's config.toml selects.
+ useEffect(() => {
+ let cancelled = false;
+ const loader = backend === 'claude' ? api.claudeModels() : api.codexModels();
+ loader
+ .then((data) => {
+ if (cancelled) return;
+ if (data?.ok && Array.isArray(data.models)) {
+ setModels(data.models.filter((m): m is string => typeof m === 'string' && m.length > 0));
+ }
+ })
+ .catch(() => {
+ /* swallow — dropdown stays empty; default-model path still works */
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [api, backend]);
// Map the backend's structured error codes to UI sentences. Anything
// we don't recognise falls back to the generic ``cli_failed`` line,
@@ -60,7 +89,9 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
const runTest = async () => {
setTesting(true);
try {
- const result = await api.testBackendAuth(backend);
+ const result = await api.testBackendAuth(backend, {
+ model: selectedModel || undefined,
+ });
setLastResult(result);
if (result.ok) {
showToast(
@@ -94,44 +125,83 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
return (
<div
className={clsx(
- 'flex items-center justify-between gap-4 rounded-xl border border-border bg-foreground/[0.025] p-5',
+ 'flex flex-col gap-3 rounded-xl border border-border bg-foreground/[0.025] p-5',
)}
>
- <div className="flex items-center gap-3">
- <div className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-mint/30 bg-mint-soft">
- <Zap size={18} className="text-mint" />
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div className="flex items-center gap-3">
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-mint/30 bg-mint-soft">
+ <Zap size={18} className="text-mint" />
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <p className="text-[14px] font-bold text-foreground">
+ {t('settings.backends.testConnectionTitle')}
+ </p>
+ <p className="text-[12px] text-muted">
+ {t('settings.backends.testConnectionSubtitle')}
+ </p>
+ </div>
</div>
- <div className="flex flex-col gap-0.5">
- <p className="text-[14px] font-bold text-foreground">
- {t('settings.backends.testConnectionTitle')}
- </p>
- <p className="text-[12px] text-muted">
- {t('settings.backends.testConnectionSubtitle')}
- </p>
- </div>
- </div>
- <div className="flex items-center gap-3">
- {resultLine && (
- <span
+ <div className="flex flex-wrap items-center gap-3">
+ {/* Model picker — empty = use the backend CLI's default. Models
+ are fetched from the same routing-config catalog so users
+ don't have to guess identifiers. Codex users in particular
+ want this to bypass a reasoning-heavy config default. */}
+ <select
+ value={selectedModel}
+ onChange={(e) => setSelectedModel(e.target.value)}
+ disabled={testing}
className={clsx(
- 'font-mono text-[11px] font-semibold',
- lastResult?.ok ? 'text-mint' : 'text-destructive',
+ 'h-9 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}
>
- {resultLine}
- </span>
- )}
- <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>
+ <option value="">{t('settings.backends.testConnectionModelDefault')}</option>
+ {models.map((m) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ {resultLine && (
+ <span
+ className={clsx(
+ 'font-mono text-[11px] font-semibold',
+ lastResult?.ok ? 'text-mint' : 'text-destructive',
+ )}
+ >
+ {resultLine}
+ </span>
+ )}
+ <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>
</div>
+
+ {/* Show what the model actually said on success — without this the
+ user only sees "ok · 312 ms" and has to trust us that the
+ round-trip went through. The excerpt is server-side trimmed to
+ 240 chars, single-line. */}
+ {lastResult?.ok && lastResult.excerpt && (
+ <div className="rounded-md border border-border bg-background px-3 py-2">
+ <p className="font-mono text-[11px] 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>
+ )}
</div>
);
};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 95acb7897..c4851bc68 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -44,7 +44,10 @@ export type ApiContextType = {
flowId: string,
) => Promise<OAuthWebMutationResult>;
removeBackendAuth: (backend: 'claude' | 'codex') => Promise<OAuthWebMutationResult>;
- testBackendAuth: (backend: 'claude' | 'codex') => Promise<BackendAuthTestResult>;
+ testBackendAuth: (
+ backend: 'claude' | 'codex',
+ options?: { model?: string },
+ ) => Promise<BackendAuthTestResult>;
getOpencodeProviders: () => Promise<OpencodeProviderListResult>;
setOpencodeProviderAuth: (
providerId: string,
@@ -478,8 +481,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}),
removeBackendAuth: (backend) =>
postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/remove`, {}),
- testBackendAuth: (backend) =>
- postJson(`/backend/${encodeURIComponent(backend)}/auth/test`, {}),
+ testBackendAuth: (backend, options) =>
+ postJson(`/backend/${encodeURIComponent(backend)}/auth/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 93d265ec1..38ffb4673 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -186,6 +186,9 @@
"testConnectionRun": "Run test",
"testConnectionLastOk": "Last run: ok · {{ms}} ms",
"testConnectionLastFail": "Last run failed: {{detail}}",
+ "testConnectionModelLabel": "Test model",
+ "testConnectionModelDefault": "Backend default",
+ "testConnectionResponseLabel": "Model response",
"testConnectionSuccessToast": "Backend reachable · {{ms}} ms",
"testConnectionFailedToast": "Backend test failed: {{detail}}",
"testFailureInvalidCredentials": "The stored credentials were rejected (401). Replace your API key or re-authenticate.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 0368dcb57..005684326 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -186,6 +186,9 @@
"testConnectionRun": "运行测试",
"testConnectionLastOk": "上次:成功 · {{ms}} ms",
"testConnectionLastFail": "上次失败:{{detail}}",
+ "testConnectionModelLabel": "测试模型",
+ "testConnectionModelDefault": "使用默认",
+ "testConnectionResponseLabel": "模型响应",
"testConnectionSuccessToast": "后端可达 · {{ms}} ms",
"testConnectionFailedToast": "后端测试失败:{{detail}}",
"testFailureInvalidCredentials": "保存的凭据被拒绝(401)。请更换 API key 或重新登录。",
diff --git a/vibe/api.py b/vibe/api.py
index 0de169977..8e20571e1 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2258,14 +2258,22 @@ def remove_backend_auth(backend: str) -> dict:
return {"ok": False, "error": "remove_failed", "detail": str(exc)}
-def test_backend_auth(backend: str) -> dict:
- """Send a single-token ``Hi`` probe through the backend CLI."""
+def test_backend_auth(backend: str, model: Optional[str] = None) -> dict:
+ """Send a single-token ``Hi`` probe through the backend CLI.
+
+ ``model`` lets the caller override the CLI's configured default —
+ important for Codex users whose ``config.toml`` selects a slow
+ reasoning model, where even "Hi" can blow past the test timeout.
+ """
backend = (backend or "").strip().lower()
if backend not in _WEB_OAUTH_BACKENDS:
return {"ok": False, "error": "unsupported_backend"}
service = _get_oauth_service()
try:
- return _submit_oauth_coro(service.test_web_auth(backend), timeout=60.0)
+ return _submit_oauth_coro(
+ service.test_web_auth(backend, model=model),
+ timeout=60.0,
+ )
except Exception as exc: # noqa: BLE001
logger.error("Web auth test failed for %s: %s", backend, exc, exc_info=True)
return {"ok": False, "error": "test_failed", "detail": str(exc)}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 803074ac1..e469934b3 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1675,7 +1675,10 @@ def backend_auth_test(backend: str):
"""Send a single-token probe through the backend CLI to verify auth."""
from vibe import api
- return jsonify(api.test_backend_auth(backend))
+ 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_backend_auth(backend, model=model))
@app.route("/backend/opencode/providers", methods=["GET"])