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(auth): probe backends through Agent transports

cyh95cab37cc6a1
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 3a6080392..bbfdefe3d 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -23,6 +23,7 @@ from modules.claude_sdk_compat import (
from modules.agents.claude_process_reaper import (
AVIBE_CLAUDE_AUTH_OWNER,
AVIBE_CLAUDE_PROCESS_OWNER_ENV,
+ _reap_pid_set,
get_claude_client_pid,
register_claude_owned_process,
)
@@ -53,10 +54,11 @@ OPENCODE_API_KEY_PROMPT_RE = re.compile(r"enteryourapikey", re.IGNORECASE)
OPENCODE_CREDENTIAL_COUNT_RE = re.compile(r"\b(\d+)\s+credential(?:s)?\b", re.IGNORECASE)
CLAUDE_LOGIN_METHODS = {"claudeai", "console"}
OPENCODE_DIRECT_SETUP_URLS = {"opencode": "https://opencode.ai/auth"}
+CLAUDE_PROBE_DISCONNECT_TIMEOUT_SECONDS = 3.0
def _pick_probe_response_excerpt(stdout_text: str) -> str:
- """Return the first content-bearing line from Codex/Claude probe stdout.
+ """Return the first content-bearing line from a backend probe response.
The CLIs emit decorations the user doesn't care about: warnings
(``warning:``, ``ERROR:``, bubblewrap notices), session
@@ -110,7 +112,7 @@ def _classify_test_failure(
*,
auth_mode: str | None = None,
) -> str:
- """Map a backend CLI's failure output to a specific UI error code.
+ """Map a backend runtime'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*``),
@@ -491,17 +493,11 @@ class AgentAuthService:
cli_path = getattr(backend_cfg, "cli_path", None) or getattr(backend_cfg, "binary", None)
return cli_path or backend
- def _resolve_claude_probe_cwd(self) -> str:
- """Return the cwd that a Settings Claude probe should execute in.
-
- Plain ``claude -p`` loads project hooks, MCP config, and CLAUDE.md from
- the process cwd. Use the same default runtime cwd as live Agent turns so
- the Settings test reflects the actual Claude runtime instead of the UI
- server launch directory.
- """
+ def _resolve_backend_probe_cwd(self, backend: str) -> str:
+ """Return the default runtime cwd for an isolated backend Agent probe."""
config = getattr(getattr(self, "controller", None), "config", None)
candidates = (
- getattr(self._resolve_backend_config("claude"), "cwd", None),
+ getattr(self._resolve_backend_config(backend), "cwd", None),
getattr(getattr(config, "runtime", None), "default_cwd", None),
)
for raw in candidates:
@@ -511,7 +507,7 @@ class AgentAuthService:
os.makedirs(path, exist_ok=True)
return path
except OSError as exc:
- logger.warning("Failed to prepare Claude Settings probe cwd=%s: %s", path, exc)
+ logger.warning("Failed to prepare %s Settings probe cwd=%s: %s", backend, path, exc)
return os.getcwd()
def _build_claude_full_subprocess_env(self, *, force_oauth: bool = False) -> dict[str, str]:
@@ -2229,45 +2225,19 @@ class AgentAuthService:
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.
+ """Send ``Hi`` through the backend's production Agent transport.
+
+ Claude uses the Agent SDK stream and Codex uses app-server JSON-RPC,
+ matching normal Avibe turns. OpenCode keeps its provider-scoped probe
+ because it already uses the live ``opencode serve`` session API.
"""
- # remove_web_auth and test_web_auth are claude / codex specific
- # (single-backend subprocess invocations). OpenCode uses the
- # per-provider DELETE / dedicated probe endpoints elsewhere.
if backend not in {"claude", "codex"}:
return {"ok": False, "error": "unsupported_backend"}
binary = self._get_cli_binary(backend)
- prompt = "Hi"
- probe_cwd = None
+ probe_cwd = self._resolve_backend_probe_cwd(backend)
auth_mode = None
if backend == "claude":
- probe_cwd = self._resolve_claude_probe_cwd()
- # ``-p`` switches Claude Code into non-interactive print mode
- # and exits after the first complete reply. Deliberately do
- # not pass ``--bare`` here: recent Claude Code builds document
- # that bare mode skips OAuth/keychain reads and only accepts
- # API-key auth. This Settings probe should answer the user's
- # real question: whether the current Avibe Claude setup can
- # run an Agent turn. It follows the normal print-mode launch
- # path used by live Claude sessions.
- cmd = [binary]
- cmd.append("-p")
- if isinstance(model, str) and model.strip():
- cmd.extend(["--model", model.strip()])
- cmd.append(prompt)
backend_cfg = self._resolve_backend_config("claude")
auth_mode = getattr(backend_cfg, "auth_mode", None)
auth_mode_set = bool(getattr(backend_cfg, "auth_mode_set", False))
@@ -2276,124 +2246,254 @@ class AgentAuthService:
await self._clear_claude_settings_env_for_oauth()
except Exception as err: # noqa: BLE001
return {"ok": False, "error": "settings_cleanup_failed", "detail": str(err)}
- try:
- env_override = self._build_claude_full_subprocess_env()
- except Exception as err: # noqa: BLE001
- if auth_mode == "oauth" and auth_mode_set:
- return {"ok": False, "error": "spawn_failed", "detail": str(err)}
- env_override = dict(os.environ)
- else:
- # Codex single-shot mode. ``--skip-git-repo-check`` bypasses
- # Codex's per-project trust gate. We also force
- # ``model_reasoning_effort=low`` 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.
- #
- # NOT ``minimal``: OpenAI's Responses API rejects ``minimal``
- # reasoning when ``image_gen`` / ``web_search`` tools are
- # attached (which Codex auto-attaches for chat models with
- # no override flag to disable). The 400 reads ``"The
- # following tools cannot be used with reasoning.effort
- # 'minimal'"``. ``low`` is described in the model catalog
- # as "Fast responses with lighter reasoning" — still fast
- # enough for a probe, compatible with all tool sets.
- cmd = [
- binary,
- "exec",
- "--skip-git-repo-check",
- "-c",
- "model_reasoning_effort=low",
- ]
- 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()
try:
- process = await asyncio.create_subprocess_exec(
- *cmd,
- # Close stdin explicitly — Codex's ``exec`` mode reads a
- # second prompt from stdin when the parent's stdin is
- # open (e.g. ``codex exec "Hi" < /dev/null`` works fine,
- # but inheriting an open stdin makes it block forever).
- stdin=asyncio.subprocess.DEVNULL,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- env=env_override,
- cwd=probe_cwd,
+ run_probe = (
+ self._run_claude_agent_probe
+ if backend == "claude"
+ else self._run_codex_agent_probe
)
- try:
- stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
- except asyncio.TimeoutError:
- # Drain whatever the CLI managed to emit before we kill it
- # so we can still classify the failure. Codex in particular
- # retries 401 / network errors several times before exit;
- # the killed-mid-retry case loses the real error code if we
- # just report ``timed_out``. Read with a tight wait so the
- # kill path stays fast.
- process.kill()
- partial_stdout = b""
- partial_stderr = b""
- try:
- partial_stdout, partial_stderr = await asyncio.wait_for(
- process.communicate(), timeout=3.0
- )
- except (asyncio.TimeoutError, Exception): # noqa: BLE001
- pass
- stdout_partial = (partial_stdout or b"").decode("utf-8", errors="replace").strip()
- stderr_partial = (partial_stderr or b"").decode("utf-8", errors="replace").strip()
- classified = _classify_test_failure(
- stdout_partial,
- stderr_partial,
- auth_mode=auth_mode,
- )
- result = {
- "ok": False,
- "error": classified if classified != "cli_failed" else "timed_out",
- "duration_ms": int((time.monotonic() - started) * 1000),
- }
- if stderr_partial or stdout_partial:
- result["detail"] = (stderr_partial or stdout_partial)[:600]
- return result
+ response_text = await asyncio.wait_for(
+ run_probe(binary=binary, cwd=probe_cwd, model=model),
+ timeout=timeout,
+ )
+ except asyncio.TimeoutError:
+ return {
+ "ok": False,
+ "error": "timed_out",
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
except FileNotFoundError:
return {"ok": False, "error": "cli_not_found", "detail": binary}
except Exception as err: # noqa: BLE001
- return {"ok": False, "error": "spawn_failed", "detail": str(err)}
-
- duration_ms = int((time.monotonic() - started) * 1000)
- stdout_text = (stdout or b"").decode("utf-8", errors="replace").strip()
- stderr_text = (stderr or b"").decode("utf-8", errors="replace").strip()
-
- if process.returncode != 0:
- classified = _classify_test_failure(
- stdout_text,
- stderr_text,
- auth_mode=auth_mode,
- )
+ detail = str(err).strip()
+ if "no such file or directory" in detail.lower() or "claude code not found" in detail.lower():
+ error = "cli_not_found"
+ else:
+ error = _classify_test_failure("", detail, auth_mode=auth_mode)
return {
"ok": False,
- "error": classified,
- "exit_code": process.returncode,
- "detail": (stderr_text or stdout_text)[:600],
- "duration_ms": duration_ms,
+ "error": error,
+ "detail": detail[:600],
+ "duration_ms": int((time.monotonic() - started) * 1000),
}
- # 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,
- "excerpt": excerpt,
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ "excerpt": _pick_probe_response_excerpt(response_text),
+ }
+
+ async def _run_claude_agent_probe(
+ self,
+ *,
+ binary: str,
+ cwd: str,
+ model: str | None,
+ ) -> str:
+ """Run an isolated turn through the same Claude Agent SDK transport."""
+ from modules.agents.model_hub import claude_setting_sources_for_launch
+ from vibe.claude_config import build_claude_subprocess_env
+
+ stderr_lines: list[str] = []
+
+ def capture_stderr(line: str) -> None:
+ text = (line or "").strip()
+ if text:
+ stderr_lines.append(text)
+ del stderr_lines[:-40]
+
+ claude_env = build_claude_subprocess_env(self._resolve_backend_config("claude"))
+ claude_env[AVIBE_CLAUDE_PROCESS_OWNER_ENV] = AVIBE_CLAUDE_AUTH_OWNER
+ option_kwargs: dict[str, Any] = {
+ "permission_mode": "bypassPermissions",
+ "cwd": cwd,
+ "setting_sources": claude_setting_sources_for_launch(None),
+ "sandbox": {"enabled": False},
+ "tools": [],
+ "max_turns": 1,
+ "env": claude_env,
+ "stderr": capture_stderr,
+ "max_buffer_size": CLAUDE_SDK_MAX_BUFFER_SIZE,
}
+ if binary and binary != "claude":
+ option_kwargs["cli_path"] = os.path.expanduser(binary)
+ if isinstance(model, str) and model.strip():
+ option_kwargs["extra_args"] = {"model": model.strip()}
+
+ client = ClaudeSDKClient(options=ClaudeAgentOptions(**option_kwargs))
+ assistant_text = ""
+ assistant_error = ""
+ terminal_text = ""
+ try:
+ await client.connect()
+ register_claude_owned_process(client, owner=AVIBE_CLAUDE_AUTH_OWNER)
+ governor_from_controller(self.controller).apply_to_pid(
+ get_claude_client_pid(client),
+ label="claude connection probe",
+ )
+ await client.query("Hi")
+ async for message in client.receive_response():
+ content = getattr(message, "content", None)
+ if isinstance(content, list):
+ text_parts = [
+ str(getattr(block, "text", "")).strip()
+ for block in content
+ if str(getattr(block, "text", "")).strip()
+ ]
+ if text_parts:
+ assistant_text = "\n".join(text_parts)
+ message_error = getattr(message, "error", None)
+ if message_error:
+ assistant_error = str(message_error)
+ if hasattr(message, "is_error"):
+ result_text = str(getattr(message, "result", "") or "").strip()
+ if bool(getattr(message, "is_error", False)):
+ errors = getattr(message, "errors", None)
+ detail_parts = [result_text, assistant_error]
+ if isinstance(errors, list):
+ detail_parts.extend(str(item) for item in errors if item)
+ detail = "; ".join(part for part in detail_parts if part)
+ raise RuntimeError(detail or "Claude Agent turn failed")
+ if result_text:
+ terminal_text = result_text
+ if terminal_text:
+ return terminal_text
+ if assistant_error:
+ raise RuntimeError(assistant_error)
+ if assistant_text:
+ return assistant_text
+ raise RuntimeError("Claude Agent turn returned no response")
+ except Exception as err:
+ detail = str(err).strip()
+ stderr = "\n".join(stderr_lines).strip()
+ if stderr and stderr not in detail:
+ raise RuntimeError(f"{detail}\n{stderr}".strip()) from err
+ raise
+ finally:
+ await self._disconnect_claude_probe_client(client)
+
+ async def _disconnect_claude_probe_client(self, client: ClaudeSDKClient) -> None:
+ """Bound probe cleanup so a wedged SDK disconnect cannot defeat its timeout."""
+ pid = get_claude_client_pid(client)
+ try:
+ await asyncio.wait_for(
+ self._disconnect_claude_client(client),
+ timeout=CLAUDE_PROBE_DISCONNECT_TIMEOUT_SECONDS,
+ )
+ except asyncio.TimeoutError:
+ logger.warning("Claude connection probe did not disconnect within the cleanup timeout")
+ if pid:
+ await _reap_pid_set({pid}, terminate_timeout=2.0, logger=logger)
+
+ async def _run_codex_agent_probe(
+ self,
+ *,
+ binary: str,
+ cwd: str,
+ model: str | None,
+ ) -> str:
+ """Run an isolated turn through the normal Codex app-server protocol."""
+ from modules.agents.codex.transport import CodexTransport
+
+ backend_cfg = self._resolve_backend_config("codex")
+ transport = CodexTransport(
+ binary=binary,
+ cwd=cwd,
+ extra_args=list(getattr(backend_cfg, "extra_args", None) or []),
+ )
+ terminal: asyncio.Future[tuple[str, str]] = asyncio.get_running_loop().create_future()
+ response_text = ""
+
+ async def on_notification(method: str, params: dict[str, Any]) -> None:
+ nonlocal response_text
+ if method == "item/completed":
+ item = params.get("item") if isinstance(params, dict) else None
+ if isinstance(item, dict) and item.get("type") == "agentMessage":
+ text = str(item.get("text") or "").strip()
+ if text:
+ response_text = text
+ return
+ if method == "error":
+ if params.get("willRetry") is True:
+ return
+ error = params.get("error") if isinstance(params, dict) else params
+ detail = error.get("message") if isinstance(error, dict) else str(error or "Codex error")
+ if not terminal.done():
+ terminal.set_result(("error", detail))
+ return
+ if method != "turn/completed":
+ return
+ turn = params.get("turn") if isinstance(params, dict) else None
+ status = turn.get("status") if isinstance(turn, dict) else None
+ if status == "failed":
+ error = turn.get("error") if isinstance(turn, dict) else None
+ detail = error.get("message") if isinstance(error, dict) else str(error or "Codex turn failed")
+ if not terminal.done():
+ terminal.set_result(("error", detail))
+ elif status == "interrupted":
+ if not terminal.done():
+ terminal.set_result(("error", "Codex turn was interrupted"))
+ elif status == "completed":
+ if not terminal.done():
+ terminal.set_result(("success", response_text))
+ elif not terminal.done():
+ terminal.set_result(("error", f"Codex turn ended with status: {status or 'unknown'}"))
+
+ async def on_server_request(
+ _request_id: int | str,
+ _method: str,
+ _params: dict[str, Any],
+ ) -> dict[str, Any]:
+ return {"approved": True}
+
+ transport.on_notification(on_notification)
+ transport.on_server_request(on_server_request)
+ try:
+ await transport.start()
+ governor_from_controller(self.controller).apply_to_pid(
+ transport.pid,
+ label="codex connection probe",
+ )
+ thread_response = await transport.send_request(
+ "thread/start",
+ {
+ "cwd": cwd,
+ "approvalPolicy": "never",
+ "sandbox": "danger-full-access",
+ },
+ )
+ thread = thread_response.get("thread")
+ thread_id = thread_response.get("id") or (
+ thread.get("id") if isinstance(thread, dict) else None
+ )
+ if not thread_id:
+ raise RuntimeError("Codex thread/start returned no thread id")
+ turn_params: dict[str, Any] = {
+ "threadId": thread_id,
+ "input": [{"type": "text", "text": "Hi"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {"type": "dangerFullAccess"},
+ "effort": "low",
+ }
+ if isinstance(model, str) and model.strip():
+ turn_params["model"] = model.strip()
+ turn_response = await transport.send_request("turn/start", turn_params)
+ turn = turn_response.get("turn")
+ turn_id = turn_response.get("id") or (
+ turn.get("id") if isinstance(turn, dict) else None
+ )
+ if not turn_id:
+ raise RuntimeError("Codex turn/start returned no turn id")
+ outcome, result = await terminal
+ if outcome == "error":
+ raise RuntimeError(result)
+ if not result.strip():
+ raise RuntimeError("Codex Agent turn returned no response")
+ return result
+ finally:
+ await transport.stop()
async def test_opencode_provider(
self,
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index f69463d14..04dfcbbf9 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -170,11 +170,18 @@ scenarios:
backend: claude
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_oauth_to_explicit_auth_token_reaches_next_turn
- id: AUTH-SETUP-905
- name: Claude API key probe drops a stale inherited auth token after switching from OAuth
+ name: Claude SDK probe drops a stale inherited auth token after switching from OAuth
status: covered
kind: historical_regression
layer: scenario
backend: claude
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_oauth_to_api_key_probe_drops_stale_auth_token
+ - id: AUTH-SETUP-906
+ name: Codex connection probe uses an app-server Agent turn
+ status: covered
+ kind: historical_regression
+ layer: scenario
+ backend: codex
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_codex_connection_probe_uses_app_server_turn
next_priority:
- AUTH-SETUP-301
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 87bc36ea2..32ec154b5 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -222,26 +222,6 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
),
encoding="utf-8",
)
- probe_cli = home / "claude-probe"
- probe_cli.write_text(
- f"""#!{sys.executable}
-import os
-import sys
-
-expected = (
- sys.argv[1:] == ["-p", "Hi"]
- and os.environ.get("ANTHROPIC_API_KEY") == "relay-api-key"
- and "ANTHROPIC_AUTH_TOKEN" not in os.environ
- and os.environ.get("ANTHROPIC_BASE_URL") == "https://ai.coinsummer.com"
-)
-if not expected:
- print("unexpected Claude probe environment")
- raise SystemExit(7)
-print("relay-probe-ok")
-""",
- encoding="utf-8",
- )
- probe_cli.chmod(0o755)
harness = AuthSetupScenarioHarness()
runner = ScenarioRunner(harness)
@@ -274,6 +254,27 @@ print("relay-probe-ok")
async def run_connection_probe(current):
current.test_result = await probe_backend_auth_async("claude")
+ class FakeClaudeSDKClient:
+ def __init__(self, *, options):
+ harness.probe_options = options
+
+ async def connect(self):
+ return None
+
+ async def query(self, text):
+ harness.probe_query = text
+
+ async def receive_response(self):
+ yield SimpleNamespace(
+ is_error=False,
+ result="relay-probe-ok",
+ content=[],
+ error=None,
+ )
+
+ async def disconnect(self):
+ return None
+
with (
patch.dict(
os.environ,
@@ -292,6 +293,7 @@ print("relay-probe-ok")
),
patch("vibe.api.restart_backend", side_effect=restart_backend),
patch("vibe.api._read_claude_cli_oauth_signed_in", return_value=None),
+ patch("core.agent_auth_service.ClaudeSDKClient", FakeClaudeSDKClient),
):
config = V2Config(
mode="self_host",
@@ -302,7 +304,7 @@ print("relay-probe-ok")
)
config.agents.claude.auth_mode = "oauth"
config.agents.claude.auth_mode_set = True
- config.agents.claude.cli_path = str(probe_cli)
+ config.agents.claude.cli_path = "claude-probe"
config.save()
await runner.run(
@@ -328,6 +330,17 @@ print("relay-probe-ok")
)
self.assertTrue(harness.test_result["ok"])
self.assertEqual(harness.test_result["excerpt"], "relay-probe-ok")
+ self.assertEqual(harness.probe_query, "Hi")
+ self.assertEqual(harness.probe_options.cli_path, "claude-probe")
+ self.assertEqual(
+ harness.probe_options.env["ANTHROPIC_API_KEY"],
+ "relay-api-key",
+ )
+ self.assertEqual(harness.probe_options.env["ANTHROPIC_AUTH_TOKEN"], "")
+ self.assertEqual(
+ harness.probe_options.env["ANTHROPIC_BASE_URL"],
+ "https://ai.coinsummer.com",
+ )
self.assertEqual(cleanup_calls, [service])
self.assertEqual(
restart_calls,
@@ -343,6 +356,105 @@ print("relay-probe-ok")
["confirm_oauth_is_active", "save_api_key", "test_connection"],
)
+ async def test_codex_connection_probe_uses_app_server_turn(self):
+ """Scenario: AUTH-SETUP-906"""
+ state_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(state_dir.cleanup)
+ home = Path(state_dir.name)
+ harness = AuthSetupScenarioHarness()
+ runner = ScenarioRunner(harness)
+ service = AgentAuthService(_ReloadingV2ConfigController())
+ requests = []
+
+ class FakeCodexTransport:
+ pid = None
+
+ def __init__(self, **kwargs):
+ harness.transport_init = kwargs
+ self.notification = None
+
+ def on_notification(self, callback):
+ self.notification = callback
+
+ def on_server_request(self, callback):
+ harness.server_request = callback
+
+ async def start(self):
+ harness.transport_started = True
+
+ async def stop(self):
+ harness.transport_stopped = True
+
+ async def send_request(self, method, params):
+ requests.append((method, params))
+ if method == "thread/start":
+ return {"thread": {"id": "thread-probe"}}
+ await self.notification(
+ "item/completed",
+ {
+ "turnId": "turn-probe",
+ "item": {"type": "agentMessage", "text": "codex-probe-ok"},
+ },
+ )
+ await self.notification(
+ "turn/completed",
+ {"turn": {"id": "turn-probe", "status": "completed"}},
+ )
+ return {"turn": {"id": "turn-probe"}}
+
+ async def run_connection_probe(current):
+ current.test_result = await probe_backend_auth_async(
+ "codex",
+ model="gpt-5.4-mini",
+ )
+
+ with (
+ patch.dict(os.environ, {"AVIBE_HOME": str(home / ".avibe")}),
+ patch("vibe.api._get_oauth_service", return_value=service),
+ patch("modules.agents.codex.transport.CodexTransport", FakeCodexTransport),
+ ):
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd=str(home)),
+ agents=AgentsConfig(),
+ )
+ config.agents.codex.cli_path = "codex-probe"
+ config.save()
+ await runner.run(ScenarioStep("test_connection", run_connection_probe))
+
+ self.assertTrue(harness.test_result["ok"])
+ self.assertEqual(harness.test_result["excerpt"], "codex-probe-ok")
+ self.assertTrue(harness.transport_started)
+ self.assertTrue(harness.transport_stopped)
+ self.assertEqual(harness.transport_init["binary"], "codex-probe")
+ self.assertEqual(
+ requests,
+ [
+ (
+ "thread/start",
+ {
+ "cwd": str(home),
+ "approvalPolicy": "never",
+ "sandbox": "danger-full-access",
+ },
+ ),
+ (
+ "turn/start",
+ {
+ "threadId": "thread-probe",
+ "input": [{"type": "text", "text": "Hi"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {"type": "dangerFullAccess"},
+ "effort": "low",
+ "model": "gpt-5.4-mini",
+ },
+ ),
+ ],
+ )
+ ScenarioExpect.step_history(runner, ["test_connection"])
+
async def test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch(self):
"""Scenario: AUTH-SETUP-903"""
agent = object.__new__(CodexAgent)
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 9118a3297..c97e6d5c5 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -16,7 +16,7 @@ import json
import os
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import ANY, AsyncMock
import pytest
@@ -1318,34 +1318,120 @@ def test_test_web_auth_rejects_unsupported_backend(service: AgentAuthService) ->
def test_test_web_auth_surfaces_cli_not_found(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- async def _spawn(*_args, **_kwargs):
- raise FileNotFoundError("no such cli")
-
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(
+ service,
+ "_run_codex_agent_probe",
+ AsyncMock(side_effect=FileNotFoundError("no such cli")),
+ )
result = _run(service.test_web_auth("codex"))
assert result["ok"] is False
assert result["error"] == "cli_not_found"
+def test_claude_probe_timeout_bounds_disconnect_and_reaps_process(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ class _WedgedClaudeClient:
+ async def disconnect(self):
+ await asyncio.Event().wait()
+
+ reap = AsyncMock(return_value=1)
+ monkeypatch.setattr(
+ "core.agent_auth_service.CLAUDE_PROBE_DISCONNECT_TIMEOUT_SECONDS",
+ 0.01,
+ )
+ monkeypatch.setattr("core.agent_auth_service.get_claude_client_pid", lambda _client: 4321)
+ monkeypatch.setattr("core.agent_auth_service._reap_pid_set", reap)
+
+ _run(service._disconnect_claude_probe_client(_WedgedClaudeClient()))
+
+ reap.assert_awaited_once_with(
+ {4321},
+ terminate_timeout=2.0,
+ logger=ANY,
+ )
+
+
def test_test_web_auth_happy_path_returns_excerpt(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- """A passing probe surfaces the first non-blank stdout line + duration."""
+ """Codex probes use app-server thread/turn requests, not ``codex exec``."""
+ captured: dict[str, object] = {"requests": []}
- class _FakeProcess:
- returncode = 0
+ class _FakeTransport:
+ pid = None
- async def communicate(self):
- return (b"\nHello from the model\nmore text", b"")
+ def __init__(self, **kwargs):
+ captured["init"] = kwargs
+ self.notification = None
- async def _spawn(*_args, **_kwargs):
- return _FakeProcess()
+ def on_notification(self, callback):
+ self.notification = callback
+
+ def on_server_request(self, callback):
+ captured["server_request"] = callback
+
+ async def start(self):
+ captured["started"] = True
+
+ async def stop(self):
+ captured["stopped"] = True
+
+ async def send_request(self, method, params):
+ captured["requests"].append((method, params))
+ if method == "thread/start":
+ return {"thread": {"id": "thread-probe"}}
+ assert self.notification is not None
+ await self.notification(
+ "error",
+ {
+ "turnId": "turn-probe",
+ "willRetry": True,
+ "error": {"message": "temporary upstream disconnect"},
+ },
+ )
+ await self.notification(
+ "item/completed",
+ {
+ "turnId": "turn-probe",
+ "item": {"type": "agentMessage", "text": "Hello from the model\nmore text"},
+ },
+ )
+ await self.notification(
+ "turn/completed",
+ {"turn": {"id": "turn-probe", "status": "completed"}},
+ )
+ return {"turn": {"id": "turn-probe"}}
+
+ monkeypatch.setattr("modules.agents.codex.transport.CodexTransport", _FakeTransport)
+ result = _run(service.test_web_auth("codex", model="gpt-5.4-mini"))
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
- result = _run(service.test_web_auth("codex"))
assert result["ok"] is True
assert result["excerpt"] == "Hello from the model"
assert isinstance(result["duration_ms"], int)
+ assert captured["started"] is True
+ assert captured["stopped"] is True
+ assert captured["requests"] == [
+ (
+ "thread/start",
+ {
+ "cwd": os.getcwd(),
+ "approvalPolicy": "never",
+ "sandbox": "danger-full-access",
+ },
+ ),
+ (
+ "turn/start",
+ {
+ "threadId": "thread-probe",
+ "input": [{"type": "text", "text": "Hi"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {"type": "dangerFullAccess"},
+ "effort": "low",
+ "model": "gpt-5.4-mini",
+ },
+ ),
+ ]
def test_verify_web_login_claude_forces_oauth_env(
@@ -1424,38 +1510,52 @@ def test_verify_web_login_claude_forces_oauth_env(
def test_test_web_auth_claude_oauth_env_removes_stale_anthropic_vars(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- """The Settings Test button runs a real Claude subprocess; when OAuth is
- explicitly selected it must use the same env cleanup as live sessions.
- """
+ """The Claude probe uses the SDK with the same filtered launch env."""
captured: dict = {}
- class _FakeProcess:
- returncode = 0
+ class _FakeClaudeClient:
+ def __init__(self, *, options):
+ captured["options"] = options
- async def communicate(self):
- return (b"Hello from Claude", b"")
+ async def connect(self):
+ captured["connected"] = True
- async def _spawn(*args, **kwargs):
- captured["args"] = args
- captured["env"] = kwargs.get("env") or {}
- return _FakeProcess()
+ async def query(self, text):
+ captured["query"] = text
+
+ async def receive_response(self):
+ yield SimpleNamespace(
+ is_error=False,
+ result="Hello from Claude",
+ content=[],
+ error=None,
+ )
+
+ async def disconnect(self):
+ captured["disconnected"] = True
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-stale-shell")
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "bearer-stale-shell")
monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://stale-relay.example")
monkeypatch.setattr(_Backend, "auth_mode", "oauth", raising=False)
monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr("core.agent_auth_service.ClaudeSDKClient", _FakeClaudeClient)
result = _run(service.test_web_auth("claude"))
assert result["ok"] is True
- assert captured["args"][:2] == ("/usr/bin/echo", "-p")
- assert "--bare" not in captured["args"]
- assert "ANTHROPIC_API_KEY" not in captured["env"]
- assert "ANTHROPIC_AUTH_TOKEN" not in captured["env"]
- assert "ANTHROPIC_BASE_URL" not in captured["env"]
+ options = captured["options"]
+ assert options.cli_path == "/usr/bin/echo"
+ assert options.permission_mode == "bypassPermissions"
+ assert options.setting_sources == ["user", "project", "local"]
+ assert options.tools == []
+ assert options.env["ANTHROPIC_API_KEY"] == ""
+ assert options.env["ANTHROPIC_AUTH_TOKEN"] == ""
+ assert options.env["ANTHROPIC_BASE_URL"] == ""
+ assert captured["query"] == "Hi"
+ assert captured["connected"] is True
+ assert captured["disconnected"] is True
def test_test_web_auth_claude_runs_in_runtime_cwd(
@@ -1463,116 +1563,90 @@ def test_test_web_auth_claude_runs_in_runtime_cwd(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Plain Claude print mode reads project config from cwd; the Settings
- probe must use the same runtime cwd as live Agent turns.
- """
+ """The isolated SDK probe uses the same default cwd as live Agent turns."""
runtime_cwd = tmp_path / "agent-workdir"
- captured: dict = {}
class _Runtime:
default_cwd = str(runtime_cwd)
- class _FakeProcess:
- returncode = 0
-
- async def communicate(self):
- return (b"Hello from Claude", b"")
-
- async def _spawn(*_args, **kwargs):
- captured["cwd"] = kwargs.get("cwd")
- return _FakeProcess()
-
+ probe = AsyncMock(return_value="Hello from Claude")
monkeypatch.setattr(_Config, "runtime", _Runtime(), raising=False)
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(service, "_run_claude_agent_probe", probe)
result = _run(service.test_web_auth("claude"))
assert result["ok"] is True
- assert captured["cwd"] == str(runtime_cwd)
+ probe.assert_awaited_once_with(
+ binary="/usr/bin/echo",
+ cwd=str(runtime_cwd),
+ model=None,
+ )
assert runtime_cwd.is_dir()
def test_test_web_auth_claude_oauth_reports_settings_cleanup_failure(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- async def _spawn(*_args, **_kwargs):
- raise AssertionError("Claude probe must not spawn when cleanup fails")
-
def fail_cleanup(**_kwargs):
raise OSError("settings locked")
+ probe = AsyncMock(side_effect=AssertionError("Claude probe must not start"))
monkeypatch.setattr(_Backend, "auth_mode", "oauth", raising=False)
monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)
monkeypatch.setattr("vibe.claude_config.apply_claude_auth", fail_cleanup)
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(service, "_run_claude_agent_probe", probe)
result = _run(service.test_web_auth("claude"))
assert result["ok"] is False
assert result["error"] == "settings_cleanup_failed"
assert "Failed to clear Claude Code settings env" in result["detail"]
+ probe.assert_not_awaited()
def test_test_web_auth_failure_surfaces_stderr(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- class _FakeProcess:
- returncode = 7
-
- async def communicate(self):
- return (b"", b"Authentication failed: no credentials configured")
-
- async def _spawn(*_args, **_kwargs):
- return _FakeProcess()
-
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(
+ service,
+ "_run_claude_agent_probe",
+ AsyncMock(side_effect=RuntimeError("Authentication failed: no credentials configured")),
+ )
result = _run(service.test_web_auth("claude"))
assert result["ok"] is False
# 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 "")
def test_test_web_auth_not_logged_in_has_specific_error_code(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- class _FakeProcess:
- returncode = 1
-
- async def communicate(self):
- return (b"Not logged in \xc2\xb7 Please run /login", b"")
-
- async def _spawn(*_args, **_kwargs):
- return _FakeProcess()
-
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(
+ service,
+ "_run_claude_agent_probe",
+ AsyncMock(side_effect=RuntimeError("Not logged in · Please run /login")),
+ )
monkeypatch.setattr(_Backend, "auth_mode", "oauth", raising=False)
result = _run(service.test_web_auth("claude"))
assert result["ok"] is False
assert result["error"] == "not_logged_in"
- assert result["exit_code"] == 1
assert "Not logged in" in (result.get("detail") or "")
def test_test_web_auth_api_key_mode_does_not_prompt_for_oauth_login(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- class _FakeProcess:
- returncode = 1
-
- async def communicate(self):
- return (b"Not logged in \xc2\xb7 Please run /login", b"")
-
- async def _spawn(*_args, **_kwargs):
- return _FakeProcess()
-
- monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(
+ service,
+ "_run_claude_agent_probe",
+ AsyncMock(side_effect=RuntimeError("Not logged in · Please run /login")),
+ )
monkeypatch.setattr(_Backend, "auth_mode", "api_key", raising=False)
monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)
@@ -1580,4 +1654,3 @@ def test_test_web_auth_api_key_mode_does_not_prompt_for_oauth_login(
assert result["ok"] is False
assert result["error"] == "invalid_credentials"
- assert result["exit_code"] == 1
diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsx
index 513aae8a5..44ab5c78b 100644
--- a/ui/src/components/settings/BackendTestPanel.tsx
+++ b/ui/src/components/settings/BackendTestPanel.tsx
@@ -19,16 +19,14 @@ export type BackendTestPanelProps = {
/**
* Settings → Backends connectivity probe. Mirrors the ``cdTest2`` /
* ``cxTest`` panels in ``design.pen``: sends a single ``Hi`` prompt
- * through the backend CLI so the user can confirm both the credentials
- * 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.
+ * through the backend's production Agent transport so the user can
+ * confirm both the credentials and the endpoint (Base URL) round-trip
+ * end-to-end. Works in both OAuth and API-Key modes.
*
* 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.
+ * (important when the configured default is unavailable or slow). 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();
diff --git a/vibe/api.py b/vibe/api.py
index 86435a83c..1e1090ee1 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -8899,11 +8899,11 @@ def test_backend_auth(backend: str, model: Optional[str] = None) -> dict:
async def test_backend_auth_async(backend: str, model: Optional[str] = None) -> dict:
- """Send a single-token ``Hi`` probe through the backend CLI.
+ """Send a ``Hi`` probe through the backend's production Agent transport.
- ``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.
+ Claude uses the Agent SDK and Codex uses app-server, matching normal
+ Avibe turns rather than a separate single-shot CLI mode. ``model`` lets
+ the caller select the model used by that isolated turn.
"""
backend = (backend or "").strip().lower()
if not supports_web_oauth(backend):
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index f5e6e2fac..2a5403bbc 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5705,7 +5705,7 @@ def backend_auth_api_key_remove(backend: str):
@app.route("/api/backend/<backend>/auth/test", methods=["POST"])
async def backend_auth_test(backend: str):
- """Send a single-token probe through the backend CLI to verify auth."""
+ """Send an isolated turn through the backend's production Agent transport."""
from vibe import api
payload = request.json or {}