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): reuse controller-owned Codex runtime

cyhb5eeb5696c98
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index bbfdefe3d..2b0a008de 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -55,6 +55,7 @@ OPENCODE_CREDENTIAL_COUNT_RE = re.compile(r"\b(\d+)\s+credential(?:s)?\b", re.IG
CLAUDE_LOGIN_METHODS = {"claudeai", "console"}
OPENCODE_DIRECT_SETUP_URLS = {"opencode": "https://opencode.ai/auth"}
CLAUDE_PROBE_DISCONNECT_TIMEOUT_SECONDS = 3.0
+CLAUDE_PROBE_PROCESS_EXIT_GRACE_SECONDS = 0.2
def _pick_probe_response_excerpt(stdout_text: str) -> str:
@@ -2249,15 +2250,15 @@ class AgentAuthService:
started = time.monotonic()
try:
- run_probe = (
- self._run_claude_agent_probe
- if backend == "claude"
- else self._run_codex_agent_probe
- )
- response_text = await asyncio.wait_for(
- run_probe(binary=binary, cwd=probe_cwd, model=model),
- timeout=timeout,
- )
+ if backend == "claude":
+ probe = self._run_claude_agent_probe(
+ binary=binary,
+ cwd=probe_cwd,
+ model=model,
+ )
+ else:
+ probe = self._run_codex_agent_probe(cwd=probe_cwd, model=model)
+ response_text = await asyncio.wait_for(probe, timeout=timeout)
except asyncio.TimeoutError:
return {
"ok": False,
@@ -2384,116 +2385,42 @@ class AgentAuthService:
)
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)
+ if not pid:
+ return
+
+ transport = getattr(client, "_transport", None)
+ process = getattr(transport, "_process", None)
+ wait = getattr(process, "wait", None)
+ if callable(wait):
+ try:
+ await asyncio.wait_for(
+ wait(),
+ timeout=CLAUDE_PROBE_PROCESS_EXIT_GRACE_SECONDS,
+ )
+ return
+ except asyncio.TimeoutError:
+ pass
+ except Exception: # noqa: BLE001
+ logger.debug(
+ "Claude connection probe process wait failed; reaping by pid",
+ exc_info=True,
+ )
+ 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()
+ """Run through the controller-owned CodexAgent transport pool."""
+ agent_service = getattr(self.controller, "agent_service", None)
+ agents = getattr(agent_service, "agents", None)
+ agent = agents.get("codex") if isinstance(agents, dict) else None
+ probe = getattr(agent, "probe_connection", None)
+ if not callable(probe):
+ raise RuntimeError("Codex Agent runtime is unavailable")
+ return await probe(cwd, model=model)
async def test_opencode_provider(
self,
diff --git a/core/internal_server.py b/core/internal_server.py
index 084b236ca..ae1394ddf 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -709,6 +709,39 @@ def create_app(controller: "Controller") -> FastAPI:
logger.exception("internal Agent backend reconcile failed")
return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+ @app.post("/internal/backend-auth/test")
+ async def _test_backend_auth(request: Request) -> Any:
+ """Probe credentials through the controller-owned Agent runtime."""
+ payload = await _safe_json(request)
+ backend = payload.get("backend")
+ model = payload.get("model")
+ if not isinstance(backend, str) or not backend.strip():
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "backend must be a non-empty string"},
+ )
+ if model is not None and not isinstance(model, str):
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "model must be a string"},
+ )
+ service = getattr(controller, "agent_auth_service", None)
+ test = getattr(service, "test_web_auth", None)
+ if not callable(test):
+ return JSONResponse(
+ status_code=503,
+ content={"ok": False, "error": "backend_runtime_unavailable"},
+ )
+ try:
+ result = await test(
+ backend.strip().lower(),
+ model=model.strip() if isinstance(model, str) and model.strip() else None,
+ )
+ return JSONResponse(status_code=200, content=result)
+ except Exception as exc:
+ logger.exception("internal backend auth test failed")
+ return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+
@app.post("/internal/model-hub")
async def _model_hub(request: Request) -> Any:
"""Dispatch UI operations to the controller-owned Model Hub aggregate."""
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index c5b45626e..a287bf286 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -62,6 +62,16 @@ _CODEX_REBINDABLE_SAME_ID_PROVIDERS = _CODEX_MANAGED_PROVIDER_IDS | frozenset(
(_CODEX_MODEL_HUB_PROVIDER_ID,)
)
CODEX_CALLER_ENV_DIR = "codex-caller-env"
+CODEX_CONNECTION_PROBE_DIR = "codex-connection-probe"
+
+
+class _CodexConnectionProbeState:
+ def __init__(self) -> None:
+ self.terminal: asyncio.Future[tuple[str, str]] = (
+ asyncio.get_running_loop().create_future()
+ )
+ self.response_text = ""
+ self.turn_id = ""
class CodexResumeUnavailableError(RuntimeError):
@@ -120,6 +130,8 @@ class CodexAgent(BaseAgent):
# base_session_id → (thread_id, effective Git PATH, PATH override persisted)
self._thread_git_path_configs: Dict[str, tuple[str, str, bool]] = {}
self._fork_correction_pending_base_sessions: set[str] = set()
+ self._connection_probes: Dict[str, _CodexConnectionProbeState] = {}
+ self._connection_probe_turns: Dict[str, str] = {}
# ------------------------------------------------------------------
# BaseAgent interface
@@ -167,6 +179,85 @@ class CodexAgent(BaseAgent):
return lambda: None
return lambda: self._transport_alive(transport)
+ async def probe_connection(self, cwd: str, *, model: str | None = None) -> str:
+ """Run a read-only ephemeral turn on the normal persistent app-server."""
+
+ probe_cwd = paths.get_runtime_dir() / CODEX_CONNECTION_PROBE_DIR
+ probe_cwd.mkdir(parents=True, exist_ok=True)
+
+ transport = self._transports.get(cwd)
+ if transport is None or not transport.is_initialized:
+ transport = await self._get_or_create_transport(cwd)
+ else:
+ self._touch_transport_activity(cwd)
+
+ thread_response = await transport.send_request(
+ "thread/start",
+ {
+ "cwd": str(probe_cwd),
+ "approvalPolicy": "never",
+ "sandbox": "read-only",
+ "ephemeral": True,
+ "developerInstructions": (
+ "This is a connection probe. Do not use tools. "
+ "Reply with a short greeting."
+ ),
+ },
+ )
+ 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")
+
+ state = _CodexConnectionProbeState()
+ self._connection_probes[thread_id] = state
+ closed_task: asyncio.Task[None] | None = None
+ try:
+ turn_params: Dict[str, Any] = {
+ "threadId": thread_id,
+ "input": [{"type": "text", "text": "Hi"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {"type": "readOnly", "networkAccess": False},
+ "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")
+ state.turn_id = str(turn_id)
+ self._connection_probe_turns[state.turn_id] = thread_id
+
+ closed_task = asyncio.create_task(transport.wait_closed())
+ done, _ = await asyncio.wait(
+ {state.terminal, closed_task},
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if state.terminal not in done:
+ raise ConnectionError("Codex app-server exited during the connection probe")
+ outcome, result = state.terminal.result()
+ if outcome == "error":
+ raise RuntimeError(result)
+ if not result.strip():
+ raise RuntimeError("Codex Agent turn returned no response")
+ self._touch_transport_activity(cwd)
+ return result
+ finally:
+ self._connection_probes.pop(thread_id, None)
+ if state.turn_id:
+ self._connection_probe_turns.pop(state.turn_id, None)
+ if not state.terminal.done():
+ state.terminal.cancel()
+ if closed_task is not None:
+ closed_task.cancel()
+ await asyncio.gather(closed_task, return_exceptions=True)
+
async def _record_model_hub_native_failure(self, context: Any, diagnostic: str) -> bool:
router = getattr(self.controller, "model_hub_runtime", None)
recorder = getattr(router, "record_native_failure", None)
@@ -2287,6 +2378,8 @@ class CodexAgent(BaseAgent):
async def _on_notification(self, method: str, params: Dict[str, Any]) -> None:
"""Route a server notification to the event handler."""
+ if self._handle_connection_probe_notification(method, params):
+ return
request = self._find_request_for_notification(method, params)
if not request:
thread_id = self._extract_thread_id(params)
@@ -2304,6 +2397,65 @@ class CodexAgent(BaseAgent):
self._touch_session_activity(request.base_session_id)
await self._event_handler.handle_notification(method, params, request)
+ def _handle_connection_probe_notification(
+ self,
+ method: str,
+ params: Dict[str, Any],
+ ) -> bool:
+ thread_id = self._extract_thread_id(params)
+ turn_id = self._extract_turn_id(params)
+ probe_turns = getattr(self, "_connection_probe_turns", {})
+ if not thread_id and turn_id:
+ thread_id = probe_turns.get(turn_id, "")
+ state = getattr(self, "_connection_probes", {}).get(thread_id)
+ if state is None:
+ return False
+ if turn_id:
+ state.turn_id = turn_id
+ probe_turns[turn_id] = thread_id
+
+ 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:
+ state.response_text = text
+ return True
+ if method == "error":
+ if params.get("willRetry") is True:
+ return True
+ 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 state.terminal.done():
+ state.terminal.set_result(("error", str(detail or "Codex error")))
+ return True
+ if method != "turn/completed":
+ return True
+
+ turn = params.get("turn") if isinstance(params, dict) else None
+ status = turn.get("status") if isinstance(turn, dict) else None
+ if status == "completed":
+ outcome = ("success", state.response_text)
+ elif status == "interrupted":
+ outcome = ("error", "Codex turn was interrupted")
+ elif 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")
+ )
+ outcome = ("error", str(detail or "Codex turn failed"))
+ else:
+ outcome = ("error", f"Codex turn ended with status: {status or 'unknown'}")
+ if not state.terminal.done():
+ state.terminal.set_result(outcome)
+ return True
+
async def _on_server_request(
self,
cwd: str,
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index 3db4b4e6f..dbe987076 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -56,6 +56,7 @@ class CodexTransport:
self._notify_queue: asyncio.Queue[tuple[str, dict[str, Any]]] = asyncio.Queue()
self._notify_task: Optional[asyncio.Task[None]] = None
self._notify_inflight = 0
+ self._closed_event = asyncio.Event()
# ------------------------------------------------------------------
# Lifecycle
@@ -67,6 +68,7 @@ class CodexTransport:
logger.warning("CodexTransport.start() called but process is already running")
return
+ self._closed_event.clear()
cmd = (
[self._binary, "--dangerously-bypass-approvals-and-sandbox"]
+ ["app-server"]
@@ -128,6 +130,7 @@ class CodexTransport:
self._initialized = False
proc = self._process
if not proc or proc.returncode is not None:
+ self._closed_event.set()
self._cleanup_tasks()
return
@@ -152,6 +155,7 @@ class CodexTransport:
pass
self._cleanup_tasks()
+ self._closed_event.set()
# Fail all pending futures
for fut in self._pending.values():
if not fut.done():
@@ -187,6 +191,15 @@ class CodexTransport:
return self._notify_inflight > 0 or not self._notify_queue.empty()
+ async def wait_closed(self) -> None:
+ """Wait until the app-server exits and already-read notifications drain."""
+
+ await self._closed_event.wait()
+ for _ in range(50):
+ if not self.has_pending_notifications:
+ return
+ await asyncio.sleep(0.01)
+
@property
def pid(self) -> Optional[int]:
"""OS pid of the codex app-server subprocess, or ``None`` if not running.
@@ -297,6 +310,7 @@ class CodexTransport:
logger.exception("Codex reader loop crashed")
finally:
self._initialized = False
+ self._closed_event.set()
# Process ended — fail pending futures
for fut in self._pending.values():
if not fut.done():
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 04dfcbbf9..322eb1b0c 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -177,11 +177,11 @@ scenarios:
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
+ name: Codex connection probe reuses the persistent app-server with an ephemeral 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
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_codex_connection_probe_reuses_persistent_app_server
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 32ec154b5..8a8c12003 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -356,52 +356,52 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
["confirm_oauth_is_active", "save_api_key", "test_connection"],
)
- async def test_codex_connection_probe_uses_app_server_turn(self):
+ async def test_codex_connection_probe_reuses_persistent_app_server(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
+ is_initialized = True
async def send_request(self, method, params):
requests.append((method, params))
if method == "thread/start":
return {"thread": {"id": "thread-probe"}}
- await self.notification(
+ await agent._on_notification(
"item/completed",
{
+ "threadId": "thread-probe",
"turnId": "turn-probe",
"item": {"type": "agentMessage", "text": "codex-probe-ok"},
},
)
- await self.notification(
+ await agent._on_notification(
"turn/completed",
- {"turn": {"id": "turn-probe", "status": "completed"}},
+ {
+ "threadId": "thread-probe",
+ "turn": {"id": "turn-probe", "status": "completed"},
+ },
)
return {"turn": {"id": "turn-probe"}}
+ async def wait_closed(self):
+ await asyncio.Event().wait()
+
+ controller = _ReloadingV2ConfigController()
+ agent = object.__new__(CodexAgent)
+ agent.controller = controller
+ agent._transports = {str(home): FakeCodexTransport()}
+ agent._transport_last_activity = {}
+ agent._connection_probes = {}
+ agent._connection_probe_turns = {}
+ controller.agent_service = SimpleNamespace(agents={"codex": agent})
+ service = AgentAuthService(controller)
+
async def run_connection_probe(current):
current.test_result = await probe_backend_auth_async(
"codex",
@@ -411,7 +411,6 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
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",
@@ -426,18 +425,22 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
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),
+ "cwd": str(
+ (home / ".avibe" / "runtime" / "codex-connection-probe").resolve()
+ ),
"approvalPolicy": "never",
- "sandbox": "danger-full-access",
+ "sandbox": "read-only",
+ "ephemeral": True,
+ "developerInstructions": (
+ "This is a connection probe. Do not use tools. "
+ "Reply with a short greeting."
+ ),
},
),
(
@@ -446,7 +449,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
"threadId": "thread-probe",
"input": [{"type": "text", "text": "Hi"}],
"approvalPolicy": "never",
- "sandboxPolicy": {"type": "dangerFullAccess"},
+ "sandboxPolicy": {"type": "readOnly", "networkAccess": False},
"effort": "low",
"model": "gpt-5.4-mini",
},
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index ddec68ebd..89bfd0d46 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -264,6 +264,132 @@ class CodexAgentNotificationRoutingTests(unittest.TestCase):
self.assertIsNone(resolved)
+class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
+ def _agent(self, cwd: str, transport):
+ agent = object.__new__(CodexAgent)
+ agent._transports = {cwd: transport}
+ agent._transport_last_activity = {}
+ agent._connection_probes = {}
+ agent._connection_probe_turns = {}
+ return agent
+
+ async def test_reuses_existing_transport_with_isolated_ephemeral_thread(self):
+ requests = []
+ cwd = "/tmp/user-project"
+ runtime_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(runtime_dir.cleanup)
+
+ class _Transport:
+ is_initialized = True
+
+ async def send_request(inner_self, method, params):
+ requests.append((method, params))
+ if method == "thread/start":
+ return {"thread": {"id": "thread-probe"}}
+ await agent._on_notification(
+ "item/completed",
+ {
+ "threadId": "thread-probe",
+ "turnId": "turn-probe",
+ "item": {"type": "agentMessage", "text": "hello"},
+ },
+ )
+ await agent._on_notification(
+ "turn/completed",
+ {
+ "threadId": "thread-probe",
+ "turn": {"id": "turn-probe", "status": "completed"},
+ },
+ )
+ return {"turn": {"id": "turn-probe"}}
+
+ async def wait_closed(inner_self):
+ await asyncio.Event().wait()
+
+ transport = _Transport()
+ agent = self._agent(cwd, transport)
+ agent._get_or_create_transport = AsyncMock(
+ side_effect=AssertionError("existing transport should be reused")
+ )
+
+ with patch.object(
+ _MODULE.paths,
+ "get_runtime_dir",
+ return_value=Path(runtime_dir.name),
+ ):
+ result = await agent.probe_connection(cwd, model="gpt-5.4-mini")
+
+ self.assertEqual(result, "hello")
+ agent._get_or_create_transport.assert_not_awaited()
+ self.assertEqual(requests[0][0], "thread/start")
+ self.assertEqual(
+ requests[0][1],
+ {
+ "cwd": str(Path(runtime_dir.name) / "codex-connection-probe"),
+ "approvalPolicy": "never",
+ "sandbox": "read-only",
+ "ephemeral": True,
+ "developerInstructions": (
+ "This is a connection probe. Do not use tools. "
+ "Reply with a short greeting."
+ ),
+ },
+ )
+ self.assertEqual(
+ requests[1],
+ (
+ "turn/start",
+ {
+ "threadId": "thread-probe",
+ "input": [{"type": "text", "text": "Hi"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {
+ "type": "readOnly",
+ "networkAccess": False,
+ },
+ "effort": "low",
+ "model": "gpt-5.4-mini",
+ },
+ ),
+ )
+ self.assertEqual(agent._connection_probes, {})
+ self.assertEqual(agent._connection_probe_turns, {})
+
+ async def test_transport_exit_settles_probe_without_outer_timeout(self):
+ cwd = "/tmp/user-project"
+ runtime_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(runtime_dir.cleanup)
+
+ class _Transport:
+ is_initialized = True
+
+ async def send_request(inner_self, method, _params):
+ if method == "thread/start":
+ return {"thread": {"id": "thread-probe"}}
+ return {"turn": {"id": "turn-probe"}}
+
+ async def wait_closed(inner_self):
+ return None
+
+ agent = self._agent(cwd, _Transport())
+
+ with (
+ patch.object(
+ _MODULE.paths,
+ "get_runtime_dir",
+ return_value=Path(runtime_dir.name),
+ ),
+ self.assertRaisesRegex(
+ ConnectionError,
+ "app-server exited during the connection probe",
+ ),
+ ):
+ await agent.probe_connection(cwd)
+
+ self.assertEqual(agent._connection_probes, {})
+ self.assertEqual(agent._connection_probe_turns, {})
+
+
class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
ownership = SimpleNamespace(
diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py
index 9bf6a16bc..8970d8117 100644
--- a/tests/test_codex_transport.py
+++ b/tests/test_codex_transport.py
@@ -78,6 +78,30 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(transport.has_pending_notifications)
+ async def test_wait_closed_waits_for_already_read_notifications(self):
+ transport = CodexTransport(binary="codex", cwd="/tmp")
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def handle(_method, _params):
+ started.set()
+ await release.wait()
+
+ transport._notification_cb = handle
+ transport._notify_task = asyncio.create_task(transport._notify_worker())
+ transport._notify_queue.put_nowait(("turn/completed", {}))
+ await started.wait()
+ transport._closed_event.set()
+ waiter = asyncio.create_task(transport.wait_closed())
+ await asyncio.sleep(0)
+ self.assertFalse(waiter.done())
+
+ release.set()
+ await waiter
+ await asyncio.sleep(0)
+ transport._notify_task.cancel()
+ await transport._notify_task
+
def test_stream_buffer_limit_allows_large_codex_thread_responses(self):
self.assertGreaterEqual(STREAM_BUFFER_LIMIT, 128 * 1024 * 1024)
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 888ff99c8..d9ec495af 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -199,6 +199,46 @@ def test_reconcile_agent_backends_missing_socket_raises_unavailable(tmp_path):
)
+def test_backend_auth_round_trip(tmp_path):
+ app = FastAPI()
+ captured: dict = {}
+
+ @app.post("/internal/backend-auth/test")
+ async def _test(payload: dict):
+ captured["payload"] = payload
+ return {"ok": True, "excerpt": "hello"}
+
+ sock = tmp_path / "dispatch.sock"
+ sock.touch()
+
+ async def _go():
+ fake_transport = httpx.ASGITransport(app=app)
+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):
+ return await internal_client.test_backend_auth(
+ "codex",
+ model="gpt-5.4-mini",
+ socket_path=sock,
+ )
+
+ result = asyncio.run(_go())
+
+ assert captured["payload"] == {"backend": "codex", "model": "gpt-5.4-mini"}
+ assert result == {
+ "status_code": 200,
+ "body": {"ok": True, "excerpt": "hello"},
+ }
+
+
+def test_backend_auth_missing_socket_raises_unavailable(tmp_path):
+ with pytest.raises(internal_client.InternalServerUnavailable):
+ asyncio.run(
+ internal_client.test_backend_auth(
+ "claude",
+ socket_path=tmp_path / "missing.sock",
+ )
+ )
+
+
def test_notify_vault_request_created_round_trip(tmp_path):
app = FastAPI()
captured: dict = {}
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 44db9913e..8bc6fbf67 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -573,6 +573,44 @@ def test_reconcile_agent_backends_endpoint_rejects_invalid_shape():
}
+def test_backend_auth_endpoint_uses_controller_owned_service():
+ controller = _build_controller_double()
+ test_web_auth = AsyncMock(return_value={"ok": True, "excerpt": "hello"})
+ controller.agent_auth_service = SimpleNamespace(test_web_auth=test_web_auth)
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post(
+ "/internal/backend-auth/test",
+ json={"backend": "Codex", "model": "gpt-5.4-mini"},
+ )
+
+ resp = asyncio.run(_go())
+
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True, "excerpt": "hello"}
+ test_web_auth.assert_awaited_once_with("codex", model="gpt-5.4-mini")
+
+
+def test_backend_auth_endpoint_rejects_invalid_shape():
+ app = internal_server.create_app(_build_controller_double())
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post(
+ "/internal/backend-auth/test",
+ json={"backend": "codex", "model": ["gpt-5.4-mini"]},
+ )
+
+ resp = asyncio.run(_go())
+
+ assert resp.status_code == 400
+ assert resp.json() == {"ok": False, "error": "model must be a string"}
+
+
async def _dispatch_round_trip(body: dict) -> httpx.Response:
app = internal_server.create_app(_build_controller_double())
transport = httpx.ASGITransport(app=app)
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 39d2abf65..11872ce6a 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -120,6 +120,32 @@ def test_fastapi_schema_routes_are_not_exposed():
assert client.get("/openapi.json").status_code != 200
+def test_backend_auth_test_routes_through_controller_runtime(monkeypatch):
+ from vibe import internal_client
+
+ calls = []
+
+ async def _test_backend_auth(backend, *, model=None):
+ calls.append((backend, model))
+ return {
+ "status_code": 200,
+ "body": {"ok": True, "excerpt": "hello"},
+ }
+
+ monkeypatch.setattr(internal_client, "test_backend_auth", _test_backend_auth)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/backend/codex/auth/test",
+ json={"model": "gpt-5.4-mini"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"ok": True, "excerpt": "hello"}
+ assert calls == [("codex", "gpt-5.4-mini")]
+
+
def test_thread_settings_routes_use_native_fastapi(monkeypatch):
from vibe import api
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index c97e6d5c5..95202b10d 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -1352,86 +1352,62 @@ def test_claude_probe_timeout_bounds_disconnect_and_reaps_process(
)
-def test_test_web_auth_happy_path_returns_excerpt(
+def test_claude_probe_reaps_process_when_disconnect_raises(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- """Codex probes use app-server thread/turn requests, not ``codex exec``."""
- captured: dict[str, object] = {"requests": []}
+ class _BrokenClaudeClient:
+ async def disconnect(self):
+ raise RuntimeError("disconnect failed")
- class _FakeTransport:
- pid = None
+ reap = AsyncMock(return_value=1)
+ monkeypatch.setattr("core.agent_auth_service.get_claude_client_pid", lambda _client: 4321)
+ monkeypatch.setattr("core.agent_auth_service._reap_pid_set", reap)
- def __init__(self, **kwargs):
- captured["init"] = kwargs
- self.notification = None
+ _run(service._disconnect_claude_probe_client(_BrokenClaudeClient()))
- def on_notification(self, callback):
- self.notification = callback
+ reap.assert_awaited_once_with(
+ {4321},
+ terminate_timeout=2.0,
+ logger=ANY,
+ )
- def on_server_request(self, callback):
- captured["server_request"] = callback
- async def start(self):
- captured["started"] = True
+def test_claude_probe_does_not_reap_process_that_exited_after_disconnect_error(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ process_wait = AsyncMock(return_value=0)
- async def stop(self):
- captured["stopped"] = True
+ class _BrokenClaudeClient:
+ _transport = SimpleNamespace(_process=SimpleNamespace(wait=process_wait))
- 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"}}
+ async def disconnect(self):
+ raise RuntimeError("disconnect failed")
+
+ reap = AsyncMock(return_value=1)
+ 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(_BrokenClaudeClient()))
+
+ process_wait.assert_awaited_once_with()
+ reap.assert_not_awaited()
+
+
+def test_test_web_auth_happy_path_returns_excerpt(
+ service: AgentAuthService,
+) -> None:
+ """AgentAuthService delegates Codex probes to the live Agent runtime."""
+ probe = AsyncMock(return_value="Hello from the model\nmore text")
+ service.controller.agent_service = SimpleNamespace(
+ agents={"codex": SimpleNamespace(probe_connection=probe)}
+ )
- monkeypatch.setattr("modules.agents.codex.transport.CodexTransport", _FakeTransport)
result = _run(service.test_web_auth("codex", model="gpt-5.4-mini"))
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",
- },
- ),
- ]
+ probe.assert_awaited_once_with(os.getcwd(), model="gpt-5.4-mini")
def test_verify_web_login_claude_forces_oauth_env(
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 94219ab52..c4bf703e3 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -263,6 +263,36 @@ async def reconcile_agent_backends(
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def test_backend_auth(
+ backend: str,
+ *,
+ model: str | None = None,
+ socket_path: Optional[Path] = None,
+ timeout: float = 60.0,
+) -> dict[str, Any]:
+ """Run a Settings connection probe on the controller-owned Agent runtime."""
+
+ target = (socket_path or default_socket_path()).expanduser().resolve()
+ if not target.exists():
+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ payload: dict[str, Any] = {"backend": backend}
+ if model:
+ payload["model"] = model
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(timeout, connect=5.0),
+ ) as client:
+ resp = await client.post("/internal/backend-auth/test", json=payload)
+ except _SOCKET_CONNECT_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ except httpx.TimeoutException as exc:
+ raise InternalServerTimeout(str(exc)) from exc
+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+
+
async def notify_vault_request_created(
request_payload: dict[str, Any],
*,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 2a5403bbc..b61830fe0 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5706,12 +5706,16 @@ 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 an isolated turn through the backend's production Agent transport."""
- from vibe import api
+ from vibe import internal_client
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(await api.test_backend_auth_async(backend, model=model))
+ try:
+ result = await internal_client.test_backend_auth(backend, model=model)
+ except (internal_client.InternalServerUnavailable, internal_client.InternalServerTimeout) as exc:
+ return jsonify({"ok": False, "error": "spawn_failed", "detail": str(exc)})
+ return jsonify(result.get("body") or {"ok": False, "error": "test_failed"})
@app.route("/api/backend/opencode/providers", methods=["GET"])