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): classify Test failures into specific UI messages

cyhd9f140aa209a
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index ffcabdf27..3371d289d 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -37,6 +37,96 @@ CLAUDE_LOGIN_METHODS = {"claudeai", "console"}
OPENCODE_DIRECT_SETUP_URLS = {"opencode": "https://opencode.ai/auth"}
+def _classify_test_failure(stdout: str, stderr: str) -> str:
+ """Map a backend CLI's failure output to a specific UI error code.
+
+ The Settings → Backends "Test connection" panel routes the returned
+ ``error`` string into an i18n key (``settings.backends.testFailure*``),
+ so the user gets a sentence they can act on instead of the opaque
+ ``cli_failed``. Order matters: more specific patterns (HTTP status
+ codes, named error strings) are checked before generic substrings.
+
+ The classifier is conservative — anything it doesn't recognise stays
+ as ``cli_failed`` and the raw stderr is preserved in ``detail`` for
+ inspection. Adding a new class is a one-line append below.
+ """
+ text = f"{stderr}\n{stdout}".lower()
+ if not text.strip():
+ return "cli_failed"
+
+ # Auth-side rejections (key wrong / revoked / not present).
+ auth_needles = (
+ "401",
+ "unauthorized",
+ "invalid api key",
+ "invalid_api_key",
+ "api key not valid",
+ "authentication",
+ "auth failed",
+ "not logged in",
+ "missing api key",
+ "no api key",
+ )
+ if any(needle in text for needle in auth_needles):
+ return "invalid_credentials"
+
+ # Quota / rate limiting.
+ if any(needle in text for needle in ("429", "rate limit", "quota", "usage limit", "too many requests")):
+ return "rate_limited"
+
+ # Authorization (key valid but not allowed).
+ if any(needle in text for needle in ("403", "forbidden", "permission denied", "access denied")):
+ return "forbidden"
+
+ # Model / endpoint mismatches.
+ if any(
+ needle in text
+ for needle in (
+ "model not found",
+ "model_not_found",
+ "unknown model",
+ "model does not exist",
+ "no such model",
+ )
+ ):
+ return "model_not_found"
+
+ # Network-side failures: the relay / endpoint isn't reachable at all.
+ if any(
+ needle in text
+ for needle in (
+ "connection refused",
+ "could not resolve",
+ "getaddrinfo",
+ "name or service not known",
+ "name resolution failed",
+ "eai_again",
+ "enotfound",
+ "econnrefused",
+ "network is unreachable",
+ "no route to host",
+ "ssl",
+ "certificate",
+ "timed out",
+ "request timeout",
+ "deadline exceeded",
+ )
+ ):
+ return "endpoint_unreachable"
+
+ # 5xx from the upstream.
+ if any(needle in text for needle in ("502", "503", "504", "bad gateway", "service unavailable", "internal server error")):
+ return "server_error"
+
+ # Codex's own trust-gate / sandbox blockers (shouldn't fire now that
+ # we pass --skip-git-repo-check, but kept for observability if a
+ # future Codex release changes the flag).
+ if "trusted directory" in text or "--skip-git-repo-check" in text:
+ return "trust_check_failed"
+
+ return "cli_failed"
+
+
def classify_auth_error(backend: str, error_text: str) -> bool:
"""Return True when the error likely requires an OAuth reset."""
text = (error_text or "").strip().lower()
@@ -1480,9 +1570,10 @@ class AgentAuthService:
stderr_text = (stderr or b"").decode("utf-8", errors="replace").strip()
if process.returncode != 0:
+ classified = _classify_test_failure(stdout_text, stderr_text)
return {
"ok": False,
- "error": "cli_failed",
+ "error": classified,
"exit_code": process.returncode,
"detail": (stderr_text or stdout_text)[:600],
"duration_ms": duration_ms,
diff --git a/tests/test_test_failure_classifier.py b/tests/test_test_failure_classifier.py
new file mode 100644
index 000000000..dbd332d4a
--- /dev/null
+++ b/tests/test_test_failure_classifier.py
@@ -0,0 +1,67 @@
+"""Regression tests for the Settings → Backends "Test connection" classifier.
+
+Pins the mapping from raw CLI stderr/stdout to the structured error
+codes the UI dispatches into ``settings.backends.testFailure*`` i18n
+sentences. The classifier is conservative — anything it doesn't
+recognise stays ``cli_failed`` so the user still sees the raw detail.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from core.agent_auth_service import _classify_test_failure
+
+
+ "stderr,expected",
+ [
+ ("Error: 401 Unauthorized", "invalid_credentials"),
+ ("invalid api key", "invalid_credentials"),
+ ("Authentication failed: no credentials configured", "invalid_credentials"),
+ ("not logged in", "invalid_credentials"),
+ ("403 Forbidden", "forbidden"),
+ ("Access denied for organization", "forbidden"),
+ ("Model not found: gpt-9.0", "model_not_found"),
+ ("unknown model 'sonnet-99'", "model_not_found"),
+ ("429 Too Many Requests", "rate_limited"),
+ ("rate limit exceeded for tier", "rate_limited"),
+ ("quota exceeded", "rate_limited"),
+ ("Connection refused", "endpoint_unreachable"),
+ ("could not resolve host", "endpoint_unreachable"),
+ ("getaddrinfo failed", "endpoint_unreachable"),
+ ("ECONNREFUSED 127.0.0.1:8080", "endpoint_unreachable"),
+ ("Request timed out after 30s", "endpoint_unreachable"),
+ ("ssl certificate problem", "endpoint_unreachable"),
+ ("502 Bad Gateway", "server_error"),
+ ("503 Service Unavailable", "server_error"),
+ ("Internal Server Error", "server_error"),
+ ("Not inside a trusted directory and --skip-git-repo-check was not specified.", "trust_check_failed"),
+ ],
+)
+def test_classifier_maps_common_stderr_patterns(stderr: str, expected: str) -> None:
+ assert _classify_test_failure("", stderr) == expected
+
+
+def test_classifier_combines_stdout_and_stderr() -> None:
+ # Some CLIs emit auth errors on stdout (Claude --print piped output);
+ # the classifier must search both streams.
+ assert _classify_test_failure("Error: invalid api key", "") == "invalid_credentials"
+
+
+def test_classifier_is_case_insensitive() -> None:
+ assert _classify_test_failure("", "401 UNAUTHORIZED") == "invalid_credentials"
+ assert _classify_test_failure("", "Connection Refused") == "endpoint_unreachable"
+
+
+def test_classifier_falls_back_to_cli_failed_for_unknown_output() -> None:
+ assert _classify_test_failure("", "Unexpected token in response") == "cli_failed"
+ assert _classify_test_failure("", "") == "cli_failed"
+
+
+def test_classifier_more_specific_wins_over_generic() -> None:
+ """A response that contains both 401 and other words should be
+ classified as ``invalid_credentials`` (auth wins over generic 5xx
+ mention)."""
+ msg = "Backend returned 401 (from upstream which sometimes 502s)"
+ assert _classify_test_failure("", msg) == "invalid_credentials"
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 1f2638234..9bf84ed9a 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -287,6 +287,9 @@ def test_test_web_auth_failure_surfaces_stderr(
monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
result = _run(service.test_web_auth("claude"))
assert result["ok"] is False
- assert result["error"] == "cli_failed"
+ # The classifier turns "Authentication failed" stderr into the
+ # specific ``invalid_credentials`` code so the UI can render the
+ # actionable "Replace your API key or re-authenticate" sentence.
+ assert result["error"] == "invalid_credentials"
assert result["exit_code"] == 7
assert "Authentication failed" in (result.get("detail") or "")
diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsx
index 77137c3cf..803d84803 100644
--- a/ui/src/components/settings/BackendTestPanel.tsx
+++ b/ui/src/components/settings/BackendTestPanel.tsx
@@ -29,6 +29,34 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
const [testing, setTesting] = useState(false);
const [lastResult, setLastResult] = useState<BackendAuthTestResult | null>(null);
+ // Map the backend's structured error codes to UI sentences. Anything
+ // we don't recognise falls back to the generic ``cli_failed`` line,
+ // and the raw ``detail`` is still surfaced in the toast for inspection.
+ 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',
+ trust_check_failed: 'settings.backends.testFailureTrustCheck',
+ cli_not_found: 'settings.backends.testFailureCliNotFound',
+ spawn_failed: 'settings.backends.testFailureSpawnFailed',
+ timed_out: 'settings.backends.testFailureTimedOut',
+ cli_failed: 'settings.backends.testFailureCliFailed',
+ };
+ 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 {
@@ -40,12 +68,7 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
'success',
);
} else {
- showToast(
- t('settings.backends.testConnectionFailedToast', {
- detail: result.error || result.detail || 'unknown',
- }),
- 'error',
- );
+ showToast(failureSentence(result), 'error');
}
} catch (err: any) {
const fallback = { ok: false, error: err?.message || 'test_failed' } as BackendAuthTestResult;
@@ -63,8 +86,9 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
ms: lastResult.duration_ms ?? '?',
});
}
- const detail = lastResult.error || lastResult.detail || 'unknown';
- return t('settings.backends.testConnectionLastFail', { detail });
+ return t('settings.backends.testConnectionLastFail', {
+ detail: failureSentence(lastResult),
+ });
})();
return (
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 5ecb911eb..ffc8d4916 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -188,6 +188,17 @@
"testConnectionLastFail": "Last run failed: {{detail}}",
"testConnectionSuccessToast": "Backend reachable · {{ms}} ms",
"testConnectionFailedToast": "Backend test failed: {{detail}}",
+ "testFailureInvalidCredentials": "The stored credentials were rejected (401). Replace your API key or re-authenticate.",
+ "testFailureForbidden": "The endpoint accepted the credentials but denied access (403). Check the relay's allowed-models list.",
+ "testFailureModelNotFound": "The model the backend tried to use was not recognised by the endpoint. Check the model id or relay routing.",
+ "testFailureRateLimited": "The endpoint returned rate-limited / quota-exceeded (429). Wait or rotate to a key with higher limits.",
+ "testFailureEndpointUnreachable": "Could not reach the configured Base URL. Check DNS, proxy, and that the relay is up.",
+ "testFailureServerError": "The endpoint responded with a 5xx error. The relay is reachable but not healthy.",
+ "testFailureTrustCheck": "Codex refused to run from the current directory. Restart the regression container so the cwd is trusted.",
+ "testFailureCliNotFound": "The backend CLI binary was not found. Check the Path on the runtime card.",
+ "testFailureSpawnFailed": "Could not launch the backend CLI: {{detail}}",
+ "testFailureTimedOut": "The CLI did not respond within the test timeout.",
+ "testFailureCliFailed": "The CLI exited with an error. Open the toast details for the raw output.",
"activeAuthOauth": "Active: OAuth",
"activeAuthApiKey": "Active: API Key",
"activeAuthNone": "Not signed in",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 52b9061a5..f9aad66aa 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -188,6 +188,17 @@
"testConnectionLastFail": "上次失败:{{detail}}",
"testConnectionSuccessToast": "后端可达 · {{ms}} ms",
"testConnectionFailedToast": "后端测试失败:{{detail}}",
+ "testFailureInvalidCredentials": "保存的凭据被拒绝(401)。请更换 API key 或重新登录。",
+ "testFailureForbidden": "端点接受了凭据但拒绝访问(403)。检查 relay 的可用模型/权限。",
+ "testFailureModelNotFound": "请求使用的模型在端点上不存在。检查模型 id 或 relay 路由。",
+ "testFailureRateLimited": "端点返回限流/超配额(429)。请稍后或更换额度更高的 key。",
+ "testFailureEndpointUnreachable": "无法访问配置的 Base URL。请检查 DNS / 代理 / relay 是否在线。",
+ "testFailureServerError": "端点返回 5xx 错误。relay 可达但当前不健康。",
+ "testFailureTrustCheck": "Codex 拒绝在当前目录运行。重启回归容器让 cwd 进入受信任列表。",
+ "testFailureCliNotFound": "未找到后端 CLI 二进制。检查 Runtime 卡片上的路径。",
+ "testFailureSpawnFailed": "无法启动后端 CLI:{{detail}}",
+ "testFailureTimedOut": "CLI 在测试超时时间内没有响应。",
+ "testFailureCliFailed": "CLI 退出失败。点击 toast 查看原始输出。",
"activeAuthOauth": "当前:OAuth",
"activeAuthApiKey": "当前:API Key",
"activeAuthNone": "未登录",