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): isolate direct Codex probe ownership

cyh5f2242ad182e
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 1033d9854..8fd096caa 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -70,6 +70,7 @@ class AppCompatConfig:
log_level: str
ack_mode: str
language: str
+ default_cwd: str
platforms: dict = field(default_factory=lambda: {"enabled": ["slack"], "primary": "slack"})
discord: Optional[DiscordConfig] = None
telegram: Optional[TelegramConfig] = None
@@ -158,6 +159,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
log_level=v2.runtime.log_level,
ack_mode=v2.ack_mode,
language=v2.language,
+ default_cwd=v2.runtime.default_cwd,
show_duration=v2.show_duration,
include_time_info=v2.include_time_info,
include_user_info=v2.include_user_info,
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 2b0a008de..16c6f9166 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -491,6 +491,17 @@ class AgentAuthService:
# flows ignore a non-default cli_path and fall through to
# ``$PATH``, breaking installs that pin a specific binary.
backend_cfg = self._resolve_backend_config(backend)
+ if backend_cfg is None:
+ try:
+ from config.v2_config import V2Config
+
+ backend_cfg = getattr(V2Config.load().agents, backend, None)
+ except Exception: # noqa: BLE001
+ logger.debug(
+ "Failed to load persisted %s config for Settings probe",
+ backend,
+ exc_info=True,
+ )
cli_path = getattr(backend_cfg, "cli_path", None) or getattr(backend_cfg, "binary", None)
return cli_path or backend
@@ -500,6 +511,7 @@ class AgentAuthService:
candidates = (
getattr(self._resolve_backend_config(backend), "cwd", None),
getattr(getattr(config, "runtime", None), "default_cwd", None),
+ getattr(config, "default_cwd", None),
)
for raw in candidates:
if isinstance(raw, str) and raw.strip():
@@ -2249,22 +2261,41 @@ class AgentAuthService:
return {"ok": False, "error": "settings_cleanup_failed", "detail": str(err)}
started = time.monotonic()
+ diagnostics: list[str] = []
+
+ def record_diagnostic(detail: str) -> None:
+ text = str(detail or "").strip()
+ if text:
+ diagnostics.append(text)
+ del diagnostics[:-40]
+
try:
if backend == "claude":
probe = self._run_claude_agent_probe(
binary=binary,
cwd=probe_cwd,
model=model,
+ on_diagnostic=record_diagnostic,
)
else:
- probe = self._run_codex_agent_probe(cwd=probe_cwd, model=model)
+ probe = self._run_codex_agent_probe(
+ binary=binary,
+ cwd=probe_cwd,
+ model=model,
+ on_diagnostic=record_diagnostic,
+ )
response_text = await asyncio.wait_for(probe, timeout=timeout)
except asyncio.TimeoutError:
- return {
+ detail = "\n".join(diagnostics).strip()
+ classified = _classify_test_failure("", detail, auth_mode=auth_mode)
+ result: dict[str, Any] = {
"ok": False,
- "error": "timed_out",
+ "error": classified if classified != "cli_failed" else "timed_out",
"duration_ms": int((time.monotonic() - started) * 1000),
}
+ if detail:
+ result["detail"] = detail[:600]
+ return result
except FileNotFoundError:
return {"ok": False, "error": "cli_not_found", "detail": binary}
except Exception as err: # noqa: BLE001
@@ -2292,6 +2323,7 @@ class AgentAuthService:
binary: str,
cwd: str,
model: str | None,
+ on_diagnostic: Callable[[str], None] | None = None,
) -> str:
"""Run an isolated turn through the same Claude Agent SDK transport."""
from modules.agents.model_hub import claude_setting_sources_for_launch
@@ -2304,6 +2336,8 @@ class AgentAuthService:
if text:
stderr_lines.append(text)
del stderr_lines[:-40]
+ if on_diagnostic is not None:
+ on_diagnostic(text)
claude_env = build_claude_subprocess_env(self._resolve_backend_config("claude"))
claude_env[AVIBE_CLAUDE_PROCESS_OWNER_ENV] = AVIBE_CLAUDE_AUTH_OWNER
@@ -2348,6 +2382,8 @@ class AgentAuthService:
message_error = getattr(message, "error", None)
if message_error:
assistant_error = str(message_error)
+ if on_diagnostic is not None:
+ on_diagnostic(assistant_error)
if hasattr(message, "is_error"):
result_text = str(getattr(message, "result", "") or "").strip()
if bool(getattr(message, "is_error", False)):
@@ -2410,17 +2446,79 @@ class AgentAuthService:
async def _run_codex_agent_probe(
self,
*,
+ binary: str,
cwd: str,
model: str | None,
+ on_diagnostic: Callable[[str], None] | None = None,
) -> str:
- """Run through the controller-owned CodexAgent transport pool."""
+ """Reuse a matching direct runtime, or own a temporary direct runtime."""
+ from config.v2_compat import CodexCompatConfig
+ from config.v2_config import DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
+ from modules.agents.codex import CodexConnectionProbeRuntimeMismatchError
+
+ backend_cfg = self._resolve_backend_config("codex")
+ runtime_config = CodexCompatConfig(
+ enabled=bool(getattr(backend_cfg, "enabled", True)),
+ binary=binary,
+ extra_args=list(getattr(backend_cfg, "extra_args", None) or []),
+ idle_timeout_seconds=int(
+ getattr(
+ backend_cfg,
+ "idle_timeout_seconds",
+ DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS,
+ )
+ ),
+ auth_mode=str(getattr(backend_cfg, "auth_mode", "oauth") or "oauth"),
+ )
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)
+ can_reuse = getattr(agent, "can_reuse_direct_connection_probe", None)
+ live_config = getattr(agent, "codex_config", None)
+ live_matches = live_config is None or (
+ str(getattr(live_config, "binary", "")) == runtime_config.binary
+ and list(getattr(live_config, "extra_args", None) or [])
+ == runtime_config.extra_args
+ and str(getattr(live_config, "auth_mode", "oauth") or "oauth")
+ == runtime_config.auth_mode
+ )
+ direct_runtime = not callable(can_reuse) or bool(can_reuse(cwd))
+ if callable(probe) and live_matches and direct_runtime:
+ try:
+ return await probe(
+ cwd,
+ model=model,
+ on_diagnostic=on_diagnostic,
+ )
+ except CodexConnectionProbeRuntimeMismatchError:
+ pass
+
+ probe_agent = self._create_codex_probe_agent(runtime_config)
+ try:
+ return await probe_agent.probe_connection(
+ cwd,
+ model=model,
+ on_diagnostic=on_diagnostic,
+ )
+ finally:
+ try:
+ await probe_agent.shutdown_runtime()
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "Failed to stop controller-owned Codex probe runtime",
+ exc_info=True,
+ )
+
+ def _create_codex_probe_agent(self, runtime_config: Any) -> Any:
+ """Create an unregistered CodexAgent whose runtime this service owns."""
+ from modules.agents.codex import CodexAgent
+
+ return CodexAgent(
+ self.controller,
+ runtime_config,
+ registered_runtime=False,
+ )
async def test_opencode_provider(
self,
diff --git a/modules/agents/codex/__init__.py b/modules/agents/codex/__init__.py
index 20edd084e..7985e7c1f 100644
--- a/modules/agents/codex/__init__.py
+++ b/modules/agents/codex/__init__.py
@@ -1,5 +1,5 @@
"""Codex agent package — persistent app-server mode."""
-from .agent import CodexAgent
+from .agent import CodexAgent, CodexConnectionProbeRuntimeMismatchError
-__all__ = ["CodexAgent"]
+__all__ = ["CodexAgent", "CodexConnectionProbeRuntimeMismatchError"]
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index a287bf286..6da074a83 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -66,12 +66,26 @@ CODEX_CONNECTION_PROBE_DIR = "codex-connection-probe"
class _CodexConnectionProbeState:
- def __init__(self) -> None:
+ def __init__(self, on_diagnostic: Callable[[str], None] | None = None) -> None:
self.terminal: asyncio.Future[tuple[str, str]] = (
asyncio.get_running_loop().create_future()
)
self.response_text = ""
self.turn_id = ""
+ self.on_diagnostic = on_diagnostic
+
+ def record_diagnostic(self, detail: str) -> None:
+ text = str(detail or "").strip()
+ if not text or self.on_diagnostic is None:
+ return
+ try:
+ self.on_diagnostic(text)
+ except Exception:
+ logger.debug("Codex probe diagnostic callback failed", exc_info=True)
+
+
+class CodexConnectionProbeRuntimeMismatchError(RuntimeError):
+ """The cached transport does not represent direct Codex credentials."""
class CodexResumeUnavailableError(RuntimeError):
@@ -100,9 +114,16 @@ class CodexAgent(BaseAgent):
name = "codex"
- def __init__(self, controller: Any, codex_config: Any) -> None:
+ def __init__(
+ self,
+ controller: Any,
+ codex_config: Any,
+ *,
+ registered_runtime: bool = True,
+ ) -> None:
super().__init__(controller)
self.codex_config = codex_config
+ self._registered_runtime = registered_runtime
# cwd → CodexTransport (one persistent process per working dir)
self._transports: Dict[str, CodexTransport] = {}
@@ -132,6 +153,7 @@ class CodexAgent(BaseAgent):
self._fork_correction_pending_base_sessions: set[str] = set()
self._connection_probes: Dict[str, _CodexConnectionProbeState] = {}
self._connection_probe_turns: Dict[str, str] = {}
+ self._connection_probe_cwds: Dict[str, int] = {}
# ------------------------------------------------------------------
# BaseAgent interface
@@ -179,42 +201,70 @@ 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)
+ def can_reuse_direct_connection_probe(self, cwd: str) -> bool:
+ """Return whether a live transport is suitable for direct-auth testing."""
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
+ return not (
+ transport is not None
+ and getattr(transport, "runtime_fingerprint", "direct") != "direct"
)
- if not thread_id:
- raise RuntimeError("Codex thread/start returned no thread id")
- state = _CodexConnectionProbeState()
- self._connection_probes[thread_id] = state
+ async def probe_connection(
+ self,
+ cwd: str,
+ *,
+ model: str | None = None,
+ on_diagnostic: Callable[[str], None] | 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: CodexTransport | None = None
+ state: _CodexConnectionProbeState | None = None
+ thread_id = ""
closed_task: asyncio.Task[None] | None = None
+ probe_cwds = self._connection_probe_cwds
+ probe_cwds[cwd] = probe_cwds.get(cwd, 0) + 1
try:
+ transport = self._transports.get(cwd)
+ if (
+ transport is not None
+ and getattr(transport, "runtime_fingerprint", "direct") != "direct"
+ ):
+ raise CodexConnectionProbeRuntimeMismatchError(
+ "The cached Codex transport does not use direct credentials"
+ )
+ 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 = str(
+ thread_response.get("id")
+ or (thread.get("id") if isinstance(thread, dict) else "")
+ or ""
+ )
+ if not thread_id:
+ raise RuntimeError("Codex thread/start returned no thread id")
+
+ state = _CodexConnectionProbeState(on_diagnostic)
+ self._connection_probes[thread_id] = state
turn_params: Dict[str, Any] = {
"threadId": thread_id,
"input": [{"type": "text", "text": "Hi"}],
@@ -249,14 +299,42 @@ class CodexAgent(BaseAgent):
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)
+ try:
+ if (
+ transport is not None
+ and state is not None
+ and state.turn_id
+ and not state.terminal.done()
+ and transport.is_initialized
+ ):
+ try:
+ await asyncio.wait_for(
+ transport.send_request(
+ "turn/interrupt",
+ {"threadId": thread_id, "turnId": state.turn_id},
+ ),
+ timeout=2.0,
+ )
+ except Exception:
+ logger.warning(
+ "Failed to interrupt cancelled Codex connection probe",
+ exc_info=True,
+ )
+ finally:
+ if thread_id:
+ self._connection_probes.pop(thread_id, None)
+ if state is not None and state.turn_id:
+ self._connection_probe_turns.pop(state.turn_id, None)
+ if state is not None and not state.terminal.done():
+ state.terminal.cancel()
+ if closed_task is not None:
+ closed_task.cancel()
+ await asyncio.gather(closed_task, return_exceptions=True)
+ remaining = probe_cwds.get(cwd, 0) - 1
+ if remaining > 0:
+ probe_cwds[cwd] = remaining
+ else:
+ probe_cwds.pop(cwd, None)
async def _record_model_hub_native_failure(self, context: Any, diagnostic: str) -> bool:
router = getattr(self.controller, "model_hub_runtime", None)
@@ -895,6 +973,8 @@ class CodexAgent(BaseAgent):
cwd: str,
transport: CodexTransport,
) -> RuntimeActivationIdentity | None:
+ if not getattr(self, "_registered_runtime", True):
+ return None
registry = getattr(getattr(self, "controller", None), "runtime_activation", None)
if registry is None:
return None
@@ -912,6 +992,8 @@ class CodexAgent(BaseAgent):
) -> tuple[Any, Any] | None:
if self._transports.get(cwd) is not transport:
return None
+ if not getattr(self, "_registered_runtime", True):
+ return (None, None)
registry = getattr(getattr(self, "controller", None), "runtime_activation", None)
if registry is None:
return (None, None)
@@ -1214,6 +1296,8 @@ class CodexAgent(BaseAgent):
return evicted
def _retire_model_hub_process_scope(self, cwd: str) -> None:
+ if not getattr(self, "_registered_runtime", True):
+ return
controller = getattr(self, "controller", None)
router = getattr(controller, "model_hub_runtime", None)
retire = getattr(router, "retire_process_scope", None)
@@ -2422,14 +2506,15 @@ class CodexAgent(BaseAgent):
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")
)
+ state.record_diagnostic(str(detail or "Codex error"))
+ if params.get("willRetry") is True:
+ return True
if not state.terminal.done():
state.terminal.set_result(("error", str(detail or "Codex error")))
return True
@@ -2449,6 +2534,7 @@ class CodexAgent(BaseAgent):
if isinstance(error, dict)
else str(error or "Codex turn failed")
)
+ state.record_diagnostic(str(detail or "Codex turn failed"))
outcome = ("error", str(detail or "Codex turn failed"))
else:
outcome = ("error", f"Codex turn ended with status: {status or 'unknown'}")
@@ -2581,6 +2667,8 @@ class CodexAgent(BaseAgent):
}
def _has_active_turns_for_cwd(self, cwd: str) -> bool:
+ if cwd in getattr(self, "_connection_probe_cwds", set()):
+ return True
for base_session_id in self._session_mgr.sessions_for_cwd(cwd):
if self._turn_registry.get_active_turn(base_session_id):
return True
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index dbe987076..38b5d6b9a 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -255,6 +255,11 @@ class CodexTransport:
try:
return await asyncio.wait_for(fut, timeout=120.0)
+ except asyncio.CancelledError:
+ self._pending.pop(req_id, None)
+ if not fut.done():
+ fut.cancel()
+ raise
except asyncio.TimeoutError:
self._pending.pop(req_id, None)
self._initialized = False
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 8a8c12003..025ca732f 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -399,6 +399,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
agent._transport_last_activity = {}
agent._connection_probes = {}
agent._connection_probe_turns = {}
+ agent._connection_probe_cwds = {}
controller.agent_service = SimpleNamespace(agents={"codex": agent})
service = AgentAuthService(controller)
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 89bfd0d46..f7737f625 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -141,6 +141,9 @@ assert _SPEC is not None and _SPEC.loader is not None
_MODULE = importlib.util.module_from_spec(_SPEC)
_SPEC.loader.exec_module(_MODULE)
CodexAgent = _MODULE.CodexAgent
+CodexConnectionProbeRuntimeMismatchError = (
+ _MODULE.CodexConnectionProbeRuntimeMismatchError
+)
CodexResumeUnavailableError = _MODULE.CodexResumeUnavailableError
for name, module in _saved_modules.items():
@@ -271,6 +274,7 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
agent._transport_last_activity = {}
agent._connection_probes = {}
agent._connection_probe_turns = {}
+ agent._connection_probe_cwds = {}
return agent
async def test_reuses_existing_transport_with_isolated_ephemeral_thread(self):
@@ -308,6 +312,7 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
transport = _Transport()
agent = self._agent(cwd, transport)
+ diagnostics = []
agent._get_or_create_transport = AsyncMock(
side_effect=AssertionError("existing transport should be reused")
)
@@ -317,7 +322,11 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
"get_runtime_dir",
return_value=Path(runtime_dir.name),
):
- result = await agent.probe_connection(cwd, model="gpt-5.4-mini")
+ result = await agent.probe_connection(
+ cwd,
+ model="gpt-5.4-mini",
+ on_diagnostic=diagnostics.append,
+ )
self.assertEqual(result, "hello")
agent._get_or_create_transport.assert_not_awaited()
@@ -354,6 +363,8 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(agent._connection_probes, {})
self.assertEqual(agent._connection_probe_turns, {})
+ self.assertEqual(agent._connection_probe_cwds, {})
+ self.assertEqual(diagnostics, [])
async def test_transport_exit_settles_probe_without_outer_timeout(self):
cwd = "/tmp/user-project"
@@ -388,6 +399,144 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._connection_probes, {})
self.assertEqual(agent._connection_probe_turns, {})
+ self.assertEqual(agent._connection_probe_cwds, {})
+
+ async def test_cancellation_interrupts_started_probe_and_clears_ownership(self):
+ cwd = "/tmp/user-project"
+ runtime_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(runtime_dir.cleanup)
+ turn_started = asyncio.Event()
+ requests = []
+
+ 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"}}
+ if method == "turn/start":
+ turn_started.set()
+ return {"turn": {"id": "turn-probe"}}
+ if method == "turn/interrupt":
+ return {}
+ raise AssertionError(method)
+
+ async def wait_closed(inner_self):
+ await asyncio.Event().wait()
+
+ agent = self._agent(cwd, _Transport())
+ with patch.object(
+ _MODULE.paths,
+ "get_runtime_dir",
+ return_value=Path(runtime_dir.name),
+ ):
+ task = asyncio.create_task(agent.probe_connection(cwd))
+ await turn_started.wait()
+ await asyncio.sleep(0)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+
+ self.assertIn(
+ (
+ "turn/interrupt",
+ {"threadId": "thread-probe", "turnId": "turn-probe"},
+ ),
+ requests,
+ )
+ self.assertEqual(agent._connection_probes, {})
+ self.assertEqual(agent._connection_probe_turns, {})
+ self.assertEqual(agent._connection_probe_cwds, {})
+
+ async def test_retriable_errors_are_preserved_as_diagnostics(self):
+ cwd = "/tmp/user-project"
+ runtime_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(runtime_dir.cleanup)
+ diagnostics = []
+
+ class _Transport:
+ is_initialized = True
+
+ async def send_request(inner_self, method, _params):
+ if method == "thread/start":
+ return {"thread": {"id": "thread-probe"}}
+ await agent._on_notification(
+ "error",
+ {
+ "threadId": "thread-probe",
+ "turnId": "turn-probe",
+ "willRetry": True,
+ "error": {"message": "401 Unauthorized"},
+ },
+ )
+ 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()
+
+ agent = self._agent(cwd, _Transport())
+ with patch.object(
+ _MODULE.paths,
+ "get_runtime_dir",
+ return_value=Path(runtime_dir.name),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "returned no response"):
+ await agent.probe_connection(
+ cwd,
+ on_diagnostic=diagnostics.append,
+ )
+
+ self.assertEqual(diagnostics, ["401 Unauthorized"])
+
+ async def test_rejects_initialized_model_hub_transport(self):
+ cwd = "/tmp/user-project"
+ transport = SimpleNamespace(
+ is_initialized=True,
+ runtime_fingerprint="hub:openai/gpt-5.4-mini",
+ )
+ agent = self._agent(cwd, transport)
+
+ with self.assertRaises(CodexConnectionProbeRuntimeMismatchError):
+ await agent.probe_connection(cwd)
+
+ self.assertEqual(agent._connection_probe_cwds, {})
+
+ async def test_unregistered_probe_runtime_preserves_live_activation(self):
+ cwd = "/tmp/user-project"
+ activation = RuntimeActivationRegistry()
+ live_identity = activation.attach("codex", cwd)
+ retire_scope = Mock()
+ transport = SimpleNamespace(stop=AsyncMock())
+ agent = object.__new__(CodexAgent)
+ agent._registered_runtime = False
+ agent._transports = {cwd: transport}
+ agent._transport_last_activity = {cwd: 1.0}
+ agent._transport_locks = {cwd: asyncio.Lock()}
+ agent._transport_cwd_inodes = {cwd: 1}
+ agent._session_last_activity = {}
+ agent._session_locks = {}
+ agent._session_mgr = SimpleNamespace(all_base_sessions=lambda: [])
+ agent._turn_registry = SimpleNamespace()
+ agent.sessions = SimpleNamespace()
+ agent.controller = SimpleNamespace(
+ runtime_activation=activation,
+ model_hub_runtime=SimpleNamespace(retire_process_scope=retire_scope),
+ )
+
+ self.assertIsNone(agent._attach_transport_activation(cwd, transport))
+ await agent.shutdown_runtime()
+
+ transport.stop.assert_awaited_once_with()
+ self.assertIs(activation.current("codex", cwd), live_identity)
+ retire_scope.assert_not_called()
class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py
index 8970d8117..e09d19373 100644
--- a/tests/test_codex_transport.py
+++ b/tests/test_codex_transport.py
@@ -54,6 +54,30 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):
with self.assertRaises(ConnectionError):
await transport.send_notification("initialized")
+ async def test_cancelled_request_does_not_leave_pending_rpc(self):
+ request_written = asyncio.Event()
+
+ class _Stdin:
+ def is_closing(self):
+ return False
+
+ def write(self, _payload):
+ return None
+
+ async def drain(self):
+ request_written.set()
+
+ transport = CodexTransport(binary="codex", cwd="/tmp")
+ transport._process = SimpleNamespace(returncode=None, stdin=_Stdin())
+
+ task = asyncio.create_task(transport.send_request("turn/interrupt", {}))
+ await request_written.wait()
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+
+ self.assertEqual(transport._pending, {})
+
async def test_pending_notification_keeps_terminal_pipeline_alive(self):
transport = CodexTransport(binary="codex", cwd="/tmp")
started = asyncio.Event()
diff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.py
index 7ad2b2823..d0c1eb870 100644
--- a/tests/test_v2_compat_platforms.py
+++ b/tests/test_v2_compat_platforms.py
@@ -50,6 +50,7 @@ def test_to_app_config_preserves_enabled_platforms():
assert compat.platform == "discord"
assert compat.platforms == {"enabled": ["slack", "discord"], "primary": "discord"}
assert compat.enabled_platforms() == ["slack", "discord"]
+ assert compat.default_cwd == config.runtime.default_cwd
def test_to_app_config_preserves_telegram_config():
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 95202b10d..b200c472c 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -1407,7 +1407,92 @@ def test_test_web_auth_happy_path_returns_excerpt(
assert result["ok"] is True
assert result["excerpt"] == "Hello from the model"
assert isinstance(result["duration_ms"], int)
- probe.assert_awaited_once_with(os.getcwd(), model="gpt-5.4-mini")
+ probe.assert_awaited_once_with(
+ os.getcwd(),
+ model="gpt-5.4-mini",
+ on_diagnostic=ANY,
+ )
+
+
+def test_test_web_auth_codex_uses_owned_runtime_when_backend_is_disabled(
+ service: AgentAuthService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ probe = AsyncMock(return_value="Hello from temporary Codex")
+ shutdown = AsyncMock()
+ temp_agent = SimpleNamespace(
+ probe_connection=probe,
+ shutdown_runtime=shutdown,
+ )
+ captured = []
+ service.controller.agent_service = SimpleNamespace(agents={})
+ monkeypatch.setattr(service, "_get_cli_binary", lambda _backend: "codex-custom")
+ monkeypatch.setattr(
+ service,
+ "_create_codex_probe_agent",
+ lambda runtime_config: captured.append(runtime_config) or temp_agent,
+ )
+
+ result = _run(service.test_web_auth("codex"))
+
+ assert result["ok"] is True
+ assert captured[0].binary == "codex-custom"
+ probe.assert_awaited_once_with(
+ os.getcwd(),
+ model=None,
+ on_diagnostic=ANY,
+ )
+ shutdown.assert_awaited_once_with()
+
+
+def test_disabled_backend_probe_uses_persisted_codex_binary(
+ service: AgentAuthService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from config.v2_config import V2Config
+
+ persisted = SimpleNamespace(
+ agents=SimpleNamespace(codex=SimpleNamespace(cli_path="/opt/codex/bin/codex"))
+ )
+ monkeypatch.setattr(service, "_resolve_backend_config", lambda _backend: None)
+ monkeypatch.setattr(V2Config, "load", classmethod(lambda _cls: persisted))
+
+ assert service._get_cli_binary("codex") == "/opt/codex/bin/codex"
+
+
+def test_test_web_auth_codex_does_not_probe_model_hub_transport(
+ service: AgentAuthService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ live_probe = AsyncMock(
+ side_effect=AssertionError("Model Hub transport must not test direct credentials")
+ )
+ live_agent = SimpleNamespace(
+ probe_connection=live_probe,
+ can_reuse_direct_connection_probe=lambda _cwd: False,
+ )
+ temp_probe = AsyncMock(return_value="Hello from direct Codex")
+ temp_agent = SimpleNamespace(
+ probe_connection=temp_probe,
+ shutdown_runtime=AsyncMock(),
+ )
+ service.controller.agent_service = SimpleNamespace(agents={"codex": live_agent})
+ monkeypatch.setattr(
+ service,
+ "_create_codex_probe_agent",
+ lambda _runtime_config: temp_agent,
+ )
+
+ result = _run(service.test_web_auth("codex"))
+
+ assert result["ok"] is True
+ live_probe.assert_not_awaited()
+ temp_probe.assert_awaited_once_with(
+ os.getcwd(),
+ model=None,
+ on_diagnostic=ANY,
+ )
+ temp_agent.shutdown_runtime.assert_awaited_once_with()
def test_verify_web_login_claude_forces_oauth_env(
@@ -1557,6 +1642,7 @@ def test_test_web_auth_claude_runs_in_runtime_cwd(
binary="/usr/bin/echo",
cwd=str(runtime_cwd),
model=None,
+ on_diagnostic=ANY,
)
assert runtime_cwd.is_dir()
@@ -1598,6 +1684,25 @@ def test_test_web_auth_failure_surfaces_stderr(
assert "Authentication failed" in (result.get("detail") or "")
+def test_test_web_auth_timeout_preserves_retry_diagnostic(
+ service: AgentAuthService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def retrying_probe(*, on_diagnostic, **_kwargs):
+ on_diagnostic("401 Unauthorized while retrying")
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(service, "_run_claude_agent_probe", retrying_probe)
+ monkeypatch.setattr(_Backend, "auth_mode", "api_key", raising=False)
+ monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)
+
+ result = _run(service.test_web_auth("claude", timeout=0.01))
+
+ assert result["ok"] is False
+ assert result["error"] == "invalid_credentials"
+ assert result["detail"] == "401 Unauthorized while retrying"
+
+
def test_test_web_auth_not_logged_in_has_specific_error_code(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None: