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.

refactor(runtime): one runtime lifecycle; configuration never interrupts or holds work (#2329)

Call Whitec54d57244ad0
diff --git a/AGENTS.md b/AGENTS.md
index 706bd7e7e..d853f6eff 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -174,10 +174,14 @@ Source-of-truth rule:
- when changing persistent product behavior, align with V2 config and current Web UI flows rather than legacy assumptions
- a successful `agents.*` runtime config save must also reconcile any live
- controller through the backend rolling-refresh path; persisted config and
- built-in Agent rows alone do not update the in-memory backend registry, and
- callers must not issue a second restart after the config API accepts that
- reconciliation
+ controller through `BackendRestartCoordinator.request_restart`; persisted
+ config and built-in Agent rows alone do not update the in-memory backend
+ registry, and callers must not issue a second restart after the config API
+ accepts that reconciliation
+- configuration changes never interrupt running work or hold new turns: each
+ runtime unit moves at its next turn. Two explicit user actions interrupt:
+ disabling a backend stops its work at once, and a native credential cutover
+ retires its runtime; see `docs/plans/runtime-generations.md`
## 5. Development Workflow
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 679f18024..a0a1a1ae9 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -51,7 +51,6 @@ class CodexCompatConfig:
class OpenCodeCompatConfig:
enabled: bool
binary: str
- port: int
request_timeout_seconds: int
default_reasoning_effort: Optional[str] = None
error_retry_limit: int = DEFAULT_OPENCODE_ERROR_RETRY_LIMIT # Max retries on LLM stream errors (0 = no retry)
@@ -178,7 +177,6 @@ def to_app_config(
"opencode",
resolve_agent_paths=resolve_agent_paths,
),
- port=4096,
request_timeout_seconds=60,
default_reasoning_effort=v2.agents.opencode.default_reasoning_effort,
error_retry_limit=v2.agents.opencode.error_retry_limit,
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 221e9aa78..5a96db257 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -16,7 +16,7 @@ import uuid
from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
-from typing import Any, Callable, Coroutine, Optional
+from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional
from core.backend_failure import terminal_backend_failure_output
from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError, finish_native_operation
@@ -51,6 +51,9 @@ from modules.im import InlineButton, InlineKeyboard, MessageContext
from vibe.i18n import t as i18n_t
from vibe.opencode_config import remove_opencode_provider_api_key
+if TYPE_CHECKING:
+ from modules.agents.opencode.client_manager import OpenCodeServerLease
+
logger = logging.getLogger(__name__)
ANSI_ESCAPE_RE = re.compile(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\))")
@@ -437,6 +440,8 @@ class WebAuthFlow:
source_account_label: str | None = None
native_cli: bool = False
native_lease: NativeCredentialLease | None = field(default=None, repr=False)
+ # The controller-owned OpenCode generation one OpenCode login runs on.
+ opencode_lease: OpenCodeServerLease | None = field(default=None, repr=False)
cancel_requested: bool = field(default=False, repr=False)
submission_task: asyncio.Task[Any] | None = field(default=None, repr=False)
native_closing: bool = field(default=False, repr=False)
@@ -482,6 +487,9 @@ class AgentAuthService:
# reload V2Config-backed credentials. The hook receives ``(backend,)``
# and runs in a worker thread to avoid blocking the auth event loop.
self._post_web_success_hook: Optional[Any] = None
+ # Bumped each time a backend's enabled config is applied; see
+ # ``_stop_disabled_backend``.
+ self._enablements: dict[str, int] = {}
@property
def _flows(self) -> dict[str, AgentAuthFlow]:
@@ -793,10 +801,10 @@ class AgentAuthService:
agent_service = getattr(self.controller, "agent_service", None)
opencode_agent = getattr(agent_service, "agents", {}).get("opencode") if agent_service else None
- if opencode_agent and hasattr(opencode_agent, "_get_server"):
+ if opencode_agent and hasattr(opencode_agent, "current_server"):
try:
- server = await opencode_agent._get_server()
- runtime_provider = await self._resolve_opencode_provider_from_existing_session(context, server)
+ async with opencode_agent.current_server() as server:
+ runtime_provider = await self._resolve_opencode_provider_from_existing_session(context, server)
if runtime_provider:
return runtime_provider
except Exception as err: # noqa: BLE001
@@ -2112,14 +2120,11 @@ class AgentAuthService:
async def _install_opencode_api_key(self, provider: str, api_key: str) -> None:
agent_service = getattr(self.controller, "agent_service", None)
opencode_agent = getattr(agent_service, "agents", {}).get("opencode") if agent_service else None
- if not opencode_agent or not hasattr(opencode_agent, "_get_server"):
+ if not opencode_agent or not hasattr(opencode_agent, "current_server"):
raise RuntimeError("OpenCode agent is not available for auth setup.")
- server = await opencode_agent._get_server()
- setter = getattr(server, "set_api_key_auth", None)
- if not callable(setter):
- raise RuntimeError("OpenCode server does not support non-interactive auth setup.")
- await setter(provider, api_key)
+ async with opencode_agent.current_server() as server:
+ await server.set_api_key_auth(provider, api_key)
try:
await _native_auth_thread(
remove_opencode_provider_api_key,
@@ -2146,18 +2151,6 @@ class AgentAuthService:
except Exception as err: # noqa: BLE001
logger.warning("Failed to clear OpenCode provider option apiKey after OAuth for %s: %s", provider, err)
- async def _refresh_opencode_server(self, *, force: bool = False) -> None:
- agent_service = getattr(self.controller, "agent_service", None)
- opencode_agent = getattr(agent_service, "agents", {}).get("opencode") if agent_service else None
- if not opencode_agent or not hasattr(opencode_agent, "_get_server"):
- return
- server = await opencode_agent._get_server()
- if hasattr(server, "restart_for_auth_refresh"):
- if force:
- await server.restart_for_auth_refresh(force=True)
- else:
- await server.restart_for_auth_refresh()
-
def _load_backend_runtime_config(self, backend: str):
from config.v2_compat import to_app_config
from config.v2_config import V2Config
@@ -2258,34 +2251,131 @@ class AgentAuthService:
except Exception as err: # noqa: BLE001
logger.warning("Failed to sync built-in Agents after backend runtime refresh: %s", err)
- async def _unregister_disabled_backend_agent(self, backend: str) -> bool:
+ @staticmethod
+ def _disable_teardown_key(backend: str, agent: Any) -> str:
+ return f"disabled:{backend}:{id(agent)}"
+
+ async def _stop_disabled_backend(self, backend: str, *, unregister: bool) -> bool:
+ """Disabling a backend is an explicit user action: stop its work now.
+
+ A Codex or OpenCode agent first leaves the registry, so no new message
+ reaches it. Its running turns and Activities then settle with the
+ backend-disabled notice, and every process of the backend stops.
+ Claude stays registered while disabled, and its clients are closed.
+ """
+ from core.backend_restart import finish_native_operation
+
agent_service = getattr(self.controller, "agent_service", None)
- agent = getattr(agent_service, "agents", {}).pop(backend, None) if agent_service else None
- if agent is None:
- setattr(self.controller.config, backend, None)
+ agents = getattr(agent_service, "agents", {})
+ agent = agents.pop(backend, None) if unregister else agents.get(backend)
+
+ async def interrupt_work() -> None:
+ coordinator = getattr(self.controller, "backend_restart_coordinator", None)
+ interrupt = getattr(coordinator, "interrupt_backend", None)
+ if callable(interrupt):
+ from core.run_settlement import SETTLED_BY_BACKEND_DISABLED
+
+ await interrupt(backend, reason=SETTLED_BY_BACKEND_DISABLED)
+
+ async def stop_processes() -> None:
+ if agent is None:
+ return
+ shutdown = getattr(agent, "shutdown_runtime", None)
+ if callable(shutdown):
+ from core.run_settlement import SETTLED_BY_BACKEND_DISABLED
+
+ # The adapter settles the work bound to its own processes as it
+ # stops them, scoped to this agent instance, so a retry after a
+ # re-enable still settles the disabled agent's work and nothing else.
+ await shutdown(settle_reason=SETTLED_BY_BACKEND_DISABLED)
+
+ # Claude stays registered while disabled, so its stop closes exactly
+ # the clients live now, busy ones included. A retry after Claude is
+ # enabled again never touches the new backend's clients.
+ session_handler = getattr(self.controller, "session_handler", None)
+ capture = getattr(session_handler, "capture_claude_clients", None)
+ captured_clients = capture() if callable(capture) and not unregister else ()
+
+ async def close_claude_clients() -> None:
+ close = getattr(session_handler, "close_captured_claude_clients", None)
+ if callable(close):
+ from core.run_settlement import SETTLED_BY_BACKEND_DISABLED
+
+ await close(captured_clients, reason=SETTLED_BY_BACKEND_DISABLED)
+
+ # The interrupt settles only the work that ran before this disable. A
+ # retry after the backend is enabled again must not touch new work, so
+ # it is skipped once a later enable bumped the backend's enablement.
+ enablement = self._enablements.get(backend, 0)
+ interrupted = False
+
+ async def teardown() -> None:
+ nonlocal interrupted
+ interrupt_error = None
+ if not interrupted and self._enablements.get(backend, 0) == enablement:
+ try:
+ await interrupt_work()
+ interrupted = True
+ except Exception as exc: # retried with the stop below
+ interrupt_error = exc
+ # Stopping the processes still ends that work; never skip it.
+ if unregister:
+ await stop_processes()
+ else:
+ await close_claude_clients()
+ if interrupt_error is not None:
+ raise interrupt_error
+
+ async def disable() -> None:
+ run_until_done = getattr(agent_service, "run_until_done", None)
+ if callable(run_until_done):
+ # The agent is out of routing, or Claude is disabled, so this
+ # owner retries a failed settlement or stop at each idle sweep,
+ # holding the lock this backend's config changes hold.
+ coordinator = getattr(self.controller, "backend_restart_coordinator", None)
+ backend_lock = getattr(coordinator, "backend_lock", None)
+ await run_until_done(
+ self._disable_teardown_key(backend, agent),
+ teardown,
+ retry_lock=backend_lock(backend) if callable(backend_lock) else None,
+ )
+ else:
+ await teardown()
+ if unregister:
+ setattr(self.controller.config, backend, None)
self._sync_builtin_default_agents()
- return False
- shutdown = getattr(agent, "shutdown_runtime", None)
- if callable(shutdown):
- await shutdown()
- elif backend == "opencode":
- server_manager = getattr(agent, "_client_manager", None)
- reset_config = getattr(server_manager, "reset_config", None)
- if callable(reset_config):
- previous_server = await reset_config(None)
- if previous_server is not None:
- detach = getattr(previous_server, "detach_after_deferred_refresh", None)
- if callable(detach):
- await detach()
- refresh = getattr(agent, "refresh_auth_state", None)
- if callable(refresh):
- await refresh()
-
- setattr(self.controller.config, backend, None)
- self._sync_builtin_default_agents()
- logger.info("Unregistered disabled %s backend after runtime config refresh", backend)
- return True
+ # The whole disable runs to completion, its process stop handed to the
+ # teardown owner, before a cancelled requester sees its cancellation.
+ await finish_native_operation(disable())
+ if agent is not None:
+ logger.info("Stopped disabled %s backend", backend)
+ return agent is not None
+
+ async def _restore_polls_after_enable(self) -> None:
+ """Deliver OpenCode work a crashed controller left while OpenCode was off.
+
+ A controller that started with OpenCode disabled kept those durable polls
+ but missed their restore; enabling OpenCode in it restores them now.
+ Every transport-ready event already ran and no later reconciliation
+ restores polls for an agent that exists, so a failed restore is kept
+ and retried at each idle sweep until it succeeds.
+ """
+ restore = getattr(self.controller, "restore_polls_on_ready_transports", None)
+ if not callable(restore):
+ return
+ agent_service = getattr(self.controller, "agent_service", None)
+ run_until_done = getattr(agent_service, "run_until_done", None)
+ if not callable(run_until_done):
+ await restore()
+ return
+ coordinator = getattr(self.controller, "backend_restart_coordinator", None)
+ backend_lock = getattr(coordinator, "backend_lock", None)
+ await run_until_done(
+ "Restoring OpenCode polls after enabling it",
+ restore,
+ retry_lock=backend_lock("opencode") if callable(backend_lock) else None,
+ )
def _register_missing_backend_agent(self, backend: str, runtime_config: Any) -> bool:
agent_service = getattr(self.controller, "agent_service", None)
@@ -2310,14 +2400,50 @@ class AgentAuthService:
logger.info("Registered %s backend after runtime config refresh", backend)
return True
+ async def renew_backend_runtime(self, backend: str, config_save: bool = False) -> None:
+ """Apply persisted runtime config.
+
+ An enabled backend renews in place without waiting for or interrupting
+ work, so each runtime unit moves at its next turn, and a newly enabled
+ backend registers at once. Disabling is the one exception: the user
+ turned the backend off, so its work stops now.
+ """
+ runtime_config = self._load_backend_runtime_config(backend)
+ if runtime_config is None:
+ await self._stop_disabled_backend(backend, unregister=True)
+ return
+ if getattr(runtime_config, "enabled", True) is not False:
+ # A disable's pending retry must not interrupt work admitted from now on.
+ self._enablements[backend] = self._enablements.get(backend, 0) + 1
+ if getattr(runtime_config, "enabled", True) is not False and self._register_missing_backend_agent(
+ backend, runtime_config
+ ):
+ if backend == "opencode":
+ await self._restore_polls_after_enable()
+ return
+ agent_service = getattr(self.controller, "agent_service", None)
+ agent = getattr(agent_service, "agents", {}).get(backend) if agent_service else None
+ # Claude stays registered while disabled; disabling it stops its work.
+ newly_disabled = getattr(runtime_config, "enabled", True) is False and (
+ getattr(getattr(self.controller.config, backend, None), "enabled", True) is not False
+ )
+ renew = getattr(agent, "renew_runtime", None)
+ if callable(renew):
+ await renew(runtime_config, config_save=config_save)
+ if newly_disabled:
+ await self._stop_disabled_backend(backend, unregister=False)
+ return
+ self._sync_builtin_default_agents()
+
async def _refresh_backend_runtime(self, backend: str) -> None:
coordinator = getattr(self.controller, "backend_restart_coordinator", None)
if coordinator is not None:
await coordinator.request_restart(backend)
return
- await self._apply_backend_runtime_refresh(backend, False)
+ await self.renew_backend_runtime(backend)
async def _apply_backend_runtime_refresh(self, backend: str, force: bool = False) -> None:
+ """Reload a backend's runtime for a native credential cutover, after its work was interrupted."""
agent_service = getattr(self.controller, "agent_service", None)
runtime_tokens: dict[str, str] = {}
snapshot_tokens = getattr(agent_service, "runtime_turn_tokens_for_backend", None)
@@ -2329,7 +2455,7 @@ class AgentAuthService:
if callable(refresh_runtime_config):
runtime_config = self._load_backend_runtime_config(backend)
if runtime_config is None:
- await self._unregister_disabled_backend_agent(backend)
+ await self._stop_disabled_backend(backend, unregister=True)
return
if runtime_config is not None and self._register_missing_backend_agent(
backend,
@@ -2356,12 +2482,6 @@ class AgentAuthService:
return
await refresh_config(runtime_config)
return
- if backend == "opencode":
- if force:
- await self._refresh_opencode_server(force=True)
- else:
- await self._refresh_opencode_server()
- return
refresh = getattr(agent, "refresh_auth_state", None)
if callable(refresh):
await refresh()
@@ -3224,10 +3344,34 @@ class AgentAuthService:
if not provider_id:
return {"ok": False, "error": "missing_provider"}
- server = await self._opencode_server()
- if server is None:
+ from modules.agents.opencode.server import DIRECTORY_BOOTSTRAP_TIMEOUT
+
+ # The lease keeps the probe's generation alive until the probe ends:
+ # through a cold directory's bootstrap, then the probe's own window.
+ opencode_lease = await self._lease_opencode_server(
+ "provider probe",
+ ttl_seconds=DIRECTORY_BOOTSTRAP_TIMEOUT + timeout + 60.0,
+ )
+ if opencode_lease is None:
return {"ok": False, "error": "opencode_server_unavailable"}
+ try:
+ return await self._probe_opencode_provider(
+ opencode_lease.server,
+ provider_id,
+ model=model,
+ timeout=timeout,
+ )
+ finally:
+ await opencode_lease.release()
+ async def _probe_opencode_provider(
+ self,
+ server: Any,
+ provider_id: str,
+ *,
+ model: str | None,
+ timeout: float,
+ ) -> dict[str, Any]:
directory = os.path.expanduser("~")
# On a fresh install the first request for a directory waits while
# OpenCode bootstraps it, which can outlast the catalog request's
@@ -3274,7 +3418,6 @@ class AgentAuthService:
# flow uses.
started = time.monotonic()
session_id: str | None = None
- active_registered = False
try:
try:
created = await server.create_session(directory, title="vibe-test-probe")
@@ -3329,8 +3472,6 @@ class AgentAuthService:
reasoning_effort=reasoning_effort,
tools={"question": False},
)
- await server.mark_run_active(session_id)
- active_registered = True
except Exception as err: # noqa: BLE001
detail = str(err)
return {
@@ -3505,8 +3646,6 @@ class AgentAuthService:
await server.abort_session(session_id, directory)
except Exception: # noqa: BLE001
pass
- if active_registered and session_id:
- await server.mark_run_inactive(session_id)
async def cancel_web_flow(self, flow_id: str) -> dict[str, Any]:
async with self._flow_lock:
@@ -3521,49 +3660,36 @@ class AgentAuthService:
self._flow_registry.drop(flow)
return {"ok": True}
- async def _opencode_server(self):
- """Lazy lookup of the live OpenCode server client.
+ async def _lease_opencode_server(
+ self,
+ purpose: str,
+ *,
+ ttl_seconds: float,
+ ) -> OpenCodeServerLease | None:
+ """Pin a controller-owned OpenCode generation; this process never launches one.
- Mirrors ``vibe.api._opencode_get_server`` rather than the IM
- controller's ``agent_service.agents['opencode']`` (the web auth
- service runs in the UI process — there is no controller-level
- agent_service). Returns ``None`` when OpenCode is disabled in
- V2Config so the caller can surface a typed error.
+ Returns ``None`` when OpenCode is disabled or no generation can serve,
+ so the caller can surface a typed error.
"""
+ from modules.agents.opencode.client_manager import lease_opencode_server
+
try:
- from config.v2_compat import to_app_config
- from config.v2_config import V2Config
- from core.resource_governance import AgentResourceGovernor, config_from_runtime
- from modules.agents.opencode import (
- OpenCodeModelHubOverlayRequiredError,
- OpenCodeServerManager,
- )
- except ImportError:
- return None
- try:
- v2_config = V2Config.load()
- compat = to_app_config(v2_config)
- except Exception as err: # noqa: BLE001
- logger.warning("V2Config.load failed in web OAuth path: %s", err)
- return None
- opencode_cfg = getattr(compat, "opencode", None)
- if opencode_cfg is None:
- return None
- try:
- server = await OpenCodeServerManager.get_instance(
- binary=opencode_cfg.binary,
- port=opencode_cfg.port,
- request_timeout_seconds=opencode_cfg.request_timeout_seconds,
- resource_governor=AgentResourceGovernor(config_from_runtime(v2_config)),
+ return await lease_opencode_server(
+ purpose,
+ ttl_seconds=ttl_seconds,
+ controller=self.controller,
)
- await server.ensure_running()
- return server
- except OpenCodeModelHubOverlayRequiredError:
- return None
except Exception as err: # noqa: BLE001
- logger.warning("OpenCodeServerManager.get_instance failed for web OAuth: %s", err)
+ logger.warning("No OpenCode generation for %s: %s", purpose, err)
return None
+ @staticmethod
+ async def _release_opencode_flow_lease(flow: WebAuthFlow) -> None:
+ lease = flow.opencode_lease
+ flow.opencode_lease = None
+ if lease is not None:
+ await lease.release()
+
async def _resolve_opencode_oauth_method(
self, server, provider_id: str
) -> tuple[int, dict[str, Any]]:
@@ -3600,39 +3726,52 @@ class AgentAuthService:
_OPENCODE_DEVICE_CODE_RE = re.compile(r"Enter code:\s*([A-Za-z0-9-]+)")
async def _start_opencode_oauth_web(self, flow: WebAuthFlow, provider_id: str) -> None:
- server = await self._opencode_server()
- if server is None:
- raise RuntimeError("opencode_server_unavailable")
- method_index, prompt_answers = await self._resolve_opencode_oauth_method(
- server, provider_id
- )
- flow.last_status_text = None
- authorize = await server.start_provider_oauth(
- provider_id,
- method=method_index,
- prompt_answers=prompt_answers,
- )
- url = authorize.get("url") if isinstance(authorize, dict) else None
- instructions = authorize.get("instructions") if isinstance(authorize, dict) else None
- if not isinstance(url, str) or not url.strip():
- raise RuntimeError("opencode_authorize_missing_url")
- flow.url = url.strip()
- if isinstance(instructions, str):
- match = self._OPENCODE_DEVICE_CODE_RE.search(instructions)
- if match:
- flow.device_code = match.group(1)
- flow.last_status_text = instructions
- mode = authorize.get("method")
- if mode not in {None, "auto", "code"}:
- raise RuntimeError("opencode_authorize_unsupported_method")
- flow.callback_kind = "code" if mode == "code" else "device" if flow.device_code else "redirect"
- flow.state = "awaiting_code"
- flow.awaiting_code = mode == "code"
- if flow.awaiting_code:
- flow.submitted_code = asyncio.get_running_loop().create_future()
- self._arm_flow_waiter(
- flow, self._wait_for_opencode_oauth_web(flow, provider_id, method_index, prompt_answers),
+ # Authorize, the pasted callback, and the wait must reach one process:
+ # the pending login lives in that server's memory. One lease pins that
+ # generation for the flow's whole budget.
+ lease = await self._lease_opencode_server(
+ "web OAuth",
+ ttl_seconds=self._remaining_flow_timeout(flow) + 60.0,
)
+ if lease is None:
+ raise RuntimeError("opencode_server_unavailable")
+ flow.opencode_lease = lease
+ server = lease.server
+ try:
+ method_index, prompt_answers = await self._resolve_opencode_oauth_method(
+ server, provider_id
+ )
+ flow.last_status_text = None
+ authorize = await server.start_provider_oauth(
+ provider_id,
+ method=method_index,
+ prompt_answers=prompt_answers,
+ )
+ url = authorize.get("url") if isinstance(authorize, dict) else None
+ instructions = authorize.get("instructions") if isinstance(authorize, dict) else None
+ if not isinstance(url, str) or not url.strip():
+ raise RuntimeError("opencode_authorize_missing_url")
+ flow.url = url.strip()
+ if isinstance(instructions, str):
+ match = self._OPENCODE_DEVICE_CODE_RE.search(instructions)
+ if match:
+ flow.device_code = match.group(1)
+ flow.last_status_text = instructions
+ mode = authorize.get("method")
+ if mode not in {None, "auto", "code"}:
+ raise RuntimeError("opencode_authorize_unsupported_method")
+ flow.callback_kind = "code" if mode == "code" else "device" if flow.device_code else "redirect"
+ flow.state = "awaiting_code"
+ flow.awaiting_code = mode == "code"
+ if flow.awaiting_code:
+ flow.submitted_code = asyncio.get_running_loop().create_future()
+ self._arm_flow_waiter(
+ flow, self._wait_for_opencode_oauth_web(flow, provider_id, method_index, prompt_answers),
+ )
+ except BaseException:
+ # Until the waiter is armed, nothing else releases this lease.
+ await self._release_opencode_flow_lease(flow)
+ raise
async def _submit_opencode_callback_url(self, flow: WebAuthFlow, code: str) -> dict[str, Any]:
"""Forward a manually-pasted 127.0.0.1 callback URL to OpenCode.
@@ -3664,11 +3803,11 @@ class AgentAuthService:
provider_id = flow.provider
if not provider_id:
return {"ok": False, "error": "flow_missing_provider"}
- server = await self._opencode_server()
- if server is None:
+ lease = flow.opencode_lease
+ if lease is None:
return {"ok": False, "error": "opencode_server_unavailable"}
try:
- await server.forward_oauth_redirect(provider_id, callback_url)
+ await lease.server.forward_oauth_redirect(provider_id, callback_url)
except Exception as err: # noqa: BLE001
logger.error(
"Failed to forward OpenCode OAuth callback for %s: %s",
@@ -3694,10 +3833,10 @@ class AgentAuthService:
# the provider until an explicit code reaches this waiter.
code = await flow.submitted_code
flow.submitted_code = None
- server = await self._opencode_server()
- if server is None:
+ lease = flow.opencode_lease
+ if lease is None:
raise RuntimeError("opencode_server_unavailable")
- await server.wait_provider_oauth(
+ await lease.server.wait_provider_oauth(
provider_id,
method=method_index,
prompt_answers=prompt_answers,
@@ -3729,6 +3868,8 @@ class AgentAuthService:
)
flow.state = "failed"
flow.error = str(err)
+ finally:
+ await self._release_opencode_flow_lease(flow)
async def _read_codex_output_web(self, flow: WebAuthFlow) -> None:
"""Parse ``codex login --device-auth`` stdout for URL + device code.
@@ -4510,6 +4651,7 @@ class AgentAuthService:
if flow.submitted_code is not None:
flow.submitted_code.cancel()
flow.submitted_code = None
+ await self._release_opencode_flow_lease(flow)
flow.awaiting_code = False
# Cleanup can race with a completed waiter. Preserve its terminal
# outcome instead of relabelling success/failure as a later cancel.
diff --git a/core/backend_restart.py b/core/backend_restart.py
index 9a333dac0..68b67ffaa 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -1,4 +1,4 @@
-"""Shared backend restart barrier and bounded drain coordinator."""
+"""Backend runtime application, maintenance windows, and native credential cutovers."""
from __future__ import annotations
@@ -16,7 +16,6 @@ from typing import Any, TypeVar
logger = logging.getLogger(__name__)
-DEFAULT_DRAIN_TIMEOUT_SECONDS = 300.0
_POLL_INTERVAL_SECONDS = 0.1
# After an interruption only teardown remains: native processes exiting and
# requests to a stopped runtime failing. By then the user's work is already
@@ -376,33 +375,28 @@ def native_cli_processes(binaries: Mapping[str, str]) -> tuple[int, ...]:
raise NativeMigrationBlockedError("process_inventory_unavailable", backends) from None
-def _configured_drain_timeout() -> float:
- raw = os.environ.get("AVIBE_BACKEND_RESTART_DRAIN_TIMEOUT_SECONDS", "")
- try:
- return max(0.0, float(raw)) if raw.strip() else DEFAULT_DRAIN_TIMEOUT_SECONDS
- except ValueError:
- logger.warning("Ignoring invalid AVIBE_BACKEND_RESTART_DRAIN_TIMEOUT_SECONDS=%r", raw)
- return DEFAULT_DRAIN_TIMEOUT_SECONDS
-
-
class BackendRestartCoordinator:
- """Serialize backend cutovers without stopping Avibe's service process."""
+ """Serialize backend cutovers without stopping Avibe's service process.
+
+ ``renew(backend, config_save)`` applies persisted runtime config without
+ waiting for or interrupting work. ``refresh(backend, forced)`` tears a
+ runtime down, and only a native credential cutover uses it.
+ """
def __init__(
self,
controller: Any,
refresh: Callable[[str, bool], Awaitable[None]],
*,
- drain_timeout: float | None = None,
+ renew: Callable[[str, bool], Awaitable[Any]],
settle_timeout: float = _INTERRUPT_SETTLE_SECONDS,
poll_interval: float = _POLL_INTERVAL_SECONDS,
process_inventory: Callable[[Mapping[str, str]], tuple[int, ...]] = native_cli_processes,
) -> None:
self.controller = controller
self._refresh = refresh
- self._drain_timeout = _configured_drain_timeout() if drain_timeout is None else max(0.0, drain_timeout)
- # Independent of the drain timeout, which only decides when a restart
- # stops waiting and interrupts; an interrupting switch never drains.
+ self._renew = renew
+ # How long a cutover waits for the teardown of the work it interrupted.
self._settle_timeout = max(0.0, settle_timeout)
self._poll_interval = max(0.001, poll_interval)
self._tasks: dict[str, asyncio.Task[Any]] = {}
@@ -560,7 +554,7 @@ class BackendRestartCoordinator:
# or cancellation, never cuts the teardown short.
for backend in targets:
if await self._has_active_turns(backend):
- restarts[backend] = self._start_restart(backend, drain_timeout=0)
+ restarts[backend] = self._start_restart(backend)
loop = asyncio.get_running_loop()
deadline = loop.time() + self._settle_timeout
for backend in targets:
@@ -632,49 +626,41 @@ class BackendRestartCoordinator:
else:
lease.release()
- async def request_restart(self, backend: str) -> str:
- """Begin or join a restart and return without waiting for a long drain."""
+ def backend_lock(self, backend: str) -> asyncio.Lock:
+ """The lock every application of ``backend``'s config holds."""
+ return self._request_locks.setdefault(backend, asyncio.Lock())
+
+ async def request_restart(self, backend: str, *, config_save: bool = False) -> str:
+ """Apply a backend's persisted runtime config; nothing waits or is interrupted.
+
+ Running work finishes on the runtime it started on and new turns start
+ on the renewed one. A disabled backend's agent retires: it admits no new
+ message, and its running work still finishes. ``config_save`` marks a
+ request that only applies a saved runtime config, so a backend may skip
+ renewal when no launch input changed. Credential flows, manual
+ restarts, and installs renew always.
+ """
self.assert_native_auth_available(backend)
lock = self._request_locks.setdefault(backend, asyncio.Lock())
async with lock:
self.assert_native_auth_available(backend)
- existing = self._tasks.get(backend)
- if existing is not None:
- if not existing.done():
- return "draining"
- self._on_done(backend, existing)
-
- agent_service = self.controller.agent_service
- session_turns = self.controller.session_turns
- agent_service.begin_backend_drain(backend)
- session_turns.begin_backend_drain(backend)
try:
- await agent_service.prepare_backend_restart(backend)
- had_active_work = await self._has_active_turns(backend)
+ await self._renew(backend, config_save)
except BaseException as exc:
self._outcomes[backend] = {"state": "failed", "error": str(exc) or type(exc).__name__}
- if backend not in self._blocked_backends():
- agent_service.end_backend_drain(backend)
- await session_turns.end_backend_drain(backend, resume_deferred=False)
raise
- task = self._start_restart(backend)
-
- # Idle refreshes remain synchronous so setup/config errors reach the
- # runtime-command requester. Only genuinely active work makes the
- # restart an acknowledged background drain.
- if not had_active_work:
- await task
- return "restarted"
- return "draining"
+ self._outcomes[backend] = {"state": "applied"}
+ return "restarted"
async def run_when_idle(self, backend: str, operation: Callable[[], Awaitable[_T]]) -> _T | None:
"""Run ``operation`` while ``backend`` admits no turn, then refresh it.
- Unattended maintenance can simply try again later, so unlike a restart
- this never waits out or cancels work: it returns ``None`` without running
- ``operation`` when a turn, cutover, migration, or native login already
- holds the backend. Messages that arrive meanwhile are deferred to the
- refreshed runtime, which also applies a restart requested during it.
+ Unattended maintenance can simply try again later, so this never waits
+ out or cancels work: it returns ``None`` without running ``operation``
+ when a turn, cutover, migration, or native login already holds the
+ backend. Admission stays closed only while ``operation`` replaces the
+ CLI, so no turn launches a half-installed binary. Messages that arrive
+ meanwhile are deferred to the renewed runtime.
"""
lock = self._request_locks.setdefault(backend, asyncio.Lock())
async with lock:
@@ -733,7 +719,7 @@ class BackendRestartCoordinator:
return await operation()
finally:
# Even a failed operation may have replaced the CLI.
- await self._refresh(backend, False)
+ await self._renew(backend, False)
refreshed = True
finally:
try:
@@ -797,15 +783,25 @@ class BackendRestartCoordinator:
return {"state": "unavailable"}
return {"state": "applied"}
- async def _interrupt(self, backend: str) -> None:
- """Settle every turn running on ``backend`` ahead of a forced refresh."""
+ async def interrupt_backend(self, backend: str, *, reason: str | None = None) -> None:
+ """Settle every turn and Activity running on ``backend`` ahead of a
+ forced stop or refresh.
+
+ ``reason`` is the settlement and picks the notice: a runtime refresh by
+ default, or ``SETTLED_BY_BACKEND_DISABLED`` when the user turned the
+ backend off.
+ """
+ from core.run_settlement import SETTLED_BY_BACKEND_REFRESH
+
+ settled_by = reason or SETTLED_BY_BACKEND_REFRESH
session_ids = self.controller.session_turns.active_runtime_session_ids_for_backend(backend)
await self.controller.session_turns.release_for_backend_refresh(
backend=backend,
base_session_ids=session_ids,
+ settled_by=settled_by,
)
await self.controller.agent_service.force_cancel_backend_turns(backend)
- self.controller.agent_service.force_end_backend_activities(backend)
+ self.controller.agent_service.force_end_backend_activities(backend, reason=settled_by)
async def _has_active_turns(self, backend: str) -> bool:
service = self.controller.agent_service
@@ -866,24 +862,20 @@ class BackendRestartCoordinator:
self._handoffs.add(task)
task.add_done_callback(self._handoffs.discard)
- def _start_restart(self, backend: str, *, drain_timeout: float | None = None) -> asyncio.Task[None]:
- task = asyncio.create_task(self._run(backend, drain_timeout), name=f"backend-restart:{backend}")
+ def _start_restart(self, backend: str) -> asyncio.Task[None]:
+ task = asyncio.create_task(self._run(backend), name=f"backend-restart:{backend}")
self._tasks[backend] = task
task.add_done_callback(lambda completed, name=backend: self._on_done(name, completed))
return task
- async def _run(self, backend: str, drain_timeout: float | None = None) -> None:
+ async def _run(self, backend: str) -> None:
+ """Interrupt a cutover backend's work, then tear its runtime down."""
forced = False
refreshed = False
- loop = asyncio.get_running_loop()
- deadline = loop.time() + (self._drain_timeout if drain_timeout is None else drain_timeout)
try:
- while await self._has_active_turns(backend):
- if loop.time() >= deadline:
- forced = True
- await self._interrupt(backend)
- break
- await asyncio.sleep(self._poll_interval)
+ if await self._has_active_turns(backend):
+ forced = True
+ await self.interrupt_backend(backend)
await self._refresh(backend, forced)
refreshed = True
finally:
diff --git a/core/controller.py b/core/controller.py
index aeb7b3317..d7463fbf6 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -196,6 +196,9 @@ def _refresh_status_bubble_config(controller: Any) -> None:
refresh()
+# Idle eviction and the runtime generation sweep run on this cadence.
+_IDLE_SWEEP_INTERVAL_SECONDS = 60
+
class Controller:
"""Main controller that coordinates all bot operations"""
@@ -286,6 +289,7 @@ class Controller:
self.backend_restart_coordinator = BackendRestartCoordinator(
self,
self.agent_auth_service._apply_backend_runtime_refresh,
+ renew=self.agent_auth_service.renew_backend_runtime,
)
if self.model_hub_service is not None:
self.model_hub_service.migration_guard = self.backend_restart_coordinator.migration_guard
@@ -501,7 +505,7 @@ class Controller:
states: dict[str, str] = {}
for backend in requested:
- states[backend] = await self.backend_restart_coordinator.request_restart(backend)
+ states[backend] = await self.backend_restart_coordinator.request_restart(backend, config_save=True)
logger.info("Hot-reconciled Agent backends: %s", states)
return {
@@ -994,18 +998,37 @@ class Controller:
logger.debug("IM runtime could not signal the event loop to stop", exc_info=True)
async def _restore_active_polls(self, platforms: set[str]) -> None:
+ try:
+ await self._restore_active_polls_or_raise(platforms)
+ except Exception as e:
+ logger.error(f"Failed to restore active polls: {e}", exc_info=True)
+
+ async def _restore_active_polls_or_raise(self, platforms: set[str]) -> None:
coordinator = getattr(self, "backend_restart_coordinator", None)
if coordinator is not None and "opencode" in coordinator._blocked_backends():
coordinator.restore_migration_blocks()
return
opencode_agent = self.agent_service.agents.get("opencode")
if opencode_agent and hasattr(opencode_agent, "restore_active_polls"):
- try:
- restored = await opencode_agent.restore_active_polls(platforms) # type: ignore[attr-defined]
- if restored > 0:
- logger.info(f"Restored {restored} active OpenCode poll(s)")
- except Exception as e:
- logger.error(f"Failed to restore active polls: {e}", exc_info=True)
+ restored = await opencode_agent.restore_active_polls(platforms) # type: ignore[attr-defined]
+ if restored > 0:
+ logger.info(f"Restored {restored} active OpenCode poll(s)")
+
+ async def restore_polls_on_ready_transports(self) -> None:
+ """Restore durable OpenCode polls on every transport that can deliver now.
+
+ IM-ready events restore polls at startup. OpenCode enabled in a running
+ controller missed them, so this runs once it registers. Raises when the
+ restore fails, so its caller can retry it; a restore skips every poll
+ already running, so a retry is safe.
+ """
+ platforms = {"avibe"}
+ for platform in list(getattr(self, "im_clients", {}) or {}):
+ if self.is_im_transport_ready(platform):
+ platforms.add(platform)
+ if self.primary_platform in platforms:
+ platforms.add("")
+ await self._restore_active_polls_or_raise(platforms)
async def _on_im_ready(self, *, platform: str) -> None:
"""Restore transport-owned state only after that transport can deliver."""
@@ -1106,6 +1129,23 @@ class Controller:
except Exception as e:
logger.error("Failed to start runtime command watcher: %s", e, exc_info=True)
+ try:
+ if "opencode" not in getattr(agent_service, "agents", {}):
+ # OpenCode is disabled, so no agent will adopt the servers a
+ # crashed controller recorded; disabling stops its work. The
+ # idle sweep retries a server that survived its stop.
+ from modules.agents.opencode.server import StopOutcome, stop_recorded_servers_sync
+ from vibe.desktop_runtime import desktop_caller_provenance
+
+ async def stop_leftover_servers() -> None:
+ outcomes = await asyncio.to_thread(stop_recorded_servers_sync, desktop_caller_provenance())
+ if any(outcome is StopOutcome.FAILED for outcome in outcomes):
+ raise RuntimeError("an OpenCode server a previous controller left did not stop")
+
+ await agent_service.run_until_done("disabled-startup:opencode", stop_leftover_servers)
+ except Exception as e:
+ logger.error("Failed to stop OpenCode servers a previous controller left: %s", e, exc_info=True)
+
try:
self._start_model_hub_snapshot_reconcile_loop()
except Exception as e:
@@ -1116,10 +1156,7 @@ class Controller:
)
try:
- claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()
- if (claude_timeout > 0 or codex_timeout > 0) and (
- self.cleanup_task is None or self.cleanup_task.done()
- ):
+ if self.cleanup_task is None or self.cleanup_task.done():
self.cleanup_task = asyncio.create_task(self.periodic_cleanup())
except Exception as e:
logger.error("Failed to start idle session cleanup: %s", e, exc_info=True)
@@ -2180,30 +2217,40 @@ class Controller:
self._trace_retention_future = None
async def periodic_cleanup(self):
- """Sweep idle backend runtime state without interrupting active work."""
- claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()
- enabled_timeouts = [timeout for timeout in (claude_timeout, codex_timeout) if timeout > 0]
- if not enabled_timeouts:
- logger.info("Idle cleanup disabled for Claude and Codex.")
- return
-
- sweep_interval = max(min(enabled_timeouts) // 6, 60)
- logger.info(
- "Starting idle cleanup loop (interval=%ss, claude_timeout=%ss, codex_timeout=%ss)",
- sweep_interval,
- claude_timeout,
- codex_timeout,
- )
+ """Sweep idle backend runtime state without interrupting active work.
+ Timeouts are read on every sweep, and the sweep interval does not depend
+ on them, so a saved change applies within one interval without a
+ backend restart.
+ """
try:
while True:
- await asyncio.sleep(sweep_interval)
+ await asyncio.sleep(_IDLE_SWEEP_INTERVAL_SECONDS)
+ claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()
+
+ try:
+ # A disabled backend's processes whose stop failed.
+ await self.agent_service.retry_pending()
+ except Exception as e:
+ logger.error("Teardown retry sweep failed: %s", e, exc_info=True)
+
+ # Retiring runtime generations stop once drained, whatever the
+ # idle timeouts say.
+ for agent in list(getattr(self.agent_service, "agents", {}).values()):
+ reap = getattr(agent, "reap_runtime_generations", None)
+ if callable(reap):
+ try:
+ await reap()
+ except Exception as e:
+ logger.error("Runtime generation sweep failed for %s: %s", agent.name, e, exc_info=True)
+ try:
+ # A client from before the latest renewal is reclaimed once
+ # idle, even with idle eviction off.
+ await self.session_handler.evict_idle_sessions(claude_timeout)
+ except Exception as e:
+ logger.error("Claude idle cleanup failed: %s", e, exc_info=True)
if claude_timeout > 0:
- try:
- await self.session_handler.evict_idle_sessions(claude_timeout)
- except Exception as e:
- logger.error("Claude idle cleanup failed: %s", e, exc_info=True)
try:
# Defense-in-depth: reconcile live claude subprocesses
# against tracked sessions and reap orphans (no-owner /
@@ -2335,6 +2382,13 @@ class Controller:
_stop_loop_coroutine(codex_agent.shutdown_runtime(), "Codex runtime")
except Exception as e:
logger.debug(f"Codex runtime cleanup skipped: {e}")
+ try:
+ # A disabled backend whose stop failed has no other owner: its
+ # agent is out of routing and the idle sweep that retries it is
+ # already cancelled, so shutdown makes the last attempt.
+ _stop_loop_coroutine(self.agent_service.retry_pending(), "Pending backend teardowns")
+ except Exception as e:
+ logger.debug(f"Pending backend teardowns skipped: {e}")
# Cancel receiver tasks without awaiting (they may belong to other loops)
try:
@@ -2383,14 +2437,15 @@ class Controller:
self._im_thread.join(timeout=5)
self._im_thread = None
- # An explicit Avibe stop/restart must not leave an adopted OpenCode
- # generation behind. Active turns have already reached shutdown cleanup.
+ # An explicit Avibe stop/restart must not leave any OpenCode generation
+ # of this controller behind; another desktop Runtime's are not ours.
+ # Active turns have already reached shutdown cleanup.
try:
- from modules.agents.opencode import OpenCodeServerManager
+ from modules.agents.opencode.server import stop_owned_generations_sync
- OpenCodeServerManager.terminate_instance_sync()
+ stop_owned_generations_sync()
except Exception as e:
- logger.debug(f"OpenCode server cleanup skipped: {e}")
+ logger.warning("OpenCode server cleanup failed: %s", e)
logger.info("Controller cleanup (sync) complete")
@@ -2651,20 +2706,12 @@ class Controller:
except FileNotFoundError:
return
self.config.model_hub = latest.model_hub
- if latest.model_hub.agents[backend].mode != "hub":
- if backend == "codex":
- agent_service = getattr(self, "agent_service", None)
- if agent_service is None:
- raise RuntimeError("Agent service is unavailable")
- await agent_service.invalidate_model_hub_runtime(backend)
- return
- runtime_config = getattr(latest.agents, backend, None)
- if runtime_config is None:
- return
- coordinator = getattr(self, "backend_restart_coordinator", None)
- if coordinator is None:
- raise RuntimeError("Backend restart coordinator is unavailable")
- await coordinator.request_restart(backend)
+ # Each runtime moves to the committed catalog at its next turn;
+ # nothing restarts or drains. A disabled backend has nothing to adopt.
+ agent = getattr(getattr(self, "agent_service", None), "agents", {}).get(backend)
+ adopt_catalog = getattr(agent, "adopt_model_hub_catalog", None)
+ if callable(adopt_catalog):
+ await adopt_catalog()
async def repair_model_selections(addresses: frozenset[str]) -> int:
# A Vibe Agent's model, a channel's routing override, and a
diff --git a/core/failure_notices.py b/core/failure_notices.py
index d71fbfa00..18dbc2b47 100644
--- a/core/failure_notices.py
+++ b/core/failure_notices.py
@@ -52,6 +52,7 @@ from core.run_settlement import (
INTERRUPT_REASON_RESTARTED,
RUN_INTERRUPTION_REASONS,
SETTLED_BY_BACKEND_REFRESH,
+ SETTLED_BY_BACKEND_DISABLED,
SETTLED_BY_INTERRUPTED,
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLED_BY_REFUSED_CONCURRENT_TURN,
@@ -239,6 +240,7 @@ DEFERRAL_RECHECK_SECONDS = 30.0
NOTICE_REASON_I18N_KEYS: dict[str, str] = {
SETTLED_BY_STOPPED: "harness.notice.reason.stopped",
SETTLED_BY_BACKEND_REFRESH: "harness.notice.reason.backendRefresh",
+ SETTLED_BY_BACKEND_DISABLED: "harness.notice.reason.backendDisabled",
SETTLED_BY_INTERRUPTED: "harness.notice.reason.interrupted",
INTERRUPT_REASON_EVICTED: "harness.notice.reason.evicted",
INTERRUPT_REASON_RESTARTED: "harness.notice.reason.restarted",
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index b7cd59b7e..eb2b1a059 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -547,10 +547,11 @@ class MessageHandler(BaseHandler):
if agent_name == "opencode":
try:
opencode_agent = self.controller.agent_service.agents.get("opencode")
- if opencode_agent and hasattr(opencode_agent, "_get_server"):
- server = await opencode_agent._get_server()
- await server.ensure_running()
- opencode_agents = await server.get_available_agents(self.controller.get_cwd(context))
+ if opencode_agent and hasattr(opencode_agent, "current_server"):
+ async with opencode_agent.current_server() as server:
+ opencode_agents = await server.get_available_agents(
+ self.controller.get_cwd(context)
+ )
name_map = {
normalize_subagent_name(a.get("name", "")): a
for a in opencode_agents
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index c9b800742..a7c736624 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -16,6 +16,7 @@ from config.v2_config import ModelHubConfig
from core.os_errors import format_os_errno
from core.run_settlement import (
+ SETTLED_BY_BACKEND_DISABLED,
SETTLED_BY_BACKEND_REFRESH,
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLED_BY_STOPPED,
@@ -46,6 +47,10 @@ SupplyState = Literal["waiting", "interrupted"]
ScopeKey = tuple[BackendName, str]
logger = logging.getLogger(__name__)
+# The user ended the turn: a Stop, or turning its backend off. Its outcome is
+# canceled, never a provider stream failure.
+_USER_CANCELLATIONS = frozenset({SETTLED_BY_STOPPED, SETTLED_BY_BACKEND_DISABLED})
+
@dataclass(frozen=True)
class AttemptIdentity:
@@ -2122,7 +2127,7 @@ class TurnCorrelationRegistry:
trace.admission_closed = True
had_recovery = bool(trace.recovery_requests)
trace.recovery_requests.clear()
- if settled_by == SETTLED_BY_STOPPED:
+ if settled_by in _USER_CANCELLATIONS:
# Preserve the exact facts present at Stop. Teardown may expose
# a later producer success, but cannot change who ended the turn.
trace.outcome_frozen = True
@@ -2162,7 +2167,7 @@ class TurnCorrelationRegistry:
or trace.terminal_error is not None
or trace.served is not None
)
- if settled_by == SETTLED_BY_STOPPED and not terminal_history_committed:
+ if settled_by in _USER_CANCELLATIONS and not terminal_history_committed:
outcome = "canceled"
canceled_attempt = (
trace.pending_attempt.payload()
@@ -2171,7 +2176,7 @@ class TurnCorrelationRegistry:
)
served = None
terminal_error = None
- elif settled_by == SETTLED_BY_STOPPED:
+ elif settled_by in _USER_CANCELLATIONS:
logger.info(
"Ignored stopped settlement after terminal Model Hub history was committed",
extra={"turn_id": normalized_turn_id},
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 16ef286e9..a337905e8 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -5073,49 +5073,40 @@ class ModelHubService:
async def set_agent_mode(self, backend: str, mode: object) -> dict:
if mode not in {"hub", "direct"}:
raise ModelHubError("mode_switch_blocked")
- from core.backend_restart import NativeMigrationBlockedError
- # Either direction serializes with takeover and retires the managed
- # runtime under the shared guard, which interrupts running work: a
- # turn left running would keep using the mode it started in, and the
- # Hub refuses a backend that has left it. Mode-only consent never
+ # A mode is a launch input like any other: running work finishes in the
+ # mode it started in, and each runtime moves at its next turn, so the
+ # switch interrupts nothing. The gateway keeps serving a Hub turn that
+ # was admitted before a switch to Direct. Mode-only consent never
# imports a login: native auth stays native beside the Hub, where the
# migration dialog can still take it over later.
+ name = cast(BackendName, backend)
async with self._migration_lock:
async with self._mutation_lock:
- current = self.store.load()
- agent = self._agent(current, backend)
+ previous = self.store.load()
+ agent = self._agent(previous, backend)
if agent.mode == mode:
- return self._agent_payload(current, agent)
- if mode == "hub":
- # Refuse a switch that would be refused anyway before the
- # guard destroys any work.
+ # A committed switch is applied only once the runtime has
+ # adopted it; a retry of the same mode finishes that.
+ if name not in self._pending_builtin_catalog_refresh:
+ return self._agent_payload(previous, agent)
+ committed = previous
+ else:
try:
- blocked = await self._native_config_blocks_launch(current, backend)
- except (TakeoverStateError, OSError):
- raise ModelHubError("mode_switch_blocked", status=409) from None
- if blocked:
- raise ModelHubError("mode_switch_blocked", status=409)
- try:
- async with self.migration_guard((backend,), external_processes=False) as verify_idle:
- async with self._mutation_lock:
- # Recheck idleness after the last asynchronous drain.
- await verify_idle()
- previous = self.store.load()
if mode == "hub" and await self._native_config_blocks_launch(previous, backend):
raise ModelHubError("mode_switch_blocked", status=409)
config = self._clone_config(previous)
self._agent(config, backend).mode = mode
if mode == "hub":
- self._carry_agent_selections(config, cast(BackendName, backend))
+ self._carry_agent_selections(config, name)
await self._commit_synced(previous, config)
- committed = self.store.load()
- return self._agent_payload(committed, self._agent(committed, backend))
- except NativeMigrationBlockedError as error:
- _log_native_refusal("Model Hub mode switch", error)
- raise ModelHubError("mode_switch_blocked", status=409) from None
- except (TakeoverStateError, OSError):
- raise ModelHubError("mode_switch_blocked", status=409) from None
+ except (TakeoverStateError, OSError):
+ raise ModelHubError("mode_switch_blocked", status=409) from None
+ committed = self.store.load()
+ self._pending_builtin_catalog_refresh.add(name)
+ await self._refresh_backend_catalog(name)
+ self._pending_builtin_catalog_refresh.discard(name)
+ return self._agent_payload(committed, self._agent(committed, backend))
async def reorder_agent_chains(
self,
@@ -7789,7 +7780,11 @@ class ModelHubService:
supply_channel: Literal["hub"] | None = None,
) -> ModelHubTurnResolution:
if config.agents[backend].mode != "hub":
- raise ModelHubError("mode_switch_blocked", status=409)
+ # Only Hub turns reach the gateway. One admitted before a switch to
+ # Direct keeps resolving its routes until it ends; new turns launch
+ # Direct, so they never get here.
+ config = self._clone_config(config)
+ config.agents[backend].mode = "hub"
resolution = resolve_model_hub_turn(
config,
backend,
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 3210873ba..948623461 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -5,6 +5,8 @@ import logging
import os
import re
import time
+from dataclasses import dataclass
+from types import SimpleNamespace
from typing import TYPE_CHECKING, Optional, Dict, Any, Tuple
from uuid import uuid4
from modules.im import MessageContext
@@ -29,6 +31,8 @@ from modules.agents.claude_process_reaper import (
register_claude_owned_process,
reap_duplicate_claude_resume_processes,
reap_orphaned_claude_processes,
+ get_claude_client_process,
+ stop_claude_process,
)
from config.v2_config import (
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS,
@@ -91,6 +95,11 @@ CLAUDE_REMOTE_PERMISSION_MODE = "bypassPermissions"
CLAUDE_REMOTE_SANDBOX = {"enabled": False}
+# How long a cancelled turn waits for its client's connect to unwind before
+# stopping the CLI process directly.
+CLAUDE_ABANDONED_CONNECT_TIMEOUT_SECONDS = 10.0
+
+
class ClaudeSessionNotFoundError(RuntimeError):
"""Claude Code could not resume a persisted session in the current cwd."""
@@ -103,6 +112,10 @@ class ClaudeSessionNotFoundError(RuntimeError):
)
+class ClaudeBackendDisabledError(RuntimeError):
+ """Claude was turned off before this turn's client could serve it."""
+
+
class ClaudeInputNotSentError(RuntimeError):
"""A local admission failure with definitive evidence of no native write."""
@@ -120,6 +133,19 @@ class _ClaudeReceiverCleanupRequired(RuntimeError):
super().__init__(f"Claude receiver cleanup is still pending for {composite_key}")
+@dataclass(frozen=True)
+class _ClaudeLaunchInputs:
+ """One Claude turn's whole configuration, read in one step at admission.
+
+ Its Model Hub resolution, client reuse check, and any new client all derive
+ from it, so a save or renewal landing mid-admission cannot split them.
+ """
+
+ epoch: int
+ config: Any
+ hub_config: Any
+
+
class SessionHandler(BaseHandler):
"""Handles all session-related operations"""
@@ -467,6 +493,180 @@ class SessionHandler(BaseHandler):
)
return True
+ def renew_runtime(self) -> None:
+ """Move every session to a new client at its next turn, interrupting nothing."""
+ self.controller.claude_runtime_epoch = getattr(self.controller, "claude_runtime_epoch", 0) + 1
+
+ def _idle_eviction_after(self, client: Any, idle_timeout: float) -> float | None:
+ """Seconds a client may stay idle before eviction; None keeps it."""
+ if getattr(client, "_vibe_runtime_epoch", 0) != getattr(self.controller, "claude_runtime_epoch", 0):
+ return 0.0
+ return idle_timeout if idle_timeout > 0 else None
+
+ async def _replace_stale_cached_claude_client(
+ self,
+ composite_key: str,
+ client: ClaudeSDKClient,
+ *,
+ context: MessageContext,
+ working_path: str,
+ effective_effort: Optional[str],
+ system_prompt: Any,
+ model_hub_launch: "ModelHubLaunch",
+ launch_inputs: "_ClaudeLaunchInputs | None" = None,
+ ) -> bool:
+ """Retire a cached client whose launch inputs changed; True once it is gone.
+
+ An idle session moves to a new client at once. While the session's own
+ background work still runs, the turn stays on the current client, and the
+ session moves at its next idle turn. The exceptions are a turn that needs
+ a Model Hub launch this client cannot carry and a turn from a different
+ caller: then the client is replaced and that work interrupted.
+ """
+ launch_changed = getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint
+ # The caller's identity carries its resource authority, so a different
+ # caller can never run in a process that holds the previous one's.
+ caller_changed = getattr(client, "_vibe_caller_env", {}) != self._caller_env_for_context(context)
+ changes = (
+ ("model_hub_channel_changed", launch_changed),
+ ("caller_env_changed", caller_changed),
+ ("reasoning_effort_changed", getattr(client, "_vibe_reasoning_effort", None) != effective_effort),
+ (
+ "runtime_renewed",
+ getattr(client, "_vibe_runtime_epoch", 0)
+ != (
+ launch_inputs.epoch
+ if launch_inputs is not None
+ else getattr(self.controller, "claude_runtime_epoch", 0)
+ ),
+ ),
+ ("system_prompt_changed", self.claude_system_prompts.get(composite_key) != system_prompt),
+ (
+ "managed_skills_changed",
+ getattr(client, "_vibe_managed_skills_env", {})
+ != managed_skill_environment(
+ working_path,
+ project_base=managed_skill_project_base(context),
+ claude_cli_path=managed_skill_claude_cli_path(
+ SimpleNamespace(claude=launch_inputs.config) if launch_inputs is not None else self.config
+ ),
+ ),
+ ),
+ ("git_path_changed", getattr(client, "_vibe_git_path_state", None) != self._claude_git_path_state(working_path)),
+ )
+ reason = next((name for name, changed in changes if changed), None)
+ if reason is None:
+ return False
+ if composite_key in self.active_sessions:
+ if not (launch_changed or caller_changed):
+ logger.info(
+ "Keeping the busy Claude SDK client for %s until its session is idle: %s",
+ composite_key,
+ reason,
+ )
+ return False
+ self._interrupt_claude_session_work(composite_key)
+ logger.info("Recreating cached Claude SDK client for %s: %s", composite_key, reason)
+ await self._cleanup_session_locked(
+ composite_key,
+ retire_model_hub_scope=model_hub_launch.channel == "direct",
+ reason=reason,
+ )
+ return True
+
+ def _interrupt_claude_session_work(self, composite_key: str, *, reason: str | None = None) -> None:
+ """Settle a replaced or stopped client's background work.
+
+ ``reason`` is the settlement; the default is a runtime update.
+ """
+ service = getattr(self.controller, "agent_service", None)
+ end_runtime = getattr(service, "force_end_runtime_activities", None)
+ if callable(end_runtime):
+ if reason is None:
+ end_runtime("claude", composite_key)
+ else:
+ end_runtime("claude", composite_key, reason=reason)
+
+ async def _connect_claude_client(self, client) -> None:
+ """Connect a client so that no exit leaves its CLI running unowned.
+
+ The client is not in ``claude_sessions`` yet, so no disable capture
+ can reach it. The connect runs shielded: a cancelled turn, such as one
+ a disable interrupts, reads the CLI's process off the client while the
+ connect is still in flight, cancels the connect once so the SDK's own
+ cleanup runs undisturbed, and then stops that process whatever the
+ cleanup achieved.
+ """
+ connect = asyncio.ensure_future(client.connect())
+ try:
+ await asyncio.shield(connect)
+ except asyncio.CancelledError:
+ process = get_claude_client_process(client)
+ connect.cancel()
+ await asyncio.shield(self._stop_abandoned_connect(client, connect, process))
+ raise
+
+ async def _stop_abandoned_connect(self, client, connect: asyncio.Future, process: Any) -> None:
+ try:
+ await asyncio.wait_for(connect, timeout=CLAUDE_ABANDONED_CONNECT_TIMEOUT_SECONDS)
+ except BaseException:
+ # Cancelled or failed: the SDK's connect already ran its cleanup.
+ pass
+ else:
+ # It connected as the turn was cancelled.
+ try:
+ await client.disconnect()
+ except Exception:
+ logger.warning("Failed to disconnect an abandoned Claude client", exc_info=True)
+ if not await stop_claude_process(process, logger=logger):
+ logger.warning(
+ "Claude CLI pid=%s of an abandoned connect survived its stop",
+ getattr(process, "pid", None),
+ )
+
+ def _claude_disabled(self) -> bool:
+ return getattr(getattr(self.config, "claude", None), "enabled", True) is False
+
+ def capture_claude_clients(self) -> tuple[tuple[str, Any, Any], ...]:
+ """Every live client, by key, identity, and CLI process, for a stop that must close exactly these.
+
+ The process is read now: a disconnect drops it from the client.
+ """
+ return tuple(
+ (composite_key, client, get_claude_client_process(client))
+ for composite_key, client in self.claude_sessions.items()
+ )
+
+ async def close_captured_claude_clients(
+ self, captured: tuple[tuple[str, Any, Any], ...], *, reason: str
+ ) -> None:
+ """Close exactly the captured clients, busy or idle, settling their work.
+
+ A client created after the capture, such as one of a re-enabled
+ backend, is never touched; one still connecting refuses its turn once
+ connected, because Claude is disabled by then. A captured client
+ counts as closed only once its CLI process has exited: a failed
+ disconnect leaves it running after it left ``claude_sessions``, so its
+ process is stopped directly, on a retry too. Raises while a captured
+ client survives, so a caller can retry.
+ """
+ for composite_key, client, _process in captured:
+ if self.claude_sessions.get(composite_key) is not client:
+ continue
+ async with self._claude_runtime_generation_lock(composite_key):
+ if self.claude_sessions.get(composite_key) is not client:
+ continue
+ self._interrupt_claude_session_work(composite_key, reason=reason)
+ await self._cleanup_session_locked(composite_key, expected_client=client, reason=reason)
+ survivors = [
+ key
+ for key, client, process in captured
+ if self.claude_sessions.get(key) is client
+ or not await stop_claude_process(process, logger=logger)
+ ]
+ if survivors:
+ raise RuntimeError(f"{len(survivors)} Claude client(s) survived their close")
+
async def _reuse_cached_claude_session_if_available(
self,
*,
@@ -480,6 +680,7 @@ class SessionHandler(BaseHandler):
effective_effort: Optional[str],
agent_system_prompt: Optional[str],
model_hub_launch: "ModelHubLaunch",
+ launch_inputs: "_ClaudeLaunchInputs | None" = None,
) -> ClaudeSDKClient | None:
client = self.claude_sessions.get(composite_key)
if client is None:
@@ -489,21 +690,6 @@ class SessionHandler(BaseHandler):
client,
):
return None
- reasoning_changed = getattr(client, "_vibe_reasoning_effort", None) != effective_effort
- if (
- reasoning_changed
- or getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint
- ):
- reason = "reasoning_effort_changed" if reasoning_changed else "model_hub_channel_changed"
- logger.info("Recreating cached Claude SDK client: %s", reason)
- await self._wait_for_claude_session_idle(composite_key)
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason=reason,
- )
- return None
-
next_system_prompt = await self._build_claude_system_prompt(
context=context,
session_key=session_key,
@@ -511,58 +697,18 @@ class SessionHandler(BaseHandler):
session_anchor=base_session_id,
agent_system_prompt=agent_system_prompt,
working_path=working_path,
+ claude_config=launch_inputs.config if launch_inputs is not None else None,
)
- cached_system_prompt = self.claude_system_prompts.get(composite_key)
- if cached_system_prompt != next_system_prompt:
- logger.info(
- "Recreating cached Claude SDK client for %s because avibe system prompt changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="system_prompt_changed",
- )
- return None
-
- caller_env = self._caller_env_for_context(context)
- if getattr(client, "_vibe_caller_env", {}) != caller_env:
- logger.info(
- "Recreating cached Claude SDK client for %s because caller context env changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="caller_env_changed",
- )
- return None
- managed_skills_env = managed_skill_environment(
- working_path,
- project_base=managed_skill_project_base(context),
- claude_cli_path=managed_skill_claude_cli_path(self.config),
- )
- if getattr(client, "_vibe_managed_skills_env", {}) != managed_skills_env:
- logger.info(
- "Recreating cached Claude SDK client for %s because managed Skill bindings changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- )
- return None
- git_path_state = self._claude_git_path_state(working_path)
- if getattr(client, "_vibe_git_path_state", None) != git_path_state:
- logger.info(
- "Recreating cached Claude SDK client for %s because Git PATH changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="git_path_changed",
- )
+ if await self._replace_stale_cached_claude_client(
+ composite_key,
+ client,
+ context=context,
+ working_path=working_path,
+ effective_effort=effective_effort,
+ system_prompt=next_system_prompt,
+ model_hub_launch=model_hub_launch,
+ launch_inputs=launch_inputs,
+ ):
return None
try:
@@ -603,6 +749,7 @@ class SessionHandler(BaseHandler):
effective_agent: str,
agent_system_prompt: Optional[str],
model_hub_launch: "ModelHubLaunch",
+ launch_inputs: "_ClaudeLaunchInputs | None" = None,
) -> ClaudeSDKClient | None:
client = self.claude_sessions.get(composite_key)
if client is None:
@@ -612,20 +759,6 @@ class SessionHandler(BaseHandler):
client,
):
return None
- reasoning_changed = getattr(client, "_vibe_reasoning_effort", None) != effective_effort
- if (
- reasoning_changed
- or getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint
- ):
- reason = "reasoning_effort_changed" if reasoning_changed else "subagent_model_hub_channel_changed"
- logger.info("Recreating cached Claude subagent SDK client: %s", reason)
- await self._wait_for_claude_session_idle(composite_key)
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason=reason,
- )
- return None
self.ensure_agent_session_id(
context,
session_key=session_key,
@@ -643,56 +776,18 @@ class SessionHandler(BaseHandler):
session_anchor=base_session_id,
agent_system_prompt=next_agent_system_prompt,
working_path=working_path,
+ claude_config=launch_inputs.config if launch_inputs is not None else None,
)
- if self.claude_system_prompts.get(composite_key) != next_system_prompt:
- logger.info(
- "Recreating cached Claude subagent SDK client for %s because avibe system prompt changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="subagent_system_prompt_changed",
- )
- return None
- caller_env = self._caller_env_for_context(context)
- if getattr(client, "_vibe_caller_env", {}) != caller_env:
- logger.info(
- "Recreating cached Claude subagent SDK client for %s because caller context env changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="subagent_caller_env_changed",
- )
- return None
- managed_skills_env = managed_skill_environment(
- working_path,
- project_base=managed_skill_project_base(context),
- claude_cli_path=managed_skill_claude_cli_path(self.config),
- )
- if getattr(client, "_vibe_managed_skills_env", {}) != managed_skills_env:
- logger.info(
- "Recreating cached Claude subagent SDK client for %s because managed Skill bindings changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- )
- return None
- git_path_state = self._claude_git_path_state(working_path)
- if getattr(client, "_vibe_git_path_state", None) != git_path_state:
- logger.info(
- "Recreating cached Claude subagent SDK client for %s because Git PATH changed",
- composite_key,
- )
- await self._cleanup_session_locked(
- composite_key,
- retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="subagent_git_path_changed",
- )
+ if await self._replace_stale_cached_claude_client(
+ composite_key,
+ client,
+ context=context,
+ working_path=working_path,
+ effective_effort=effective_effort,
+ system_prompt=next_system_prompt,
+ model_hub_launch=model_hub_launch,
+ launch_inputs=launch_inputs,
+ ):
return None
if desired_model:
try:
@@ -1070,10 +1165,12 @@ class SessionHandler(BaseHandler):
)
return disallowed
- def _get_claude_cli_path_override(self) -> Optional[str]:
+ def _get_claude_cli_path_override(self, claude_config: Any = None) -> Optional[str]:
from vibe.claude_config import normalize_claude_cli_path
- return normalize_claude_cli_path(getattr(getattr(self.config, "claude", None), "cli_path", None))
+ if claude_config is None:
+ claude_config = getattr(self.config, "claude", None)
+ return normalize_claude_cli_path(getattr(claude_config, "cli_path", None))
def _load_agent_file(self, agent_name: str, working_path: str) -> Optional[Dict[str, Any]]:
"""Load an agent file and return its parsed content.
@@ -1278,6 +1375,13 @@ class SessionHandler(BaseHandler):
else:
base_session_id, working_path, composite_key = self.get_session_info(context, source=turn_source)
+ router = getattr(self.controller, "model_hub_runtime", None)
+ hub_snapshot = getattr(router, "snapshot", None)
+ launch_inputs = _ClaudeLaunchInputs(
+ epoch=getattr(self.controller, "claude_runtime_epoch", 0),
+ config=getattr(self.config, "claude", None),
+ hub_config=hub_snapshot() if callable(hub_snapshot) else None,
+ )
settings_key = self._get_settings_key(context)
session_key = self._get_session_key(context)
# Resume the native session bound to the RESERVED workbench row (by PK).
@@ -1339,6 +1443,7 @@ class SessionHandler(BaseHandler):
launch_model or "",
process_scope=cached_key or composite_key,
context=context,
+ config=launch_inputs.hub_config,
)
bind_launch(context, model_hub_launch)
runtime_model = model_hub_launch.runtime_model or launch_model
@@ -1371,6 +1476,7 @@ class SessionHandler(BaseHandler):
effective_effort=effective_effort,
agent_system_prompt=None,
model_hub_launch=model_hub_launch,
+ launch_inputs=launch_inputs,
)
if client is not None:
return client
@@ -1394,6 +1500,7 @@ class SessionHandler(BaseHandler):
effective_agent=effective_agent,
agent_system_prompt=agent_system_prompt,
model_hub_launch=model_hub_launch,
+ launch_inputs=launch_inputs,
)
if client is not None:
return client
@@ -1421,6 +1528,7 @@ class SessionHandler(BaseHandler):
effective_agent=effective_agent,
agent_system_prompt=agent_system_prompt,
model_hub_launch=model_hub_launch,
+ launch_inputs=launch_inputs,
)
else:
client = await self._reuse_cached_claude_session_if_available(
@@ -1434,6 +1542,7 @@ class SessionHandler(BaseHandler):
effective_effort=effective_effort,
agent_system_prompt=None,
model_hub_launch=model_hub_launch,
+ launch_inputs=launch_inputs,
)
if client is not None:
return client
@@ -1452,6 +1561,7 @@ class SessionHandler(BaseHandler):
effective_effort=effective_effort,
agent_system_prompt=agent_system_prompt,
fork_session=bool(fork_source_claude_session_id),
+ launch_inputs=launch_inputs,
)
if not create_future.done():
create_future.set_result(client)
@@ -1481,7 +1591,21 @@ class SessionHandler(BaseHandler):
effective_effort: Optional[str],
agent_system_prompt: Optional[str],
fork_session: bool = False,
+ launch_inputs: "_ClaudeLaunchInputs | None" = None,
) -> ClaudeSDKClient:
+ # One coherent config for the whole launch, taken at the turn's
+ # admission: a renewal while this turn resolves or creates its client
+ # leaves it on the epoch and config it started with, and its next turn
+ # moves it.
+ if launch_inputs is None:
+ launch_inputs = _ClaudeLaunchInputs(
+ epoch=getattr(self.controller, "claude_runtime_epoch", 0),
+ config=getattr(self.config, "claude", None),
+ hub_config=None,
+ )
+ runtime_epoch = launch_inputs.epoch
+ claude_config = launch_inputs.config
+ launch_config = SimpleNamespace(claude=claude_config)
# Ensure working directory exists
if not os.path.exists(working_path):
@@ -1545,6 +1669,7 @@ class SessionHandler(BaseHandler):
agent_system_prompt=agent_system_prompt,
skill_catalog_sink=skill_catalog_sink,
working_path=working_path,
+ claude_config=claude_config,
)
# Echo native input frames so the long-lived receiver can correlate
@@ -1574,7 +1699,7 @@ class SessionHandler(BaseHandler):
)
from core.git_runtime import prepend_vendored_git_to_path
- claude_env = build_claude_subprocess_env(getattr(self.config, "claude", None))
+ claude_env = build_claude_subprocess_env(claude_config)
if model_hub_launch is not None:
claude_env = build_claude_hub_env(claude_env, model_hub_launch)
claude_env.update(self._caller_env_for_context(context))
@@ -1582,7 +1707,7 @@ class SessionHandler(BaseHandler):
managed_skill_environment(
working_path,
project_base=managed_skill_project_base(context),
- claude_cli_path=managed_skill_claude_cli_path(self.config),
+ claude_cli_path=managed_skill_claude_cli_path(launch_config),
)
)
prepend_vendored_git_to_path(
@@ -1620,7 +1745,7 @@ class SessionHandler(BaseHandler):
}
if tool_policy_hooks:
option_kwargs["hooks"] = tool_policy_hooks
- cli_path_override = self._get_claude_cli_path_override()
+ cli_path_override = self._get_claude_cli_path_override(claude_config)
if cli_path_override:
option_kwargs["cli_path"] = cli_path_override
if effective_effort == NO_REASONING_EFFORT:
@@ -1657,6 +1782,10 @@ class SessionHandler(BaseHandler):
else:
logger.info(f"Creating new Claude session")
+ if self._claude_disabled():
+ # Turned off after this turn was admitted: start nothing.
+ raise ClaudeBackendDisabledError("claude backend disabled")
+
# Create new Claude client
client = ClaudeSDKClient(options=options)
setattr(client, "_vibe_pending_skill_catalog", skill_catalog_sink[0] if skill_catalog_sink else None)
@@ -1668,11 +1797,12 @@ class SessionHandler(BaseHandler):
managed_skill_environment(
working_path,
project_base=managed_skill_project_base(context),
- claude_cli_path=managed_skill_claude_cli_path(self.config),
+ claude_cli_path=managed_skill_claude_cli_path(launch_config),
),
)
setattr(client, "_vibe_git_path_state", git_path_state)
setattr(client, "_vibe_reasoning_effort", effective_effort)
+ setattr(client, "_vibe_runtime_epoch", runtime_epoch)
setattr(
client,
"_vibe_model_hub_fingerprint",
@@ -1692,7 +1822,7 @@ class SessionHandler(BaseHandler):
# Connect the client
try:
- await client.connect()
+ await self._connect_claude_client(client)
governor_from_controller(self.controller).apply_to_pid(
get_claude_client_pid(client),
label="claude",
@@ -1734,6 +1864,18 @@ class SessionHandler(BaseHandler):
) from exc
raise
+ if self._claude_disabled():
+ # Turned off while this client connected, possibly after the
+ # disable captured the live clients, so nothing else would close it.
+ process = get_claude_client_process(client)
+ try:
+ await client.disconnect()
+ except Exception:
+ logger.warning("Failed to disconnect a Claude client of a disabled backend", exc_info=True)
+ await stop_claude_process(process, logger=logger)
+ self._retire_model_hub_process_scope(composite_key)
+ raise ClaudeBackendDisabledError("claude backend disabled")
+
self.claude_system_prompts[composite_key] = final_system_prompt
setattr(client, "_vibe_current_model", effective_model)
self.bind_claude_runtime_session(
@@ -1770,8 +1912,11 @@ class SessionHandler(BaseHandler):
agent_system_prompt: Optional[str],
working_path: Optional[str] = None,
skill_catalog_sink: list[dict] | None = None,
+ claude_config: Any = None,
) -> str | Dict[str, str]:
- base_prompt = agent_system_prompt or self.config.claude.system_prompt
+ if claude_config is None:
+ claude_config = self.config.claude
+ base_prompt = agent_system_prompt or claude_config.system_prompt
quick_replies_on = getattr(self.config, "reply_enhancements", True)
platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
@@ -1791,7 +1936,7 @@ class SessionHandler(BaseHandler):
enabled_agents=get_enabled_agents_for_prompt(self.controller),
skills_cwd=working_path,
skills_project_base=managed_skill_project_base(context),
- skills_claude_cli_path=managed_skill_claude_cli_path(self.config),
+ skills_claude_cli_path=managed_skill_claude_cli_path(SimpleNamespace(claude=claude_config)),
skill_catalog_sink=skill_catalog_sink,
)
@@ -2448,17 +2593,18 @@ class SessionHandler(BaseHandler):
) -> int:
"""Disconnect Claude sessions that have been idle beyond the timeout.
+ A client from before the latest runtime renewal can never serve another
+ turn, so it is disconnected as soon as it is idle, even when
+ ``idle_timeout <= 0`` turns idle eviction off.
+
Durable Turn and Activity ownership always vetoes reclamation, even
during silent inference or tools. The age backstop repairs an
adapter-local active flag only after durable ownership independently
allows reclamation. Pass ``stuck_active_multiplier <= 0`` to disable
that stale-flag repair.
"""
- if idle_timeout <= 0:
- return 0
-
stuck_threshold = None
- if stuck_active_multiplier > 0:
+ if idle_timeout > 0 and stuck_active_multiplier > 0:
stuck_threshold = max(
idle_timeout * stuck_active_multiplier,
max(0.0, stuck_active_floor_seconds),
@@ -2471,6 +2617,10 @@ class SessionHandler(BaseHandler):
(composite_key, client)
for composite_key in self.session_last_activity
if (client := self.claude_sessions.get(composite_key)) is not None
+ and (
+ self._idle_eviction_after(client, idle_timeout) is not None
+ or (stuck_threshold is not None and composite_key in self.active_sessions)
+ )
)
targets_by_key = self._claude_runtime_ownership_targets(ownership_items)
provider = getattr(self.controller, "runtime_ownership", None)
@@ -2516,7 +2666,8 @@ class SessionHandler(BaseHandler):
):
expired.append((composite_key, idle_for))
continue
- if not ownership.blocks_reclamation and idle_for >= idle_timeout:
+ evict_after = self._idle_eviction_after(client, idle_timeout)
+ if not ownership.blocks_reclamation and evict_after is not None and idle_for >= evict_after:
expired.append((composite_key, idle_for))
evicted = 0
@@ -2574,9 +2725,11 @@ class SessionHandler(BaseHandler):
and not ownership.blocks_reclamation
)
else:
+ evict_after = self._idle_eviction_after(client, idle_timeout)
allowed = bool(
not ownership.blocks_reclamation
- and recheck_idle >= idle_timeout
+ and evict_after is not None
+ and recheck_idle >= evict_after
)
else:
allowed = False
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 7279b45dc..a11dd19c4 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -453,30 +453,28 @@ class SettingsHandler(BaseHandler):
if "opencode" in backends_to_load:
try:
opencode_agent = self.controller.agent_service.agents.get("opencode")
- if opencode_agent and hasattr(opencode_agent, "_get_server"):
- server = await opencode_agent._get_server() # type: ignore[attr-defined]
- await server.ensure_running()
-
- cwd = self.controller.get_cwd(context)
- opencode_agents = await server.get_available_agents(cwd)
- model_hub_service = getattr(
- self.controller,
- "model_hub_service",
- None,
- )
- public_models = (
- model_hub_service.opencode_public_models()
- if model_hub_service is not None
- else None
- )
- if public_models is None:
- opencode_models = await server.get_available_models(cwd)
- else:
- opencode_models = await server.get_available_models(
- cwd,
- model_hub_models=public_models,
+ if opencode_agent and hasattr(opencode_agent, "current_server"):
+ async with opencode_agent.current_server() as server: # type: ignore[attr-defined]
+ cwd = self.controller.get_cwd(context)
+ opencode_agents = await server.get_available_agents(cwd)
+ model_hub_service = getattr(
+ self.controller,
+ "model_hub_service",
+ None,
+ )
+ public_models = (
+ model_hub_service.opencode_public_models()
+ if model_hub_service is not None
+ else None
)
- opencode_default_config = await server.get_default_config(cwd)
+ if public_models is None:
+ opencode_models = await server.get_available_models(cwd)
+ else:
+ opencode_models = await server.get_available_models(
+ cwd,
+ model_hub_models=public_models,
+ )
+ opencode_default_config = await server.get_default_config(cwd)
except Exception as e:
logger.warning(f"Failed to fetch OpenCode data: {e}")
diff --git a/core/internal_server.py b/core/internal_server.py
index c7ffdc41b..91679c155 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1016,6 +1016,55 @@ def create_app(
logger.exception("internal Agent backend reconcile failed")
return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+ @app.post("/internal/opencode/generation-leases")
+ async def _lease_opencode_generation(request: Request) -> Any:
+ """Pin a controller-owned OpenCode generation for a caller in another process.
+
+ The UI process never launches OpenCode itself: it leases the generation
+ that serves the current launch spec and talks to it over HTTP.
+ """
+ payload = await _safe_json(request)
+ purpose = payload.get("purpose")
+ ttl_seconds = payload.get("ttl_seconds")
+ if (
+ not isinstance(purpose, str)
+ or not purpose.strip()
+ or isinstance(ttl_seconds, bool)
+ or not isinstance(ttl_seconds, (int, float))
+ or ttl_seconds <= 0
+ ):
+ return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_lease_request"})
+ agent = getattr(getattr(controller, "agent_service", None), "agents", {}).get("opencode")
+ lease_generation = getattr(agent, "lease_generation", None)
+ if not callable(lease_generation):
+ return JSONResponse(status_code=404, content={"ok": False, "error": "opencode_disabled"})
+ try:
+ lease = await lease_generation(purpose.strip(), ttl_seconds=float(ttl_seconds))
+ except Exception as exc:
+ logger.exception("internal OpenCode generation lease failed")
+ return JSONResponse(
+ status_code=503,
+ content={"ok": False, "error": "opencode_server_unavailable", "detail": str(exc)},
+ )
+ server = lease["server"]
+ return {
+ "ok": True,
+ "lease_id": lease["lease_id"],
+ "generation_id": server.generation_id,
+ "base_url": server.base_url,
+ "request_timeout_seconds": server.request_timeout_seconds,
+ "model_hub_provider_ids": list(server.model_hub_provider_ids),
+ }
+
+ @app.post("/internal/opencode/generation-leases/{lease_id}/release")
+ async def _release_opencode_generation_lease(lease_id: str) -> Any:
+ from modules.agents.opencode.client_manager import release_opencode_lease
+
+ released = await release_opencode_lease(lease_id, controller=controller)
+ if released is None:
+ return JSONResponse(status_code=404, content={"ok": False, "error": "opencode_disabled"})
+ return {"ok": True, "released": released}
+
@app.post("/internal/backend-auth/test")
async def _test_backend_auth(request: Request) -> Any:
"""Probe credentials through the controller-owned Agent runtime."""
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 4b2503fc9..a607bb202 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -49,6 +49,7 @@ from core.reply_enhancer import (
strip_silent_blocks,
)
from core.run_settlement import (
+ SETTLED_BY_BACKEND_DISABLED,
SETTLED_BY_BACKEND_REFRESH,
SETTLED_BY_STOPPED,
SETTLED_BY_TERMINAL_RESULT,
@@ -266,7 +267,7 @@ async def _stream_chunk(
# ``SETTLED_BY_NO_TERMINAL_RESULT`` is the pessimistic default a fallback
# releaser writes, and upgrading THAT when a real result lands is the whole
# point of this line.
- if sink.get("settled_by") not in (SETTLED_BY_STOPPED, SETTLED_BY_BACKEND_REFRESH):
+ if sink.get("settled_by") not in (SETTLED_BY_STOPPED, SETTLED_BY_BACKEND_REFRESH, SETTLED_BY_BACKEND_DISABLED):
sink["settled_by"] = SETTLED_BY_TERMINAL_RESULT
done = sink.get("done_event")
if done is not None:
diff --git a/core/run_settlement.py b/core/run_settlement.py
index f87b088c9..3785a793c 100644
--- a/core/run_settlement.py
+++ b/core/run_settlement.py
@@ -64,6 +64,11 @@ SETTLED_BY_TURN_ONLY_RESULT: Final = "turn_only_result"
#: healthy service, rather than the service itself shutting down.
SETTLED_BY_BACKEND_REFRESH: Final = "backend_refresh"
+#: The user disabled the turn's Agent backend, which stops its work at once.
+#: Like a Stop it is the user's own intent, so a run ends ``canceled``; unlike a
+#: Stop the user may not be watching this session, so the turn says why.
+SETTLED_BY_BACKEND_DISABLED: Final = "backend_disabled"
+
#: The scheduled service shut down while its exact claimed request was executing.
#: The interrupted attempt is terminal; a later process must not replay it.
SETTLED_BY_RESTARTED: Final = "restarted"
@@ -82,6 +87,7 @@ SETTLEMENTS_WITHOUT_RESULT: Final = frozenset(
SETTLED_BY_STOPPED,
SETTLED_BY_REFUSED_CONCURRENT_TURN,
SETTLED_BY_BACKEND_REFRESH,
+ SETTLED_BY_BACKEND_DISABLED,
SETTLED_BY_RESTARTED,
SETTLED_BY_INTERRUPTED,
}
@@ -97,6 +103,7 @@ INTERRUPT_REASON_NO_TERMINAL_RESULT: Final = SETTLED_BY_NO_TERMINAL_RESULT
INTERRUPT_REASON_STOPPED: Final = SETTLED_BY_STOPPED
INTERRUPT_REASON_REFUSED_CONCURRENT_TURN: Final = SETTLED_BY_REFUSED_CONCURRENT_TURN
INTERRUPT_REASON_BACKEND_REFRESH: Final = SETTLED_BY_BACKEND_REFRESH
+INTERRUPT_REASON_BACKEND_DISABLED: Final = SETTLED_BY_BACKEND_DISABLED
INTERRUPT_REASON_RESTARTED: Final = SETTLED_BY_RESTARTED
INTERRUPT_REASON_INTERRUPTED: Final = SETTLED_BY_INTERRUPTED
@@ -181,6 +188,7 @@ RUN_INTERRUPTION_REASONS: Final = frozenset(
{
SETTLED_BY_STOPPED,
SETTLED_BY_BACKEND_REFRESH,
+ SETTLED_BY_BACKEND_DISABLED,
SETTLED_BY_INTERRUPTED,
INTERRUPT_REASON_EVICTED,
INTERRUPT_REASON_RESTARTED,
@@ -204,6 +212,7 @@ SETTLEMENT_I18N_KEYS: Final = {
SETTLED_BY_STOPPED: "harness.run.interrupted.stopped",
SETTLED_BY_REFUSED_CONCURRENT_TURN: "harness.run.interrupted.refusedConcurrentTurn",
SETTLED_BY_BACKEND_REFRESH: "harness.run.interrupted.backendRefresh",
+ SETTLED_BY_BACKEND_DISABLED: "harness.run.interrupted.backendDisabled",
SETTLED_BY_RESTARTED: "harness.run.interrupted.restarted",
SETTLED_BY_INTERRUPTED: "harness.run.interrupted.interrupted",
}
@@ -227,6 +236,7 @@ SETTLEMENT_TERMINAL_STATUS: Final = {
SETTLED_BY_STOPPED: "canceled",
SETTLED_BY_REFUSED_CONCURRENT_TURN: "failed",
SETTLED_BY_BACKEND_REFRESH: "failed",
+ SETTLED_BY_BACKEND_DISABLED: "canceled",
SETTLED_BY_RESTARTED: "failed",
SETTLED_BY_INTERRUPTED: "failed",
}
@@ -254,6 +264,7 @@ SETTLEMENT_TERMINAL_STATUS: Final = {
NON_COMPLETING_TURN_SETTLEMENTS: Final = {
SETTLED_BY_STOPPED: "canceled",
SETTLED_BY_BACKEND_REFRESH: "canceled",
+ SETTLED_BY_BACKEND_DISABLED: "canceled",
}
def covered(test_node: str) -> tuple[str, str]:
diff --git a/core/services/running_agents.py b/core/services/running_agents.py
index 617c130ac..fb2a63044 100644
--- a/core/services/running_agents.py
+++ b/core/services/running_agents.py
@@ -6,7 +6,7 @@ liveness source it reads is controller in-memory state:
- Claude: ``controller.claude_sessions`` (composite_key -> SDK client),
``claude_active_sessions`` (active turn set), ``session_last_activity``.
-- Codex: ``CodexAgent._session_mgr`` / ``_turn_registry`` / ``_transports``
+- Codex: ``CodexAgent._session_mgr`` / ``_turn_registry`` / ``transport_for_session``
(one transport/pid per working dir, shared by many sessions).
- OpenCode: ``OpenCodeAgent._active_requests`` (no OS subprocess / pid).
- Orphans: the persisted Claude process registry (``claude_processes.json``)
@@ -206,17 +206,17 @@ def _collect_codex(controller: "Controller") -> list[dict[str, Any]]:
return rows
session_mgr = getattr(agent, "_session_mgr", None)
turn_registry = getattr(agent, "_turn_registry", None)
- transports = getattr(agent, "_transports", {}) or {}
- if session_mgr is None:
+ transport_for_session = getattr(agent, "transport_for_session", None)
+ if session_mgr is None or not callable(transport_for_session):
return rows
# ``all_base_sessions`` unions three lock-free dicts internally, so guard it
# against concurrent mutation (we run in a worker thread, §to_thread).
base_ids = list(_safe_call(session_mgr.all_base_sessions, []))
- # Resolve each base's cwd once, then count sessions per cwd (so the UI can
- # flag a pid shared across sessions) — avoids a second get_cwd pass.
+ # Resolve each base's app-server once, then count sessions per process (so
+ # the UI can flag a pid shared across sessions).
entries: list[tuple[str, Optional[str], bool, Any]] = []
- cwd_session_count: dict[str, int] = {}
+ transport_session_count: dict[int, int] = {}
for base in base_ids:
cwd = session_mgr.get_cwd(base)
active_turn = turn_registry.get_active_turn(base) if turn_registry is not None else None
@@ -231,11 +231,11 @@ def _collect_codex(controller: "Controller") -> list[dict[str, Any]]:
else False
)
is_active = bool(active_turn) or has_pending
- transport = transports.get(cwd) if cwd else None
+ transport = _safe_call(lambda base=base: transport_for_session(base), None)
# A transport object can outlive its app-server when the process exits out
- # of band (crash / reader-task failure): it lingers in ``_transports`` with
- # ``is_alive`` False until a later cleanup removes it. Treat a dead transport
- # as no live transport so it can't surface as a phantom idle row.
+ # of band (crash / reader-task failure): it stays bound with ``is_alive``
+ # False until a later cleanup removes it. Treat a dead transport as no
+ # live transport so it can't surface as a phantom idle row.
if transport is not None and not getattr(transport, "is_alive", True):
transport = None
# Idle eviction drops the app-server transport but preserves cwd/session
@@ -245,16 +245,16 @@ def _collect_codex(controller: "Controller") -> list[dict[str, Any]]:
if transport is None and not is_active:
continue
entries.append((base, cwd, is_active, transport))
- if cwd and transport is not None:
- cwd_session_count[cwd] = cwd_session_count.get(cwd, 0) + 1
+ if transport is not None:
+ transport_session_count[id(transport)] = transport_session_count.get(id(transport), 0) + 1
for base, cwd, is_active, transport in entries:
pid = getattr(transport, "pid", None) if transport is not None else None
- # No per-session elapsed for codex: ``_transport_last_activity`` is keyed
- # by cwd (shared across every session on that transport) and is touched on
- # every streaming event, so it reflects neither this session's turn
- # duration nor its idle time. Report ``None`` rather than a misleading
- # value; the row still shows backend / state / pid_shared.
+ # No per-session elapsed for codex: an app-server's activity time is shared
+ # across every session on that process and is touched on every streaming
+ # event, so it reflects neither this session's turn duration nor its idle
+ # time. Report ``None`` rather than a misleading value; the row still
+ # shows backend / state / pid_shared.
rows.append(
_make_row(
backend="codex",
@@ -262,7 +262,7 @@ def _collect_codex(controller: "Controller") -> list[dict[str, Any]]:
base_session_id=base,
workdir=cwd,
pid=pid,
- pid_shared=bool(cwd and transport is not None and cwd_session_count.get(cwd, 0) > 1),
+ pid_shared=bool(transport is not None and transport_session_count.get(id(transport), 0) > 1),
elapsed_seconds=None,
)
)
@@ -648,60 +648,23 @@ async def _end_codex(controller: "Controller", base_session_id: Optional[str]) -
agent = _get_agent(controller, "codex")
if agent is None:
return {"ok": False, "error": "codex_unavailable"}
- session_mgr = getattr(agent, "_session_mgr", None)
- turn_registry = getattr(agent, "_turn_registry", None)
- transports = getattr(agent, "_transports", {}) or {}
- if session_mgr is None or turn_registry is None:
+ end_session = getattr(agent, "end_session", None)
+ if not callable(end_session):
return {"ok": False, "error": "codex_registries_unavailable"}
- cwd = session_mgr.get_cwd(base_session_id)
- thread_id = session_mgr.get_thread_id(base_session_id)
- turn_id = turn_registry.get_active_turn(base_session_id)
- transport = transports.get(cwd) if cwd else None
- # Interrupt the active turn (the shared app-server transport stays up for
- # other sessions on the same cwd); then clear THIS session's thread/turn state.
- interrupted = False
- if turn_id and thread_id and transport is not None:
- try:
- await transport.send_request("turn/interrupt", {"threadId": thread_id, "turnId": turn_id})
- interrupted = True
- except Exception: # noqa: BLE001
- logger.debug("end: codex turn/interrupt failed for %s", base_session_id, exc_info=True)
+ # The adapter owns End: it serializes it with the Session's turns, releases
+ # the Session's thread on an app-server other Sessions still use, or stops
+ # the directory's app-servers once this was their last user, and clears the
+ # Session only after that succeeded.
try:
- turn_registry.clear_session(base_session_id)
+ ended = await end_session(base_session_id)
except Exception as exc: # noqa: BLE001
- logger.warning("end: codex clear failed for %s: %s", base_session_id, exc)
- return {"ok": False, "error": "clear_failed", "detail": str(exc)}
- # The app-server transport is shared per cwd. If THIS was the last session on
- # that cwd, stop it too so the codex process is actually freed (otherwise it
- # lingers with zero sessions); if other sessions still use it, leave it up.
- process_killed = False
- retire_idle = getattr(agent, "retire_unowned_session_transport", None)
- other_sessions = (
- set(session_mgr.sessions_for_cwd(cwd)) - {base_session_id}
- if cwd else set()
- )
- if cwd and transport is not None and not other_sessions and callable(retire_idle):
- try:
- process_killed = bool(
- await retire_idle(cwd, ending_session_id=base_session_id)
- )
- except Exception as exc: # noqa: BLE001
- logger.warning("end: codex transport stop failed for %s", cwd, exc_info=True)
- return {"ok": False, "error": "transport_retire_failed", "detail": str(exc)}
- if not process_killed:
- return {"ok": False, "error": "transport_retire_failed"}
- try:
- # Keep the cwd mapping until transport retirement succeeds, so a failed
- # close remains reachable by Session ID for a later End attempt.
- session_mgr.clear(base_session_id)
- getattr(agent, "_session_locks", {}).pop(base_session_id, None)
- getattr(agent, "_session_last_activity", {}).pop(base_session_id, None)
- clear_thread_cache = getattr(agent, "_clear_thread_developer_instructions", None)
- if callable(clear_thread_cache):
- clear_thread_cache(base_session_id)
- except Exception as exc: # noqa: BLE001
- logger.warning("end: codex clear failed for %s: %s", base_session_id, exc)
- return {"ok": False, "error": "clear_failed", "detail": str(exc)}
+ released = getattr(exc, "reason", None) == "codex_thread_release_unavailable"
+ logger.warning("end: codex teardown failed for %s", base_session_id, exc_info=True)
+ return {
+ "ok": False,
+ "error": "thread_release_failed" if released else "transport_retire_failed",
+ "detail": str(exc),
+ }
# ``interrupted`` is False when there was no active turn to stop (idle/stale):
# the session state is still cleared, but the caller can tell nothing was
# actively interrupted.
@@ -709,8 +672,8 @@ async def _end_codex(controller: "Controller", base_session_id: Optional[str]) -
"ok": True,
"action": "ended",
"backend": "codex",
- "interrupted": interrupted,
- "process_killed": process_killed,
+ "interrupted": bool(ended.get("interrupted")),
+ "process_killed": bool(ended.get("process_killed")),
}
@@ -729,8 +692,10 @@ async def _end_opencode(controller: "Controller", base_session_id: Optional[str]
# Active End has already gone through the canonical stop path. Finish
# interrupting its native poll, but do not retire a shared server here.
try:
- if req_info:
- server = await agent._get_server()
+ # Only the generation running this native turn can abort it.
+ bound = getattr(agent, "_bound_generation", None)
+ server = bound(base_session_id) if callable(bound) else None
+ if req_info and server is not None:
await server.abort_session(req_info[0], req_info[1])
except Exception: # noqa: BLE001
logger.debug("end: opencode remote abort failed for %s", base_session_id, exc_info=True)
@@ -751,17 +716,24 @@ async def _end_opencode(controller: "Controller", base_session_id: Optional[str]
if any(not request.done() for request in active_requests.values()):
return {"ok": True, "action": "ended", "backend": "opencode", "process_killed": False}
- # The serve process is shared across Sessions. Its existing strict idle
- # retirement checks native requests, durable ownership, and process proof.
- server = getattr(getattr(agent, "_client_manager", None), "_server_manager", None)
- if server is None:
+ # The serve process is shared across Sessions. Retiring the current
+ # generation stops it now when idle; work bound to any generation keeps
+ # that process until the work drains.
+ retire = getattr(agent, "retire_current_generation", None)
+ if not callable(retire):
return {"ok": True, "action": "ended", "backend": "opencode", "process_killed": False}
try:
- await server.retire_for_native_migration()
+ outcome = await retire()
except Exception as exc: # noqa: BLE001
logger.warning("end: opencode idle server retirement failed for %s: %s", base_session_id, exc)
return {"ok": False, "error": "runtime_retirement_failed", "detail": str(exc)}
- return {"ok": True, "action": "ended", "backend": "opencode", "process_killed": True}
+ outcome = getattr(outcome, "value", outcome)
+ if outcome == "failed":
+ # The stop ran and the process survived; its record stays for a retry.
+ return {"ok": False, "error": "runtime_retirement_failed", "detail": "OpenCode server did not exit"}
+ # "draining": a lease or other work still binds the process, which stops
+ # once that drains. Only a confirmed stop reports a killed process.
+ return {"ok": True, "action": "ended", "backend": "opencode", "process_killed": outcome == "stopped"}
async def _settle_workbench_turn(
@@ -1322,12 +1294,19 @@ async def end_running_agent(
if teardown.get("process_killed"):
result["process_killed"] = True
return result
- return stop_result if stop_ok else (teardown if isinstance(teardown, dict) else stop_result)
+ # The turn may be stopped, but the Session still holds its thread
+ # and its row, so End did not finish: report the teardown failure.
+ return teardown if isinstance(teardown, dict) else stop_result
if not stop_ok:
return stop_result
if backend == "opencode":
- await _end_opencode(controller, base_session_id)
+ teardown = await _end_opencode(controller, base_session_id)
+ if isinstance(teardown, dict) and not teardown.get("ok"):
+ # The turn stopped, but the runtime End asked to retire survived.
+ return teardown
+ if isinstance(teardown, dict) and teardown.get("process_killed"):
+ stop_result["process_killed"] = True
elif backend == "claude" and isinstance(claude_pid, int):
# Claude's client is already removed by the stop path (so its row clears,
# and calling _end_claude here would wrongly report ``session_not_live``);
diff --git a/core/session_activities.py b/core/session_activities.py
index 8c4855571..42b521a03 100644
--- a/core/session_activities.py
+++ b/core/session_activities.py
@@ -983,6 +983,30 @@ class SessionActivityRegistry:
def has_active(self, backend: str, runtime_key: str) -> bool:
return bool(self.active_for_runtime(backend, runtime_key))
+ def has_active_for_activation(
+ self, backend: str, activation_identity: RuntimeActivationIdentity
+ ) -> bool:
+ """Whether an active Activity was started under ``activation_identity``."""
+ with self._lock:
+ return any(
+ key[0] == str(backend) and identity is activation_identity
+ for key, identity in self._active_identities.items()
+ )
+
+ def runtime_keys_for_activation(
+ self, backend: str, activation_identity: RuntimeActivationIdentity
+ ) -> set[str]:
+ """The runtime keys holding an Activity or connection under ``activation_identity``."""
+ with self._lock:
+ return {
+ key[1]
+ for key, identity in (
+ *self._active_identities.items(),
+ *self._connection_identities.items(),
+ )
+ if key[0] == str(backend) and identity is activation_identity
+ }
+
def has_blocking_run_activity(self, run_id: str) -> bool:
"""Whether a non-detached active Activity is owned by ``run_id``."""
diff --git a/core/session_turns.py b/core/session_turns.py
index 18663e4c9..b21c857aa 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -43,6 +43,7 @@ from core.native_dispatch_phase import (
from core.run_settlement import (
NON_COMPLETING_TURN_SETTLEMENTS,
SETTLEMENTS_WITHOUT_RESULT,
+ SETTLED_BY_BACKEND_DISABLED,
SETTLED_BY_BACKEND_REFRESH,
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLED_BY_REFUSED_CONCURRENT_TURN,
@@ -4592,7 +4593,8 @@ class SessionTurnManager:
)
abandoned_start = bool(
abandon_unaccepted_start
- and outcome == "failed"
+ # A disable cancels an unresolved start; a refresh fails it.
+ and outcome in {"failed", "canceled"}
and initial_batch
and all(row["state"] == "claimed" for row in initial_batch)
and turn.get("start_receipt_outcome") != "accepted"
@@ -6497,7 +6499,11 @@ class SessionTurnManager:
delivered = await self.controller.emit_agent_message(
context,
"notify",
- i18n_t(message_key, self._controller_language()),
+ i18n_t(
+ message_key,
+ self._controller_language(),
+ agent=i18n_t(f"backend.{backend}", self._controller_language()) if backend else "",
+ ),
# Recovery already settled this Turn. Carry its exact identity
# through delayed sends without granting another settlement or
# guessing the target from the Session's current Turn.
@@ -8081,9 +8087,14 @@ class SessionTurnManager:
*,
backend: str,
base_session_ids: set[str],
+ settled_by: str = SETTLED_BY_BACKEND_REFRESH,
) -> int:
"""Release active Workbench turns whose backend runtime is being refreshed.
+ ``settled_by`` names why: a runtime refresh, the user disabling the
+ backend (``SETTLED_BY_BACKEND_DISABLED``), which also chooses the notice,
+ or the user ending the runtime (``SETTLED_BY_STOPPED``), which needs none.
+
A backend refresh is a terminal runtime event: Codex/OpenCode/Claude cached
process state can disappear underneath a Workbench turn before that turn's
normal result path emits ``turn.end``. The manager owns the Workbench gate,
@@ -8132,14 +8143,14 @@ class SessionTurnManager:
# and needs no refresh notice.
refresh_owns_outcome = not self._turn_outcome_decided(turn)
if refresh_owns_outcome:
- turn.cancel_settled_by = SETTLED_BY_BACKEND_REFRESH
+ turn.cancel_settled_by = settled_by
turn.cancel_defers_queue_resume = True
# The same cause for the Run this Turn's dispatch waits on: a backend
# whose cancellation cleanup releases the waiter itself would
# otherwise report it as a Turn that produced no result.
mark_complete = getattr(self.controller, "mark_turn_complete", None)
if refresh_owns_outcome and callable(mark_complete) and not turn.task.done():
- mark_complete(turn.context, settled_by=SETTLED_BY_BACKEND_REFRESH)
+ mark_complete(turn.context, settled_by=settled_by)
if turn.task.done():
self.in_flight.pop(session_id, None)
from core.inbox_events import bus
@@ -8151,7 +8162,11 @@ class SessionTurnManager:
else:
turn.task.cancel()
tasks_to_settle.append(turn.task)
- if refresh_owns_outcome and not harness_run_identity(turn.context, None):
+ if (
+ refresh_owns_outcome
+ and settled_by != SETTLED_BY_STOPPED
+ and not harness_run_identity(turn.context, None)
+ ):
interrupted_turns.append((session_id, turn))
if backend in self._draining_backends:
self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
@@ -8165,7 +8180,7 @@ class SessionTurnManager:
self.controller.set_agent_status(session_id, "idle")
for session_id, turn in interrupted_turns:
self._notify_backend_refresh(
- session_id, "", turn.logical_turn_id or "", backend, context=turn.context
+ session_id, "", turn.logical_turn_id or "", backend, context=turn.context, settled_by=settled_by
)
released_restored: set[str] = set()
for owner in restored_owners:
@@ -8176,10 +8191,13 @@ class SessionTurnManager:
owned_by_run = bool(self.accepted_agent_run_ids_for_turn(owner_id))
origin_message_id = self._turn_origin_native_message_id(owner_id)
if owner["state"] == "starting":
+ # An unresolved start fails on a refresh, but a disable or an
+ # End is the user's own cancellation, whatever stage the start
+ # reached.
terminal = self._terminalize_durable_turn(
owner_id,
- "failed",
- settled_by=SETTLED_BY_BACKEND_REFRESH,
+ "canceled" if settled_by in (SETTLED_BY_BACKEND_DISABLED, SETTLED_BY_STOPPED) else "failed",
+ settled_by=settled_by,
evidence_kind="backend_refresh_start_failed",
evidence={
"backend": backend,
@@ -8197,14 +8215,17 @@ class SessionTurnManager:
terminal = self._terminalize_durable_turn(
owner_id,
"canceled",
- settled_by=SETTLED_BY_BACKEND_REFRESH,
+ settled_by=settled_by,
evidence_kind="backend_refresh",
)
if terminal.get("changed"):
released_restored.add(str(owner["session_id"]))
- # Starting or active, the refresh retired this conversation's input.
- if not owned_by_run and self.controller is not None:
- self._notify_backend_refresh(str(owner["session_id"]), origin_message_id, owner_id, backend)
+ # Starting or active, the refresh retired this conversation's
+ # input. The user's own stop needs no explanation.
+ if not owned_by_run and self.controller is not None and settled_by != SETTLED_BY_STOPPED:
+ self._notify_backend_refresh(
+ str(owner["session_id"]), origin_message_id, owner_id, backend, settled_by=settled_by
+ )
for session_id in released_restored:
if backend in self._draining_backends:
self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
@@ -8247,17 +8268,23 @@ class SessionTurnManager:
backend: str,
*,
context: "MessageContext | None" = None,
+ settled_by: str = SETTLED_BY_BACKEND_REFRESH,
) -> None:
# Off the teardown's path: a slow platform send must not hold the
# runtime refresh that is waiting on this release. A send that fails is
# held and retried like a service-restart report.
+ message_key = (
+ "turn.interrupted.backendDisabled"
+ if settled_by == SETTLED_BY_BACKEND_DISABLED
+ else "turn.interrupted.backendRefresh"
+ )
asyncio.create_task(
self._report_interrupted_turn(
session_id,
origin_native_message_id,
turn_id,
backend,
- message_key="turn.interrupted.backendRefresh",
+ message_key=message_key,
context=context,
),
name=f"backend-refresh-notice:{session_id}",
diff --git a/docs/CLI.md b/docs/CLI.md
index 48ccda8db..d9ad805d3 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -678,7 +678,7 @@ The web UI (`http://127.0.0.1:5123`) provides the same controls:
| `~/.vibe_remote/runtime/remote-access-cloudflared.pid` | cloudflared tunnel PID for Avibe Cloud remote access |
| `~/.vibe_remote/screenshots/` | Default output directory for `vibe screenshot` |
| `~/.vibe_remote/logs/vibe_remote.log` | Application logs |
-| `~/.vibe_remote/logs/opencode_server.json` | OpenCode server PID file |
+| `~/.vibe_remote/runtime/opencode/generations/` | One record per running OpenCode server generation |
### Migration Backup Lifetime
@@ -701,12 +701,6 @@ covered by this age policy. Restoring a SQLite backup revokes the old expiry
evidence before replacing the live database. Keep a separate manual archive
when recovery must remain possible beyond the automatic rollback window.
-## Environment Variables
-
-| Variable | Description |
-|----------|-------------|
-| `OPENCODE_PORT` | Override OpenCode server port (default: 4096) |
-
## See Also
- [Slack Setup Guide](SLACK_SETUP.md)
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 7593cb2cf..392f35651 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -602,13 +602,7 @@ Web UI (`http://127.0.0.1:5123`) 提供相同的控制功能:
| `~/.vibe_remote/state/task_requests/` | task run 与 hook 的请求队列 |
| `~/.vibe_remote/state/user_preferences.md` | 共享的长期用户偏好笔记 |
| `~/.vibe_remote/logs/vibe_remote.log` | 应用日志 |
-| `~/.vibe_remote/logs/opencode_server.json` | OpenCode 服务器 PID 文件 |
-
-## 环境变量
-
-| 变量 | 说明 |
-|------|------|
-| `OPENCODE_PORT` | 覆盖 OpenCode 服务器端口(默认:4096) |
+| `~/.vibe_remote/runtime/opencode/generations/` | 每个运行中的 OpenCode 服务器代各一条记录 |
## 另请参阅
diff --git a/docs/plans/backend-rolling-restart.md b/docs/plans/backend-rolling-restart.md
index fb2f0eaf6..891029d58 100644
--- a/docs/plans/backend-rolling-restart.md
+++ b/docs/plans/backend-rolling-restart.md
@@ -1,93 +1,36 @@
# Backend Rolling Restart
-## Goal
+Status: superseded by `runtime-generations.md`.
-Restart Claude, Codex, and OpenCode runtime state without destabilizing the
-Avibe service, Web UI, tunnel, or Session context. A restart must never allow
-two turns to work on the same Session concurrently.
+Configuration changes, credential flows, manual Restart, CLI installs, and
+enabling a backend no longer drain or interrupt anything. Each runtime unit
+moves to the new configuration at its next turn, and running work finishes on
+the process it started on. Disabling a backend stops its work at once, because
+the user asked for that. The 300 s drain, its timeout override, and the
+drain-then-interrupt cutover are deleted.
-## Contract
+## What remains of the barrier
-The shared runtime owns a backend restart barrier with four states:
+The backend admission barrier (`begin_backend_drain` / `end_backend_drain`)
+remains for two exclusive operations only:
-`READY -> DRAINING -> SWITCHING -> READY`
+- **Native credential cutover** (`BackendRestartCoordinator.migration_guard`).
+ An explicit user decision moves a native credential, so the guard interrupts
+ the backend's running work and retires its runtime strictly before the move.
+ An old process could otherwise rewrite a credential file while it is moved.
+- **Unattended CLI auto-update** (`run_when_idle`). Admission is closed only
+ while the CLI is replaced, so no turn launches a half-installed binary. The
+ runtime then renews in place.
-- `READY`: new turns may start.
-- `DRAINING`: turns accepted before the barrier continue. New turns wait. A
- Workbench message for a busy Session remains in its durable queue.
-- `SWITCHING`: no new turn can enter while the old runtime is terminated and
- refreshed configuration is activated.
-- `READY`: queued work resumes through the normal Session gate.
-
-The Session FSM remains the authority. A Session changes generation only after
-its active turn reaches IDLE. Stop and send-now use the existing interruption
-path; after the old turn settles, the queued message resumes on the new runtime.
-Backend-native background Activities are a second, orthogonal liveness axis:
-the drain also waits for active Activities and their pending output to settle.
-
-## Why the barrier is shared
-
-Claude, Codex, and OpenCode have different process models, but the safety
-invariants are identical. Keeping the barrier in `AgentService` and the durable
-queue interaction in `SessionTurnManager` avoids backend-specific queue and
-locking rules.
-
-The first implementation uses a single-writer cutover for every backend.
-OpenCode must not run two servers against the same local state concurrently.
-Codex and Claude may later prepare a new generation during DRAINING, but only if
-their adapters can prove isolated ownership. That optimization does not change
-the Session protocol.
-
-Agent CLI install/upgrade jobs measure the CLI selected by the persisted
-`agents.<backend>.cli_path` before and after installation. Only an unchanged
-configured path, resolved target, and known reported version can skip the
-refresh. A changed configured path requires reconciliation even when it resolves
-to the same executable. Missing configuration, paths, or versions conservatively
-retain the existing refresh path. Measurements bypass the UI version cache.
-
-The install worker produces this decision and the existing controller restart
-coordinator remains the sole owner of any required cutover. This optimization
-does not relax the barrier for real upgrades or change manual/auth refreshes.
-
-## Timeout
-
-Draining is bounded. At the deadline, the coordinator:
-
-1. cancels matching Workbench waiters without flushing them onto the old
- runtime;
-2. marks remaining backend Activities killed and settles their owning Runs;
-3. force-refreshes the backend runtime, which terminates the old process tree;
-4. releases stale runtime-turn tokens;
-5. reopens the backend barrier and flushes queued Sessions.
-
-The default drain timeout is five minutes and can be overridden for operations
-and tests with `AVIBE_BACKEND_RESTART_DRAIN_TIMEOUT_SECONDS`.
-
-## Invariants
+These invariants still hold for both:
- At most one active turn per Session and runtime key.
-- Restart coordination never stops the Avibe service, UI, or tunnel.
-- A failed refresh reopens the barrier; it cannot deadlock future turns.
-- Concurrent restart requests for one backend coalesce into one operation.
-- Queue rows are claimed only by the existing Session queue transaction.
-- Old-turn completion and timeout force-cutover are idempotent races.
-
-## Scenarios
-
-- `BRR-001`: idle backend refreshes immediately and accepts the next turn.
-- `BRR-002`: active Session drains; its new message remains queued until IDLE.
-- `BRR-003`: another Session cannot enter the switching window.
-- `BRR-004`: Stop/send-now settles the old turn and advances cutover.
-- `BRR-005`: drain timeout cancels the old waiter, force-refreshes, then flushes.
-- `BRR-006`: refresh failure reopens the barrier and preserves queued input.
-- `BRR-007`: concurrent restart requests coalesce without duplicate process kills.
-- `BRR-008`: backend restart does not touch service, UI, or tunnel lifecycle.
+- The barrier never stops the Avibe service, UI, or tunnel.
+- A failed operation reopens the barrier and preserves queued input.
## Service restart boundary
-This protocol is also the prerequisite for a future service-process handoff,
-but it does not claim that a SIGTERM of the current Avibe process can preserve
-an in-memory receiver. A true service rolling restart additionally needs an
-external supervisor and cross-process ownership handoff. Until that exists,
-backend restarts use this protocol; service restart remains crash-recovery
+A SIGTERM of the Avibe process cannot preserve an in-memory receiver. A true
+service rolling restart would need an external supervisor and a cross-process
+ownership handoff. Until that exists, a service restart keeps crash-recovery
semantics and must not pretend to be seamless.
diff --git a/docs/plans/runtime-generations-codex.md b/docs/plans/runtime-generations-codex.md
new file mode 100644
index 000000000..8da0a2e74
--- /dev/null
+++ b/docs/plans/runtime-generations-codex.md
@@ -0,0 +1,387 @@
+# Runtime Generations: Codex Adapter
+
+Status: implemented on the Codex lane of `runtime-generations.md`, on the
+shared core of `modules/agents/runtime_generations.py`. The owner decisions
+recorded in that document are binding here.
+
+## Verification gate (done)
+
+Hermetic probe environment:
+
+- `codex-cli 0.159.3`, running under a `sandbox-exec` wrapper that allows
+ loopback egress only, using the repository `CodexTransport`;
+- temporary `HOME`, `CODEX_HOME`, and `TMPDIR`;
+- `tests/e2e/drivers/mock_llm_upstream.py` serving the Responses API, configured
+ as a `model_providers` entry in a temporary `config.toml`.
+
+All scratch was deleted afterwards.
+
+| Check | Result |
+| --- | --- |
+| (a) Two app-servers in one cwd | Pass. Both initialize. Concurrent turns on different threads, one per server, both complete. |
+| (b) Resume on B while A is alive | Fails as written. Codex holds a cross-process writer lock: an OS file lock on `$CODEX_HOME/thread-writer-locks/<thread>.lock`, implemented in `codex-rs/rollout/src/writer_lock.rs`. While A has the thread loaded, even idle, B's `thread/resume` returns `-32600 "thread … already has an active writer"`. |
+| (b') Release lever | `thread/unsubscribe` on A returns `unsubscribed`. Once a thread has no subscriber and is idle, A unloads it after `thread_unload_delay_secs` (default 60; see `app-server/src/request_processors/thread_lifecycle.rs`), emits `thread/closed`, and drops the lock. Measured: 60.02 s at the default, 0.05 s with `-c thread_unload_delay_secs=0`. B then resumes while A stays alive, and B's next upstream request carries A's turn history. A later stray `turn/start` on A fails with `thread not found`. |
+| (b'') Release by exit | EOF, SIGTERM, or SIGKILL of A's process tree releases the lock. After SIGKILL a stale `.lock` file remains, but the OS lock is gone and B resumes. |
+| (c) A's shutdown appends nothing | Pass in every variant: unsubscribe with delay 0 then EOF or SIGTERM; unsubscribe at the default delay then EOF; no unsubscribe then EOF, SIGTERM, or SIGKILL. The rollout's size and sha256 are identical before and after both A's unload and A's exit. A's exit changes only its own lock and tmp files in `CODEX_HOME`; the SQLite WAL files are unchanged. A fresh server later reads every turn as completed, with all user texts in order. |
+| (d) `thread/read` and `thread/fork` on B while A holds the source | Both work, whether the source is idle or has an active turn. Neither touches the source rollout. |
+| (e) Cross-process read of a live turn | B reports A's in-progress turn as `interrupted`, never as `inProgress`. |
+| (f) Unsubscribe during an active turn | Codex defers the unload until the turn ends. Our connection stops receiving that turn's notifications, so `turn/completed` never arrives. When the turn ends, the thread unloads and `thread/closed` is delivered. |
+
+Consequences:
+
+1. **A thread moves only after its old generation releases it.** The release
+ is `thread/unsubscribe` followed by `thread/closed`, or the old process
+ having exited. Every Codex app-server launches with
+ `thread_unload_delay_secs=0`. Avibe never unsubscribes a thread it still
+ routes to, so the setting changes nothing else.
+2. **Never unsubscribe a thread whose turn Avibe still needs to observe** (f).
+ When a move follows an interrupt, Avibe settles the interrupted request
+ itself.
+3. **Live-turn reads must go to the generation running the turn** (e). This
+ matters for the fork boundary read.
+4. Codex's own lock makes a misroute fail loudly (`active writer` or
+ `thread not found`) rather than corrupt a rollout.
+
+## Model
+
+`modules/agents/codex/agent.py` keeps one `RuntimeGenerationSet` per working
+directory (`_units[cwd]`). Each generation wraps one `_CodexRuntime`:
+
+| Field | Meaning |
+| --- | --- |
+| `transport` | the app-server process |
+| `hub` | it holds the directory's Model Hub gateway credential |
+| `activation` | its own `RuntimeActivationIdentity`, key `"{cwd}#{serial}"` |
+| `threads` | base session id → the Codex thread loaded in this process |
+| `released_threads` | thread id → set on `thread/closed` |
+| `last_activity` | idle-eviction clock |
+| `ended` | the process is gone (the core detaches a generation before its teardown, and a graceful teardown may still decline) |
+
+`_session_generations[base_session_id]` names the generation holding each
+Session's thread. `_session_mgr.get_thread_id(bid)` is set only while that
+thread is loaded there.
+
+A live binding has exactly two owners, because Codex lets one process at a
+time hold a thread:
+
+- the process ending (`_forget_runtime_sessions`);
+- the thread's release (`_release_session_thread`).
+
+Every other path uses `_forget_stale_session`, which clears only thread ids
+that no live process holds:
+
+- the bulk refresh, migration, and resume paths;
+- `/new`, through `clear_sessions`, which first releases each live thread.
+
+A Session whose process survived a failed stop therefore stays bound to it. Every
+per-Session path routes through this binding: `handle_stop`,
+`steer_active_turn`, `reconcile_steer_attempt`, liveness capture, activation
+lookup, and notification filtering. `_runtimes[cwd]` tracks every process not
+yet ended, attached to its unit or not, for Hub scope decisions and shutdown.
+
+### Launch spec
+
+`CodexLaunchSpec.digest` hashes the exact process inputs, so two generations
+with equal digests are interchangeable:
+
+```text
+sha256({
+ "epoch": renewal_epoch,
+ "binary": {configured, realpath, [st_dev, st_ino, st_size, st_mtime_ns]},
+ "argv": hub_overrides + extra_args, # gateway URL
+ "catalog": content-addressed catalog path,
+ "env": sha256(sorted launch env), # managed PATH, AVIBE_MODEL_HUB_TOKEN, CODEX_HOME
+ "credential": codex_credential_identity(CODEX_HOME),
+ "cwd": [cwd, inode(cwd)],
+})
+```
+
+- **Binary identity.** This is the resolved path and its stat signature; no
+ version probe runs. Every install path replaces the file: npm wrote new
+ inodes and install-time mtimes for `codex.js` and `package.json`. So the
+ signature changes on every upgrade or reinstall, including one made outside
+ Avibe, and no turn pays for a `--version` subprocess.
+- **Credential identity** (`vibe/codex_config.py`). This is the effective
+ credential store, the auth mode, the API key digest, and the ChatGPT
+ `account_id`. Tokens are excluded: a running app-server reloads its
+ credential store itself on a 401 for the same account
+ (`UnauthorizedRecovery` in `codex-rs/login`). So only an account, key, mode,
+ or sign-in change needs a new process. Only `auth.json` is read. With the
+ `keyring` or `auto` store, Codex may keep the credential in the OS keyring
+ (`Direct`, the default off Windows) or in `secrets/codex_auth.age` with its
+ key in the keyring (`Secrets`, the Windows default). Avibe never reads
+ either, so a change made there outside Avibe is adopted at the next renewal.
+ Avibe's own sign-in renews, and an API key Avibe writes pins the file store.
+- `config.toml` is not a process input: app-server reloads it for every
+ `thread/start` and `thread/resume`.
+- **Excluded inputs.** `auth_mode` (unused), `idle_timeout_seconds` (read
+ live), and every per-turn input.
+- `direct` and `native_cli` launches have identical inputs, so they share a
+ generation.
+- The spec carries the binary, argv, environment, and a catalog pin. `start`
+ uses only these values, so nothing re-reads the configuration between the
+ resolution and the launch.
+
+The Hub catalog comes from the turn's `ModelHubRuntimeRouter.snapshot()`, the
+same load the launch resolution used. It is cached by `(binary identity,
+models digest)`, with the two most recent entries kept. Each Hub generation
+holds its own pin while it runs.
+
+A turn's whole configuration is one load, taken in one synchronous step at
+admission, before anything awaits (`_launch_inputs`): the Model Hub snapshot,
+the Codex config's binary and extra arguments, the runtime environment, the
+renewal epoch, and the binary, credential, and cwd identities. The Hub launch
+resolution, catalog preparation, the spec digest, acquisition, and a failure
+retry all use only that load, so a save or renewal that lands while any of them
+is awaited changes nothing about the turn; the directory's next turn moves
+(RUNTIME-GEN-015). The turn's shell environment builds on the environment its
+app-server was launched with, never on the current config. A probe takes its
+own load the same way, at its own start.
+
+## Lifecycle invariants
+
+Every transition below was audited against each invariant, by the adapter
+author and two independent reviewers.
+
+| Invariant | Rule | Owner |
+| --- | --- | --- |
+| Binding | A live Session binding is dropped only by its process ending or by a proven release. Every other path forgets only bindings whose process is gone. | `_forget_runtime_sessions`, `_release_session_thread`, `_forget_stale_session` |
+| Release proof | A thread loads elsewhere only after `thread/closed`, `notLoaded`, absence from `thread/loaded/list`, or the old process's exit by return code. Anything less raises `CodexThreadReleaseUnavailableError` and changes nothing; every caller propagates it. | `_release_session_thread` |
+| Settlement | Every adapter-initiated kill of a process with bound work settles that work (turns and every bound Session's Activities) with its reason (the runtime-update notice, or a disable's), and only that work: turns running when settlement begins that still own their gate, and Activities started by this agent's own generations. | `_end_bound_work` via `_stop_runtime(settle_reason=)`, `force_end_runtime_work` |
+| Fence | Once a teardown begins, no durable owner commits to its generation: the retirement is reserved before the final drained check, settlement, and stop, and aborted when any of them declines or fails. | `_stop_runtime` |
+| Hub scope | The gateway credential is revoked exactly when this agent's last Hub process in the directory is gone, a starting or failed-start one included; another agent instance's processes never share it. | `_runtimes`, `_retire_hub_scope_after` |
+| Per generation | A decision about a generation reads only its own Sessions, turns, bindings, and process. | admission, drained check, eviction, End |
+| Session serialization | Turn admission, End, `/new`, and resume preparation run under the Session's lifecycle lock. | `session_lifecycle` |
+| Spec identity | Equal digests are interchangeable processes; the credential identity covers the file store only, and names an account by its ChatGPT account id or, in an older bag without one, by its id_token subject or email, never by a token. | `_launch_spec_digest`, `codex_credential_identity` |
+| Eventual teardown | Every started process is eventually stopped: drained retiring ones, the cap's victim, failed starts, and survivors of a failed or cancelled stop. | core reconciler, sweep, `_readopt` |
+
+Two documented exceptions: shutdown ends processes without the
+runtime-update notice, and a process ending unbinds its Sessions without their
+locks. That unbinding is synchronous and checks generation identity, so it
+never drops a binding that already moved; taking Session locks in the
+reconciler would deadlock against failure replacement, which waits for the
+reconciler while holding one.
+
+## Turn admission
+
+Under the Session lock, `handle_message`:
+
+1. takes the router snapshot and resolves the launch from it;
+2. builds the spec;
+3. retires every unusable attached generation, then calls `unit.acquire(spec)`,
+ and checks the acquired process again, since it may have died while the
+ spec was prepared;
+4. keeps that binding until the turn is registered or has failed;
+5. if the Session's thread is loaded in another generation, moves it there
+ (`_move_session_to`).
+
+The move, `_release_session_thread`, is the one release primitive. It returns
+only on proof of release; anything less raises
+`CodexThreadReleaseUnavailableError`, a visible failure with the input held for
+an explicit retry, and leaves the binding in place:
+
+- If that process is being torn down, wait for the teardown: its exit releases
+ the thread, and the Session's next turn cannot be among the work the
+ teardown settles.
+- If the Session's own turn is still running there, interrupt it. Only an
+ accepted interrupt, or a turn or process that already ended, lets the move
+ go on; the interrupted request is then settled locally, because
+ unsubscribing ends this connection's view of that turn. A refused interrupt
+ changes nothing.
+- Send `thread/unsubscribe`, then wait for `thread/closed` from that process,
+ bounded at 15 s.
+- On a timeout, `thread/loaded/list` decides. A thread still loaded fails the
+ move.
+- The process's exit, by its return code, counts as released. A closed stdout
+ reader does not: the child can outlive it and keep the writer lock, so the
+ move waits for the exit within the same bound.
+
+The turn then resumes, starts, or forks its thread through
+`_open_session_thread`, which binds whatever thread ended up loaded. A resume
+claims its thread in the target process before the RPC, so one whose answer is
+lost is still released there before any other process resumes it. A new or
+forked thread is persisted before the Session uses it, so a failed write never
+leaves a conversation out of resume history.
+
+A cancelled admission clears its pending turn start, so it never pins its
+generation.
+
+Notifications arrive per generation. `thread/closed` resolves a pending
+release. A thread-level event without a turn id is dropped when its Session is
+no longer bound to the emitting generation. A turn that completes on a
+non-current generation schedules a reap.
+
+The fork boundary is read through the generation that holds the source thread
+while that process runs, even if it stopped answering: reading it then fails
+closed, while any other process reports a live turn as `interrupted`. Fork
+metadata names the durable source Session, not its base session.
+
+## Stop and reap
+
+`stop(generation, force) -> bool` is the only teardown hook, and the core's
+reconciler is its only caller:
+
+- A **graceful** stop declines while `_generation_drained` is false. That is
+ the case while a bound Session has a live turn on a running process, or while
+ the ownership snapshot blocks replacement:
+ - `blocks_transport_replacement` for a running process;
+ - `blocks_dead_transport_replacement` for one that exited.
+
+ Drained is decided twice: once outside the fence, so a busy generation never
+ blocks admissions, and again inside it before the stop.
+- A **forced** stop at the cap settles the generation's work through
+ `_end_bound_work`, then ends the process. `force_end_runtime_work` captures
+ the exact turns before its first await, so a Session's next turn, admitted
+ while the settlement runs and waiting for the teardown, is never cancelled
+ with them. A registered turn whose gate a later turn already took, such as
+ one the liveness monitor settled after the reader closed, is not settled
+ again. A process whose reader closed while the child runs can never
+ report its work again, so it is stopped the same way. Shutdown ends
+ processes without the notice.
+- `_stop_runtime` owns the fence. Only after a successful stop are the
+ generation's Sessions unbound and its Hub scope revisited.
+
+Ownership targets: the current generation answers for every durable Session in
+its directory, as before. A detached or retiring generation answers only for
+the Sessions it still holds.
+
+Reap triggers:
+
+- the controller sweep (`reap_runtime_generations`, every 60 s), which also
+ retires processes that exited or stopped answering and retries the stop of a
+ child that outlived its own failed start;
+- a turn completing on a non-current generation;
+- a Session moving off a generation;
+- the release of the last binding.
+
+Idle eviction judges each generation only by the Sessions whose threads it
+holds. The current generation keeps the idle timeout and the two ownership
+snapshots, then calls `unit.retire` and waits for `unit.settled()`. The
+stuck-active backstop applies to every generation: it settles only the exact
+stuck turn, under the Session's lifecycle and after the terminal emission, and
+then retires that generation, so a native turn that may still run ends with
+its process once its neighbours finish.
+
+Native-credential migration, End, and the exclusive refresh need processes gone
+outside the core's own decisions. They use `_stop_generations_now`:
+
+- After the final synchronous check, it detaches every selected generation
+ before the first stop awaits. A turn arriving meanwhile starts its own
+ generation and cannot bind to one about to be killed.
+- End settles through `_end_bound_work`. Migration and the exclusive refresh
+ pass `settle=False`, because `migration_guard` and the coordinator already
+ settled the backend.
+- A generation whose stop fails, or that a cancellation left unstopped, is
+ adopted back as retiring with its Sessions still bound, so a later call or
+ sweep can retry.
+
+Failure replacement instead releases its own binding and retires the broken
+generation, which is atomic with admission. The process then stops only
+through the drained check, so a neighbour's running turn is never killed.
+
+## End, `/new`, and resume
+
+`end_session` owns End from Running Agents, under the Session's lifecycle:
+
+- It acts on the directory whose app-server holds the Session's thread, not on
+ the Session's configured working directory.
+- If no other Session is bound to that directory's processes, they stop, and
+ the ending Session's own turn and Activities settle first.
+- Otherwise only its thread is released, which interrupts its own turn first
+ and fails rather than forget a turn Codex did not stop. That includes a
+ process the reconciler already detached: its stop may still decline, so End
+ waits out that teardown and proves the release instead of killing it.
+- Its state is cleared only after that succeeded, so a failed End stays
+ retryable; Running Agents reports the failure even after a successful
+ canonical stop.
+
+`clear_sessions` (`/new`) holds every cleared Session's lifecycle, releases
+each thread first, and clears the durable and in-memory mappings only after
+every release succeeded. Those mappings are cleared per session key, so a
+Session of that key that started meanwhile is locked and released too before
+anything is cleared. `prepare_resume_binding` releases the thread under the
+lifecycle; the core rewrites the mapping right after, with no await between.
+
+## Model Hub gateway scope
+
+All Hub generations of a directory share its request-scoped gateway
+credential. Per-turn routes ride on `responsesapiClientMetadata`. The scope is
+retired only when the directory's last Hub process ends.
+
+The scope belongs to one agent instance (`<cwd>#<instance>`), and so does each
+generation's activation and ownership key (`<cwd>#<instance>.<serial>`): a
+re-enabled agent numbers its generations from 1 again while a disabled agent's
+retried teardown may still reserve its own. Any failure after a spawn, in the
+start itself or in the setup that follows it, leaves the process marked for
+the sweep. A disable whose
+teardown failed keeps the old agent's processes until the idle sweep's retry
+stops them, while a re-enabled agent already runs its own in the same
+directory. The old agent revoking its scope with its last Hub process therefore
+never revokes the credential the new agent's processes hold (RUNTIME-GEN-016).
+
+## Triggers
+
+| Hook | Behavior |
+| --- | --- |
+| `renew_runtime(config, config_save=False)` | Adopts the config. A plain `agents.*` save (`config_save=True`) needs nothing more, because the binary and extra arguments are already spec inputs. Every other caller bumps the renewal epoch. Nothing stops or waits. |
+| `adopt_model_hub_catalog()` | Drops the prepared catalogs; the next Hub turn prepares from its own snapshot. |
+| Hub/Direct mode switch | The core commits the mode and calls `adopt_model_hub_catalog()`. The mode decides the turn's launch, so it is a spec change: the next turn starts on a process for the new mode, while a running Hub turn finishes on its own process and keeps the gateway credential until it ends (RUNTIME-GEN-016). |
+| `shutdown_runtime(settle_reason=None)` | Service shutdown, probe teardown, and disabling the backend. A disable passes `settle_reason="backend_disabled"`: every forced stop then settles the turns and Activities bound to its generation with that reason before it kills the process, so this agent's work is settled even when the core's own interrupt failed. Activities are ended by the stopping generation's activation identity, never by runtime key or bound Session, because after a re-enable a new agent can run the same Session in the same directory under the same key, and an Activity can outlive its turn or its Session's thread move; turns settle only while they still own their gate. Service shutdown and probe teardown pass no reason and show no notice. A turn that captured the agent before the routing change fails visibly with `error.agentRuntimeRetired` and starts no process (RUNTIME-GEN-006). It raises while any app-server survives; a Session bound to a survivor keeps its state, so the retried teardown settles whatever is still bound and stops it. Re-enabling constructs a new agent. |
+| `refresh_runtime_config` / `refresh_auth_state` | Kept only for the exclusive `migration_guard` cutover: stop every generation. |
+| `retire_for_native_migration` | Refuses while any generation is bound or not drained; otherwise ends every process and requires it to exit. |
+| `prepare_resume_binding` | Releases only the resumed Session's thread; the process keeps serving others. |
+| `end_session` (End) | See End above. |
+| `probe_connection` | Binds, never acquires, a live generation whose spec equals the current direct spec. The probe never promotes a generation or starts one in a working directory. |
+
+## Deleted
+
+- The 30 s runtime-change wait, `CodexRuntimeChangeBlockedError`, and
+ `error.codexRuntimeChangeBlocked`.
+- `_interrupt_active_turn_before_runtime_change`. Its local settle step lives
+ on in the move.
+- `CodexTransport.runtime_fingerprint` and every fingerprint comparison.
+- `_get_or_create_transport`, the per-cwd lock, activity, and inode maps, the
+ stale-cwd branch, and the probe-cwd counter.
+- The single-slot catalog cache and `invalidate_model_hub_runtime`.
+- The dead `_is_transport_evictable`.
+
+## Defects fixed
+
+| ID | Defect | Pre-fix failure |
+| --- | --- | --- |
+| RUNTIME-GEN-010 | A busy directory held a new turn on a new spec | 30 s wait, then `CodexRuntimeChangeBlockedError` |
+| RUNTIME-GEN-012 | A busy Session's own turn was interrupted before the replacement was known to proceed, so both turns were lost while a neighbour ran | interrupted, then refused |
+| RUNTIME-GEN-014 | A direct launch with Model Hub enabled lost the desktop-managed environment: `build_codex_hub_launch` answers `None` for a non-Hub channel, and the adapter used that as the environment | `env=None` |
+| RUNTIME-GEN-015 | Identical `direct` and `native_cli` launches replaced each other | two processes |
+
+These four were run against the base adapter with one harness built through
+the real `__init__`. They fail there for the reasons above and pass here.
+RUNTIME-GEN-011, 013, and 016–018 cover behaviour that only exists with
+generations. RUNTIME-GEN-019 is the opt-in real-binary contract
+(`-m e2e_model_hub`).
+
+## Open risks
+
+- **Version window.** The writer lock and `thread/unsubscribe` were verified
+ on codex-cli 0.159.3, and RUNTIME-GEN-019 guards upgrades.
+ - A Codex without the lock resumes freely.
+ - One without `thread/unsubscribe` fails the move with the held-input error
+ until its old process ends.
+- **No eager pre-start.** A directory has no single desired spec when its
+ Sessions use different channels, so a new spec pays about one app-server
+ start at its next turn.
+- **Pre-existing race.** A turn can resolve its Hub token just before the
+ directory's last Hub process retires the scope. It then fails visibly, as it
+ did before.
+- **Core resume order.** Resume sends its confirmation and commits channel
+ routing before the backend prepares, so a thread that stays loaded shows the
+ confirmation and then the failure.
+- **Survivors of a failed stop.** The exclusive refresh logs a stop failure
+ and goes on; the survivor is uninitialized, so it is retired and reaped, and
+ migration's exit check backstops it. Shutdown drops the Session bindings of
+ a process that survived both stop attempts, then raises, so a disable's
+ teardown is kept and retried on every idle sweep until the process is gone
+ (RUNTIME-GEN-006).
+- **Untracked writers.** A thread still held by a process Avibe does not track,
+ such as a wedged child of an earlier controller, fails its resume as
+ unavailable rather than as held.
diff --git a/docs/plans/runtime-generations-opencode.md b/docs/plans/runtime-generations-opencode.md
new file mode 100644
index 000000000..e1af8c019
--- /dev/null
+++ b/docs/plans/runtime-generations-opencode.md
@@ -0,0 +1,792 @@
+# OpenCode on Runtime Generations: Adapter Design
+
+Status: implemented on the core contract at 32f655d2e. The sections below
+are the Phase 1 design. Their line references are to
+`refactor/runtime-generations` at 1eec27fab.
+
+## How the implementation differs from the Phase 1 design
+
+- The adapter's generation set is `OpenCodeRuntime` in `client_manager.py`.
+- The core has no idle hook. `stop(generation, force)` declines a graceful
+ stop while the process still has requests in flight or native run markers.
+ The set then retries it on the next release or sweep.
+- Leases are core bindings plus an adapter timer. Their expiry is persisted
+ in the generation record. A release is routed by lease id to the runtime
+ holding the lease, even after a disabled backend's agent was unregistered
+ while that lease drains. Only a lease that no runtime has adopted yet goes
+ to the registered agent, which adopts it first. Each lease's TTL covers the
+ longest its holder may legitimately need. For the provider probe, that is
+ the directory-bootstrap ceiling plus the probe's own timeout.
+- Adoption keeps the newest adopted generation whose recorded digest equals
+ the current spec as current. Every other adopted generation retires and
+ stops once its restored work drains.
+- `renew_runtime(config, config_save=True)` renews nothing. Every
+ `agents.opencode` field is read per turn except the CLI path, and the CLI
+ path's binary identity is already a spec input. Credential flows, manual
+ Restart, and installs bump the renewal epoch.
+- A forced refresh cancels running work and retires every generation. This is
+ the coordinator's interrupt path, kept until it is deleted.
+- Adoption skips generations that a runtime of this controller process is
+ starting or has attached. Those belong to the runtime of an OpenCode backend
+ that was disabled and enabled again, and that runtime stops them itself. The
+ process keeps this ownership in memory, marking an adopted generation only
+ once a runtime attaches it, so an adoption cut short leaves the rest to its
+ retry. The record has no `owner_pid`, and adoption writes nothing except the
+ conversion of a legacy record. Adoption applies resource governance to each
+ adopted generation, as a start does.
+- Disabling OpenCode is the user's own interruption (owner decision,
+ 2026-10-03). The core interrupts the backend's turns and Activities with the
+ disabled notice, unregisters the agent, and awaits
+ `shutdown_runtime(settle_reason="backend_disabled")`. That call stops every
+ generation at once with a forced `stop_all`, and each forced stop settles
+ the work bound to its process with that reason. The core's backend-wide
+ interrupt is only the fast path: it may fail, and a retry after OpenCode is
+ enabled again skips it, so the adapter's own settlement is the guaranteed
+ one. A turn that raced the disable fails with the localized
+ `error.agentRuntimeRetired`. Re-enabling builds a new agent. Every other
+ configuration change still renews in place without interrupting anything.
+- A controller that starts with OpenCode disabled stops the servers a crashed
+ controller recorded, through `stop_recorded_servers_sync()`, the same
+ function as `vibe stop`. It honors ownership here, process identity, and the
+ desktop foreign-Runtime refusal. Their durable polls stay durable until
+ OpenCode is enabled again.
+- A UI lease release reaches the runtime holding the lease, even after its
+ agent was unregistered, or else the registered agent, which adopts first.
+- Explicit shutdown stops only the generations a runtime of this controller
+ started or adopted (`stop_owned_generations_sync()`). Another desktop
+ Runtime's generations, sharing this state directory, keep running.
+- Bindings, and so leases, count as active runtime work, so maintenance such as
+ a CLI replacement waits for a leased sequence between its requests.
+- Work outside a turn (`current_server()` and UI leases) is admitted the way a
+ turn is. It waits while a native migration drains the backend, and counts as
+ active until it is bound.
+- A restored poll bound to a generation other than the one it names is
+ rewritten to name the generation it is bound to.
+- See section 12 for the lifecycle invariants and the audit.
+- A record that cannot be parsed is kept and never counted as dead. Its
+ process may still run on a port that nothing else records.
+- A failed record write never leaves a record protecting less than its process
+ runs. A run marker or lease is persisted before its work starts. A turn
+ clears its run marker together with its durable poll, so when the write
+ fails both stay and a later restore retries. Any other change that only
+ releases protection takes effect at once. If its write fails, the record
+ stays stale until the next sweep rewrites it. A crash before that sweep only
+ keeps the process until the stale lease expires, or until adoption drops a
+ marker that no durable poll backs.
+- `vibe stop` forgets every record whose process already ended, with its
+ overlay copy, as shutdown and adoption do.
+- The renewal epoch is persisted under `runtime/opencode/renew_epoch`. A
+ generation retired by a renewal therefore never serves again after a crash.
+- Readiness and adoption accept a listener that is the spawned process or one
+ of its descendants, as with npm shims and Windows `.cmd` wrappers.
+- The two-version gate in section 11 passed (RUNTIME-GEN-OBS-020), so a
+ version change can coexist.
+- Status, abort, and prompts are confirmed to be per process
+ (RUNTIME-GEN-OBS-021).
+
+## Worked example
+
+A user replaces the `openrouter` API key in Settings while session `S1` runs a
+long OpenCode turn on generation `G1`.
+
+1. The save writes `~/.config/opencode/opencode.json` and signals the
+ controller, which advances the snapshot. Nothing stops.
+2. `S2` sends a message. Its turn computes the launch spec. The user-config
+ digest differs from `G1`'s, and `S1` is bound to `G1`. The core therefore
+ starts `G2` on a new port (serialized), marks `G1` retiring, and binds `S2`
+ to `G2`.
+3. Every call for `S2`'s run goes to `G2`'s port: prompt, status polls,
+ steering, and abort. `S1`'s calls keep going to `G1`'s port. Both processes
+ write the one SQLite database.
+4. `S1`'s turn ends. Its run marker is cleared in `G1`'s record and its binding
+ is released. `G1` is now idle and retiring, so it is stopped: the process
+ tree is killed and the record deleted.
+5. `S1`'s next turn binds to `G2` and continues the same native session from
+ the shared database.
+
+## Facts this design relies on
+
+- Verified by the orchestrator: two servers can share one OpenCode home. This
+ covers the WAL database, cross-server continuation, and concurrent prompts.
+ Simultaneous fresh starts fail with `database is locked`.
+- Verified here (hermetic probe, OpenCode 1.18.33, temporary `HOME` and XDG
+ directories): `opencode serve --port=0` listens on the default 4096, not on
+ an ephemeral port. Avibe must choose each port itself.
+- Verified here: a second `opencode serve` on a port that is already taken
+ exits at once with `ServeError`, and the first stays healthy. A health probe
+ on that port right after a spawn can therefore be answered by the other
+ process.
+- Verified here: on macOS, psutil 7.2.2 `Process.net_connections()` proves
+ that a same-user process is listening on a port.
+- From the code: the adapter has no SSE event stream. Live turns and restored
+ polls poll over HTTP through the server object they are handed
+ (`agent.py:1869-1881`, `agent.py:3027`, `poll_loop.py:922`). "Per-generation
+ event streams" therefore means handing each poll its own generation.
+- Assumed, not probed: `/session/status`, abort, and `prompt_async` act on
+ each process's in-memory run state, while sessions and messages live in the
+ shared database. The design does not depend on this, because every call for
+ a live run goes to that run's generation.
+
+## 1. Objects
+
+### `OpenCodeServerClient` (`server.py`)
+
+The HTTP surface for one base URL. It holds everything at
+`server.py:2206-2873`:
+
+- directory readiness and sessions;
+- prompts, messages, status, and abort;
+- catalogs, auth, and OAuth;
+- diagnostics and the config readers.
+
+It also holds the loop-aware HTTP session (`server.py:516-548`). It is built
+from `base_url`, `request_timeout_seconds`, and `model_hub_provider_ids`
+(which feed `_public_opencode_catalog`). It owns no process and has no
+`ensure_running`. The UI process uses it directly with a leased URL.
+
+### `OpenCodeGeneration(OpenCodeServerClient)` (`server.py`)
+
+One `opencode serve` process. Its state:
+
+- identity: `generation_id`, `pid`, `process_created_at`, `port`;
+- launch: `spec` (digest and a non-secret summary), `record_path`, and
+ `caller_context_path`;
+- work: `active_run_sessions`, the in-flight request count, and persisted
+ leases;
+- the activation `identity`;
+- `_process` when this controller started it;
+- the observed-exit state for resource diagnostics, moved from
+ `server.py:306-380`.
+
+Its methods:
+
+- `mark_run_active` / `mark_run_inactive`: the record read-modify-write from
+ `server.py:1006-1049` and `1125-1165`, without the overlay-reservation
+ parameter;
+- `request_scope`: the counter from `server.py:1051-1061`, without the
+ pending-restart branch.
+
+It subclasses the client, so every consumer that takes a "server" keeps
+working unchanged:
+
+- `_SteeringAwareOpenCodeServer` (`agent.py:189-707`);
+- the poll loop;
+- `OpenCodeSessionManager` (`session.py:212`, `338`, `407`, `448`).
+
+### `OpenCodeGenerations` (`client_manager.py`)
+
+This replaces `OpenCodeClientManager` (`client_manager.py:1-55`). It is the
+adapter half of the core generation set for the single unit
+`opencode:instance`:
+
+- `launch_spec(snapshot) -> OpenCodeLaunchSpec` (section 5);
+- `start_generation(spec) -> OpenCodeGeneration` (section 2.3);
+- `stop_generation(generation, force)` and `generation_idle(generation)`
+ (section 4);
+- `can_coexist = True`;
+- `adopt_recorded()` (section 2.2), `generation(id)`, and `generations()`.
+
+## 2. Processes and records
+
+### 2.1 Generation record
+
+Each record lives at
+`paths.get_runtime_dir() / "opencode" / "generations" / f"{generation_id}.json"`
+and is written with `write_atomic` (mode 0600).
+
+```json
+{
+ "schema": 1,
+ "generation_id": "ocg_<16 hex>",
+ "pid": 123,
+ "process_created_at": 1790000000.12,
+ "host": "127.0.0.1",
+ "port": 52123,
+ "started_at": 1790000000.0,
+ "spec_digest": "<sha256>",
+ "binary": {"path": "/abs/opencode", "version": "1.18.33"},
+ "caller_context_path": "/abs/runtime/opencode_caller_context.json",
+ "model_hub_overlay_hash": "<sha256> | null",
+ "model_hub_overlay_provider_ids": ["..."],
+ "active_run_sessions": ["ses_..."],
+ "leases": {"lease_id": 1790000960.0}
+}
+```
+
+- The record is written right after spawn, as `_write_pid_file` is today
+ (`server.py:2052-2056`). A crash during start therefore leaves a record that
+ adoption cleans up.
+- Run-marker and lease changes update it under the generation's own lock.
+- It is deleted only after the process is proven gone.
+
+### 2.2 Adoption after a controller restart
+
+`adopt_recorded()` runs once, lazily, before whichever comes first of the
+first acquire, `restore_active_polls`, `prepare_runtime_restart`, or an
+ownership snapshot. For each record:
+
+1. **Prove ownership.** The pid is alive, and `runtime.process_create_time(pid)`
+ equals `process_created_at` (today's `_pid_file_proves_owned_server`,
+ `server.py:382-393`). The command line is `opencode serve ... --port=<port>`
+ (`server.py:1566-1569`).
+2. **Check health and the port.** `/global/health` answers on the recorded
+ port, and psutil shows this pid listening on it. This replaces the
+ Linux-only `/proc` walk at `server.py:1572-1616`.
+3. **Proven and healthy:** adopt it with its recorded spec and attach an
+ activation identity. Reconcile `active_run_sessions` against the durable
+ active polls that name this generation. This generalizes
+ `server.py:735-780`.
+4. **Proven but unhealthy:** terminate its tree (`server.py:1701-1793`) and
+ delete the record, as `_cleanup_orphaned_managed_server` does today
+ (`server.py:1833-1846`).
+5. **Not proven** (dead or reused pid): delete the record and never send a
+ signal.
+
+An adopted generation becomes current only when an acquire's desired spec
+equals its spec. The newest match wins, and every other adopted generation
+retires.
+
+The released shape is `logs/opencode_server.json`, which every released
+version writes (`server.py:1080-1117`). Adoption converts a proven, live
+legacy server into a record whose `spec_digest` is `"legacy"`, so it never
+becomes current. The record keeps that file's `active_run_sessions`, and the
+legacy file is then deleted.
+
+- Trust follows today's rules for that file: the birth identity when it is
+ present, otherwise the command line and port, as in
+ `terminate_instance_sync` (`server.py:2129-2179`).
+- A legacy file with a dead pid is deleted.
+- Load fixtures cover each released shape: with and without
+ `process_created_at`, `caller_context_path`, and the overlay fields.
+
+Unrecorded `opencode serve` processes are never adopted. Today's port scan
+(`_find_opencode_serve_pids`, `server.py:1628-1684`) exists only because the
+port is fixed.
+
+### 2.3 Starting a generation
+
+`start_generation(spec)` runs under the core's per-backend start serialization.
+The start includes the wait for health, so one start's migration never
+overlaps another's.
+
+1. `ensure_plugin_installed()` (`caller_context.py:128-134`).
+2. **Port.** Bind `127.0.0.1:0` in Python, read the port, close the socket,
+ and pass `--port=<port>`. Never pass `--port=0`.
+3. **Environment.** Use today's launch environment (`server.py:2011-2038`):
+ - the desktop role, EXA, and external Skills off;
+ - `server_environment()` and `AVIBE_OPENCODE_MODEL_HUB`;
+ - in Hub mode, `OPENCODE_CONFIG_CONTENT` from the spec's overlay, and
+ `OPENCODE_CONFIG` pointing at a per-generation copy
+ `<generation_id>.overlay.json` (mode 0600).
+
+ The copy replaces the shared overlay path, because `prepare_opencode_overlay`
+ rewrites the shared file for every new overlay (`model_hub.py:1281-1291`)
+ while older generations still run with that path.
+4. Spawn the process, write the record, and apply resource governance
+ (`server.py:1119-1123`).
+5. **Readiness.** The generation is ready when `/global/health` is healthy
+ and psutil shows this pid listening on the port. If the process exits
+ first, another process took the port, so pick a new port and retry, up to
+ three attempts. A timeout reaps the process, as at `server.py:2074-2090`.
+6. Attach the activation identity with
+ `registry.attach("opencode", f"opencode:{generation_id}")`. Each generation
+ has its own resource key, so a reused port can never alias an older
+ identity.
+
+When a start fails, `OpenCodeGenerations` keeps the failed pid.
+`_resource_failure_for_server` (`agent.py:987-1037`) uses it to attribute the
+failure to cgroup pressure, as it does today.
+
+## 3. Routing
+
+### Binding map
+
+`OpenCodeAgent._session_generations: dict[str, OpenCodeGeneration]` is keyed
+by `base_session_id`.
+
+- **Set:** when a turn's acquire returns, or when a restored poll resolves its
+ generation.
+- **Popped:** wherever `_active_requests` and the request session are popped
+ (`agent.py:1301-1304`, `3123-3125`).
+
+Every session-scoped lookup that today calls `_get_server()` or
+`_client_manager._server_manager` reads this map instead:
+
+| Call site | Today | New |
+| --- | --- | --- |
+| Turn start | `_get_server()`, then `configure_model_hub_overlay`, then `ensure_running` (`agent.py:1356-1365`) | `spec = launch_spec(snapshot)`, then `binding = await generations.acquire(spec)`, then `server = binding.generation` |
+| Caller-context path | `caller_context_binding_path()` from the singleton PID file (`agent.py:1366`, `server.py:405-410`) | `server.caller_context_path` from the record |
+| Activation identity | `_attach_server_activation` (`agent.py:887-908`) | `server.identity`, attached at start or adoption |
+| Run marker | Singleton, with an overlay reservation (`agent.py:1748-1755`) | `server.mark_run_active(session_id)` |
+| Durable active poll | `add_active_poll` (`agent.py:1760-1779`) | The same call, plus `processing_indicator["opencode_generation_id"]`. That bag already carries other OpenCode keys, so storage does not change. |
+| Prompt and poll | `_SteeringAwareOpenCodeServer(server, state)` (`agent.py:1869`) | Unchanged; `server` is now the generation |
+| Turn end | `_retire_active_poll(server, ...)` (`agent.py:2037-2044`, `2086-2100`) | Unchanged, then `binding.release()` |
+| Superseding a running request | `_get_server()` abort and `wait_for_session_idle` (`agent.py:1266-1274`) | The old task's generation |
+| Steering | `_client_manager._server_manager` (`agent.py:2176`) | `state.generation`, a new `_OpenCodeSteerState` field set at `agent.py:1827` and `2991` |
+| Steer reconciliation | Singleton (`agent.py:2369`) | The bound generation. Finding a part is a database read, so an unbound session falls back to the current generation. |
+| `/stop` and `clear_sessions` | `_get_server()` (`agent.py:2478`, `2517`) | The generation captured from the map before awaiting the task |
+| `_abort_active_request` | `_get_server()` (`agent.py:2538`, `2546`) | The bound generation. With no binding there is no native run, so skip. |
+| Restore | `_get_server()` (`agent.py:2635`, `2951`; `poll_loop.py:922`) | The resolved generation, passed explicitly as `run_restored_poll_loop(poll_info, server)` |
+| Activation resolvers | Singleton identity (`agent.py:942-964`) | The bound generation's identity, else the current generation's, else `None` |
+
+### Durable active-poll recovery
+
+`restore_active_polls` (`agent.py:2598-2911`) resolves each poll's generation
+in this order:
+
+1. If `processing_indicator["opencode_generation_id"]` names an adopted
+ generation, use it.
+2. If the key is missing (the released shape), use the adopted generation
+ whose `active_run_sessions` lists the session. In practice this is the
+ converted legacy record.
+3. Otherwise no live process owns the run. Verification reads use a lease on
+ the current generation, as a dead server is handled today. The existing
+ `session_still_active` logic then settles the run.
+
+The restored task binds `_session_generations`, re-marks the run on that
+generation (`agent.py:2951-2953`), and gets
+`_SteeringAwareOpenCodeServer(generation, state)` (`agent.py:3027`).
+
+### Caller context
+
+The binding file stays one file keyed by native session id
+(`caller_context.py:114`, `202-337`). That is safe across generations: a
+session is active on at most one generation, and unbinding checks a token
+(`caller_context.py:282-306`).
+
+- Each generation launches with `server_environment()` and records that path.
+- A turn uses its own generation's recorded path (`agent.py:1669`, `2758`).
+- The plugin source digest is a spec input. A plugin change starts a new
+ generation instead of refusing turns.
+
+## 4. Retire when drained, the cap, and serialized starts
+
+`generation_idle(G)` uses adapter evidence only. `G` is idle when all of these
+hold:
+
+- it has no live binding (turns, restored polls, or controller-side leases);
+- its in-flight request count is zero;
+- its `active_run_sessions` is empty after reconciliation;
+- its record holds no unexpired lease (UI leases, section 6).
+
+A per-generation ownership snapshot would list only the sessions bound to that
+generation. That list is empty exactly when the conditions above hold, and
+unbound sessions acquire the current generation, so the snapshot cannot veto
+retiring a generation.
+
+Exclusive operations still use ownership snapshots.
+`runtime_ownership_snapshots()` (`agent.py:1097-1159`) returns one target per
+generation with that generation's bound sessions. The current generation's
+target keeps `include_all_backend_sessions=True`, so durable work that has not
+acquired a generation still blocks `migration_guard`, as it does today.
+
+`stop_generation(G, force)`:
+
+- **Not forced:** call `registry.retire_if_current(G.identity, lambda:
+ generation_idle(G))`, which replaces the predicate at `agent.py:910-940`. If
+ it refuses, keep `G` running. Otherwise close the HTTP session, terminate
+ the tree, and delete the record and the overlay copy.
+- **Forced** (the cap, migration, or an explicit stop):
+ 1. Mark the sessions bound to `G` as interrupted by a runtime update.
+ 2. Cancel their request tasks with `_cancel_active_requests`
+ (`agent.py:1225-1253`), filtered to `G`. The cancellation handler then
+ emits the standard runtime-update notice instead of removing the ack
+ silently. This mirrors `_user_stopped_sessions` (`agent.py:765`,
+ `2118-2123`).
+ 3. Retire the durable polls, terminate the tree, and delete the record.
+
+The core owns the cap of three and the serialized starts. The adapter declares
+`can_coexist = True`.
+
+Other lifecycle cases:
+
+- **Backend disabled.** The core interrupts the backend's work, unregisters
+ the agent, and awaits `OpenCodeAgent.shutdown_runtime(settle_reason=...)`,
+ which stops every generation at once and settles the work bound to each with
+ that reason.
+- **Native migration.** `retire_for_native_migration` (`agent.py:1086-1089`,
+ `server.py:550-593`) strictly stops every generation. It refuses while any
+ generation has requests or runs, and keeps today's ownership proofs.
+- **Controller shutdown.** `terminate_all_generations_sync()` covers tracked
+ generations and records. It replaces `terminate_instance_sync` at
+ `controller.py:2386-2393`.
+
+## 5. Launch spec
+
+`OpenCodeLaunchSpec` holds `digest`, `binary_path`, `overlay`, and a summary.
+Two specs are equal when their digests are equal. The digest is the sha256 of
+canonical JSON over these inputs:
+
+| Input | Source | Notes |
+| --- | --- | --- |
+| Binary identity | `resolve_cli_path` on the snapshot's `agents.opencode.cli_path` | Covers the realpath and `(st_dev, st_ino, st_size, st_mtime_ns)`. Every install writes the file anew, so the stat signature changes on any upgrade or reinstall, including an in-place one. The version (`<binary> --version`, cached per stat signature) goes into the generation's record only, so the digest stays a pure function of the snapshot. |
+| Hub overlay | `overlay.content_hash` and `provider_ids`; `None` in Direct mode | The same overlay object the turn resolves its model with. A Hub/Direct switch therefore changes the spec. |
+| Managed policy | `_MANAGED_RUNTIME_POLICY_REVISION` (`server.py:72`) | A bump now starts a new generation instead of refusing turns. |
+| Caller-context plugin | sha256 of `PLUGIN_SOURCE` | |
+| User config | The global files OpenCode loads: `get_opencode_config_paths()` plus XDG `{config.json, opencode.json, opencode.jsonc}` | Each file contributes its canonical parsed JSON with `$schema` removed, its raw bytes when it cannot be parsed, or an absence marker. OpenCode may insert `$schema` on load, and that must not start new generations. |
+| Credentials | Normalized `auth.json` | Each provider maps to its type, plus its key for `api` and `wellknown` entries, plus stable non-secret OAuth identity fields. OAuth `access`, `refresh`, and `expires` are excluded. OpenCode rewrites them whenever it refreshes a token, so a raw digest would start a new generation after every refresh. |
+| Renew epoch | The core | Set by manual Restart, and by an Avibe-initiated OAuth success (section 6). |
+
+**Snapshot discipline.** A turn should load the Model Hub configuration once.
+Today there are three loads:
+
+- `turn_mode` (`agent.py:1348-1355`, `model_hub.py:931-932`);
+- `prepare_opencode_overlay` (`model_hub.py:1177-1178`);
+- `resolve_opencode_overlay_launch`, for unlisted models
+ (`model_hub.py:1085`).
+
+Proposal: pass the core snapshot's Model Hub configuration into
+`prepare_opencode_overlay(config)` and
+`resolve_opencode_overlay_launch(overlay, model, config)`, and derive the turn
+mode as `direct` when the overlay is `None`, `hub` otherwise. The overlay
+digest and the model resolution then come from one load. `model_hub.py` is
+shared, so this needs core agreement.
+
+**One snapshot per launch.** `_prepare_launch()` reads every mutable launch
+input in one synchronous step, before its first await. That covers the Model Hub
+snapshot, the CLI path, the renewal epoch, the binary identity, and the user
+config and credential digests (`OpenCodeRuntime.launch_inputs()`). The policy
+revision and plugin source are constants of the Avibe build. The overlay is
+derived from that Hub snapshot, and the spec is a pure function of the
+snapshot and the overlay (`compute_launch_spec(inputs, overlay)`). Turns,
+restored polls, `current_server()`, leases, and adoption all use this one
+path. A save or renewal that lands while the overlay is prepared therefore
+changes nothing about that launch: it stays on the generation its snapshot
+names, starts no spare generation, and the next launch moves. After the
+snapshot, only the generation's HTTP request timeout is read live; it is a
+client setting, not a process input.
+
+The same snapshot carries the `agents.opencode` settings object the CLI path
+was read from (`OpenCodeLaunchInputs.settings`). After admission, the turn
+reads no live `agents.opencode` field:
+
+| Read | Disposition |
+| --- | --- |
+| `default_provider` and `default_reasoning_effort` (model resolution in `_run_turn`) | taken from the admission settings |
+| `active_turn_timeout_seconds` and `error_retry_limit` (`run_prompt_poll`) | taken from the admission settings |
+| the same two in `run_restored_poll_loop` | read once when the restore starts; a restored poll has no earlier admission |
+| `request_timeout_seconds` (a generation's HTTP client) | read when the generation starts; always 60 from `to_app_config`, not a user setting |
+| `controller.config.language` | not an `agents.opencode` field |
+| channel and scope overrides | out of scope: a recorded follow-up, as for Codex |
+
+**Check-to-spawn window.** Files are digested before the spawn. If a save
+lands in between, the generation loads files newer than its label says. The
+next turn sees the mismatch and starts one more generation. A generation never
+runs files older than its label.
+
+## 6. The UI process stops launching servers
+
+Today these UI-process paths call `ensure_running`:
+
+- `vibe/api.py:5902-5908`: model options;
+- `vibe/api.py:11666-11697` (`_opencode_get_server`): providers (`12030`),
+ model save (`12591`), and auth deletion (`12934`);
+- `core/agent_auth_service.py:3524-3566` (`_opencode_server`): Web OAuth
+ (`3602`, `3667`, `3697`) and the provider probe (`3227`).
+
+None of them may launch a server after this change. Instead, they lease a
+generation from the controller over control IPC (`core/internal_server.py`,
+`vibe/internal_client.py`):
+
+- `POST /internal/opencode/generation-leases` with `{purpose, ttl_seconds}`.
+ The controller captures the snapshot, computes the launch spec, and acquires
+ with a lease, which is a core binding with a TTL. It returns
+ `{lease_id, generation_id, base_url, model_hub_provider_ids, expires_at}`.
+ It returns 404 when OpenCode is disabled, and 503 when the Hub engine is
+ down or the start fails.
+- `POST /internal/opencode/generation-leases/{lease_id}/release`.
+
+The lease expiry is persisted in the generation record. A controller restart
+therefore keeps an OAuth flow's generation alive; today the UI's own server
+also survives a controller restart.
+
+The UI helper is `async with internal_client.opencode_generation(purpose,
+ttl) as server`, which yields an `OpenCodeServerClient`. The controller-side
+`AgentAuthService` uses the agent's local lease with the same shape.
+
+| Flow | Change |
+| --- | --- |
+| Options, providers, model save, auth deletion | One lease per call (a 60 s request window), released in `finally`. Outside the controller a lease lasts `LEASED_REQUEST_TIMEOUT_SECONDS` longer than the window it is asked for, timed from before the controller grants it, and the leased client's request timeout is at most that constant. The client starts no request that its timeout could carry past the lease, so the controller never stops a generation under a running UI request; the TTL only stays behind a UI process that died holding the lease. `_opencode_lease` returns `None` only when OpenCode is disabled; a lease an enabled OpenCode cannot give raises, so no caller takes an unavailable runtime for a disabled one. Options and providers report the error. Model save fails closed, since it needs the live catalog to refuse a built-in duplicate. Auth deletion reports "OpenCode is unavailable" instead of "disabled". |
+| Web OAuth | One lease from `_start_opencode_oauth_web` through the waiter. Authorize, the pasted-callback forward, and `wait_provider_oauth` must reach the same process, because the pending OAuth lives in its memory. The TTL is the flow timeout plus 60 s. The lease is released in the waiter's `finally` and in `_terminate_web_flow`. A success renews OpenCode. |
+| Provider probe | One lease for the probe. Drop its `mark_run_active` and `mark_run_inactive` calls (`agent_auth_service.py:3332`, `3509`), which today write the controller's PID file from the UI process. |
+| Provider save | Still calls `restart_backend("opencode")` (`api.py:12924`, and the other provider writes at `12444-13042`), which the core remaps to a snapshot advance. `_refresh_opencode_provider_catalog_async` then leases the current spec, which is a new generation if the save changed the digest. |
+| Status | `_opencode_process_status` (`api.py:9852-9872`) reads the records and reports running when any proven generation is alive. |
+
+## 7. Other consumers
+
+- `vibe/cli.py:13872-13914` (`_stop_opencode_server`): iterate the records
+ and the legacy file with the same per-pid checks. Return `True` when any
+ server stopped.
+- `core/services/running_agents.py:717-764` (`_end_opencode`): abort on the
+ bound generation. When the last session ends, call
+ `agent.retire_idle_generations()` instead of `retire_for_native_migration`
+ on the singleton.
+- `core/handlers/settings_handler.py:453-479` and
+ `core/handlers/message_handler.py:548-562`: use
+ `async with agent.catalog_server()`, a lease on the current generation.
+- `core/agent_auth_service.py`:
+ - the provider lookup (`796-805`) and the IM API-key install
+ (`2112-2130`) use a lease;
+ - `_refresh_opencode_server` (`2149-2160`) is deleted;
+ - the disable branch (`2272-2280`) becomes `shutdown_runtime`;
+ - the OpenCode branches at `2339-2346` and `2359-2364` move to the core
+ path.
+- `docs/CLI.md:681` and `708`, and `docs/CLI_ZH.md`: point the PID-file row at
+ the records directory, and drop the `OPENCODE_PORT` row. That setting does
+ not exist; the port is hard-coded at `config/v2_compat.py:182`.
+
+## 8. Deletions
+
+| Mechanism | Code |
+| --- | --- |
+| `PATCH /global/config` reload | `refresh_global_config` (`server.py:667-706`); `_merge_global_config_snapshot` and `_get_global_config_snapshot` (`server.py:2792-2812`); the reload branch of `refresh_runtime_config` (`agent.py:1171-1223`); `config_reconciler.py`, whose only caller is `server.py:2798`. |
+| Deferred refresh | `_auth_refresh_pending`, `_auth_refresh_pending_port`, and `_pending_runtime_config` (`server.py:285-288`); `_restart_for_auth_refresh_locked` (`595-649`); `detach_after_deferred_refresh` (`651-665`); `reload_runtime_config`, `_set_runtime_config`, and `_apply_pending_runtime_config_locked` (`708-730`); `restart_for_auth_refresh` (`2181-2194`); the pending branches at `1054-1055` and `1863-1864`. |
+| Overlay transition and reservations | The overlay fields (`server.py:290-304`); `MODEL_HUB_OVERLAY_DRAIN_TIMEOUT_SECONDS` (`66`); `set_model_hub_overlay_preparer` (`428-434`); `_configured_model_hub_overlay` through `_prepare_model_hub_launch_boundary` (`812-873`); `configure_model_hub_overlay` (`875-997`); `release_model_hub_overlay_reservation` (`999-1004`); the reservation parameter of `mark_run_active` (`1006-1037`); `OpenCodeModelHubOverlayRequiredError` (`238-239`); the agent's reservation plumbing (`agent.py:750-756`, `1323`, `1360-1364`, `1748-1755`, `2068-2084`, and the `_release...` calls). |
+| Policy- and plugin-pending refusals | `OpenCodeManagedPolicyRefreshPendingError` (`server.py:234-235`); `_caller_context_plugin_refresh_pending` (`287`); the refusal block (`1860-1913`); `_pid_file_has_caller_context_binding`, `_pid_file_has_current_runtime_policy`, `_pid_file_was_started_by_current_process`, and `_pid_file_has_known_no_active_runs` (`1189-1208`); their display mapping (`agent.py:1064-1067`); the i18n keys `error.opencodeModelHubOverlayRequired` and `error.opencodePolicyRefreshPending` (`vibe/i18n/en.json:442-443`, `zh.json:442-443`). |
+| #2328 compatibility checks | None on this base; #2328 is still an open draft. Nothing is ported from it. |
+| Singleton and fixed port | `DEFAULT_OPENCODE_PORT` (`server.py:51`); `_instance`, `_class_lock`, `get_instance`, and `get_instance_if_managed_server_exists` (`249-250`, `436-501`); `_pid_file` (`281`); `_runtime_generation_token` and the replacement-retire helpers (`324-366`); `_is_port_available` and `_find_opencode_serve_pids` (`1618-1684`); `_cleanup_orphaned_managed_server` (`1795-1846`); `ensure_running` and `_ensure_running_with_current_overlay` (`1848-1947`); `stop_instance_sync` and `terminate_instance_sync` (`2156-2204`); the `port` field of `OpenCodeCompatConfig` (`v2_compat.py:53`, `182`). |
+| Adapter refresh entry | `OpenCodeAgent.refresh_runtime_config` (`agent.py:1171-1223`) becomes `apply_runtime_config_change`: reload `opencode_config` and take no server action. A forced refresh, used only by the coordinator's interrupt path until that path is deleted, force-stops every generation. `prepare_runtime_restart` (`agent.py:1082-1084`) becomes the adoption trigger. |
+
+## 9. Tests
+
+The rule: each deleted mechanism loses its tests, each rewritten contract
+keeps one test at its owner boundary, and each new behavior gets a test that
+fails on the old code.
+
+| File | Change |
+| --- | --- |
+| `tests/test_opencode_server.py` | **Delete** the tests for removed mechanisms: `refresh_global_config` (`1397-2149`); `restart_for_auth_refresh` (`2172-2277`); `request_scope` pending (`2455`); `reload_runtime_config` (`2469`); pending detach (`2598`); `get_instance` (`2493-2570`, `2652`); Hub launch refusals and rechecks (`506-565`); plugin and policy refreshes, deferrals, and refusals (`483`, `691-903`); stale-pid cleanup (`1021`); the unmanaged healthy server (`1049`); singleton generation replacement (`1069`, `1095`); the Windows port scan (`2151`); `terminate_instance_sync` (`243`, `267`); the overlay transition tests (`3350-3527`). **Rewrite** as generation tests: the start timeout (`198`); record run markers (`933-1002`); record birth identity (`954`); adoption with active runs and reused pids (`2289`, `2301`); `terminate_sync` (`2313-2341`); adoption and stop proofs (`2354-2445`); the observed exit (`2445`); resource governance (`2482`); overlay preparation as a spec input (`600`, `672`); the recorded caller-context path (`903`); the catalog projection with the generation's provider ids (`302`, `342`). **Keep** the HTTP and diagnostic tests (`175-192`, `288`, `1126-1377`, `2629-2675`, `2700-3189`, `3260`, `3317`). |
+| New tests: spec | An in-place binary change (stat or version) changes the digest; this fails on the old code, which compared only the path. An OAuth token rewrite keeps the digest. An API-key change changes it. Inserting `$schema` keeps it. |
+| New tests: process and routing | The launch never passes `--port=0`. Adoption covers every record plus the legacy file. A start on a taken port retries. A turn's status, abort, and steering go to its own generation while a newer one is current. A retiring generation stops when its last binding is released. |
+| `tests/test_opencode_client_manager.py` | Replace both tests (`14`, `47`) with hook tests for `OpenCodeGenerations`. |
+| `tests/test_opencode_config_reconciler.py` | Delete, with the module. |
+| `tests/test_agent_auth_service.py` | Delete `1580` and `1761-2185` (refresh, global-config reload, and uncached-server attach). Add one test: a config change takes no server action, and the next turn gets a new generation. |
+| `tests/test_ui_api.py` | `43-1546`: patch the lease helper instead of `OpenCodeServerManager.get_instance`. The catalog assertions stay. Delete `346` (the UI launch boundary). Rewrite `600` as a lease-error mapping. |
+| `tests/test_web_oauth_flow.py` | `856-2172`: patch the lease. Add one test: authorize, callback, and wait share one lease, which is released on success, cancel, and expiry. |
+| `tests/test_multi_platform_runtime.py` | Delete `59` and `91` (the localized refusals). Move `127`, `223`, `1179`, `1373`, and `3978` from overlay reservations and `ensure_running` to acquire bindings. |
+| `tests/test_opencode_restore_polls.py` | `340-1114`: route through the poll's generation. Add one test: a poll in the released shape (no generation key) routes to the legacy record. |
+| `tests/test_agent_steering.py` | `1306`, `1450`, `2706`, and `2920`: steer through the bound generation. `2706` covers "no binding". |
+| `tests/test_vibe_cli.py` | `1007` and `1035`: stop every record plus the legacy file. |
+| `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | `3037`, `4083`, and `4273`: use leases and renew-on-OAuth. Update the matching scenario IDs in `catalog.yaml`. |
+| `tests/test_runtime_activation.py` and `tests/scenarios/model_hub/catalog.yaml` | Rewrite `242` for per-generation identity. MH-RUNTIME-002, 003, 004, and 007 (`catalog.yaml:503-538`) describe the deleted transition. Retire them and add IDs for "an overlay change starts a new generation; the old one finishes its run". |
+| Smaller fake-server updates | `tests/test_opencode_stop_receipt.py:233` (binding release replaces reservation release); `tests/test_opencode_directory_bootstrap.py:188`; `tests/test_runtime_ownership.py:299` (per-generation targets); `tests/test_native_takeover_lifecycle.py:862`, `883`; `tests/test_desktop_runtime_stop.py:241`, `543`, `718` (dynamic-port argv, several servers); `tests/test_agent_backend_alive.py:135-221`; `tests/test_running_agents_service.py:1075`, `1109`; `tests/test_settings_handler.py:520-636`; `tests/test_message_handler_typing.py:361`; `tests/test_save_opencode_provider_auth.py:524`, `666`, `916`; `tests/test_native_writer_custody.py:290`; `tests/test_backend_connection.py:118`; `tests/test_native_login_single_flight.py:79`. |
+
+## 10. What the adapter needs from the core contract
+
+1. The spec object carries the adapter's launch inputs: the overlay content
+ and the binary path. Equality is by digest only.
+2. `acquire(spec, *, purpose, ttl=None)` returns a binding that pins its
+ generation until released or expired. The binding works as an async
+ context manager, and another task can release it.
+3. `bind(generation)` binds a restored poll to an adopted generation without
+ comparing specs. `adopt(generations)` registers adopted generations, with
+ "the newest matching generation becomes current".
+4. A decision on who emits the runtime-update notice on a forced stop. The
+ adapter can emit it from the cancelled task's handler.
+5. A renew epoch as a spec input, for manual Restart and Avibe-initiated OAuth
+ success.
+6. The snapshot carries the Model Hub configuration for
+ `prepare_opencode_overlay` (section 5).
+7. For backends that can coexist, in-place replacement starts the new
+ generation before stopping the old one, so it never waits on a stop.
+
+## 11. Risks and open items
+
+- **Cross-version coexistence is unverified.** An upgrade while an old
+ generation is busy runs the new version's database migrations under a
+ running older version. Gate for Phase 2: a hermetic two-version probe in
+ which the old version is mid-prompt while the new one starts, the old prompt
+ completes, and the session continues on the new version. If the probe
+ fails, the owner must decide whether a version change interrupts the old
+ generation or waits for it to drain.
+- **OAuth tokens are assumed to be read live.** The normalized credential
+ digest assumes OpenCode reads OAuth tokens from `auth.json` on each request.
+ Renew-on-OAuth-success covers Avibe's own logins either way.
+- **Memory.** Up to three servers can run at once.
+
+## 12. Lifecycle invariants and audit
+
+This audit covers head `2b35e0739`. Each invariant below is a one-line rule. In
+the transition table, every cell names the code path and states whether the
+rule holds under normal flow, a failed write (W), cancellation (C), and
+process death (D). A gap is a real violation and is fixed in the push that
+follows the audit, with a regression that fails on `2b35e0739`. A known item
+is a bounded consequence kept by design, and is also listed in the PR's
+Known-by-design ledger. Gaps G4 and G5 came from Codex's review of
+`2b35e0739`, on transitions the first version of this table missed. Gaps G6–G9
+and the corrected cells came from an independent agent that checked every
+"holds" claim against the code.
+
+### Invariants
+
+| ID | Rule |
+| --- | --- |
+| R1 | Every `opencode serve` process Avibe started has a record on disk before it can serve, until it is confirmed gone. |
+| R2 | A record is removed only once its process is confirmed gone: stopped by Avibe, dead, or proven not ours. A record that cannot be read is kept. |
+| R6 | A record of another desktop Runtime sharing this state directory is never adopted, stopped, forgotten, or overlay-cleaned here. `_record_is_ours()`, applied in `_recorded_processes()`, is the one gate every reader goes through. A durable poll whose run a live process of another Runtime executes is never bound, rewritten, or settled here. |
+| R3 | A record never protects less than its process runs. A run marker or lease is written before its work starts. A release may lag, but a sweep rewrites it. |
+| R4 | A generation's overlay copy lives and goes with its record. |
+| R5 | No write recreates the record of a process that has stopped. |
+| O1 | A live process is attached to at most one runtime in this controller. |
+| O2 | Every recorded live process is attached to a runtime here, or is being started here, or stays unmarked so that an adoption here or a successor can take it. |
+| O3 | The owned-here mark, the process's pid and create time, is set at spawn, before anything that can fail, the record write included. It ends only when a stop proves the process gone or its start proves it exited. Service shutdown stops every owned process, through its record or, without one, by that identity. |
+| O4 | Every attached generation whose stop declined or failed is retried, by the controller's sweep or by its own runtime's sweep. |
+| L1 | A lease holds one binding on its generation from grant until release or expiry. |
+| L2 | Every lease ends by a release, its TTL, or a controller restart, where adoption re-holds what remains or drops what expired. |
+| L3 | A release reaches the runtime holding the lease, whether or not its agent is registered. If no runtime holds it yet, the registered agent adopts first. |
+| L4 | A lease's TTL covers its holder's longest legitimate wait. |
+| L5 | A lease's expiry is in the record before the lease is handed out (R3). |
+| B1 | A turn, a restored poll, a `current_server()` use, and a lease each hold one binding for their whole use, and release it exactly once on every exit. |
+| B2 | No new work binds to a closed or stopped generation. A turn's prompt, status, abort, steering, and stop reach the generation it is bound to. |
+| B3 | A bound generation is stopped only by a forced stop, which first settles the bound work, each session once across retries, with the stop's reason (a disable's, else a runtime update), and never another agent instance's work. |
+| M1 | A native run is marked on its generation, and that marker persisted, before the run's first native write. |
+| M2 | A turn clears its marker together with its durable poll: both go, or both stay. This is master's contract. |
+| M3 | A marker that no live run or durable poll backs never keeps a process: adoption reconciliation and the re-reconcile in `_stop`. |
+| S1 | New turns run on the generation whose spec equals the current spec. A renewal is persisted before it takes effect. |
+| N1 | A native migration never overlaps the start of an OpenCode process: work outside a turn waits while the backend drains, and admitted work counts as active until it is bound. |
+| P1 | A durable poll names the generation that runs its native turn, including after a restore binds it elsewhere. |
+
+### Transitions
+
+| Transition | Code path | Invariants and outcome |
+| --- | --- | --- |
+| Start: success | `start_generation`: overlay copy, spawn, mark owned, `write_record`, governance, `_wait_until_ready`; core `acquire` installs it current | R1, R4, O3, S1 hold. **Known K1:** a controller crash in the microseconds between spawn and the record write leaves an unrecorded process (R1). |
+| Start: port taken | outcome `exited`: ownership and record dropped, same id retried on a new port | R1, R2, O3 hold. |
+| Start: timeout or cancellation | terminate the spawned process; on exit remove the record, else hand the survivor to the runtime that started it (`on_survivor`), which keeps it owned, record and overlay included, and stops it at every later `reap()` and at `shutdown()` until it is gone | R1, R2, R4 hold. W: a failed record write aborts the start and terminates the process. C: holds for one cancellation. **Known K4:** a second cancellation inside the cleanup can skip the record removal (a stale record, later removed as dead) or, if it lands before the kill, leave the process recorded but unsignalled until `vibe stop`, shutdown, or the next adoption. **Gap G12:** such a survivor was dropped from ownership, so nothing here retried its stop and it ran beside later generations until service shutdown. Every process a runtime spawned is now retried until it is gone, unrecorded ones included (a failed record write), since the runtime holds the process itself. **Gap G14:** ownership began only after the record write, so a start whose write and termination both failed left a process owned by nothing but its runtime's next reap; a service stop before that reap never found it. |
+| Start: runtime closed meanwhile | core `acquire` attaches it closed and retiring and kicks the reconciler | O2, O4 hold. |
+| Adopt: fresh record | `adopt_recorded_generations` proves, health-checks, and returns it; `ensure_adopted` attaches them oldest first by process start, so the set's serials follow process age, and reconciles markers (W: write-behind), attaches, marks owned, applies governance, attaches activation, re-holds leases | O1–O3, L2 hold. C: cancellation lands only inside `adopt_recorded_generations` (the attach loop has no suspension point), so nothing is marked and the retry adopts everything. D: an unhealthy proven process is stopped; a survivor keeps its record. **Gap G7:** one failed 5 s health probe stops a proven process, which may be busy with runs that durable polls would restore. **Gap G9:** a recorded lease is re-held for `expires_at - now`, unclamped, so a backward clock step across the crash pins the generation for that long. **Gap G15:** generations were attached in record filename order, which is random, so the cap's force-stop of the lowest serial took an arbitrary adopted process instead of the oldest. |
+| Adopt: legacy record | converted to a generation with spec `legacy`; the legacy file goes once the new record is written (write-behind) | R1, R3 hold. **Gap G3:** a crash between writing the converted record and removing the legacy file, or a failed removal, makes the next adoption adopt one process twice (O1). **Gap G6:** the same happens inside one controller: a runtime created by a re-enable re-adopts a legacy server that the closed runtime still owns, because ownership is known by generation id and a legacy record has none. A failed unlink also cleared `_supersedes`, so the removal was never retried. |
+| Adopt: unreadable record | `_read_json_object` returns `None` and the record is skipped and kept | R2, R4 hold. Its process is excluded from adoption, shutdown, and `vibe stop` alike; only a log line reports it. This is by design: nothing can prove what it names. |
+| Adopt: malformed field | a readable record whose field has the wrong type reads as one without that field: `_record_pid`, `_record_port`, `_record_number` (finite numbers only), and `_record_runtime_id` (an id, null, or unrecorded, so judged by its live process); a generation's id is its file name | R2, R6 hold. **Gap G17:** an unhashable `desktop_runtime_id` or `generation_id`, or a number too large for a float, raised in the gate, `_owned_here`, or the proof, so one corrupt record failed every adoption, lease, restore, and shutdown stop. |
+| Adopt: dead or not ours | record and overlay removed without a signal | R2, R4 hold. |
+| Lease acquire, in controller | `lease_generation` → `OpenCodeRuntime.lease`: core `acquire`, then `set_lease` (persisted first), then `_hold_lease` (timer and holder) | L1, L5 hold. W: the lease fails and its binding is released. C: no binding survives. |
+| Lease acquire, IPC | `POST /internal/opencode/generation-leases` → same path | Same as above. A UI caller that gives up after the grant leaves the lease to its TTL (L2). |
+| Lease renew | none by design; each holder sizes its TTL | L4 holds for realistic runs: OAuth uses the remaining flow budget + 60 s; the probe uses bootstrap + timeout + 60 s; model options makes at most about 5 × 10 s of requests under 60 s; catalog, model save, and auth removal each make one request bounded by its request timeout. A probe whose every request hits its own timeout can outlast its lease, and then fails anyway. A UI caller that gives up before the grant leaves a lease nobody releases, bounded by its TTL. |
+| Lease release | in controller: the captured agent's `release_generation_lease`; IPC: `release_opencode_lease` (holder map, else each runtime agent adopts first, else the recorded lease is cleared, else 404); expiry timer → `release_lease` | L1–L3 hold. W: the drop is write-behind and flushed by the next sweep. After a force-stop, the record write is a no-op (R5). |
+| Turn bind and unbind | `_run_turn`: acquire → `_session_generations` → `mark_run_active` (persisted first) → durable poll → prompt; `_process_message` `finally` releases | B1, B2, M1, M2 hold. C: release is synchronous bookkeeping in a `finally`. W: a failed marker write fails the turn before its first native write; a failed clear keeps marker and poll (M2). |
+| Restored poll | `_bind_restored_poll` (adopts first; binds by generation id, else legacy marker, else current) → task → `finally` releases | B2 holds. A closed runtime refuses the bind, so the poll stays durable. **Gap G19:** each handed-off poll task waits for the restore to publish it; a restore cancelled, or failing to mark an earlier poll's session running, left the rest waiting forever, holding their binding and request, so later restores skipped them. **Gap G18:** a failed rewrite of the poll's generation was logged and the poll still ran, so a crash before it finished left it naming the old process and the next restore bound it to another server. **Gap G16:** a poll whose run another desktop Runtime's live server executes found no generation here, so restore started its own, rewrote the poll to it, and settled the run from a server that does not run it. **Gap G8:** `restore_active_polls` holds the binding across several awaits before the poll task takes it over. An exception in that stretch leaks the binding (B1), and a forced stop in it leaves the poll registering on a dead process (B3). **Gap G5:** a poll bound to a generation other than the one it names keeps the old name, so after another crash adoption drops the new generation's marker and the rebind goes to the wrong process (P1, M3). |
+| Native migration | `BackendRestartCoordinator` guard: `begin_backend_drain` holds turns; it waits on `backend_runtime_active` → `runtime_has_active_turns`; `retire_for_native_migration` → `retire_all_strict`; `verify_idle` | **Gap G4:** `current_server()` and `lease_generation()` bypass turn admission, and an acquisition still starting a process is invisible to `runtime_has_active_turns`, so the guard can yield while a process starts (N1). |
+| Retire: renewal | `renew()` persists the epoch first; the next turn's spec installs a new current and the old one retires | S1 holds. W: renewal raises without effect. |
+| Retire: End-idle and strict migration | `retire_confirmed()` waits for the reconciler and reports stopped, draining, or failed | B3, O4 hold. |
+| Retire: forced refresh | `_cancel_active_requests()` then `retire_all()` | B3 holds; leases keep their generation until released. |
+| Disable | the core interrupts the backend's work, unregisters the agent, and runs `shutdown_runtime(settle_reason="backend_disabled")` → `OpenCodeRuntime.shutdown()` inside `AgentService.run_until_done`: a forced `stop_all` of every attached generation, each forced stop settling its bound work with that reason, then `stop_recorded_servers_sync()` for every recorded server no runtime here owns. It raises while any process survives, so the idle sweep retries it; a retry repeats both steps | B3 holds by the user's own interruption. L3 holds: a later UI release reaches the holder. W/D: a survivor fails the teardown, which is retried until it stops. **Gap G2:** a runtime that never adopted stopped without adopting, so a crashed predecessor's generations ran until shutdown (O2). Gap G1, a closed runtime that was never swept, ended with the drain path. **Gap G10:** an incomplete shutdown returned normally, so the teardown's retry was lost. **Gap G13:** the forced stop settled bound work only as a runtime update, so a disable whose core interrupt failed, retried after a re-enable that skips that interrupt, never settled it as disabled; it ended Activities by runtime key, which a re-enabled agent's Activities in the same session share; and a retry settled again a session an earlier attempt had settled, whose next turn may run on the re-enabled agent. |
+| Cap force-stop | core `_next_victim` forces the oldest retiring generation; `_on_generation_stopping(force)` → `_interrupt_generation_work` settles the bound sessions' turns and, by the runtime keys the ownership snapshot gives them, their Activities; `stop_generation` | B3 holds; a lease holder sees its process end, by design. **Gap G11:** the forced stop passed no runtime keys, so the interrupted sessions' Activities and Runs stayed active after the process was killed. Every forced stop of the adapter goes through this one hook; `forget()` handles a process that already died, and the record-based stops touch only records no runtime here owns. |
+| Controller restart | explicit: shutdown stops every generation this controller owns; next start adopts and restores polls on a new current. After a crash with OpenCode disabled, startup runs `stop_recorded_servers_sync()` | R2, B1 hold. **Gap S-1:** after a crash, a restart with OpenCode disabled never stopped its leftovers, which ran until the next stop or enable (O2). |
+| Crash between steps | spawn→record (K1); record→ready (adopted or stopped); lease grant→hand-out (the successor honors it until TTL); marker→durable poll (marker reconciled away); kill→record removal (unproven, removed later); legacy write→legacy removal (G3) | R1–R3 hold except K1 and G3. |
+| Process death | `acquire` replaces a dead current (`forget` → `stop_generation` cleans up); a dead retiring generation is cleaned on its last release | R2, B1 hold. |
+| CLI stop | `stop_recorded_servers_sync(provenance)`: `forget_dead_records()`, then each proven record, through the one ownership gate, `stop_recorded_server_sync` | R2, R4 hold; a survivor keeps its record; exit stays non-fatal (#2242). |
+| Shutdown | `stop_owned_generations_sync()`: stop each recorded generation a runtime of this controller owns, then each owned process with no record by its pid and create time (never one whose create time differs or cannot be read); another desktop Runtime's records are left alone | R2, R4 hold. **Known K5:** the loop keeps running briefly after this call, and a lease expiry or sweep there can rewrite a record of a process just killed (R5). The next adoption or `vibe stop` removes it as dead. |
+
+### Fixes
+
+| Gap | Fix | Regression |
+| --- | --- | --- |
+| G1 | moot: disabling stops every generation at once, so no closed runtime waits for a sweep. `reap()` still does not wait for a completed adoption | — |
+| G2 | `shutdown()` stops a previous controller's servers by their records, after its forced stop of what it attached | `test_disabling_the_backend_stops_a_previous_controllers_generations` |
+| G10 | `shutdown()` raises while any attached generation or recorded server survives | `test_a_disable_shutdown_that_leaves_a_process_raises_and_its_retry_finishes` |
+| G11 | `_interrupt_generation_work` passes `base_session_id:working_path` runtime keys | `test_a_cap_forced_stop_settles_the_activities_of_the_sessions_it_interrupts` |
+| G12 | a failed start's surviving process stays owned by its runtime, whose `reap()` and `shutdown()` retry its stop until it is gone | `test_a_failed_start_whose_process_survives_is_reaped_until_it_is_gone` |
+| G17 | every record reader takes fields through the typed readers above; a malformed Runtime id is judged by the live process; `_every_recorded_process` sets each generation's id from its file name | `test_a_malformed_record_never_disables_opencode` |
+| G18 | `_bind_restored_poll` releases its binding and raises when the rewrite fails; restore and the poll task leave the poll durable, its Turn live, and add it to `_polls_awaiting_restore`, as every other restore step that leaves a poll for later does; `reap_runtime_generations` restores again through `restore_polls_on_ready_transports` while one remains | `test_a_restore_whose_generation_rewrite_fails_runs_nothing_and_the_sweep_restores_it`, `test_a_poll_task_whose_rebind_cannot_be_recorded_leaves_its_turn_live_for_the_sweep` |
+| G19 | `restore_active_polls` tracks every handoff and, in a `finally` around the whole restore, cancels each task it never published, before its poll loop starts: the task releases its binding and request, and the poll stays durable in `_polls_awaiting_restore` for the sweep | `test_a_restore_whose_publication_fails_leaves_no_poll_task_waiting_on_it` |
+| G15 | `ensure_adopted` attaches adopted generations sorted by `started_at`; a record without one, such as the legacy record, takes its process's create time | `test_the_cap_stops_the_oldest_adopted_generation_whatever_its_record_order` |
+| G16 | restore reads `other_runtimes_live_records()` once and leaves every poll whose run one of them executes: the generation it names, or for a poll naming none, the process whose record marks its session running | `test_restore_leaves_every_poll_whose_run_another_desktop_runtimes_live_server_executes` |
+| G14 | ownership starts at spawn and ends only on a proven exit; `stop_owned_generations_sync()` also stops owned processes no record names, proven by pid and create time | `test_service_shutdown_stops_a_started_process_whose_record_was_never_written` |
+| G13 | `shutdown_runtime(settle_reason)` makes the reason this agent's forced-stop settlement for good; `_interrupt_generation_work` names sessions only from this agent's bindings, ends the Activities started under the stopping generation's activation identity, bound session or not, and settles each session of a generation once, recorded on the generation, so a retried stop settles only the rest | `test_runtime_gen_006_a_disable_retried_after_a_re_enable_settles_only_the_disabled_agents_work` |
+| G3 | adoption skips and removes a legacy record whose process a converted record already named | `test_adoption_takes_a_converted_legacy_server_once` |
+| G4 | `_outside_turn_admission()`: work outside a turn waits while the backend drains; it is counted, in one step with the readiness check, until it is bound; `runtime_has_active_turns()` reports it | `test_a_native_migration_never_overlaps_an_opencode_start_outside_a_turn` |
+| G5 | `_bind_restored_poll` rewrites the poll's `opencode_generation_id` whenever it binds a different generation | `test_runtime_gen_022_a_restored_poll_resumes_on_the_generation_that_runs_it` |
+| G6 | the ownership map records each owned process's identity; adoption skips a legacy record whose process a runtime here owns; `_supersedes` clears only once the legacy file is gone, and every flush retries it | `test_a_reenabled_backend_leaves_a_legacy_server_another_runtime_here_owns` |
+| G7 | adoption probes a proven process up to three times, two seconds apart, before stopping it | `test_adoption_gives_a_busy_server_more_than_one_health_probe` |
+| G8 | the restore loop holds a poll's binding in one `try` from the bind to the handoff `create_task`, and releases it on any `BaseException`, cancellation included; the task rebinds when a forced stop took the generation it was handed | `test_restore_releases_a_poll_binding_its_task_never_took`, `test_a_cancelled_restore_releases_the_binding_its_poll_task_never_took`, `test_a_restored_poll_whose_generation_was_force_stopped_rebinds_before_registering` |
+| G9 | an adopted lease is re-held for at most `MAX_LEASE_SECONDS` | `test_adoption_never_holds_a_recorded_lease_longer_than_any_lease_is_granted` |
+| S-1 | controller startup with OpenCode not registered runs `stop_recorded_servers_sync(desktop_caller_provenance())` | `test_a_controller_starting_with_opencode_disabled_stops_a_crashed_controllers_servers` (RUNTIME-GEN-025) |
+
+### Desktop Runtime ownership
+
+Several desktop Runtimes can share one Avibe state directory, so every record
+names the Runtime whose controller wrote it (`desktop_runtime_id`, written at
+spawn: the one Runtime this process acts for, or null). `_record_is_ours()` is
+the one ownership predicate:
+
+- A caller with no desktop provenance acts on any record, as `vibe stop`
+ always has.
+- A record that names a Runtime is ours only when this caller acts for exactly
+ that Runtime. Null counts as a Runtime too, so it is foreign to a desktop
+ caller.
+- A record from a release or build before the field existed, including the
+ legacy single-server record, is judged by its live process. This is the same
+ check as `refuse_foreign_desktop_process`: a process carrying another or no
+ Runtime id, or one whose environment cannot be read, is foreign; a process
+ that is gone belongs to nobody, so its record can be forgotten. Adopting such
+ a record keeps it without the field, so the check stays the same on every
+ later read.
+
+Every reader goes through `_recorded_processes()`, which applies the gate.
+
+What a shared state directory shares. Two Runtimes share one when they run
+with the same `AVIBE_HOME`, by default `~/.avibe`. This is the supported
+desktop update path: each private Runtime tree has its own id, and the new
+Runtime takes over the home of the one it replaces. It also happens when a
+terminal install and the desktop app share a home. Everything under the home
+is shared: the V2 config, the SQLite state (sessions, turns, deliveries,
+Activities, settings, and OpenCode's active polls), logs, the runtime
+directory, and OpenCode's generation records and overlays. The OpenCode
+caller-context binding file and plugin are shared too, but they are keyed by
+native session and renewed by their writer. The data-directory service lock is
+held for a controller's lifetime, so at most one controller runs on a home at
+a time. Two Runtimes' poll loops therefore never run at once.
+
+Ownership follows processes, not user data. The SQLite state is the user's,
+and any Runtime's controller resumes it, exactly as after a restart; that
+boundary is the core's, and it is Runtime-agnostic by design. A Runtime owns
+only the processes it started. Durable state stays that Runtime's for as long
+as it names a live process of that Runtime:
+
+- A record is the process's identity. Another Runtime's record is never acted
+ on, even after its process ends, because a failed proof must never disown a
+ live process. Its own Runtime forgets it once its process is gone.
+- A poll belongs to the process that executes its run: the generation it
+ names, or, for a poll from before generations, the process whose record marks
+ its native session running. While another Runtime's record proves that process
+ live (`other_runtimes_live_records()`, through the same
+ `_record_proves_process` every record reader uses), restore leaves the poll
+ untouched: no bind, no rewrite, no settlement. Its Runtime resumes it. Once
+ the process is gone, no process runs the poll's run, and this controller
+ settles it as after a restart. An app update therefore never strands a turn.
+
+| Path | Disposition |
+| --- | --- |
+| Adoption, including legacy conversion and dedupe, unproven-record removal, and the unhealthy-server stop | gated |
+| Adoption's sweep of overlays without a record | removed: another Runtime writes its overlay before it spawns and records the process |
+| `ensure_adopted` lease re-hold, marker reconciliation, `reap()` flush, and `_stop` | act only on generations this runtime attached, so they are ours |
+| `stop_owned_generations_sync()` (controller shutdown) | gated for records, and limited to processes owned here; an owned process with no record is ours by spawn |
+| `stop_recorded_servers_sync(runtime_ids)` (`vibe stop` and a disabled startup) | gated for the caller's ids; the inline refusal moved into the gate |
+| `forget_dead_records(runtime_ids)` and `recorded_servers(runtime_ids)` | gated |
+| Status: `vibe/api.py` `_opencode_process_status` → `recorded_servers()` | gated by the UI process's provenance, so another Runtime's servers do not count |
+| Lease release | reaches only the holder or the registered agent, so it is ours |
+| `start_generation` | writes `desktop_runtime_id` |
+| `restore_active_polls` | leaves every poll whose run another Runtime's live process executes; resumes the rest |
+
+### Known by design
+
+- **K1.** A controller crash in the microseconds between spawn and the first
+ record write leaves one unrecorded process.
+- **M2 pin.** A turn whose marker clear fails keeps its generation, through
+ marker and durable poll, until the next restore or cap pressure. This is
+ master's contract. In the reverse case, a cleared marker whose poll removal
+ failed, the next restore settles the poll.
+- **K4.** A second cancellation inside a failed start's cleanup can leave a
+ stale record, or a recorded process that is never signalled, until
+ `vibe stop`, shutdown, or the next adoption.
+- **K6.** A poll left to another Runtime keeps its durable turn live here,
+ so the core queues new messages on that session behind it. An idle
+ `opencode serve` never exits on its own, so after that Runtime's controller
+ crashed, its turn waits until that Runtime runs here again or its server is
+ stopped, for example by its scoped `vibe stop --expect-runtime-id`. Taking
+ it over instead would settle the run from a server that does not run it.
+- **K5.** After shutdown stops the recorded generations, a late write can
+ recreate the record of a killed process; it is removed as dead later.
+- **Core reconciler latency.** A generation that drains while the reconciler
+ pass that declined it is still running waits for the next release or sweep
+ (60 s, or the closed runtime's own sweep). This is core behavior.
diff --git a/docs/plans/runtime-generations.md b/docs/plans/runtime-generations.md
new file mode 100644
index 000000000..170b126b8
--- /dev/null
+++ b/docs/plans/runtime-generations.md
@@ -0,0 +1,513 @@
+# Runtime Generations
+
+Status: approved by the owner on 2026-10-01 (decisions recorded below). Supersedes the per-backend catalog
+compatibility approach in #2328 (draft). Extends `backend-rolling-restart.md`
+by implementing its deferred "prepare a new generation during DRAINING".
+
+## Background
+
+### One case today
+
+A user adds model `X` to the Codex catalog. Session `S1` is running a two-hour
+task in `/repo`, and session `S2` in the same directory sends a message.
+
+1. The catalog callback calls `BackendRestartCoordinator.request_restart`.
+2. Admission closes for every Codex directory. `S2`'s message, and any message
+ to any other Codex session, waits.
+3. After 300 s `S1` is force-interrupted, every app-server is stopped, and
+ admission reopens.
+
+The same drain-then-interrupt runs for any `agents.*` save, credential change,
+OpenCode provider edit, manual restart, or CLI install. It runs for Claude
+too, although every Claude session owns its own process.
+
+### What exists, and what does not
+
+- Shared runtime units: a Claude client serves one session; a Codex app-server
+ serves one working directory; one `opencode serve` serves the whole instance.
+- `backend-rolling-restart.md` defines the barrier
+ `READY -> DRAINING -> SWITCHING -> READY`. Turns admitted before the barrier
+ finish on the old process, while new turns wait. The document defers
+ "prepare a new generation during DRAINING", so no backend runs an old and a
+ new process side by side.
+- `RuntimeActivationRegistry` keeps exactly one live generation per
+ `(backend, resource)`. It is a fence against late commits from a retired
+ process, not a router.
+
+### How changes reach runtimes today
+
+| Trigger | Policy | Interrupts running work |
+| --- | --- | --- |
+| `agents.*` save, credential save or removal, OpenCode provider edits, manual restart, CLI install job | Whole-backend drain, 300 s, then interrupt | Yes |
+| Hub/Direct mode switch, native credential migration | Immediate interrupt, user-confirmed | Yes, by design |
+| Unattended CLI auto-update | Only when idle, otherwise skipped | No |
+| Codex gateway channel or token change | Per directory: wait 30 s, then refuse the new turn | Only the same session's own stale turn |
+| OpenCode overlay change | The next turn waits for every run on the shared server, with no bound | No, but new turns can wait indefinitely |
+| Claude per-session launch input change | Some inputs wait for the session to idle (no bound); others rebuild immediately | Possibly, for immediate rebuilds |
+
+Defects found while mapping these paths:
+
+- Fields that are read live still drain and interrupt, for example
+ `idle_timeout_seconds`, and Codex's unused `auth_mode`.
+- Direct-mode Claude credentials and the CLI path are never compared on
+ client reuse. Their correctness depends on the global teardown.
+- An in-place OpenCode CLI upgrade keeps the old server, because an unchanged
+ binary path selects the `PATCH /global/config` reload.
+- Codex interrupts the session's own turn before it knows the replacement can
+ proceed. If the directory stays busy, both turns are lost.
+- No turn is bound to one configuration snapshot from model resolution through
+ process launch. Review of #2328 kept finding races where a turn resolved its
+ model from one catalog and ran on a runtime holding another.
+
+## Goal
+
+- **G1.** A new turn or session is never blocked or refused because of a
+ configuration change. No routine change interrupts running work, except to
+ reclaim a generation at the cap below.
+- **G2.** Every turn runs against one configuration snapshot end to end. Its
+ model resolution and its runtime's launch inputs come from the same snapshot.
+- **G3.** One mechanism serves all backends. Backends differ only in how they
+ declare their runtime unit, their launch spec, and whether generations can
+ run side by side.
+
+Exclusive, user-confirmed operations keep their explicit cutover: Hub/Direct
+mode switch, native credential migration, and an explicit "stop running work".
+
+## Model
+
+**Configuration snapshot.** An immutable view of every input that affects a
+runtime: Model Hub configuration and catalogs, `agents.*` runtime config, and
+credential identity. A turn captures one snapshot when it is admitted.
+
+**Runtime unit.** The scope one runtime process serves:
+
+- Claude: one session client (composite session key);
+- Codex: one working directory;
+- OpenCode: the Avibe instance.
+
+**Launch spec.** A comparable digest, computed by the backend, of every
+process-level input for a unit under a snapshot. It covers binary identity
+(resolved path and version), credential identity, Hub channel, gateway URL and
+token, catalog or overlay digest, managed policy, and launch environment.
+Per-turn inputs (model, effort, prompt text, per-turn routing metadata) are not
+part of it.
+
+**Generation.** One running process for a unit, with one launch spec. It is in
+one of three states:
+
+- `current`: admits new turns;
+- `retiring`: serves only work already bound to it;
+- `stopped`.
+
+A unit has at most one `current` generation and a bounded number of
+`retiring` ones.
+
+**Binding.** A turn binds to exactly one generation at admission, together
+with any Activity, delivery, or scheduled run it owns. Only bound work keeps a
+retiring generation alive.
+
+### Turn admission
+
+1. Capture the snapshot and resolve the turn's launch (model, route, efforts)
+ from it.
+2. Compute the unit's desired launch spec from the same snapshot.
+3. Let `G` be the unit's current generation:
+ - if `G.spec == desired`, bind to `G`;
+ - otherwise, if nothing is bound to `G`, replace `G` in place and bind;
+ - otherwise, if the backend runs generations side by side, start `G'` with
+ the desired spec, mark `G` retiring, and bind to `G'`;
+ - otherwise, when the new generation cannot coexist with `G` (the cap is
+ reached, or the backend cannot run the two side by side), force-stop the
+ oldest conflicting generation, interrupt its work with the standard
+ runtime-update notice, and start `G'`. The new turn never waits for the
+ old work and is never refused.
+4. When a retiring generation's bound work reaches zero, stop it.
+5. When a stale current generation goes idle, replace it eagerly, so the next
+ turn does not pay the startup cost.
+
+The same example under this model: `S2` resolves with the snapshot that
+contains `X`. `/repo`'s app-server is busy with `S1`, so Avibe starts a second
+app-server for `/repo` and `S2` resumes its thread there. `S1` finishes on the
+first app-server, which then stops. `S1`'s next turn runs on the second one.
+
+### Invariants
+
+- A session is active on at most one generation at a time. The session turn FSM
+ already guarantees one active turn per session.
+- A generation stops only when no turn, Activity, delivery, or durable owner is
+ bound to it. Durable ownership snapshots already enumerate these.
+- Starting a generation is serialized per backend.
+- A unit runs at most three generations. When another one is needed at the
+ cap, the new one starts first and the oldest retiring generation is then
+ force-stopped, so a failed start costs no running work. Its sessions get the
+ runtime-update interruption notice and continue on the current generation.
+- Teardown never runs under the generation lock, because a forced stop settles
+ work that releases its bindings. A teardown that fails or is cancelled keeps
+ the generation tracked, closed to admission, so the next sweep retries it.
+
+## Per-backend design
+
+### Claude Code
+
+- **Unit:** one session client.
+- **Side by side:** not within one session. Two processes must never resume
+ the same session transcript concurrently.
+- **Launch spec:** compared on every reuse:
+ - the Model Hub launch fingerprint (channel, gateway, token, process
+ settings);
+ - reasoning effort;
+ - system prompt;
+ - caller identity, Skill bindings, git PATH;
+ - the renewal epoch. Direct-mode credentials and the CLI path change only
+ through flows that renew, so the epoch covers them.
+- **Spec change while the session's own background Activity runs:** the turn
+ stays on the session's current client, keeping that client's process inputs,
+ and the session switches at its next idle point. Only when that client
+ cannot serve the turn is it force-stopped and replaced. That happens when the
+ turn's Hub launch needs a different gateway route, token, or process settings,
+ and when the turn comes from a different caller, whose resource authority
+ the old process must never carry.
+ A model added after the client started does not count: a live client accepts
+ `set_model` for it, which a hermetic probe confirmed on Claude CLI 2.1.286.
+ Nothing waits.
+- **Removed:** the backend-wide barrier and the `refresh_auth_state` teardown
+ for routine changes. A configuration or credential save only advances the
+ snapshot. Each session rebuilds at its next turn when its spec differs.
+
+### Codex
+
+- **Unit:** one working directory.
+- **Side by side:** yes, behind the verification gate below.
+- **Launch spec:** binary identity, credential identity (`CODEX_HOME` auth
+ digest), Hub channel, gateway URL and token, catalog digest, managed launch
+ environment.
+- **Routing:** `_transports[cwd]` becomes the directory's generation set. A
+ session's live turn is routed to the generation it is bound to. A new turn
+ goes to the current generation and resumes its thread there, which replacement
+ already does today.
+- **Removed:**
+ - the 30 s runtime-change wait and `CodexRuntimeChangeBlockedError` for
+ routine changes;
+ - `_interrupt_active_turn_before_runtime_change`;
+ - the catalog compatibility checks from #2328;
+ - `refresh_auth_state` as the apply path for configuration and credential
+ changes.
+
+### OpenCode
+
+- **Unit:** the instance.
+- **Side by side:** yes. See the verification below.
+- **Launch spec:**
+ - binary identity;
+ - Hub overlay digest;
+ - managed policy revision and caller-context plugin digest;
+ - digest of the user `opencode.json` and `auth.json` that the server loads.
+- **Required changes:**
+ - one port per generation (the pinned 4096 goes away);
+ - one PID record per generation, and adoption of every recorded generation
+ after a controller restart;
+ - per-generation event streams, poll loops, and active-run tracking;
+ - serialized generation starts.
+- **Removed:**
+ - the overlay transition and its reservations;
+ - the deferred auth refresh flags;
+ - the `PATCH /global/config` reload path;
+ - the policy-pending and plugin-pending refusals;
+ - the compatibility checks from #2328.
+
+## Existing mechanisms and their fate
+
+Rule: a lifecycle that can run through generations does. Only an operation that
+must be exclusive for safety keeps a dedicated path. A legacy convention is not
+a reason to keep a path.
+
+| Mechanism today | Used by | Fate |
+| --- | --- | --- |
+| `BackendRestartCoordinator.request_restart`: whole-backend drain, 300 s, then interrupt | `agents.*` save; credential save or removal; Web OAuth; IM `/setup`; OpenCode provider edits; manual Restart; CLI install job; catalog changes before #2328 | Replaced. Every caller advances the snapshot. The drain path is deleted. |
+| `migration_guard`: immediate interrupt, then exclusive cutover | Native credential migration, startup migration recovery, Hub re-authentication | Kept. Custody needs exclusivity: an old process can rewrite a credential file that is being moved. |
+| `migration_guard` for the Hub/Direct mode switch | Mode toggle | Replaced. Mode becomes a launch-spec input. The gateway keeps admitting turns bound to a Hub-mode generation until they end, so a switch interrupts nothing. |
+| `run_when_idle` | Unattended CLI auto-update | Kept for the install step only. The refresh that follows is replaced by the binary identity in the spec. |
+| Backend drain admission (`begin/end_backend_drain`, `wait_backend_ready`) | All coordinator paths | Kept only inside `migration_guard` and the install window. |
+| `RuntimeActivationRegistry` | Turn, Activity, delivery, and scheduled-task commits | Kept as the fence. Each generation gets its own resource key, so one live identity per key still holds. |
+| Durable runtime ownership snapshots | Replacement safety | Kept as the evidence that a generation is drained. |
+| `restart_backend` marker file and `RuntimeCommandWatcher` | UI-process requests to the controller | Kept as the signal. Its action becomes "advance the snapshot", or "renew generations" for manual Restart. |
+| CLI install job fingerprint (path, realpath, version) | Decides whether to restart after an install | Replaced. Binary identity is part of every launch spec. |
+| Claude `refresh_auth_state` global teardown | Every Claude refresh | Kept for shutdown and migration only. |
+| Claude lazy rebuild on fingerprint or effort change: waits for idle with no bound | Hub route, process settings, effort | Unified under the Claude rule. |
+| Claude immediate rebuild on prompt, caller env, Skills, or git PATH change | Reuse check | Unified under the Claude rule; these become spec inputs. |
+| Codex `refresh_auth_state` stop-all | Every Codex refresh | Kept for shutdown and migration only. |
+| Codex fingerprint replacement: 30 s wait, then `CodexRuntimeChangeBlockedError` | Channel or token change | Replaced by directory generation sets. |
+| Codex `_interrupt_active_turn_before_runtime_change` | Channel change | Deleted. A new message to a busy session keeps Codex's normal semantics. |
+| Codex catalog invalidation and the #2328 compatibility checks | Catalog change | Replaced. The catalog digest is a spec input. |
+| Codex replaced-cwd, dead-transport, and idle-eviction replacement | Health | Kept. Idle eviction becomes the generation reaper. |
+| OpenCode `PATCH /global/config` reload | Settings and credential refreshes | Deleted. User config and credential digests are spec inputs. |
+| OpenCode deferred refresh (`_auth_refresh_pending`, `_pending_runtime_config`) | Busy refreshes | Deleted. |
+| OpenCode overlay transition and reservations | Hub overlay changes | Deleted. The overlay digest is a spec input. |
+| OpenCode policy-pending and plugin-pending refusals | Policy or plugin changes | Deleted. Both are spec inputs, so new turns are never refused. |
+| OpenCode single-port singleton manager, one PID file, adoption | Every OpenCode turn | Replaced by generation servers on dynamic ports, one PID record per generation, and adoption of every record. |
+| UI-process OpenCode manager calling `ensure_running` | Web OAuth flows | Replaced. The UI process asks the controller and never launches a server. |
+
+Defects that the refactor fixes as it touches these paths:
+
+- Claude `idle_timeout_seconds` is read once at startup. It becomes live.
+- An in-place OpenCode CLI upgrade is ignored. Binary identity includes the
+ version.
+- Codex direct launches with Model Hub enabled lose the desktop-managed
+ environment.
+- Codex `direct` and `native_cli` launch identical processes under different
+ fingerprints. Comparing specs removes the needless replacement.
+
+## Triggers after the refactor
+
+| Trigger | Action |
+| --- | --- |
+| `agents.*` save, credential save or removal, provider settings, CLI install or upgrade, catalog edit, built-in snapshot refresh, credential-address repair, Hub/Direct mode switch | Advance the snapshot. Each unit switches generation at its next turn. |
+| Manual "Restart backend" | Renew generations: new turns start a new generation, and old ones retire when their work is done. Nothing is interrupted. |
+| Explicit "stop running work" | The existing interruption path. |
+| Native credential migration, migration recovery, Hub re-authentication | `migration_guard`, unchanged. |
+| Unattended CLI auto-update | `run_when_idle` for the install step only. |
+| Backend disabled | Its work stops at once with the interruption notice, and its agent is destroyed. New messages get the disabled reply at once. |
+| Backend enabled | A new agent registers at once. |
+
+The `AGENTS.md` rule that an `agents.*` save reconciles "through the backend
+rolling-refresh path" becomes: the save advances the snapshot, and live units
+move to it through generations.
+
+## Core contract
+
+Implemented in the first PR; the Codex and OpenCode adapters build on it.
+
+- **Renewal instead of restart.**
+ - `BackendRestartCoordinator.request_restart(backend)` first asks
+ `AgentAuthService.renew_backend_runtime(backend)`. When the backend's agent
+ implements `renew_runtime(runtime_config)`, the coordinator adopts the
+ config and returns `"restarted"` without a drain.
+ - Every routine trigger reaches the coordinator, so implementing the hook
+ moves all of them at once: `agents.*` saves, credential flows, provider
+ edits, manual Restart, and the install job.
+ - Enabling and disabling a backend follow the same rule; see "One
+ lifecycle: deleting the drain path" below.
+- **Renewal epoch.**
+ - `renew_runtime(runtime_config, *, config_save)` bumps the backend's renewal
+ epoch, which is part of every launch spec. A config save
+ (`config_save=True`) whose only changes are fields read live renews
+ nothing. Each unit therefore moves at its next turn even when the
+ change is invisible to the spec, such as a credential written to the
+ CLI's own store.
+ - `idle_timeout_seconds` is read on every idle sweep, so it needs no
+ renewal at all.
+- **Catalog changes.** The Model Hub catalog callback calls the agent's
+ `adopt_model_hub_catalog()` when present. Claude's is a no-op because each
+ turn resolves its launch. Without the hook, the legacy path runs.
+- **`modules/agents/runtime_generations.py`.** `RuntimeGenerationSet` holds
+ one unit's generations.
+ - `acquire(spec)` runs admission step 3: reuse, replace in place when idle,
+ or start a new current generation while the busy one retires. At the cap
+ of three, the oldest retiring generation is force-stopped. A failed start
+ leaves the current generation serving.
+ - `reap()` stops drained retiring generations, and `stop_all(force)` serves
+ shutdown.
+ - Adapters provide `start(spec)` and `stop(generation, force) -> bool`, and
+ own the routing of bound work. The core decides "drained" from its own
+ binding count alone. A graceful stop may decline with `False` while the
+ adapter's own evidence still shows work. That evidence always includes
+ an Activity the process started (`AgentService.activation_has_activities`):
+ an Activity can outlive its turn and its Session's move to a newer
+ process, so no Session binding names it any longer.
+ - Admission is pure bookkeeping: every state change happens in one
+ synchronous step, and no admission path ever awaits a teardown. One
+ reconciler task per set owns every stop. It runs stops one at a time and,
+ after each, re-evaluates the cap and which generations are drained.
+ - The cap counts every attached generation, including ones whose graceful
+ stop declined. When a unit is over the cap, the oldest generation is
+ force-stopped. Admission never waits, so while a forced stop is still
+ running, a unit can briefly exceed the cap by one generation for each new
+ spec that arrives. The adapter's forced stop has a bounded kill timeout,
+ and once it returns, the reconciler stops the unit back down to the cap.
+ - A declined stop is retried on the next release or sweep. A failed or
+ cancelled stop is retried only by the next sweep; the generation is
+ `closed`, so it never serves a turn again. A sweep or stop-all that
+ arrives while a stop runs entitles every generation, including that one,
+ to one more attempt.
+ - `stop_all` closes admission first. A graceful `stop_all` lets bound
+ generations finish their work. `settled()` waits for the reconciler.
+- **Forced stops.** `AgentService.force_end_runtime_activities(backend,
+ runtime_key)` settles one runtime's Activities as interrupted by a runtime
+ update, using the existing backend-refresh notice.
+- **Snapshot discipline.** A turn loads its configuration once. Its launch
+ resolution and its launch spec both derive from that load. Each adapter
+ reads every mutable launch input (config, renewal epoch, binary and
+ credential identity, Hub snapshot) in one synchronous step before its
+ first await, and nothing after that step reads adapter state.
+
+## Verification
+
+### OpenCode, two servers on one home (done)
+
+Hermetic probe, OpenCode 1.18.33, temporary `HOME` and XDG directories, fake
+OpenAI-compatible upstream. Two `opencode serve` processes ran on different
+ports over one data directory:
+
+| Check | Result |
+| --- | --- |
+| Storage | One SQLite database in WAL mode (`opencode.db`, `-wal`, `-shm`) |
+| Session created and prompted on A | Visible on B with its messages |
+| Same session continued on B | Both servers then list four messages; no stale cache on A |
+| Concurrent prompts on different sessions, one per server | Both completed in parallel (1.6 s against a 1.5 s upstream delay) |
+| Both servers started at the same moment on a fresh home | Both failed with `database is locked` while migrating. Starting them in sequence works, so generation starts must be serialized. |
+
+### Codex, two app-servers in one directory (gate for the Codex PR)
+
+Hermetic probe with a fake Responses upstream:
+
+- two app-servers run in one directory at the same time;
+- a thread started on A resumes on B while A is still alive;
+- A's later shutdown appends nothing to that thread's rollout.
+
+If the last check fails, A must unload a thread before the thread moves.
+
+## Delivery
+
+Three PRs; the second and third run in parallel lanes:
+
+1. **Core and Claude** (orchestrator):
+ - the core contract above;
+ - Claude on the complete launch spec and the Claude rule;
+ - every routine trigger renewed in place through the coordinator. Codex
+ and OpenCode keep their current path until their own PR lands;
+ - the Model Hub catalog callback;
+ - this document and `AGENTS.md`.
+2. **Codex** (lane):
+ - the verification gate;
+ - directory generation sets;
+ - Codex triggers on the new entry;
+ - the Codex defects above.
+3. **OpenCode** (lane):
+ - generation servers;
+ - OpenCode triggers on the new entry;
+ - removal of the reload, deferral, transition, and refusal paths;
+ - the UI-process launch path.
+
+The Hub/Direct mode switch is a snapshot change in the first PR. It never enters
+`migration_guard`. The gateway keeps resolving a Hub turn that was admitted
+before a switch to Direct, until that turn ends.
+
+The Codex adapter is integrated into the first PR's branch before that PR
+merges, so the shared core ships with a production caller. The OpenCode
+adapter follows as a stacked PR. The drain-then-interrupt path is deleted
+once the last backend renews in place.
+
+Each PR ships scenario IDs and regression tests that fail on the code before
+it.
+
+## One lifecycle: deleting the drain path
+
+Once all three adapters renew in place, no routine trigger needs the drain.
+Enabling a backend registers it at once. Disabling a backend is the one
+change that stops work, because the user asked for exactly that.
+
+### Example
+
+Codex is running a long turn in `~/app` when the user turns Codex off in
+Settings. Before this step, new Codex messages were held for up to 300 s, then
+the running turn was interrupted, and only then did the held messages get the
+"Codex is disabled" reply. After this step:
+
+1. The save reaches `request_restart("codex", config_save=True)`. The Codex
+ agent leaves the registry at once, so a new message gets the disabled
+ reply without waiting.
+2. The turn in `~/app` and its Activities settle as `backend_disabled`,
+ through the coordinator's `interrupt_backend`, which the native credential
+ cutover also uses with `backend_refresh`. The conversation is told "This
+ turn was stopped because Codex was turned off", and a Harness run ends
+ `canceled` with the same explanation, because the user chose this.
+3. `shutdown_runtime()` stops every app-server of the agent, and the agent is
+ gone. A turn that raced the disable fails visibly with
+ `error.agentRuntimeRetired` and starts nothing.
+4. Turning Codex back on registers a fresh agent at once.
+
+An earlier draft let a disabled backend's agent keep its running work and
+drain, and let a re-enable reopen it. Every lookup that serves running work
+then had to reach retired agents, and review kept finding the ones that did
+not. The owner decided that a disable, being the user's own action, should
+simply stop the work, and that machinery is gone.
+
+### Coordinator
+
+- `request_restart(backend, *, config_save)` never drains or holds a message.
+ `AgentAuthService.renew_backend_runtime` owns the cases:
+ - **Registered and enabled:** `renew_runtime`, unchanged.
+ - **Codex or OpenCode disabled:** unregister, `interrupt_backend`, then
+ `shutdown_runtime()`. A cancelled requester never leaves it half done.
+ - **Claude disabled:** Claude stays registered with `enabled=False`, as
+ before. Its work is interrupted the same way, and the clients live at
+ that moment, busy ones included, are captured by identity and closed; a
+ retry closes only those, never a client of a re-enabled backend. Saving
+ again while it is disabled interrupts nothing more.
+
+ Disable-teardown ownership: the core's backend-wide interrupt is the fast
+ path, and it is skipped once the backend is enabled again. The guaranteed
+ settlement is scoped to what the disable captured: the disabled agent's own
+ generations (adapter forced stop with `settle_reason`), or Claude's captured
+ clients. The core matches that work by owner, never by key: every forced
+ generation stop, a disable's or the cap's, ends the Activities started
+ under that process's activation identity, whatever runtime key they carry
+ and whether or not a Session still binds the process, and settles turns
+ only where the stopping agent holds the Session's turn gate
+ (`force_end_runtime_work(..., activation_identities=, agent=)`). A retry
+ after a re-enable therefore still finishes the disabled agent's work and
+ touches nothing new, and an Activity that outlived its turn or its
+ Session's move still settles with its process.
+ - **Enabled but not registered:** a new agent registers at once.
+- `run_when_idle` keeps admission closed for the install step only. Afterwards
+ it renews instead of refreshing.
+- `migration_guard` is unchanged.
+- Deleted: the 300 s drain, `AVIBE_BACKEND_RESTART_DRAIN_TIMEOUT_SECONDS`,
+ `"draining"` as a restart result, and the legacy catalog restart. The
+ refresh that tears a runtime down survives only inside `migration_guard`.
+
+### Adapter hooks
+
+| Hook | Meaning |
+| --- | --- |
+| `renew_runtime(config, *, config_save)` | Unchanged. |
+| `reap_runtime_generations()` | Called by the 60 s sweep on every registered agent. |
+| `shutdown_runtime(settle_reason=None)` | Stop every process of this agent now. A disable passes `settle_reason="backend_disabled"`, and every forced stop then settles the turns and Activities bound to that process with it, scoped to this agent instance; service shutdown and probe teardown pass nothing and show no notice. It raises when any process survives, so `AgentService.run_until_done` keeps the teardown and the idle sweep retries it; a retry must be idempotent and never touch another instance's work. |
+
+### Startup
+
+A controller that starts with OpenCode disabled stops the OpenCode servers
+recorded by a controller that crashed; no agent would ever adopt them. Their
+durable polls stay durable, and the next controller with OpenCode enabled
+restores them, as before. Codex app-servers and Claude clients exit with their
+parent's stdio, so they leave nothing behind.
+
+### Scenarios
+
+- **RUNTIME-GEN-006.** Disabling a backend stops its work at once: new
+ messages see it disabled, running work settles with the interruption
+ notice, and every process stops.
+- **RUNTIME-GEN-007.** Re-enabling registers a fresh agent at once.
+- **RUNTIME-GEN-008.** An unattended CLI update renews after the install
+ instead of refreshing.
+
+## Decisions
+
+Recorded from the owner, 2026-10-01:
+
+1. A configuration change never blocks or refuses a new turn or session. The
+ user experience takes precedence over legacy conventions.
+2. Manual "Restart backend" renews generations without interrupting running
+ work.
+3. A unit runs at most three generations. At the cap, the oldest retiring
+ generation is force-stopped and its work interrupted.
+4. When a Claude spec changes while the session's own background Activity
+ runs, the turn stays on the current client until the session is idle. The
+ client is force-replaced only when its snapshot cannot serve the turn.
+5. Lifecycles are unified under generations wherever safety allows. PRs are
+ few, and work that can run in parallel does.
+
+Recorded from the owner, 2026-10-03:
+
+6. Disabling a backend is an explicit, user-visible action. It stops that
+ backend's work immediately and destroys its agent; nothing drains.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 95ec28639..249b263ac 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -9,7 +9,11 @@ from typing import Any, Callable, Literal, Optional
from core.agent_auth_service import classify_auth_error
from core.agent_tool_policy import runs_in_background as tool_runs_in_background
from core.backend_failure import backend_failure_notification_output, emit_backend_failure
-from core.handlers.session_handler import ClaudeInputNotSentError, ClaudeSessionNotFoundError
+from core.handlers.session_handler import (
+ ClaudeBackendDisabledError,
+ ClaudeInputNotSentError,
+ ClaudeSessionNotFoundError,
+)
from core.message_dispatcher import ActivityOutputDeliveryError
from core.message_output import (
HARNESS_RUN_ID_TRIGGER_KINDS,
@@ -104,6 +108,18 @@ class _ClaudeOutputRecoveryRecord:
claim_metadata: dict[str, object] | None = None
+
+# Read live on every use, so changing them needs no new client.
+_CLAUDE_LIVE_CONFIG_FIELDS = frozenset({"idle_timeout_seconds"})
+
+
+def _claude_launch_inputs(claude_config: Any) -> dict[str, Any]:
+ return {
+ key: value
+ for key, value in vars(claude_config).items()
+ if key not in _CLAUDE_LIVE_CONFIG_FIELDS
+ }
+
class ClaudeAgent(BaseAgent):
"""Existing Claude Code integration extracted into an agent backend."""
@@ -542,6 +558,20 @@ class ClaudeAgent(BaseAgent):
session_id=composite_key,
)
+ async def _refuse_disabled_turn(self, context, request) -> None:
+ language = str(getattr(getattr(self.controller, "config", None), "language", "en") or "en")
+ await emit_backend_failure(
+ self.controller,
+ context,
+ self.name,
+ "claude backend disabled",
+ display_text=(
+ f"❌ {i18n_t('error.agentRuntimeRetired', language, agent=i18n_t('backend.claude', language))}"
+ ),
+ request=request,
+ )
+ await self._remove_ack_reaction(request)
+
async def handle_message(self, request: AgentRequest) -> None:
context = request.context
runtime_base_session_id = request.base_session_id
@@ -556,17 +586,30 @@ class ClaudeAgent(BaseAgent):
# await self._handle_question_callback(request)
# return
+ if getattr(getattr(self.config, "claude", None), "enabled", True) is False:
+ # Claude stays registered while disabled, so a turn queued behind
+ # the one the disable interrupted still reaches it. It must start
+ # nothing and say why, as Codex and OpenCode do.
+ await self._refuse_disabled_turn(context, request)
+ return
+
try:
- client = await self.session_handler.get_or_create_claude_session(
- context,
- subagent_name=request.subagent_name,
- subagent_model=request.subagent_model or getattr(request, "vibe_agent_model", None),
- subagent_reasoning_effort=(
- request.subagent_reasoning_effort
- or getattr(request, "vibe_agent_reasoning_effort", None)
- ),
- agent_system_prompt=getattr(request, "vibe_agent_system_prompt", None),
- )
+ try:
+ client = await self.session_handler.get_or_create_claude_session(
+ context,
+ subagent_name=request.subagent_name,
+ subagent_model=request.subagent_model or getattr(request, "vibe_agent_model", None),
+ subagent_reasoning_effort=(
+ request.subagent_reasoning_effort
+ or getattr(request, "vibe_agent_reasoning_effort", None)
+ ),
+ agent_system_prompt=getattr(request, "vibe_agent_system_prompt", None),
+ )
+ except ClaudeBackendDisabledError:
+ # Claude was turned off while this turn's client was being
+ # created; the client is already gone.
+ await self._refuse_disabled_turn(context, request)
+ return
runtime_base_session_id = getattr(client, "_vibe_runtime_base_session_id", runtime_base_session_id)
runtime_session_key = getattr(client, "_vibe_runtime_session_key", runtime_session_key)
mark_session_active = getattr(self.session_handler, "mark_session_active", None)
@@ -1052,6 +1095,32 @@ class ClaudeAgent(BaseAgent):
logger.info("Refreshed Claude auth state across %d runtime session(s)", len(session_ids))
+ async def adopt_model_hub_catalog(self) -> None:
+ """Nothing to apply: each turn resolves its model, limits, and efforts.
+
+ A session whose resolved launch changed moves to a new client at that
+ turn, by the same rule as any other launch-input change.
+ """
+
+ async def renew_runtime(self, claude_config, *, config_save: bool = False) -> None:
+ """Adopt persisted runtime config; each session moves to it at its next turn.
+
+ Every session owns its own process, so nothing drains or reconnects
+ here: a session's next turn starts a new client, unless background work
+ it started is still running. A config save that changes only fields read
+ live, such as the idle timeout, renews nothing.
+ """
+ previous = self.config.claude
+ self.config.claude = claude_config
+ self.controller.config.claude = claude_config
+ session_handler = getattr(self, "session_handler", None)
+ if session_handler is None:
+ return
+ session_handler.config = self.controller.config
+ if config_save and _claude_launch_inputs(previous) == _claude_launch_inputs(claude_config):
+ return
+ session_handler.renew_runtime()
+
async def refresh_runtime_config(self, claude_config) -> None:
"""Reload persisted runtime config before reconnecting Claude sessions."""
self.config.claude = claude_config
diff --git a/modules/agents/claude_process_reaper.py b/modules/agents/claude_process_reaper.py
index bda002a22..4ff10ffb5 100644
--- a/modules/agents/claude_process_reaper.py
+++ b/modules/agents/claude_process_reaper.py
@@ -34,24 +34,37 @@ class ClaudeOwnedProcess:
started_at: float | None = None
-def get_claude_client_pid(client: object | None) -> int | None:
- """Return the SDK-managed Claude CLI pid when the current SDK exposes it."""
- transport = getattr(client, "_transport", None)
- process = getattr(transport, "_process", None)
+def get_claude_client_process(client: object | None) -> object | None:
+ """Return the SDK-managed Claude CLI subprocess while the client holds it.
+
+ ``disconnect()`` drops the client's transport, so a caller that must
+ verify the process exits reads it first.
+ """
+ return getattr(getattr(client, "_transport", None), "_process", None)
+
+
+def _process_pid(process: object | None) -> int | None:
pid = getattr(process, "pid", None)
- return pid if isinstance(pid, int) and pid > 0 else None
+ return pid if isinstance(pid, int) and not isinstance(pid, bool) and pid > 0 else None
-def get_claude_client_returncode(client: object | None) -> int | None:
- """Return the Claude CLI exit code once its subprocess has terminated."""
- transport = getattr(client, "_transport", None)
- process = getattr(transport, "_process", None)
+def _process_returncode(process: object | None) -> int | None:
returncode = getattr(process, "returncode", None)
if isinstance(returncode, bool) or not isinstance(returncode, int):
return None
return returncode
+def get_claude_client_pid(client: object | None) -> int | None:
+ """Return the SDK-managed Claude CLI pid when the current SDK exposes it."""
+ return _process_pid(get_claude_client_process(client))
+
+
+def get_claude_client_returncode(client: object | None) -> int | None:
+ """Return the Claude CLI exit code once its subprocess has terminated."""
+ return _process_returncode(get_claude_client_process(client))
+
+
def claude_process_exit_reason(returncode: int) -> str:
"""Format a subprocess exit code for logs and user-facing diagnostics."""
if returncode < 0:
@@ -440,6 +453,36 @@ async def reap_duplicate_claude_resume_processes(
return await _reap_pid_set(target_pids, terminate_timeout=terminate_timeout, logger=logger)
+async def stop_claude_process(
+ process: object | None,
+ *,
+ logger: logging.Logger,
+ timeout: float = 5.0,
+) -> bool:
+ """Whether a Claude CLI subprocess is gone, stopping it and its tools first if not.
+
+ A failed ``disconnect()`` can leave the CLI and its tool processes running.
+ While the subprocess's returncode is unknown, its pid is still this
+ process's unreaped child, so signalling it can never reach a reused pid.
+ """
+ pid = _process_pid(process)
+ if pid is None or _process_returncode(process) is not None:
+ return True
+ try:
+ rows = _parse_ps_rows(await asyncio.to_thread(_run_ps))
+ except Exception:
+ # No process table, as on Windows: the CLI alone.
+ rows = []
+ await _reap_pid_set(_runtime_related_pids(rows, pid), terminate_timeout=timeout, logger=logger)
+ wait = getattr(process, "wait", None)
+ if callable(wait):
+ try:
+ await asyncio.wait_for(wait(), timeout=timeout)
+ except Exception:
+ logger.debug("Claude CLI pid=%s did not report its exit", pid, exc_info=True)
+ return _process_returncode(process) is not None
+
+
async def _reap_pid_set(
target_pids: set[int],
*,
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index c7f125bd8..69e9b246a 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -4,13 +4,17 @@ from __future__ import annotations
import asyncio
import hashlib
+import itertools
+import json
import logging
import os
import shlex
+import shutil
import time
+from collections import OrderedDict
from collections.abc import Mapping
-from contextlib import AsyncExitStack
-from dataclasses import dataclass
+from contextlib import AsyncExitStack, asynccontextmanager
+from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Sequence
@@ -34,6 +38,7 @@ from core.native_dispatch_phase import (
mark_prewrite_recovery_required,
)
from core.processing_indicator import STOPPED_REACTION_EMOJI
+from core.run_settlement import SETTLED_BY_BACKEND_REFRESH, SETTLED_BY_STOPPED
from core.prompt_registry import prompt_text
from core.services.agent_steering import (
ActiveSteerTarget,
@@ -67,7 +72,17 @@ from modules.agents.codex.event_handler import CodexEventHandler
from modules.agents.codex.session import CodexSessionManager
from modules.agents.codex.transport import CodexResponseTooLargeError, CodexRPCError, CodexTransport
from modules.agents.codex.turn_state import CodexTurnRegistry
-from vibe.codex_config import LEGACY_MANAGED_PROVIDER_IDS, MANAGED_PROVIDER_ID
+from modules.agents.runtime_generations import (
+ RuntimeBinding,
+ RuntimeGeneration,
+ RuntimeGenerationSet,
+ RuntimeUnitStopping,
+)
+from vibe.codex_config import (
+ LEGACY_MANAGED_PROVIDER_IDS,
+ MANAGED_PROVIDER_ID,
+ codex_credential_identity,
+)
from vibe.desktop_backends import desktop_backend_subprocess_environment
from vibe.i18n import t as i18n_t
from vibe.message_identity import is_input_turn
@@ -89,10 +104,84 @@ CODEX_CONNECTION_PROBE_DIR = "codex-connection-probe"
CODEX_PROMPT_STRATEGY_METADATA_KEY = "codex_prompt_strategy"
_STEER_RECONCILIATION_TTL_SECONDS = 300.0
_MAX_STEER_RECONCILIATION_TARGETS = 128
-# How long a runtime change waits for the shared per-cwd app-server to go idle.
-# Short waits cover a replacement prompt's own interrupted turn; a long job in
-# another Session must fail this turn visibly instead of holding it forever.
-_RUNTIME_CHANGE_WAIT_SECONDS = 30.0
+# How long a Session waits for the app-server generation it leaves to release
+# its thread. Codex bounds its own thread shutdown at 10 s.
+_THREAD_RELEASE_TIMEOUT_SECONDS = 15.0
+# Numbers agent instances: each owns the Model Hub scope of its own processes.
+_AGENT_INSTANCE_SERIALS = itertools.count(1)
+# Hub catalogs kept prepared for future launches; running generations hold
+# their own pins.
+_CACHED_HUB_CATALOGS = 2
+
+
+@dataclass(frozen=True, eq=False)
+class CodexLaunchSpec:
+ """Every process-level input of one app-server.
+
+ Two generations whose digests match were started from the same binary,
+ arguments, environment, credentials, and directory, so either can serve a
+ turn that needs this spec.
+ """
+
+ digest: str
+ cwd: str
+ binary: str
+ args: tuple[str, ...]
+ extra_args: tuple[str, ...]
+ env: Mapping[str, str] = field(repr=False)
+ hub: bool = False
+ catalog: CodexHubCatalog | None = field(default=None, repr=False)
+
+ def close(self) -> None:
+ """Release this spec's catalog pin; a started transport holds its own."""
+ if self.catalog is not None:
+ self.catalog.close()
+
+
+@dataclass(frozen=True, eq=False)
+class _LaunchInputs:
+ """A turn's whole configuration, captured in one synchronous step at admission.
+
+ Its Model Hub launch resolution, Hub catalog, launch spec digest, and
+ process all derive from this load, so a save or renewal that lands while
+ any of them is awaited changes nothing about the turn; the directory's
+ next turn moves. Nothing on the turn path reads the mutable source again.
+ """
+
+ # The Model Hub snapshot the launch resolves against; None without a router.
+ hub_config: Any = field(repr=False)
+ binary: str
+ extra_args: tuple[str, ...]
+ env: Mapping[str, str] = field(repr=False)
+ # Renewal epoch, binary and credential identity, and the cwd's inode.
+ identity: Mapping[str, Any] = field(repr=False)
+
+
+@dataclass(eq=False)
+class _CodexRuntime:
+ """One app-server process serving a working directory."""
+
+ cwd: str
+ serial: int
+ transport: CodexTransport
+ hub: bool = False
+ activation: RuntimeActivationIdentity | None = None
+ # base_session_id -> the Codex thread loaded in this process for it
+ threads: dict[str, str] = field(default_factory=dict)
+ # thread id -> set when this process reports ``thread/closed``
+ released_threads: dict[str, asyncio.Event] = field(default_factory=dict)
+ last_activity: float = field(default_factory=time.monotonic)
+ # Set once the process is gone. The shared core detaches a generation
+ # before its teardown runs, and a graceful teardown may still decline.
+ ended: bool = False
+ # Set while a teardown holds the activation fence; done when it finishes.
+ teardown: asyncio.Future[None] | None = None
+ # No unit holds this running process: it outlived its own failed start, or
+ # its setup failed after the spawn. The sweep retries its stop.
+ orphaned: bool = False
+
+
+_CodexGeneration = RuntimeGeneration[CodexLaunchSpec, _CodexRuntime]
@dataclass(frozen=True)
@@ -104,6 +193,7 @@ class _CodexSteerReconciliationTarget:
thread_id: str
cwd: str
recorded_at: float
+ runtime: _CodexRuntime | None = None
class _CodexConnectionProbeState:
@@ -129,10 +219,10 @@ class CodexConnectionProbeRuntimeMismatchError(RuntimeError):
"""The cached transport does not represent direct Codex credentials."""
-class CodexRuntimeChangeBlockedError(RuntimeError):
- """Another live turn owns the cwd transport that a runtime change must replace."""
+class CodexThreadReleaseUnavailableError(RuntimeError):
+ """The generation a Session leaves could not release the Session's thread."""
- reason = "transport_runtime_change_blocked"
+ reason = "codex_thread_release_unavailable"
class CodexModelHubCatalogUnavailableError(RuntimeError):
@@ -164,11 +254,12 @@ class CodexResumeUnavailableError(RuntimeError):
class CodexAgent(BaseAgent):
- """Codex CLI integration via persistent ``codex app-server`` subprocess.
+ """Codex CLI integration via persistent ``codex app-server`` subprocesses.
- One transport (subprocess) is maintained per unique working directory.
- Multiple Slack threads in the same channel share a transport but each
- gets its own Codex thread.
+ Each working directory has a set of app-server generations. New turns use
+ the current one; a generation started from older launch inputs keeps
+ serving the turns already running on it and stops once they drain.
+ Sessions in one directory share a generation, each with its own thread.
"""
name = "codex"
@@ -183,22 +274,31 @@ class CodexAgent(BaseAgent):
super().__init__(controller)
self.codex_config = codex_config
self._registered_runtime = registered_runtime
- self._model_hub_catalog: CodexHubCatalog | None = None
+ # (binary identity, configured models digest) -> prepared Hub catalog
+ self._model_hub_catalogs: OrderedDict[tuple[str, str], CodexHubCatalog] = OrderedDict()
self._model_hub_catalog_lock = asyncio.Lock()
- self._model_hub_catalog_generation = 0
- # cwd → CodexTransport (one persistent process per working dir)
- self._transports: Dict[str, CodexTransport] = {}
- self._transport_locks: Dict[str, asyncio.Lock] = {}
- self._transport_last_activity: Dict[str, float] = {}
+ # cwd -> the app-server generations serving that working directory.
+ # New turns use the current generation; a retiring one keeps serving
+ # the turns already running on it and stops once they drain.
+ self._units: Dict[str, RuntimeGenerationSet[CodexLaunchSpec, _CodexRuntime]] = {}
+ # base_session_id -> the generation its Codex thread is loaded in
+ self._session_generations: Dict[str, _CodexGeneration] = {}
+ self._generation_serials = itertools.count(1)
+ # cwd -> processes not yet ended, attached to their unit or not
+ self._runtimes: Dict[str, set[_CodexRuntime]] = {}
+ # Shutdown, which also serves disabling the backend, ends every
+ # process without the runtime-update notice and admits nothing more.
+ self._shutting_down = False
+ self._instance_serial = next(_AGENT_INSTANCE_SERIALS)
+ # Set by a disable's shutdown: every forced stop then settles the work
+ # bound to its generation with this reason. None shows no notice.
+ self._shutdown_settle_reason: str | None = None
+ # Part of every launch spec: renewing moves each cwd to a new process
+ # at its next turn.
+ self._runtime_epoch = 0
+ self._reap_tasks: set[asyncio.Task[None]] = set()
self._session_last_activity: Dict[str, float] = {}
- # cwd inode at app-server spawn time, keyed like ``_transports``. A
- # cached app-server whose directory was deleted (even if re-created
- # with the same path) sits in a dead inode and fails every
- # ``thread/start`` with a misleading "failed to load configuration:
- # No such file or directory" (#561); the inode comparison detects
- # that staleness BEFORE paying a failed RPC.
- self._transport_cwd_inodes: Dict[str, Optional[int]] = {}
self._session_mgr = CodexSessionManager()
self._turn_registry = CodexTurnRegistry()
@@ -232,26 +332,19 @@ 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
# ------------------------------------------------------------------
def backend_alive(self, context) -> Optional[bool]:
- """Liveness via the CodexTransport for this turn's working directory.
+ """Liveness of the app-server generation this turn's Session is bound to.
- Resolves base_session_id → cwd → transport and returns transport.is_alive.
Returns None (unknown) when anything can't be resolved, so the status
bubble never false-alarms ⚠️."""
payload = getattr(context, "platform_specific", None) or {}
base_session_id = str(payload.get("turn_base_session_id") or "").strip()
- if not base_session_id:
- return None
- cwd = self._session_mgr.get_cwd(base_session_id)
- if not cwd:
- return None
- transport = self._transports.get(cwd)
+ transport = self.transport_for_session(base_session_id) if base_session_id else None
if transport is None:
return None
return self._transport_alive(transport)
@@ -274,8 +367,7 @@ class CodexAgent(BaseAgent):
payload = getattr(context, "platform_specific", None) or {}
base_session_id = str(payload.get("turn_base_session_id") or "").strip()
- cwd = self._session_mgr.get_cwd(base_session_id) if base_session_id else None
- transport = self._transports.get(cwd) if cwd else None
+ transport = self.transport_for_session(base_session_id) if base_session_id else None
if transport is None:
return lambda: None
return lambda: self._transport_alive(transport)
@@ -288,8 +380,7 @@ class CodexAgent(BaseAgent):
payload = getattr(context, "platform_specific", None) or {}
base_session_id = str(payload.get("turn_base_session_id") or "").strip()
- cwd = self._session_mgr.get_cwd(base_session_id) if base_session_id else None
- transport = self._transports.get(cwd) if cwd else None
+ transport = self.transport_for_session(base_session_id) if base_session_id else None
if transport is None:
return None
@@ -335,14 +426,26 @@ class CodexAgent(BaseAgent):
return diagnose
def can_reuse_direct_connection_probe(self, cwd: str) -> bool:
- """Return whether a cached transport can test direct credentials."""
+ """Return whether a live generation can test the current direct credentials."""
- transport = self._transports.get(cwd)
- return bool(
- transport is not None
- and getattr(transport, "runtime_fingerprint", "direct") == "direct"
- and os.path.isdir(cwd)
- )
+ return self._direct_probe_generation(cwd) is not None
+
+ def _direct_probe_generation(self, cwd: str) -> _CodexGeneration | None:
+ """The live generation started exactly as a direct launch would start now."""
+
+ unit = self._units.get(cwd)
+ if unit is None or not os.path.isdir(cwd):
+ return None
+ inputs = self._launch_inputs(cwd)
+ digest = self._launch_spec_digest(inputs, args=(), env=inputs.env)
+ for generation in reversed(unit.generations):
+ if (
+ not generation.closed
+ and generation.spec.digest == digest
+ and generation.runtime.transport.is_initialized
+ ):
+ return generation
+ return None
async def probe_connection(
self,
@@ -362,22 +465,20 @@ class CodexAgent(BaseAgent):
state: _CodexConnectionProbeState | None = None
thread_id = ""
closed_task: asyncio.Task[None] | None = None
- probe_cwds = self._connection_probe_cwds
- owns_probe_cwd = False
+ binding: RuntimeBinding[CodexLaunchSpec, _CodexRuntime] | None = None
try:
- if (
- getattr(self, "_registered_runtime", True)
- and not self.can_reuse_direct_connection_probe(cwd)
- ):
- raise CodexConnectionProbeRuntimeMismatchError(
- "No cached direct Codex transport is available for the probe"
- )
- transport = await self._get_or_create_transport(
- cwd,
- allow_runtime_replacement=False,
- )
- probe_cwds[cwd] = probe_cwds.get(cwd, 0) + 1
- owns_probe_cwd = True
+ if getattr(self, "_registered_runtime", True):
+ # Never start or promote a process just to probe: that would
+ # change which generation serves this directory's turns.
+ generation = self._direct_probe_generation(cwd)
+ if generation is None:
+ raise CodexConnectionProbeRuntimeMismatchError(
+ "No live direct Codex generation is available for the probe"
+ )
+ binding = await self._unit(cwd).bind(generation)
+ else:
+ binding = await self._acquire_generation(cwd)
+ transport = binding.generation.runtime.transport
thread_response = await transport.send_request(
"thread/start",
@@ -434,7 +535,7 @@ class CodexAgent(BaseAgent):
raise RuntimeError(result)
if not result.strip():
raise RuntimeError("Codex Agent turn returned no response")
- self._touch_transport_activity(cwd)
+ self._touch_runtime(binding.generation.runtime)
return result
finally:
try:
@@ -465,15 +566,14 @@ class CodexAgent(BaseAgent):
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)
- if owns_probe_cwd:
- remaining = probe_cwds.get(cwd, 0) - 1
- if remaining > 0:
- probe_cwds[cwd] = remaining
- else:
- probe_cwds.pop(cwd, None)
+ try:
+ if closed_task is not None:
+ closed_task.cancel()
+ await asyncio.gather(closed_task, return_exceptions=True)
+ finally:
+ # Even a cancellation landing above must not leak the binding.
+ if binding is not None:
+ await binding.release()
async def _record_model_hub_native_failure(self, context: Any, diagnostic: str) -> bool:
router = getattr(self.controller, "model_hub_runtime", None)
@@ -490,223 +590,287 @@ class CodexAgent(BaseAgent):
"""Process a user message by routing it through app-server.
Flow:
- 1. Get or create transport for the working directory
+ 1. Bind to the working directory's app-server generation for this
+ turn's launch spec, moving the Session's thread there if needed
2. Get or create a Codex thread for this Slack thread
3. If a turn is active → interrupt it first
4. Start a new turn with the user's message
"""
- # Serialize turn lifecycle per session
- if request.base_session_id not in self._session_locks:
- self._session_locks[request.base_session_id] = asyncio.Lock()
-
- async with self._session_locks[request.base_session_id]:
- launch = None
+ async with self.session_lifecycle(request.base_session_id):
+ # A binding keeps the generation this turn admits to alive until the
+ # turn is registered there or has failed; a registered turn then
+ # keeps its generation alive as idle evidence of its own.
+ bindings: list[RuntimeBinding[CodexLaunchSpec, _CodexRuntime]] = []
try:
- # Register a complete durable binding before any transport
- # acquisition or resume can fail and require ownership checks.
- self.ensure_agent_session_id(request)
- self._session_mgr.set_session_key(request.base_session_id, request.session_key)
- self._session_mgr.set_cwd(request.base_session_id, request.working_path)
- self._bind_runtime_agent_session_id(request)
- if getattr(self.controller, "model_hub_runtime", None) is not None:
- from modules.agents.model_hub import bind_launch, resolve_model_hub_launch
-
- _, requested_model, _, _ = self._resolve_codex_agent_settings(request)
- launch = await resolve_model_hub_launch(
- self.controller,
- "codex",
- requested_model or "",
- process_scope=request.working_path,
- context=request.context,
- )
- bind_launch(request.context, launch)
- await self._interrupt_active_turn_before_runtime_change(request, launch)
- transport = await self._get_or_create_transport(request.working_path, launch)
- else:
- transport = await self._get_or_create_transport(request.working_path)
- except FileNotFoundError:
- await emit_backend_failure(
- self.controller,
- request.context,
- self.name,
- "Codex CLI not found",
- display_text="❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",
- request=request,
- )
- await self._remove_ack_reaction(request)
- self._event_handler._release_stream_turn(request.context)
- return
- except Exception as e:
- from modules.agents.model_hub import launch_refusal_copy
+ await self._handle_message_locked(request, bindings)
+ except asyncio.CancelledError:
+ # A cancelled admission owns no turn, whether it was cancelled on
+ # its first attempt or on its retry; a pending start left behind
+ # would keep its generation from ever stopping.
+ self._turn_registry.clear_pending_turn_start(request.base_session_id, request)
+ raise
+ finally:
+ for binding in bindings:
+ await binding.release()
+
+ @asynccontextmanager
+ async def session_lifecycle(self, base_session_id: str):
+ """Serialize one Session's lifecycle.
+
+ Turn admission holds it, and so must every other operation that
+ changes the Session's thread binding or in-memory state (End,
+ ``/new``, resume preparation), so none can interleave with a turn. A
+ holder may forget the lock as its last step; a waiter that then wakes
+ on the forgotten lock retries on the current one, so two holders
+ never overlap.
+ """
+ while True:
+ lock = self._session_locks.get(base_session_id)
+ if lock is None:
+ lock = self._session_locks[base_session_id] = asyncio.Lock()
+ async with lock:
+ if self._session_locks.get(base_session_id) is lock:
+ yield
+ return
- logger.error("Failed to start Codex transport: %s", e, exc_info=True)
- language = str(
- getattr(getattr(self.controller, "config", None), "language", "en")
- or "en"
- )
- refusal = launch_refusal_copy(self.controller, e)
- if isinstance(e, CodexRuntimeChangeBlockedError):
- # Not a source failure: no Hub cooldown. Hold the unwritten
- # input for an explicit retry once the blocking turn ends.
- mark_prewrite_recovery_required(request.context, e.reason)
- display_text = f"❌ {i18n_t('error.codexRuntimeChangeBlocked', language)}"
- elif isinstance(e, CodexModelHubCatalogUnavailableError):
- await self._record_model_hub_native_failure(request.context, str(e))
- display_text = f"❌ {i18n_t('modelHub.errors.codex_catalog_unavailable', language)}"
- elif refusal is not None:
- await self._record_model_hub_native_failure(request.context, str(e))
- display_text = f"❌ {refusal}"
- else:
- await self._record_model_hub_native_failure(request.context, str(e))
- display_text = f"❌ Failed to start Codex CLI: {e}"
- await emit_backend_failure(
+ def _forget_session_lock(self, base_session_id: str) -> None:
+ """Forget a Session's lock unless a turn admission holds it."""
+ lock = self._session_locks.get(base_session_id)
+ if lock is not None and not lock.locked():
+ self._session_locks.pop(base_session_id, None)
+
+ async def _handle_message_locked(
+ self,
+ request: AgentRequest,
+ bindings: list[RuntimeBinding[CodexLaunchSpec, _CodexRuntime]],
+ ) -> None:
+ launch = None
+ inputs: _LaunchInputs | None = None
+ try:
+ if self._shutting_down:
+ # Past the agent lookup already: refuse before anything is
+ # recorded or a Hub launch is resolved for this turn.
+ raise RuntimeUnitStopping("runtime unit is stopping")
+ # Register a complete durable binding before any transport
+ # acquisition or resume can fail and require ownership checks.
+ self.ensure_agent_session_id(request)
+ self._session_mgr.set_session_key(request.base_session_id, request.session_key)
+ self._session_mgr.set_cwd(request.base_session_id, request.working_path)
+ self._bind_runtime_agent_session_id(request)
+ router = getattr(self.controller, "model_hub_runtime", None)
+ hub_snapshot = getattr(router, "snapshot", None)
+ # The turn's whole configuration is one load, taken here before
+ # anything awaits: its Hub launch, catalog, spec, and process all
+ # derive from it, so a concurrent save or renewal cannot split them.
+ inputs = self._launch_inputs(
+ request.working_path,
+ hub_config=hub_snapshot() if callable(hub_snapshot) else None,
+ )
+ if router is not None:
+ from modules.agents.model_hub import bind_launch, resolve_model_hub_launch
+
+ _, requested_model, _, _ = self._resolve_codex_agent_settings(request)
+ launch = await resolve_model_hub_launch(
self.controller,
- request.context,
- self.name,
- str(e),
- display_text=display_text,
- request=request,
- cause=e,
+ "codex",
+ requested_model or "",
+ process_scope=self._hub_process_scope(request.working_path),
+ context=request.context,
+ config=inputs.hub_config,
)
- await self._remove_ack_reaction(request)
- self._event_handler._release_stream_turn(request.context)
- return
+ bind_launch(request.context, launch)
+ binding = await self._acquire_generation(request.working_path, launch, inputs=inputs)
+ bindings.append(binding)
+ await self._move_session_to(binding.generation, request)
+ except FileNotFoundError:
+ await emit_backend_failure(
+ self.controller,
+ request.context,
+ self.name,
+ "Codex CLI not found",
+ display_text="❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",
+ request=request,
+ )
+ await self._remove_ack_reaction(request)
+ self._event_handler._release_stream_turn(request.context)
+ return
+ except Exception as e:
+ from modules.agents.model_hub import launch_refusal_copy
- self._touch_transport_activity(request.working_path)
- await self._delete_ack(request)
+ logger.error("Failed to start Codex transport: %s", e, exc_info=True)
+ language = str(
+ getattr(getattr(self.controller, "config", None), "language", "en")
+ or "en"
+ )
+ refusal = launch_refusal_copy(self.controller, e)
+ if isinstance(e, CodexThreadReleaseUnavailableError):
+ # Not a source failure: no Hub cooldown. Hold the unwritten
+ # input for an explicit retry.
+ mark_prewrite_recovery_required(request.context, e.reason)
+ display_text = f"❌ {i18n_t('error.codexThreadReleaseUnavailable', language)}"
+ elif isinstance(e, RuntimeUnitStopping):
+ # Not a source failure: no Hub cooldown.
+ display_text = (
+ f"❌ {i18n_t('error.agentRuntimeRetired', language, agent=i18n_t('backend.codex', language))}"
+ )
+ elif isinstance(e, CodexModelHubCatalogUnavailableError):
+ await self._record_model_hub_native_failure(request.context, str(e))
+ display_text = f"❌ {i18n_t('modelHub.errors.codex_catalog_unavailable', language)}"
+ elif refusal is not None:
+ await self._record_model_hub_native_failure(request.context, str(e))
+ display_text = f"❌ {refusal}"
+ else:
+ await self._record_model_hub_native_failure(request.context, str(e))
+ display_text = f"❌ Failed to start Codex CLI: {e}"
+ await emit_backend_failure(
+ self.controller,
+ request.context,
+ self.name,
+ str(e),
+ display_text=display_text,
+ request=request,
+ cause=e,
+ )
+ await self._remove_ack_reaction(request)
+ self._event_handler._release_stream_turn(request.context)
+ return
- self._turn_registry.remember_request(request)
- developer_instructions: Optional[str] = None
- prompt_rendered = False
- try:
- # Get or create thread (with resume support)
- thread_id = self._session_mgr.get_thread_id(request.base_session_id)
+ generation = binding.generation
+ transport = generation.runtime.transport
+ self._touch_runtime(generation.runtime)
+ await self._delete_ack(request)
- if not thread_id:
- developer_instructions = await self._build_thread_developer_instructions(request)
- prompt_rendered = True
- thread_id = await self._start_or_resume_thread(
- transport, request, developer_instructions=developer_instructions
- )
+ self._turn_registry.remember_request(request)
+ developer_instructions: Optional[str] = None
+ prompt_rendered = False
+ try:
+ # Set only while the thread is loaded in ``generation``.
+ thread_id = self._session_mgr.get_thread_id(request.base_session_id)
- # If a turn is active, interrupt it first
- active_turn = self._turn_registry.get_active_turn(request.base_session_id)
- if active_turn:
- try:
- await transport.send_request(
- "turn/interrupt",
- {"threadId": thread_id, "turnId": active_turn},
- )
- except Exception as e:
- if self._is_recoverable_transport_error(e):
- raise
- logger.warning("Failed to interrupt turn %s: %s", active_turn, e)
- await emit_backend_failure(
- self.controller,
- request.context,
- self.name,
- str(e),
- display_text=f"❌ Failed to interrupt previous Codex turn: {e}",
- request=request,
- )
- await self._remove_ack_reaction(request)
- self._event_handler._release_stream_turn(request.context)
- return
- interrupted_request = self._event_handler.clear_pending(active_turn)
- if interrupted_request:
- await self._remove_ack_reaction(interrupted_request)
-
- # Render once at the actual Turn boundary. Besides keeping the
- # payload byte-stable, this avoids repeating admission
- # side effects while the same request refreshes and starts.
- if not prompt_rendered:
- developer_instructions = await self._build_thread_developer_instructions(request)
- prompt_rendered = True
- await self._refresh_thread_developer_instructions_if_needed(
- transport,
- request,
- thread_id,
- )
- self._bind_runtime_agent_session_id(request)
- thread_id = await self._start_turn(
- transport,
- request,
- thread_id,
- developer_instructions=developer_instructions,
+ if not thread_id:
+ developer_instructions = await self._build_thread_developer_instructions(request)
+ prompt_rendered = True
+ thread_id = await self._open_session_thread(
+ generation, request, developer_instructions=developer_instructions
)
- except Exception as e:
- # Safety net: if the thread is stale (e.g. Codex server-side
- # expiry, or the proactive invalidation in _get_or_create_transport
- # was bypassed by a race), invalidate and retry once.
- if (
- self._is_recoverable_transport_error(e)
- and backend_dispatch_attempted(request.context) is False
- ):
- logger.warning(
- "Recoverable Codex transport failure for session %s, restarting transport and retrying: %s",
- request.base_session_id,
- e,
+ # If a turn is active, interrupt it first
+ active_turn = self._turn_registry.get_active_turn(request.base_session_id)
+ if active_turn:
+ try:
+ await transport.send_request(
+ "turn/interrupt",
+ {"threadId": thread_id, "turnId": active_turn},
)
- if await self._drop_transport_after_failure(request.working_path, transport, request):
- try:
- if launch is None:
- transport = await self._get_or_create_transport(request.working_path)
- else:
- transport = await self._get_or_create_transport(request.working_path, launch)
- self._touch_transport_activity(request.working_path)
- if not prompt_rendered:
- self.ensure_agent_session_id(request)
- developer_instructions = await self._build_thread_developer_instructions(request)
- prompt_rendered = True
- thread_id = await self._start_or_resume_thread(
- transport, request, developer_instructions=developer_instructions
- )
- self._bind_runtime_agent_session_id(request)
- await self._start_turn(
- transport,
- request,
- thread_id,
- developer_instructions=developer_instructions,
- )
- return # retry succeeded
- except Exception as retry_err:
- e = retry_err # fall through to normal error handling
-
- # FAIL LOUD on a server-side "thread not found": the conversation is
- # gone, so surface the error instead of silently clearing the
- # mapping and forking a fresh thread (which hid the context loss).
- # The mapping is kept so the failure is consistent until the user
- # explicitly starts a new session (product decision: no silent
- # fallbacks).
- if isinstance(e, (CodexResumeUnavailableError, CodexResponseTooLargeError)):
- mark_prewrite_recovery_required(request.context, "codex_resume_unavailable")
- elif isinstance(e, CodexRuntimeChangeBlockedError):
- mark_prewrite_recovery_required(request.context, e.reason)
- self._turn_registry.clear_pending_turn_start(request.base_session_id, request)
- logger.error("Error in Codex handle_message: %s", e, exc_info=True)
- if not isinstance(e, CodexRuntimeChangeBlockedError):
- await self._record_model_hub_native_failure(request.context, str(e))
- # A successful replacement consumes no shared pressure evidence.
- # Diagnose only the transport whose failure is actually reported.
- resource_failure = self._resource_failure_for_transport(transport)
- error_text = self._error_display_text(
+ except Exception as e:
+ if self._is_recoverable_transport_error(e):
+ raise
+ logger.warning("Failed to interrupt turn %s: %s", active_turn, e)
+ await emit_backend_failure(
+ self.controller,
+ request.context,
+ self.name,
+ str(e),
+ display_text=f"❌ Failed to interrupt previous Codex turn: {e}",
+ request=request,
+ )
+ await self._remove_ack_reaction(request)
+ self._event_handler._release_stream_turn(request.context)
+ return
+ interrupted_request = self._event_handler.clear_pending(active_turn)
+ if interrupted_request:
+ await self._remove_ack_reaction(interrupted_request)
+
+ # Render once at the actual Turn boundary. Besides keeping the
+ # payload byte-stable, this avoids repeating admission
+ # side effects while the same request refreshes and starts.
+ if not prompt_rendered:
+ developer_instructions = await self._build_thread_developer_instructions(request)
+ prompt_rendered = True
+ await self._refresh_thread_developer_instructions_if_needed(
+ transport,
+ request,
+ thread_id,
+ )
+ self._bind_runtime_agent_session_id(request)
+ thread_id = await self._start_turn(
+ transport,
+ request,
+ thread_id,
+ developer_instructions=developer_instructions,
+ )
+
+ except Exception as e:
+ # Safety net: if the app-server broke before this turn reached it,
+ # replace that generation and retry once on a working one.
+ if (
+ self._is_recoverable_transport_error(e)
+ and backend_dispatch_attempted(request.context) is False
+ ):
+ logger.warning(
+ "Recoverable Codex transport failure for session %s, restarting transport and retrying: %s",
+ request.base_session_id,
e,
- resource_failure=resource_failure,
- )
- await emit_backend_failure(
- self.controller,
- request.context,
- self.name,
- str(e),
- display_text=error_text,
- request=request,
)
- await self._remove_ack_reaction(request)
- # The turn never started (all retries failed) — release the
- # web-Chat working/Stop state instead of leaving it until the
- # fallback timeout (Codex P2).
- self._event_handler._release_stream_turn(request.context)
+ if await self._drop_generation_after_failure(generation, request, binding):
+ try:
+ # The retry keeps the turn's admission load.
+ binding = await self._acquire_generation(
+ request.working_path, launch, inputs=inputs
+ )
+ bindings.append(binding)
+ generation = binding.generation
+ transport = generation.runtime.transport
+ self._touch_runtime(generation.runtime)
+ if not prompt_rendered:
+ self.ensure_agent_session_id(request)
+ developer_instructions = await self._build_thread_developer_instructions(request)
+ prompt_rendered = True
+ thread_id = await self._open_session_thread(
+ generation, request, developer_instructions=developer_instructions
+ )
+ self._bind_runtime_agent_session_id(request)
+ await self._start_turn(
+ transport,
+ request,
+ thread_id,
+ developer_instructions=developer_instructions,
+ )
+ return # retry succeeded
+ except Exception as retry_err:
+ e = retry_err # fall through to normal error handling
+
+ # FAIL LOUD on a server-side "thread not found": the conversation is
+ # gone, so surface the error instead of silently clearing the
+ # mapping and forking a fresh thread (which hid the context loss).
+ # The mapping is kept so the failure is consistent until the user
+ # explicitly starts a new session (product decision: no silent
+ # fallbacks).
+ if isinstance(e, (CodexResumeUnavailableError, CodexResponseTooLargeError)):
+ mark_prewrite_recovery_required(request.context, "codex_resume_unavailable")
+ self._turn_registry.clear_pending_turn_start(request.base_session_id, request)
+ logger.error("Error in Codex handle_message: %s", e, exc_info=True)
+ await self._record_model_hub_native_failure(request.context, str(e))
+ # A successful replacement consumes no shared pressure evidence.
+ # Diagnose only the transport whose failure is actually reported.
+ resource_failure = self._resource_failure_for_transport(transport)
+ error_text = self._error_display_text(
+ e,
+ resource_failure=resource_failure,
+ )
+ await emit_backend_failure(
+ self.controller,
+ request.context,
+ self.name,
+ str(e),
+ display_text=error_text,
+ request=request,
+ )
+ await self._remove_ack_reaction(request)
+ # The turn never started (all retries failed) — release the
+ # web-Chat working/Stop state instead of leaving it until the
+ # fallback timeout (Codex P2).
+ self._event_handler._release_stream_turn(request.context)
def steering_native_turn_id(self, target: ActiveSteerTarget) -> Optional[str]:
active_request = target.agent_request
@@ -735,6 +899,7 @@ class CodexAgent(BaseAgent):
*,
thread_id: str,
cwd: str,
+ runtime: _CodexRuntime | None = None,
) -> None:
if not request.attempt_id or not thread_id or not cwd:
return
@@ -751,6 +916,7 @@ class CodexAgent(BaseAgent):
thread_id=thread_id,
cwd=cwd,
recorded_at=time.monotonic(),
+ runtime=runtime,
)
def _forget_steer_reconciliation_target(self, attempt_id: str) -> None:
@@ -846,7 +1012,9 @@ class CodexAgent(BaseAgent):
thread_id = self._session_mgr.get_thread_id(base_session_id)
cwd = self._session_mgr.get_cwd(base_session_id) or active_request.working_path
- transport = self._transports.get(cwd)
+ generation = self._generation_for_session(base_session_id)
+ runtime = generation.runtime if generation is not None else None
+ transport = runtime.transport if runtime is not None else None
if not thread_id:
return steer_result(SteerOutcome.NOT_ACTIVE, reason="missing_native_thread", backend=self.name)
if transport is None or not transport.is_initialized:
@@ -856,6 +1024,7 @@ class CodexAgent(BaseAgent):
target,
thread_id=thread_id,
cwd=cwd,
+ runtime=runtime,
)
steer_params = {
@@ -929,7 +1098,7 @@ class CodexAgent(BaseAgent):
diagnostic=diagnostic,
),
)
- self._touch_transport_activity(cwd)
+ self._touch_runtime(runtime)
return steer_result(
SteerOutcome.UNKNOWN,
reason="acknowledgement_ambiguous",
@@ -937,7 +1106,7 @@ class CodexAgent(BaseAgent):
diagnostic=diagnostic,
)
except TimeoutError as exc:
- self._touch_transport_activity(cwd)
+ self._touch_runtime(runtime)
return steer_result(
SteerOutcome.UNKNOWN,
reason="acknowledgement_ambiguous",
@@ -945,7 +1114,7 @@ class CodexAgent(BaseAgent):
diagnostic=str(exc),
)
- self._touch_transport_activity(cwd)
+ self._touch_runtime(runtime)
response_turn_id = str(response.get("turnId") or "").strip()
if response_turn_id != request.expected_native_turn_id:
return self._finish_steer_receipt(
@@ -989,9 +1158,12 @@ class CodexAgent(BaseAgent):
)
targets = getattr(self, "_steer_reconciliation_targets", None) or {}
retained = targets.get(request.attempt_id)
+ transport: CodexTransport | None = None
if retained is not None:
thread_id = retained.thread_id
cwd = retained.cwd
+ if retained.runtime is not None:
+ transport = retained.runtime.transport
else:
active_turn_id = self._turn_registry.get_active_turn(base_session_id)
if active_turn_id == request.expected_native_turn_id:
@@ -999,6 +1171,7 @@ class CodexAgent(BaseAgent):
cwd = self._session_mgr.get_cwd(base_session_id)
if not cwd and active_request is not None:
cwd = active_request.working_path
+ transport = self.transport_for_session(base_session_id)
else:
durable = self._durable_reconciliation_binding(
request.target_session_id,
@@ -1012,52 +1185,58 @@ class CodexAgent(BaseAgent):
)
thread_id, cwd = durable
- transport = self._transports.get(cwd) if cwd else None
if transport is not None and getattr(transport, "is_alive", True) is False:
transport = None
- if transport is None and cwd:
+ binding: RuntimeBinding[CodexLaunchSpec, _CodexRuntime] | None = None
+ try:
+ if transport is None and cwd:
+ try:
+ # A timed-out request marks the transport uninitialized, but
+ # an alive reader can still answer this read-only evidence
+ # query, and ``thread/read`` works from any generation of
+ # the directory. Start one only when none is live; this
+ # never replays the original steer.
+ binding = await self._bind_any_generation(cwd)
+ transport = binding.generation.runtime.transport
+ except Exception as exc:
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="attempt_evidence_unavailable",
+ backend=self.name,
+ diagnostic=str(exc),
+ )
+ if not thread_id or transport is None:
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="attempt_evidence_unavailable",
+ backend=self.name,
+ )
+
try:
- # A timed-out request marks the transport uninitialized, but an
- # alive reader can still answer this read-only evidence query.
- # If no usable process remains, create a fresh app-server for
- # thread/read; this never replays the original steer.
- transport = await self._get_or_create_transport(cwd)
- except Exception as exc:
+ response = await transport.send_request(
+ "thread/read",
+ {
+ "threadId": thread_id,
+ "includeTurns": True,
+ },
+ )
+ except (ConnectionError, TimeoutError) as exc:
return steer_result(
SteerOutcome.UNKNOWN,
reason="attempt_evidence_unavailable",
backend=self.name,
diagnostic=str(exc),
)
- if not thread_id or transport is None:
- return steer_result(
- SteerOutcome.UNKNOWN,
- reason="attempt_evidence_unavailable",
- backend=self.name,
- )
-
- try:
- response = await transport.send_request(
- "thread/read",
- {
- "threadId": thread_id,
- "includeTurns": True,
- },
- )
- except (ConnectionError, TimeoutError) as exc:
- return steer_result(
- SteerOutcome.UNKNOWN,
- reason="attempt_evidence_unavailable",
- backend=self.name,
- diagnostic=str(exc),
- )
- except Exception as exc: # noqa: BLE001 - absence is not negative proof
- return steer_result(
- SteerOutcome.UNKNOWN,
- reason="attempt_evidence_unavailable",
- backend=self.name,
- diagnostic=str(exc),
- )
+ except Exception as exc: # noqa: BLE001 - absence is not negative proof
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="attempt_evidence_unavailable",
+ backend=self.name,
+ diagnostic=str(exc),
+ )
+ finally:
+ if binding is not None:
+ await binding.release()
thread = response.get("thread") if isinstance(response, dict) else None
turns = thread.get("turns") if isinstance(thread, dict) else None
@@ -1105,7 +1284,7 @@ class CodexAgent(BaseAgent):
request.stop_failure_reason = "not_active"
return False
- transport = self._transports.get(request.working_path)
+ transport = self.transport_for_session(request.base_session_id)
if not transport or not transport.is_alive:
request.stop_failure_reason = "runtime_unavailable"
return False
@@ -1177,22 +1356,33 @@ class CodexAgent(BaseAgent):
return True
async def clear_sessions(self, session_key: str) -> int:
- """Clear sessions scoped to a specific session_key."""
- self.sessions.clear_agent_sessions(session_key, self.name)
-
- # Use session_key index (not _threads) so sessions with
- # invalidated threads are still cleaned up properly.
- to_clear = self._session_mgr.get_sessions_by_session_key(session_key)
-
- count = self._session_mgr.clear_by_session_key(session_key)
+ """Clear sessions scoped to a specific session_key.
- # Clean up in-memory turn state and session locks for cleared sessions
- for bid in to_clear:
- self._turn_registry.clear_session(bid)
- self._session_locks.pop(bid, None)
- self._clear_thread_developer_instructions(bid)
-
- return count
+ Under each cleared Session's lock, its thread is released first, so a
+ cleared conversation never stays loaded in a process that keeps
+ serving other Sessions. A thread that stays loaded fails the clear
+ before anything is forgotten, so the clear stays retryable.
+ """
+ while True:
+ # Use session_key index (not _threads) so sessions with
+ # invalidated threads are still cleaned up properly.
+ to_clear = sorted(self._session_mgr.get_sessions_by_session_key(session_key))
+ async with AsyncExitStack() as held:
+ for bid in to_clear:
+ await held.enter_async_context(self.session_lifecycle(bid))
+ for bid in to_clear:
+ await self.release_session_runtime(bid)
+ if sorted(self._session_mgr.get_sessions_by_session_key(session_key)) != to_clear:
+ # A Session of this key started meanwhile, and the clear
+ # below covers the whole key: release that one too.
+ continue
+ self.sessions.clear_agent_sessions(session_key, self.name)
+ count = self._session_mgr.clear_by_session_key(session_key)
+ for bid in to_clear:
+ self._turn_registry.clear_session(bid)
+ self._clear_thread_developer_instructions(bid)
+ self._session_locks.pop(bid, None)
+ return count
def runtime_turn_keys(self) -> set[str]:
return {
@@ -1212,62 +1402,95 @@ class CodexAgent(BaseAgent):
async def retire_for_native_migration(self) -> None:
"""Retire every idle app-server generation or refuse credential mutation."""
- for cwd, transport in list(self._transports.items()):
- async with self._transport_locks.setdefault(cwd, asyncio.Lock()):
- detached = await self._stop_and_detach_transport_generation(
- cwd,
- transport,
- final_predicate=lambda: self._transport_replacement_is_safe(cwd, transport),
- require_process_exit=True,
- )
- if not detached:
+ for unit in list(self._units.values()):
+ # A teardown already in flight must answer before custody moves.
+ await unit.settled()
+ for generation in unit.generations:
+ if not await self._generation_drained(generation):
raise RuntimeError("Codex runtime retirement was refused")
- self._retire_model_hub_process_scope(cwd)
+ # Re-check synchronously: work may have bound during the awaits above.
+ generations = unit.generations
+ if any(self._generation_has_live_work(generation) for generation in generations):
+ raise RuntimeError("Codex runtime retirement was refused")
+ # migration_guard interrupted the backend's work before custody
+ # moves, and the drained check above refuses any owner it missed.
+ await self._stop_generations_now(
+ unit, generations, require_process_exit=True, settle_reason=None
+ )
+ await self._end_unattached_runtimes(require_process_exit=True)
for base_session_id in self._session_mgr.all_base_sessions():
- self._session_mgr.invalidate_thread(base_session_id)
+ self._forget_stale_session(base_session_id)
self._turn_registry.clear_session(base_session_id)
- self._clear_thread_developer_instructions(base_session_id)
-
- async def retire_unowned_session_transport(
- self, cwd: str, *, ending_session_id: str | None = None
- ) -> bool:
- """Reclaim the exact cwd generation while retaining the ending Session on failure."""
-
- async with self._transport_locks.setdefault(cwd, asyncio.Lock()):
- transport = self._transports.get(cwd)
-
- def has_other_sessions() -> bool:
- return any(
- session_id != ending_session_id
- for session_id in self._session_mgr.sessions_for_cwd(cwd)
- )
- if transport is None or has_other_sessions():
- return False
+ async def release_session_runtime(self, base_session_id: str) -> None:
+ """Unload an ending Session's thread so no app-server keeps holding it.
- async def still_unowned() -> bool:
- return (
- self._transports.get(cwd) is transport
- and not has_other_sessions()
- and not self._has_active_turns_for_cwd(cwd)
+ Codex lets one process at a time hold a thread; a thread left loaded in
+ a shared app-server would block resuming that conversation elsewhere.
+ The caller holds ``session_lifecycle(base_session_id)``.
+ """
+ generation = self._generation_for_session(base_session_id)
+ if generation is None:
+ self._forget_stale_session(base_session_id)
+ return
+ await self._release_session_thread(generation, base_session_id)
+
+ async def end_session(self, base_session_id: str) -> dict[str, bool]:
+ """End one Session's live runtime, for End in Running Agents.
+
+ Under the Session's lifecycle, a Session that was the only user of its
+ directory's app-servers takes them down: its own running turn and
+ Activities settle through ``_end_bound_work`` first. Otherwise only
+ its thread is released, which interrupts its own turn first and
+ raises ``CodexThreadReleaseUnavailableError`` rather than forget a
+ turn Codex did not stop. The Session's state is cleared only after
+ that succeeded, so a failed End can be retried.
+ """
+ async with self.session_lifecycle(base_session_id):
+ interrupted = bool(self._turn_registry.get_active_turn(base_session_id))
+ generation = self._generation_for_session(base_session_id)
+ unit = self._units.get(generation.runtime.cwd) if generation is not None else None
+ process_killed = False
+ if generation is None:
+ self._forget_stale_session(base_session_id)
+ elif (
+ unit is not None
+ and generation in unit.generations
+ and not self._serves_another_session(unit, base_session_id)
+ ):
+ # End is the user's explicit request to kill, so what it ends
+ # is settled as their stop.
+ await self._stop_generations_now(
+ unit, unit.generations, require_process_exit=True, settle_reason=SETTLED_BY_STOPPED
)
+ process_killed = True
+ else:
+ # A process the reconciler already detached is not End's to
+ # kill: release the thread there, which waits out its teardown.
+ await self._release_session_thread(generation, base_session_id)
+ process_killed = generation.runtime.ended
+ self._turn_registry.clear_session(base_session_id)
+ self._session_mgr.clear(base_session_id)
+ self._session_last_activity.pop(base_session_id, None)
+ self._clear_thread_developer_instructions(base_session_id)
+ # End holds this lock; forgetting it is its last step.
+ self._session_locks.pop(base_session_id, None)
+ return {"interrupted": interrupted, "process_killed": process_killed}
- detached = await self._stop_and_detach_transport_generation(
- cwd,
- transport,
- final_predicate=still_unowned,
- require_process_exit=True,
- )
- if detached:
- self._retire_model_hub_process_scope(cwd)
- return detached
+ def _serves_another_session(
+ self,
+ unit: RuntimeGenerationSet[CodexLaunchSpec, _CodexRuntime],
+ base_session_id: str,
+ ) -> bool:
+ """Whether any process of the directory still serves another Session."""
+ return any(
+ generation.bindings
+ or any(other != base_session_id for other in generation.runtime.threads)
+ for generation in unit.generations
+ )
async def refresh_auth_state(self) -> None:
- """Drop app-server runtime state so future turns pick up fresh auth."""
- if not hasattr(self, "_transport_last_activity"):
- self._transport_last_activity = {}
- if not hasattr(self, "_session_last_activity"):
- self._session_last_activity = {}
+ """Stop every app-server generation; used by exclusive credential cutovers."""
base_session_ids = list(self._session_mgr.all_base_sessions())
controller = getattr(self, "controller", None)
turn_manager = getattr(controller, "session_turns", None)
@@ -1280,65 +1503,99 @@ class CodexAgent(BaseAgent):
)
except Exception:
logger.warning("Failed to release Workbench turns during Codex refresh", exc_info=True)
- if not hasattr(self, "_transport_locks"):
- self._transport_locks = {}
- transport_items = list(self._transports.items())
self._session_last_activity.clear()
stopped = 0
- for cwd, transport in transport_items:
- lock = self._transport_locks.setdefault(cwd, asyncio.Lock())
- async with lock:
- try:
- detached = await self._stop_and_detach_transport_generation(
- cwd,
- transport,
- )
- except Exception as exc:
- logger.warning("Failed to stop Codex transport during auth refresh: %s", exc)
- continue
- if not detached:
- continue
- self._retire_model_hub_process_scope(cwd)
- stopped += 1
+ for unit in list(self._units.values()):
+ await unit.settled()
+ generations = unit.generations
+ try:
+ # The exclusive cutover runs after the coordinator interrupted
+ # this backend's turns and Activities.
+ await self._stop_generations_now(unit, generations, settle_reason=None)
+ except Exception as exc:
+ logger.warning("Failed to stop Codex transport during auth refresh: %s", exc)
+ stopped += sum(1 for generation in generations if generation.runtime.ended)
+ try:
+ await self._end_unattached_runtimes()
+ except Exception as exc:
+ logger.warning("Failed to stop Codex transport during auth refresh: %s", exc)
for base_session_id in base_session_ids:
- self._session_mgr.invalidate_thread(base_session_id)
+ # A Session whose process survived a failed stop stays bound to it.
+ self._forget_stale_session(base_session_id)
self._turn_registry.clear_session(base_session_id)
- self._clear_thread_developer_instructions(base_session_id)
logger.info("Refreshed Codex auth state across %d transport(s)", stopped)
async def refresh_runtime_config(self, codex_config: Any) -> None:
- """Reload persisted runtime config before respawning app-server transports."""
+ """Reload persisted runtime config and stop every app-server generation."""
self.codex_config = codex_config
self.controller.config.codex = codex_config
- await self.invalidate_model_hub_runtime()
+ await self.adopt_model_hub_catalog()
await self.refresh_auth_state()
- async def invalidate_model_hub_runtime(self) -> None:
- """Make the next Hub launch rebuild its catalog without touching Direct transports."""
- self._model_hub_catalog_generation += 1
- if self._model_hub_catalog is not None:
- self._model_hub_catalog.close()
- self._model_hub_catalog = None
+ async def renew_runtime(self, codex_config: Any, *, config_save: bool = False) -> None:
+ """Adopt persisted runtime config; each cwd moves to it at its next turn.
+
+ Nothing stops or waits here. The binary and extra arguments are launch
+ spec inputs, and the other ``agents.codex`` fields are read live, so a
+ plain config save needs no renewal. Every other caller (credential
+ flows, manual Restart, installs) bumps the renewal epoch, which is part
+ of every launch spec: a cwd's next turn then starts a new app-server
+ generation while turns already running finish on theirs.
+ """
+ self.codex_config = codex_config
+ self.controller.config.codex = codex_config
+ if not config_save:
+ self._runtime_epoch += 1
+
+ async def adopt_model_hub_catalog(self) -> None:
+ """Forget prepared catalogs; each Hub turn prepares from its own snapshot.
+
+ A changed catalog changes the launch spec, so a cwd moves to a new
+ generation at its next Hub turn. Running generations keep the catalog
+ pinned for as long as they run.
+ """
+ catalogs = list(self._model_hub_catalogs.values())
+ self._model_hub_catalogs.clear()
+ for catalog in catalogs:
+ catalog.close()
+
+ async def prepare_model_hub_runtime(
+ self,
+ config: Any = None,
+ *,
+ inputs: _LaunchInputs | None = None,
+ ) -> CodexHubCatalog:
+ """Bind Hub metadata to this Agent's exact configured Codex binary.
- async def prepare_model_hub_runtime(self) -> CodexHubCatalog:
- """Bind Hub metadata to this Agent's exact configured Codex binary."""
+ ``config`` is the turn's Model Hub snapshot; the catalog lists exactly
+ the models that snapshot resolved against. ``inputs`` is the turn's
+ launch snapshot, so the catalog comes from the binary its process runs.
+ """
from vibe import backend_model_catalog
- async with self._model_hub_catalog_lock:
- if self._model_hub_catalog is not None:
- return self._model_hub_catalog
- generation = self._model_hub_catalog_generation
+ if inputs is None:
binary = self.codex_config.binary
- configured_models = None
+ binary_identity = self._binary_identity(binary, self._codex_runtime_environment())
+ else:
+ binary, binary_identity = inputs.binary, inputs.identity["binary"]
+ configured_models = None
+ if config is None:
model_hub_service = getattr(self.controller, "model_hub_service", None)
store = getattr(model_hub_service, "store", None)
- if store is not None:
- configured_models = [
- model.to_payload()
- for model in store.load().agents["codex"].models
- ]
+ config = store.load() if store is not None else None
+ if config is not None:
+ configured_models = [model.to_payload() for model in config.agents["codex"].models]
+ key = (
+ json.dumps(binary_identity, sort_keys=True),
+ hashlib.sha256(json.dumps(configured_models, sort_keys=True).encode()).hexdigest(),
+ )
+ async with self._model_hub_catalog_lock:
+ cached = self._model_hub_catalogs.get(key)
+ if cached is not None:
+ self._model_hub_catalogs.move_to_end(key)
+ return cached
preparation = asyncio.create_task(
asyncio.to_thread(
backend_model_catalog.prepare_codex_hub_catalog,
@@ -1358,12 +1615,10 @@ class CodexAgent(BaseAgent):
raise CodexModelHubCatalogUnavailableError(
"Codex Model Hub catalog preparation failed"
) from exc
- if self._model_hub_catalog_generation != generation:
- catalog.close()
- raise CodexModelHubCatalogUnavailableError(
- "Codex Model Hub catalog generation changed during preparation"
- )
- self._model_hub_catalog = catalog
+ self._model_hub_catalogs[key] = catalog
+ while len(self._model_hub_catalogs) > _CACHED_HUB_CATALOGS:
+ _, evicted = self._model_hub_catalogs.popitem(last=False)
+ evicted.close()
return catalog
@staticmethod
@@ -1380,86 +1635,75 @@ class CodexAgent(BaseAgent):
session_key: str,
working_path: str,
) -> None:
- """Restart a Codex transport only when the resumed session owns that cwd."""
- if not hasattr(self, "_transport_locks"):
- self._transport_locks = {}
- lock = self._transport_locks.setdefault(working_path, asyncio.Lock())
- async with lock:
- transport = self._transports.get(working_path)
- if transport is None:
- return
-
- affected_sessions = self._session_mgr.sessions_for_cwd(working_path)
- other_sessions = [session_id for session_id in affected_sessions if session_id != base_session_id]
- if other_sessions:
- logger.info(
- "Skipping Codex resume preparation for %s; cwd=%s is shared by %d other session(s)",
- base_session_id,
- working_path,
- len(other_sessions),
- )
- return
- try:
- detached = await self._stop_and_detach_transport_generation(
- working_path,
- transport,
- )
- except Exception as exc:
- logger.warning("Failed to stop Codex transport during resume preparation: %s", exc)
- return
- if not detached:
- logger.warning(
- "Failed to retire Codex transport generation during resume preparation for cwd=%s",
- working_path,
- )
- return
- self._retire_model_hub_process_scope(working_path)
+ """Release the Session's current thread before it binds another one.
- self._session_mgr.invalidate_thread(base_session_id)
- self._turn_registry.clear_session(base_session_id)
- self._clear_thread_developer_instructions(base_session_id)
+ Only this Session's thread is unloaded; the app-server keeps serving
+ every other Session in the directory. Raises
+ ``CodexThreadReleaseUnavailableError`` when the thread stays loaded.
+ """
+ # Serialized with turn admission. The caller rewrites the durable
+ # mapping right after this returns, with no await in between.
+ async with self.session_lifecycle(base_session_id):
+ generation = self._generation_for_session(base_session_id)
+ if generation is None:
+ self._forget_stale_session(base_session_id)
+ else:
+ # A thread that stays loaded aborts the resume before its mapping
+ # changes; otherwise the next turn would still reach the old thread.
+ await self._release_session_thread(generation, base_session_id)
+ self._turn_registry.clear_session(base_session_id)
logger.info("Prepared Codex runtime for resumed session %s", base_session_id)
- async def shutdown_runtime(self) -> None:
- """Stop all app-server transports during vibe-remote shutdown."""
- await self.invalidate_model_hub_runtime()
- if not hasattr(self, "_transport_last_activity"):
- self._transport_last_activity = {}
- if not hasattr(self, "_transport_locks"):
- self._transport_locks = {}
- if not hasattr(self, "_session_locks"):
- self._session_locks = {}
- if not hasattr(self, "_session_last_activity"):
- self._session_last_activity = {}
- transport_items = list(self._transports.items())
+ async def shutdown_runtime(self, settle_reason: str | None = None) -> None:
+ """Stop every app-server now: service shutdown, probe teardown, or disable.
+
+ Disabling the backend is an explicit, user-visible stop: the core has
+ removed this agent from routing and passes ``settle_reason``. Every
+ forced stop then settles the turns and Activities bound to its
+ generation with that reason before it kills the process, so this
+ agent's work is settled even if the core's own interrupt failed, and
+ no other agent's work is touched. Service shutdown and probe teardown
+ pass none and show no notice. A turn that captured the agent before
+ the routing change fails visibly and starts no process.
+
+ Raises while any app-server survives: nothing else owns it once the
+ agent leaves routing, so the caller keeps the teardown and retries
+ it. A retry stops every survivor again and settles whatever is still
+ bound to it.
+ """
+ await self.adopt_model_hub_catalog()
self._session_last_activity.clear()
- stopped = 0
- for cwd, transport in transport_items:
- lock = self._transport_locks.setdefault(cwd, asyncio.Lock())
- async with lock:
- try:
- detached = await self._stop_and_detach_transport_generation(
- cwd,
- transport,
- )
- except Exception as exc:
- logger.warning("Failed to stop Codex transport during shutdown: %s", exc)
- continue
- if not detached:
- continue
- self._retire_model_hub_process_scope(cwd)
- stopped += 1
+ self._shutting_down = True
+ self._shutdown_settle_reason = settle_reason
+ stopped = sum(len(runtimes) for runtimes in self._runtimes.values())
+ for unit in list(self._units.values()):
+ # A forced stop that fails leaves its generation attached; the
+ # pass below retries every process still running, attached or not.
+ await unit.stop_all(force=True)
+ failure: Exception | None = None
+ try:
+ await self._end_unattached_runtimes(settle_reason=settle_reason)
+ except Exception as exc:
+ failure = exc
+ # Shutdown ends the whole runtime: every process was just asked to end,
+ # so all Session state goes with it, including any bindings. A Session
+ # still bound to a survivor keeps its state, so a retry can settle it.
for base_session_id in list(self._session_mgr.all_base_sessions()):
+ if self._generation_for_session(base_session_id) is not None:
+ continue
session_key = self._session_mgr.get_session_key(base_session_id)
if session_key:
self.sessions.clear_agent_session_mapping(session_key, self.name, base_session_id)
+ self._session_generations.pop(base_session_id, None)
self._session_mgr.clear(base_session_id)
self._turn_registry.clear_session(base_session_id)
self._clear_thread_developer_instructions(base_session_id)
self._session_locks.clear()
- self._transport_locks.clear()
+ survivors = sum(len(runtimes) for runtimes in self._runtimes.values())
+ if failure is not None or survivors:
+ raise RuntimeError(f"{survivors} Codex app-server(s) survived shutdown") from failure
logger.info("Stopped Codex runtime across %d transport(s)", stopped)
def _bind_runtime_agent_session_id(self, request: AgentRequest) -> None:
@@ -1508,18 +1752,18 @@ class CodexAgent(BaseAgent):
or "en"
)
message = i18n_t("error.codexPromptRefreshUnavailable", language)
- elif isinstance(error, CodexForkBoundaryUnavailableError):
+ elif isinstance(error, RuntimeUnitStopping):
language = str(
getattr(getattr(self.controller, "config", None), "language", "en")
or "en"
)
- message = i18n_t("error.codexForkBoundaryUnavailable", language)
- elif isinstance(error, CodexRuntimeChangeBlockedError):
+ message = i18n_t("error.agentRuntimeRetired", language, agent=i18n_t("backend.codex", language))
+ elif isinstance(error, CodexForkBoundaryUnavailableError):
language = str(
getattr(getattr(self.controller, "config", None), "language", "en")
or "en"
)
- message = i18n_t("error.codexRuntimeChangeBlocked", language)
+ message = i18n_t("error.codexForkBoundaryUnavailable", language)
else:
message = f"Codex error: {error}"
@@ -1537,10 +1781,19 @@ class CodexAgent(BaseAgent):
message = f"{message} {i18n_t('error.agentMemoryLimit', language)}"
return f"❌ {message}"
- def _runtime_ownership_target_for_cwd(
+ def _runtime_ownership_target_for_generation(
self,
- cwd: str,
+ generation: _CodexGeneration,
) -> RuntimeResourceTarget | None:
+ """Durable ownership scope of one generation.
+
+ The current generation answers for every durable Session of its
+ directory, including ones not yet bound in memory. A retiring one
+ answers only for the Sessions whose threads it still holds; work that
+ moved to a newer generation must not keep it alive.
+ """
+ runtime = generation.runtime
+ cwd = runtime.cwd
sessions_for_cwd = getattr(self._session_mgr, "sessions_for_cwd", None)
all_base_sessions = getattr(self._session_mgr, "all_base_sessions", None)
get_cwd = getattr(self._session_mgr, "get_cwd", None)
@@ -1562,8 +1815,15 @@ class CodexAgent(BaseAgent):
):
return None
+ current = not generation.retiring and not generation.stopped
+ # A Session cleared from the manager no longer owns anything here.
+ session_ids = (
+ sessions_for_cwd(cwd)
+ if current
+ else [base_session_id for base_session_id in runtime.threads if get_cwd(base_session_id)]
+ )
bindings: list[RuntimeSessionBinding] = []
- for base_session_id in sessions_for_cwd(cwd):
+ for base_session_id in session_ids:
session_key = str(get_session_key(base_session_id) or "").strip()
agent_session_id = str(
get_agent_session_id(base_session_id) or ""
@@ -1603,247 +1863,974 @@ class CodexAgent(BaseAgent):
)
return RuntimeResourceTarget(
backend="codex",
- resource_key=cwd,
+ resource_key=self._generation_resource_key(runtime),
bindings=tuple(bindings),
known_activity_runtime_keys=known_activity_keys,
known_fallback_route_keys=known_route_keys,
- durable_session_workdir=cwd,
+ durable_session_workdir=cwd if current else None,
)
- def _runtime_ownership_snapshot_for_cwd(self, cwd: str):
- target = self._runtime_ownership_target_for_cwd(cwd)
- provider = getattr(getattr(self, "controller", None), "runtime_ownership", None)
- snapshot = getattr(provider, "snapshot", None)
- if target is None or not callable(snapshot):
- logger.error(
- "Codex runtime ownership mapping unavailable for cwd=%s",
- cwd,
- )
- return None
- result = snapshot(target)
- wake_runtime_ownership(self.controller, result)
- return result
+ def _generation_resource_key(self, runtime: _CodexRuntime) -> str:
+ """One generation's activation and ownership key.
- async def _runtime_ownership_snapshots_for_cwds(
+ A disabled agent's retried teardown can hold its generations while a
+ re-enabled agent numbers its own from 1 in the same directory, so the
+ key names the agent instance as well.
+ """
+ return f"{runtime.cwd}#{self._instance_serial}.{runtime.serial}"
+
+ async def _ownership_snapshots(
self,
- cwds: tuple[str, ...],
+ generations: Sequence[_CodexGeneration],
) -> tuple[Any, ...] | None:
"""Read one backend snapshot batch without blocking the controller loop."""
- if not cwds:
+ if not generations:
return ()
provider = getattr(getattr(self, "controller", None), "runtime_ownership", None)
+ targets = tuple(
+ self._runtime_ownership_target_for_generation(generation)
+ for generation in generations
+ )
+ if any(target is None for target in targets):
+ logger.error("Codex runtime ownership mapping unavailable")
+ return None
snapshot_many = getattr(provider, "snapshot_many", None)
- targets = tuple(self._runtime_ownership_target_for_cwd(cwd) for cwd in cwds)
- if callable(snapshot_many) and all(target is not None for target in targets):
- snapshots = await asyncio.to_thread(snapshot_many, targets)
- for snapshot in snapshots:
- wake_runtime_ownership(self.controller, snapshot)
- return tuple(snapshots)
-
- # Tests and legacy embedders can still provide the older single-target
- # probe. Keep it off the event loop; production SQLite providers take the
- # batched path above.
- snapshots = await asyncio.gather(
- *(
- asyncio.to_thread(self._runtime_ownership_snapshot_for_cwd, cwd)
- for cwd in cwds
+ if callable(snapshot_many):
+ snapshots = tuple(await asyncio.to_thread(snapshot_many, targets))
+ else:
+ snapshot = getattr(provider, "snapshot", None)
+ if not callable(snapshot):
+ logger.error("Codex runtime ownership provider unavailable")
+ return None
+ snapshots = tuple(
+ await asyncio.gather(*(asyncio.to_thread(snapshot, target) for target in targets))
)
- )
- if any(snapshot is None for snapshot in snapshots):
+ if any(item is None for item in snapshots):
return None
- return tuple(snapshots)
+ for item in snapshots:
+ wake_runtime_ownership(self.controller, item)
+ return snapshots
- async def _runtime_ownership_snapshot_for_cwd_async(self, cwd: str):
- snapshots = await self._runtime_ownership_snapshots_for_cwds((cwd,))
+ async def _ownership_snapshot(self, generation: _CodexGeneration):
+ snapshots = await self._ownership_snapshots((generation,))
return snapshots[0] if snapshots else None
async def runtime_ownership_snapshots(self) -> tuple[Any, ...] | None:
- return await self._runtime_ownership_snapshots_for_cwds(tuple(self._transports))
+ return await self._ownership_snapshots(self._live_generations())
- @staticmethod
- def _transport_activation_identity(
- transport: CodexTransport | None,
- ) -> RuntimeActivationIdentity | None:
- identity = getattr(transport, "_vibe_runtime_activation_identity", None)
- return identity if isinstance(identity, RuntimeActivationIdentity) else None
-
- def _attach_transport_activation(
+ def _attach_runtime_activation(
self,
- cwd: str,
- transport: CodexTransport,
+ runtime: _CodexRuntime,
) -> 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
- existing = self._transport_activation_identity(transport)
- if existing is not None and registry.is_current(existing):
- return existing
- identity = registry.attach(self.name, cwd)
- setattr(transport, "_vibe_runtime_activation_identity", identity)
- return identity
+ return registry.attach(self.name, self._generation_resource_key(runtime))
- def _reserve_transport_retirement(
+ def runtime_activation_identity_for_request(
self,
- cwd: str,
- transport: CodexTransport,
- ) -> tuple[Any, Any] | None:
- if self._transports.get(cwd) is not transport:
+ request: Any,
+ ) -> RuntimeActivationIdentity | None:
+ base_session_id = str(getattr(request, "base_session_id", "") or "").strip()
+ if base_session_id:
+ generation = self._generation_for_session(base_session_id)
+ if generation is not None:
+ return generation.runtime.activation
+ cwd = str(getattr(request, "working_path", "") or "").strip()
+ if not cwd:
+ metadata = getattr(request, "metadata", None)
+ if isinstance(metadata, dict):
+ cwd = str(metadata.get("session_workdir") or "").strip()
+ if cwd:
+ generation = self._current_generation(cwd)
+ return generation.runtime.activation if generation is not None else None
+
+ session_key = str(getattr(request, "session_key", "") or "").strip()
+ if not session_key:
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)
- identity = self._transport_activation_identity(transport)
- if identity is None:
- identity = self._attach_transport_activation(cwd, transport)
+ get_sessions = getattr(self._session_mgr, "get_sessions_by_session_key", None)
+ get_cwd = getattr(self._session_mgr, "get_cwd", None)
+ if not callable(get_sessions) or not callable(get_cwd):
+ raise ValueError("Codex Session route mapping is unavailable")
+
+ live_identities: dict[int, RuntimeActivationIdentity] = {}
+ for base_session_id in get_sessions(session_key):
+ generation = self._generation_for_session(base_session_id)
+ if generation is None:
+ mapped_cwd = str(get_cwd(base_session_id) or "").strip()
+ generation = self._current_generation(mapped_cwd) if mapped_cwd else None
+ if generation is None:
+ continue
+ identity = generation.runtime.activation
+ if identity is None:
+ raise ValueError("Codex runtime generation is not attached")
+ live_identities[id(generation)] = identity
+
+ if len(live_identities) > 1:
+ raise ValueError("multiple live Codex runtime resources match Session route")
+ return next(iter(live_identities.values()), None)
+
+ def runtime_activation_identity_for_session_binding(
+ self,
+ *,
+ session_anchor: str,
+ workdir: str | None,
+ ) -> RuntimeActivationIdentity | None:
+ normalized_anchor = str(session_anchor or "").strip()
+ normalized_workdir = str(workdir or "").strip()
+ if not normalized_anchor or not normalized_workdir:
+ return None
+ bound_workdir = str(self._session_mgr.get_cwd(normalized_anchor) or "").strip()
+ if bound_workdir and bound_workdir != normalized_workdir:
+ raise ValueError("Codex Session binding changed workdir")
+ generation = self._generation_for_session(normalized_anchor)
+ if generation is None:
+ generation = self._current_generation(normalized_workdir)
+ if generation is None:
+ return None
+ identity = generation.runtime.activation
if identity is None:
+ raise ValueError("Codex runtime generation is not attached")
+ return identity
+
+ def record_runtime_turn_start(
+ self,
+ *,
+ runtime_key: str,
+ request: AgentRequest | None,
+ ) -> None:
+ if request is None:
+ return
+ generation = self._generation_for_session(request.base_session_id)
+ if generation is not None:
+ self._touch_runtime(generation.runtime)
+ self._touch_session_activity(request.base_session_id)
+
+ # ------------------------------------------------------------------
+ # Runtime generations
+ # ------------------------------------------------------------------
+
+ def _unit(self, cwd: str) -> RuntimeGenerationSet[CodexLaunchSpec, _CodexRuntime]:
+ unit = self._units.get(cwd)
+ if unit is None:
+ if self._shutting_down:
+ # Every existing unit already refuses admission; a new
+ # directory must not start a process nobody would stop.
+ raise RuntimeUnitStopping("runtime unit is stopping")
+ unit = RuntimeGenerationSet(
+ start=self._start_generation,
+ stop=self._stop_generation,
+ )
+ self._units[cwd] = unit
+ return unit
+
+ def _current_generation(self, cwd: str) -> _CodexGeneration | None:
+ unit = self._units.get(cwd)
+ return unit.current if unit is not None else None
+
+ def _live_generations(self) -> tuple[_CodexGeneration, ...]:
+ return tuple(
+ generation
+ for unit in self._units.values()
+ for generation in unit.generations
+ )
+
+ def _generation_for_session(self, base_session_id: str) -> _CodexGeneration | None:
+ """The live generation holding this Session's thread, if any."""
+ generation = self._session_generations.get(base_session_id)
+ if generation is not None and generation.runtime.ended:
+ self._forget_stale_session(base_session_id)
+ return None
+ return generation
+
+ def _generation_holding_thread(self, thread_id: str) -> _CodexGeneration | None:
+ """The live generation that has ``thread_id`` loaded, if any."""
+ for generation in self._session_generations.values():
+ if not generation.runtime.ended and thread_id in generation.runtime.threads.values():
+ return generation
+ return None
+
+ def transport_for_session(self, base_session_id: str) -> CodexTransport | None:
+ """The app-server process serving this Session's thread, if one is live.
+
+ A pure read: the Running Agents snapshot calls it from a worker thread.
+ """
+ generation = self._session_generations.get(base_session_id)
+ if generation is None or generation.runtime.ended:
return None
- reservation = registry.reserve_retirement(identity)
- return (registry, reservation) if reservation is not None else None
+ return generation.runtime.transport
+
+ def _generation_running(self, transport: CodexTransport) -> _CodexGeneration | None:
+ """The attached generation whose process is ``transport``."""
+ for unit in self._units.values():
+ for generation in unit.generations:
+ if generation.runtime.transport is transport:
+ return generation
+ return None
+
+ def _bind_session_thread(
+ self,
+ generation: _CodexGeneration,
+ base_session_id: str,
+ thread_id: str,
+ ) -> None:
+ previous = self._session_generations.get(base_session_id)
+ if previous is not None and previous is not generation:
+ previous.runtime.threads.pop(base_session_id, None)
+ generation.runtime.threads[base_session_id] = thread_id
+ self._session_generations[base_session_id] = generation
+
+ def _unbind_session(self, base_session_id: str, runtime: _CodexRuntime) -> None:
+ """Drop a Session's binding to ``runtime``; its next turn resumes the thread.
+
+ Only two owners may drop a live binding: the process ending
+ (``_forget_runtime_sessions``) and the thread being released
+ (``_release_session_thread``). Codex lets one process at a time hold a
+ thread, so forgetting a binding any other way would strand the thread's
+ writer lock in a process Avibe no longer routes to.
+ """
+ runtime.threads.pop(base_session_id, None)
+ generation = self._session_generations.get(base_session_id)
+ if generation is not None and generation.runtime is not runtime:
+ return
+ self._session_generations.pop(base_session_id, None)
+ self._session_mgr.invalidate_thread(base_session_id)
+ self._clear_thread_developer_instructions(base_session_id)
+
+ def _forget_stale_session(self, base_session_id: str) -> bool:
+ """Forget a Session's thread id when no live process holds that thread.
+
+ A Session still bound to a live process is left alone and False is
+ returned: only that process ending or the thread's release unbinds it.
+ """
+ generation = self._session_generations.get(base_session_id)
+ if generation is not None and not generation.runtime.ended:
+ return False
+ if generation is not None:
+ self._unbind_session(base_session_id, generation.runtime)
+ return True
+ self._session_mgr.invalidate_thread(base_session_id)
+ self._clear_thread_developer_instructions(base_session_id)
+ return True
+
+ def _session_has_turn(self, base_session_id: str) -> bool:
+ if self._turn_registry.get_active_turn(base_session_id):
+ return True
+ has_pending_turn_start = getattr(self._turn_registry, "has_pending_turn_start", None)
+ return bool(callable(has_pending_turn_start) and has_pending_turn_start(base_session_id))
+
+ def _launch_inputs(self, cwd: str, *, hub_config: Any = None) -> _LaunchInputs:
+ """Read every mutable launch input for ``cwd`` in one step, with no await.
+
+ The directory is created first, so its inode is the one the process
+ will run in.
+ """
+ os.makedirs(cwd, exist_ok=True)
+ codex_config = self.codex_config
+ binary = codex_config.binary
+ env = dict(self._codex_runtime_environment())
+ codex_home = env.get("CODEX_HOME") or os.path.join(
+ env.get("HOME") or os.path.expanduser("~"),
+ ".codex",
+ )
+ return _LaunchInputs(
+ hub_config=hub_config,
+ binary=binary,
+ extra_args=tuple(codex_config.extra_args),
+ env=env,
+ identity={
+ "epoch": self._runtime_epoch,
+ "binary": self._binary_identity(binary, env),
+ "credential": codex_credential_identity(Path(codex_home).expanduser()),
+ # A directory deleted and re-created under the same path leaves
+ # a running app-server in a dead inode (#561).
+ "cwd": [cwd, self._cwd_inode(cwd)],
+ },
+ )
@staticmethod
- def _finish_transport_retirement(
- reserved: tuple[Any, Any],
+ def _launch_spec_digest(
+ inputs: _LaunchInputs,
*,
- retire: bool,
- ) -> bool:
- registry, reservation = reserved
- if registry is None:
- return True
- return bool(registry.finish_retirement(reservation, retire=retire))
+ args: Sequence[str],
+ env: Mapping[str, str],
+ catalog_path: str | None = None,
+ ) -> str:
+ identity = {
+ **inputs.identity,
+ "argv": [*args, *inputs.extra_args],
+ "catalog": catalog_path,
+ # Digest only: the environment carries the Hub gateway token.
+ "env": hashlib.sha256(
+ json.dumps(sorted(env.items()), separators=(",", ":")).encode()
+ ).hexdigest(),
+ }
+ return hashlib.sha256(
+ json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()
+ ).hexdigest()
+
+ @staticmethod
+ def _binary_identity(binary: str, env: Mapping[str, str]) -> dict[str, Any]:
+ """The executable a launch would run; any reinstall changes its stat."""
+ resolved = shutil.which(binary, path=env.get("PATH")) or binary
+ real = os.path.realpath(resolved)
+ try:
+ st = os.stat(real)
+ except OSError:
+ return {"configured": binary, "resolved": real, "stat": None}
+ return {
+ "configured": binary,
+ "resolved": real,
+ "stat": [st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns],
+ }
- def _detach_transport_bookkeeping(
+ async def _launch_spec(
self,
cwd: str,
- transport: CodexTransport,
- ) -> bool:
- """Remove only the exact transport after its process has stopped."""
- if self._transports.get(cwd) is not transport:
+ launch: "ModelHubLaunch | None" = None,
+ *,
+ inputs: _LaunchInputs | None = None,
+ ) -> CodexLaunchSpec:
+ """Every process-level input an app-server for ``cwd`` needs, from one load.
+
+ ``inputs`` is the turn's admission snapshot. A caller outside a turn
+ passes none, and one is taken here before anything awaits.
+ """
+ if inputs is None:
+ inputs = self._launch_inputs(cwd)
+ env = dict(inputs.env)
+ args: list[str] = []
+ catalog: CodexHubCatalog | None = None
+ if launch is not None and launch.channel == "hub":
+ from modules.agents.model_hub import build_codex_hub_launch
+
+ catalog = (await self.prepare_model_hub_runtime(inputs.hub_config, inputs=inputs)).retain()
+ try:
+ args, hub_env = build_codex_hub_launch(
+ [],
+ env,
+ launch,
+ model_catalog_path=catalog.path,
+ )
+ except BaseException:
+ catalog.close()
+ raise
+ # A launch without Hub settings keeps the managed environment.
+ if hub_env is not None:
+ env = hub_env
+ digest = self._launch_spec_digest(
+ inputs,
+ args=args,
+ env=env,
+ catalog_path=str(catalog.path) if catalog is not None else None,
+ )
+ return CodexLaunchSpec(
+ digest=digest,
+ cwd=cwd,
+ binary=inputs.binary,
+ args=tuple(args),
+ extra_args=inputs.extra_args,
+ env=env,
+ hub=catalog is not None,
+ catalog=catalog,
+ )
+
+ async def _acquire_generation(
+ self,
+ cwd: str,
+ launch: "ModelHubLaunch | None" = None,
+ *,
+ inputs: _LaunchInputs | None = None,
+ ) -> RuntimeBinding[CodexLaunchSpec, _CodexRuntime]:
+ """Bind a new turn to the generation serving this turn's launch spec.
+
+ A turn passes its admission snapshot as ``inputs``; work outside a
+ turn passes none, and one is taken here before anything awaits.
+ """
+ if inputs is None:
+ inputs = self._launch_inputs(cwd)
+ unit = self._unit(cwd)
+ await self._retire_unusable_generations(unit)
+ spec = await self._launch_spec(cwd, launch, inputs=inputs)
+ try:
+ binding = await unit.acquire(spec)
+ if not binding.generation.runtime.transport.is_initialized:
+ # It became unusable while the spec was prepared.
+ await binding.release()
+ await self._retire_unusable_generations(unit)
+ binding = await unit.acquire(spec)
+ return binding
+ finally:
+ spec.close()
+
+ async def _bind_any_generation(self, cwd: str) -> RuntimeBinding[CodexLaunchSpec, _CodexRuntime]:
+ """Bind read-only work to any live generation, starting one only if none is."""
+ unit = self._unit(cwd)
+ for generation in reversed(unit.generations):
+ if generation.runtime.transport.is_initialized:
+ try:
+ return await unit.bind(generation)
+ except RuntimeError:
+ continue
+ return await self._acquire_generation(cwd)
+
+ async def _retire_unusable_generations(
+ self,
+ unit: RuntimeGenerationSet[CodexLaunchSpec, _CodexRuntime],
+ ) -> None:
+ """New turns must not bind to a process that can no longer serve.
+
+ Admission may promote a retiring generation whose spec matches, so
+ every attached generation is checked, not only the current one.
+ """
+ for generation in unit.generations:
+ if generation.closed or generation.runtime.transport.is_initialized:
+ continue
+ # Exited, or alive but unusable after a request timed out. New
+ # turns get a fresh process; this one stops once nothing needs it,
+ # which for an exited process is as soon as no durable owner
+ # outlives it.
+ logger.warning(
+ "Retiring unusable Codex app-server generation %s for cwd=%s",
+ generation.runtime.serial,
+ generation.runtime.cwd,
+ )
+ await unit.retire(generation)
+
+ async def _start_generation(self, spec: CodexLaunchSpec) -> _CodexRuntime:
+ transport = CodexTransport(
+ binary=spec.binary,
+ cwd=spec.cwd,
+ extra_args=list(spec.extra_args),
+ runtime_args=list(spec.args),
+ runtime_env=dict(spec.env),
+ model_hub_catalog=spec.catalog,
+ )
+ runtime = _CodexRuntime(
+ cwd=spec.cwd,
+ serial=next(self._generation_serials),
+ transport=transport,
+ hub=spec.hub,
+ )
+ transport.on_notification(
+ lambda method, params: self._on_notification(method, params, runtime=runtime)
+ )
+ transport.on_server_request(
+ lambda req_id, method, params: self._on_server_request(
+ runtime.cwd, req_id, method, params
+ )
+ )
+ # Tracked from before the spawn, so a starting Hub child keeps the
+ # directory's gateway credential and a failed start is still owned.
+ self._runtimes.setdefault(runtime.cwd, set()).add(runtime)
+ try:
+ await transport.start()
+ governor_from_controller(self.controller).apply_to_pid(
+ getattr(transport, "pid", None),
+ label="codex app-server",
+ )
+ runtime.activation = self._attach_runtime_activation(runtime)
+ except BaseException:
+ # No generation will hold this process, whatever failed: a start
+ # whose own cleanup failed, or setup after a successful spawn.
+ if self._process_exited(transport):
+ runtime.ended = True
+ self._runtimes.get(runtime.cwd, set()).discard(runtime)
+ self._retire_hub_scope_after(runtime)
+ else:
+ # The sweep, or shutdown, stops it.
+ runtime.orphaned = True
+ raise
+ logger.info(
+ "Started Codex app-server generation %s for cwd=%s",
+ runtime.serial,
+ runtime.cwd,
+ )
+ return runtime
+
+ async def _generation_drained(self, generation: _CodexGeneration) -> bool:
+ """Whether no turn and no durable owner still needs this process."""
+ runtime = generation.runtime
+ # A turn registered on an exited process can no longer progress there.
+ # A closed reader alone is not exit: the child may still be running it.
+ dead = self._process_exited(runtime.transport)
+ if not dead and any(
+ self._session_has_turn(base_session_id) for base_session_id in runtime.threads
+ ):
+ return False
+ if not dead:
+ # An Activity this process started keeps it, though no Session
+ # binding names it after its turn ended or its Session moved.
+ service = getattr(getattr(self, "controller", None), "agent_service", None)
+ holds = getattr(service, "activation_has_activities", None)
+ if callable(holds) and holds(self.name, runtime.activation):
+ return False
+ ownership = await self._ownership_snapshot(generation)
+ if ownership is None:
+ return False
+ if dead:
+ return not ownership.blocks_dead_transport_replacement
+ return not ownership.blocks_transport_replacement
+
+ async def _stop_generation(self, generation: _CodexGeneration, force: bool) -> bool:
+ """Stop one generation the shared core has detached from its unit.
+
+ A graceful stop declines while a turn or a durable owner still needs
+ the process; the core keeps it and asks again later. A forced stop
+ settles that work with the runtime-update notice and ends the process.
+ A failure propagates, so the core retries and the Sessions stay bound
+ until the process is really gone.
+ """
+ runtime = generation.runtime
+ # A child whose reader closed can never report its work again, so it
+ # is ended like a forced stop instead of waiting for that work.
+ broken = not self._process_exited(runtime.transport) and not getattr(runtime.transport, "is_alive", True)
+ kill = force or broken
+ if not kill and not await self._generation_drained(generation):
return False
- self._transports.pop(cwd, None)
- if hasattr(self, "_transport_last_activity"):
- self._transport_last_activity.pop(cwd, None)
- self._cwd_inodes().pop(cwd, None)
+ # Every adapter-initiated kill settles its bound work through
+ # ``_end_bound_work`` with the runtime-update notice. A shutdown
+ # settles with its own reason: a disable's, or none at service
+ # shutdown, whose restart recovery reports interrupted work.
+ if not kill:
+ settle_reason = None
+ elif self._shutting_down:
+ settle_reason = self._shutdown_settle_reason
+ else:
+ settle_reason = SETTLED_BY_BACKEND_REFRESH
+ stopped = await self._stop_runtime(
+ runtime,
+ # The decision is repeated inside the fence, where no owner can
+ # commit to this generation any longer.
+ still_drained=None if kill else lambda: self._generation_drained(generation),
+ settle_reason=settle_reason,
+ )
+ if not stopped:
+ return False
+ self._forget_runtime_sessions(runtime)
+ logger.info(
+ "Stopped Codex app-server generation %s for cwd=%s%s",
+ runtime.serial,
+ runtime.cwd,
+ " (forced)" if force else "",
+ )
return True
- async def _stop_and_detach_transport_generation(
+ async def _end_bound_work(self, runtime: _CodexRuntime, reason: str) -> None:
+ """Settle a force-stopped generation's work with ``reason``'s notice.
+
+ Its bound Sessions' registered turns and every Activity started under
+ its activation settle here. An Activity can outlive its foreground turn
+ or its Session's thread move and still keep this process owned, so
+ Activities are found by activation, never by Session. A turn still
+ starting holds the unit's binding inside ``handle_message`` and fails
+ or retries on its own once its process is gone. Only this agent's work
+ settles: after a re-enable, another agent can run the same Session in
+ the same directory. Settling again finds nothing left, so a retried
+ teardown may call this freely.
+ """
+ sessions = set(runtime.threads)
+ service = getattr(getattr(self, "controller", None), "agent_service", None)
+ # A turn whose gate a later turn of its Session already took was settled
+ # when that gate was released, for example by the liveness monitor after
+ # the reader closed. Settling its Session now would cancel the later turn.
+ still_owns_gate = getattr(service, "emit_matches_runtime_turn", lambda _context: True)
+ busy = set()
+ for base_session_id in sessions:
+ turn_id = self._turn_registry.get_active_turn(base_session_id)
+ request = self._turn_registry.get_request_for_turn(turn_id) if turn_id else None
+ if turn_id and (request is None or still_owns_gate(request.context)):
+ busy.add(base_session_id)
+ logger.warning(
+ "Force-stopping Codex app-server generation %s for cwd=%s with %d running turn(s)",
+ runtime.serial,
+ runtime.cwd,
+ len(busy),
+ )
+ end_work = getattr(service, "force_end_runtime_work", None)
+ if callable(end_work):
+ await end_work(
+ self.name,
+ base_session_ids=busy,
+ activation_identities={runtime.activation},
+ reason=reason,
+ agent=self,
+ )
+
+ async def _stop_runtime(
+ self,
+ runtime: _CodexRuntime,
+ *,
+ still_drained: Callable[[], Awaitable[bool]] | None = None,
+ settle_reason: str | None = None,
+ require_process_exit: bool = False,
+ ) -> bool:
+ """Tear one process down inside its activation fence.
+
+ The retirement is reserved before anything awaits, so no durable owner
+ commits to the generation while its final drained check runs, its bound
+ work settles (with ``settle_reason``), or its process stops. A failed check or
+ teardown aborts the reservation. Returns False when ``still_drained``
+ declined.
+ """
+ registry = getattr(getattr(self, "controller", None), "runtime_activation", None)
+ reservation = (
+ registry.reserve_retirement(runtime.activation)
+ if registry is not None and runtime.activation is not None
+ else None
+ )
+ transport = runtime.transport
+ process = getattr(transport, "_process", None)
+ # A Session moving off this process meanwhile waits for the teardown,
+ # so its next turn cannot be among the work this teardown settles.
+ teardown = runtime.teardown = asyncio.get_running_loop().create_future()
+ try:
+ if still_drained is not None and not await still_drained():
+ if reservation is not None:
+ registry.finish_retirement(reservation, retire=False)
+ return False
+ if settle_reason is not None:
+ await self._end_bound_work(runtime, settle_reason)
+ await transport.stop()
+ if require_process_exit and process is not None and process.returncode is None:
+ await asyncio.wait_for(process.wait(), timeout=5)
+ if process.returncode is None:
+ raise RuntimeError("Codex native process did not exit")
+ except BaseException:
+ if reservation is not None:
+ registry.finish_retirement(reservation, retire=False)
+ raise
+ finally:
+ runtime.teardown = None
+ teardown.set_result(None)
+ runtime.ended = True
+ runtime.orphaned = False
+ self._runtimes.get(runtime.cwd, set()).discard(runtime)
+ if reservation is not None:
+ registry.finish_retirement(reservation, retire=True)
+ return True
+
+ def _forget_runtime_sessions(self, runtime: _CodexRuntime) -> None:
+ """Unbind every Session of a stopped generation and release its Hub scope."""
+ for base_session_id in list(runtime.threads):
+ self._unbind_session(base_session_id, runtime)
+ self._turn_registry.clear_session(base_session_id)
+ self._retire_hub_scope_after(runtime)
+
+ def _retire_hub_scope_after(self, runtime: _CodexRuntime) -> None:
+ """Revoke the directory's gateway credential once its last Hub process is gone.
+
+ Every Hub generation of a directory, a starting one included, shares
+ one request-scoped credential; only the last one may revoke it.
+ """
+ if runtime.hub and not any(other.hub for other in self._runtimes.get(runtime.cwd, ())):
+ self._retire_model_hub_process_scope(runtime.cwd)
+
+ def _generation_has_live_work(self, generation: _CodexGeneration) -> bool:
+ runtime = generation.runtime
+ # A turn registered on an exited process can no longer progress there.
+ return bool(generation.bindings) or (
+ not self._process_exited(runtime.transport)
+ and any(self._session_has_turn(base_session_id) for base_session_id in runtime.threads)
+ )
+
+ async def _stop_generations_now(
+ self,
+ unit: RuntimeGenerationSet[CodexLaunchSpec, _CodexRuntime],
+ generations: Sequence[_CodexGeneration],
+ *,
+ require_process_exit: bool = False,
+ settle_reason: str | None,
+ ) -> None:
+ """Stop generations outside the core's own decisions.
+
+ Every generation is detached before the first stop awaits, so a turn
+ arriving meanwhile starts its own generation instead of binding to one
+ about to be killed. With ``settle_reason``, each generation's bound
+ work is settled through ``_end_bound_work`` inside its activation
+ fence; callers pass None only when that work was already settled
+ upstream.
+ A process whose stop fails, or that a cancellation left unstopped, is
+ adopted back as retiring with its Sessions still bound, so a later
+ call or sweep can retry.
+ """
+ pending = list(generations)
+ for generation in pending:
+ await unit.discard(generation) # synchronous bookkeeping
+ failure: BaseException | None = None
+ try:
+ while pending:
+ generation = pending[0]
+ try:
+ await self._stop_runtime(
+ generation.runtime, settle_reason=settle_reason, require_process_exit=require_process_exit
+ )
+ except Exception as exc:
+ failure = failure or exc
+ await self._readopt(unit, generation)
+ else:
+ self._forget_runtime_sessions(generation.runtime)
+ pending.pop(0)
+ finally:
+ for generation in pending:
+ await self._readopt(unit, generation)
+ if failure is not None:
+ raise failure
+
+ async def _readopt(
+ self,
+ unit: RuntimeGenerationSet[CodexLaunchSpec, _CodexRuntime],
+ generation: _CodexGeneration,
+ ) -> None:
+ """Attach a detached generation whose process still runs again, as retiring."""
+ runtime = generation.runtime
+ if runtime.ended:
+ return
+ try:
+ restored = await unit.adopt(generation.spec, runtime, current=False)
+ except RuntimeUnitStopping:
+ return # Shutdown ends it through ``_runtimes``.
+ for base_session_id, bound in list(self._session_generations.items()):
+ if bound is generation:
+ self._session_generations[base_session_id] = restored
+
+ async def _end_unattached_runtimes(
+ self,
+ *,
+ require_process_exit: bool = False,
+ settle_reason: str | None = None,
+ ) -> None:
+ """End every process this Agent still owns that no unit holds any longer.
+
+ Migration and the exclusive refresh have already settled the backend's
+ work. A shutdown passes its own reason: a disable's, or none.
+ """
+ failure: BaseException | None = None
+ for runtimes in list(self._runtimes.values()):
+ for runtime in list(runtimes):
+ try:
+ await self._stop_runtime(
+ runtime, require_process_exit=require_process_exit, settle_reason=settle_reason
+ )
+ except Exception as exc:
+ failure = failure or exc
+ continue
+ self._forget_runtime_sessions(runtime)
+ if failure is not None:
+ raise failure
+
+ def _schedule_reap(self, cwd: str) -> None:
+ """Stop the directory's drained retiring generations without blocking the caller."""
+ unit = self._units.get(cwd)
+ if unit is None or not any(generation.retiring for generation in unit.generations):
+ return
+ task = asyncio.create_task(unit.reap())
+ self._reap_tasks.add(task)
+ task.add_done_callback(self._reap_done)
+
+ def _reap_done(self, task: asyncio.Task[None]) -> None:
+ self._reap_tasks.discard(task)
+ if not task.cancelled() and task.exception() is not None:
+ logger.error("Codex runtime generation reap failed", exc_info=task.exception())
+
+ async def reap_runtime_generations(self) -> None:
+ """Stop every retiring generation whose bound work has drained.
+
+ The sweep also retires processes that exited or stopped answering, so
+ an idle directory's dead process and its Hub scope do not linger, and
+ retries the stop of every process no unit holds.
+ """
+ for unit in list(self._units.values()):
+ await self._retire_unusable_generations(unit)
+ await unit.reap()
+ for runtimes in list(self._runtimes.values()):
+ for runtime in [runtime for runtime in runtimes if runtime.orphaned]:
+ try:
+ await self._stop_runtime(runtime)
+ except Exception:
+ logger.warning("Failed to stop a Codex app-server no generation holds", exc_info=True)
+ continue
+ self._forget_runtime_sessions(runtime)
+
+ async def _move_session_to(self, generation: _CodexGeneration, request: AgentRequest) -> None:
+ """Make sure this Session's thread can be loaded in ``generation``."""
+ base_session_id = request.base_session_id
+ bound = self._generation_for_session(base_session_id)
+ if bound is generation:
+ return
+ if bound is not None:
+ logger.info(
+ "Moving Codex session %s from app-server generation %s to %s for cwd=%s",
+ base_session_id,
+ bound.runtime.serial,
+ generation.runtime.serial,
+ generation.runtime.cwd,
+ )
+ await self._release_session_thread(bound, base_session_id)
+ else:
+ # Not loaded anywhere: forget any stale thread id so the next step resumes it.
+ self._forget_stale_session(base_session_id)
+ self._turn_registry.clear_session(base_session_id)
+
+ async def _release_session_thread(self, generation: _CodexGeneration, base_session_id: str) -> None:
+ """Have ``generation`` unload this Session's thread so another can resume it.
+
+ Codex lets only one process at a time hold a thread's writer lock. This
+ returns only on proof that the thread is released: ``thread/closed``
+ from that process, Codex reporting it not loaded there, or the process
+ having exited. Anything less raises
+ ``CodexThreadReleaseUnavailableError`` and leaves the binding in place.
+ """
+ runtime = generation.runtime
+ thread_id = runtime.threads.get(base_session_id) or self._session_mgr.get_thread_id(base_session_id)
+ transport = runtime.transport
+ teardown = runtime.teardown
+ if teardown is not None:
+ # A teardown is settling this process's work and then ends it;
+ # its exit releases the thread.
+ try:
+ await asyncio.wait_for(asyncio.shield(teardown), _THREAD_RELEASE_TIMEOUT_SECONDS)
+ except TimeoutError as exc:
+ raise CodexThreadReleaseUnavailableError(
+ f"Codex app-server generation {runtime.serial} is still stopping"
+ ) from exc
+ bound = self._generation_for_session(base_session_id)
+ if bound is None or bound.runtime is not runtime:
+ return # The stop unbound it.
+ # The teardown declined or failed, and adopting a survivor back
+ # rebinds the Session to the same process: release it there.
+ if thread_id and not runtime.ended and not self._process_exited(transport):
+ active_turn = self._turn_registry.get_active_turn(base_session_id)
+ if active_turn:
+ await self._interrupt_turn_before_move(transport, base_session_id, thread_id, active_turn)
+ released = asyncio.Event()
+ runtime.released_threads[thread_id] = released
+ try:
+ await self._await_thread_release(transport, thread_id, released)
+ finally:
+ runtime.released_threads.pop(thread_id, None)
+ self._unbind_session(base_session_id, runtime)
+ self._schedule_reap(runtime.cwd)
+
+ @staticmethod
+ def _process_exited(transport: CodexTransport) -> bool:
+ """Whether the app-server process is gone.
+
+ A closed stdout reader is no proof: the child can outlive it and keep
+ every thread's writer lock.
+ """
+ process = getattr(transport, "_process", None)
+ if process is None:
+ return not getattr(transport, "is_alive", True)
+ return process.returncode is not None
+
+ async def _await_thread_release(
+ self,
+ transport: CodexTransport,
+ thread_id: str,
+ released: asyncio.Event,
+ ) -> None:
+ unavailable = CodexThreadReleaseUnavailableError(f"Codex app-server did not release thread {thread_id}")
+ try:
+ response = await transport.send_request("thread/unsubscribe", {"threadId": thread_id})
+ except ConnectionError:
+ # The reader is gone, so only the process exit can release the thread.
+ response = None
+ except (CodexRPCError, TimeoutError) as exc:
+ raise unavailable from exc
+ if self._process_exited(transport) or (response is not None and response.get("status") == "notLoaded"):
+ return
+ process = getattr(transport, "_process", None)
+ waits = {asyncio.create_task(released.wait())}
+ if process is not None and process.returncode is None:
+ waits.add(asyncio.create_task(process.wait()))
+ try:
+ await asyncio.wait(waits, timeout=_THREAD_RELEASE_TIMEOUT_SECONDS, return_when=asyncio.FIRST_COMPLETED)
+ finally:
+ for task in waits:
+ task.cancel()
+ await asyncio.gather(*waits, return_exceptions=True)
+ if released.is_set() or self._process_exited(transport):
+ return
+ if response is None or not transport.is_alive:
+ raise unavailable
+ try:
+ loaded = await transport.send_request("thread/loaded/list", {})
+ except Exception as exc: # noqa: BLE001 - unknown is not released
+ if self._process_exited(transport):
+ return
+ raise unavailable from exc
+ if thread_id in (loaded.get("data") or ()):
+ raise unavailable
+
+ async def _interrupt_turn_before_move(
self,
- cwd: str,
transport: CodexTransport,
- *,
- final_predicate: Callable[[], Awaitable[bool]] | None = None,
- require_process_exit: bool = False,
- ) -> bool:
- """Stop one exact generation, retaining it if validation or stop fails."""
+ base_session_id: str,
+ thread_id: str,
+ active_turn: str,
+ ) -> None:
+ """Interrupt a Session's own running turn before its thread moves.
- reserved = self._reserve_transport_retirement(cwd, transport)
- if reserved is None:
- return False
+ Unsubscribing ends this connection's view of the turn, so the turn is
+ settled here, and only once Codex accepted the interrupt or the turn or
+ its process already ended. A refused interrupt changes nothing.
+ """
try:
- if final_predicate is not None and not await final_predicate():
- self._finish_transport_retirement(reserved, retire=False)
- return False
- process = getattr(transport, "_process", None)
- await transport.stop()
- if require_process_exit and process is not None and process.returncode is None:
- await asyncio.wait_for(process.wait(), timeout=5)
- if process.returncode is None:
- raise RuntimeError("Codex native process did not exit")
- except BaseException:
- self._finish_transport_retirement(reserved, retire=False)
- raise
- if not self._finish_transport_retirement(reserved, retire=True):
- raise RuntimeError(
- f"Codex transport retirement lost its exact generation for cwd={cwd}"
+ await transport.send_request(
+ "turn/interrupt",
+ {"threadId": thread_id, "turnId": active_turn},
)
- return self._detach_transport_bookkeeping(cwd, transport)
-
- def runtime_activation_identity_for_request(
- self,
- request: Any,
- ) -> RuntimeActivationIdentity | None:
- cwd = str(getattr(request, "working_path", "") or "").strip()
- if not cwd:
- metadata = getattr(request, "metadata", None)
- if isinstance(metadata, dict):
- cwd = str(metadata.get("session_workdir") or "").strip()
- if cwd:
- return self._transport_activation_identity(self._transports.get(cwd))
-
- session_key = str(getattr(request, "session_key", "") or "").strip()
- if not session_key:
- return None
- get_sessions = getattr(self._session_mgr, "get_sessions_by_session_key", None)
- get_cwd = getattr(self._session_mgr, "get_cwd", None)
- if not callable(get_sessions) or not callable(get_cwd):
- raise ValueError("Codex Session route mapping is unavailable")
-
- live_identities: dict[str, RuntimeActivationIdentity] = {}
- for base_session_id in get_sessions(session_key):
- mapped_cwd = str(get_cwd(base_session_id) or "").strip()
- if not mapped_cwd or mapped_cwd in live_identities:
- continue
- transport = self._transports.get(mapped_cwd)
- if transport is None:
- continue
- identity = self._transport_activation_identity(transport)
- if identity is None:
- raise ValueError("Codex runtime generation is not attached")
- live_identities[mapped_cwd] = identity
-
- if len(live_identities) > 1:
- raise ValueError("multiple live Codex runtime resources match Session route")
- return next(iter(live_identities.values()), None)
-
- def runtime_activation_identity_for_session_binding(
- self,
- *,
- session_anchor: str,
- workdir: str | None,
- ) -> RuntimeActivationIdentity | None:
- normalized_anchor = str(session_anchor or "").strip()
- normalized_workdir = str(workdir or "").strip()
- if not normalized_anchor or not normalized_workdir:
- return None
- bound_workdir = str(self._session_mgr.get_cwd(normalized_anchor) or "").strip()
- if bound_workdir and bound_workdir != normalized_workdir:
- raise ValueError("Codex Session binding changed workdir")
- transport = self._transports.get(normalized_workdir)
- if transport is None:
- return None
- identity = self._transport_activation_identity(transport)
- if identity is None:
- raise ValueError("Codex runtime generation is not attached")
- return identity
+ except Exception as exc:
+ if self._turn_registry.get_active_turn(base_session_id) == active_turn and not self._process_exited(
+ transport
+ ):
+ raise CodexThreadReleaseUnavailableError(
+ f"Codex app-server did not interrupt turn {active_turn} before moving thread {thread_id}"
+ ) from exc
+ interrupted_request = self._event_handler.clear_pending(active_turn)
+ if interrupted_request:
+ await self._remove_ack_reaction(interrupted_request)
+ # Its completion never arrives here. Release is token-guarded, so
+ # it cannot close the new turn.
+ self._event_handler._release_stream_turn(interrupted_request.context)
+ self._turn_registry.clear_session(base_session_id)
- def record_runtime_turn_start(
+ async def _open_session_thread(
self,
+ generation: _CodexGeneration,
+ request: AgentRequest,
*,
- runtime_key: str,
- request: AgentRequest | None,
- ) -> None:
- if request is None:
- return
- self._touch_transport_activity(request.working_path)
- self._touch_session_activity(request.base_session_id)
+ developer_instructions: Optional[str] = None,
+ ) -> str:
+ """Start, fork, or resume the Session's thread in ``generation``."""
+ try:
+ return await self._start_or_resume_thread(
+ generation.runtime.transport,
+ request,
+ developer_instructions=developer_instructions,
+ )
+ finally:
+ # A thread may be loaded even when a later step failed.
+ thread_id = self._session_mgr.get_thread_id(request.base_session_id)
+ if thread_id:
+ self._bind_session_thread(generation, request.base_session_id, thread_id)
- def _stuck_active_sessions_for_cwd(
+ def _stuck_active_sessions(
self,
- cwd: str,
+ runtime: _CodexRuntime,
*,
now: float,
cap: float | None,
) -> list[str]:
+ """The Sessions on ``runtime`` whose turn made no progress within ``cap``."""
if cap is None:
return []
- if not hasattr(self, "_session_last_activity"):
- self._session_last_activity = {}
stuck = []
- for base_session_id in self._session_mgr.sessions_for_cwd(cwd):
+ for base_session_id in list(runtime.threads):
if not self._turn_registry.get_active_turn(base_session_id):
continue
last_progress = self._session_last_activity.get(base_session_id)
@@ -1851,150 +2838,136 @@ class CodexAgent(BaseAgent):
stuck.append(base_session_id)
return stuck
+ def _has_active_turns_on(self, runtime: _CodexRuntime) -> bool:
+ return any(self._session_has_turn(base_session_id) for base_session_id in list(runtime.threads))
+
+ async def _settle_stuck_sessions(self, generation: _CodexGeneration, stuck_sessions: Sequence[str]) -> bool:
+ """Settle each stuck turn still held by ``generation``; True if any was.
+
+ Only the exact stuck turn is forgotten: one that a new admission
+ replaced meanwhile, or that moved to another generation, is left alone.
+ """
+ runtime = generation.runtime
+ settled = False
+ for base_session_id in stuck_sessions:
+ turn_id = self._turn_registry.get_active_turn(base_session_id)
+ if not turn_id or self._session_generations.get(base_session_id) is not generation:
+ continue
+ logger.warning(
+ "Settling stuck-active Codex session %s for cwd=%s after exact progress timeout",
+ base_session_id,
+ runtime.cwd,
+ )
+ await self._settle_stuck_active_request(base_session_id)
+ # Not held across the terminal emission, which may admit the next turn.
+ async with self.session_lifecycle(base_session_id):
+ if self._turn_registry.get_active_turn(base_session_id) == turn_id:
+ self._turn_registry.clear_session(base_session_id)
+ self._session_last_activity.pop(base_session_id, None)
+ settled = True
+ return settled
+
async def evict_idle_transports(self, idle_timeout: float) -> int:
- """Stop idle Codex transports after two exact ownership snapshots."""
+ """Retire idle app-servers and repair stuck turns on every generation.
+
+ Each generation is judged only by the Sessions whose threads it holds.
+ A directory's current generation retires once it stays idle; a
+ retiring one whose turn is stuck past the age backstop has that turn
+ settled, so it can drain. Two exact ownership snapshots gate each
+ decision, and the shared core stops a generation only if no turn bound
+ to it meanwhile.
+ """
if idle_timeout <= 0:
return 0
- if not hasattr(self, "_transport_last_activity"):
- self._transport_last_activity = {}
- if not hasattr(self, "_transport_locks"):
- self._transport_locks = {}
- if not hasattr(self, "_session_locks"):
- self._session_locks = {}
- if not hasattr(self, "_session_last_activity"):
- self._session_last_activity = {}
-
stuck_active_cap = self._stuck_active_idle_eviction_cap(idle_timeout)
now = time.monotonic()
evicted = 0
- initial_cwds = tuple(self._transports)
- initial_snapshots = await self._runtime_ownership_snapshots_for_cwds(
- initial_cwds
+ candidates = tuple(
+ generation
+ for unit in list(self._units.values())
+ for generation in unit.generations
+ if generation is unit.current
+ or self._stuck_active_sessions(generation.runtime, now=now, cap=stuck_active_cap)
)
+ initial_snapshots = await self._ownership_snapshots(candidates)
if initial_snapshots is None:
return 0
- ownership_by_cwd = dict(zip(initial_cwds, initial_snapshots, strict=True))
- for cwd, last_activity in list(self._transport_last_activity.items()):
- transport = self._transports.get(cwd)
- if transport is None:
- self._transport_last_activity.pop(cwd, None)
+ for generation, ownership in zip(candidates, initial_snapshots, strict=True):
+ runtime = generation.runtime
+ unit = self._units.get(runtime.cwd)
+ if unit is None or generation not in unit.generations:
continue
- ownership = ownership_by_cwd.get(cwd)
- if ownership is None:
- continue
- stuck_sessions = self._stuck_active_sessions_for_cwd(
- cwd,
- now=now,
- cap=stuck_active_cap,
- )
- has_active = self._has_active_turns_for_cwd(cwd)
- idle_for = now - last_activity
+ current = unit.current is generation
+ stuck_sessions = self._stuck_active_sessions(runtime, now=now, cap=stuck_active_cap)
+ idle_for = now - runtime.last_activity
ordinary_candidate = (
- not ownership.blocks_reclamation
- and not has_active
+ current
+ and not ownership.blocks_reclamation
+ and not generation.bindings
+ and not self._has_active_turns_on(runtime)
and idle_for >= idle_timeout
)
stuck_candidate = bool(stuck_sessions) and not ownership.blocks_reclamation
if not ordinary_candidate and not stuck_candidate:
continue
- lock = self._transport_locks.setdefault(cwd, asyncio.Lock())
- async with lock:
- current_transport = self._transports.get(cwd)
- current_last_activity = self._transport_last_activity.get(cwd)
- if current_transport is None or current_transport is not transport:
- continue
- if current_last_activity is None:
- continue
- ownership = await self._runtime_ownership_snapshot_for_cwd_async(cwd)
- if ownership is None:
- continue
- current_now = time.monotonic()
- idle_for = current_now - current_last_activity
- stuck_sessions = self._stuck_active_sessions_for_cwd(
- cwd,
- now=current_now,
- cap=stuck_active_cap,
- )
- # Silence cannot revoke a durable Turn or Activity owner.
- # The age backstop only repairs stale adapter-local flags once
- # durable ownership independently allows reclamation.
- if ownership.blocks_reclamation:
- continue
+ ownership = await self._ownership_snapshot(generation)
+ moved = generation not in unit.generations or (unit.current is generation) != current
+ if ownership is None or ownership.blocks_reclamation or moved:
+ continue
+ # Silence cannot revoke a durable Turn or Activity owner. The age
+ # backstop only repairs stale adapter-local flags once durable
+ # ownership independently allows reclamation.
+ current_now = time.monotonic()
+ stuck_sessions = self._stuck_active_sessions(runtime, now=current_now, cap=stuck_active_cap)
+ if await self._settle_stuck_sessions(generation, stuck_sessions):
+ # A settled turn may still run natively. It ends with its
+ # process, which stops once nothing else needs it.
+ await unit.retire(generation)
+ await unit.reap()
+ evicted += int(runtime.ended)
+ continue
+ if not current:
+ continue
+ idle_for = time.monotonic() - runtime.last_activity
+ if (
+ unit.current is not generation
+ or self._has_active_turns_on(runtime)
+ or idle_for < idle_timeout
+ ):
+ continue
- settled_stuck_sessions: set[str] = set()
- for base_session_id in stuck_sessions:
- logger.warning(
- "Settling stuck-active Codex session %s for cwd=%s after exact progress timeout",
- base_session_id,
- cwd,
- )
- await self._settle_stuck_active_request(base_session_id)
- self._turn_registry.clear_session(base_session_id)
- settled_stuck_sessions.add(base_session_id)
- self._session_locks.pop(base_session_id, None)
+ sessions = list(self._session_mgr.sessions_for_cwd(runtime.cwd))
+ await unit.retire(generation)
+ await unit.settled()
+ if not runtime.ended:
+ # Work bound meanwhile; the generation stops once it drains.
+ continue
+ logger.info(
+ "Evicting idle Codex transport for cwd=%s after %.1fs idle",
+ runtime.cwd,
+ idle_for,
+ )
+ # The stop unbound every Session it served. One that bound to
+ # another generation meanwhile keeps its state.
+ for base_session_id in sessions:
+ if self._session_generations.get(base_session_id) is None:
+ self._forget_session_lock(base_session_id)
self._session_last_activity.pop(base_session_id, None)
+ evicted += 1
- if stuck_sessions:
- ownership = await self._runtime_ownership_snapshot_for_cwd_async(cwd)
- if ownership is None or ownership.blocks_reclamation:
- continue
- final: dict[str, float] = {}
-
- async def final_reclamation_predicate() -> bool:
- if self._transports.get(cwd) is not transport:
- return False
- latest_activity = self._transport_last_activity.get(cwd)
- if latest_activity is None:
- return False
- current_ownership = (
- await self._runtime_ownership_snapshot_for_cwd_async(cwd)
- )
- if current_ownership is None or current_ownership.blocks_reclamation:
- return False
- current_idle_for = time.monotonic() - latest_activity
- final["idle_for"] = current_idle_for
- return bool(
- not self._has_active_turns_for_cwd(cwd)
- and current_idle_for >= idle_timeout
- )
-
- try:
- detached = await self._stop_and_detach_transport_generation(
- cwd,
- transport,
- final_predicate=final_reclamation_predicate,
- )
- except Exception as exc:
- logger.warning(
- "Failed to stop idle Codex transport for cwd=%s: %s",
- cwd,
- exc,
- )
- continue
- if not detached:
- continue
- idle_for = final.get("idle_for", idle_for)
-
- logger.info(
- "Evicting idle Codex transport for cwd=%s after %.1fs idle",
- cwd,
- idle_for,
- )
- self._retire_model_hub_process_scope(cwd)
-
- for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):
- self._session_mgr.invalidate_thread(base_session_id)
- if base_session_id not in settled_stuck_sessions:
- self._turn_registry.clear_session(base_session_id)
- self._session_locks.pop(base_session_id, None)
- self._session_last_activity.pop(base_session_id, None)
- self._clear_thread_developer_instructions(base_session_id)
+ return evicted
- evicted += 1
+ def _hub_process_scope(self, cwd: str) -> str:
+ """The gateway credential scope of this agent's Hub processes in ``cwd``.
- return evicted
+ A disable whose teardown failed keeps the old agent's processes until
+ a retry stops them, while a re-enabled agent already runs its own in
+ the same directory. Each agent owns its scope, so the old one revoking
+ it with its last Hub process never revokes the new one's credential.
+ """
+ return f"{cwd}#{self._instance_serial}"
def _retire_model_hub_process_scope(self, cwd: str) -> None:
if not getattr(self, "_registered_runtime", True):
@@ -2003,7 +2976,7 @@ class CodexAgent(BaseAgent):
router = getattr(controller, "model_hub_runtime", None)
retire = getattr(router, "retire_process_scope", None)
if callable(retire):
- retire("codex", cwd)
+ retire("codex", self._hub_process_scope(cwd))
async def _settle_stuck_active_request(self, base_session_id: str) -> None:
"""Settle a turn we are about to force-reap.
@@ -2071,33 +3044,6 @@ class CodexAgent(BaseAgent):
floor = max(0.0, float(DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS))
return max(idle_timeout * multiplier, floor)
- def _is_transport_evictable(
- self,
- *,
- has_active: bool,
- idle_for: float,
- idle_timeout: float,
- stuck_active_cap: Optional[float],
- ) -> bool:
- """Decide whether an idle transport is eligible for eviction.
-
- Pure decision (no lookups), so callers evaluate the active-turn flag
- exactly once. An idle transport with no active turn is evictable once it
- crosses the normal ``idle_timeout``. A transport with an active turn is
- normally vetoed, but is force-evictable once it crosses
- ``stuck_active_cap`` (the absolute-time backstop) — the only path that
- reaps a wedged app-server whose ``turn/completed`` never arrived.
- """
- if has_active:
- if stuck_active_cap is None:
- return False
- return idle_for >= stuck_active_cap
- return idle_for >= idle_timeout
-
- # ------------------------------------------------------------------
- # Transport management
- # ------------------------------------------------------------------
-
def _is_recoverable_transport_error(self, error: Exception) -> bool:
if isinstance(error, CodexResponseTooLargeError):
return False
@@ -2119,301 +3065,37 @@ class CodexAgent(BaseAgent):
)
)
- async def _transport_replacement_is_safe(self, cwd: str, transport: CodexTransport) -> bool:
- """Recheck durable ownership and live turns inside retirement."""
- ownership = await self._runtime_ownership_snapshot_for_cwd_async(cwd)
- dead = self._transport_alive(transport) is False
- blocked = getattr(
- ownership,
- "blocks_dead_transport_replacement" if dead else "blocks_transport_replacement",
- True,
- )
- return bool(
- ownership is not None
- and not blocked
- and (dead or not self._has_active_turns_for_cwd(cwd))
- )
-
- async def _drop_transport_after_failure(
+ async def _drop_generation_after_failure(
self,
- cwd: str,
- transport: CodexTransport,
+ generation: _CodexGeneration,
request: AgentRequest,
+ binding: RuntimeBinding[CodexLaunchSpec, _CodexRuntime],
) -> bool:
- """Remove a broken app-server and clear stale in-memory request state."""
- lock = self._transport_locks.setdefault(cwd, asyncio.Lock())
- async with lock:
- current = self._transports.get(cwd)
- should_invalidate_cwd_sessions = current is None or current is transport
- if current is transport:
- try:
- detached = await self._stop_and_detach_transport_generation(
- cwd,
- transport,
- final_predicate=lambda: self._transport_replacement_is_safe(cwd, transport),
- )
- except Exception as exc:
- logger.warning(
- "Failed to stop broken Codex transport for cwd=%s: %s",
- cwd,
- exc,
- )
- return False
- if not detached:
- logger.warning("Codex failure recovery cannot replace an owned transport for cwd=%s", cwd)
- return False
- elif current is None:
- identity = self._transport_activation_identity(transport)
- registry = getattr(getattr(self, "controller", None), "runtime_activation", None)
- if identity is not None and registry is not None and registry.is_current(identity):
- logger.error(
- "Refusing to stop an untracked current Codex generation for cwd=%s",
- cwd,
- )
- return False
- try:
- await transport.stop()
- except Exception as exc:
- logger.warning(
- "Failed to stop detached broken Codex transport for cwd=%s: %s",
- cwd,
- exc,
- )
- return False
- else:
- identity = self._transport_activation_identity(transport)
- registry = getattr(
- getattr(self, "controller", None),
- "runtime_activation",
- None,
- )
- if identity is not None and registry is not None and registry.is_current(
- identity
- ):
- logger.error(
- "Refusing to stop a replaced but still-current Codex generation for cwd=%s",
- cwd,
- )
- return False
- try:
- await transport.stop()
- except Exception as exc:
- logger.warning(
- "Failed to stop replaced broken Codex transport for cwd=%s: %s",
- cwd,
- exc,
- )
- return False
-
- if should_invalidate_cwd_sessions:
- for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):
- if base_session_id == request.base_session_id:
- continue
- self._session_mgr.invalidate_thread(base_session_id)
- self._clear_thread_developer_instructions(base_session_id)
- self._turn_registry.clear_session(base_session_id)
+ """Replace a broken app-server generation when no other work still needs it.
- self._session_mgr.invalidate_thread(request.base_session_id)
- self._clear_thread_developer_instructions(request.base_session_id)
- self._turn_registry.clear_session(request.base_session_id)
+ Retiring is atomic with admission, so no new turn binds to the broken
+ process; it stops only through the core's drained check.
+ """
+ runtime = generation.runtime
+ # Stopping the generation forgets every Session it held.
+ forgotten_by_stop = request.base_session_id in runtime.threads and not runtime.ended
+ if not runtime.ended:
+ unit = self._units.get(runtime.cwd)
+ await binding.release() # this turn no longer needs the broken process
+ if unit is not None:
+ await unit.retire(generation)
+ await unit.settled()
+ if not runtime.ended:
+ logger.warning(
+ "Codex failure recovery cannot replace an owned transport for cwd=%s",
+ runtime.cwd,
+ )
+ return False
+ if not forgotten_by_stop:
+ self._forget_stale_session(request.base_session_id)
+ self._turn_registry.clear_session(request.base_session_id)
return True
- async def _get_or_create_transport(
- self,
- cwd: str,
- launch: "ModelHubLaunch | None" = None,
- *,
- allow_runtime_replacement: bool = True,
- ) -> CodexTransport:
- """Return an initialized transport for the given working directory."""
- # Serialize creation per cwd
- if cwd not in self._transport_locks:
- self._transport_locks[cwd] = asyncio.Lock()
-
- wait_deadline: float | None = None
- while True:
- wait_for_active_turns = False
- async with self._transport_locks[cwd], AsyncExitStack() as catalog_pins:
- # Double-check after acquiring lock
- existing = self._transports.get(cwd)
- desired_fingerprint = launch.fingerprint if launch is not None else "direct"
- existing_fingerprint = getattr(existing, "runtime_fingerprint", "direct")
- runtime_changed = existing_fingerprint != desired_fingerprint
- if existing is not None and runtime_changed and not allow_runtime_replacement:
- raise CodexConnectionProbeRuntimeMismatchError(
- "The cached Codex transport does not use direct credentials"
- )
- if existing and existing.is_initialized:
- # Reuse only while the directory the app-server was spawned in
- # is still the SAME directory (#561): after a delete (+ possible
- # re-create) the cached process sits in a dead inode and every
- # thread/start fails. Untracked legacy entries reuse as before.
- spawned_ino = self._cwd_inodes().get(cwd)
- stale_cwd = spawned_ino is not None and self._cwd_inode(cwd) != spawned_ino
- if not stale_cwd and not runtime_changed:
- self._attach_transport_activation(cwd, existing)
- self._touch_transport_activity(cwd)
- return existing
- if runtime_changed and self._has_active_turns_for_cwd(cwd):
- wait_for_active_turns = True
- elif stale_cwd:
- logger.warning(
- "Codex transport cwd was replaced under the cached app-server; "
- "restarting transport for cwd=%s",
- cwd,
- )
- else:
- logger.info("Restarting Codex transport after Model Hub channel change for cwd=%s", cwd)
-
- if wait_for_active_turns:
- now = time.monotonic()
- if wait_deadline is None:
- wait_deadline = now + _RUNTIME_CHANGE_WAIT_SECONDS
- logger.info(
- "Codex runtime change waiting for active turns: cwd=%s from=%s to=%s",
- cwd,
- existing_fingerprint.split(":", 1)[0],
- desired_fingerprint.split(":", 1)[0],
- )
- elif now >= wait_deadline:
- logger.warning(
- "Codex runtime change blocked by active turns after %.0fs: cwd=%s",
- _RUNTIME_CHANGE_WAIT_SECONDS,
- cwd,
- )
- raise CodexRuntimeChangeBlockedError(
- "Another active Codex turn in this working directory uses a "
- "different runtime; the requested model cannot start until it finishes"
- )
- else:
- runtime_args: list[str] = []
- runtime_env = dict(self._codex_runtime_environment())
- runtime_fingerprint = "direct"
- catalog = None
- if launch is not None:
- from modules.agents.model_hub import build_codex_hub_launch
-
- if launch.channel == "hub":
- # Capture the reference before any later await.
- # Invalidation may drop the cache while we retire
- # an old transport or spawn/initialize its successor.
- catalog = (await self.prepare_model_hub_runtime()).retain()
- catalog_pins.callback(catalog.close)
- runtime_args, runtime_env = build_codex_hub_launch(
- [],
- runtime_env,
- launch,
- model_catalog_path=catalog.path if catalog is not None else None,
- )
- runtime_fingerprint = launch.fingerprint
-
- # Stop stale transport if any
- if existing:
- detached = await self._stop_and_detach_transport_generation(
- cwd,
- existing,
- final_predicate=lambda: self._transport_replacement_is_safe(cwd, existing),
- )
- if not detached:
- raise RuntimeError(
- "Codex transport replacement blocked by a durable owner "
- "or changed generation"
- )
- if (
- runtime_changed
- and desired_fingerprint == "direct"
- and existing_fingerprint.startswith("hub:")
- ):
- self._retire_model_hub_process_scope(cwd)
- # The new app-server process won't know about threads/turns
- # from the old process. Invalidate only sessions bound to
- # this cwd so healthy sessions on other cwds are unaffected.
- affected = self._session_mgr.sessions_for_cwd(cwd)
- for bid in affected:
- self._session_mgr.invalidate_thread(bid)
- self._clear_thread_developer_instructions(bid)
- self._turn_registry.clear_session(bid)
- if affected:
- logger.info(
- "Invalidated %d stale Codex session(s) after transport restart for cwd=%s",
- len(affected),
- cwd,
- )
-
- transport = CodexTransport(
- binary=self.codex_config.binary,
- cwd=cwd,
- extra_args=list(self.codex_config.extra_args),
- runtime_args=runtime_args,
- runtime_env=runtime_env,
- runtime_fingerprint=runtime_fingerprint,
- model_hub_catalog=catalog,
- )
-
- # Wire up callbacks
- transport.on_notification(self._on_notification)
- # Bind the cwd so any server request (e.g. an auto-approval)
- # refreshes this transport's activity even without a turn id.
- transport.on_server_request(
- lambda req_id, method, params, _cwd=cwd: self._on_server_request(
- _cwd, req_id, method, params
- )
- )
-
- await transport.start()
- governor_from_controller(self.controller).apply_to_pid(
- getattr(transport, "pid", None),
- label="codex app-server",
- )
- self._attach_transport_activation(cwd, transport)
- self._transports[cwd] = transport
- self._cwd_inodes()[cwd] = self._cwd_inode(cwd)
- self._touch_transport_activity(cwd)
- return transport
- if wait_for_active_turns:
- await asyncio.sleep(0.05)
-
- async def _interrupt_active_turn_before_runtime_change(
- self,
- request: AgentRequest,
- launch: "ModelHubLaunch",
- ) -> None:
- """Let a replacement prompt interrupt its own stale-runtime turn."""
-
- transport = self._transports.get(request.working_path)
- if transport is None or not transport.is_initialized:
- return
- if getattr(transport, "runtime_fingerprint", "direct") == launch.fingerprint:
- return
- thread_id = self._session_mgr.get_thread_id(request.base_session_id)
- active_turn = self._turn_registry.get_active_turn(request.base_session_id)
- if not thread_id or not active_turn:
- return
- try:
- await transport.send_request(
- "turn/interrupt",
- {"threadId": thread_id, "turnId": active_turn},
- )
- except Exception:
- # A dead/wedged transport cannot acknowledge the interrupt. Hide
- # and release the old turn anyway so the runtime-change path can
- # replace that transport instead of waiting on it forever.
- logger.warning(
- "Codex turn interrupt failed before Model Hub runtime change; "
- "replacing stale transport for cwd=%s",
- request.working_path,
- exc_info=True,
- )
- interrupted_request = self._event_handler.clear_pending(active_turn)
- if interrupted_request:
- await self._remove_ack_reaction(interrupted_request)
- # The app-server may be replaced before its interrupted completion
- # notification arrives. Settle the old request now; release is
- # token-guarded, so it cannot close the replacement turn.
- release = getattr(self._event_handler, "_release_stream_turn", None)
- if callable(release):
- release(interrupted_request.context)
-
# ------------------------------------------------------------------
# Thread management
# ------------------------------------------------------------------
@@ -2476,13 +3158,19 @@ class CodexAgent(BaseAgent):
self,
params: Dict[str, Any],
request: AgentRequest,
+ process_env: Mapping[str, str],
*,
force_path: bool = False,
) -> tuple[str, bool]:
+ """Set the turn's shell environment on top of ``process_env``.
+
+ ``process_env`` is the environment of the app-server that runs the
+ turn, which its shell inherits; see ``_process_environment``.
+ """
from core.git_runtime import prepend_vendored_git_to_path
env = self._caller_env_for_request(request)
- runtime_env = self._codex_runtime_environment()
+ runtime_env = process_env
config = dict(params.get("config") or {})
config["skills.include_instructions"] = False
params["config"] = config
@@ -2508,10 +3196,10 @@ class CodexAgent(BaseAgent):
params["config"] = config
return git_path_state, path_managed
- def _git_path_state_for_request(self, request: AgentRequest) -> str:
+ def _git_path_state_for_request(self, request: AgentRequest, process_env: Mapping[str, str]) -> str:
from core.git_runtime import prepend_vendored_git_to_path
- runtime_env = self._codex_runtime_environment()
+ runtime_env = process_env
env: dict[str, str] = {}
prepend_vendored_git_to_path(
env,
@@ -2520,6 +3208,16 @@ class CodexAgent(BaseAgent):
)
return env["PATH"] if "PATH" in env else runtime_env.get("PATH", "")
+ @staticmethod
+ def _process_environment(transport: CodexTransport) -> Mapping[str, str]:
+ """The environment an app-server runs with, which its shell inherits.
+
+ It comes from the launch the process was started from, never from the
+ current configuration, so a save during a turn cannot split them.
+ """
+ env = getattr(transport, "runtime_env", None)
+ return env if env is not None else os.environ
+
def _codex_runtime_environment(self) -> Mapping[str, str]:
base_env = os.environ
binary = getattr(getattr(self, "codex_config", None), "binary", "codex")
@@ -2548,7 +3246,9 @@ class CodexAgent(BaseAgent):
params["developerInstructions"] = await self._native_thread_prompt(
transport, request, developer_instructions
)
- git_path_state, git_path_managed = self._inject_caller_env_config(params, request)
+ git_path_state, git_path_managed = self._inject_caller_env_config(
+ params, request, self._process_environment(transport)
+ )
resp = await transport.send_request("thread/start", params)
# thread/start returns Thread directly OR may nest under "thread"
@@ -2560,9 +3260,12 @@ class CodexAgent(BaseAgent):
if not thread_id:
raise RuntimeError("Codex thread/start returned no thread id")
- self._session_mgr.set_thread_id(request.base_session_id, thread_id)
- # Also persist for resume support
+ # Persisted first: a thread the durable mapping lacks must not serve a
+ # turn, or that conversation would vanish from resume history. A failed
+ # write leaves the new, still empty thread unused, and the retry starts
+ # another.
self.bind_agent_session_id(request, thread_id)
+ self._session_mgr.set_thread_id(request.base_session_id, thread_id)
if developer_instructions:
from core.skill_observability import accept_catalog
@@ -2680,7 +3383,9 @@ class CodexAgent(BaseAgent):
params["developerInstructions"] = None
if effective_model:
params["model"] = effective_model
- git_path_state, git_path_managed = self._inject_caller_env_config(params, request)
+ git_path_state, git_path_managed = self._inject_caller_env_config(
+ params, request, self._process_environment(transport)
+ )
self._mark_fork_correction_pending(request.base_session_id)
try:
@@ -2717,10 +3422,11 @@ class CodexAgent(BaseAgent):
await self._inject_forked_session_correction(transport, request, thread_id)
finally:
self._clear_fork_correction_pending(request.base_session_id)
- self._session_mgr.set_thread_id(request.base_session_id, thread_id)
+ # Persisted first, as for a new thread.
target_agent_session_id = (
self.bind_agent_session_id(request, thread_id) or target_agent_session_id
)
+ self._session_mgr.set_thread_id(request.base_session_id, thread_id)
cache_source_prompt_strategy = True
if source_prompt_instructions is not None:
persisted_prompt_strategy = self._persist_prompt_strategy(
@@ -2900,6 +3606,14 @@ class CodexAgent(BaseAgent):
source_thread_id = str(fork.get("source_native_session_id") or "").strip()
if not active_turn_id or not source_thread_id:
return True, None
+ # Another process reads a live turn as interrupted; only the generation
+ # holding the source thread reports it in progress. ``source_session_id``
+ # is the durable Session id, not a base session, so look up the thread.
+ source_generation = self._generation_holding_thread(source_thread_id)
+ if source_generation is not None and not self._process_exited(source_generation.runtime.transport):
+ # Even one that stopped answering: reading it fails closed, while
+ # another process would report the live turn as interrupted.
+ transport = source_generation.runtime.transport
cursor: Optional[str] = None
seen_cursors: set[str] = set()
@@ -3095,6 +3809,7 @@ class CodexAgent(BaseAgent):
git_path_state, git_path_managed = self._inject_caller_env_config(
resume_params,
request,
+ self._process_environment(transport),
)
model_provider = await self._resolve_resume_model_provider_override(
transport,
@@ -3104,6 +3819,13 @@ class CodexAgent(BaseAgent):
)
if model_provider:
resume_params["modelProvider"] = model_provider
+ holder = self._generation_running(transport)
+ if holder is not None:
+ # A resume whose answer is lost may still load the thread
+ # there. Claim it first, so it is released there before any
+ # other process resumes it; releasing a thread that never
+ # loaded is a cheap ``notLoaded``.
+ self._bind_session_thread(holder, request.base_session_id, persisted)
resp = await transport.send_request(
"thread/resume",
resume_params,
@@ -3351,7 +4073,7 @@ class CodexAgent(BaseAgent):
# Refresh caller environment and git path after prompt rendering,
# without rendering the prompt a second time.
caller_env = self._caller_env_for_request(request)
- git_path_state = self._git_path_state_for_request(request)
+ git_path_state = self._git_path_state_for_request(request, self._process_environment(transport))
if not hasattr(self, "_thread_caller_env_configs"):
self._thread_caller_env_configs = {}
@@ -3376,6 +4098,7 @@ class CodexAgent(BaseAgent):
git_path_state, git_path_managed = self._inject_caller_env_config(
resume_params,
request,
+ self._process_environment(transport),
force_path=git_path_managed,
)
model_provider = await self._resolve_resume_model_provider_override(transport, request, thread_id)
@@ -4214,9 +4937,14 @@ class CodexAgent(BaseAgent):
raise RuntimeError("Codex turn/start returned no turn id")
turn_state = self._turn_registry.finalize_turn_start_response(turn_id, request)
+ generation = self._generation_for_session(request.base_session_id)
self._mark_runtime_turn_started(
getattr(request, "context", None),
- activation_identity=self._transport_activation_identity(transport),
+ activation_identity=(
+ generation.runtime.activation
+ if generation is not None and generation.runtime.transport is transport
+ else None
+ ),
)
bind_generated_image_snapshot = getattr(event_handler, "bind_generated_image_snapshot", None)
if callable(bind_generated_image_snapshot):
@@ -4290,8 +5018,19 @@ class CodexAgent(BaseAgent):
# Callback handlers (wired to transport)
# ------------------------------------------------------------------
- async def _on_notification(self, method: str, params: Dict[str, Any]) -> None:
- """Route a server notification to the event handler."""
+ async def _on_notification(
+ self,
+ method: str,
+ params: Dict[str, Any],
+ *,
+ runtime: _CodexRuntime | None = None,
+ ) -> None:
+ """Route a server notification from one app-server to the event handler."""
+ if runtime is not None and method == "thread/closed":
+ released = runtime.released_threads.get(self._extract_thread_id(params))
+ if released is not None:
+ released.set()
+ return
if self._handle_connection_probe_notification(method, params):
return
request = self._find_request_for_notification(method, params)
@@ -4305,11 +5044,27 @@ class CodexAgent(BaseAgent):
turn_id,
)
return
+ if runtime is not None and not self._extract_turn_id(params):
+ # Turn ids are unique across processes, so only thread-scoped
+ # events can reach the wrong turn: a Session that moved on must not
+ # receive late events from the generation it left.
+ generation = self._session_generations.get(request.base_session_id)
+ if generation is not None and generation.runtime is not runtime:
+ logger.debug(
+ "Dropping Codex notification %s from a previous generation of session %s",
+ method,
+ request.base_session_id,
+ )
+ return
if self._notification_is_real_progress(method):
- self._touch_transport_activity(request.working_path)
+ if runtime is not None:
+ self._touch_runtime(runtime)
self._touch_session_activity(request.base_session_id)
await self._event_handler.handle_notification(method, params, request)
+ if runtime is not None and method == "turn/completed":
+ # A turn that ends on a retiring generation may be its last work.
+ self._schedule_reap(runtime.cwd)
def _handle_connection_probe_notification(
self,
@@ -4476,11 +5231,6 @@ class CodexAgent(BaseAgent):
finally:
request.ack_message_id = None
- def _cwd_inodes(self) -> Dict[str, Optional[int]]:
- if not hasattr(self, "_transport_cwd_inodes"):
- self._transport_cwd_inodes = {}
- return self._transport_cwd_inodes
-
@staticmethod
def _cwd_inode(cwd: str) -> Optional[int]:
try:
@@ -4488,11 +5238,10 @@ class CodexAgent(BaseAgent):
except OSError:
return None
- def _touch_transport_activity(self, cwd: str) -> None:
- if not hasattr(self, "_transport_last_activity"):
- self._transport_last_activity = {}
- if cwd:
- self._transport_last_activity[cwd] = time.monotonic()
+ @staticmethod
+ def _touch_runtime(runtime: _CodexRuntime | None) -> None:
+ if runtime is not None:
+ runtime.last_activity = time.monotonic()
def _touch_session_activity(self, base_session_id: str) -> None:
if not hasattr(self, "_session_last_activity"):
@@ -4510,12 +5259,7 @@ 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
- has_pending_turn_start = getattr(self._turn_registry, "has_pending_turn_start", None)
- if callable(has_pending_turn_start) and has_pending_turn_start(base_session_id):
- return True
- return False
+ return any(
+ self._session_has_turn(base_session_id)
+ for base_session_id in self._session_mgr.sessions_for_cwd(cwd)
+ )
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index ebca566a5..931ea9886 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -9,7 +9,7 @@ import os
import signal
from asyncio.subprocess import Process
from contextlib import nullcontext
-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional
+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Mapping, Optional
from core.process_diagnostics import log_process_snapshot, process_identity
from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
@@ -59,6 +59,10 @@ AVIBE_APP_SERVER_CONFIG_OVERRIDES = (
"features.tool_suggest=false",
"features.workspace_dependencies=false",
"skills.include_instructions=false",
+ # Unload a thread as soon as Avibe unsubscribes from it while it is idle.
+ # That releases Codex's cross-process thread writer lock, so another
+ # app-server generation for the same directory can resume the thread.
+ "thread_unload_delay_secs=0",
# Host-owned questions. Codex 0.153.2 gates the synchronous tool only;
# asynchronous exposure still needs upstream support (openai/codex#43821).
"tools.experimental_request_user_input.enabled=false",
@@ -109,7 +113,6 @@ class CodexTransport:
extra_args: list[str] | None = None,
runtime_args: list[str] | None = None,
runtime_env: dict[str, str] | None = None,
- runtime_fingerprint: str = "direct",
model_hub_catalog: CodexHubCatalog | None = None,
) -> None:
self._binary = binary
@@ -117,7 +120,6 @@ class CodexTransport:
self._extra_args = extra_args or []
self._runtime_args = runtime_args or []
self._runtime_env = runtime_env
- self.runtime_fingerprint = runtime_fingerprint
self._model_hub_catalog = model_hub_catalog.retain() if model_hub_catalog is not None else None
self._catalog_required = model_hub_catalog is not None
self._catalog_exit_task: asyncio.Task[None] | None = None
@@ -331,6 +333,11 @@ class CodexTransport:
return False
return True
+ @property
+ def runtime_env(self) -> Mapping[str, str] | None:
+ """The environment the process runs with; None inherits this process's."""
+ return self._runtime_env
+
@property
def is_initialized(self) -> bool:
return self._initialized and self.is_alive
@@ -396,11 +403,14 @@ class CodexTransport:
try:
await self._write_message(msg)
- except Exception:
+ except BaseException as exc:
# Clean up the pending future so it doesn't leak
self._pending.pop(req_id, None)
if not fut.done():
- fut.set_exception(ConnectionError(f"Failed to send {method}"))
+ if isinstance(exc, Exception):
+ fut.set_exception(ConnectionError(f"Failed to send {method}"))
+ else:
+ fut.cancel()
raise
try:
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index 9f6c03b0d..ccc77c08d 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -246,6 +246,7 @@ async def resolve_model_hub_launch(
*,
process_scope: Optional[str] = None,
context: Any = None,
+ config: Any = None,
) -> ModelHubLaunch:
router = getattr(controller, "model_hub_runtime", None)
resolver = getattr(router, "resolve", None)
@@ -253,12 +254,14 @@ async def resolve_model_hub_launch(
manager = getattr(controller, "session_turns", None)
turn_lookup = getattr(manager, "model_hub_turn_id_for_task", None)
turn_id = turn_lookup() if callable(turn_lookup) else None
+ snapshot = {"config": config} if config is not None else {}
try:
return await resolver(
backend,
requested_model,
process_scope=process_scope,
turn_id=turn_id,
+ **snapshot,
)
except ModelHubError as exc:
failure = _localized_launch_error(
@@ -284,12 +287,14 @@ async def resolve_opencode_overlay_launch(
overlay: OpenCodeOverlay | None,
*,
context: Any = None,
+ config: Any = None,
) -> ModelHubLaunch:
router = getattr(controller, "model_hub_runtime", None)
resolver = getattr(router, "resolve_opencode_overlay_launch", None)
if overlay is not None and callable(resolver):
+ snapshot = {"config": config} if config is not None else {}
try:
- return await resolver(overlay, requested_model)
+ return await resolver(overlay, requested_model, **snapshot)
except ModelHubError as exc:
failure = _localized_launch_error(
controller,
@@ -300,7 +305,7 @@ async def resolve_opencode_overlay_launch(
_hold_unrunnable_input(context, failure)
raise failure from None
return await resolve_model_hub_launch(
- controller, "opencode", requested_model, context=context,
+ controller, "opencode", requested_model, context=context, config=config,
)
@@ -928,8 +933,18 @@ class ModelHubRuntimeRouter:
terminal_turn_id=terminal_turn_id,
)
- def turn_mode(self, backend: BackendName) -> TurnMode:
- return cast(TurnMode, self.service.store.load().agents[backend].mode)
+ def snapshot(self) -> ModelHubConfig:
+ """Load the configuration one turn resolves and launches against.
+
+ A turn that passes this snapshot to every call below derives its launch
+ and its runtime's launch inputs from one load, so a concurrent catalog
+ change cannot split them.
+ """
+ return self.service.store.load()
+
+ def turn_mode(self, backend: BackendName, *, config: ModelHubConfig | None = None) -> TurnMode:
+ config = config if config is not None else self.service.store.load()
+ return cast(TurnMode, config.agents[backend].mode)
async def resolve(
self,
@@ -938,9 +953,10 @@ class ModelHubRuntimeRouter:
*,
process_scope: Optional[str] = None,
turn_id: Optional[str] = None,
+ config: ModelHubConfig | None = None,
) -> ModelHubLaunch:
requested_model = str(requested_model or "").strip()
- config = self.service.store.load()
+ config = config if config is not None else self.service.store.load()
config, resolution = await self._resolve_turn(
config,
backend,
@@ -1074,15 +1090,18 @@ class ModelHubRuntimeRouter:
self,
overlay: OpenCodeOverlay,
requested_model: str,
+ *,
+ config: ModelHubConfig | None = None,
) -> ModelHubLaunch:
"""Activate the exact source snapshot used to build an overlay."""
+ snapshot = config
launch = next(
(item for item in overlay.launches if item.requested_model == requested_model),
None,
)
if launch is None:
- config = self.service.store.load()
+ config = snapshot if snapshot is not None else self.service.store.load()
if all(model.id != requested_model for model in config.agents["opencode"].models):
# The overlay holds launches only for listed rows.
raise self._no_candidate_error(
@@ -1106,7 +1125,7 @@ class ModelHubRuntimeRouter:
turn_id=None,
)
raise ModelHubError("mapping_target_unavailable", status=409)
- config = self.service.store.load()
+ config = snapshot if snapshot is not None else self.service.store.load()
self._emit_transition(launch, config)
return launch
@@ -1174,8 +1193,12 @@ class ModelHubRuntimeRouter:
setattr(context, _CONTEXT_FAILURE_RECORDED_ATTR, True)
return persisted
- async def prepare_opencode_overlay(self) -> OpenCodeOverlay | None:
- config = self.service.store.load()
+ async def prepare_opencode_overlay(
+ self,
+ *,
+ config: ModelHubConfig | None = None,
+ ) -> OpenCodeOverlay | None:
+ config = config if config is not None else self.service.store.load()
agent = config.agents["opencode"]
if agent.mode == "direct":
return None
diff --git a/modules/agents/opencode/__init__.py b/modules/agents/opencode/__init__.py
index 9e4dbfe10..d29b03a7b 100644
--- a/modules/agents/opencode/__init__.py
+++ b/modules/agents/opencode/__init__.py
@@ -17,8 +17,7 @@ from .utils import (
__all__ = [
"OpenCodeAgent",
- "OpenCodeModelHubOverlayRequiredError",
- "OpenCodeServerManager",
+ "OpenCodeServerClient",
"build_claude_reasoning_options",
"build_codex_reasoning_options",
"build_reasoning_effort_options",
@@ -33,19 +32,16 @@ def __getattr__(name: str):
return OpenCodeAgent
if name in {
- "OpenCodeModelHubOverlayRequiredError",
- "OpenCodeServerManager",
+ "OpenCodeServerClient",
"project_opencode_model_hub_models",
}:
from .server import (
- OpenCodeModelHubOverlayRequiredError,
- OpenCodeServerManager,
+ OpenCodeServerClient,
project_opencode_model_hub_models,
)
return {
- "OpenCodeModelHubOverlayRequiredError": OpenCodeModelHubOverlayRequiredError,
- "OpenCodeServerManager": OpenCodeServerManager,
+ "OpenCodeServerClient": OpenCodeServerClient,
"project_opencode_model_hub_models": project_opencode_model_hub_models,
}[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 3cce4d671..db062ab13 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -1,7 +1,8 @@
"""OpenCode agent implementation (coordinator).
Most heavy lifting lives in:
-- server.py: OpenCodeServerManager
+- server.py: OpenCode generations (processes) and their HTTP API
+- client_manager.py: the OpenCode instance's generation set and launch specs
- poll_loop.py: unified poll loop
- session.py: session mapping + concurrency guards
"""
@@ -9,12 +10,13 @@ Most heavy lifting lives in:
from __future__ import annotations
import asyncio
+from contextlib import asynccontextmanager
import logging
import os
import secrets
import time
from dataclasses import dataclass, field
-from typing import Any, Dict, Optional
+from typing import Any, AsyncIterator, Dict, Optional
import aiohttp
@@ -46,6 +48,7 @@ from core.resource_governance import (
governor_from_controller,
pids_failure_labels,
)
+from core.run_settlement import SETTLED_BY_BACKEND_REFRESH
from core.runtime_activation import RuntimeActivationIdentity
from core.runtime_ownership import (
RuntimeResourceTarget,
@@ -65,6 +68,7 @@ from core.system_prompt_injection import (
get_enabled_agents_for_prompt,
)
from modules.agents.base import AgentRequest, BaseAgent, message_with_files
+from modules.agents.runtime_generations import RuntimeBinding, RuntimeUnitStopping
from modules.agents.model_hub import (
ModelHubLaunch,
OpenCodeOverlay,
@@ -84,7 +88,7 @@ from .caller_context import (
refresh_session as refresh_caller_context_session,
unbind_session as unbind_caller_context_session,
)
-from .client_manager import OpenCodeClientManager
+from .client_manager import OpenCodeRuntime
from .message_processor import OpenCodeMessageProcessorMixin
from .poll_loop import (
OpenCodePollLoop,
@@ -94,12 +98,13 @@ from .poll_loop import (
)
from .server import (
OpenCodeDirectoryBootstrapTimeoutError,
- OpenCodeManagedPolicyRefreshPendingError,
- OpenCodeModelHubOverlayRequiredError,
+ OpenCodeGeneration,
+ OpenCodeLaunchSpec,
+ StopOutcome,
OpenCodePromptRejectedError,
OpenCodeRuntimeConfigInvalidError,
- OpenCodeServerManager,
native_part_id_for_attempt,
+ other_runtimes_live_records,
)
from .session import (
OpenCodeResumeUnavailableError,
@@ -112,6 +117,9 @@ logger = logging.getLogger(__name__)
_STEERING_SNAPSHOT_KEY = "opencode_native_steering"
_MODEL_HUB_DISPLAY_MODEL_KEY = "model_hub_display_model"
_CALLER_CONTEXT_ENV_SNAPSHOT_KEY = "opencode_caller_context_env"
+# The generation whose process runs a polled native turn; polls persisted by
+# releases before generations lack it.
+_GENERATION_SNAPSHOT_KEY = "opencode_generation_id"
_MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY = "opencode_managed_skill_project_base"
_MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY = "opencode_managed_skill_builtin_snapshot"
_STATUS_RECONCILIATION_FAILURE_LIMIT = 3
@@ -147,6 +155,55 @@ def _binding_path_kwargs(path: str | None) -> dict[str, str]:
return {"path": path} if path else {}
+def _poll_generation_id(poll_info: Any) -> str | None:
+ snapshot = getattr(poll_info, "processing_indicator", None)
+ value = snapshot.get(_GENERATION_SNAPSHOT_KEY) if isinstance(snapshot, dict) else None
+ return value if isinstance(value, str) and value else None
+
+
+class _RestoredPollUnrecorded(RuntimeError):
+ """A restored poll binds elsewhere than it names, and that was not recorded."""
+
+
+@dataclass
+class _RestoredPollHandoff:
+ """A poll task a restore started, waiting for the restore to publish it."""
+
+ ready: asyncio.Future[bool]
+ published: asyncio.Event
+ poll_info: Any
+ task: asyncio.Task
+
+
+def _poll_runs_in(poll_info: Any, records: list[dict[str, Any]]) -> bool:
+ """Whether one of ``records`` names the process executing a poll's run.
+
+ That is the generation the poll names; a poll from before generations
+ names none, and the process marking its native session as running does.
+ """
+
+ generation_id = _poll_generation_id(poll_info)
+ if generation_id is not None:
+ return any(record.get("generation_id") == generation_id for record in records)
+ return any(
+ isinstance(record.get("active_run_sessions"), list)
+ and poll_info.opencode_session_id in record["active_run_sessions"]
+ for record in records
+ )
+
+
+def _log_lifecycle_failure(task: asyncio.Task) -> None:
+ if not task.cancelled() and task.exception() is not None:
+ logger.error("OpenCode generation lifecycle step failed", exc_info=task.exception())
+
+
+@dataclass
+class _TurnGeneration:
+ """The binding that keeps a turn's generation alive until the turn settles."""
+
+ binding: RuntimeBinding | None = None
+
+
def _task_is_stopping(task: asyncio.Task) -> bool:
cancelling = getattr(task, "cancelling", None)
return task.done() or bool(cancelling and cancelling())
@@ -180,6 +237,8 @@ class _OpenCodeSteerState:
status_reconciliation_failures: int = 0
terminal_status_failure_messages: list[Dict[str, Any]] | None = None
terminal_status_failure_generation: int = 0
+ # The generation whose process runs this native turn.
+ generation: Any = None
@property
def native_turn_id(self) -> str:
@@ -191,7 +250,7 @@ class _SteeringAwareOpenCodeServer:
def __init__(
self,
- server: OpenCodeServerManager,
+ server: OpenCodeGeneration,
state: _OpenCodeSteerState,
) -> None:
self._server = server
@@ -739,21 +798,22 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"""OpenCode Server API integration via HTTP."""
name = "opencode"
+ # How a forced stop settles the work bound to its process: a runtime update,
+ # unless a disable's shutdown named its own reason.
+ _forced_stop_reason: str = SETTLED_BY_BACKEND_REFRESH
def __init__(self, controller, opencode_config):
super().__init__(controller)
self.opencode_config = opencode_config
- self._client_manager = OpenCodeClientManager(opencode_config)
- self._client_manager.set_resource_governor(governor_from_controller(controller))
- model_hub_runtime = getattr(controller, "model_hub_runtime", None)
- prepare_overlay = getattr(
- model_hub_runtime,
- "prepare_opencode_overlay",
- None,
+ self._runtime = OpenCodeRuntime(
+ opencode_config,
+ resource_governor=governor_from_controller(controller),
)
- if callable(prepare_overlay):
- self._client_manager.set_model_hub_overlay_preparer(prepare_overlay)
+ self._runtime.durable_poll_generations = self._durable_poll_generations
+ self._runtime.on_generation_ready = self._attach_generation_activation
+ self._runtime.on_generation_stopping = self._on_generation_stopping
+ self._runtime.holds_activities = self._generation_holds_activities
self._session_manager = OpenCodeSessionManager(self.settings_manager, self.name)
self._poll_loop = OpenCodePollLoop(self)
@@ -770,19 +830,135 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# their own cleanup. A forced refresh never cancels these again, and a
# restored poll it interrupted retires its own durable record.
self._settling_request_tasks: set[asyncio.Task] = set()
+ # The generation each running native turn is bound to, by base session.
+ self._session_generations: Dict[str, OpenCodeGeneration] = {}
+ # Binding releases and reaps run apart from the turn that ends them, so
+ # no turn's cleanup waits on another generation's start or stop.
+ self._lifecycle_tasks: set[asyncio.Task] = set()
+ self._resource_failures: Dict[tuple[Any, ...], AgentResourceFailure | None] = {}
+ # One restore at a time: an enable-triggered restore can overlap an
+ # IM-ready or reconnect one, and a poll is claimed only at its handoff.
+ self._restore_lock = asyncio.Lock()
+ # Durable polls a restore left for a later one; the sweep restores again.
+ self._polls_awaiting_restore: set[str] = set()
+
+ def _durable_poll_generations(self) -> Dict[str, Optional[str]]:
+ return {
+ session_id: _poll_generation_id(poll_info)
+ for session_id, poll_info in self.sessions.get_all_active_polls().items()
+ }
- async def _get_server(self) -> OpenCodeServerManager:
- current_task = asyncio.current_task()
- if current_task is not None:
- restored_server = self._restored_poll_servers.get(current_task)
- if restored_server is not None:
- return restored_server
- server = await self._client_manager.get_server()
- server.set_active_poll_session_ids_provider(
- lambda: set(self.sessions.get_all_active_polls())
+ async def _prepare_launch(
+ self,
+ context: Any = None,
+ ) -> tuple[Any, OpenCodeOverlay | None, OpenCodeLaunchSpec, Any]:
+ """Snapshot every launch input in one step, then derive the launch from it.
+
+ The Model Hub snapshot and the runtime's own inputs (CLI path, renewal
+ epoch, binary, config, and credential identities) are read together,
+ before the first await, with the ``agents.opencode`` settings they came
+ from. The overlay and the spec derive from that snapshot only, and the
+ turn takes its per-turn settings from the returned settings, so a save
+ or renewal that lands meanwhile changes nothing about this turn; the
+ next one moves.
+ """
+
+ model_hub_runtime = getattr(self.controller, "model_hub_runtime", None)
+ snapshot = getattr(model_hub_runtime, "snapshot", None)
+ config = snapshot() if callable(snapshot) else None
+ inputs = self._runtime.launch_inputs()
+ snapshot_kwargs = {"config": config} if config is not None else {}
+ turn_mode = getattr(model_hub_runtime, "turn_mode", None)
+ if context is not None and callable(turn_mode):
+ bind_turn_mode(context, turn_mode("opencode", **snapshot_kwargs))
+ prepare_overlay = getattr(model_hub_runtime, "prepare_opencode_overlay", None)
+ overlay = await prepare_overlay(**snapshot_kwargs) if callable(prepare_overlay) else None
+ return config, overlay, await self._runtime.launch_spec(overlay, inputs), inputs.settings
+
+ async def _ensure_adopted(self) -> None:
+ """Adopt a previous controller's generations against the current spec."""
+
+ if self._runtime.adopted:
+ return
+ try:
+ _config, _overlay, current_spec, _settings = await self._prepare_launch()
+ except Exception:
+ # Without a spec nothing can keep serving; every adopted generation
+ # retires and stops once its restored work drains.
+ logger.warning("Adopting OpenCode generations without the current launch spec", exc_info=True)
+ current_spec = None
+ await self._runtime.ensure_adopted(current_spec)
+
+ @asynccontextmanager
+ async def _outside_turn_admission(self) -> AsyncIterator[None]:
+ """Admit work outside a turn the way a turn is admitted.
+
+ A native migration drains the backend, and work outside a turn waits
+ for it to end. Admitted work counts as active until it is bound, so
+ the migration never overlaps the start of an OpenCode process.
+ """
+
+ agent_service = getattr(self.controller, "agent_service", None)
+ is_ready = getattr(agent_service, "is_backend_ready", None)
+ while True:
+ # Counted before the check, in one step with it, so a drain that
+ # begins later sees this work.
+ self._runtime.outside_turn_acquisitions += 1
+ if not callable(is_ready) or is_ready(self.name):
+ break
+ self._runtime.outside_turn_acquisitions -= 1
+ await agent_service.wait_backend_ready(self.name)
+ try:
+ yield
+ finally:
+ self._runtime.outside_turn_acquisitions -= 1
+
+ @asynccontextmanager
+ async def current_server(self) -> AsyncIterator[OpenCodeGeneration]:
+ """Pin the current generation for one controller-side request sequence."""
+
+ async with self._outside_turn_admission():
+ _config, _overlay, spec, _settings = await self._prepare_launch()
+ binding = await self._runtime.acquire(spec)
+ try:
+ yield binding.generation.runtime
+ finally:
+ await self._release_binding(binding)
+
+ async def lease_generation(self, purpose: str, *, ttl_seconds: float) -> Dict[str, Any]:
+ """Pin the current generation for a caller outside the controller."""
+
+ async with self._outside_turn_admission():
+ _config, _overlay, spec, _settings = await self._prepare_launch()
+ lease_id, generation = await self._runtime.lease(spec, ttl_seconds)
+ logger.info(
+ "Leased OpenCode generation %s for %s (%s)",
+ generation.generation_id,
+ purpose,
+ lease_id,
)
- self._attach_server_activation(server)
- return server
+ return {"lease_id": lease_id, "server": generation}
+
+ async def release_generation_lease(self, lease_id: str) -> bool:
+ # After a controller restart the lease lives only in its generation's
+ # record until adoption re-holds it; release it there, not nowhere.
+ await self._ensure_adopted()
+ return await self._runtime.release_lease(lease_id)
+
+ def _track_lifecycle(self, operation: Any) -> None:
+ task = asyncio.get_running_loop().create_task(operation)
+ self._lifecycle_tasks.add(task)
+ task.add_done_callback(self._lifecycle_tasks.discard)
+ task.add_done_callback(_log_lifecycle_failure)
+
+ async def _release_binding(self, binding: RuntimeBinding | None) -> None:
+ # Release is bookkeeping only; the set stops a drained generation in
+ # its own reconciler, so no turn's cleanup waits on a teardown.
+ if binding is not None:
+ await binding.release()
+
+ def _schedule_reap(self) -> None:
+ self._track_lifecycle(self._runtime.reap())
async def _maintain_caller_context_binding(
self,
@@ -877,75 +1053,77 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
return True
- @staticmethod
- def _server_activation_identity(
- server: OpenCodeServerManager | None,
- ) -> RuntimeActivationIdentity | None:
- identity = getattr(server, "_vibe_runtime_activation_identity", None)
- return identity if isinstance(identity, RuntimeActivationIdentity) else None
-
- def _attach_server_activation(
- self,
- server: OpenCodeServerManager,
- ) -> RuntimeActivationIdentity | None:
+ def _attach_generation_activation(self, generation: OpenCodeGeneration) -> None:
registry = getattr(getattr(self, "controller", None), "runtime_activation", None)
- if registry is None:
- return None
- existing = self._server_activation_identity(server)
- if existing is not None and registry.is_current(existing):
- return existing
- identity = registry.attach(self.name, server.base_url)
- setattr(server, "_vibe_runtime_activation_identity", identity)
- set_retire = getattr(server, "set_runtime_activation_retire", None)
- if callable(set_retire):
- set_retire(
- lambda force=False, native_turns_drained=False: self._retire_server_activation(
- server,
- force=force,
- native_turns_drained=native_turns_drained,
- )
- )
- return identity
+ if registry is not None:
+ generation.identity = registry.attach(self.name, f"opencode:{generation.generation_id}")
- def _retire_server_activation(
- self,
- server: OpenCodeServerManager,
- *,
- force: bool = False,
- native_turns_drained: bool = False,
- ) -> bool:
+ def _retire_generation_activation(self, generation: OpenCodeGeneration) -> None:
registry = getattr(getattr(self, "controller", None), "runtime_activation", None)
- identity = self._server_activation_identity(server)
- if registry is None or identity is None:
- return True
- if not registry.is_current(identity):
- return True
+ identity = generation.identity
+ if registry is not None and isinstance(identity, RuntimeActivationIdentity):
+ # A turn never needs one particular unbound generation, and bound
+ # work keeps a generation from stopping unless it is forced. No
+ # commit fenced by this identity is lost when it retires.
+ registry.retire_if_current(identity, lambda: True)
+
+ def _generation_holds_activities(self, generation: OpenCodeGeneration) -> bool:
+ service = getattr(self.controller, "agent_service", None)
+ holds = getattr(service, "activation_has_activities", None)
+ identity = generation.identity if isinstance(generation.identity, RuntimeActivationIdentity) else None
+ return bool(callable(holds) and holds(self.name, identity))
+
+ async def _on_generation_stopping(self, generation: OpenCodeGeneration, force: bool) -> None:
+ self._retire_generation_activation(generation)
+ if force:
+ await self._interrupt_generation_work(generation)
+
+ async def _interrupt_generation_work(self, generation: OpenCodeGeneration) -> None:
+ """Settle every turn and Activity of a generation being force-stopped.
+
+ Only this agent's bindings name the sessions, so a disabled agent's
+ stop never reaches a re-enabled agent's work. A stop is retried while
+ its process survives, and a retry settles only the sessions no earlier
+ attempt settled: the core settles turns by session, and a settled
+ session's next turn may already run on the re-enabled agent. Every
+ Activity started under this generation's activation settles too, bound
+ session or not: an Activity can outlive its foreground turn.
+ """
- def final_predicate() -> bool:
- if force:
- return True
- snapshots = self.runtime_ownership_snapshots()
- return bool(
- snapshots is not None
- and all(
- not (
- snapshot.blocks_transport_replacement_after_turn_drain
- if native_turns_drained
- else snapshot.blocks_transport_replacement
- )
- for snapshot in snapshots
- )
+ sessions = {
+ base_session_id
+ for base_session_id, bound in self._session_generations.items()
+ if bound is generation
+ }
+ logger.warning(
+ "Force-stopping OpenCode generation %s interrupts %s session(s)",
+ generation.generation_id,
+ len(sessions),
+ )
+ unsettled = sessions - generation.interrupted_sessions
+ force_end = getattr(getattr(self.controller, "agent_service", None), "force_end_runtime_work", None)
+ if callable(force_end):
+ await force_end(
+ self.name,
+ base_session_ids=unsettled,
+ activation_identities={generation.identity},
+ reason=self._forced_stop_reason,
+ agent=self,
)
+ generation.interrupted_sessions |= unsettled
+ if sessions:
+ await self._cancel_active_requests(base_session_ids=sessions)
- return bool(registry.retire_if_current(identity, final_predicate))
+ def _bound_generation(self, base_session_id: str | None) -> OpenCodeGeneration | None:
+ return self._session_generations.get(str(base_session_id or ""))
def runtime_activation_identity_for_request(
self,
request: Any,
) -> RuntimeActivationIdentity | None:
- del request
- server = self._client_manager._server_manager
- return self._attach_server_activation(server) if server is not None else None
+ generation = self._bound_generation(getattr(request, "base_session_id", None)) or self._runtime.current()
+ identity = getattr(generation, "identity", None)
+ return identity if isinstance(identity, RuntimeActivationIdentity) else None
def runtime_activation_identity_for_session_binding(
self,
@@ -960,8 +1138,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
active = self._session_manager.get_request_session(normalized_anchor)
if active is not None and str(active[1] or "").strip() != normalized_workdir:
raise ValueError("OpenCode Session binding changed workdir")
- server = self._client_manager._server_manager
- return self._attach_server_activation(server) if server is not None else None
+ generation = self._bound_generation(normalized_anchor) or self._runtime.current()
+ identity = getattr(generation, "identity", None)
+ return identity if isinstance(identity, RuntimeActivationIdentity) else None
def _idle_reconciliation_message(
self,
@@ -986,49 +1165,24 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
def _resource_failure_for_server(
self,
- server: OpenCodeServerManager | None,
+ server: Any,
) -> AgentResourceFailure | None:
- process = getattr(server, "_process", None)
- if process is not None:
- if getattr(process, "returncode", None) is None:
- return None
- pid = getattr(process, "pid", None)
- generation = ("process", process)
+ """Attribute a generation's own exit to shared resource pressure, once."""
+
+ observed_exit = getattr(server, "observed_exit_pid", None)
+ if callable(observed_exit):
+ pid = observed_exit()
+ key: tuple[Any, ...] = ("generation", getattr(server, "generation_id", None), pid)
else:
- pid = getattr(server, "_last_start_failure_pid", None)
- if pid is not None:
- generation = (
- "startup",
- getattr(server, "_start_attempt_generation", 0),
- pid,
- )
- else:
- observed_exit = getattr(server, "observed_runtime_exit_pid", None)
- if callable(observed_exit):
- pid = observed_exit()
- generation = (
- "adopted",
- getattr(server, "_runtime_generation_token", None),
- pid,
- )
+ # The turn has no generation: the start itself failed.
+ pid = self._runtime.last_start_failure_pid
+ key = ("startup", self._runtime.start_failures, pid)
if not isinstance(pid, int) or pid <= 0:
return None
- cached_generation = getattr(server, "_vibe_resource_failure_generation", None)
- same_generation = (
- cached_generation is not None
- and cached_generation[0] == generation[0]
- and (
- cached_generation[1] is process
- if generation[0] == "process"
- else cached_generation == generation
- )
- )
- if same_generation:
- return getattr(server, "_vibe_resource_failure", None)
+ if key in self._resource_failures:
+ return self._resource_failures[key]
failure = observe_agent_resource_pressure(self.controller)
- if server is not None:
- setattr(server, "_vibe_resource_failure_generation", generation)
- setattr(server, "_vibe_resource_failure", failure)
+ self._resource_failures[key] = failure
if failure is not None:
logger.error(
"OpenCode server exited while the shared Agent cgroup reported resource pressure: %s",
@@ -1060,45 +1214,55 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
*,
resource_failure: AgentResourceFailure | None = None,
) -> str:
- localized_key = None
- if isinstance(error, OpenCodeModelHubOverlayRequiredError):
- localized_key = "error.opencodeModelHubOverlayRequired"
- elif isinstance(error, OpenCodeManagedPolicyRefreshPendingError):
- localized_key = "error.opencodePolicyRefreshPending"
- elif isinstance(error, OpenCodeRuntimeConfigInvalidError):
- localized_key = "error.opencodeRuntimeConfigInvalid"
+ language = str(
+ getattr(getattr(self.controller, "config", None), "language", "en")
+ or "en"
+ )
+ if isinstance(error, OpenCodeRuntimeConfigInvalidError):
+ message = i18n_t("error.opencodeRuntimeConfigInvalid", language)
elif isinstance(error, OpenCodeDirectoryBootstrapTimeoutError):
- localized_key = "error.opencodeDirectoryBootstrapTimeout"
- if localized_key is not None:
- language = str(
- getattr(getattr(self.controller, "config", None), "language", "en")
- or "en"
+ message = i18n_t("error.opencodeDirectoryBootstrapTimeout", language)
+ elif isinstance(error, RuntimeUnitStopping):
+ # The backend was disabled after this turn looked its agent up.
+ message = i18n_t(
+ "error.agentRuntimeRetired",
+ language,
+ agent=i18n_t("backend.opencode", language),
)
- message = i18n_t(localized_key, language)
else:
message = f"Failed to start OpenCode server: {error}"
return f"❌ {message}{self._resource_failure_suffix(resource_failure)}"
async def prepare_runtime_restart(self) -> None:
- """Adopt persisted server state before the shared drain snapshot."""
- await self._get_server()
+ """Adopt the generations a previous controller left running."""
+ await self._ensure_adopted()
async def retire_for_native_migration(self) -> None:
- server = self._client_manager._server_manager
- if server is not None:
- await server.retire_for_native_migration()
+ """Strictly stop every generation; native custody needs no OpenCode process."""
+ await self._ensure_adopted()
+ if self.runtime_has_active_turns():
+ raise RuntimeError("OpenCode runtime is busy")
+ await self._runtime.retire_all_strict()
def runtime_has_active_turns(self) -> bool:
+ # A lease is a binding: an OAuth flow or another leased sequence between
+ # its HTTP requests keeps its process in use.
+ if self._runtime.outside_turn_acquisitions or self._runtime.has_bound_work():
+ return True
if any(not task.done() for task in self._active_requests.values()):
return True
- server = self._client_manager._server_manager
- return bool(server is not None and server.runtime_has_active_turns())
+ return any(not generation.is_drained() for generation in self._runtime.generations())
def runtime_ownership_snapshots(self) -> tuple[Any, ...] | None:
- """Map the one shared OpenCode server to its exact durable identities."""
+ """Map each generation to the exact durable identities it serves.
- server = self._client_manager._server_manager
- if server is None:
+ Unbound Sessions acquire the current generation, so its target keeps
+ every backend Session in view. A retiring generation serves only the
+ Sessions bound to it.
+ """
+
+ generations = self._runtime.generations()
+ if not generations:
return ()
request_sessions = self._session_manager.list_all()
get_agent_session_id = getattr(
@@ -1130,33 +1294,38 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
fallback_route_keys=(session_key,),
)
)
- target = RuntimeResourceTarget(
- backend="opencode",
- resource_key=server.base_url,
- bindings=tuple(bindings),
- known_activity_runtime_keys=tuple(sorted(self.runtime_turn_keys())),
- known_fallback_route_keys=tuple(
- sorted(
- session_key
- for (
- _native_session_id,
- _working_path,
- session_key,
- ) in request_sessions.values()
- )
- ),
- include_all_backend_sessions=True,
- maps_all_backend_activities=True,
- maps_all_backend_fallback_runs=True,
- )
provider = getattr(self.controller, "runtime_ownership", None)
snapshot = getattr(provider, "snapshot", None)
if not callable(snapshot):
logger.error("OpenCode runtime ownership provider is unavailable")
return None
- result = snapshot(target)
- wake_runtime_ownership(self.controller, result)
- return (result,)
+ catch_all = self._runtime.current() or generations[-1]
+ results = []
+ for generation in generations:
+ serves_all = generation is catch_all
+ served = tuple(
+ binding
+ for binding in bindings
+ if serves_all or self._bound_generation(binding.session_anchor) is generation
+ )
+ target = RuntimeResourceTarget(
+ backend="opencode",
+ resource_key=f"opencode:{generation.generation_id}",
+ bindings=served,
+ known_activity_runtime_keys=tuple(
+ sorted(key for binding in served for key in binding.activity_runtime_keys)
+ ),
+ known_fallback_route_keys=tuple(
+ sorted(key for binding in served for key in binding.fallback_route_keys)
+ ),
+ include_all_backend_sessions=serves_all,
+ maps_all_backend_activities=serves_all,
+ maps_all_backend_fallback_runs=serves_all,
+ )
+ result = snapshot(target)
+ wake_runtime_ownership(self.controller, result)
+ results.append(result)
+ return tuple(results)
def record_runtime_turn_start(
self,
@@ -1168,62 +1337,92 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if request is not None:
self._session_last_activity[request.base_session_id] = time.monotonic()
+ def _adopt_runtime_config(self, opencode_config) -> None:
+ self.opencode_config = opencode_config
+ self.controller.config.opencode = opencode_config
+ self._runtime.config = opencode_config
+
+ async def renew_runtime(self, opencode_config, *, config_save: bool = False) -> None:
+ """Adopt persisted runtime config; the next turn moves to a new generation.
+
+ Nothing reloads or drains here: running turns finish on the generation
+ they started on. Every ``agents.opencode`` field is read per turn except
+ the CLI path, whose binary identity is already a launch spec input, so a
+ plain config save renews nothing. Credential flows, a manual Restart,
+ and installs can change what a process loaded without touching a file
+ the spec reads, so they renew every generation.
+ """
+ self._adopt_runtime_config(opencode_config)
+ if not config_save:
+ self._runtime.renew()
+ self._schedule_reap()
+
async def refresh_runtime_config(self, opencode_config, *, force: bool = False) -> None:
- """Reload runtime config and refresh the shared server.
+ """Adopt runtime config; ``force`` interrupts every generation's work first."""
+ if not force:
+ await self.renew_runtime(opencode_config)
+ return
+ self._adopt_runtime_config(opencode_config)
+ await self._cancel_active_requests()
+ # The interrupted work releases its bindings, and each generation
+ # stops as it drains. A new turn starts on a fresh generation.
+ await self._runtime.retire_all()
- OpenCode caches opencode.json provider/model config in the serve
- process. Prefer OpenCode's own global-config reload endpoint so
- Settings writes take effect without terminating active serve
- processes; fall back to restart for older OpenCode versions.
+ async def adopt_model_hub_catalog(self) -> None:
+ """Nothing to apply: each turn builds its overlay from one catalog snapshot.
+
+ A turn whose overlay changed gets a new generation by the same rule as
+ any other launch-input change.
"""
- if force:
- await self._cancel_active_requests()
- previous_server = await self._client_manager.reset_config(opencode_config)
- if previous_server is None:
- previous_server = await OpenCodeServerManager.get_instance_if_managed_server_exists(
- binary=self.opencode_config.binary,
- port=self.opencode_config.port,
- request_timeout_seconds=self.opencode_config.request_timeout_seconds,
- resource_governor=governor_from_controller(self.controller),
- )
- self.opencode_config = opencode_config
- self.controller.config.opencode = opencode_config
- if previous_server is not None:
- refreshed = False
- runtime_unchanged = (
- previous_server.binary == opencode_config.binary
- and previous_server.port == opencode_config.port
- and previous_server.request_timeout_seconds == opencode_config.request_timeout_seconds
- )
- refresh_global_config = getattr(previous_server, "refresh_global_config", None)
- if not force and runtime_unchanged and callable(refresh_global_config):
- try:
- refreshed = bool(await refresh_global_config())
- except Exception:
- logger.warning("OpenCode global config refresh failed; falling back to restart", exc_info=True)
- refreshed = False
- if not refreshed:
- detach = getattr(previous_server, "detach_after_deferred_refresh", None)
- if callable(detach):
- if force:
- await detach(force=True)
- else:
- await detach()
- elif hasattr(previous_server, "restart_for_auth_refresh"):
- if force:
- await previous_server.restart_for_auth_refresh(force=True)
- else:
- await previous_server.restart_for_auth_refresh()
- reload_config = getattr(previous_server, "reload_runtime_config", None)
- if callable(reload_config):
- await reload_config(
- binary=opencode_config.binary,
- port=opencode_config.port,
- request_timeout_seconds=opencode_config.request_timeout_seconds,
- )
- async def _cancel_active_requests(self) -> None:
- """Cancel every request task before a forced server teardown.
+ async def reap_runtime_generations(self) -> None:
+ await self._runtime.reap()
+ await self._restore_left_polls()
+
+ async def _restore_left_polls(self) -> None:
+ """Restore again every durable poll a restore left for a later one.
+
+ Startup restores each transport's polls once, so a poll a transient
+ failure left would otherwise wait for the next restart.
+ """
+ if not self._polls_awaiting_restore:
+ return
+ self._polls_awaiting_restore &= set(self.sessions.get_all_active_polls())
+ restore = getattr(self.controller, "restore_polls_on_ready_transports", None)
+ if self._polls_awaiting_restore and callable(restore):
+ try:
+ await restore()
+ except Exception:
+ logger.warning("Restoring the OpenCode polls an earlier restore left failed", exc_info=True)
+
+ async def shutdown_runtime(self, settle_reason: str | None = None) -> None:
+ """The backend is disabled, or the service stops: stop every process now.
+
+ A disable passes ``settle_reason``, and every forced stop settles the
+ turns and Activities bound to its process with it. The core's
+ backend-wide interrupt may have failed, or been skipped because the
+ backend was enabled again, so this is the settlement a retry relies on.
+ A previous controller's servers stop too. Admission closes, and a turn
+ that raced the disable fails with the localized retired error. Raises
+ while any process survives; a retry is safe at any point.
+ """
+ if settle_reason is not None:
+ # This agent never serves again, so every later stop of its
+ # processes, a retry's included, belongs to the same disable.
+ self._forced_stop_reason = settle_reason
+ await self._runtime.shutdown()
+
+ async def retire_current_generation(self) -> StopOutcome | None:
+ """Retire the current generation and report its confirmed outcome.
+
+ ``None`` means no generation was running. The next turn starts a fresh
+ generation either way.
+ """
+ outcomes = await self._runtime.retire_confirmed()
+ return next(iter(outcomes.values()), None)
+
+ async def _cancel_active_requests(self, base_session_ids: set[str] | None = None) -> None:
+ """Cancel request tasks before a forced generation stop.
Turn owners cancel foreground requests first; restored polls have no
owner, so without this they would poll the stopped server until their
@@ -1231,6 +1430,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"""
cancelled: list[asyncio.Task] = []
for base_session_id, task in list(self._active_requests.items()):
+ if base_session_ids is not None and base_session_id not in base_session_ids:
+ continue
# Cancelling a task that is already settling could abort the
# retirement in its cleanup.
if task.done() or task in self._settling_request_tasks:
@@ -1264,8 +1465,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
request.base_session_id,
)
req_info = self._session_manager.get_request_session(request.base_session_id)
- if req_info:
- server = await self._get_server()
+ server = self._bound_generation(request.base_session_id)
+ if req_info and server is not None:
await self._abort_active_request(
request.base_session_id,
existing_task,
@@ -1314,13 +1515,22 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
_mark(request.context)
async def _process_message(self, request: AgentRequest) -> None:
+ turn = _TurnGeneration()
+ try:
+ await self._run_turn(request, turn)
+ finally:
+ generation = turn.binding.generation.runtime if turn.binding is not None else None
+ if generation is not None and self._session_generations.get(request.base_session_id) is generation:
+ self._session_generations.pop(request.base_session_id, None)
+ await self._release_binding(turn.binding)
+
+ async def _run_turn(self, request: AgentRequest, turn: _TurnGeneration) -> None:
run_registered = False
steer_state: _OpenCodeSteerState | None = None
poll_server: _SteeringAwareOpenCodeServer | None = None
model_hub_overlay: OpenCodeOverlay | None = None
- model_hub_turn_mode: str | None = None
+ model_hub_config: Any = None
model_hub_launch: ModelHubLaunch | None = None
- model_hub_overlay_reservation: object | None = None
server = None
# Bind early: get_or_create_session_id (below) can raise BEFORE assigning
# session_id (a transient server error now that get_session raises on
@@ -1346,25 +1556,16 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
active_poll_removal_pending = True
try:
model_hub_runtime = getattr(self.controller, "model_hub_runtime", None)
- turn_mode = getattr(model_hub_runtime, "turn_mode", None)
- if callable(turn_mode):
- model_hub_turn_mode = turn_mode("opencode")
- bind_turn_mode(
- request.context,
- model_hub_turn_mode,
- )
- prepare_overlay = getattr(model_hub_runtime, "prepare_opencode_overlay", None)
- if callable(prepare_overlay):
- model_hub_overlay = await prepare_overlay()
- server = await self._get_server()
- configure_overlay = getattr(server, "configure_model_hub_overlay", None)
- if callable(configure_overlay):
- model_hub_overlay_reservation = await configure_overlay(
- model_hub_overlay
- )
- await server.ensure_running()
+ # One Model Hub load serves this turn end to end: its overlay is a
+ # launch spec input, and its model resolves from the same overlay.
+ model_hub_config, model_hub_overlay, launch_spec, opencode_settings = await self._prepare_launch(
+ request.context
+ )
+ turn.binding = await self._runtime.acquire(launch_spec)
+ server = turn.binding.generation.runtime
+ self._session_generations[request.base_session_id] = server
caller_context_binding_path = _caller_context_path_for_server(server)
- activation_identity = self._attach_server_activation(server)
+ activation_identity = getattr(server, "identity", None)
await self._session_manager.ensure_working_dir(request.working_path)
# A healthy server may still be bootstrapping this directory (about
# a minute on a fresh host). Waiting here, before the ack is deleted,
@@ -1372,18 +1573,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# its ordinary request timeout.
await server.ensure_directory_ready(request.working_path)
except asyncio.CancelledError:
- await self._finish_prestart_cancellation(
- request,
- server,
- model_hub_overlay_reservation,
- )
+ await self._finish_prestart_cancellation(request)
raise
except Exception as e:
- await self._release_model_hub_overlay_reservation(
- server,
- model_hub_overlay_reservation,
- )
- model_hub_overlay_reservation = None
resource_failure = self._resource_failure_for_server(server)
logger.error(f"Failed to start OpenCode server: {e}", exc_info=True)
await emit_backend_failure(
@@ -1404,34 +1596,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
await self._delete_ack(request)
except BaseException as error:
if isinstance(error, asyncio.CancelledError):
- await self._finish_prestart_cancellation(
- request,
- server,
- model_hub_overlay_reservation,
- )
- else:
- await self._release_model_hub_overlay_reservation(
- server,
- model_hub_overlay_reservation,
- )
- model_hub_overlay_reservation = None
+ await self._finish_prestart_cancellation(request)
raise
try:
session_id = await self._session_manager.get_or_create_session_id(request, server)
except asyncio.CancelledError:
- await self._finish_prestart_cancellation(
- request,
- server,
- model_hub_overlay_reservation,
- )
+ await self._finish_prestart_cancellation(request)
raise
except OpenCodeResumeUnavailableError as e:
- await self._release_model_hub_overlay_reservation(
- server,
- model_hub_overlay_reservation,
- )
- model_hub_overlay_reservation = None
resource_failure = resource_failure or self._resource_failure_for_server(server)
# The previous session is gone server-side — surface it as a terminal
# ERROR result (outbound chokepoint turns the dot red), don't silently
@@ -1447,11 +1620,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
await self._remove_ack_reaction(request)
return
except Exception as e:
- await self._release_model_hub_overlay_reservation(
- server,
- model_hub_overlay_reservation,
- )
- model_hub_overlay_reservation = None
resource_failure = resource_failure or self._resource_failure_for_server(server)
# A transient/transport/auth failure while acquiring the session
# (get_session now raises on non-404, Codex P2): surface it as a
@@ -1471,11 +1639,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
await self._remove_ack_reaction(request)
return
if not session_id:
- await self._release_model_hub_overlay_reservation(
- server,
- model_hub_overlay_reservation,
- )
- model_hub_overlay_reservation = None
await emit_backend_failure(
self.controller,
request.context,
@@ -1500,17 +1663,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
except BaseException as error:
if isinstance(error, asyncio.CancelledError):
- await self._finish_prestart_cancellation(
- request,
- server,
- model_hub_overlay_reservation,
- )
- else:
- await self._release_model_hub_overlay_reservation(
- server,
- model_hub_overlay_reservation,
- )
- model_hub_overlay_reservation = None
+ await self._finish_prestart_cancellation(request)
raise
try:
@@ -1536,7 +1689,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
model_str = require_agent_model(
override_model, "opencode", getattr(self.controller.config, "language", "en")
)
- opencode_cfg = getattr(self.controller.config, "opencode", None)
requested_model_str = opencode_requested_model_for_overlay(
model_str,
model_hub_overlay,
@@ -1547,6 +1699,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
requested_model_str,
model_hub_overlay,
context=request.context,
+ config=model_hub_config,
)
bind_launch(request.context, model_hub_launch)
model_str = opencode_model_for_overlay(
@@ -1558,7 +1711,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
default_provider = (
None
if model_hub_overlay is not None
- else getattr(opencode_cfg, "default_provider", None)
+ else getattr(opencode_settings, "default_provider", None)
)
model_dict = resolve_opencode_model_dict(model_str, default_provider)
if model_dict is None:
@@ -1574,7 +1727,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if not reasoning_effort:
reasoning_effort = server.get_agent_reasoning_effort_from_config(agent_to_use)
if not reasoning_effort:
- reasoning_effort = getattr(opencode_cfg, "default_reasoning_effort", None)
+ reasoning_effort = getattr(opencode_settings, "default_reasoning_effort", None)
if model_dict:
try:
model_catalog = (
@@ -1744,15 +1897,10 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
processing_indicator["model_hub_launch"] = launch_identity
if display_model_dict is not None:
processing_indicator[_MODEL_HUB_DISPLAY_MODEL_KEY] = display_model_dict
+ # A restored poll resumes on the process that runs this native turn.
+ processing_indicator[_GENERATION_SNAPSHOT_KEY] = server.generation_id
- if model_hub_overlay_reservation is None:
- await server.mark_run_active(session_id)
- else:
- await server.mark_run_active(
- session_id,
- overlay_reservation=model_hub_overlay_reservation,
- )
- model_hub_overlay_reservation = None
+ await server.mark_run_active(session_id)
run_registered = True
# Persist the complete recovery address before the first native write.
# A crash after OpenCode accepts the exact attempt part can now rebuild
@@ -1836,6 +1984,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
reasoning_effort=reasoning_effort,
system=system_prompt_injection,
baseline_message_ids=set(baseline_message_ids),
+ generation=server,
catalog_accepted=lambda: accept_catalog(
self.controller, request.context, skill_catalog_sink[0] if skill_catalog_sink else None,
backend="opencode",
@@ -1878,6 +2027,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
model_dict=model_dict,
reasoning_effort=reasoning_effort,
baseline_message_ids=baseline_message_ids,
+ settings=opencode_settings,
)
if not should_emit:
@@ -2060,28 +2210,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
caller_context_binding_session_id,
exc_info=True,
)
- await self._release_model_hub_overlay_reservation(
- server,
- model_hub_overlay_reservation,
- )
-
- @staticmethod
- async def _release_model_hub_overlay_reservation(
- server: Any,
- reservation: object | None,
- ) -> None:
- if server is None or reservation is None:
- return
- release = getattr(server, "release_model_hub_overlay_reservation", None)
- if not callable(release):
- return
- try:
- await release(reservation)
- except Exception:
- logger.warning(
- "Failed to release OpenCode Model Hub overlay reservation",
- exc_info=True,
- )
async def _retire_active_poll(
self,
@@ -2097,15 +2225,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
return False
self.sessions.remove_active_poll(session_id)
+ # A retiring generation may have just drained.
+ self._schedule_reap()
return True
- async def _finish_prestart_cancellation(
- self,
- request: AgentRequest,
- server: Any,
- reservation: object | None,
- ) -> None:
- await self._release_model_hub_overlay_reservation(server, reservation)
+ async def _finish_prestart_cancellation(self, request: AgentRequest) -> None:
await self._remove_ack_reaction(
request,
terminal_emoji=(
@@ -2173,7 +2297,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if native_turn_id != request.expected_native_turn_id:
return steer_result(SteerOutcome.NOT_ACTIVE, reason="stale_native_turn", backend=self.name)
- server = self._client_manager._server_manager
+ # Status, prompts, and aborts act on one process's in-memory run state,
+ # so a steer goes to the generation that runs this native turn.
+ server = state.generation
if server is None:
return steer_result(SteerOutcome.REFUSED, reason="runtime_unavailable", backend=self.name)
@@ -2366,7 +2492,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
reason="stale_native_session",
backend=self.name,
)
- server = self._client_manager._server_manager
+ # The part lives in the shared database, so any generation can find it.
+ server = self._bound_generation(base_session_id) or self._runtime.current()
if server is None:
return steer_result(
SteerOutcome.UNKNOWN,
@@ -2435,6 +2562,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
opencode_session_id = None
if req_info:
opencode_session_id = req_info[0]
+ # Read before the task settles: its cleanup unbinds the generation.
+ generation = self._bound_generation(request.base_session_id)
# Claimed BEFORE the abort: the request coroutine is what owns the 👀,
# and its cancellation handler is the only place that trades it for the
# ⏹️ receipt. The helper waits for any already-started steering write,
@@ -2472,11 +2601,12 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# past the handlers; a claimed intent is already gone.
self._user_stopped_sessions.discard(request.base_session_id)
- if opencode_session_id and self._active_poll_is_persisted(
+ if (
opencode_session_id
+ and generation is not None
+ and self._active_poll_is_persisted(opencode_session_id)
):
- server = await self._get_server()
- await self._retire_active_poll(server, opencode_session_id)
+ await self._retire_active_poll(generation, opencode_session_id)
# A user-initiated stop is terminal but intentional, so it carries NO
# user-facing message: a single SILENT result settles the dot to idle +
@@ -2502,6 +2632,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
req_info = self._session_manager.get_request_session(base_id)
if req_info and len(req_info) >= 3 and req_info[2] == session_key:
opencode_session_id = req_info[0]
+ generation = self._bound_generation(base_id)
if not task.done():
try:
await self._abort_active_request(base_id, task, req_info)
@@ -2513,9 +2644,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
except asyncio.CancelledError:
pass
terminated += 1
- if self._active_poll_is_persisted(opencode_session_id):
- server = await self._get_server()
- await self._retire_active_poll(server, opencode_session_id)
+ if generation is not None and self._active_poll_is_persisted(opencode_session_id):
+ await self._retire_active_poll(generation, opencode_session_id)
return terminated
async def _abort_active_request(
@@ -2526,6 +2656,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
*,
cancel_before_abort: bool = False,
) -> bool:
+ # Only the process running the native turn can abort it. Without a bound
+ # generation no native run exists yet.
+ server = self._bound_generation(base_session_id)
state = self._steering_states.get(base_session_id)
if state is not None and state.task is task:
async with state.lock:
@@ -2534,16 +2667,14 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if task.done():
return False
task.cancel()
- if request_session:
- server = await self._get_server()
+ if request_session and server is not None:
await server.abort_session(request_session[0], request_session[1])
return True
if cancel_before_abort:
if task.done():
return False
task.cancel()
- if request_session:
- server = await self._get_server()
+ if request_session and server is not None:
await server.abort_session(request_session[0], request_session[1])
return True
@@ -2596,18 +2727,56 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
return base_session_id or None
async def restore_active_polls(self, platforms: set[str] | None = None) -> int:
- """Restore active poll loops that were interrupted by vibe-remote restart."""
+ """Restore active poll loops that were interrupted by vibe-remote restart.
+
+ Callers pass only platforms whose transport can deliver. Overlapping
+ calls run one after another, so a poll whose loop one of them started
+ is seen as running by the next and never gets a second loop.
+ """
+
+ async with self._restore_lock:
+ handed_off: list[_RestoredPollHandoff] = []
+ try:
+ return await self._restore_active_polls(platforms, handed_off)
+ finally:
+ await self._abandon_unpublished_polls(handed_off)
+
+ async def _abandon_unpublished_polls(self, handed_off: list["_RestoredPollHandoff"]) -> None:
+ """Cancel every poll task a restore handed off but never published.
+ A restore that ends early, cancelled or failing, would leave each such
+ task waiting for a publication that never comes, holding its request
+ and binding. Cancelled before its poll loop starts, the task releases
+ both, and the poll stays durable for the sweep's next restore.
+ """
+
+ abandoned: list[asyncio.Task] = []
+ for handoff in handed_off:
+ if handoff.published.is_set():
+ continue
+ self._polls_awaiting_restore.add(handoff.poll_info.opencode_session_id)
+ handoff.task.cancel()
+ abandoned.append(handoff.task)
+ if abandoned:
+ # Bounded like a forced stop's cancellation: a stuck cleanup must
+ # not hold the restore lock, and each task still finishes its own.
+ await asyncio.wait(abandoned, timeout=2.0)
+
+ async def _restore_active_polls(
+ self,
+ platforms: set[str] | None,
+ restoration_results: list["_RestoredPollHandoff"],
+ ) -> int:
active_polls = self.sessions.get_all_active_polls()
if not active_polls:
logger.debug("No active polls to restore")
return 0
+ # A run another desktop Runtime's live process executes is that
+ # Runtime's: its poll is never bound, rewritten, or settled here.
+ foreign_records = await asyncio.to_thread(other_runtimes_live_records)
restored_count = 0
stale_poll_ids = []
- restoration_results: list[
- tuple[asyncio.Future[bool], asyncio.Event, Any]
- ] = []
for session_id, poll_info in active_polls.items():
poll_platform = restored_platform_from_poll_info(poll_info)
@@ -2616,6 +2785,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
existing_task = self._active_requests.get(poll_info.base_session_id)
if existing_task is not None and not existing_task.done():
continue
+ if _poll_runs_in(poll_info, foreign_records):
+ logger.info(
+ "Leaving OpenCode poll %s to the desktop Runtime whose server runs it",
+ session_id,
+ )
+ continue
+ self._polls_awaiting_restore.discard(session_id)
processing_snapshot = (
poll_info.processing_indicator
if isinstance(poll_info.processing_indicator, dict)
@@ -2631,239 +2807,263 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
else ""
)
verification_unknown = False
+ binding: RuntimeBinding | None = None
+ server: OpenCodeGeneration | None = None
try:
- server = await self._get_server()
- messages = await server.list_messages(
- session_id=poll_info.opencode_session_id,
- directory=poll_info.working_path,
- )
- except Exception as err:
- logger.warning(f"Failed to verify OpenCode session {session_id} for restoration: {err}")
- messages = []
- verification_unknown = True
-
- baseline_message_ids = set(poll_info.baseline_message_ids)
- start_attempt_part_id = (
- native_part_id_for_attempt(start_attempt_id)
- if start_attempt_id
- else ""
- )
- start_attempt_found = any(
- start_attempt_part_id
- and message.get("info", {}).get("role") == "user"
- and any(
- isinstance(part, dict)
- and str(part.get("id") or "") == start_attempt_part_id
- for part in (message.get("parts") or [])
- )
- for message in messages
- )
- has_in_progress = False
- last_assistant_finish = None
- last_completed_assistant_index = -1
- for index, message in enumerate(messages):
- info = message.get("info", {})
- if info.get("role") != "assistant":
- continue
- time_info = info.get("time") or {}
- if not time_info.get("completed"):
- has_in_progress = True
- continue
- if info.get("id") in baseline_message_ids:
- continue
- last_completed_assistant_index = index
- last_assistant_finish = info.get("finish")
-
- has_post_assistant_user = any(
- last_completed_assistant_index >= 0
- and index > last_completed_assistant_index
- and message.get("info", {}).get("role") == "user"
- and message.get("info", {}).get("id") not in baseline_message_ids
- for index, message in enumerate(messages)
- )
- reconcile_after_message_ids = (
- {
- str(message.get("info", {}).get("id"))
- for message in messages[: last_completed_assistant_index + 1]
- if message.get("info", {}).get("id")
- }
- if has_post_assistant_user
- else None
- )
- status_unknown = verification_unknown
- native_status = None
- if not verification_unknown:
try:
- native_status = await server.get_session_status(
- poll_info.opencode_session_id,
- poll_info.working_path,
+ binding = await self._bind_restored_poll(poll_info)
+ server = binding.generation.runtime
+ messages = await server.list_messages(
+ session_id=poll_info.opencode_session_id,
+ directory=poll_info.working_path,
)
+ except RuntimeUnitStopping:
+ # OpenCode was disabled while restoring: the poll stays durable
+ # for the next controller that has OpenCode enabled.
+ continue
+ except _RestoredPollUnrecorded:
+ # Still naming its old process, the poll waits for a later restore.
+ self._polls_awaiting_restore.add(session_id)
+ continue
except Exception as err:
- logger.debug("Failed to read OpenCode status while restoring %s: %s", session_id, err)
- status_unknown = True
-
- native_status_is_active = (
- native_status is not None
- and native_status.get("type") in {"busy", "retry"}
- )
- if native_status_is_active and reconcile_after_message_ids is None:
- reconcile_after_message_ids = {
- str(message.get("info", {}).get("id"))
- for message in messages[: last_completed_assistant_index + 1]
- if message.get("info", {}).get("id")
- }
- session_still_active = (
- status_unknown
- or native_status_is_active
- or has_in_progress
- or last_assistant_finish == "tool-calls"
- or has_post_assistant_user
- or start_attempt_found
- )
- if not session_still_active:
- if start_attempt_id and logical_turn_id:
+ logger.warning(f"Failed to verify OpenCode session {session_id} for restoration: {err}")
+ messages = []
+ verification_unknown = True
+
+ baseline_message_ids = set(poll_info.baseline_message_ids)
+ start_attempt_part_id = (
+ native_part_id_for_attempt(start_attempt_id)
+ if start_attempt_id
+ else ""
+ )
+ start_attempt_found = any(
+ start_attempt_part_id
+ and message.get("info", {}).get("role") == "user"
+ and any(
+ isinstance(part, dict)
+ and str(part.get("id") or "") == start_attempt_part_id
+ for part in (message.get("parts") or [])
+ )
+ for message in messages
+ )
+ has_in_progress = False
+ last_assistant_finish = None
+ last_completed_assistant_index = -1
+ for index, message in enumerate(messages):
+ info = message.get("info", {})
+ if info.get("role") != "assistant":
+ continue
+ time_info = info.get("time") or {}
+ if not time_info.get("completed"):
+ has_in_progress = True
+ continue
+ if info.get("id") in baseline_message_ids:
+ continue
+ last_completed_assistant_index = index
+ last_assistant_finish = info.get("finish")
+
+ has_post_assistant_user = any(
+ last_completed_assistant_index >= 0
+ and index > last_completed_assistant_index
+ and message.get("info", {}).get("role") == "user"
+ and message.get("info", {}).get("id") not in baseline_message_ids
+ for index, message in enumerate(messages)
+ )
+ reconcile_after_message_ids = (
+ {
+ str(message.get("info", {}).get("id"))
+ for message in messages[: last_completed_assistant_index + 1]
+ if message.get("info", {}).get("id")
+ }
+ if has_post_assistant_user
+ else None
+ )
+ status_unknown = verification_unknown
+ native_status = None
+ if not verification_unknown:
try:
- self.controller.session_turns.reconcile_start_attempt_not_written(
- logical_turn_id,
- start_attempt_id,
- backend="opencode",
+ native_status = await server.get_session_status(
+ poll_info.opencode_session_id,
+ poll_info.working_path,
)
+ except Exception as err:
+ logger.debug("Failed to read OpenCode status while restoring %s: %s", session_id, err)
+ status_unknown = True
+
+ native_status_is_active = (
+ native_status is not None
+ and native_status.get("type") in {"busy", "retry"}
+ )
+ if native_status_is_active and reconcile_after_message_ids is None:
+ reconcile_after_message_ids = {
+ str(message.get("info", {}).get("id"))
+ for message in messages[: last_completed_assistant_index + 1]
+ if message.get("info", {}).get("id")
+ }
+ session_still_active = (
+ status_unknown
+ or native_status_is_active
+ or has_in_progress
+ or last_assistant_finish == "tool-calls"
+ or has_post_assistant_user
+ or start_attempt_found
+ )
+ if not session_still_active:
+ if start_attempt_id and logical_turn_id:
+ try:
+ self.controller.session_turns.reconcile_start_attempt_not_written(
+ logical_turn_id,
+ start_attempt_id,
+ backend="opencode",
+ )
+ except Exception:
+ logger.exception(
+ "Failed to persist definitive missing OpenCode start "
+ "attempt for Turn=%s",
+ logical_turn_id,
+ )
+ await self._release_binding(binding)
+ self._polls_awaiting_restore.add(session_id)
+ continue
+ logger.info(f"OpenCode session {session_id} has completed, removing from active polls")
+ try:
+ await server.mark_run_inactive(poll_info.opencode_session_id)
except Exception:
logger.exception(
- "Failed to persist definitive missing OpenCode start "
- "attempt for Turn=%s",
- logical_turn_id,
+ "Failed to clear OpenCode run marker for session=%s; "
+ "preserving its active poll and continuing restoration",
+ poll_info.opencode_session_id,
)
+ await self._release_binding(binding)
+ self._polls_awaiting_restore.add(session_id)
continue
- logger.info(f"OpenCode session {session_id} has completed, removing from active polls")
- try:
- await server.mark_run_inactive(poll_info.opencode_session_id)
- except Exception:
- logger.exception(
- "Failed to clear OpenCode run marker for session=%s; "
- "preserving its active poll and continuing restoration",
- poll_info.opencode_session_id,
- )
+ await self._release_binding(binding)
+ await self._poll_loop.remove_restored_ack(poll_info)
+ stale_poll_ids.append(session_id)
continue
- await self._poll_loop.remove_restored_ack(poll_info)
- stale_poll_ids.append(session_id)
- continue
- logger.info(
- f"Restoring poll loop for OpenCode session {session_id} "
- f"(thread={poll_info.base_session_id}, cwd={poll_info.working_path})"
- )
+ logger.info(
+ f"Restoring poll loop for OpenCode session {session_id} "
+ f"(thread={poll_info.base_session_id}, cwd={poll_info.working_path})"
+ )
- restored_binding_token = secrets.token_hex(16)
- restored_binding_path = _caller_context_path_for_server(server)
- restored_caller_env = validated_caller_env_snapshot(
- processing_snapshot.get(_CALLER_CONTEXT_ENV_SNAPSHOT_KEY)
- )
- restored_context = restored_context_from_poll_info(poll_info)
- if (
- poll_platform == "avibe"
- and str(restored_context.user_id or "").startswith("remote:")
- ):
- # Legacy persisted polls do not carry the authorization snapshot.
- # Keep them remote-but-unprivileged instead of silently treating an
- # absent snapshot as a local caller.
- restored_caller_env.setdefault(AVIBE_SESSION_ID_ENV, poll_info.base_session_id)
- restored_caller_env.setdefault(AVIBE_CALLER_PLATFORM_ENV, "avibe")
- restored_caller_env.setdefault(
- AVIBE_CALLER_USER_ID_ENV,
- str(restored_context.user_id),
+ restored_binding_token = secrets.token_hex(16)
+ restored_binding_path = (
+ _caller_context_path_for_server(server) if server is not None else None
)
- restored_caller_env.setdefault(AVIBE_CALLER_REMOTE_ENV, "1")
- restored_project_base = processing_snapshot.get(
- _MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY
- )
- restored_project_base = (
- restored_project_base
- if isinstance(restored_project_base, str) and restored_project_base
- else None
- )
- restored_snapshot_kwargs: dict[str, str] = {}
- if _MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY in processing_snapshot:
- restored_snapshot = processing_snapshot.get(
- _MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY
+ restored_caller_env = validated_caller_env_snapshot(
+ processing_snapshot.get(_CALLER_CONTEXT_ENV_SNAPSHOT_KEY)
)
- restored_snapshot_kwargs = {
- "builtin_snapshot_id": (
- restored_snapshot.get("id", "")
- if isinstance(restored_snapshot, dict)
- and isinstance(restored_snapshot.get("id"), str)
- else ""
- ),
- "builtin_snapshot_root": (
- restored_snapshot.get("root", "")
- if isinstance(restored_snapshot, dict)
- and isinstance(restored_snapshot.get("root"), str)
- else ""
+ restored_context = restored_context_from_poll_info(poll_info)
+ if (
+ poll_platform == "avibe"
+ and str(restored_context.user_id or "").startswith("remote:")
+ ):
+ # Legacy persisted polls do not carry the authorization snapshot.
+ # Keep them remote-but-unprivileged instead of silently treating an
+ # absent snapshot as a local caller.
+ restored_caller_env.setdefault(AVIBE_SESSION_ID_ENV, poll_info.base_session_id)
+ restored_caller_env.setdefault(AVIBE_CALLER_PLATFORM_ENV, "avibe")
+ restored_caller_env.setdefault(
+ AVIBE_CALLER_USER_ID_ENV,
+ str(restored_context.user_id),
+ )
+ restored_caller_env.setdefault(AVIBE_CALLER_REMOTE_ENV, "1")
+ restored_project_base = processing_snapshot.get(
+ _MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY
+ )
+ restored_project_base = (
+ restored_project_base
+ if isinstance(restored_project_base, str) and restored_project_base
+ else None
+ )
+ restored_snapshot_kwargs: dict[str, str] = {}
+ if _MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY in processing_snapshot:
+ restored_snapshot = processing_snapshot.get(
+ _MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY
+ )
+ restored_snapshot_kwargs = {
+ "builtin_snapshot_id": (
+ restored_snapshot.get("id", "")
+ if isinstance(restored_snapshot, dict)
+ and isinstance(restored_snapshot.get("id"), str)
+ else ""
+ ),
+ "builtin_snapshot_root": (
+ restored_snapshot.get("root", "")
+ if isinstance(restored_snapshot, dict)
+ and isinstance(restored_snapshot.get("root"), str)
+ else ""
+ ),
+ }
+ restored_managed_skills_env = managed_skill_environment(
+ poll_info.working_path,
+ project_base=restored_project_base,
+ claude_cli_path=managed_skill_claude_cli_path(
+ getattr(getattr(self, "controller", None), "config", None)
),
- }
- restored_managed_skills_env = managed_skill_environment(
- poll_info.working_path,
- project_base=restored_project_base,
- claude_cli_path=managed_skill_claude_cli_path(
- getattr(getattr(self, "controller", None), "config", None)
- ),
- **restored_snapshot_kwargs,
- )
- restored_bound = False
- for attempt in range(3):
- try:
- restored_bound = await asyncio.to_thread(
- bind_caller_context_session,
+ **restored_snapshot_kwargs,
+ )
+ restored_bound = False
+ for attempt in range(3):
+ try:
+ restored_bound = await asyncio.to_thread(
+ bind_caller_context_session,
+ poll_info.opencode_session_id,
+ None,
+ base_env=os.environ,
+ working_dir=poll_info.working_path,
+ extra_env={
+ **restored_caller_env,
+ **restored_managed_skills_env,
+ },
+ binding_token=restored_binding_token,
+ **_binding_path_kwargs(restored_binding_path),
+ )
+ except Exception:
+ logger.warning(
+ "Failed to restore OpenCode caller context for session=%s (attempt %s/3)",
+ poll_info.opencode_session_id,
+ attempt + 1,
+ exc_info=True,
+ )
+ if restored_bound:
+ break
+ if attempt < 2:
+ await asyncio.sleep(0)
+ if not restored_bound:
+ logger.error(
+ "Restoring OpenCode poll without caller context for session=%s",
poll_info.opencode_session_id,
- None,
- base_env=os.environ,
- working_dir=poll_info.working_path,
- extra_env={
+ )
+
+ restoration_ready = asyncio.get_running_loop().create_future()
+ restoration_published = asyncio.Event()
+ task = asyncio.create_task(
+ self._run_restored_poll_loop_with_tracking(
+ poll_info,
+ generation_binding=binding,
+ reconcile_initial_status=status_unknown,
+ reconcile_after_message_ids=reconcile_after_message_ids,
+ restoration_ready=restoration_ready,
+ restoration_published=restoration_published,
+ caller_context_binding_token=(
+ restored_binding_token
+ ),
+ caller_context_binding_path=restored_binding_path,
+ caller_context_binding_extra_env={
**restored_caller_env,
**restored_managed_skills_env,
},
- binding_token=restored_binding_token,
- **_binding_path_kwargs(restored_binding_path),
- )
- except Exception:
- logger.warning(
- "Failed to restore OpenCode caller context for session=%s (attempt %s/3)",
- poll_info.opencode_session_id,
- attempt + 1,
- exc_info=True,
+ caller_context_binding_initially_bound=restored_bound,
)
- if restored_bound:
- break
- if attempt < 2:
- await asyncio.sleep(0)
- if not restored_bound:
- logger.error(
- "Restoring OpenCode poll without caller context for session=%s",
- poll_info.opencode_session_id,
)
-
- restoration_ready = asyncio.get_running_loop().create_future()
- restoration_published = asyncio.Event()
- task = asyncio.create_task(
- self._run_restored_poll_loop_with_tracking(
- poll_info,
- reconcile_initial_status=status_unknown,
- reconcile_after_message_ids=reconcile_after_message_ids,
- restoration_ready=restoration_ready,
- restoration_published=restoration_published,
- caller_context_binding_token=(
- restored_binding_token
- ),
- caller_context_binding_path=restored_binding_path,
- caller_context_binding_extra_env={
- **restored_caller_env,
- **restored_managed_skills_env,
- },
- caller_context_binding_initially_bound=restored_bound,
- )
- )
+ except BaseException:
+ # Until the poll task owns the binding, nothing else releases it.
+ await self._release_binding(binding)
+ raise
restoration_results.append(
- (restoration_ready, restoration_published, poll_info)
+ _RestoredPollHandoff(restoration_ready, restoration_published, poll_info, task)
)
self._active_requests[poll_info.base_session_id] = task
self._session_manager.set_request_session(
@@ -2887,21 +3087,21 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if restoration_results:
registered = await asyncio.gather(
- *(future for future, _, _ in restoration_results)
+ *(handoff.ready for handoff in restoration_results)
)
- for is_registered, (_, published, poll_info) in zip(
+ for is_registered, handoff in zip(
registered,
restoration_results,
):
try:
if not is_registered:
continue
- workbench_session_id = self._workbench_session_id_for_poll(poll_info)
+ workbench_session_id = self._workbench_session_id_for_poll(handoff.poll_info)
if workbench_session_id:
self.controller.session_turns.restore_running(workbench_session_id)
restored_count += 1
finally:
- published.set()
+ handoff.published.set()
if restored_count > 0:
logger.info(f"Restored {restored_count} active poll loop(s)")
@@ -2914,6 +3114,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
self,
poll_info,
*,
+ generation_binding: RuntimeBinding | None = None,
reconcile_initial_status: bool = False,
reconcile_after_message_ids: set[str] | None = None,
restoration_ready: asyncio.Future[bool] | None = None,
@@ -2948,7 +3149,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
registration_attempts = 2 if poll_platform in _RESTORED_IM_PLATFORMS else 1
for attempt in range(registration_attempts):
try:
- server = await self._get_server()
+ if generation_binding is not None and generation_binding.generation.stopped:
+ # A forced stop took the process before this poll
+ # registered on it; a live generation settles the run.
+ await self._release_binding(generation_binding)
+ generation_binding = None
+ if generation_binding is None:
+ generation_binding = await self._bind_restored_poll(poll_info)
+ server = generation_binding.generation.runtime
+ self._session_generations[poll_info.base_session_id] = server
await server.mark_run_active(poll_info.opencode_session_id)
break
except Exception:
@@ -3021,6 +3230,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
),
restored=True,
reconcile_initial_status=reconcile_initial_status,
+ generation=server,
)
if has_steering_identity:
self._steering_states[poll_info.base_session_id] = steer_state
@@ -3041,8 +3251,17 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if delivery_recovery_complete is not None:
await delivery_recovery_complete.wait()
terminal_poll_cleanup = bool(
- await self._poll_loop.run_restored_poll_loop(poll_info)
+ await self._poll_loop.run_restored_poll_loop(
+ poll_info,
+ self._restored_poll_servers.get(current_task) or server,
+ )
)
+ except _RestoredPollUnrecorded:
+ if restoration_registered:
+ raise
+ # Unregistered and still naming its old process, the poll stays
+ # durable with its Turn live, and a later restore retries it.
+ self._polls_awaiting_restore.add(poll_info.opencode_session_id)
except Exception as err:
if restoration_registered:
raise
@@ -3080,51 +3299,105 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
err,
)
finally:
- interrupted = current_task in self._settling_request_tasks
- if current_task is not None:
- # Settling from here on, however the poll ended.
- self._settling_request_tasks.add(current_task)
- current_task.add_done_callback(self._settling_request_tasks.discard)
- await self._stop_caller_context_binding_renewal(
- caller_context_binding_renewal
- )
- if current_task is not None:
- self._restored_poll_servers.pop(current_task, None)
- if steer_state is not None:
- async with steer_state.lock:
- steer_state.closing = True
- if self._steering_states.get(poll_info.base_session_id) is steer_state:
- self._steering_states.pop(poll_info.base_session_id, None)
- if (terminal_poll_cleanup or interrupted) and server is not None:
- await self._retire_active_poll(
- server,
- poll_info.opencode_session_id,
+ try:
+ interrupted = current_task in self._settling_request_tasks
+ if current_task is not None:
+ # Settling from here on, however the poll ended.
+ self._settling_request_tasks.add(current_task)
+ current_task.add_done_callback(self._settling_request_tasks.discard)
+ await self._stop_caller_context_binding_renewal(
+ caller_context_binding_renewal
)
- elif interrupted:
- # Interrupted before registering a run marker: only the durable
- # record would bring the run back after a restart.
- self.sessions.remove_active_poll(poll_info.opencode_session_id)
- if caller_context_binding_token and not self._active_poll_is_persisted(
- poll_info.opencode_session_id
- ):
- try:
- await asyncio.to_thread(
- unbind_caller_context_session,
- poll_info.opencode_session_id,
- binding_token=caller_context_binding_token,
- **_binding_path_kwargs(caller_context_binding_path),
- )
- except Exception:
- logger.warning(
- "Failed to clear restored OpenCode caller context for session %s",
+ if current_task is not None:
+ self._restored_poll_servers.pop(current_task, None)
+ if steer_state is not None:
+ async with steer_state.lock:
+ steer_state.closing = True
+ if self._steering_states.get(poll_info.base_session_id) is steer_state:
+ self._steering_states.pop(poll_info.base_session_id, None)
+ if (terminal_poll_cleanup or interrupted) and server is not None:
+ await self._retire_active_poll(
+ server,
poll_info.opencode_session_id,
- exc_info=True,
)
- if self._active_requests.get(poll_info.base_session_id) is current_task:
- self._active_requests.pop(poll_info.base_session_id, None)
- self._session_manager.pop_request_session(poll_info.base_session_id)
- if restoration_ready is not None and not restoration_ready.done():
- restoration_ready.set_result(False)
+ elif interrupted:
+ # Interrupted before registering a run marker: only the durable
+ # record would bring the run back after a restart.
+ self.sessions.remove_active_poll(poll_info.opencode_session_id)
+ if caller_context_binding_token and not self._active_poll_is_persisted(
+ poll_info.opencode_session_id
+ ):
+ try:
+ await asyncio.to_thread(
+ unbind_caller_context_session,
+ poll_info.opencode_session_id,
+ binding_token=caller_context_binding_token,
+ **_binding_path_kwargs(caller_context_binding_path),
+ )
+ except Exception:
+ logger.warning(
+ "Failed to clear restored OpenCode caller context for session %s",
+ poll_info.opencode_session_id,
+ exc_info=True,
+ )
+ finally:
+ # A cancel that lands while the cleanup above awaits must not
+ # leave this poll's request, generation, or binding behind.
+ if self._active_requests.get(poll_info.base_session_id) is current_task:
+ self._active_requests.pop(poll_info.base_session_id, None)
+ self._session_manager.pop_request_session(poll_info.base_session_id)
+ if server is not None and self._session_generations.get(poll_info.base_session_id) is server:
+ self._session_generations.pop(poll_info.base_session_id, None)
+ await self._release_binding(generation_binding)
+ if restoration_ready is not None and not restoration_ready.done():
+ restoration_ready.set_result(False)
+
+ async def _bind_restored_poll(self, poll_info) -> RuntimeBinding:
+ """Bind a restored poll to the generation whose process runs its native turn."""
+
+ await self._ensure_adopted()
+ generation_id = _poll_generation_id(poll_info)
+ generation = self._runtime.generation(generation_id) if generation_id else None
+ if generation is None and generation_id is None:
+ # Polls written before generations name no process: the adopted
+ # legacy server is the one that recorded their run.
+ generation = next(
+ (
+ candidate
+ for candidate in self._runtime.generations()
+ if poll_info.opencode_session_id in candidate.active_run_sessions
+ ),
+ None,
+ )
+ if generation is not None:
+ binding = await self._runtime.bind(generation)
+ else:
+ # No live process owns this run any more. Its messages are in the
+ # shared database, so the current generation reads and settles it.
+ _config, _overlay, spec, _settings = await self._prepare_launch()
+ binding = await self._runtime.acquire(spec)
+ bound_id = binding.generation.runtime.generation_id
+ if bound_id != generation_id:
+ # The poll names the process that now runs its native turn, so a
+ # later restart adopts that process for it and binds it there.
+ indicator = poll_info.processing_indicator if isinstance(poll_info.processing_indicator, dict) else {}
+ try:
+ self.sessions.update_active_poll_state(
+ poll_info.opencode_session_id,
+ processing_indicator={**indicator, _GENERATION_SNAPSHOT_KEY: bound_id},
+ )
+ except Exception as exc:
+ # Never run a poll whose record still names another process: a
+ # crash would bind its next restore to the wrong server.
+ await self._release_binding(binding)
+ logger.warning(
+ "Could not record OpenCode generation %s for restored poll %s; a later restore retries it",
+ bound_id,
+ poll_info.opencode_session_id,
+ exc_info=True,
+ )
+ raise _RestoredPollUnrecorded(poll_info.opencode_session_id) from exc
+ return binding
def _prepare_message_with_files(self, request: AgentRequest) -> str:
return message_with_files(request.message, request.files)
diff --git a/modules/agents/opencode/client_manager.py b/modules/agents/opencode/client_manager.py
index 19c39c950..9a63ec98d 100644
--- a/modules/agents/opencode/client_manager.py
+++ b/modules/agents/opencode/client_manager.py
@@ -1,55 +1,801 @@
-"""Client facade for talking to OpenCode server."""
+"""The OpenCode instance as a runtime unit: its generations and launch specs."""
from __future__ import annotations
import asyncio
-from typing import Any, Awaitable, Callable, Optional
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+import hashlib
+import json
+import logging
+import os
+from pathlib import Path
+import re
+import secrets
+import shutil
+import subprocess
+import time
+from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Mapping, Optional
-from .server import OpenCodeServerManager
+from config import paths
+from config.atomic_io import write_atomic
+from modules.agents.runtime_generations import (
+ RuntimeBinding,
+ RuntimeGeneration,
+ RuntimeGenerationSet,
+)
+from vibe.opencode_config import (
+ get_opencode_auth_path,
+ get_opencode_config_paths,
+ managed_opencode_runtime_config_content,
+ parse_jsonc_object,
+)
+from .caller_context import PLUGIN_SOURCE, server_environment
+from vibe.desktop_runtime import desktop_caller_provenance
-class OpenCodeClientManager:
- """Lazily initializes and returns a shared OpenCodeServerManager instance."""
+from .server import (
+ _MANAGED_RUNTIME_POLICY_REVISION,
+ OpenCodeGeneration,
+ OpenCodeGenerationStartError,
+ OpenCodeLaunchSpec,
+ OpenCodeServerClient,
+ StopOutcome,
+ adopt_recorded_generations,
+ apply_resource_governance,
+ own_generation,
+ start_generation,
+ stop_generation,
+ stop_recorded_servers_sync,
+)
- def __init__(self, opencode_config):
- self._config = opencode_config
- self._server_manager: Optional[OpenCodeServerManager] = None
- self._lock = asyncio.Lock()
- self._resource_governor = None
- self._model_hub_overlay_preparer: (
- Callable[[], Awaitable[Any | None]] | None
- ) = None
+logger = logging.getLogger(__name__)
- def set_resource_governor(self, governor) -> None:
- self._resource_governor = governor
- if self._server_manager is not None:
- self._server_manager.resource_governor = governor
+# 2: the binary is identified by its stat signature alone.
+_LAUNCH_SPEC_SCHEMA = 2
+# OpenCode rewrites these fields of an OAuth entry whenever it refreshes the
+# token, and every live process reads them from auth.json per request.
+_VOLATILE_OAUTH_FIELDS = frozenset({"access", "refresh", "expires"})
+_VERSION_RE = re.compile(r"\d+\.\d+\.\d+[0-9A-Za-z.+-]*")
+_binary_versions: dict[tuple[Any, ...], Optional[str]] = {}
+# A lease outlives no caller: the UI process renews nothing and releases on exit.
+MAX_LEASE_SECONDS = 1800.0
+# The longest one request may run on a generation leased outside the
+# controller. Such a lease lasts this much past the window its caller asks for.
+LEASED_REQUEST_TIMEOUT_SECONDS = 60
+# The runtime holding each live lease. A release reaches it there even after
+# its backend was disabled and its agent unregistered.
+_LEASE_HOLDERS: dict[str, "OpenCodeRuntime"] = {}
- def set_model_hub_overlay_preparer(
+
+def _digest(value: object) -> str:
+ return hashlib.sha256(
+ json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode()
+ ).hexdigest()
+
+
+def _probe_binary_version(binary: str) -> Optional[str]:
+ try:
+ result = subprocess.run(
+ [binary, "--version"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ match = _VERSION_RE.search(f"{result.stdout or ''} {result.stderr or ''}")
+ return match.group(0) if match else None
+
+
+def _binary_identity(configured: str) -> tuple[str, dict[str, Any]]:
+ """The executable a launch runs, and what identifies its exact build.
+
+ Every install writes the file anew, so its stat signature changes on any
+ upgrade or reinstall, including one made outside Avibe.
+ """
+
+ resolved = configured if os.path.isabs(configured) else shutil.which(configured)
+ if not resolved:
+ return configured, {"path": configured, "missing": True}
+ real = os.path.realpath(resolved)
+ try:
+ stat = os.stat(real)
+ except OSError:
+ return resolved, {"path": real, "missing": True}
+ return resolved, {"path": real, "stat": [stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns]}
+
+
+def _global_config_files() -> list[Path]:
+ xdg_config_home = os.environ.get("XDG_CONFIG_HOME")
+ config_dir = (Path(xdg_config_home).expanduser() if xdg_config_home else Path.home() / ".config") / "opencode"
+ candidates = [
+ *get_opencode_config_paths(),
+ *(config_dir / name for name in ("config.json", "opencode.json", "opencode.jsonc")),
+ ]
+ return list(dict.fromkeys(candidates))
+
+
+def _file_bytes(path: Path) -> Optional[bytes]:
+ try:
+ return path.read_bytes()
+ except FileNotFoundError:
+ return None
+
+
+def _user_config_digest(path: Path) -> Optional[str]:
+ raw = _file_bytes(path)
+ if raw is None:
+ return None
+ try:
+ payload = parse_jsonc_object(raw.decode("utf-8"))
+ except Exception:
+ return hashlib.sha256(raw).hexdigest()
+ # OpenCode may add ``$schema`` when it loads a file; that changes nothing it runs.
+ payload.pop("$schema", None)
+ return _digest(payload)
+
+
+def _credential_digest(path: Path) -> Optional[str]:
+ raw = _file_bytes(path)
+ if raw is None:
+ return None
+ try:
+ entries = json.loads(raw)
+ except ValueError:
+ return hashlib.sha256(raw).hexdigest()
+ if not isinstance(entries, dict):
+ return hashlib.sha256(raw).hexdigest()
+ normalized = {
+ provider_id: (
+ {key: value for key, value in entry.items() if key not in _VOLATILE_OAUTH_FIELDS}
+ if isinstance(entry, dict) and entry.get("type") == "oauth"
+ else entry
+ )
+ for provider_id, entry in entries.items()
+ }
+ return _digest(normalized)
+
+
+@dataclass(frozen=True, eq=False)
+class OpenCodeLaunchInputs:
+ """Every mutable input of a launch spec except the Model Hub overlay.
+
+ ``read_launch_inputs`` reads them in one step with no await, in the same
+ step as the turn's Model Hub snapshot, so a save or renewal that lands
+ while the overlay is prepared changes nothing about that launch.
+ """
+
+ executable: str
+ binary_identity: dict[str, Any]
+ renew_epoch: int
+ caller_context_path: str
+ user_config: dict[str, Optional[str]]
+ credentials: Optional[str]
+ # The ``agents.opencode`` settings the CLI path was read from. The turn
+ # takes every per-turn setting from here, never from the live config.
+ settings: Any = None
+
+
+def read_launch_inputs(binary: str, renew_epoch: int, settings: Any = None) -> OpenCodeLaunchInputs:
+ executable, binary_identity = _binary_identity(binary)
+ return OpenCodeLaunchInputs(
+ settings=settings,
+ executable=executable,
+ binary_identity=binary_identity,
+ renew_epoch=renew_epoch,
+ caller_context_path=server_environment()["AVIBE_OPENCODE_CALLER_CONTEXT_PATH"],
+ user_config={str(path): _user_config_digest(path) for path in _global_config_files()},
+ credentials=_credential_digest(get_opencode_auth_path()),
+ )
+
+
+def _binary_version(inputs: OpenCodeLaunchInputs) -> Optional[str]:
+ """The build's version for its record, probed once per file identity."""
+
+ stat = inputs.binary_identity.get("stat")
+ if stat is None:
+ return None
+ key = (inputs.binary_identity["path"], *stat)
+ if key not in _binary_versions:
+ _binary_versions[key] = _probe_binary_version(inputs.executable)
+ return _binary_versions[key]
+
+
+def compute_launch_spec(inputs: OpenCodeLaunchInputs, overlay: Any | None) -> OpenCodeLaunchSpec:
+ """The launch spec of one launch: a pure function of its inputs and overlay."""
+
+ overlay_hash: Optional[str] = None
+ provider_ids: tuple[str, ...] = ()
+ file_content: Optional[bytes] = None
+ inline_content: Optional[str] = None
+ if overlay is not None:
+ provider_ids = getattr(overlay, "provider_ids", ())
+ if (
+ not isinstance(provider_ids, tuple)
+ or not provider_ids
+ or any(not isinstance(provider_id, str) or not provider_id for provider_id in provider_ids)
+ or len(set(provider_ids)) != len(provider_ids)
+ ):
+ raise RuntimeError("Model Hub OpenCode overlay providers are unavailable")
+ content = getattr(overlay, "content", None)
+ if not isinstance(content, (bytes, str)):
+ raise RuntimeError("Model Hub OpenCode overlay content is unavailable")
+ file_content = content.encode() if isinstance(content, str) else content
+ inline_content = managed_opencode_runtime_config_content(content)
+ overlay_hash = str(overlay.content_hash)
+ if hashlib.sha256(inline_content.encode()).hexdigest() != overlay_hash:
+ raise RuntimeError("Model Hub OpenCode overlay content hash changed")
+ digest = _digest(
+ {
+ "schema": _LAUNCH_SPEC_SCHEMA,
+ "binary": inputs.binary_identity,
+ "model_hub_overlay": overlay_hash,
+ "model_hub_overlay_provider_ids": list(provider_ids),
+ # Constants of this Avibe build.
+ "policy": _MANAGED_RUNTIME_POLICY_REVISION,
+ "plugin": hashlib.sha256(PLUGIN_SOURCE.encode()).hexdigest(),
+ "caller_context_path": inputs.caller_context_path,
+ "user_config": inputs.user_config,
+ "credentials": inputs.credentials,
+ "renew_epoch": inputs.renew_epoch,
+ }
+ )
+ return OpenCodeLaunchSpec(
+ digest=digest,
+ binary=inputs.executable,
+ binary_version=_binary_version(inputs),
+ overlay_hash=overlay_hash,
+ overlay_provider_ids=provider_ids,
+ overlay_file_content=file_content,
+ overlay_inline_content=inline_content,
+ )
+
+
+def _renew_epoch_path() -> Path:
+ return paths.get_runtime_dir() / "opencode" / "renew_epoch"
+
+
+def _read_renew_epoch() -> int:
+ try:
+ return int(_renew_epoch_path().read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ return 0
+
+
+def _stop_outcome(wrapper: RuntimeGeneration[Any, OpenCodeGeneration]) -> StopOutcome:
+ if wrapper.stopped:
+ return StopOutcome.STOPPED
+ if wrapper.failed:
+ return StopOutcome.FAILED
+ return StopOutcome.DRAINING
+
+
+@dataclass(frozen=True)
+class _RecordedSpec:
+ """The spec of an adopted process, known only by its recorded digest."""
+
+ digest: str
+
+
+class OpenCodeRuntime:
+ """The generations of the OpenCode instance, Avibe's one OpenCode runtime unit."""
+
+ def __init__(self, opencode_config: Any, *, resource_governor: Any | None = None) -> None:
+ self.config = opencode_config
+ self.resource_governor = resource_governor
+ # Persisted, so a generation a renewal retired before a controller
+ # crash never serves new turns again after the restart.
+ self._renew_epoch = _read_renew_epoch()
+ self._generations: RuntimeGenerationSet[Any, OpenCodeGeneration] = RuntimeGenerationSet(
+ start=self._start,
+ stop=self._stop,
+ )
+ self._wrappers: dict[str, RuntimeGeneration[Any, OpenCodeGeneration]] = {}
+ self._adopted = False
+ self._adopt_lock: Optional[asyncio.Lock] = None
+ # Work outside a turn admitted but not yet bound; a native migration
+ # counts it as active, so it never overlaps a process start.
+ self.outside_turn_acquisitions = 0
+ self._leases: dict[str, tuple[RuntimeBinding[Any, OpenCodeGeneration], Optional[asyncio.TimerHandle]]] = {}
+ self._lease_tasks: set[asyncio.Task[None]] = set()
+ # Processes a failed start could not stop. Every process this runtime
+ # spawned is stopped by a later reap or shutdown until it is gone.
+ self._start_survivors: dict[str, OpenCodeGeneration] = {}
+ # Pid of the last start whose process exited on its own: resource evidence.
+ self.last_start_failure_pid: Optional[int] = None
+ self.start_failures = 0
+ # Wired by the agent.
+ self.durable_poll_generations: Optional[Callable[[], Mapping[str, Optional[str]]]] = None
+ self.on_generation_ready: Optional[Callable[[OpenCodeGeneration], None]] = None
+ self.on_generation_stopping: Optional[Callable[[OpenCodeGeneration, bool], Awaitable[None]]] = None
+ # Whether a generation still runs an Activity it started; a graceful
+ # stop declines while it does.
+ self.holds_activities: Optional[Callable[[OpenCodeGeneration], bool]] = None
+
+ def renew(self) -> None:
+ """New turns start a new generation; running work stays where it is.
+
+ The epoch is persisted before it takes effect. A renewal that cannot be
+ persisted fails rather than being undone by the next controller.
+ """
+ epoch = self._renew_epoch + 1
+ path = _renew_epoch_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ write_atomic(path, str(epoch))
+ self._renew_epoch = epoch
+
+ def launch_inputs(self) -> OpenCodeLaunchInputs:
+ """Read this runtime's launch inputs now; the CLI path and epoch move together."""
+ settings = self.config
+ return read_launch_inputs(settings.binary, self._renew_epoch, settings)
+
+ async def launch_spec(self, overlay: Any | None, inputs: OpenCodeLaunchInputs) -> OpenCodeLaunchSpec:
+ # Off the loop only for the first version probe of a new build.
+ return await asyncio.to_thread(compute_launch_spec, inputs, overlay)
+
+ @property
+ def adopted(self) -> bool:
+ return self._adopted
+
+ def current(self) -> Optional[OpenCodeGeneration]:
+ current = self._generations.current
+ return current.runtime if current is not None else None
+
+ def has_bound_work(self) -> bool:
+ """Whether a turn, restored poll, request sequence, or lease holds a generation."""
+ return any(generation.bindings for generation in self._generations.generations)
+
+ def generations(self) -> tuple[OpenCodeGeneration, ...]:
+ """Every live generation, oldest first."""
+ return tuple(generation.runtime for generation in self._generations.generations)
+
+ def generation(self, generation_id: str) -> Optional[OpenCodeGeneration]:
+ wrapper = self._wrappers.get(generation_id)
+ return wrapper.runtime if wrapper is not None and not wrapper.stopped else None
+
+ async def ensure_adopted(self, current_spec: Optional[OpenCodeLaunchSpec] = None) -> None:
+ """Adopt the generations a previous controller left running, once.
+
+ The newest one whose spec equals ``current_spec`` keeps serving new
+ turns. Every other one retires: it stops at once when it runs nothing,
+ or once its restored work drains.
+ """
+
+ if self._adopted:
+ return
+ if self._adopt_lock is None:
+ self._adopt_lock = asyncio.Lock()
+ async with self._adopt_lock:
+ if self._adopted:
+ return
+ # Oldest first, so the set's serials follow process age and the cap
+ # gives way from the oldest work; records come in no order.
+ adopted = sorted(
+ await adopt_recorded_generations(
+ request_timeout_seconds=self.config.request_timeout_seconds,
+ ),
+ key=lambda item: item.started_at,
+ )
+ durable = self._durable_polls()
+ serving = next(
+ (
+ generation
+ for generation in reversed(adopted)
+ if current_spec is not None and generation.spec_digest == current_spec.digest
+ ),
+ None,
+ )
+ for generation in adopted:
+ self._reconcile_run_markers(generation, durable)
+ wrapper = await self._generations.adopt(
+ _RecordedSpec(generation.spec_digest),
+ generation,
+ current=generation is serving,
+ )
+ self._wrappers[generation.generation_id] = wrapper
+ # Owned only once attached, so an adoption cut short leaves
+ # the rest for its retry.
+ own_generation(generation)
+ apply_resource_governance(self.resource_governor, generation.pid)
+ if self.on_generation_ready is not None:
+ self.on_generation_ready(generation)
+ now = time.time()
+ for lease_id, expires_at in list(generation.leases.items()):
+ if expires_at <= now:
+ generation.drop_lease(lease_id)
+ continue
+ binding = await self._generations.bind(wrapper)
+ # Never longer than any lease is granted, whatever the clock did.
+ self._hold_lease(lease_id, binding, min(expires_at - now, MAX_LEASE_SECONDS))
+ self._adopted = True
+
+ def _durable_polls(self) -> Optional[Mapping[str, Optional[str]]]:
+ provider = self.durable_poll_generations
+ if provider is None:
+ return None
+ try:
+ return provider()
+ except Exception:
+ logger.warning("Could not read durable OpenCode polls to reconcile run markers", exc_info=True)
+ return None
+
+ @staticmethod
+ def _reconcile_run_markers(
+ generation: OpenCodeGeneration,
+ durable: Optional[Mapping[str, Optional[str]]],
+ ) -> None:
+ """Drop adopted run markers that no durable poll can bring back."""
+
+ if durable is None or not generation.active_run_sessions:
+ return
+ retained = {
+ session_id
+ for session_id in generation.active_run_sessions
+ if session_id in durable and durable[session_id] in (None, generation.generation_id)
+ }
+ if retained == generation.active_run_sessions:
+ return
+ logger.info(
+ "Removed %s orphaned OpenCode run marker(s) without durable polls",
+ len(generation.active_run_sessions - retained),
+ )
+ generation.active_run_sessions = retained
+ generation.write_record_or_defer("its reconciled run markers")
+
+ async def acquire(self, spec: OpenCodeLaunchSpec) -> RuntimeBinding[Any, OpenCodeGeneration]:
+ """Bind new work to the generation that serves ``spec``."""
+
+ await self.ensure_adopted(spec)
+ for _attempt in range(2):
+ binding = await self._generations.acquire(spec)
+ wrapper = binding.generation
+ self._wrappers[wrapper.runtime.generation_id] = wrapper
+ if wrapper.runtime.process_alive():
+ return binding
+ # The process ended without Avibe stopping it. Never serve a turn
+ # on it; the next acquire starts a fresh generation.
+ logger.warning(
+ "OpenCode generation %s pid=%s exited; starting another",
+ wrapper.runtime.generation_id,
+ wrapper.runtime.pid,
+ )
+ await binding.release()
+ await self.forget(wrapper.runtime)
+ raise OpenCodeGenerationStartError("OpenCode server exited right after it started")
+
+ async def bind(self, generation: OpenCodeGeneration) -> RuntimeBinding[Any, OpenCodeGeneration]:
+ """Bind recovered work, such as a restored poll, to the generation that runs it."""
+ wrapper = self._wrappers.get(generation.generation_id)
+ if wrapper is None:
+ raise RuntimeError("OpenCode generation is no longer tracked")
+ return await self._generations.bind(wrapper)
+
+ async def forget(self, generation: OpenCodeGeneration) -> None:
+ """Drop a generation whose process already ended."""
+
+ wrapper = self._wrappers.pop(generation.generation_id, None)
+ if wrapper is None:
+ return
+ await self._generations.discard(wrapper)
+ if self.on_generation_stopping is not None:
+ await self.on_generation_stopping(generation, False)
+ try:
+ await stop_generation(generation)
+ except Exception:
+ logger.warning("Could not clean up OpenCode generation %s", generation.generation_id, exc_info=True)
+
+ async def lease(self, spec: OpenCodeLaunchSpec, ttl_seconds: float) -> tuple[str, OpenCodeGeneration]:
+ """Pin the generation that serves ``spec`` for a caller outside this process."""
+
+ ttl = min(max(float(ttl_seconds), 1.0), MAX_LEASE_SECONDS)
+ binding = await self.acquire(spec)
+ generation = binding.generation.runtime
+ lease_id = f"ocl_{secrets.token_hex(12)}"
+ try:
+ # Persisted, so a controller restart keeps the process for its caller.
+ generation.set_lease(lease_id, time.time() + ttl)
+ except BaseException:
+ await binding.release()
+ raise
+ self._hold_lease(lease_id, binding, ttl)
+ return lease_id, generation
+
+ def _hold_lease(
self,
- preparer: Callable[[], Awaitable[Any | None]],
+ lease_id: str,
+ binding: RuntimeBinding[Any, OpenCodeGeneration],
+ ttl: float,
) -> None:
- self._model_hub_overlay_preparer = preparer
- if self._server_manager is not None:
- self._server_manager.set_model_hub_overlay_preparer(preparer)
-
- async def get_server(self) -> OpenCodeServerManager:
- async with self._lock:
- if self._server_manager is None:
- self._server_manager = await OpenCodeServerManager.get_instance(
- binary=self._config.binary,
- port=self._config.port,
- request_timeout_seconds=self._config.request_timeout_seconds,
- resource_governor=self._resource_governor,
- )
- if self._model_hub_overlay_preparer is not None:
- self._server_manager.set_model_hub_overlay_preparer(
- self._model_hub_overlay_preparer
- )
- return self._server_manager
-
- async def reset_config(self, opencode_config) -> Optional[OpenCodeServerManager]:
- async with self._lock:
- previous = self._server_manager
- self._config = opencode_config
- return previous
+ timer = asyncio.get_running_loop().call_later(ttl, self._expire_lease, lease_id)
+ self._leases[lease_id] = (binding, timer)
+ _LEASE_HOLDERS[lease_id] = self
+
+ def _expire_lease(self, lease_id: str) -> None:
+ task = asyncio.get_running_loop().create_task(self.release_lease(lease_id))
+ self._lease_tasks.add(task)
+ task.add_done_callback(self._lease_tasks.discard)
+
+ async def release_lease(self, lease_id: str) -> bool:
+ held = self._leases.pop(lease_id, None)
+ if held is None:
+ return False
+ _LEASE_HOLDERS.pop(lease_id, None)
+ binding, timer = held
+ if timer is not None:
+ timer.cancel()
+ binding.generation.runtime.drop_lease(lease_id)
+ await binding.release()
+ return True
+
+ async def reap(self) -> None:
+ await self._stop_start_survivors()
+ for generation in self.generations():
+ generation.flush_record()
+ await self._generations.reap()
+
+ def _keep_start_survivor(self, generation: OpenCodeGeneration) -> None:
+ logger.warning(
+ "OpenCode generation %s pid=%s survived its failed start; reaping retries its stop",
+ generation.generation_id,
+ generation.pid,
+ )
+ self._start_survivors[generation.generation_id] = generation
+
+ async def _stop_start_survivors(self) -> None:
+ for generation_id, generation in list(self._start_survivors.items()):
+ try:
+ await stop_generation(generation)
+ except Exception:
+ logger.warning("OpenCode generation %s survived its stop again", generation_id, exc_info=True)
+ continue
+ self._start_survivors.pop(generation_id, None)
+
+ async def retire_confirmed(
+ self,
+ generations: Optional[Iterable[OpenCodeGeneration]] = None,
+ ) -> dict[str, StopOutcome]:
+ """Retire generations, wait for their stops, and report each outcome.
+
+ This is the controller's one confirmed-stop primitive: a stop counts as
+ done only after the reconciler has run it. ``generations`` defaults to
+ the current generation.
+ """
+
+ if generations is None:
+ current = self._generations.current
+ wrappers = [current] if current is not None else []
+ else:
+ wrappers = [
+ wrapper
+ for generation in generations
+ if (wrapper := self._wrappers.get(generation.generation_id)) is not None
+ ]
+ for wrapper in wrappers:
+ await self._generations.retire(wrapper)
+ # Waits for the reconciler, and retries graceful stops that declined earlier.
+ await self._generations.reap()
+ return {wrapper.runtime.generation_id: _stop_outcome(wrapper) for wrapper in wrappers}
+
+ async def shutdown(self) -> None:
+ """Admit nothing more and stop every OpenCode process now, bound work included.
+
+ Every generation this runtime attached is force-stopped. Then every
+ recorded server no runtime here owns, such as one a crashed controller
+ left, is stopped by its record, as a disabled startup stops them. The
+ set admits no adoption once stopping, and a disable needs none.
+
+ Raises while any process survives, so the caller's teardown owner
+ retries it. A retry repeats both steps and is safe at any point.
+ """
+ await self._generations.stop_all(force=True)
+ await self._stop_start_survivors()
+ leftovers = await asyncio.to_thread(stop_recorded_servers_sync, desktop_caller_provenance())
+ survivors = [generation.generation_id for generation in (*self.generations(), *self._start_survivors.values())]
+ failed = sum(outcome is StopOutcome.FAILED for outcome in leftovers)
+ if survivors or failed:
+ raise RuntimeError(
+ f"OpenCode shutdown is incomplete: {len(survivors)} generation(s) and "
+ f"{failed} recorded server(s) survived their stop"
+ )
+
+ async def retire_all(self) -> None:
+ """Admit nothing more to any live generation; each stops once its work drains.
+
+ New turns still start a fresh generation afterwards.
+ """
+
+ for generation in self._generations.generations:
+ await self._generations.retire(generation)
+
+ async def retire_all_strict(self) -> None:
+ """Stop every generation now, failing if any work or process remains.
+
+ A generation still bound, or whose process survives, stays tracked as
+ closed, so it never serves again and a later sweep retries its stop.
+ """
+
+ outcomes = await self.retire_confirmed(self.generations())
+ if any(outcome is not StopOutcome.STOPPED for outcome in outcomes.values()):
+ raise RuntimeError("OpenCode server did not exit")
+
+ async def _start(self, spec: Any) -> OpenCodeGeneration:
+ try:
+ generation = await start_generation(
+ spec,
+ request_timeout_seconds=self.config.request_timeout_seconds,
+ resource_governor=self.resource_governor,
+ on_survivor=self._keep_start_survivor,
+ )
+ except OpenCodeGenerationStartError as exc:
+ self.start_failures += 1
+ self.last_start_failure_pid = exc.exited_pid
+ raise
+ self.last_start_failure_pid = None
+ if self.on_generation_ready is not None:
+ self.on_generation_ready(generation)
+ return generation
+
+ async def _stop(self, wrapper: RuntimeGeneration[Any, OpenCodeGeneration], force: bool) -> bool:
+ """Stop one generation; decline a graceful stop while it still has work.
+
+ Bindings cover turns, restored polls, and leases. Requests and native
+ runs outside them, such as a run marker whose poll failed to clear it,
+ still keep the process. Safe to retry: when the process survives, the
+ set keeps the generation and a later sweep stops it again.
+ """
+
+ generation = wrapper.runtime
+ if not force and generation.process_alive():
+ if not generation.is_drained():
+ # A run marker that no durable poll backs, left by an adoption
+ # that could not read the durable polls, keeps the process only
+ # until a later sweep's retry of that reconciliation succeeds.
+ self._reconcile_run_markers(generation, self._durable_polls())
+ if not generation.is_drained():
+ return False
+ # An Activity outlives its turn, so no binding names it any longer.
+ if self.holds_activities is not None and self.holds_activities(generation):
+ return False
+ if self.on_generation_stopping is not None:
+ await self.on_generation_stopping(generation, force)
+ await stop_generation(generation)
+ self._wrappers.pop(generation.generation_id, None)
+ return True
+
+
+class OpenCodeRuntimeUnavailableError(RuntimeError):
+ """No controller-owned OpenCode generation can serve this caller."""
+
+ def __init__(self, reason: str, detail: str = "") -> None:
+ super().__init__(detail or reason)
+ self.reason = reason
+
+
+@dataclass
+class OpenCodeServerLease:
+ """A controller-owned generation pinned for one caller until released."""
+
+ server: OpenCodeServerClient
+ lease_id: str
+ _release: Callable[[], Awaitable[None]]
+ released: bool = False
+
+ async def release(self) -> None:
+ if self.released:
+ return
+ self.released = True
+ try:
+ await self._release()
+ except Exception:
+ # The lease expires on its own; a failed release only shortens nothing.
+ logger.warning("Could not release OpenCode lease %s", self.lease_id, exc_info=True)
+
+
+async def lease_opencode_server(
+ purpose: str,
+ *,
+ ttl_seconds: float,
+ controller: Any = None,
+) -> OpenCodeServerLease:
+ """Pin the current OpenCode generation without ever launching one here.
+
+ In the controller the agent leases directly. Any other process asks the
+ controller over control IPC and talks to the leased generation over HTTP.
+ There, ``ttl_seconds`` is the window in which the caller may start
+ requests, and the lease lasts one request timeout longer. The lease, timed
+ from before the controller grants it, ends no earlier here than in the
+ controller, and the leased client starts no request that could outlive
+ it. The controller never stops the process under a running request, and
+ the lease only stays behind a caller that died holding it.
+ """
+
+ agent_service = getattr(controller, "agent_service", None)
+ if agent_service is not None:
+ agent = getattr(agent_service, "agents", {}).get("opencode")
+ lease_generation = getattr(agent, "lease_generation", None)
+ if not callable(lease_generation):
+ raise OpenCodeRuntimeUnavailableError("opencode_disabled")
+ payload = await lease_generation(purpose, ttl_seconds=ttl_seconds)
+ generation = payload["server"]
+ lease_id = payload["lease_id"]
+
+ async def _release_local() -> None:
+ await agent.release_generation_lease(lease_id)
+
+ return OpenCodeServerLease(server=generation, lease_id=lease_id, _release=_release_local)
+
+ from vibe import internal_client
+
+ lease_seconds = ttl_seconds + LEASED_REQUEST_TIMEOUT_SECONDS
+ requested_at = asyncio.get_running_loop().time()
+ try:
+ result = await internal_client.create_opencode_generation_lease(purpose, ttl_seconds=lease_seconds)
+ except (internal_client.InternalServerUnavailable, internal_client.InternalServerTimeout) as exc:
+ raise OpenCodeRuntimeUnavailableError("controller_unavailable", str(exc)) from exc
+ body = result.get("body") if isinstance(result.get("body"), dict) else {}
+ if result.get("status_code") != 200 or not body.get("ok"):
+ raise OpenCodeRuntimeUnavailableError(
+ str(body.get("error") or "opencode_server_unavailable"),
+ str(body.get("detail") or ""),
+ )
+ lease_id = str(body["lease_id"])
+ request_timeout = body.get("request_timeout_seconds")
+ server = OpenCodeServerClient(
+ str(body["base_url"]),
+ # Bounded, so every request it starts ends before its lease does.
+ request_timeout_seconds=(
+ request_timeout
+ if isinstance(request_timeout, int)
+ and not isinstance(request_timeout, bool)
+ and 0 < request_timeout <= LEASED_REQUEST_TIMEOUT_SECONDS
+ else LEASED_REQUEST_TIMEOUT_SECONDS
+ ),
+ model_hub_provider_ids=tuple(
+ item for item in body.get("model_hub_provider_ids") or () if isinstance(item, str) and item
+ ),
+ )
+ server.lease_expires_at = requested_at + lease_seconds
+
+ async def _release_remote() -> None:
+ try:
+ await server.close_http_session()
+ finally:
+ await internal_client.release_opencode_generation_lease(lease_id)
+
+ return OpenCodeServerLease(server=server, lease_id=lease_id, _release=_release_remote)
+
+
+async def release_opencode_lease(lease_id: str, *, controller: Any) -> Optional[bool]:
+ """Release a lease in the runtime holding it, wherever its agent went.
+
+ A lease no runtime holds yet, recorded before a controller restart, goes
+ to the registered agent, which adopts it first. ``None`` means OpenCode is
+ disabled and holds no such lease.
+ """
+
+ holder = _LEASE_HOLDERS.get(lease_id)
+ if holder is not None:
+ return await holder.release_lease(lease_id)
+ agent = getattr(getattr(controller, "agent_service", None), "agents", {}).get("opencode")
+ release = getattr(agent, "release_generation_lease", None)
+ if not callable(release):
+ return None
+ return bool(await release(lease_id))
+
+
+@asynccontextmanager
+async def leased_opencode_server(
+ purpose: str,
+ *,
+ ttl_seconds: float = 60.0,
+ controller: Any = None,
+) -> AsyncIterator[OpenCodeServerClient]:
+ """Run one caller's requests on a pinned controller-owned generation."""
+
+ lease = await lease_opencode_server(purpose, ttl_seconds=ttl_seconds, controller=controller)
+ try:
+ yield lease.server
+ finally:
+ await lease.release()
diff --git a/modules/agents/opencode/config_reconciler.py b/modules/agents/opencode/config_reconciler.py
deleted file mode 100644
index 00a07643e..000000000
--- a/modules/agents/opencode/config_reconciler.py
+++ /dev/null
@@ -1,234 +0,0 @@
-"""Reconcile OpenCode user config, auth storage, and live runtime config."""
-
-from __future__ import annotations
-
-import copy
-from dataclasses import dataclass
-from typing import Any, Dict, Mapping
-
-LOCAL_PROVIDER_IDS = {"ollama", "lmstudio", "lm-studio"}
-USER_MODEL_META_KEY = "vibe_remote"
-
-
-@dataclass(frozen=True)
-class OpenCodeConfigReconciler:
- """Build the config payload that should be applied to live OpenCode.
-
- ``opencode.json`` is the source of truth for user-managed config.
- ``auth.json`` is the source of truth for provider credentials.
- The live OpenCode config is only a preservation source for providers
- OpenCode owns at runtime, currently auth-backed and local providers.
- """
-
- local_provider_ids: frozenset[str] = frozenset(LOCAL_PROVIDER_IDS)
-
- def reconcile(
- self,
- *,
- user_config: Mapping[str, Any],
- live_config: Mapping[str, Any],
- auth_entries: Mapping[str, Mapping[str, Any]],
- ) -> Dict[str, Any]:
- merged = copy.deepcopy(dict(user_config))
- user_providers = user_config.get("provider")
- if not isinstance(user_providers, Mapping):
- if "provider" in user_config:
- merged.pop("provider", None)
- else:
- live_providers = live_config.get("provider")
- live_providers = live_providers if isinstance(live_providers, Mapping) else {}
- preserved = self._reconcile_providers(
- user_providers={},
- live_providers=live_providers,
- auth_entries=auth_entries,
- )
- if preserved:
- merged["provider"] = preserved
- return merged
-
- live_providers = live_config.get("provider")
- live_providers = live_providers if isinstance(live_providers, Mapping) else {}
- merged["provider"] = self._reconcile_providers(
- user_providers=user_providers,
- live_providers=live_providers,
- auth_entries=auth_entries,
- )
- return merged
-
- def _reconcile_providers(
- self,
- *,
- user_providers: Mapping[str, Any],
- live_providers: Mapping[str, Any],
- auth_entries: Mapping[str, Mapping[str, Any]],
- ) -> Dict[str, Any]:
- merged: Dict[str, Any] = {}
- for provider_id, user_provider in user_providers.items():
- if not isinstance(provider_id, str) or not isinstance(user_provider, Mapping):
- continue
- merged[provider_id] = self._reconcile_user_provider(
- provider_id=provider_id,
- user_provider=user_provider,
- live_provider=live_providers.get(provider_id),
- auth_entry=auth_entries.get(provider_id),
- )
-
- for provider_id, auth_entry in auth_entries.items():
- if provider_id in merged or not isinstance(provider_id, str) or not isinstance(auth_entry, Mapping):
- continue
- live_provider = live_providers.get(provider_id)
- if isinstance(live_provider, Mapping):
- merged[provider_id] = self._copy_auth_backed_live_provider(
- live_provider=live_provider,
- auth_entry=auth_entry,
- )
- else:
- auth_api_key = self._auth_api_key(auth_entry)
- if auth_api_key:
- merged[provider_id] = {"options": {"apiKey": auth_api_key}}
-
- for provider_id, live_provider in live_providers.items():
- if provider_id in merged or not isinstance(provider_id, str) or not isinstance(live_provider, Mapping):
- continue
- if self._is_local_provider(provider_id):
- merged[provider_id] = self._copy_live_local_provider(live_provider)
-
- return merged
-
- def _reconcile_user_provider(
- self,
- *,
- provider_id: str,
- user_provider: Mapping[str, Any],
- live_provider: Any,
- auth_entry: Mapping[str, Any] | None,
- ) -> Dict[str, Any]:
- if isinstance(live_provider, Mapping):
- provider = self._deep_merge_config(dict(live_provider), user_provider)
- else:
- provider = copy.deepcopy(dict(user_provider))
-
- is_local_provider = self._is_local_provider(provider_id)
- self._reconcile_user_provider_options(provider, user_provider, auth_entry, is_local_provider)
- self._reconcile_user_provider_models(provider, user_provider, is_local_provider)
- return provider
-
- def _reconcile_user_provider_options(
- self,
- provider: Dict[str, Any],
- user_provider: Mapping[str, Any],
- auth_entry: Mapping[str, Any] | None,
- is_local_provider: bool,
- ) -> None:
- user_options = user_provider.get("options")
- auth_api_key = self._auth_api_key(auth_entry)
- if isinstance(user_options, Mapping):
- options = copy.deepcopy(dict(user_options))
- if auth_api_key and "apiKey" not in options:
- options["apiKey"] = auth_api_key
- provider["options"] = options
- return
-
- if "options" in user_provider:
- provider.pop("options", None)
- return
-
- if auth_api_key:
- provider["options"] = {"apiKey": auth_api_key}
- return
-
- if is_local_provider and isinstance(provider.get("options"), Mapping):
- return
-
- provider.pop("options", None)
-
- @staticmethod
- def _reconcile_user_provider_models(
- provider: Dict[str, Any],
- user_provider: Mapping[str, Any],
- is_local_provider: bool,
- ) -> None:
- user_models = user_provider.get("models")
- if isinstance(user_models, Mapping):
- if is_local_provider and isinstance(provider.get("models"), Mapping):
- provider["models"] = OpenCodeConfigReconciler._merge_local_provider_models(
- provider["models"],
- user_models,
- )
- else:
- provider["models"] = copy.deepcopy(dict(user_models))
- elif "models" in user_provider:
- provider.pop("models", None)
-
- @staticmethod
- def _merge_local_provider_models(live_models: Mapping[str, Any], user_models: Mapping[str, Any]) -> Dict[str, Any]:
- merged: Dict[str, Any] = {}
- for model_id, model_info in live_models.items():
- if not isinstance(model_id, str):
- continue
- if isinstance(model_info, Mapping) and OpenCodeConfigReconciler._is_explicit_user_model(model_info):
- continue
- merged[model_id] = copy.deepcopy(model_info)
- merged.update(copy.deepcopy(dict(user_models)))
- return merged
-
- @staticmethod
- def _copy_live_local_provider(live_provider: Mapping[str, Any]) -> Dict[str, Any]:
- provider = copy.deepcopy(dict(live_provider))
- models = provider.get("models")
- if isinstance(models, Mapping):
- provider["models"] = OpenCodeConfigReconciler._merge_local_provider_models(models, {})
- return provider
-
- @staticmethod
- def _is_explicit_user_model(model_info: Mapping[str, Any]) -> bool:
- meta = model_info.get(USER_MODEL_META_KEY)
- return isinstance(meta, Mapping) and meta.get("user_model") is True
-
- def _copy_auth_backed_live_provider(
- self,
- *,
- live_provider: Mapping[str, Any],
- auth_entry: Mapping[str, Any],
- ) -> Dict[str, Any]:
- provider = copy.deepcopy(dict(live_provider))
- auth_api_key = self._auth_api_key(auth_entry)
- options = provider.get("options")
- if auth_api_key:
- if not isinstance(options, Mapping):
- options = {}
- else:
- options = copy.deepcopy(dict(options))
- options["apiKey"] = auth_api_key
- provider["options"] = options
- elif auth_entry.get("type") == "oauth" and isinstance(options, Mapping):
- options = copy.deepcopy(dict(options))
- options.pop("apiKey", None)
- if options:
- provider["options"] = options
- else:
- provider.pop("options", None)
- return provider
-
- def _is_local_provider(self, provider_id: str) -> bool:
- return provider_id.lower() in self.local_provider_ids
-
- @staticmethod
- def _auth_api_key(auth_entry: Mapping[str, Any] | None) -> str | None:
- if not isinstance(auth_entry, Mapping) or auth_entry.get("type") != "api":
- return None
- key = auth_entry.get("key")
- return key if isinstance(key, str) and key else None
-
- @classmethod
- def _deep_merge_config(cls, base: Any, override: Any) -> Any:
- if not isinstance(base, Mapping) or not isinstance(override, Mapping):
- return copy.deepcopy(override)
- merged = copy.deepcopy(dict(base))
- for key, value in override.items():
- current = merged.get(key)
- if isinstance(current, Mapping) and isinstance(value, Mapping):
- merged[key] = cls._deep_merge_config(current, value)
- else:
- merged[key] = copy.deepcopy(value)
- return merged
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index c5571d88c..f1ed0de9e 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -25,7 +25,7 @@ from modules.im import MessageContext
from vibe.i18n import t as i18n_t
from .message_processor import is_empty_terminal_opencode_message
-from .server import OpenCodeServerManager
+from .server import OpenCodeGeneration
logger = logging.getLogger(__name__)
@@ -280,7 +280,7 @@ class OpenCodePollLoop:
if callable(record_failure):
await record_failure(context, diagnostic)
- def _active_turn_timeout_seconds(self) -> float:
+ def _active_turn_timeout_seconds(self, settings: Any = None) -> float:
"""The configured wall-clock bound, or ``0.0`` when it is disabled.
Non-positive, missing, or non-finite values all read as disabled. The
@@ -291,7 +291,7 @@ class OpenCodePollLoop:
"""
raw_timeout = getattr(
- self._agent.opencode_config,
+ settings if settings is not None else self._agent.opencode_config,
"active_turn_timeout_seconds",
DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS,
)
@@ -322,7 +322,7 @@ class OpenCodePollLoop:
async def _native_session_is_live(
self,
- server: OpenCodeServerManager,
+ server: OpenCodeGeneration,
session_id: str,
directory: str,
*,
@@ -361,7 +361,7 @@ class OpenCodePollLoop:
self,
*,
request: AgentRequest,
- server: OpenCodeServerManager,
+ server: OpenCodeGeneration,
session_id: str,
working_path: str,
timeout_seconds: float,
@@ -405,7 +405,7 @@ class OpenCodePollLoop:
self,
*,
request: AgentRequest,
- server: OpenCodeServerManager,
+ server: OpenCodeGeneration,
session_id: str,
working_path: str,
failures: int,
@@ -578,13 +578,14 @@ class OpenCodePollLoop:
async def run_prompt_poll(
self,
request: AgentRequest,
- server: OpenCodeServerManager,
+ server: OpenCodeGeneration,
session_id: str,
*,
agent_to_use: Optional[str],
model_dict: Optional[Dict[str, str]],
reasoning_effort: Optional[str],
baseline_message_ids: set[str],
+ settings: Any = None,
) -> tuple[Optional[str], bool]:
"""Poll messages for a prompt.
@@ -598,14 +599,15 @@ class OpenCodePollLoop:
seen_tool_calls: set[str] = set()
emitted_assistant_messages: set[str] = set()
final_text: Optional[str] = None
- timeout_seconds = self._active_turn_timeout_seconds()
+ # The settings the turn was admitted with, never the live config.
+ timeout_seconds = self._active_turn_timeout_seconds(settings)
deadline = (
time.monotonic() + timeout_seconds if timeout_seconds > 0 else math.inf
)
error_retry_count = 0
error_retry_limit = getattr(
- self._agent.opencode_config,
+ settings if settings is not None else self._agent.opencode_config,
"error_retry_limit",
DEFAULT_OPENCODE_ERROR_RETRY_LIMIT,
)
@@ -902,8 +904,8 @@ class OpenCodePollLoop:
return final_text, True
- async def run_restored_poll_loop(self, poll_info) -> bool:
- """Continue a poll loop that was interrupted by restart."""
+ async def run_restored_poll_loop(self, poll_info, server: OpenCodeGeneration) -> bool:
+ """Continue a poll loop that was interrupted by restart, on its own generation."""
session_id = poll_info.opencode_session_id
restored_request = self._build_restored_ack_request(poll_info)
@@ -919,7 +921,6 @@ class OpenCodePollLoop:
"Resuming interrupted OpenCode session after restart...",
)
- server = await self._agent._get_server()
baseline_message_ids = set(poll_info.baseline_message_ids)
seen_tool_calls = set(poll_info.seen_tool_calls)
emitted_assistant_messages = set(poll_info.emitted_assistant_messages)
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 85d6f0695..375cb764b 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -1,54 +1,50 @@
-"""OpenCode server lifecycle + HTTP API wrapper."""
+"""OpenCode runtime generations: process lifecycle and HTTP API."""
from __future__ import annotations
import asyncio
from contextlib import asynccontextmanager
+from dataclasses import dataclass, field
from datetime import datetime
-import hashlib
+from enum import Enum
import json
import logging
+import math
import os
from pathlib import Path
import re
+import secrets
import signal
import socket
-import subprocess
import time
from urllib.parse import quote as _url_quote
import urllib.error
import urllib.parse
import urllib.request
-import threading
from asyncio.subprocess import Process
-from typing import Any, Awaitable, Callable, Dict, List, Optional
+from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional
import aiohttp
import psutil
from config import paths
from config.atomic_io import write_atomic
-from config.v2_config import V2Config, is_model_hub_enabled
from core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL
from core.process_isolation import isolated_subprocess_kwargs
-from core.resource_governance import is_controller_resource_governor
from modules.agents.opencode.caller_context import ensure_plugin_installed, server_environment
-from modules.agents.opencode.config_reconciler import OpenCodeConfigReconciler
from vibe import runtime
-from vibe.desktop_runtime import DESKTOP_OPENCODE_ROLE, DESKTOP_ROLE_ENV
+from vibe.desktop_runtime import DESKTOP_OPENCODE_ROLE, DESKTOP_ROLE_ENV, desktop_caller_provenance
from vibe.opencode_config import (
OPENCODE_REASONING_VARIANTS,
OpenCodeRuntimeConfigInvalidError,
get_opencode_custom_provider_adapter,
load_first_opencode_user_config,
managed_opencode_runtime_config_content as _managed_runtime_config_content,
- parse_jsonc_object,
read_opencode_provider_auth_entries,
)
logger = logging.getLogger(__name__)
-DEFAULT_OPENCODE_PORT = 4096
DEFAULT_OPENCODE_HOST = "127.0.0.1"
# A cold OpenCode process can take close to a minute to load on a busy or
# freshly provisioned host. This is only a ceiling: a healthy start returns as
@@ -63,12 +59,28 @@ SERVER_START_TIMEOUT = 120
# a request timeout.
DIRECTORY_BOOTSTRAP_TIMEOUT = 300
OPENCODE_LOG_TAIL_BYTES = 2_000_000
-MODEL_HUB_OVERLAY_DRAIN_TIMEOUT_SECONDS = 30.0
-_USE_CURRENT_CALLER_CONTEXT_PATH = object()
-_CURRENT_OWNER_PID = os.getpid()
+# Ports Avibe chooses can be taken by another process before OpenCode binds.
+_PORT_ATTEMPTS = 3
+GENERATION_RECORD_SCHEMA = 1
+# The spec of a server adopted from the single-server record of a release
+# before generations. No new turn's spec ever equals it.
+LEGACY_SPEC_DIGEST = "legacy"
+# A record written before the desktop Runtime id was recorded.
+_UNRECORDED_RUNTIME_ID = object()
+# Generations a runtime of this process is starting or has attached, with the
+# process each one runs. Adoption leaves them to that runtime, for example the
+# one of an OpenCode backend disabled and enabled again while its turn still
+# runs; it stops them once their work drains. A started process is owned from
+# its spawn, before its record is written, until a stop proves it gone or its
+# start proves it exited, so this controller's shutdown stops it, recorded or not.
+_OWNED_HERE: dict[str, tuple[int, Optional[float]]] = {}
+# A busy server after a controller crash can miss one health probe; adoption
+# gives it this many before stopping it.
+_ADOPTION_PROBES = 3
+_ADOPTION_PROBE_INTERVAL_SECONDS = 2.0
_DURABLE_ATTEMPT_ID_RE = re.compile(r"^atm_([0-9a-f]{32})$")
-# Bump whenever the process-level Avibe policy applied in ``_start_server``
-# changes so an adopted process cannot silently keep the previous behavior.
+# Bump whenever the process-level Avibe policy applied at launch changes. It is
+# a launch spec input, so the next turn starts a generation under the new policy.
_MANAGED_RUNTIME_POLICY_REVISION = "disable-native-skill-v2"
@@ -231,183 +243,121 @@ class OpenCodePromptRejectedError(RuntimeError):
return self.status == 400
-class OpenCodeManagedPolicyRefreshPendingError(RuntimeError):
- """The adopted OpenCode process cannot apply Avibe's current policy yet."""
+class OpenCodeDirectoryBootstrapTimeoutError(RuntimeError):
+ """OpenCode is still bootstrapping a directory after the readiness ceiling."""
-class OpenCodeModelHubOverlayRequiredError(RuntimeError):
- """Hub mode cannot launch OpenCode until its owner configures an overlay."""
+class StopOutcome(str, Enum):
+ """What a confirmed stop found once nothing about it was still pending."""
-class OpenCodeDirectoryBootstrapTimeoutError(RuntimeError):
- """OpenCode is still bootstrapping a directory after the readiness ceiling."""
+ # The process is gone and its record removed.
+ STOPPED = "stopped"
+ # Work or a lease still binds it; it stops once that drains.
+ DRAINING = "draining"
+ # Its stop ran and the process survived; its record stays for a retry.
+ FAILED = "failed"
-class OpenCodeServerManager:
- """Manages a singleton OpenCode server process shared across all working directories."""
+class OpenCodeGenerationStartError(RuntimeError):
+ """A generation's ``opencode serve`` process did not become ready."""
- _instance: Optional["OpenCodeServerManager"] = None
- _class_lock: threading.Lock = threading.Lock()
+ def __init__(self, message: str, *, exited_pid: int | None = None) -> None:
+ super().__init__(message)
+ # Set only when the process exited on its own: the evidence a resource
+ # pressure diagnosis may consume. A process Avibe stopped for timeout is
+ # not that evidence.
+ self.exited_pid = exited_pid
- def __init__(
- self,
- binary: str = "opencode",
- port: int = DEFAULT_OPENCODE_PORT,
- request_timeout_seconds: int = 60,
- resource_governor: Any | None = None,
- ):
- self.binary = binary
- self.port = port
- self.request_timeout_seconds = request_timeout_seconds
- self.resource_governor = resource_governor
- self.host = DEFAULT_OPENCODE_HOST
- self._process: Optional[Process] = None
- self._last_start_failure_pid: int | None = None
- self._start_attempt_generation = 0
- # The event loop ``_process`` was created on. Subprocess transports
- # bind their internal Future / wait helpers to the creating loop;
- # ``process.wait()`` from a different loop raises ``RuntimeError: got
- # Future attached to a different loop``. The singleton outlives
- # ``asyncio.run`` calls (Flask UI server creates a new loop per
- # request), so any code that touches ``_process`` from a
- # non-creating loop has to detach it first. ``_process_loop`` is set
- # alongside every ``_process`` assignment.
- self._process_loop: Optional[asyncio.AbstractEventLoop] = None
- self._base_url: Optional[str] = None
- self._http_session: Optional[aiohttp.ClientSession] = None
- self._http_session_loop: Optional[asyncio.AbstractEventLoop] = None
- self._lock: Optional[asyncio.Lock] = None
- self._lock_loop: Optional[asyncio.AbstractEventLoop] = None
- self._pid_file = paths.get_logs_dir() / "opencode_server.json"
- self._active_requests = 0
- self._active_run_sessions: set[str] = set()
- self._active_poll_session_ids_provider: Callable[[], set[str]] | None = None
- self._auth_refresh_pending = False
- self._auth_refresh_pending_port: Optional[int] = None
- self._caller_context_plugin_refresh_pending = False
- self._pending_runtime_config: Optional[tuple[str, int, int]] = None
- self._last_prompt_started_at: dict[str, float] = {}
- self._model_hub_overlay_path: Optional[str] = None
- self._model_hub_overlay_hash: Optional[str] = None
- self._model_hub_overlay_content: Optional[str] = None
- self._model_hub_overlay_provider_ids: tuple[str, ...] = ()
- self._model_hub_overlay_preparer: (
- Callable[[], Awaitable[Any | None]] | None
- ) = None
- self._model_hub_overlay_refusal_logged = False
- self._model_hub_overlay_transition: tuple[
- Optional[str], Optional[str], object
- ] | None = None
- self._model_hub_overlay_reservations: dict[
- object, tuple[Optional[str], Optional[str]]
- ] = {}
- self._model_hub_overlay_drain_timeout_seconds = MODEL_HUB_OVERLAY_DRAIN_TIMEOUT_SECONDS
- self._runtime_activation_retire: Callable[[bool, bool], bool] | None = None
- self._runtime_generation_token: tuple[int, float | None] | None = None
- self._observed_runtime_process: tuple[int, float] | None = None
-
- def set_runtime_activation_retire(
- self,
- callback: Callable[[bool, bool], bool],
- ) -> None:
- self._runtime_activation_retire = callback
- def set_active_poll_session_ids_provider(
- self,
- provider: Callable[[], set[str]],
- ) -> None:
- """Attach the durable recovery records that confirm adopted run markers."""
+def generation_records_dir() -> Path:
+ """Where each generation's process record lives."""
- self._active_poll_session_ids_provider = provider
+ return paths.get_runtime_dir() / "opencode" / "generations"
- @staticmethod
- def _runtime_token_from_pid_info(
- info: Optional[Dict[str, Any]],
- ) -> tuple[int, float | None] | None:
- if not isinstance(info, dict):
- return None
- pid = info.get("pid")
- if not isinstance(pid, int):
- return None
- started_at = info.get("started_at")
- return (
- pid,
- float(started_at) if isinstance(started_at, (int, float)) else None,
- )
- def _retire_runtime_generation_for_replacement(self) -> None:
- retire_activation = self._runtime_activation_retire
- if callable(retire_activation) and not retire_activation(True, False):
- raise RuntimeError(
- "OpenCode runtime replacement could not retire its activation generation"
- )
- self._runtime_generation_token = None
- self._observed_runtime_process = None
+def legacy_pid_file() -> Path:
+ """The single-server record every release before generations wrote."""
- def _observe_runtime_generation(
- self,
- info: Optional[Dict[str, Any]] = None,
- ) -> None:
- if info is None:
- info = self._read_pid_file()
- token = self._runtime_token_from_pid_info(info)
- if token is None:
- return
- previous = self._runtime_generation_token
- if previous is not None and previous != token:
- self._retire_runtime_generation_for_replacement()
- self._runtime_generation_token = token
- if previous != token:
- self._last_start_failure_pid = None
- if previous != token or self._observed_runtime_process is None:
- created_at = runtime.process_create_time(token[0])
- self._observed_runtime_process = (
- (token[0], created_at) if created_at is not None else None
- )
+ return paths.get_logs_dir() / "opencode_server.json"
- def observed_runtime_exit_pid(self) -> int | None:
- """Return only an observed server generation that has since exited."""
- identity = self._observed_runtime_process
- if identity is None:
- return None
- pid, created_at = identity
- current_created_at = runtime.process_create_time(pid)
- if current_created_at == created_at or (
- current_created_at is None and self._pid_exists(pid)
+def _pid_exists(pid: int) -> bool:
+ return runtime.pid_alive(pid)
+
+
+def _get_pid_command(pid: int) -> Optional[str]:
+ return runtime.get_process_command(pid)
+
+
+def _is_opencode_serve_cmd(command: str, port: int) -> bool:
+ if not command:
+ return False
+ return "opencode" in command and " serve" in command and f"--port={port}" in command
+
+
+def _pid_listens_on(pid: int, port: int) -> bool:
+ """Whether ``pid``, or a process it started, holds the listening socket on ``port``.
+
+ A launcher such as an npm shim or a Windows ``.cmd`` wrapper starts the
+ server as its child, so the listener can belong to a descendant.
+ """
+
+ try:
+ root = psutil.Process(pid)
+ processes = [root, *root.children(recursive=True)]
+ except psutil.Error:
+ return False
+ for process in processes:
+ try:
+ connections = process.net_connections(kind="tcp")
+ except psutil.Error:
+ continue
+ if any(
+ connection.status == psutil.CONN_LISTEN
+ and connection.laddr
+ and connection.laddr.port == port
+ for connection in connections
):
- return None
- return pid
+ return True
+ return False
- def _pid_file_proves_owned_server(self, info: Optional[Dict[str, Any]]) -> bool:
- if not isinstance(info, dict):
- return False
- pid = info.get("pid")
- created_at = info.get("process_created_at")
- if not isinstance(pid, int) or not isinstance(created_at, (int, float)):
- return False
- if isinstance(created_at, bool) or created_at <= 0:
- return False
- if not self._pid_file_references_current_server(info):
- return False
- return runtime.process_create_time(pid) == float(created_at)
- def _terminate_owned_adopted_server_sync(
- self, pid: int, info: Dict[str, Any]
- ) -> bool:
- if not self._pid_file_proves_owned_server(info):
- raise RuntimeError("OpenCode server ownership cannot be proven")
- return self._terminate_pid_tree_sync(pid)
+def _choose_port(host: str) -> int:
+ # ``opencode serve --port=0`` listens on its default 4096 rather than an
+ # ephemeral port, so the port is chosen here. Another process can take it
+ # before OpenCode binds; the start then sees its own process exit and
+ # retries with another port.
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind((host, 0))
+ return int(sock.getsockname()[1])
- def _caller_context_path(self) -> str:
- return server_environment()["AVIBE_OPENCODE_CALLER_CONTEXT_PATH"]
- def caller_context_binding_path(self) -> Path:
- info = self._read_pid_file()
- recorded = info.get("caller_context_path") if isinstance(info, dict) else None
- if isinstance(recorded, str) and recorded and os.path.isabs(recorded):
- return Path(recorded)
- return Path(self._caller_context_path())
+class OpenCodeServerClient:
+ """The HTTP API of one ``opencode serve`` process at ``base_url``."""
+
+ def __init__(
+ self,
+ base_url: str,
+ *,
+ request_timeout_seconds: int = 60,
+ model_hub_provider_ids: tuple[str, ...] = (),
+ ) -> None:
+ self.base_url = base_url
+ self.request_timeout_seconds = request_timeout_seconds
+ # Private Hub transport providers of the process behind ``base_url``;
+ # user-facing catalogs never show them.
+ self.model_hub_provider_ids = tuple(model_hub_provider_ids)
+ self._http_session: Optional[aiohttp.ClientSession] = None
+ self._http_session_loop: Optional[asyncio.AbstractEventLoop] = None
+ self._lock: Optional[asyncio.Lock] = None
+ self._lock_loop: Optional[asyncio.AbstractEventLoop] = None
+ self._active_requests = 0
+ self._last_prompt_started_at: dict[str, float] = {}
+ # The event-loop time a lease on this process expires, for a client in
+ # another process than the controller. No request starts that its
+ # timeout could carry past it, so the process never stops under one.
+ self.lease_expires_at: Optional[float] = None
def _get_lock(self) -> asyncio.Lock:
"""Get or create an asyncio.Lock bound to the current event loop."""
@@ -417,94 +367,21 @@ class OpenCodeServerManager:
self._lock_loop = current_loop
return self._lock
- def _maybe_update_resource_governor(self, resource_governor: Any | None) -> None:
- if resource_governor is None:
- return
- if is_controller_resource_governor(resource_governor) or not is_controller_resource_governor(
- self.resource_governor
- ):
- self.resource_governor = resource_governor
-
- def set_model_hub_overlay_preparer(
- self,
- preparer: Callable[[], Awaitable[Any | None]],
- ) -> None:
- """Attach the controller-owned overlay builder to this process."""
-
- self._model_hub_overlay_preparer = preparer
-
- @classmethod
- async def get_instance(
- cls,
- binary: str = "opencode",
- port: int = DEFAULT_OPENCODE_PORT,
- request_timeout_seconds: int = 60,
- resource_governor: Any | None = None,
- ) -> "OpenCodeServerManager":
- with cls._class_lock:
- if cls._instance is None:
- cls._instance = cls(
- binary=binary,
- port=port,
- request_timeout_seconds=request_timeout_seconds,
- resource_governor=resource_governor,
- )
- return cls._instance
- cls._instance._maybe_update_resource_governor(resource_governor)
- if (
- cls._instance.binary != binary
- or cls._instance.port != port
- or cls._instance.request_timeout_seconds != request_timeout_seconds
- ):
- logger.warning(
- "OpenCodeServerManager already initialized with "
- f"binary={cls._instance.binary}, port={cls._instance.port}, "
- f"request_timeout_seconds={cls._instance.request_timeout_seconds}; "
- f"ignoring new params binary={binary}, port={port}, "
- f"request_timeout_seconds={request_timeout_seconds}"
- )
- return cls._instance
-
- @classmethod
- async def get_instance_if_managed_server_exists(
- cls,
- binary: str = "opencode",
- port: int = DEFAULT_OPENCODE_PORT,
- request_timeout_seconds: int = 60,
- resource_governor: Any | None = None,
- ) -> Optional["OpenCodeServerManager"]:
- with cls._class_lock:
- if cls._instance is not None:
- cls._instance._maybe_update_resource_governor(resource_governor)
- return cls._instance
-
- pid_file = paths.get_logs_dir() / "opencode_server.json"
- try:
- data = json.loads(pid_file.read_text())
- except Exception:
- return None
- if not isinstance(data, dict) or data.get("port") != port:
- return None
- pid = data.get("pid")
- if not isinstance(pid, int) or not runtime.pid_alive(pid):
- return None
- command = runtime.get_process_command(pid)
- if not command or not cls._is_opencode_serve_cmd(command, port):
- return None
-
- cls._instance = cls(
- binary=binary,
- port=port,
- request_timeout_seconds=request_timeout_seconds,
- resource_governor=resource_governor,
- )
- return cls._instance
+ def _active_model_hub_provider_ids(self) -> tuple[str, ...]:
+ return self.model_hub_provider_ids
- @property
- def base_url(self) -> str:
- if self._base_url:
- return self._base_url
- return f"http://{self.host}:{self.port}"
+ @asynccontextmanager
+ async def _request_scope(self):
+ if (
+ self.lease_expires_at is not None
+ and asyncio.get_running_loop().time() + self.request_timeout_seconds > self.lease_expires_at
+ ):
+ raise TimeoutError(f"The OpenCode lease on {self.base_url} ends before this request could")
+ self._active_requests += 1
+ try:
+ yield
+ finally:
+ self._active_requests = max(0, self._active_requests - 1)
@staticmethod
def _normalize_variant(reasoning_effort: Optional[str]) -> Optional[str]:
@@ -547,666 +424,6 @@ class OpenCodeServerManager:
return
await self._close_http_session_locked()
- async def retire_for_native_migration(self) -> None:
- """Strictly stop our tracked server, never an arbitrary port occupant."""
- from core.backend_restart import finish_native_operation
-
- async with self._get_lock():
- if self._active_requests or self._has_active_run_sessions():
- raise RuntimeError("OpenCode runtime is busy")
- process = self._process
- info = self._read_pid_file()
- recorded_pid = info.get("pid") if isinstance(info, dict) else None
- if process is None and isinstance(recorded_pid, int) and self._pid_exists(recorded_pid):
- # A command/port match alone can belong to a reused PID.
- if not self._pid_file_proves_owned_server(info):
- raise RuntimeError("OpenCode server ownership cannot be proven")
- retire = self._runtime_activation_retire
- if callable(retire) and not retire(False, True):
- raise RuntimeError("OpenCode runtime retirement was refused")
- if process is None and isinstance(recorded_pid, int) and self._pid_exists(recorded_pid):
- if not await finish_native_operation(
- asyncio.to_thread(
- self._terminate_owned_adopted_server_sync,
- recorded_pid,
- info,
- )
- ) or self._pid_exists(recorded_pid):
- raise RuntimeError("OpenCode server did not exit")
- if process is not None and process.returncode is None:
- if not await finish_native_operation(
- asyncio.to_thread(self._terminate_pid_tree_sync, process.pid)
- ):
- raise RuntimeError("OpenCode server did not exit")
- await asyncio.wait_for(process.wait(), timeout=5)
- if process.returncode is None:
- raise RuntimeError("OpenCode server did not exit")
- await self._close_http_session_locked()
- self._clear_pid_file()
- self._process = None
- self._process_loop = None
- self._base_url = None
- self._runtime_generation_token = None
- self._observed_runtime_process = None
- self._auth_refresh_pending = False
- self._auth_refresh_pending_port = None
- self._apply_pending_runtime_config_locked()
-
- async def _restart_for_auth_refresh_locked(
- self,
- *,
- force: bool = False,
- native_turns_drained: bool = False,
- ) -> None:
- retire_activation = self._runtime_activation_retire
- if callable(retire_activation) and not retire_activation(
- force,
- native_turns_drained,
- ):
- self._auth_refresh_pending = True
- raise RuntimeError(
- "OpenCode runtime restart is blocked by a newly admitted owner"
- )
- await self._close_http_session_locked()
-
- cleanup_port = self._auth_refresh_pending_port or self.port
- targets: list[int] = []
- info = self._read_pid_file()
- pid = info.get("pid") if isinstance(info, dict) else None
- if isinstance(pid, int) and self._pid_exists(pid):
- cmd = self._get_pid_command(pid)
- if cmd and self._is_opencode_serve_cmd(cmd, cleanup_port):
- targets.append(pid)
- elif (
- isinstance(info, dict)
- and info.get("port") == cleanup_port
- and self._pid_owns_listening_port(pid, cleanup_port)
- ):
- logger.info(
- "Trusting OpenCode pid file for pid=%s because it still owns port %s",
- pid,
- cleanup_port,
- )
- targets.append(pid)
-
- if not targets:
- for candidate in self._find_opencode_serve_pids(cleanup_port):
- cmd = self._get_pid_command(candidate)
- if cmd and self._is_opencode_serve_cmd(cmd, cleanup_port):
- targets.append(candidate)
-
- for target_pid in dict.fromkeys(targets):
- await self._terminate_pid(target_pid, reason="auth refresh")
-
- self._clear_pid_file()
- self._process = None
- self._process_loop = None
- self._base_url = None
- self._runtime_generation_token = None
- self._observed_runtime_process = None
- self._auth_refresh_pending = False
- self._auth_refresh_pending_port = None
- self._apply_pending_runtime_config_locked()
-
- async def detach_after_deferred_refresh(self, *, force: bool = False) -> None:
- """Drop cached client state when a refresh must wait for active runs."""
- async with self._get_lock():
- if force:
- self._active_run_sessions.clear()
- if not force and (self._active_requests > 0 or self._has_active_run_sessions()):
- self._auth_refresh_pending = True
- self._auth_refresh_pending_port = self.port
- logger.info(
- "Deferring OpenCode runtime detach until %s active request(s) and %s active run(s) finish",
- self._active_requests,
- len(self._active_run_sessions),
- )
- return
- await self._restart_for_auth_refresh_locked(force=force)
-
- async def refresh_global_config(self) -> bool:
- """Ask a live OpenCode server to reload global opencode.json config.
-
- OpenCode's HTTP API applies ``PATCH /global/config`` to the
- global config and disposes its cached instances, which refreshes
- provider options without terminating the shared ``opencode serve``
- process. Return ``False`` when the endpoint is unavailable so
- callers can fall back to a process restart.
- """
-
- config = self._load_opencode_user_config()
- if config is None:
- return False
-
- total_timeout: Optional[int] = None if self.request_timeout_seconds <= 0 else self.request_timeout_seconds
- async with self._get_lock():
- if self._active_requests > 0 or self._has_active_run_sessions():
- return False
- if not await self._is_healthy():
- return False
- current_config = await self._get_global_config_snapshot()
- if current_config is None:
- return False
- config = self._merge_global_config_snapshot(current_config, config)
- async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=total_timeout)) as session:
- async with session.patch(
- f"{self.base_url}/global/config",
- json=config,
- ) as resp:
- if resp.status == 200:
- await resp.read()
- return True
- if resp.status in (404, 405):
- await resp.read()
- return False
- error_text = await resp.text()
- raise RuntimeError(
- f"Failed to refresh OpenCode global config: {resp.status} {error_text}"
- )
- return False
-
- async def reload_runtime_config(
- self,
- *,
- binary: str,
- port: int,
- request_timeout_seconds: int,
- ) -> None:
- async with self._get_lock():
- if self._auth_refresh_pending:
- self._pending_runtime_config = (binary, port, request_timeout_seconds)
- return
- self._set_runtime_config(binary, port, request_timeout_seconds)
-
- def _set_runtime_config(self, binary: str, port: int, request_timeout_seconds: int) -> None:
- self.binary = binary
- self.port = port
- self.request_timeout_seconds = request_timeout_seconds
-
- def _apply_pending_runtime_config_locked(self) -> None:
- if self._pending_runtime_config is None:
- return
- self._set_runtime_config(*self._pending_runtime_config)
- self._pending_runtime_config = None
-
- def _has_active_run_sessions(self) -> bool:
- return bool(self._active_run_sessions)
-
- def _reconcile_adopted_active_run_sessions(
- self,
- info: Optional[Dict[str, Any]],
- ) -> Optional[Dict[str, Any]]:
- """Discard adopted pre-write markers that have no durable recovery poll."""
-
- if self._active_run_sessions or not self._pid_file_references_current_server(info):
- return info
- active = info.get("active_run_sessions") if isinstance(info, dict) else None
- if not isinstance(active, list) or not active:
- return info
- if any(not isinstance(item, str) or not item for item in active):
- return info
- provider = self._active_poll_session_ids_provider
- if provider is None:
- return info
- try:
- durable = provider()
- except Exception:
- logger.warning(
- "Could not reconcile adopted OpenCode run markers with durable polls",
- exc_info=True,
- )
- return info
- if any(not isinstance(item, str) or not item for item in durable):
- logger.warning("Ignoring invalid OpenCode durable active-poll identifiers")
- return info
-
- retained = set(active).intersection(durable)
- revised = dict(info)
- revised["active_run_sessions"] = sorted(retained)
- if retained != set(active):
- try:
- write_atomic(self._pid_file, json.dumps(revised))
- except Exception:
- logger.warning(
- "Could not persist reconciled OpenCode run markers",
- exc_info=True,
- )
- return info
- logger.info(
- "Removed %s orphaned OpenCode run marker(s) without durable polls",
- len(set(active) - retained),
- )
- self._active_run_sessions = retained
- return revised
-
- def runtime_has_active_turns(self) -> bool:
- if self._active_requests > 0 or self._has_active_run_sessions():
- return True
- info = self._read_pid_file()
- if not self._pid_file_references_current_server(info):
- return False
- pid = info.get("pid") if isinstance(info, dict) else None
- if not isinstance(pid, int) or not self._pid_exists(pid):
- return False
- active = info.get("active_run_sessions") if isinstance(info, dict) else None
- return isinstance(active, list) and bool(active)
-
- def _active_model_hub_provider_ids(self) -> tuple[str, ...]:
- if self._model_hub_overlay_provider_ids:
- return self._model_hub_overlay_provider_ids
- info = self._read_pid_file()
- if not self._pid_file_references_current_server(info):
- return ()
- provider_ids = (
- info.get("model_hub_overlay_provider_ids")
- if isinstance(info, dict)
- else ()
- )
- if not isinstance(provider_ids, list) or any(
- not isinstance(provider_id, str) or not provider_id
- for provider_id in provider_ids
- ):
- return ()
- return tuple(dict.fromkeys(provider_ids))
-
- def _configured_model_hub_overlay(self) -> bool:
- return bool(
- self._model_hub_overlay_path
- and self._model_hub_overlay_hash
- and self._model_hub_overlay_content
- and self._model_hub_overlay_provider_ids
- )
-
- @staticmethod
- def _model_hub_mode_enabled() -> bool:
- if not is_model_hub_enabled():
- return False
- return V2Config.load().model_hub.agents["opencode"].mode == "hub"
-
- def _refuse_unconfigured_model_hub_launch(self) -> None:
- message = (
- "OpenCode cannot be launched in Gateway mode without the Model Hub "
- "overlay; the controller owns overlay configuration"
- )
- if not self._model_hub_overlay_refusal_logged:
- logger.error(message)
- self._model_hub_overlay_refusal_logged = True
- raise OpenCodeModelHubOverlayRequiredError(message)
-
- async def _start_server_for_current_model_hub_mode_locked(self) -> None:
- # Known by design: a settings PATCH may commit while the OS spawn is in
- # progress. Reading here bounds that cross-process race to the spawn;
- # the next controller Hub use configures the overlay and restarts any
- # unoverlaid server through the normal overlay-change path.
- if self._model_hub_mode_enabled() and (
- not is_controller_resource_governor(self.resource_governor)
- or not self._configured_model_hub_overlay()
- ):
- self._refuse_unconfigured_model_hub_launch()
- await self._start_server()
-
- async def _prepare_model_hub_launch_boundary(self) -> object | None:
- hub_mode = self._model_hub_mode_enabled()
- if not hub_mode:
- self._model_hub_overlay_refusal_logged = False
- if (
- is_controller_resource_governor(self.resource_governor)
- and self._configured_model_hub_overlay()
- and not self._model_hub_overlay_reservations
- ):
- return await self.configure_model_hub_overlay(None)
- return None
-
- if not is_controller_resource_governor(self.resource_governor):
- self._refuse_unconfigured_model_hub_launch()
- if self._model_hub_overlay_reservations:
- if not self._configured_model_hub_overlay():
- self._refuse_unconfigured_model_hub_launch()
- return None
-
- preparer = self._model_hub_overlay_preparer
- if not callable(preparer):
- self._refuse_unconfigured_model_hub_launch()
- overlay = await preparer()
- if overlay is None:
- self._refuse_unconfigured_model_hub_launch()
- return await self.configure_model_hub_overlay(overlay)
-
- async def configure_model_hub_overlay(self, overlay: Any | None) -> object:
- """Select an overlay and reserve it until the caller registers its run."""
-
- desired_path = str(overlay.path) if overlay is not None else None
- desired_hash = str(overlay.content_hash) if overlay is not None else None
- desired_provider_ids = getattr(overlay, "provider_ids", ())
- if overlay is not None and (
- not isinstance(desired_provider_ids, tuple)
- or not desired_provider_ids
- or any(
- not isinstance(provider_id, str) or not provider_id
- for provider_id in desired_provider_ids
- )
- or len(set(desired_provider_ids)) != len(desired_provider_ids)
- ):
- raise RuntimeError("Model Hub OpenCode overlay providers are unavailable")
- desired_content = None
- if overlay is not None:
- content = getattr(overlay, "content", None)
- if isinstance(content, bytes):
- desired_content = _managed_runtime_config_content(content)
- elif isinstance(content, str):
- desired_content = _managed_runtime_config_content(content)
- if desired_content is None:
- raise RuntimeError("Model Hub OpenCode overlay content is unavailable")
- composed_hash = hashlib.sha256(desired_content.encode()).hexdigest()
- if composed_hash != desired_hash:
- raise RuntimeError("Model Hub OpenCode overlay content hash changed")
- self._model_hub_overlay_refusal_logged = False
- drain_deadline = time.monotonic() + self._model_hub_overlay_drain_timeout_seconds
- transition_owner = object()
- owns_transition = False
- try:
- while True:
- should_wait = False
- async with self._get_lock():
- transition = self._model_hub_overlay_transition
- if transition is not None and transition[2] is not transition_owner:
- # Once a real configuration change is queued, new turns on
- # the old overlay must wait. Otherwise they can continuously
- # replenish the active set and starve the transition.
- should_wait = True
- else:
- info = self._read_pid_file() or {}
- current_server = self._pid_file_references_current_server(info)
- effective_path = (
- info.get("model_hub_overlay_path") if current_server else None
- )
- effective_hash = (
- info.get("model_hub_overlay_hash") if current_server else None
- )
- if effective_path is None and effective_hash is None:
- effective_path = self._model_hub_overlay_path
- effective_hash = self._model_hub_overlay_hash
-
- # Most turns reuse the running server's overlay. They must
- # not wait behind unrelated active work when no transition
- # has claimed the runtime.
- if (effective_path, effective_hash) == (
- desired_path,
- desired_hash,
- ):
- self._model_hub_overlay_path = desired_path
- self._model_hub_overlay_hash = desired_hash
- self._model_hub_overlay_content = desired_content
- self._model_hub_overlay_provider_ids = desired_provider_ids
- self._model_hub_overlay_reservations[transition_owner] = (
- desired_path,
- desired_hash,
- )
- return transition_owner
-
- if not owns_transition:
- self._model_hub_overlay_transition = (
- desired_path,
- desired_hash,
- transition_owner,
- )
- owns_transition = True
-
- if (
- self._active_requests > 0
- or self._has_active_run_sessions()
- or self._model_hub_overlay_reservations
- ):
- should_wait = True
- else:
- persisted_active = current_server and bool(
- info.get("active_run_sessions")
- )
- if persisted_active and time.monotonic() < drain_deadline:
- should_wait = True
- else:
- if persisted_active:
- logger.warning(
- "Ignoring stale OpenCode active-run metadata after %.1fs overlay drain timeout",
- self._model_hub_overlay_drain_timeout_seconds,
- )
- self._model_hub_overlay_path = desired_path
- self._model_hub_overlay_hash = desired_hash
- self._model_hub_overlay_content = desired_content
- self._model_hub_overlay_provider_ids = desired_provider_ids
- if await self._is_healthy():
- logger.info(
- "Restarting OpenCode server after Model Hub overlay change"
- )
- await self._restart_for_auth_refresh_locked(
- native_turns_drained=True,
- )
- self._model_hub_overlay_reservations[
- transition_owner
- ] = (desired_path, desired_hash)
- self._model_hub_overlay_transition = None
- owns_transition = False
- return transition_owner
- if should_wait:
- await asyncio.sleep(0.05)
- finally:
- if owns_transition:
- async with self._get_lock():
- transition = self._model_hub_overlay_transition
- if transition is not None and transition[2] is transition_owner:
- self._model_hub_overlay_transition = None
-
- async def release_model_hub_overlay_reservation(
- self,
- reservation: object,
- ) -> None:
- async with self._get_lock():
- self._model_hub_overlay_reservations.pop(reservation, None)
-
- async def mark_run_active(
- self,
- session_id: str,
- *,
- overlay_reservation: object | None = None,
- ) -> None:
- async with self._get_lock():
- reserved_overlay = None
- if overlay_reservation is not None:
- reserved_overlay = self._model_hub_overlay_reservations.get(
- overlay_reservation
- )
- if reserved_overlay is None:
- raise RuntimeError("OpenCode overlay reservation is no longer active")
- previous_active_runs = set(self._active_run_sessions)
- if overlay_reservation is not None:
- self._model_hub_overlay_reservations.pop(
- overlay_reservation,
- None,
- )
- try:
- self._active_run_sessions = self._persist_active_run_session_change(
- session_id,
- active=True,
- )
- except Exception:
- self._active_run_sessions = previous_active_runs
- if overlay_reservation is not None and reserved_overlay is not None:
- self._model_hub_overlay_reservations[
- overlay_reservation
- ] = reserved_overlay
- raise
-
- async def mark_run_inactive(self, session_id: str) -> None:
- async with self._get_lock():
- previous_active_runs = set(self._active_run_sessions)
- try:
- self._active_run_sessions = self._persist_active_run_session_change(
- session_id,
- active=False,
- )
- except Exception:
- self._active_run_sessions = previous_active_runs
- raise
-
- @asynccontextmanager
- async def _request_scope(self):
- async with self._get_lock():
- if self._auth_refresh_pending and self._active_requests == 0 and not self._has_active_run_sessions():
- await self._restart_for_auth_refresh_locked()
- self._active_requests += 1
- try:
- yield
- finally:
- async with self._get_lock():
- self._active_requests = max(0, self._active_requests - 1)
-
- def _read_pid_file(self) -> Optional[Dict[str, Any]]:
- try:
- raw = self._pid_file.read_text()
- except FileNotFoundError:
- return None
- except Exception as e:
- logger.debug(f"Failed to read OpenCode pid file: {e}")
- return None
-
- try:
- data = json.loads(raw)
- except Exception as e:
- logger.debug(f"Failed to parse OpenCode pid file: {e}")
- return None
-
- return data if isinstance(data, dict) else None
-
- def _write_pid_file(
- self,
- pid: int,
- *,
- caller_context_path: object = _USE_CURRENT_CALLER_CONTEXT_PATH,
- owner_pid: Optional[int] = _CURRENT_OWNER_PID,
- runtime_policy_revision: Optional[str] = _MANAGED_RUNTIME_POLICY_REVISION,
- process_created_at: float | None = None,
- ) -> None:
- try:
- self._pid_file.parent.mkdir(parents=True, exist_ok=True)
- payload = {
- "pid": pid,
- "port": self.port,
- "host": self.host,
- "started_at": time.time(),
- "active_run_sessions": sorted(self._active_run_sessions),
- }
- if owner_pid is not None:
- payload["owner_pid"] = owner_pid
- if process_created_at is not None:
- payload["process_created_at"] = process_created_at
- if runtime_policy_revision is not None:
- payload["runtime_policy_revision"] = runtime_policy_revision
- if caller_context_path is _USE_CURRENT_CALLER_CONTEXT_PATH:
- caller_context_path = self._caller_context_path()
- if isinstance(caller_context_path, str) and caller_context_path:
- payload["caller_context_path"] = caller_context_path
- if self._model_hub_overlay_path and self._model_hub_overlay_hash:
- payload["model_hub_overlay_path"] = self._model_hub_overlay_path
- payload["model_hub_overlay_hash"] = self._model_hub_overlay_hash
- if self._model_hub_overlay_provider_ids:
- payload["model_hub_overlay_provider_ids"] = list(
- self._model_hub_overlay_provider_ids
- )
- write_atomic(self._pid_file, json.dumps(payload))
- except Exception as e:
- logger.debug(f"Failed to write OpenCode pid file: {e}")
-
- def _apply_resource_governance(self, pid: int | None) -> None:
- governor = getattr(self, "resource_governor", None)
- apply_to_pid = getattr(governor, "apply_to_pid", None)
- if callable(apply_to_pid):
- apply_to_pid(pid, label="opencode serve")
-
- def _persist_active_run_session_change(
- self,
- session_id: str,
- *,
- active: bool,
- ) -> set[str]:
- try:
- raw_info = self._pid_file.read_text()
- except FileNotFoundError:
- info = None
- except Exception as exc:
- raise RuntimeError("Could not read OpenCode active-run metadata") from exc
- else:
- try:
- info = json.loads(raw_info)
- except (TypeError, ValueError) as exc:
- raise RuntimeError("OpenCode active-run metadata is invalid") from exc
- if not isinstance(info, dict):
- raise RuntimeError("OpenCode active-run metadata is invalid")
-
- updated = set(self._active_run_sessions)
- references_current_server = self._pid_file_references_current_server(info)
- if references_current_server:
- assert isinstance(info, dict)
- persisted = info.get("active_run_sessions")
- if not isinstance(persisted, list) or any(
- not isinstance(item, str) or not item for item in persisted
- ):
- raise RuntimeError("OpenCode active-run metadata is invalid")
- updated.update(persisted)
-
- if active:
- updated.add(session_id)
- else:
- updated.discard(session_id)
-
- if references_current_server:
- assert isinstance(info, dict)
- info["active_run_sessions"] = sorted(updated)
- write_atomic(self._pid_file, json.dumps(info))
- return updated
-
- def _clear_pid_file(self) -> None:
- try:
- if self._pid_file.exists():
- self._pid_file.unlink()
- except Exception as e:
- logger.debug(f"Failed to clear OpenCode pid file: {e}")
-
- def _pid_file_references_current_server(self, info: Optional[Dict[str, Any]]) -> bool:
- if not isinstance(info, dict):
- return False
- pid = info.get("pid")
- if not isinstance(pid, int):
- return False
- if info.get("port") != self.port:
- return False
- cmd = self._get_pid_command(pid)
- if cmd:
- return self._is_opencode_serve_cmd(cmd, self.port)
- if self._pid_owns_listening_port(pid, self.port):
- return True
- return False
-
- def _pid_file_has_caller_context_binding(self, info: Optional[Dict[str, Any]]) -> bool:
- if not self._pid_file_references_current_server(info):
- return False
- recorded = info.get("caller_context_path") if isinstance(info, dict) else None
- return bool(isinstance(recorded, str) and recorded and os.path.isabs(recorded))
-
- def _pid_file_has_current_runtime_policy(self, info: Optional[Dict[str, Any]]) -> bool:
- return bool(
- self._pid_file_references_current_server(info)
- and isinstance(info, dict)
- and info.get("runtime_policy_revision") == _MANAGED_RUNTIME_POLICY_REVISION
- )
-
- def _pid_file_was_started_by_current_process(self, info: Optional[Dict[str, Any]]) -> bool:
- return bool(isinstance(info, dict) and info.get("owner_pid") == _CURRENT_OWNER_PID)
-
- @staticmethod
- def _pid_file_has_known_no_active_runs(info: Optional[Dict[str, Any]]) -> bool:
- active = info.get("active_run_sessions") if isinstance(info, dict) else None
- return isinstance(active, list) and not active
-
@staticmethod
def _extract_json_object(text: str, start: int) -> Optional[str]:
if start < 0 or start >= len(text) or text[start] != "{":
@@ -1415,10 +632,10 @@ class OpenCodeServerManager:
if isinstance(error, dict):
message = error.get("message")
if isinstance(message, str) and message.strip():
- return OpenCodeServerManager._redact_diagnostic_text(message.strip())[:240]
+ return OpenCodeServerClient._redact_diagnostic_text(message.strip())[:240]
message = payload.get("message")
if isinstance(message, str) and message.strip():
- return OpenCodeServerManager._redact_diagnostic_text(message.strip())[:240]
+ return OpenCodeServerClient._redact_diagnostic_text(message.strip())[:240]
return ""
@staticmethod
@@ -1514,694 +731,45 @@ class OpenCodeServerManager:
method="POST",
)
for key, value in headers.items():
- request.add_header(key, value)
- try:
- with urllib.request.urlopen(request, timeout=12) as response:
- content_type = response.headers.get("content-type", "")
- raw = response.read(2048).decode(errors="replace")
- if "text/html" in content_type.lower() or raw.lstrip().lower().startswith("<!doctype html"):
- return (
- f"Provider Base URL {self._safe_url(base_url)} returned an HTML page instead of an API "
- f"response; use the API base path, usually {self._suggest_api_base_url(base_url)}."
- )
- return None
- except urllib.error.HTTPError as err:
- content_type = err.headers.get("content-type", "")
- raw = err.read(2048).decode(errors="replace")
- if "text/html" in content_type.lower() or raw.lstrip().lower().startswith("<!doctype html"):
- return (
- f"Provider Base URL {self._safe_url(base_url)} returned an HTML page instead of an API "
- f"response; use the API base path, usually {self._suggest_api_base_url(base_url)}."
- )
- try:
- payload = json.loads(raw)
- except Exception:
- payload = {}
- message = self._diagnostic_payload_message(payload)
- if message:
- return f"Provider API returned HTTP {err.code}: {message}"
- return f"Provider API returned HTTP {err.code}."
- except urllib.error.URLError as err:
- reason = self._redact_diagnostic_text(str(err.reason or err))
- return f"Provider API request failed: {reason[:240]}"
- except (TimeoutError, OSError) as err:
- reason = self._redact_diagnostic_text(str(err))
- return f"Provider API request failed: {reason[:240] or type(err).__name__}"
- except Exception as err:
- logger.debug("OpenCode provider API diagnostic failed for %s/%s: %s", provider_id, model_id, err)
- return None
-
- async def get_provider_api_diagnostic(self, provider_id: str, model_id: str) -> Optional[str]:
- return await asyncio.to_thread(self._provider_api_diagnostic_sync, provider_id, model_id)
-
- @staticmethod
- def _pid_exists(pid: int) -> bool:
- return runtime.pid_alive(pid)
-
- @staticmethod
- def _get_pid_command(pid: int) -> Optional[str]:
- return runtime.get_process_command(pid)
-
- @staticmethod
- def _is_opencode_serve_cmd(command: str, port: int) -> bool:
- if not command:
- return False
- return "opencode" in command and " serve" in command and f"--port={port}" in command
-
- @staticmethod
- def _pid_owns_listening_port(pid: int, port: int) -> bool:
- if os.name == "nt" or pid <= 0:
- return False
-
- proc_fd_dir = f"/proc/{pid}/fd"
- try:
- fd_entries = os.listdir(proc_fd_dir)
- except OSError:
- return False
-
- inodes: set[str] = set()
- for entry in fd_entries:
- try:
- target = os.readlink(f"{proc_fd_dir}/{entry}")
- except OSError:
- continue
- if target.startswith("socket:[") and target.endswith("]"):
- inodes.add(target[8:-1])
-
- if not inodes:
- return False
-
- for table in ("/proc/net/tcp", "/proc/net/tcp6"):
- try:
- with open(table, encoding="utf-8") as handle:
- next(handle, None)
- for raw_line in handle:
- parts = raw_line.split()
- if len(parts) < 10:
- continue
- local_address = parts[1]
- state = parts[3]
- inode = parts[9]
- if state != "0A" or inode not in inodes:
- continue
- _, _, port_hex = local_address.rpartition(":")
- try:
- if int(port_hex, 16) == port:
- return True
- except ValueError:
- continue
- except OSError:
- continue
-
- return False
-
- def _is_port_available(self) -> bool:
- try:
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- sock.bind((self.host, self.port))
- return True
- except OSError:
- return False
-
- @staticmethod
- def _find_opencode_serve_pids(port: int) -> List[int]:
- if os.name == "nt":
- try:
- result = subprocess.run(
- ["netstat", "-ano", "-p", "tcp"],
- capture_output=True,
- text=True,
- check=False,
- )
- except Exception:
- return []
-
- pids: List[int] = []
- for line in (result.stdout or "").splitlines():
- parts = line.split()
- if len(parts) < 5 or parts[0].upper() != "TCP":
- continue
- local_addr = parts[1]
- state = parts[3].upper()
- pid_str = parts[4]
- if state != "LISTENING" or local_addr.rsplit(":", 1)[-1] != str(port):
- continue
- try:
- pid = int(pid_str)
- except ValueError:
- continue
- command = runtime.get_process_command(pid)
- if command and OpenCodeServerManager._is_opencode_serve_cmd(command, port):
- pids.append(pid)
- return pids
-
- try:
- result = subprocess.run(
- ["ps", "-ax", "-o", "pid=,command="],
- capture_output=True,
- text=True,
- check=False,
- )
- except Exception:
- return []
-
- needle = f"--port={port}"
- pids: List[int] = []
- for line in (result.stdout or "").splitlines():
- line = line.strip()
- if not line:
- continue
- parts = line.split(None, 1)
- if len(parts) != 2:
- continue
- pid_str, cmd = parts
- if "opencode" in cmd and " serve" in cmd and needle in cmd:
- try:
- pids.append(int(pid_str))
- except ValueError:
- continue
- return pids
-
- async def _terminate_pid(self, pid: int, reason: str) -> None:
- logger.info(f"Stopping OpenCode server pid={pid} ({reason})")
- stopped = await asyncio.to_thread(self._terminate_pid_tree_sync, pid)
- if not stopped and self._pid_exists(pid):
- logger.debug("Failed to terminate OpenCode server pid=%s", pid)
-
- async def _terminate_tracked_process(self, process: Process, reason: str) -> None:
- """Stop a server this loop started, then let its exit be reaped."""
- await self._terminate_pid(process.pid, reason=reason)
- try:
- await asyncio.wait_for(process.wait(), timeout=5)
- except asyncio.TimeoutError:
- logger.warning("OpenCode server pid=%s did not exit after it was stopped", process.pid)
-
- @staticmethod
- def _terminate_pid_tree_sync(pid: int, timeout: float = 5.0) -> bool:
- """Stop the OpenCode server and every process it started.
-
- OpenCode starts each tool command detached, as the leader of a new
- session and process group, so the server's own group never reaches it.
- Only a live parent ties a process to the server, so the tree is walked
- before anything is signalled and again before escalating. Every process
- is held as a ``psutil.Process``, which refuses a pid reused since.
- """
- if os.name == "nt":
- return runtime.stop_pid(pid, timeout=timeout)
- try:
- server = psutil.Process(pid)
- except psutil.NoSuchProcess:
- return True
- except psutil.Error:
- return not runtime.pid_alive(pid)
-
- def running(processes: list[psutil.Process]) -> list[psutil.Process]:
- alive = []
- for process in processes:
- try:
- # A zombie has exited; reaping it belongs to its parent.
- if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
- alive.append(process)
- except psutil.NoSuchProcess:
- continue
- except psutil.Error:
- alive.append(process)
- return alive
-
- own_group = os.getpgrp()
- founded_groups: set[int] = set()
- tree = [server]
- for sig in (signal.SIGTERM, signal.SIGKILL):
- found = dict.fromkeys(tree)
- for process in tree:
- try:
- found.update(dict.fromkeys(process.children(recursive=True)))
- except psutil.Error:
- continue
- tree = running(list(found))
- if not tree:
- return True
- groups = {}
- for process in tree:
- try:
- groups[process] = os.getpgid(process.pid)
- except OSError:
- continue
- # The caller's own group is the one carrying out this stop: ``vibe
- # stop`` run from an OpenCode tool sits inside the tree. It is never
- # signalled, nor waited for, so the stop can finish its own work.
- tree = [process for process in tree if groups.get(process) != own_group]
- if not tree:
- return True
- # A group is the tree's when a process of the tree founded it. It is
- # signalled only while a live process of the tree is still in it,
- # proof that its id was not recycled, and the group signal also
- # reaches whatever those processes started since the walk.
- founded_groups.update(process.pid for process, pgid in groups.items() if process.pid == pgid)
- owned_groups = (set(groups.values()) & founded_groups) - {own_group}
- if sig == signal.SIGKILL:
- logger.warning("Escalating to SIGKILL for %d process(es) of OpenCode server pid=%s", len(tree), pid)
- elif len(tree) > 1:
- logger.info("OpenCode server pid=%s has %d descendant process(es) to stop", pid, len(tree) - 1)
- signalled_groups = set()
- for pgid in owned_groups:
- try:
- os.killpg(pgid, sig)
- except ProcessLookupError:
- pass
- except OSError:
- # Fall back to signalling its known members one by one.
- continue
- signalled_groups.add(pgid)
- for process in tree:
- if groups.get(process) in signalled_groups:
- continue
- try:
- process.send_signal(sig)
- except psutil.NoSuchProcess:
- continue
- except psutil.Error:
- logger.debug("Failed to signal OpenCode process pid=%s", process.pid, exc_info=True)
- deadline = time.monotonic() + timeout
- tree = running(tree)
- while tree and time.monotonic() < deadline:
- time.sleep(0.1)
- tree = running(tree)
- if not tree:
- return True
- return False
-
- async def _cleanup_orphaned_managed_server(self) -> None:
- info = self._read_pid_file()
- if not info:
- return
-
- pid = info.get("pid")
- port = info.get("port")
- if not isinstance(pid, int) or port != self.port:
- self._clear_pid_file()
- return
-
- if self._process and self._process.returncode is None and self._process.pid == pid:
- return
-
- # Check if the server is healthy before deciding to kill it.
- # If it's healthy, we should adopt it rather than kill it.
- if await self._is_healthy():
- # Update PID file to reflect the actual running process.
- # The PID in the file may be stale if OpenCode was restarted externally.
- actual_pids = self._find_opencode_serve_pids(self.port)
- if actual_pids:
- actual_pid = actual_pids[0]
- if actual_pid != pid:
- logger.info(f"Adopting healthy OpenCode server (updating stale PID {pid} -> {actual_pid})")
- self._write_pid_file(
- actual_pid,
- caller_context_path=None,
- owner_pid=None,
- runtime_policy_revision=None,
- )
- else:
- logger.info(f"Adopting healthy OpenCode server pid={pid} from previous run")
- else:
- # Server is healthy but we can't find its PID - clear stale file
- logger.info(f"Adopting healthy OpenCode server (clearing stale PID file, pid={pid} not found)")
- self._clear_pid_file()
- return
-
- cmd = self._get_pid_command(pid)
- if self._pid_exists(pid):
- if self._runtime_activation_retire is not None:
- self._retire_runtime_generation_for_replacement()
- if cmd and self._is_opencode_serve_cmd(cmd, self.port):
- await self._terminate_pid(pid, reason="orphaned and unhealthy")
- elif cmd is None and self._pid_owns_listening_port(pid, self.port):
- logger.info(
- "Trusting OpenCode pid file for orphan cleanup pid=%s because it still owns port %s",
- pid,
- self.port,
- )
- await self._terminate_pid(pid, reason="orphaned and unhealthy")
- self._clear_pid_file()
-
- async def ensure_running(self) -> str:
- overlay_reservation = await self._prepare_model_hub_launch_boundary()
- try:
- return await self._ensure_running_with_current_overlay()
- finally:
- if overlay_reservation is not None:
- await self.release_model_hub_overlay_reservation(
- overlay_reservation
- )
-
- async def _ensure_running_with_current_overlay(self) -> str:
- async with self._get_lock():
- plugin_install = ensure_plugin_installed()
- if plugin_install.changed:
- self._caller_context_plugin_refresh_pending = True
- if self._auth_refresh_pending and self._active_requests == 0 and not self._has_active_run_sessions():
- await self._restart_for_auth_refresh_locked()
- await self._cleanup_orphaned_managed_server()
-
- if await self._is_healthy():
- pid_info = self._read_pid_file()
- if not self._pid_file_references_current_server(pid_info):
- raise RuntimeError(
- f"OpenCode server is already healthy on port {self.port}, but it is not managed by Avibe. "
- "Stop that server or configure Avibe to use another OPENCODE_PORT so caller context "
- "environment variables can be injected safely."
- )
- pid_info = self._reconcile_adopted_active_run_sessions(pid_info)
- if not self._pid_file_has_caller_context_binding(pid_info):
- self._caller_context_plugin_refresh_pending = True
- runtime_policy_stale = not self._pid_file_has_current_runtime_policy(pid_info)
- if (
- (self._caller_context_plugin_refresh_pending or runtime_policy_stale)
- and self._active_requests == 0
- and not self._has_active_run_sessions()
- and (
- self._pid_file_was_started_by_current_process(pid_info)
- or self._pid_file_has_known_no_active_runs(pid_info)
- )
- ):
- refresh_reasons = []
- if self._caller_context_plugin_refresh_pending:
- refresh_reasons.append("caller-context plugin")
- if runtime_policy_stale:
- refresh_reasons.append("managed runtime policy")
- logger.info(
- "Restarting OpenCode server to refresh %s at %s",
- " and ".join(refresh_reasons),
- plugin_install.path,
- )
- await self._restart_for_auth_refresh_locked()
- await self._start_server_for_current_model_hub_mode_locked()
- self._caller_context_plugin_refresh_pending = False
- return self.base_url
- if runtime_policy_stale:
- raise OpenCodeManagedPolicyRefreshPendingError(
- "OpenCode managed runtime policy refresh is pending for an adopted or active server; "
- "retry after the existing OpenCode turn finishes so Avibe can restart the server "
- "with native Skills disabled."
- )
- if self._caller_context_plugin_refresh_pending:
- raise RuntimeError(
- "OpenCode caller-context plugin refresh is pending for an adopted or active server; "
- "retry after the existing OpenCode turn finishes so Avibe can restart the server "
- "with AVIBE_* env injection."
- )
- # If the server is already running (e.g., started by a previous run),
- # record its PID so shutdown can clean it up.
- if not self._read_pid_file():
- pids = self._find_opencode_serve_pids(self.port)
- if pids:
- pid = pids[0]
- cmd = self._get_pid_command(pid)
- if cmd and self._is_opencode_serve_cmd(cmd, self.port):
- self._write_pid_file(pid)
- self._apply_resource_governance(pid)
- else:
- pid = (pid_info or {}).get("pid") if isinstance(pid_info, dict) else None
- self._apply_resource_governance(pid)
-
- self._base_url = f"http://{self.host}:{self.port}"
- self._observe_runtime_generation(self._read_pid_file())
- return self.base_url
-
- if not self._is_port_available():
- for pid in self._find_opencode_serve_pids(self.port):
- await self._terminate_pid(pid, reason="port occupied but unhealthy")
- await asyncio.sleep(0.5)
-
- if not self._is_port_available():
- raise RuntimeError(
- f"OpenCode port {self.port} is already in use but the server is not responding. "
- "Stop the process using this port or set OPENCODE_PORT to a free port."
- )
-
- if self._runtime_generation_token is not None:
- self._retire_runtime_generation_for_replacement()
- await self._start_server_for_current_model_hub_mode_locked()
- self._caller_context_plugin_refresh_pending = False
- return self.base_url
-
- async def _is_healthy(self) -> bool:
- try:
- session = await self._get_http_session()
- async with session.get(f"{self.base_url}/global/health", timeout=aiohttp.ClientTimeout(total=5)) as resp:
- if resp.status == 200:
- data = await resp.json()
- return data.get("healthy", False)
- except Exception as e:
- logger.debug(f"Health check failed: {e}")
- return False
-
- async def _start_server(self) -> None:
- # ``self._process`` may be a stale subprocess from a previous
- # ``asyncio.run()`` call (the Flask UI server creates a new loop
- # per request, while ``OpenCodeServerManager`` is a singleton).
- # ``process.wait()`` uses the transport's internal Future — that
- # Future is bound to the loop that created the subprocess, and
- # awaiting it from any other loop raises "got Future attached to a
- # different loop". The OS-level pid signaling below
- # (``_terminate_pid``) is loop-agnostic and is the correct cleanup
- # path; just detach the dangling Python object first.
- current_loop = asyncio.get_running_loop()
- self._start_attempt_generation += 1
- self._last_start_failure_pid = None
- if (
- self._process
- and self._process.returncode is None
- and self._process_loop is current_loop
- ):
- await self._terminate_tracked_process(self._process, reason="stale server")
- elif self._process and self._process_loop is not current_loop:
- # Foreign-loop subprocess. We can't trust ``returncode`` here
- # — the transport callbacks fire on the original (now-closed)
- # loop, so the cached ``returncode`` stays ``None`` even if
- # the OS process exited long ago. Worse, the PID may have
- # been reused by an unrelated process. Only OS-signal when
- # we can confirm the PID still owns an OpenCode serve
- # cmdline; otherwise just drop the dangling Python object.
- # ``_find_opencode_serve_pids`` + ``_cleanup_orphaned_
- # managed_server`` (called earlier in ``ensure_running``)
- # pick up any true orphan from a separate, pid-file-backed
- # path that doesn't rely on this dead reference.
- stale_pid = getattr(self._process, "pid", None)
- if isinstance(stale_pid, int) and self._pid_exists(stale_pid):
- cmd = self._get_pid_command(stale_pid)
- if cmd and self._is_opencode_serve_cmd(cmd, self.port):
- await self._terminate_pid(stale_pid, reason="foreign-loop cleanup")
- self._process = None
- self._process_loop = None
-
- # Ensure any stale pid file is cleared before starting.
- self._clear_pid_file()
-
- cmd = [
- self.binary,
- "serve",
- f"--hostname={self.host}",
- f"--port={self.port}",
- ]
-
- logger.info(f"Starting OpenCode server: {' '.join(cmd)}")
-
- env = os.environ.copy()
- env[DESKTOP_ROLE_ENV] = DESKTOP_OPENCODE_ROLE
- env["OPENCODE_ENABLE_EXA"] = "1"
- env["OPENCODE_DISABLE_EXTERNAL_SKILLS"] = "1"
- env.update(server_environment())
- env["AVIBE_OPENCODE_MODEL_HUB"] = "1" if self._model_hub_overlay_path else "0"
- if self._model_hub_overlay_path:
- env["OPENCODE_CONFIG"] = self._model_hub_overlay_path
- content = self._model_hub_overlay_content
- if content is None:
- try:
- raw_content = Path(self._model_hub_overlay_path).read_bytes()
- except OSError as exc:
- raise RuntimeError("Model Hub OpenCode overlay is unavailable") from exc
- content = _managed_runtime_config_content(raw_content)
- if hashlib.sha256(content.encode()).hexdigest() != self._model_hub_overlay_hash:
- raise RuntimeError("Model Hub OpenCode overlay content hash changed")
- # Inline config is OpenCode's runtime-override tier, loaded after
- # project config. Reasserting the exact overlay here prevents a
- # checked-in opencode.json from replacing Hub provider transport.
- env["OPENCODE_CONFIG_CONTENT"] = content
-
- # Request-level ``tools.skill=false`` prevents native Skill calls. The
- # runtime override adds defense in depth, while the Avibe runtime plugin
- # removes OpenCode's independently assembled native Catalog.
- env["OPENCODE_CONFIG_CONTENT"] = _managed_runtime_config_content(
- env.get("OPENCODE_CONFIG_CONTENT")
- )
-
- try:
- self._process = await asyncio.create_subprocess_exec(
- *cmd,
- stdout=asyncio.subprocess.DEVNULL,
- stderr=asyncio.subprocess.DEVNULL,
- env=env,
- **isolated_subprocess_kwargs(),
- )
- # Pair the subprocess object with the loop it was created on
- # so a future request from another loop can detach it
- # safely before issuing ``process.wait()``.
- self._process_loop = current_loop
- if self._process and self._process.pid:
- self._write_pid_file(
- self._process.pid,
- process_created_at=runtime.process_create_time(self._process.pid),
- )
- self._apply_resource_governance(self._process.pid)
- except FileNotFoundError:
- raise RuntimeError(
- f"OpenCode CLI not found at '{self.binary}'. Please install OpenCode or set OPENCODE_CLI_PATH."
- )
-
- start_time = time.monotonic()
- while time.monotonic() - start_time < SERVER_START_TIMEOUT:
- if await self._is_healthy():
- self._base_url = f"http://{self.host}:{self.port}"
- self._observe_runtime_generation(self._read_pid_file())
- logger.info(f"OpenCode server started at {self._base_url}")
- return
- if self._process.returncode is not None:
- break
- await asyncio.sleep(0.5)
-
- process = self._process
- exit_code = process.returncode
- # A live process below is terminated by Avibe for timeout. Only an
- # independently exited process may consume shared pressure evidence.
- self._last_start_failure_pid = (
- getattr(process, "pid", None) if exit_code is not None else None
- )
- if exit_code is None:
- # A late-starting process must not become a healthy but unmanaged
- # server after this call reports failure and clears its PID file.
- await self._terminate_tracked_process(process, reason="startup timeout")
- self._clear_pid_file()
- self._process = None
- self._process_loop = None
- raise RuntimeError(
- f"OpenCode server failed to start within {SERVER_START_TIMEOUT}s. Process exit code: {exit_code}"
- )
-
- async def stop(self) -> None:
- async with self._get_lock():
- await self._close_http_session_locked()
-
- # Don't terminate OpenCode server on vibe-remote shutdown.
- # Let it continue running so the next vibe-remote instance can adopt it.
- # This prevents interrupting tasks that are still in progress.
- logger.info("OpenCode server left running for next vibe-remote instance to adopt")
-
- # Keep pid_file so next instance knows about the running server.
- self._process = None
- self._process_loop = None
-
- def _close_http_session_sync(self) -> None:
- if self._http_session and self._http_session_loop:
- try:
- future = asyncio.run_coroutine_threadsafe(self._http_session.close(), self._http_session_loop)
- future.result(timeout=5)
- except Exception as e:
- logger.debug(f"Failed to close OpenCode HTTP session: {e}")
- finally:
- self._http_session = None
- self._http_session_loop = None
-
- def stop_sync(self) -> None:
- self._close_http_session_sync()
-
- # Don't terminate OpenCode server on vibe-remote shutdown.
- # Let it continue running so the next vibe-remote instance can adopt it.
- # This prevents interrupting tasks that are still in progress.
- logger.info("OpenCode server left running for next vibe-remote instance to adopt")
-
- # Keep pid_file so next instance knows about the running server.
- # Don't clear _process reference - just let it be garbage collected.
- self._process = None
- self._process_loop = None
-
- def terminate_sync(self) -> None:
- """Terminate the managed server during an explicit Avibe shutdown."""
- self._close_http_session_sync()
- info = self._read_pid_file()
- pid = info.get("pid") if isinstance(info, dict) else None
- tracked_pid = getattr(self._process, "pid", None)
- stopped = False
- if isinstance(pid, int) and self._pid_exists(pid):
- command = self._get_pid_command(pid)
- trusted_pid_file = bool(command and self._is_opencode_serve_cmd(command, self.port)) or (
- isinstance(info, dict)
- and info.get("port") == self.port
- and self._pid_owns_listening_port(pid, self.port)
- )
- if trusted_pid_file:
- stopped = self._terminate_pid_tree_sync(pid)
- if not stopped and isinstance(tracked_pid, int) and self._pid_exists(tracked_pid):
- tracked_command = self._get_pid_command(tracked_pid)
- if tracked_command and self._is_opencode_serve_cmd(tracked_command, self.port):
- self._terminate_pid_tree_sync(tracked_pid)
- self._clear_pid_file()
- self._base_url = None
- self._process = None
- self._process_loop = None
- self._runtime_generation_token = None
- self._observed_runtime_process = None
-
- @classmethod
- def terminate_instance_sync(cls) -> None:
- if cls._instance is not None:
- cls._instance.terminate_sync()
- return
- pid_file = paths.get_logs_dir() / "opencode_server.json"
- try:
- info = json.loads(pid_file.read_text(encoding="utf-8"))
- except Exception:
- return
- pid = info.get("pid") if isinstance(info, dict) else None
- port = info.get("port") if isinstance(info, dict) else None
- if not isinstance(pid, int) or not isinstance(port, int):
- return
- command = runtime.get_process_command(pid)
- trusted_pid_file = bool(command and cls._is_opencode_serve_cmd(command, port)) or (
- command is None and cls._pid_owns_listening_port(pid, port)
- )
- if trusted_pid_file:
- cls._terminate_pid_tree_sync(pid)
- try:
- pid_file.unlink(missing_ok=True)
- except OSError:
- logger.debug("Failed to clear OpenCode pid file during shutdown", exc_info=True)
-
- async def restart_for_auth_refresh(self, *, force: bool = False) -> None:
- """Terminate the shared server so the next request reloads refreshed auth."""
- async with self._get_lock():
- if force:
- self._active_run_sessions.clear()
- if not force and (self._active_requests > 0 or self._has_active_run_sessions()):
- self._auth_refresh_pending = True
- logger.info(
- "Deferring OpenCode auth refresh restart until %s active request(s) and %s active run(s) finish",
- self._active_requests,
- len(self._active_run_sessions),
- )
- return
- await self._restart_for_auth_refresh_locked(force=force)
-
- @classmethod
- def stop_instance_sync(cls) -> None:
- if cls._instance:
- cls._instance.stop_sync()
- return
+ request.add_header(key, value)
+ try:
+ with urllib.request.urlopen(request, timeout=12) as response:
+ content_type = response.headers.get("content-type", "")
+ raw = response.read(2048).decode(errors="replace")
+ if "text/html" in content_type.lower() or raw.lstrip().lower().startswith("<!doctype html"):
+ return (
+ f"Provider Base URL {self._safe_url(base_url)} returned an HTML page instead of an API "
+ f"response; use the API base path, usually {self._suggest_api_base_url(base_url)}."
+ )
+ return None
+ except urllib.error.HTTPError as err:
+ content_type = err.headers.get("content-type", "")
+ raw = err.read(2048).decode(errors="replace")
+ if "text/html" in content_type.lower() or raw.lstrip().lower().startswith("<!doctype html"):
+ return (
+ f"Provider Base URL {self._safe_url(base_url)} returned an HTML page instead of an API "
+ f"response; use the API base path, usually {self._suggest_api_base_url(base_url)}."
+ )
+ try:
+ payload = json.loads(raw)
+ except Exception:
+ payload = {}
+ message = self._diagnostic_payload_message(payload)
+ if message:
+ return f"Provider API returned HTTP {err.code}: {message}"
+ return f"Provider API returned HTTP {err.code}."
+ except urllib.error.URLError as err:
+ reason = self._redact_diagnostic_text(str(err.reason or err))
+ return f"Provider API request failed: {reason[:240]}"
+ except (TimeoutError, OSError) as err:
+ reason = self._redact_diagnostic_text(str(err))
+ return f"Provider API request failed: {reason[:240] or type(err).__name__}"
+ except Exception as err:
+ logger.debug("OpenCode provider API diagnostic failed for %s/%s: %s", provider_id, model_id, err)
+ return None
- # Don't terminate OpenCode server on vibe-remote shutdown.
- # Let it continue running so the next vibe-remote instance can adopt it.
- logger.info("OpenCode server left running for next vibe-remote instance to adopt")
+ async def get_provider_api_diagnostic(self, provider_id: str, model_id: str) -> Optional[str]:
+ return await asyncio.to_thread(self._provider_api_diagnostic_sync, provider_id, model_id)
async def ensure_directory_ready(self, directory: str) -> None:
"""Wait until OpenCode has bootstrapped its instance for ``directory``.
@@ -2559,8 +1127,6 @@ class OpenCodeServerManager:
async def set_api_key_auth(self, provider_id: str, api_key: str) -> None:
"""Persist provider API auth via OpenCode's own auth endpoint."""
- await self.ensure_running()
-
async with self._request_scope():
session = await self._get_http_session()
async with session.put(
@@ -2579,8 +1145,6 @@ class OpenCodeServerManager:
DELETE optimistically without first checking presence.
"""
- await self.ensure_running()
-
async with self._request_scope():
session = await self._get_http_session()
async with session.delete(
@@ -2603,8 +1167,6 @@ class OpenCodeServerManager:
``local`` flags surfaced in the Settings UI.
"""
- await self.ensure_running()
-
async with self._request_scope():
session = await self._get_http_session()
try:
@@ -2639,7 +1201,6 @@ class OpenCodeServerManager:
type), ``prompt_answers`` is merged into the body so the caller
can pre-answer (e.g. ``{"deploymentType": "github.com"}``).
"""
- await self.ensure_running()
payload = {"method": method}
if prompt_answers:
payload.update(prompt_answers)
@@ -2684,7 +1245,6 @@ class OpenCodeServerManager:
long-poll on the OAuth event loop with
``aiohttp.ServerDisconnectedError``.
"""
- await self.ensure_running()
payload = {key: value for key, value in (prompt_answers or {}).items() if key not in {"method", "code"}}
payload["method"] = method
if code is not None:
@@ -2764,8 +1324,6 @@ class OpenCodeServerManager:
local providers (Ollama / LM Studio) report an empty list.
"""
- await self.ensure_running()
-
async with self._request_scope():
session = await self._get_http_session()
try:
@@ -2789,28 +1347,6 @@ class OpenCodeServerManager:
probe = load_first_opencode_user_config(logger_instance=logger)
return probe.config
- def _merge_global_config_snapshot(self, current_config: Dict[str, Any], user_config: Dict[str, Any]) -> Dict[str, Any]:
- try:
- auth_entries = read_opencode_provider_auth_entries(logger_instance=logger)
- except Exception as exc:
- logger.debug("Could not read OpenCode auth entries during global config merge: %s", exc)
- auth_entries = {}
- return OpenCodeConfigReconciler().reconcile(
- user_config=user_config,
- live_config=current_config,
- auth_entries=auth_entries,
- )
-
- async def _get_global_config_snapshot(self) -> Optional[Dict[str, Any]]:
- total_timeout: Optional[int] = None if self.request_timeout_seconds <= 0 else self.request_timeout_seconds
- async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=total_timeout)) as session:
- async with session.get(f"{self.base_url}/global/config") as resp:
- if resp.status != 200:
- await resp.read()
- return None
- data = await resp.json()
- return data if isinstance(data, dict) else None
-
def _get_agent_config(self, config: Dict[str, Any], agent_name: Optional[str]) -> Dict[str, Any]:
"""Get agent-specific config from opencode.json with type safety."""
@@ -2871,3 +1407,937 @@ class OpenCodeServerManager:
# Users can override via channel settings.
# Default to the native "build" agent; Avibe supplies its model explicitly.
return "build"
+
+
+def terminate_pid_tree_sync(pid: int, timeout: float = 5.0) -> bool:
+ """Stop the OpenCode server and every process it started.
+
+ OpenCode starts each tool command detached, as the leader of a new
+ session and process group, so the server's own group never reaches it.
+ Only a live parent ties a process to the server, so the tree is walked
+ before anything is signalled and again before escalating. Every process
+ is held as a ``psutil.Process``, which refuses a pid reused since.
+ """
+ if os.name == "nt":
+ return runtime.stop_pid(pid, timeout=timeout)
+ try:
+ server = psutil.Process(pid)
+ except psutil.NoSuchProcess:
+ return True
+ except psutil.Error:
+ return not runtime.pid_alive(pid)
+
+ def running(processes: list[psutil.Process]) -> list[psutil.Process]:
+ alive = []
+ for process in processes:
+ try:
+ # A zombie has exited; reaping it belongs to its parent.
+ if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
+ alive.append(process)
+ except psutil.NoSuchProcess:
+ continue
+ except psutil.Error:
+ alive.append(process)
+ return alive
+
+ own_group = os.getpgrp()
+ founded_groups: set[int] = set()
+ tree = [server]
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ found = dict.fromkeys(tree)
+ for process in tree:
+ try:
+ found.update(dict.fromkeys(process.children(recursive=True)))
+ except psutil.Error:
+ continue
+ tree = running(list(found))
+ if not tree:
+ return True
+ groups = {}
+ for process in tree:
+ try:
+ groups[process] = os.getpgid(process.pid)
+ except OSError:
+ continue
+ # The caller's own group is the one carrying out this stop: ``vibe
+ # stop`` run from an OpenCode tool sits inside the tree. It is never
+ # signalled, nor waited for, so the stop can finish its own work.
+ tree = [process for process in tree if groups.get(process) != own_group]
+ if not tree:
+ return True
+ # A group is the tree's when a process of the tree founded it. It is
+ # signalled only while a live process of the tree is still in it,
+ # proof that its id was not recycled, and the group signal also
+ # reaches whatever those processes started since the walk.
+ founded_groups.update(process.pid for process, pgid in groups.items() if process.pid == pgid)
+ owned_groups = (set(groups.values()) & founded_groups) - {own_group}
+ if sig == signal.SIGKILL:
+ logger.warning("Escalating to SIGKILL for %d process(es) of OpenCode server pid=%s", len(tree), pid)
+ elif len(tree) > 1:
+ logger.info("OpenCode server pid=%s has %d descendant process(es) to stop", pid, len(tree) - 1)
+ signalled_groups = set()
+ for pgid in owned_groups:
+ try:
+ os.killpg(pgid, sig)
+ except ProcessLookupError:
+ pass
+ except OSError:
+ # Fall back to signalling its known members one by one.
+ continue
+ signalled_groups.add(pgid)
+ for process in tree:
+ if groups.get(process) in signalled_groups:
+ continue
+ try:
+ process.send_signal(sig)
+ except psutil.NoSuchProcess:
+ continue
+ except psutil.Error:
+ logger.debug("Failed to signal OpenCode process pid=%s", process.pid, exc_info=True)
+ deadline = time.monotonic() + timeout
+ tree = running(tree)
+ while tree and time.monotonic() < deadline:
+ time.sleep(0.1)
+ tree = running(tree)
+ if not tree:
+ return True
+ return False
+
+
+@dataclass(frozen=True)
+class OpenCodeLaunchSpec:
+ """Process-level inputs of one generation; equal specs have equal digests."""
+
+ digest: str
+ binary: str
+ binary_version: Optional[str] = None
+ overlay_hash: Optional[str] = None
+ overlay_provider_ids: tuple[str, ...] = ()
+ # The Hub overlay as Model Hub wrote it, and as OpenCode receives it inline.
+ overlay_file_content: Optional[bytes] = field(default=None, repr=False)
+ overlay_inline_content: Optional[str] = field(default=None, repr=False)
+
+
+class OpenCodeGeneration(OpenCodeServerClient):
+ """One ``opencode serve`` process, a runtime generation of the OpenCode instance.
+
+ Its record lets a controller adopt it after a crash, so a failed write
+ never leaves the record protecting less than the process runs. A run
+ marker or a lease is persisted before its work starts. A turn clears its
+ run marker together with its durable poll: when the record cannot be
+ written, both stay and a later restore retries. Any other change that only
+ releases protection takes effect at once; when its write fails, the record
+ stays stale until a sweep's ``flush_record`` writes it, and a crash before
+ then only keeps the process until the stale lease expires or adoption drops
+ a marker no durable poll backs.
+ """
+
+ def __init__(
+ self,
+ *,
+ generation_id: str,
+ pid: int,
+ port: int,
+ spec_digest: str,
+ process_created_at: float | None,
+ host: str = DEFAULT_OPENCODE_HOST,
+ binary: str = "",
+ binary_version: Optional[str] = None,
+ caller_context_path: Optional[str] = None,
+ model_hub_overlay_hash: Optional[str] = None,
+ model_hub_provider_ids: tuple[str, ...] = (),
+ active_run_sessions: Iterable[str] = (),
+ leases: Optional[Mapping[str, float]] = None,
+ started_at: float | None = None,
+ desktop_runtime_id: Any = None,
+ process: Optional[Process] = None,
+ request_timeout_seconds: int = 60,
+ ) -> None:
+ super().__init__(
+ f"http://{host}:{port}",
+ request_timeout_seconds=request_timeout_seconds,
+ model_hub_provider_ids=model_hub_provider_ids,
+ )
+ self.generation_id = generation_id
+ self.pid = pid
+ self.port = port
+ self.host = host
+ self.spec_digest = spec_digest
+ self.process_created_at = process_created_at
+ self.binary = binary
+ self.binary_version = binary_version
+ self.caller_context_path = caller_context_path
+ self.model_hub_overlay_hash = model_hub_overlay_hash
+ self.active_run_sessions: set[str] = set(active_run_sessions)
+ # Expiry of each lease held by a caller in another process.
+ self.leases: dict[str, float] = dict(leases or {})
+ self.started_at = time.time() if started_at is None else started_at
+ # The desktop Runtime this process serves, or None for none; a record
+ # written before Runtime ids were recorded keeps omitting it.
+ self.desktop_runtime_id = desktop_runtime_id
+ # Set when a change took effect but its record write failed.
+ self.record_stale = False
+ # Set once the process stopped and its record was removed.
+ self._record_removed = False
+ # A legacy record this record replaces once it is written.
+ self._supersedes: Optional[Path] = None
+ # The runtime activation identity the agent attached to this process.
+ self.identity: Any = None
+ # Sessions whose work a forced stop of this process already settled.
+ self.interrupted_sessions: set[str] = set()
+ self._process = process
+
+ @property
+ def record_path(self) -> Path:
+ return generation_records_dir() / f"{self.generation_id}.json"
+
+ @property
+ def overlay_path(self) -> Path:
+ return generation_records_dir() / f"{self.generation_id}.overlay.json"
+
+ def caller_context_binding_path(self) -> Path:
+ if self.caller_context_path and os.path.isabs(self.caller_context_path):
+ return Path(self.caller_context_path)
+ return Path(server_environment()["AVIBE_OPENCODE_CALLER_CONTEXT_PATH"])
+
+ def record(self) -> Dict[str, Any]:
+ return {
+ "schema": GENERATION_RECORD_SCHEMA,
+ "generation_id": self.generation_id,
+ "pid": self.pid,
+ "process_created_at": self.process_created_at,
+ "host": self.host,
+ "port": self.port,
+ "started_at": self.started_at,
+ "spec_digest": self.spec_digest,
+ "binary": {"path": self.binary, "version": self.binary_version},
+ "caller_context_path": self.caller_context_path,
+ "model_hub_overlay_hash": self.model_hub_overlay_hash,
+ "model_hub_overlay_provider_ids": list(self.model_hub_provider_ids),
+ "active_run_sessions": sorted(self.active_run_sessions),
+ "leases": dict(self.leases),
+ **(
+ {}
+ if self.desktop_runtime_id is _UNRECORDED_RUNTIME_ID
+ else {"desktop_runtime_id": self.desktop_runtime_id}
+ ),
+ }
+
+ def write_record(self) -> None:
+ """Persist this record now, raising when it cannot be written."""
+ if self._record_removed:
+ return
+ self.record_path.parent.mkdir(parents=True, exist_ok=True)
+ write_atomic(self.record_path, json.dumps(self.record()))
+ self.record_stale = False
+ if self._supersedes is not None:
+ _remove_quietly(self._supersedes)
+ # A removal that failed is retried by the next flush.
+ if not self._supersedes.exists():
+ self._supersedes = None
+
+ def write_record_or_defer(self, change: str) -> None:
+ """Persist a change that has already taken effect, or leave it to a sweep."""
+ try:
+ self.write_record()
+ except Exception:
+ log = logger.debug if self.record_stale else logger.warning
+ self.record_stale = True
+ log(
+ "Could not persist %s for OpenCode generation %s; a sweep retries",
+ change,
+ self.generation_id,
+ exc_info=True,
+ )
+
+ def flush_record(self) -> None:
+ if self.record_stale or self._supersedes is not None:
+ self.write_record_or_defer("an earlier change")
+
+ def _change_run_marker(self, session_id: str, *, active: bool) -> None:
+ previous = set(self.active_run_sessions)
+ if active:
+ self.active_run_sessions.add(session_id)
+ else:
+ self.active_run_sessions.discard(session_id)
+ if self.active_run_sessions == previous:
+ return
+ try:
+ self.write_record()
+ except Exception:
+ self.active_run_sessions = previous
+ raise
+
+ async def mark_run_active(self, session_id: str) -> None:
+ """Record a native run on this process before its first native write."""
+ async with self._get_lock():
+ self._change_run_marker(session_id, active=True)
+
+ async def mark_run_inactive(self, session_id: str) -> None:
+ async with self._get_lock():
+ self._change_run_marker(session_id, active=False)
+
+ def set_lease(self, lease_id: str, expires_at: float) -> None:
+ previous = dict(self.leases)
+ self.leases[lease_id] = expires_at
+ try:
+ self.write_record()
+ except Exception:
+ self.leases = previous
+ raise
+
+ def drop_lease(self, lease_id: str) -> None:
+ if self.leases.pop(lease_id, None) is not None:
+ self.write_record_or_defer(f"the release of lease {lease_id}")
+
+ def is_drained(self) -> bool:
+ """Whether no request or native run of this process is in flight."""
+ return not self.has_requests_in_flight() and not self.active_run_sessions
+
+ def has_requests_in_flight(self) -> bool:
+ return self._active_requests > 0
+
+ def process_alive(self) -> bool:
+ process = self._process
+ if process is not None and process.returncode is not None:
+ return False
+ created_at = runtime.process_create_time(self.pid)
+ if self.process_created_at is None:
+ return created_at is not None or _pid_exists(self.pid)
+ return created_at == self.process_created_at
+
+ def observed_exit_pid(self) -> int | None:
+ """This process's pid once it has exited, never a pid reused since."""
+ return None if self.process_alive() else self.pid
+
+ async def is_healthy(self) -> bool:
+ try:
+ session = await self._get_http_session()
+ async with session.get(f"{self.base_url}/global/health", timeout=aiohttp.ClientTimeout(total=5)) as resp:
+ if resp.status == 200:
+ data = await resp.json()
+ return bool(data.get("healthy", False))
+ except Exception as e:
+ logger.debug(f"Health check failed: {e}")
+ return False
+
+
+def _remove_quietly(path: Path) -> None:
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ logger.debug("Could not remove %s", path, exc_info=True)
+
+
+def apply_resource_governance(resource_governor: Any | None, pid: int | None) -> None:
+ apply_to_pid = getattr(resource_governor, "apply_to_pid", None)
+ if callable(apply_to_pid):
+ apply_to_pid(pid, label="opencode serve")
+
+
+def _launch_environment(spec: OpenCodeLaunchSpec, overlay_path: Optional[Path]) -> dict[str, str]:
+ env = os.environ.copy()
+ env[DESKTOP_ROLE_ENV] = DESKTOP_OPENCODE_ROLE
+ env["OPENCODE_ENABLE_EXA"] = "1"
+ env["OPENCODE_DISABLE_EXTERNAL_SKILLS"] = "1"
+ env.update(server_environment())
+ hub = spec.overlay_inline_content is not None
+ env["AVIBE_OPENCODE_MODEL_HUB"] = "1" if hub else "0"
+ if hub:
+ env["OPENCODE_CONFIG"] = str(overlay_path)
+ # Inline config is OpenCode's runtime-override tier, loaded after
+ # project config. Reasserting the exact overlay here prevents a
+ # checked-in opencode.json from replacing Hub provider transport.
+ env["OPENCODE_CONFIG_CONTENT"] = spec.overlay_inline_content
+ # Request-level ``tools.skill=false`` prevents native Skill calls. The
+ # runtime override adds defense in depth, while the Avibe runtime plugin
+ # removes OpenCode's independently assembled native Catalog.
+ env["OPENCODE_CONFIG_CONTENT"] = _managed_runtime_config_content(env.get("OPENCODE_CONFIG_CONTENT"))
+ return env
+
+
+async def _wait_until_ready(generation: OpenCodeGeneration, process: Process) -> str:
+ deadline = time.monotonic() + SERVER_START_TIMEOUT
+ while time.monotonic() < deadline:
+ if process.returncode is not None:
+ return "exited"
+ # A healthy answer alone may come from another process that won the
+ # port; only this process listening on it proves the generation.
+ if await generation.is_healthy() and _pid_listens_on(process.pid, generation.port):
+ return "ready"
+ await asyncio.sleep(0.25)
+ return "exited" if process.returncode is not None else "timeout"
+
+
+async def _terminate_started_process(process: Process, reason: str) -> bool:
+ """Stop a process this start spawned; return whether it has exited."""
+
+ logger.info("Stopping OpenCode server pid=%s (%s)", process.pid, reason)
+ await asyncio.to_thread(terminate_pid_tree_sync, process.pid)
+ try:
+ await asyncio.wait_for(process.wait(), timeout=5)
+ except asyncio.TimeoutError:
+ logger.warning("OpenCode server pid=%s did not exit after it was stopped", process.pid)
+ return False
+ return True
+
+
+async def start_generation(
+ spec: OpenCodeLaunchSpec,
+ *,
+ request_timeout_seconds: int = 60,
+ resource_governor: Any | None = None,
+ on_survivor: Optional[Callable[[OpenCodeGeneration], None]] = None,
+) -> OpenCodeGeneration:
+ """Start one generation on a port of its own and wait until it serves.
+
+ A start that fails after spawning stops its process. When the process
+ survives that stop, ``on_survivor`` receives it, still owned here, so its
+ runtime keeps retrying the stop; its record and overlay stay meanwhile.
+ The process is owned here from its spawn, so even one whose record was
+ never written is stopped by this controller's shutdown.
+ """
+
+ generation_id = f"ocg_{secrets.token_hex(8)}"
+ ensure_plugin_installed()
+ caller_context_path = server_environment()["AVIBE_OPENCODE_CALLER_CONTEXT_PATH"]
+ overlay_path: Optional[Path] = None
+ if spec.overlay_inline_content is not None:
+ # Model Hub rewrites its own overlay file for every new overlay while
+ # older generations still run, so each generation keeps its own copy.
+ overlay_path = generation_records_dir() / f"{generation_id}.overlay.json"
+ overlay_path.parent.mkdir(parents=True, exist_ok=True)
+ write_atomic(overlay_path, spec.overlay_file_content or spec.overlay_inline_content.encode())
+ env = _launch_environment(spec, overlay_path)
+ exited_pid: int | None = None
+ exit_code: int | None = None
+ # A process that survives its stop keeps its record and overlay; its
+ # runtime retries the stop, and ``vibe stop`` can still find it.
+ survivor: Optional[OpenCodeGeneration] = None
+ try:
+ for _attempt in range(_PORT_ATTEMPTS):
+ port = _choose_port(DEFAULT_OPENCODE_HOST)
+ cmd = [spec.binary, "serve", f"--hostname={DEFAULT_OPENCODE_HOST}", f"--port={port}"]
+ logger.info("Starting OpenCode generation %s: %s", generation_id, " ".join(cmd))
+ try:
+ process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ env=env,
+ **isolated_subprocess_kwargs(),
+ )
+ except FileNotFoundError as exc:
+ raise OpenCodeGenerationStartError(
+ f"OpenCode CLI not found at '{spec.binary}'. Please install OpenCode or set OPENCODE_CLI_PATH."
+ ) from exc
+ # Owned before anything else can fail, the record write included.
+ created_at = runtime.process_create_time(process.pid)
+ _OWNED_HERE[generation_id] = (process.pid, created_at)
+ generation = OpenCodeGeneration(
+ generation_id=generation_id,
+ pid=process.pid,
+ port=port,
+ spec_digest=spec.digest,
+ process_created_at=created_at,
+ binary=spec.binary,
+ binary_version=spec.binary_version,
+ caller_context_path=caller_context_path,
+ model_hub_overlay_hash=spec.overlay_hash,
+ model_hub_provider_ids=spec.overlay_provider_ids,
+ desktop_runtime_id=_this_desktop_runtime_id(),
+ process=process,
+ request_timeout_seconds=request_timeout_seconds,
+ )
+ try:
+ # Written before readiness, so a controller that dies during
+ # the start leaves a record its successor cleans up.
+ generation.write_record()
+ apply_resource_governance(resource_governor, process.pid)
+ outcome = await _wait_until_ready(generation, process)
+ except BaseException:
+ await generation.close_http_session()
+ if await _terminate_started_process(process, "start interrupted"):
+ _disown_ended_start(generation)
+ else:
+ survivor = generation
+ raise
+ if outcome == "ready":
+ logger.info("OpenCode generation %s serves at %s", generation_id, generation.base_url)
+ return generation
+ await generation.close_http_session()
+ if outcome == "exited":
+ # Most often another process took the port first.
+ _disown_ended_start(generation)
+ exited_pid, exit_code = process.pid, process.returncode
+ continue
+ # A late-starting process must not become a healthy server that
+ # nothing records.
+ if await _terminate_started_process(process, "startup timeout"):
+ _disown_ended_start(generation)
+ else:
+ survivor = generation
+ raise OpenCodeGenerationStartError(
+ f"OpenCode server failed to start within {SERVER_START_TIMEOUT}s."
+ )
+ raise OpenCodeGenerationStartError(
+ f"OpenCode server exited during startup. Process exit code: {exit_code}",
+ exited_pid=exited_pid,
+ )
+ except BaseException:
+ if survivor is not None and on_survivor is not None:
+ # Still owned here: the runtime that started it retries its stop.
+ on_survivor(survivor)
+ if overlay_path is not None and survivor is None:
+ _remove_quietly(overlay_path)
+ raise
+
+
+def _disown_ended_start(generation: OpenCodeGeneration) -> None:
+ """A start's process exited: it is no longer owned here, and its record goes."""
+
+ _OWNED_HERE.pop(generation.generation_id, None)
+ _remove_quietly(generation.record_path)
+
+
+async def stop_generation(generation: OpenCodeGeneration) -> None:
+ """Stop one generation's process tree, then remove its record.
+
+ The record stays when the process survives, so adoption or ``vibe stop``
+ can try again.
+ """
+
+ await generation.close_http_session()
+ process = generation._process
+ if generation.process_alive():
+ logger.info("Stopping OpenCode generation %s pid=%s", generation.generation_id, generation.pid)
+ stopped = await asyncio.to_thread(terminate_pid_tree_sync, generation.pid)
+ if process is not None:
+ try:
+ await asyncio.wait_for(process.wait(), timeout=5)
+ except asyncio.TimeoutError:
+ pass
+ if not stopped and generation.process_alive():
+ raise RuntimeError(
+ f"OpenCode generation {generation.generation_id} pid={generation.pid} did not exit"
+ )
+ generation._record_removed = True
+ _OWNED_HERE.pop(generation.generation_id, None)
+ _remove_quietly(generation.record_path)
+ _remove_quietly(generation.overlay_path)
+ if generation._supersedes is not None:
+ _remove_quietly(generation._supersedes)
+
+
+def _read_json_object(path: Path) -> Optional[Dict[str, Any]]:
+ """A record's content; ``None`` when it is missing or cannot be parsed."""
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return None
+ except Exception:
+ data = None
+ if not isinstance(data, dict):
+ # Its process may still run on a port nothing else records, so the
+ # record stays for a person to inspect rather than counting as dead.
+ logger.warning("Keeping an unreadable OpenCode process record at %s", path)
+ return None
+ return data
+
+
+# A record is read back from disk, where any field can be malformed. Readers
+# take each field only through these, so a corrupt record degrades to one that
+# lacks the field and never breaks the readers of every other record.
+
+
+def _record_pid(info: Mapping[str, Any]) -> Optional[int]:
+ pid = info.get("pid")
+ return pid if isinstance(pid, int) and not isinstance(pid, bool) and 0 < pid < 2**32 else None
+
+
+def _record_port(info: Mapping[str, Any]) -> Optional[int]:
+ port = info.get("port")
+ return port if isinstance(port, int) and not isinstance(port, bool) and 0 < port < 65536 else None
+
+
+def _record_number(value: object) -> Optional[float]:
+ """A finite number a record holds, or None for anything else."""
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ try:
+ number = float(value)
+ except OverflowError:
+ return None
+ return number if math.isfinite(number) else None
+
+
+def _record_runtime_id(info: Mapping[str, Any]) -> Any:
+ """The desktop Runtime a record names: an id, None, or unrecorded.
+
+ A record from before the field existed, or one whose value is no id at
+ all, counts as unrecorded and is judged by its live process.
+ """
+ value = info.get("desktop_runtime_id", _UNRECORDED_RUNTIME_ID)
+ return value if value is None or isinstance(value, str) else _UNRECORDED_RUNTIME_ID
+
+
+def _record_proves_process(info: Mapping[str, Any], *, require_port: bool = True) -> bool:
+ """Whether a record still names the exact ``opencode serve`` it started.
+
+ Stopping a server needs no port, so it accepts the bare legacy shape that
+ ``vibe stop`` always accepted; adopting one does.
+ """
+
+ pid = _record_pid(info)
+ port = _record_port(info)
+ if pid is None or not _pid_exists(pid):
+ return False
+ has_port = port is not None
+ if require_port and not has_port:
+ return False
+ created_at = _record_number(info.get("process_created_at"))
+ if created_at is not None:
+ # A command line alone can belong to a reused pid.
+ if runtime.process_create_time(pid) != created_at:
+ return False
+ command = _get_pid_command(pid)
+ if command:
+ if has_port:
+ return _is_opencode_serve_cmd(command, port)
+ return "opencode" in command and "serve" in command
+ return has_port and _pid_listens_on(pid, port)
+
+
+def _string_tuple(value: object) -> tuple[str, ...]:
+ if not isinstance(value, list):
+ return ()
+ return tuple(dict.fromkeys(item for item in value if isinstance(item, str) and item))
+
+
+def _generation_from_record(
+ info: Mapping[str, Any],
+ *,
+ generation_id: str,
+ spec_digest: str,
+ request_timeout_seconds: int,
+) -> OpenCodeGeneration:
+ binary = info.get("binary") if isinstance(info.get("binary"), dict) else {}
+ pid = int(info["pid"])
+ created_at = _record_number(info.get("process_created_at"))
+ if created_at is None:
+ created_at = runtime.process_create_time(pid)
+ started_at = _record_number(info.get("started_at"))
+ leases = info.get("leases") if isinstance(info.get("leases"), dict) else {}
+ caller_context_path = info.get("caller_context_path")
+ overlay_hash = info.get("model_hub_overlay_hash")
+ host = info.get("host")
+ binary_path = binary.get("path")
+ return OpenCodeGeneration(
+ generation_id=generation_id,
+ pid=pid,
+ port=int(info["port"]),
+ host=host if isinstance(host, str) and host else DEFAULT_OPENCODE_HOST,
+ spec_digest=spec_digest,
+ process_created_at=created_at,
+ binary=binary_path if isinstance(binary_path, str) else "",
+ binary_version=binary.get("version") if isinstance(binary.get("version"), str) else None,
+ caller_context_path=caller_context_path if isinstance(caller_context_path, str) else None,
+ model_hub_overlay_hash=overlay_hash if isinstance(overlay_hash, str) else None,
+ model_hub_provider_ids=_string_tuple(info.get("model_hub_overlay_provider_ids")),
+ active_run_sessions=_string_tuple(info.get("active_run_sessions")),
+ leases={
+ str(key): expires_at
+ for key, value in leases.items()
+ if (expires_at := _record_number(value)) is not None
+ },
+ # The process's age: a record without a start time, such as the
+ # legacy one, started when its process did, never at its adoption.
+ started_at=started_at if started_at is not None else created_at,
+ # Rewritten without a malformed id, so every later read judges it alike.
+ desktop_runtime_id=_record_runtime_id(info),
+ request_timeout_seconds=request_timeout_seconds,
+ )
+
+
+def _this_desktop_runtime_id() -> Optional[str]:
+ """The one desktop Runtime this process acts for, or None."""
+
+ runtime_ids = desktop_caller_provenance()
+ return next(iter(runtime_ids)) if len(runtime_ids) == 1 else None
+
+
+def _record_is_ours(info: Mapping[str, Any], runtime_ids: frozenset[str]) -> bool:
+ """Whether a caller acting for ``runtime_ids`` may act on a record at all.
+
+ It is the one ownership gate for every path that reads or acts on records.
+ A caller with no desktop provenance acts on any record, as ``vibe stop``
+ always has. A record names the desktop Runtime whose controller wrote it;
+ a record from before Runtime ids were recorded, or whose id is malformed,
+ is judged by its live process, exactly as ``refuse_foreign_desktop_process``
+ judges one, and a record whose process is gone belongs to nobody.
+ """
+
+ if not runtime_ids:
+ return True
+ recorded = _record_runtime_id(info)
+ if recorded is not _UNRECORDED_RUNTIME_ID:
+ return runtime_ids == {recorded}
+ pid = _record_pid(info)
+ if pid is None:
+ return True
+ try:
+ runtime.refuse_foreign_desktop_process(pid, "opencode", runtime_ids)
+ except runtime.DesktopRuntimeClaimRefused:
+ return False
+ return True
+
+
+def _recorded_processes(runtime_ids: Optional[frozenset[str]] = None) -> list[tuple[Path, Dict[str, Any]]]:
+ """This caller's generation records, then the legacy single-server record.
+
+ Records of another desktop Runtime sharing this state directory are left
+ out, so nothing here adopts, stops, forgets, or cleans them.
+ ``runtime_ids`` defaults to this process's desktop provenance.
+ """
+
+ ids = desktop_caller_provenance() if runtime_ids is None else runtime_ids
+ found = _every_recorded_process()
+ ours = [(path, info) for path, info in found if _record_is_ours(info, ids)]
+ if len(ours) < len(found):
+ logger.debug("Leaving %s OpenCode record(s) of another desktop Runtime alone", len(found) - len(ours))
+ return ours
+
+
+def other_runtimes_live_records() -> list[Dict[str, Any]]:
+ """Records of another desktop Runtime whose process is proven running.
+
+ Durable state naming such a process, such as the poll of a run it
+ executes, is that Runtime's: nothing here resumes, rewrites, or settles it,
+ and its controller resumes it when it runs here again. Once the process
+ is gone, the state names nothing to protect and any controller here
+ settles it, as after a restart.
+ """
+
+ runtime_ids = desktop_caller_provenance()
+ return [
+ info
+ for _path, info in _every_recorded_process()
+ if not _record_is_ours(info, runtime_ids) and _record_proves_process(info, require_port=False)
+ ]
+
+
+def _every_recorded_process() -> list[tuple[Path, Dict[str, Any]]]:
+ found: list[tuple[Path, Dict[str, Any]]] = []
+ records_dir = generation_records_dir()
+ if records_dir.is_dir():
+ for path in sorted(records_dir.glob("*.json")):
+ if path.name.endswith(".overlay.json"):
+ continue
+ info = _read_json_object(path)
+ if info is not None:
+ # A generation's record is named for it, so its file name is
+ # the id every reader uses, whatever the content claims.
+ info["generation_id"] = path.stem
+ found.append((path, info))
+ legacy = _read_json_object(legacy_pid_file())
+ if legacy is not None:
+ found.append((legacy_pid_file(), legacy))
+ return found
+
+
+async def _serves_after_restart(generation: OpenCodeGeneration) -> bool:
+ for attempt in range(_ADOPTION_PROBES):
+ if await generation.is_healthy() and _pid_listens_on(generation.pid, generation.port):
+ return True
+ if attempt + 1 < _ADOPTION_PROBES:
+ await asyncio.sleep(_ADOPTION_PROBE_INTERVAL_SECONDS)
+ return False
+
+
+async def adopt_recorded_generations(*, request_timeout_seconds: int = 60) -> list[OpenCodeGeneration]:
+ """Adopt every recorded generation still serving after a controller restart.
+
+ A record whose process is gone or unproven is removed without signalling.
+ A proven process that no longer serves is stopped. A legacy single-server
+ record becomes a generation whose spec never matches a new turn's.
+ """
+
+ adopted: list[OpenCodeGeneration] = []
+ adopted_processes: set[tuple[int, Optional[float]]] = set()
+ legacy_path = legacy_pid_file()
+ for path, info in _recorded_processes():
+ is_legacy = path == legacy_path
+ if _owned_here(info, by_id=not is_legacy):
+ # A legacy file a runtime here already converted goes once the
+ # converted record is written.
+ continue
+ if not _record_proves_process(info):
+ _remove_quietly(path)
+ if not is_legacy and isinstance(info.get("generation_id"), str):
+ _remove_quietly(generation_records_dir() / f"{info['generation_id']}.overlay.json")
+ continue
+ if is_legacy and (int(info["pid"]), runtime.process_create_time(int(info["pid"]))) in adopted_processes:
+ # This pass adopted it from its converted record; a crash or a
+ # failed removal after the conversion left this file behind.
+ _remove_quietly(path)
+ continue
+ recorded_id = info.get("generation_id")
+ generation = _generation_from_record(
+ info,
+ generation_id=(
+ recorded_id
+ if isinstance(recorded_id, str) and recorded_id and not is_legacy
+ else f"ocg_{secrets.token_hex(8)}"
+ ),
+ spec_digest=(
+ LEGACY_SPEC_DIGEST
+ if is_legacy or not isinstance(info.get("spec_digest"), str)
+ else str(info["spec_digest"])
+ ),
+ request_timeout_seconds=request_timeout_seconds,
+ )
+ if not await _serves_after_restart(generation):
+ logger.info("Stopping recorded OpenCode server pid=%s that no longer serves", generation.pid)
+ await generation.close_http_session()
+ await asyncio.to_thread(stop_recorded_server_sync, path, info)
+ continue
+ if is_legacy:
+ # The legacy record goes once the generation record replacing it exists.
+ generation._supersedes = path
+ generation.write_record_or_defer("the record of an adopted pre-generations server")
+ logger.info("Adopted OpenCode generation %s pid=%s", generation.generation_id, generation.pid)
+ adopted.append(generation)
+ adopted_processes.add((generation.pid, generation.process_created_at))
+ # No sweep of overlays without a record: another desktop Runtime writes
+ # its overlay before it spawns and records the process.
+ return adopted
+
+
+def _owned_here(info: Mapping[str, Any], *, by_id: bool = True) -> bool:
+ """Whether a runtime of this process started or attached the recorded process."""
+
+ if not _OWNED_HERE:
+ # A CLI process, or a controller whose OpenCode never ran, owns nothing.
+ return False
+ generation_id = info.get("generation_id")
+ if by_id and isinstance(generation_id, str) and generation_id in _OWNED_HERE:
+ return True
+ pid = _record_pid(info)
+ if pid is None:
+ return False
+ return (pid, runtime.process_create_time(pid)) in _OWNED_HERE.values()
+
+
+def own_generation(generation: OpenCodeGeneration) -> None:
+ """Mark an adopted generation as attached to a runtime of this process."""
+ _OWNED_HERE[generation.generation_id] = (generation.pid, generation.process_created_at)
+
+
+def forget_record(path: Path) -> None:
+ """Remove a generation record and the overlay copy beside it.
+
+ The overlay carries the Model Hub gateway credential, so it never outlives
+ its record.
+ """
+
+ _remove_quietly(path)
+ if path.name.endswith(".json") and path.parent == generation_records_dir():
+ _remove_quietly(path.with_name(path.name.removesuffix(".json") + ".overlay.json"))
+
+
+def forget_dead_records(runtime_ids: Optional[frozenset[str]] = None) -> None:
+ """Forget every record of this caller no live process backs, with its overlay."""
+
+ for path, info in _recorded_processes(runtime_ids):
+ if not _record_proves_process(info, require_port=False):
+ forget_record(path)
+
+
+def recorded_servers(runtime_ids: Optional[frozenset[str]] = None) -> list[tuple[int, Path, Dict[str, Any]]]:
+ """This caller's live, proven OpenCode servers, for status and ``vibe stop``."""
+
+ return [
+ (int(info["pid"]), path, info)
+ for path, info in _recorded_processes(runtime_ids)
+ if _record_proves_process(info, require_port=False)
+ ]
+
+
+def stop_recorded_server_sync(path: Path, info: Mapping[str, Any]) -> StopOutcome:
+ """Stop one recorded server outside any runtime, confirming the outcome.
+
+ A record no live process of ours backs is simply forgotten. A process
+ that survives its stop keeps its record, so ``vibe stop`` or the next
+ adoption retries it.
+ """
+
+ if _record_proves_process(info, require_port=False) and not terminate_pid_tree_sync(int(info["pid"])):
+ logger.warning("Recorded OpenCode server pid=%s survived its stop", info["pid"])
+ return StopOutcome.FAILED
+ forget_record(path)
+ return StopOutcome.STOPPED
+
+
+def stop_recorded_servers_sync(runtime_ids: frozenset[str] = frozenset()) -> list[StopOutcome]:
+ """Stop every recorded server of ``runtime_ids`` no runtime of this process owns.
+
+ ``vibe stop`` runs it, as does a controller that starts with OpenCode
+ disabled: no agent there would adopt what a crashed controller left. A
+ record whose process already ended is forgotten with its overlay. A record
+ of another desktop Runtime is left alone. OpenCode starts each tool
+ command in its own session, so each stop takes the whole process tree.
+
+ The result holds one outcome per stop it ran; ``StopOutcome.FAILED`` means
+ a process survived, its record stays, and the caller should retry.
+ """
+
+ forget_dead_records(runtime_ids)
+ outcomes: list[StopOutcome] = []
+ for _pid, path, info in recorded_servers(runtime_ids):
+ if _owned_here(info):
+ continue
+ outcomes.append(stop_recorded_server_sync(path, info))
+ return outcomes
+
+
+def stop_owned_generations_sync() -> None:
+ """Stop every process a runtime of this controller started or adopted.
+
+ An explicit Avibe shutdown runs it. A recorded process stops through its
+ record. One owned here whose record is missing, such as a start whose
+ record write failed, stops by its process identity. A record no runtime
+ here owns, such as one of another desktop Runtime sharing this state
+ directory, is left alone.
+ """
+
+ recorded: set[str] = set()
+ for path, info in _recorded_processes():
+ if _owned_here(info):
+ stop_recorded_server_sync(path, info)
+ if isinstance(info.get("generation_id"), str):
+ recorded.add(info["generation_id"])
+ for generation_id, (pid, created_at) in list(_OWNED_HERE.items()):
+ if generation_id not in recorded:
+ _stop_unrecorded_process_sync(generation_id, pid, created_at)
+
+
+def _stop_unrecorded_process_sync(generation_id: str, pid: int, created_at: Optional[float]) -> None:
+ """Stop an owned process no record names, proven by its pid and create time.
+
+ A process whose create time is unknown or cannot be read now is never
+ signalled: its pid may have been reused. One whose pid is gone, or now
+ names another process, has ended, and is no longer owned here.
+ """
+
+ if _pid_exists(pid):
+ current = runtime.process_create_time(pid)
+ if created_at is None or current is None:
+ logger.warning("Leaving OpenCode generation %s pid=%s: its process cannot be proven", generation_id, pid)
+ return
+ if current == created_at and not terminate_pid_tree_sync(pid):
+ logger.warning("OpenCode generation %s pid=%s survived its stop", generation_id, pid)
+ return
+ _OWNED_HERE.pop(generation_id, None)
+ _remove_quietly(generation_records_dir() / f"{generation_id}.overlay.json")
+
+
diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.py
index 9195052da..90d8a1e72 100644
--- a/modules/agents/opencode/session.py
+++ b/modules/agents/opencode/session.py
@@ -18,7 +18,7 @@ from modules.agents.native_sessions.opencode import OpenCodeNativeSessionProvide
from modules.agents.base import AgentRequest, BaseAgent
from vibe.message_identity import is_input_turn
-from .server import OpenCodeServerManager
+from .server import OpenCodeServerClient
class OpenCodeResumeUnavailableError(RuntimeError):
@@ -211,7 +211,7 @@ class OpenCodeSessionManager:
async def _resolve_running_fork_point(
self,
- server: OpenCodeServerManager,
+ server: OpenCodeServerClient,
source_session_id: str,
directory: str,
fork: dict,
@@ -338,7 +338,7 @@ class OpenCodeSessionManager:
async def repair_message_order(
self,
request: AgentRequest,
- server: OpenCodeServerManager,
+ server: OpenCodeServerClient,
session_id: str,
messages: list[Dict[str, Any]],
) -> str:
@@ -406,7 +406,7 @@ class OpenCodeSessionManager:
async def wait_for_session_idle(
self,
- server: OpenCodeServerManager,
+ server: OpenCodeServerClient,
session_id: str,
directory: str,
timeout_seconds: float = 15.0,
@@ -445,7 +445,7 @@ class OpenCodeSessionManager:
if not os.path.exists(working_path):
os.makedirs(working_path, exist_ok=True)
- async def get_or_create_session_id(self, request: AgentRequest, server: OpenCodeServerManager) -> Optional[str]:
+ async def get_or_create_session_id(self, request: AgentRequest, server: OpenCodeServerClient) -> Optional[str]:
"""Get a cached OpenCode session id, or create a new session.
The session anchor is the bare base (the thread's identity), independent
diff --git a/modules/agents/opencode_agent.py b/modules/agents/opencode_agent.py
index 24ce6c07f..9448a0d4f 100644
--- a/modules/agents/opencode_agent.py
+++ b/modules/agents/opencode_agent.py
@@ -10,14 +10,12 @@ Keep this module to preserve the public import path:
from modules.agents.opencode import (
OpenCodeAgent,
- OpenCodeServerManager,
build_codex_reasoning_options,
build_reasoning_effort_options,
)
__all__ = [
"OpenCodeAgent",
- "OpenCodeServerManager",
"build_codex_reasoning_options",
"build_reasoning_effort_options",
]
diff --git a/modules/agents/runtime_generations.py b/modules/agents/runtime_generations.py
new file mode 100644
index 000000000..351ca5a3f
--- /dev/null
+++ b/modules/agents/runtime_generations.py
@@ -0,0 +1,364 @@
+"""Runtime generations: one runtime unit's processes across launch changes.
+
+A runtime unit (a Codex working directory, the OpenCode instance) serves new
+turns on its current generation. When a turn needs a different launch spec, the
+new generation starts and the old one retires: it keeps serving the work bound
+to it and stops once that work is released. New turns never wait for old work;
+at the cap, the oldest retiring generation is force-stopped instead.
+
+Admission is pure bookkeeping: every method that changes state does so in one
+synchronous step and never awaits a teardown. One reconciler task per set owns
+every stop. It runs them one at a time and re-evaluates the cap and the drained
+generations after each, so a stop that declines, fails, or is cancelled simply
+leaves its generation attached for the next pass.
+
+Adapters own everything backend-specific: the spec (whose digest includes their
+renewal epoch, so a manual restart is just a new spec), how a runtime starts and
+stops, any evidence of work beyond bindings, and the notice a forced stop shows.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import itertools
+import logging
+from dataclasses import dataclass
+from typing import Awaitable, Callable, Generic, Protocol, TypeVar
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_GENERATION_CAP = 3
+
+
+class LaunchSpec(Protocol):
+ """The process-level inputs of a unit; two specs are equal when their digests are."""
+
+ @property
+ def digest(self) -> str: ...
+
+
+_S = TypeVar("_S", bound=LaunchSpec)
+_R = TypeVar("_R")
+
+
+class RuntimeUnitStopping(RuntimeError):
+ """The unit is shutting down and admits no more work."""
+
+
+@dataclass(eq=False)
+class RuntimeGeneration(Generic[_S, _R]):
+ """One running process of a unit, started from one launch spec."""
+
+ spec: _S
+ runtime: _R
+ serial: int
+ retiring: bool = False
+ stopped: bool = False
+ bindings: int = 0
+ # Never promoted back to current: retired on purpose, or its teardown failed.
+ closed: bool = False
+ # Its graceful stop declined; the next sweep or release retries it.
+ deferred: bool = False
+ # Its stop failed; only the next sweep retries it, even at the cap.
+ failed: bool = False
+
+
+@dataclass(eq=False)
+class RuntimeBinding(Generic[_S, _R]):
+ """Work bound to one generation; it keeps that generation alive until released."""
+
+ generation: RuntimeGeneration[_S, _R]
+ _owner: "RuntimeGenerationSet[_S, _R]"
+ released: bool = False
+
+ async def release(self) -> None:
+ """Release this binding; any task may call it, and only once counts."""
+ self._owner._release(self)
+
+
+class RuntimeGenerationSet(Generic[_S, _R]):
+ """The generations of one runtime unit."""
+
+ def __init__(
+ self,
+ *,
+ start: Callable[[_S], Awaitable[_R]],
+ stop: Callable[[RuntimeGeneration[_S, _R], bool], Awaitable[bool]],
+ cap: int = DEFAULT_GENERATION_CAP,
+ ) -> None:
+ """``stop(generation, force)`` returns False to decline a graceful stop.
+
+ A graceful stop runs only once no binding remains; the adapter declines
+ while its own evidence still shows work. A forced stop must end the
+ process. A stop that declines or fails is retried by the next sweep.
+ """
+ if cap < 2:
+ raise ValueError("a runtime unit needs room for a current and a retiring generation")
+ self._start = start
+ self._stop = stop
+ self._cap = cap
+ self._start_lock = asyncio.Lock()
+ self._serials = itertools.count(1)
+ self._current: RuntimeGeneration[_S, _R] | None = None
+ self._retiring: list[RuntimeGeneration[_S, _R]] = []
+ self._stopping = False
+ self._force_all = False
+ self._reconciler: asyncio.Task[None] | None = None
+ # The serials a reconciler pass has already tried, per kind of stop, so
+ # a stop that keeps failing waits for a retry instead of looping.
+ self._tried_forced: set[int] = set()
+ self._tried_graceful: set[int] = set()
+ # Bumped by every retry request; a stop that was running when one
+ # arrived leaves its generation eligible for another attempt.
+ self._retry_requests = 0
+
+ @property
+ def current(self) -> RuntimeGeneration[_S, _R] | None:
+ return self._current
+
+ @property
+ def generations(self) -> tuple[RuntimeGeneration[_S, _R], ...]:
+ """Every attached generation, oldest first."""
+ return (*self._retiring, *((self._current,) if self._current is not None else ()))
+
+ async def acquire(self, spec: _S) -> RuntimeBinding[_S, _R]:
+ """Bind a new turn that needs ``spec`` to the generation that serves it."""
+ binding = self._bind_serving(spec)
+ if binding is not None:
+ return binding
+ # Starts are serialized, but turns a live generation already serves never
+ # queue behind one.
+ async with self._start_lock:
+ binding = self._bind_serving(spec)
+ if binding is not None:
+ return binding
+ # A failed start leaves the current generation serving.
+ runtime = await self._start(spec)
+ generation = RuntimeGeneration(spec, runtime, next(self._serials))
+ if self._stopping:
+ generation.closed = True
+ self._add_retiring(generation)
+ self._kick()
+ raise RuntimeUnitStopping("runtime unit is stopping")
+ self._install_current(generation)
+ return self._bind(generation)
+
+ async def bind(self, generation: RuntimeGeneration[_S, _R]) -> RuntimeBinding[_S, _R]:
+ """Bind recovered work, such as a restored poll, to its known generation."""
+ self._admitting()
+ if generation.stopped:
+ raise RuntimeError("cannot bind work to a stopped runtime generation")
+ return self._bind(generation)
+
+ async def adopt(self, spec: _S, runtime: _R, *, current: bool) -> RuntimeGeneration[_S, _R]:
+ """Register a process found running, for example after a controller restart."""
+ self._admitting()
+ generation = RuntimeGeneration(spec, runtime, next(self._serials))
+ if current:
+ self._install_current(generation)
+ else:
+ self._add_retiring(generation)
+ self._kick()
+ return generation
+
+ async def retire(self, generation: RuntimeGeneration[_S, _R]) -> None:
+ """Admit no new turn to a generation; it stops once its work is released."""
+ self._retire(generation)
+
+ async def retire_current(self) -> None:
+ """Retire whichever generation is current, for example when a backend is disabled."""
+ if self._current is not None:
+ self._retire(self._current)
+
+ async def discard(self, generation: RuntimeGeneration[_S, _R]) -> None:
+ """Forget a generation whose process already ended or was retired elsewhere."""
+ self._detach(generation)
+
+ async def reap(self) -> None:
+ """Retry every retiring generation, then wait for the stops this starts."""
+ self._request_retry()
+ self._kick()
+ await self.settled()
+
+ async def stop_all(self, *, force: bool) -> None:
+ """Admit nothing more and stop every generation, for example at shutdown.
+
+ A graceful stop-all retires every generation: unbound ones stop now and
+ bound ones stop when their work is released. A forced one stops all.
+ """
+ self._stopping = True
+ self._force_all = self._force_all or force
+ for generation in self.generations:
+ generation.closed = True
+ if generation is self._current:
+ self._current = None
+ self._add_retiring(generation)
+ self._request_retry()
+ self._kick()
+ # A start already in flight attaches its runtime for teardown once it
+ # returns; wait for it so every process started before admission closed
+ # is covered.
+ async with self._start_lock:
+ pass
+ await self.settled()
+
+ async def settled(self) -> None:
+ """Wait until the reconciler has no stop left to run."""
+ while self._reconciler is not None and not self._reconciler.done():
+ await asyncio.shield(self._reconciler)
+
+ def _request_retry(self) -> None:
+ """Entitle every generation to one more stop attempt, including one whose stop is running."""
+ self._retry_requests += 1
+ self._tried_forced.clear()
+ self._tried_graceful.clear()
+ for generation in self._retiring:
+ generation.deferred = False
+ generation.failed = False
+
+ def _admitting(self) -> None:
+ if self._stopping:
+ raise RuntimeUnitStopping("runtime unit is stopping")
+
+ def _bind_serving(self, spec: _S) -> RuntimeBinding[_S, _R] | None:
+ self._admitting()
+ current = self._current
+ if current is not None and current.spec.digest == spec.digest:
+ return self._bind(current)
+ match = next(
+ (item for item in reversed(self._retiring) if item.spec.digest == spec.digest and not item.closed),
+ None,
+ )
+ if match is None:
+ return None
+ # A live generation already serves this spec, for example when sessions
+ # alternate between two launch channels.
+ self._retiring.remove(match)
+ match.retiring = False
+ match.deferred = False
+ self._install_current(match)
+ return self._bind(match)
+
+ def _install_current(self, generation: RuntimeGeneration[_S, _R]) -> None:
+ previous = self._current
+ self._current = generation
+ if previous is not None and previous is not generation:
+ # The new generation already serves, so an unbound predecessor stops
+ # without a gap.
+ self._add_retiring(previous)
+ self._kick()
+
+ def _retire(self, generation: RuntimeGeneration[_S, _R]) -> None:
+ if generation.stopped:
+ return
+ generation.closed = True
+ if self._current is generation:
+ self._current = None
+ if generation not in self._retiring:
+ self._add_retiring(generation)
+ self._kick()
+
+ def _bind(self, generation: RuntimeGeneration[_S, _R]) -> RuntimeBinding[_S, _R]:
+ generation.bindings += 1
+ return RuntimeBinding(generation, self)
+
+ def _release(self, binding: RuntimeBinding[_S, _R]) -> None:
+ if binding.released:
+ return
+ binding.released = True
+ generation = binding.generation
+ generation.bindings -= 1
+ if generation.retiring and generation.bindings == 0:
+ # Drained now, so its graceful stop deserves another attempt even
+ # if this pass already tried one while it was still bound.
+ generation.deferred = False
+ self._tried_graceful.discard(generation.serial)
+ self._kick()
+
+ def _add_retiring(self, generation: RuntimeGeneration[_S, _R]) -> None:
+ # Oldest first, so the cap always gives way from the oldest work.
+ generation.retiring = True
+ self._retiring.append(generation)
+ self._retiring.sort(key=lambda item: item.serial)
+
+ def _detach(self, generation: RuntimeGeneration[_S, _R]) -> None:
+ if generation in self._retiring:
+ self._retiring.remove(generation)
+ if self._current is generation:
+ self._current = None
+ generation.retiring = False
+ generation.stopped = True
+
+ def _kick(self) -> None:
+ if self._reconciler is None or self._reconciler.done():
+ self._reconciler = asyncio.get_running_loop().create_task(self._reconcile())
+
+ def _next_victim(self) -> tuple[RuntimeGeneration[_S, _R], bool] | None:
+ # Each pass tries a generation at most once per kind of stop until a
+ # retry is requested, so a stop that keeps failing never loops, while a
+ # declined graceful stop can still be forced in this pass.
+ unforced = [generation for generation in self._retiring if generation.serial not in self._tried_forced]
+ if self._force_all and unforced:
+ return unforced[0], True
+ if not self._stopping and len(self._retiring) + (self._current is not None) > self._cap and unforced:
+ # Never make a new turn wait: the oldest work gives way, whether its
+ # adapter still reports work or an earlier stop failed. A stopping
+ # unit admits no new turn, so a start that lands after admission
+ # closed stops by itself instead of costing the oldest its work.
+ return unforced[0], True
+ drained = next(
+ (
+ generation
+ for generation in unforced
+ if generation.serial not in self._tried_graceful
+ and generation.bindings == 0
+ and not generation.deferred
+ and not generation.failed
+ ),
+ None,
+ )
+ return (drained, False) if drained is not None else None
+
+ async def _reconcile(self) -> None:
+ self._tried_forced.clear()
+ self._tried_graceful.clear()
+ while (choice := self._next_victim()) is not None:
+ generation, force = choice
+ (self._tried_forced if force else self._tried_graceful).add(generation.serial)
+ requests = self._retry_requests
+ self._detach(generation)
+ try:
+ stopped = await self._stop(generation, force)
+ except asyncio.CancelledError:
+ self._reattach(generation, failed=True, retry=False)
+ raise
+ except Exception:
+ logger.warning(
+ "Runtime generation %s failed to stop; keeping it for the next sweep",
+ generation.serial,
+ exc_info=True,
+ )
+ self._reattach(generation, failed=True, retry=self._retry_requests != requests)
+ continue
+ if stopped is False:
+ # The adapter still sees work. A forced stop that declines is a
+ # failure; a graceful one is retried by the next sweep or release.
+ self._reattach(generation, failed=force, retry=self._retry_requests != requests)
+
+ def _reattach(self, generation: RuntimeGeneration[_S, _R], *, failed: bool, retry: bool) -> None:
+ """Track a generation whose stop did not finish.
+
+ ``retry`` means a retry was requested while the stop ran, so the
+ generation stays eligible for one more attempt in this pass.
+ """
+ generation.stopped = False
+ if failed:
+ # A process whose teardown went wrong never serves a turn again.
+ generation.closed = True
+ if not retry:
+ if failed:
+ generation.failed = True
+ else:
+ generation.deferred = True
+ if generation not in self._retiring:
+ self._add_retiring(generation)
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 712ea62c3..8caad89e6 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -3,7 +3,7 @@ import asyncio
import inspect
import uuid
from dataclasses import dataclass, field
-from typing import Any, Callable, Dict, Optional
+from typing import Any, Awaitable, Callable, Dict, Iterable, Optional
from core.run_settlement import SETTLED_BY_BACKEND_REFRESH
from core.session_activities import SessionActivityRegistry
@@ -52,6 +52,9 @@ class AgentService:
):
self.controller = controller
self.agents: Dict[str, BaseAgent] = {}
+ # Teardowns that must finish even after they failed once, such as a
+ # disabled backend's processes; the idle sweep retries them.
+ self._pending_operations: Dict[str, tuple[Callable[[], Awaitable[None]], Optional[asyncio.Lock]]] = {}
self.default_agent = "claude"
self._turn_gates: dict[str, _RuntimeTurnGate] = {}
self.activities = activities or SessionActivityRegistry()
@@ -191,23 +194,131 @@ class AgentService:
logger.debug("Backend active-runtime probe failed for %s", backend, exc_info=True)
return True
- def force_end_backend_activities(self, backend: str) -> list[Any]:
- """End every Activity of a runtime the service is tearing down itself."""
+ def force_end_backend_activities(self, backend: str, *, reason: str = SETTLED_BY_BACKEND_REFRESH) -> list[Any]:
+ """End every Activity of a runtime the service is tearing down itself.
+
+ ``reason`` is the settlement: a runtime refresh, or the user disabling
+ the backend.
+ """
# The cause rides on each Activity it ends, so a settlement retried
- # after a transient failure or a restart still reports the refresh.
+ # after a transient failure or a restart still reports it.
completed = self.activities.end_backend(
backend,
status="killed",
- metadata={"interrupt_reason": SETTLED_BY_BACKEND_REFRESH},
+ metadata={"interrupt_reason": reason},
)
for activity in completed:
self.on_activity_terminal(activity)
return completed
+ def force_end_runtime_activities(
+ self, backend: str, runtime_key: str, *, reason: str = SETTLED_BY_BACKEND_REFRESH
+ ) -> list[Any]:
+ """End the Activities of one runtime the service replaces or stops itself."""
+ # Retained until the Run owner settles them, like a whole-backend stop,
+ # so a transient settlement failure leaves something to retry.
+ completed = self.activities.end_runtime(
+ backend,
+ runtime_key,
+ status="killed",
+ retain_terminal_snapshots=True,
+ force=True,
+ metadata={"interrupt_reason": reason},
+ )
+ for activity in completed:
+ self.on_activity_terminal(activity)
+ return completed
+
+ def activation_has_activities(
+ self, backend: str, activation_identity: Optional[RuntimeActivationIdentity]
+ ) -> bool:
+ """Whether a process still runs an Activity it started.
+
+ A graceful stop must decline while one does: an Activity can outlive
+ its turn and its Session's move to a newer process, so no Session
+ binding names it any longer.
+ """
+ if activation_identity is None:
+ return False
+ return self.activities.has_active_for_activation(backend, activation_identity)
+
+ def force_end_activation_activities(
+ self,
+ backend: str,
+ activation_identities: Iterable[Optional[RuntimeActivationIdentity]],
+ *,
+ reason: str = SETTLED_BY_BACKEND_REFRESH,
+ ) -> list[Any]:
+ """End every Activity started under one of ``activation_identities``.
+
+ A process's Activities are found by the activation it started them
+ under, whatever runtime key they carry: an Activity can outlive the
+ turn or thread binding that named it, and after a backend is enabled
+ again a new agent's Activities can share its runtime keys. An unknown
+ identity (None) proves nothing and ends nothing.
+ """
+ completed = []
+ for identity in activation_identities:
+ if identity is None:
+ continue
+ for runtime_key in sorted(self.activities.runtime_keys_for_activation(backend, identity)):
+ # Retained until the Run owner settles them, as above.
+ completed.extend(
+ self.activities.end_runtime(
+ backend,
+ runtime_key,
+ status="killed",
+ retain_terminal_snapshots=True,
+ activation_identity=identity,
+ metadata={"interrupt_reason": reason},
+ )
+ )
+ for activity in completed:
+ self.on_activity_terminal(activity)
+ return completed
+
def register(self, agent: BaseAgent):
self.agents[agent.name] = agent
logger.info(f"Registered agent backend: {agent.name}")
+ async def run_until_done(
+ self,
+ key: str,
+ operation: Callable[[], Awaitable[None]],
+ *,
+ retry_lock: Optional[asyncio.Lock] = None,
+ ) -> bool:
+ """Run an operation that must eventually finish; True once it has.
+
+ A backend lifecycle step with no other owner left to retry it uses
+ this: a disabled agent's teardown, whose agent is already gone, or the
+ poll restore of a backend enabled after its transports became ready.
+ A failure is logged and kept, and ``retry_pending`` runs it again on
+ every idle sweep until it succeeds, so it must be safe to repeat. A
+ cancelled requester never leaves it half done. A retry holds
+ ``retry_lock``, the lock the first run's caller held, so it never
+ interleaves with a later change.
+ """
+ from core.backend_restart import finish_native_operation
+
+ self._pending_operations.pop(key, None)
+ try:
+ await finish_native_operation(operation())
+ except Exception:
+ logger.warning("%s failed; the idle sweep retries it", key, exc_info=True)
+ self._pending_operations[key] = (operation, retry_lock)
+ return False
+ return True
+
+ async def retry_pending(self) -> None:
+ for key, (operation, retry_lock) in list(self._pending_operations.items()):
+ if retry_lock is None:
+ await self.run_until_done(key, operation)
+ continue
+ async with retry_lock:
+ if key in self._pending_operations:
+ await self.run_until_done(key, operation, retry_lock=retry_lock)
+
def _on_activity_output_settled(self, activity: Any) -> None:
agent = self.agents.get(str(getattr(activity, "backend", "") or ""))
notify = getattr(agent, "on_activity_output_settled", None)
@@ -1099,10 +1210,56 @@ class AgentService:
async def force_cancel_backend_turns(self, backend: str) -> None:
"""Cancel every foreground owner and emit a terminal outcome before cutover."""
+ await self._force_cancel_turns(lambda gate: gate.backend == backend)
+
+ async def force_end_runtime_work(
+ self,
+ backend: str,
+ *,
+ base_session_ids: set[str],
+ activation_identities: Iterable[Optional[RuntimeActivationIdentity]],
+ reason: str = SETTLED_BY_BACKEND_REFRESH,
+ agent: Optional[BaseAgent] = None,
+ ) -> None:
+ """Interrupt the work of a runtime the service stops itself.
+
+ The scoped form of a forced backend refresh: the named sessions' turns
+ and the Activities started under ``activation_identities`` (the
+ stopping processes') settle with ``reason``'s notice (a runtime update,
+ or the backend disabled), and every other session keeps running.
+
+ ``agent`` is the agent instance whose runtime stops. A Session whose
+ running turn another instance holds is left alone: after a backend is
+ enabled again, a disabled agent's retried stop names Sessions whose
+ next turn may already run on the new agent.
+ """
+ # Only the turns running now: a session's next turn, admitted while the
+ # release below awaits, runs elsewhere and is not this runtime's work.
+ gates = [
+ gate
+ for gate in self._turn_gates.values()
+ if gate.token
+ and gate.backend == backend
+ and getattr(gate.request, "base_session_id", None) in base_session_ids
+ ]
+ if agent is not None:
+ base_session_ids = set(base_session_ids) - {
+ gate.request.base_session_id for gate in gates if gate.agent is not None and gate.agent is not agent
+ }
+ gates = [gate for gate in gates if gate.agent is None or gate.agent is agent]
+ tokens = {gate.token for gate in gates}
+ manager = getattr(self.controller, "session_turns", None)
+ release = getattr(manager, "release_for_backend_refresh", None)
+ if callable(release) and base_session_ids:
+ await release(backend=backend, base_session_ids=set(base_session_ids), settled_by=reason)
+ await self._force_cancel_turns(lambda gate: gate.token in tokens)
+ self.force_end_activation_activities(backend, activation_identities, reason=reason)
+
+ async def _force_cancel_turns(self, owns: Callable[["_RuntimeTurnGate"], bool]) -> None:
owned = [
(runtime_key, gate, gate.token)
for runtime_key, gate in self._turn_gates.items()
- if gate.backend == backend and gate.token
+ if gate.token and owns(gate)
]
tasks = {
gate.task
@@ -1340,17 +1497,6 @@ class AgentService:
finally:
self.release_runtime_turn_tokens(runtime_tokens)
- async def invalidate_model_hub_runtime(self, agent_name: str) -> bool:
- """Invalidate future Hub-only runtime state without disturbing Direct work."""
- agent = self.agents.get(agent_name)
- if agent is None:
- return False
- invalidate = getattr(agent, "invalidate_model_hub_runtime", None)
- if not callable(invalidate):
- return False
- await invalidate()
- return True
-
@dataclass
class _RuntimeTurnGate:
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index 60034c389..cbd7afff4 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -569,6 +569,7 @@ class SessionsFacade:
seen_tool_calls: Optional[List[str]] = None,
emitted_assistant_messages: Optional[List[str]] = None,
prompt_started_at: Optional[float] = None,
+ processing_indicator: Optional[Dict[str, Any]] = None,
) -> None:
poll_info = self.sessions_store.get_active_poll(opencode_session_id)
if poll_info:
@@ -578,6 +579,8 @@ class SessionsFacade:
poll_info.emitted_assistant_messages = emitted_assistant_messages
if prompt_started_at is not None:
poll_info.prompt_started_at = prompt_started_at
+ if processing_indicator is not None:
+ poll_info.processing_indicator = processing_indicator
self.sessions_store.update_active_poll(poll_info)
def get_all_active_polls(self) -> Dict[str, Any]:
diff --git a/storage/background.py b/storage/background.py
index 0e8ce46c7..fa3905e55 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1795,6 +1795,7 @@ RUN_INTERRUPTION_REASONS = frozenset(
{
"stopped",
"backend_refresh",
+ "backend_disabled",
"interrupted",
"evicted",
"restarted",
diff --git a/tests/codex_generation_support.py b/tests/codex_generation_support.py
new file mode 100644
index 000000000..726cc3cd8
--- /dev/null
+++ b/tests/codex_generation_support.py
@@ -0,0 +1,145 @@
+"""Install fake Codex app-server generations on test agents.
+
+Tests that build a ``CodexAgent`` without ``__init__`` use these helpers to
+place a fake transport into a working directory's generation set exactly as a
+started app-server would be, without spawning a process.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import itertools
+from collections import OrderedDict
+from dataclasses import dataclass
+from types import SimpleNamespace
+from typing import Any, Mapping
+
+import modules.agents.codex.agent as codex_agent_module
+from modules.agents.codex.agent import CodexAgent, _CodexRuntime
+
+
+@dataclass(frozen=True)
+class FakeLaunchSpec:
+ digest: str
+ hub: bool = False
+
+ def close(self) -> None:
+ return None
+
+
+def init_generation_state(agent: Any) -> Any:
+ """Give an ``__init__``-less agent the generation state ``__init__`` creates."""
+ agent._units = {}
+ agent._session_generations = {}
+ agent._generation_serials = itertools.count(1)
+ agent._runtimes = {}
+ agent._shutting_down = False
+ agent._instance_serial = next(codex_agent_module._AGENT_INSTANCE_SERIALS)
+ agent._runtime_epoch = 0
+ agent._reap_tasks = set()
+ agent._model_hub_catalogs = OrderedDict()
+ agent._model_hub_catalog_lock = asyncio.Lock()
+ if not hasattr(agent, "_session_last_activity"):
+ agent._session_last_activity = {}
+ if not hasattr(agent, "_session_locks"):
+ agent._session_locks = {}
+ return agent
+
+
+def codex_agent_shell() -> CodexAgent:
+ """A ``CodexAgent`` without ``__init__`` that can hold generations."""
+ return init_generation_state(object.__new__(CodexAgent))
+
+
+def run_unlocked(coro: Any) -> Any:
+ """Drive a generation-set call whose lock is free, from sync or async tests."""
+ try:
+ coro.send(None)
+ except StopIteration as done:
+ return done.value
+ coro.close()
+ raise RuntimeError("the generation set is busy")
+
+
+def install_codex_transport(
+ agent: Any,
+ cwd: str,
+ transport: Any,
+ *,
+ sessions: Mapping[str, str] | None = None,
+ digest: str = "installed",
+ hub: bool = False,
+ activation: Any = None,
+ current: bool = True,
+ last_activity: float | None = None,
+) -> Any:
+ """Adopt ``transport`` as a running generation of ``cwd``; return its wrapper.
+
+ ``sessions`` maps base session ids to the thread each has loaded there.
+ """
+ if not hasattr(agent, "_units"):
+ init_generation_state(agent)
+ runtime = _CodexRuntime(
+ cwd=cwd,
+ serial=next(agent._generation_serials),
+ transport=transport,
+ hub=hub,
+ activation=activation,
+ )
+ if last_activity is not None:
+ runtime.last_activity = last_activity
+ agent._runtimes.setdefault(cwd, set()).add(runtime)
+ unit = agent._unit(cwd)
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ # A sync test has no loop to run the stop reconciler on.
+ unit._kick = lambda: None
+ try:
+ generation = run_unlocked(unit.adopt(FakeLaunchSpec(digest, hub), runtime, current=current))
+ finally:
+ unit.__dict__.pop("_kick", None)
+ for base_session_id, thread_id in (sessions or {}).items():
+ agent._bind_session_thread(generation, base_session_id, thread_id)
+ return generation
+
+
+def bind_installed(agent: Any, generation: Any) -> Any:
+ """A binding on an installed generation, as ``_acquire_generation`` returns."""
+ return run_unlocked(agent._unit(generation.runtime.cwd).bind(generation))
+
+
+def codex_transports(agent: Any) -> dict[str, Any]:
+ """Each working directory's current transport."""
+ return {
+ cwd: unit.current.runtime.transport
+ for cwd, unit in getattr(agent, "_units", {}).items()
+ if unit.current is not None
+ }
+
+
+def acquire_returning(agent: Any, *transports: Any, session: str | None = "session-1") -> Any:
+ """A mock ``_acquire_generation`` that serves each transport in turn.
+
+ Each call adopts the next transport as the directory's current generation
+ with ``session`` already loaded there, so the turn needs no move. The
+ launch load a turn takes at admission only feeds acquisition, so it is
+ stubbed too, keeping its Model Hub snapshot.
+ """
+ from unittest.mock import AsyncMock
+
+ agent._launch_inputs = lambda cwd, *, hub_config=None: SimpleNamespace(hub_config=hub_config)
+ queue = list(transports)
+ served = itertools.count(1)
+
+ async def acquire(cwd: str, launch: Any = None, *, inputs: Any = None) -> Any:
+ generation = install_codex_transport(
+ agent,
+ cwd,
+ queue.pop(0),
+ sessions={session: "loaded-thread"} if session else None,
+ digest=f"acquired-{next(served)}",
+ )
+ return bind_installed(agent, generation)
+
+ return AsyncMock(side_effect=acquire)
diff --git a/tests/e2e/test_codex_runtime_generations_contract.py b/tests/e2e/test_codex_runtime_generations_contract.py
new file mode 100644
index 000000000..f30843c8f
--- /dev/null
+++ b/tests/e2e/test_codex_runtime_generations_contract.py
@@ -0,0 +1,127 @@
+"""RUNTIME-GEN-019: the real Codex CLI contract that app-server generations rely on.
+
+Two app-servers share one working directory and one ``CODEX_HOME``. A thread
+loaded in one cannot be resumed in the other until the first unsubscribes from
+it and reports ``thread/closed``; the move appends nothing to the rollout.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import shutil
+from pathlib import Path
+
+import pytest
+
+from modules.agents.codex.transport import CodexRPCError, CodexTransport
+from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
+from tests.e2e.test_model_hub_catalog_consumer import ( # noqa: F401 -- fixture dependency
+ _isolated_runtime,
+ _loopback_cli,
+ rejected_external_proxy,
+)
+
+
+pytestmark = pytest.mark.e2e_model_hub
+
+
+class _Server:
+ def __init__(self, binary, runtime, cwd):
+ self.transport = CodexTransport(binary=binary, cwd=cwd, runtime_env=runtime.env)
+ self.completed: dict[str, asyncio.Queue] = {}
+ self.closed: dict[str, asyncio.Event] = {}
+ self.transport.on_notification(self._notify)
+
+ async def _notify(self, method, params):
+ thread_id = params.get("threadId")
+ if method == "turn/completed":
+ self.completed.setdefault(thread_id, asyncio.Queue()).put_nowait(params)
+ elif method == "thread/closed":
+ self.closed.setdefault(thread_id, asyncio.Event()).set()
+
+ async def turn(self, thread_id, text):
+ queue = self.completed.setdefault(thread_id, asyncio.Queue())
+ await self.transport.send_request(
+ "turn/start", {"threadId": thread_id, "input": [{"type": "text", "text": text}]}
+ )
+ done = await asyncio.wait_for(queue.get(), timeout=60)
+ assert done["turn"]["status"] == "completed", done
+
+
+def _digest(path: Path) -> tuple[int, str]:
+ data = path.read_bytes()
+ return len(data), hashlib.sha256(data).hexdigest()
+
+
+def codex_home_runtime(tmp_path, rejected_external_proxy):
+ binary = shutil.which("codex")
+ if binary is None:
+ pytest.skip("Codex executable is unavailable")
+ runtime = _isolated_runtime(tmp_path, rejected_external_proxy)
+ binary = _loopback_cli(binary, runtime)
+ codex_home = Path(runtime.env["CODEX_HOME"])
+ codex_home.mkdir()
+ node = shutil.which("node")
+ if node:
+ runtime.env["PATH"] += ":" + str(Path(node).parent)
+ upstream = MockLLMUpstream().start()
+ upstream.configure(protocol="openai_responses")
+ runtime.env["PROBE_API_KEY"] = "fixture-only"
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "file"\n'
+ 'model = "generation-fixture"\n'
+ 'model_provider = "fixture"\n'
+ "[model_providers.fixture]\n"
+ 'name = "fixture"\n'
+ f'base_url = "{upstream.url}/v1"\n'
+ 'wire_api = "responses"\n'
+ 'env_key = "PROBE_API_KEY"\n'
+ )
+ workdir = runtime.home / "工作 目录"
+ workdir.mkdir()
+ try:
+ yield binary, runtime, str(workdir)
+ finally:
+ upstream.stop()
+
+
+async def test_runtime_gen_019_a_thread_moves_between_app_servers_only_after_release(codex_home_runtime):
+ binary, runtime, cwd = codex_home_runtime
+ old = _Server(binary, runtime, cwd)
+ new = _Server(binary, runtime, cwd)
+ try:
+ await old.transport.start()
+ await new.transport.start()
+ started = await old.transport.send_request(
+ "thread/start", {"cwd": cwd, "approvalPolicy": "never", "sandbox": "danger-full-access"}
+ )
+ thread_id = started["thread"]["id"]
+ rollout = Path(started["thread"]["path"])
+ await old.turn(thread_id, "第一轮 on the old process")
+
+ # Codex lets one process at a time write a thread.
+ with pytest.raises(CodexRPCError, match="active writer"):
+ await new.transport.send_request("thread/resume", {"threadId": thread_id, "excludeTurns": True})
+
+ before = _digest(rollout)
+ closed = old.closed.setdefault(thread_id, asyncio.Event())
+ response = await old.transport.send_request("thread/unsubscribe", {"threadId": thread_id})
+ assert response["status"] == "unsubscribed"
+ # Avibe's thread_unload_delay_secs=0 unloads an idle thread at once.
+ await asyncio.wait_for(closed.wait(), timeout=5)
+ assert _digest(rollout) == before
+
+ await new.transport.send_request("thread/resume", {"threadId": thread_id, "excludeTurns": True})
+ await new.turn(thread_id, "second turn on the new process")
+ moved = _digest(rollout)
+
+ await old.transport.stop()
+ await asyncio.sleep(0.5)
+ assert _digest(rollout) == moved
+ read = await new.transport.send_request("thread/read", {"threadId": thread_id, "includeTurns": True})
+ assert [turn["status"] for turn in read["thread"]["turns"]] == ["completed", "completed"]
+ finally:
+ await old.transport.stop()
+ await new.transport.stop()
diff --git a/tests/opencode_generation_fakes.py b/tests/opencode_generation_fakes.py
new file mode 100644
index 000000000..84afbb03b
--- /dev/null
+++ b/tests/opencode_generation_fakes.py
@@ -0,0 +1,158 @@
+"""A one-generation stand-in for the OpenCode runtime, serving a fake server.
+
+Adapter tests that exercise a turn, a stop, or a restored poll need the agent
+to bind work to some server. The stand-in records every acquire, bind, and
+release, so a test can assert that work held its generation exactly as long as
+it ran.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+
+class FakeBinding:
+ def __init__(self, server: Any) -> None:
+ self.generation = SimpleNamespace(runtime=server, stopped=False)
+ self.released = False
+
+ async def release(self) -> None:
+ self.released = True
+
+
+class FakeOpenCodeRuntime:
+ def __init__(self, server: Any, agent: Any = None) -> None:
+ self.server = server
+ self._agent = agent
+ self.bindings: list[FakeBinding] = []
+ self.specs: list[Any] = []
+ self.last_start_failure_pid = None
+ self.start_failures = 0
+ self.adopted = True
+ self.outside_turn_acquisitions = 0
+
+ def launch_inputs(self) -> Any:
+ # The real runtime's config is the agent's ``agents.opencode`` object.
+ agent = self._agent
+ settings = getattr(agent, "opencode_config", None) or getattr(
+ getattr(getattr(agent, "controller", None), "config", None), "opencode", None
+ )
+ return SimpleNamespace(settings=settings)
+
+ async def launch_spec(self, overlay: Any, inputs: Any) -> Any:
+ spec = SimpleNamespace(digest="spec", overlay=overlay)
+ self.specs.append(spec)
+ return spec
+
+ async def acquire(self, spec: Any) -> FakeBinding:
+ binding = FakeBinding(self.server)
+ self.bindings.append(binding)
+ return binding
+
+ async def bind(self, generation: Any) -> FakeBinding:
+ binding = FakeBinding(generation)
+ self.bindings.append(binding)
+ return binding
+
+ async def ensure_adopted(self) -> None:
+ return None
+
+ def current(self) -> Any:
+ return self.server
+
+ def has_bound_work(self) -> bool:
+ return any(not binding.released for binding in self.bindings)
+
+ def generations(self) -> tuple[Any, ...]:
+ return (self.server,) if self.server is not None else ()
+
+ def generation(self, generation_id: str) -> Any:
+ if self.server is not None and getattr(self.server, "generation_id", None) == generation_id:
+ return self.server
+ return None
+
+ async def reap(self) -> None:
+ return None
+
+
+def serve_opencode_agent(agent: Any, server: Any) -> FakeOpenCodeRuntime:
+ """Make ``agent`` run every turn on ``server`` as its only generation."""
+
+ if server is not None and not hasattr(server, "generation_id"):
+ server.generation_id = "ocg_test"
+ if server is not None and not hasattr(server, "active_run_sessions"):
+ server.active_run_sessions = set()
+ runtime = FakeOpenCodeRuntime(server, agent)
+ agent._runtime = runtime
+ agent._session_generations = {}
+ agent._lifecycle_tasks = set()
+ agent._resource_failures = {}
+ return runtime
+
+
+class FakeServerLease:
+ """A lease on ``server``, recording whether its holder released it."""
+
+ def __init__(self, server: Any) -> None:
+ self.server = server
+ self.lease_id = "ocl_test"
+ self.released = False
+
+ async def release(self) -> None:
+ self.released = True
+
+
+def lease_returning(server: Any):
+ """An ``AgentAuthService._lease_opencode_server`` stand-in that leases ``server``.
+
+ Its ``leases`` list holds every lease it handed out, and ``ttls`` the
+ lifetime each one asked for.
+ """
+
+ leases: list[FakeServerLease] = []
+ ttls: list[float] = []
+
+ async def _lease(_purpose: str, *, ttl_seconds: float) -> FakeServerLease | None:
+ ttls.append(ttl_seconds)
+ if server is None:
+ return None
+ lease = FakeServerLease(server)
+ leases.append(lease)
+ return lease
+
+ _lease.leases = leases # type: ignore[attr-defined]
+ _lease.ttls = ttls # type: ignore[attr-defined]
+ return _lease
+
+
+def ui_lease(get_server):
+ """A ``vibe.api._opencode_lease`` stand-in over an async ``get_server`` factory.
+
+ A factory returning ``None`` means OpenCode is disabled; one that raises
+ propagates, as an unreachable controller does.
+ """
+
+ async def _lease(_purpose: str) -> FakeServerLease | None:
+ server = await get_server()
+ return None if server is None else FakeServerLease(server)
+
+ return _lease
+
+
+def lease_via(get_server):
+ """A ``lease_opencode_server`` stand-in that leases what ``get_server()`` returns.
+
+ Its ``leases`` list holds every lease it handed out.
+ """
+
+ leases: list[FakeServerLease] = []
+
+ async def _lease(_purpose: str, *, ttl_seconds: float, controller: Any = None) -> FakeServerLease:
+ del ttl_seconds, controller
+ lease = FakeServerLease(await get_server())
+ leases.append(lease)
+ return lease
+
+ _lease.leases = leases # type: ignore[attr-defined]
+ return _lease
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index fe76845e0..b550c40c3 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -98,6 +98,20 @@ capabilities:
- ui/src/components/onboarding/providers/providerStage.test.ts
- ui/src/components/onboarding/providers/ProvidersScreen.test.tsx
- ui/scripts/scenarioCatalog.test.mjs
+ - id: runtime_generations
+ name: Configuration changes reach backend runtimes through generations
+ status: active
+ catalog: tests/scenarios/runtime_generations/catalog.yaml
+ observations: tests/scenarios/runtime_generations/observations.yaml
+ scenario_tests:
+ - tests/test_runtime_generations.py
+ - tests/test_codex_runtime_generations.py
+ - tests/e2e/test_codex_runtime_generations_contract.py
+ unit_or_contract_tests:
+ - tests/test_claude_cli_path.py
+ - tests/test_backend_restart.py
+ - tests/test_controller_idle_cleanup.py
+ - tests/test_opencode_generations.py
- id: harness_failure_recovery
name: Harness per-Session failure recovery
status: active
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index ec825622b..5d149c7c5 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -22,6 +22,7 @@ import pytest
import yaml
from aiohttp import web
from cryptography.hazmat.primitives.asymmetric import rsa
+from tests.codex_generation_support import init_generation_state, install_codex_transport
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
@@ -41,6 +42,7 @@ from config.v2_config import (
UiConfig,
V2Config,
)
+from tests.opencode_generation_fakes import ui_lease, lease_returning
from core.agent_auth_service import AgentAuthService
from core.handlers.model_hub.adapter import SOURCE_PROTOCOLS
from core.handlers.model_hub.service import (
@@ -1550,20 +1552,24 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
await asyncio.Event().wait()
controller = _ReloadingV2ConfigController()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = controller
- agent._transports = {str(home): FakeCodexTransport()}
- agent._transport_last_activity = {}
agent._connection_probes = {}
agent._connection_probe_turns = {}
- agent._connection_probe_cwds = {}
- agent._get_or_create_transport = AsyncMock(
- return_value=agent._transports[str(home)]
- )
controller.agent_service = SimpleNamespace(agents={"codex": agent})
service = AgentAuthService(controller)
+ installed = {}
async def run_connection_probe(current):
+ # The persistent app-server was started exactly as a direct launch
+ # with the saved configuration would start it now.
+ agent.codex_config = SimpleNamespace(binary="codex-probe", extra_args=[], auth_mode="oauth")
+ installed["generation"] = install_codex_transport(
+ agent,
+ str(home),
+ FakeCodexTransport(),
+ digest=(await agent._launch_spec(str(home))).digest,
+ )
current.test_result = await probe_backend_auth_async(
"codex",
model="gpt-5.4-mini",
@@ -1586,10 +1592,9 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(harness.test_result["ok"])
self.assertEqual(harness.test_result["excerpt"], "codex-probe-ok")
- agent._get_or_create_transport.assert_awaited_once_with(
- str(home),
- allow_runtime_replacement=False,
- )
+ # The probe borrowed the running generation and started nothing.
+ self.assertIs(agent._current_generation(str(home)), installed["generation"])
+ self.assertEqual(installed["generation"].bindings, 0)
self.assertEqual(
requests,
[
@@ -1626,7 +1631,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch(self):
"""Scenario: AUTH-SETUP-903"""
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
config=SimpleNamespace(platform="avibe", reply_enhancements=True)
)
@@ -2590,9 +2595,11 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
fake_process = FakeProcess()
runtime = _FakeCodexNextTurnRuntime()
runner = ScenarioRunner(harness)
- harness.controller.agent_service.agents["codex"] = SimpleNamespace(
- refresh_auth_state=AsyncMock(side_effect=runtime.refresh)
- )
+ async def renew(_runtime_config, **_kwargs):
+ await runtime.refresh()
+
+ harness.controller.agent_service.agents["codex"] = SimpleNamespace(renew_runtime=AsyncMock(side_effect=renew))
+ harness.service._load_backend_runtime_config = Mock(return_value=SimpleNamespace(enabled=True))
harness.service._start_codex_process = AsyncMock(return_value=fake_process)
harness.service._read_codex_output = AsyncMock(return_value=None)
harness.service._verify_login = AsyncMock(return_value=(True, "Logged in using ChatGPT"))
@@ -2623,7 +2630,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
),
)
- harness.controller.agent_service.agents["codex"].refresh_auth_state.assert_awaited_once()
+ harness.controller.agent_service.agents["codex"].renew_runtime.assert_awaited_once()
ScenarioExpect.step_history(runner, ["start_setup", "emit_device_url", "next_turn_after_success"])
ScenarioExpect.text_contains(harness, "codex login is active again")
ScenarioExpect.flow_missing(harness, "C1:codex")
@@ -3040,12 +3047,19 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
runtime = _FakeNextTurnRuntime()
runner = ScenarioRunner(harness)
- harness.controller.agent_service.agents["opencode"] = SimpleNamespace(
- clear_sessions=AsyncMock(side_effect=runtime.clear_sessions)
+ async def renew(_runtime_config, **_kwargs):
+ await runtime.refresh()
+
+ # The new credential reaches the runtime by renewal: the next turn
+ # starts a generation that loaded it.
+ agent = SimpleNamespace(
+ clear_sessions=AsyncMock(side_effect=runtime.clear_sessions),
+ renew_runtime=AsyncMock(side_effect=renew),
)
+ harness.controller.agent_service.agents["opencode"] = agent
harness.service._resolve_opencode_provider = AsyncMock(return_value="opencode")
harness.service._install_opencode_api_key = AsyncMock()
- harness.service._refresh_opencode_server = AsyncMock(side_effect=runtime.refresh)
+ harness.service._load_backend_runtime_config = Mock(return_value=SimpleNamespace(enabled=True))
await runner.run(
ScenarioStep(
@@ -3066,7 +3080,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
)
harness.service._install_opencode_api_key.assert_awaited_once_with("opencode", "oc_live_Abcdef1234567890")
- harness.service._refresh_opencode_server.assert_awaited_once()
+ agent.renew_runtime.assert_awaited_once()
ScenarioExpect.step_history(runner, ["start_setup", "submit_direct_credential", "next_turn_after_success"])
ScenarioExpect.text_contains(harness, "opencode login is active again")
ScenarioExpect.flow_missing(harness, "C1:opencode")
@@ -4084,7 +4098,7 @@ def test_manual_provider_connection_reaches_controller_confirmed_readiness(monke
"""AUTH-SETUP-119: runtime manual-code transport -> native store -> apply -> read."""
from core.backend_restart import BackendRestartCoordinator
from core.internal_server import create_app
- from modules.agents.opencode.server import OpenCodeServerManager
+ from modules.agents.opencode.server import OpenCodeServerClient
from vibe import api, internal_client
from vibe.opencode_config import get_opencode_auth_path, upsert_opencode_provider_api_key
from tests.test_backend_restart import _AgentService, _controller
@@ -4108,8 +4122,8 @@ def test_manual_provider_connection_reaches_controller_confirmed_readiness(monke
service.agents = {"opencode": object()}
service.active = True
controller = _controller(service)
- refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ renew = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, AsyncMock(), renew=renew, poll_interval=0.001)
controller.backend_restart_coordinator = coordinator
internal_app = create_app(controller)
callbacks = []
@@ -4130,7 +4144,7 @@ def test_manual_provider_connection_reaches_controller_confirmed_readiness(monke
site = web.TCPSite(server, "127.0.0.1", 0)
await site.start()
port = site._server.sockets[0].getsockname()[1]
- transport = SimpleNamespace(base_url=f"http://127.0.0.1:{port}", ensure_running=AsyncMock())
+ transport = SimpleNamespace(base_url=f"http://127.0.0.1:{port}")
class Provider:
async def get_provider_auth(self):
@@ -4141,11 +4155,11 @@ def test_manual_provider_connection_reaches_controller_confirmed_readiness(monke
return {"method": "code", "url": "https://provider.invalid/authorize"}
async def wait_provider_oauth(self, provider_id, **kwargs):
- return await OpenCodeServerManager.wait_provider_oauth(transport, provider_id, **kwargs)
+ return await OpenCodeServerClient.wait_provider_oauth(transport, provider_id, **kwargs)
harness = AuthSetupScenarioHarness()
auth = harness.service
- monkeypatch.setattr(auth, "_opencode_server", AsyncMock(return_value=Provider()))
+ monkeypatch.setattr(auth, "_lease_opencode_server", lease_returning(Provider()))
monkeypatch.setattr(auth, "_OPENCODE_OAUTH_PROMPT_ANSWERS", {"test-provider": {"deployment": "fixture", "method": 999, "code": "must-not-override"}})
# No-hook consumers retain the existing coordinator application owner.
monkeypatch.setattr(auth, "_refresh_backend_runtime", coordinator.request_restart)
@@ -4174,13 +4188,11 @@ def test_manual_provider_connection_reaches_controller_confirmed_readiness(monke
assert h.web_flow.state == "success"
state = await api.get_backend_connection("opencode")
assert state["auth"] == "subscription"
- assert state["application"] == "draining" and not state["ready"]
+ # Work still running on OpenCode never holds the new credential back.
+ assert state["application"] == "applied" and state["ready"]
async def apply(h):
- service.active = False
- await coordinator.wait("opencode")
- assert (await api.get_backend_connection("opencode"))["ready"]
- refresh.assert_awaited_once_with("opencode", False)
+ renew.assert_awaited_once_with("opencode", False)
assert len(callbacks) == 1
assert await api._read_opencode_config_api_key("test-provider") is None
@@ -4299,7 +4311,7 @@ def test_explicit_opencode_model_recovery_preserves_agent_and_completes(monkeypa
]}),
close_http_session=AsyncMock(),
)
- monkeypatch.setattr(api, "_opencode_get_server", AsyncMock(return_value=server))
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(AsyncMock(return_value=server)))
monkeypatch.setattr(api, "resolve_cli_path", lambda _: str(tmp_path / "测试/bin/opencode"))
# Isolated application evidence, never the machine's running controller.
from vibe import internal_client
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 85e04843e..c233eedba 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -2458,6 +2458,9 @@ scenarios:
layer: contract
backend: codex
test: tests/test_codex_agent.py::CodexAgentStopTests::test_hfr_144_stuck_active_settles_only_exact_codex_owner
+ related_tests:
+ - tests/test_codex_runtime_generations.py::test_hfr_144_a_stuck_turn_settles_on_the_generation_that_runs_it
+ - tests/test_codex_runtime_generations.py::test_hfr_144_the_stuck_turn_backstop_never_forgets_a_turn_admitted_meanwhile
- id: HFR-145
name: every enabled backend invalidation path consumes exact ownership
status: covered
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index e08b604cb..ff44adaae 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -500,24 +500,6 @@ scenarios:
layer: unit
missing_layer: scenario
test: tests/test_model_hub_runtime.py::test_mh_runtime_001_service_restart_reports_installed_engine_as_not_started
- - id: MH-RUNTIME-002
- name: Matching OpenCode overlay never waits behind an unrelated active Turn
- status: covered
- kind: concurrency
- layer: unit
- test: tests/test_opencode_server.py::test_mh_runtime_002_matching_overlay_does_not_wait_for_an_unrelated_active_run
- - id: MH-RUNTIME-003
- name: A pending OpenCode overlay transition cannot be starved by new Turns on the old overlay
- status: covered
- kind: concurrency
- layer: unit
- test: tests/test_opencode_server.py::test_mh_runtime_003_pending_overlay_transition_blocks_new_turns_on_the_old_overlay
- - id: MH-RUNTIME-004
- name: An OpenCode overlay selection remains reserved until its initiating Turn becomes active
- status: covered
- kind: concurrency
- layer: unit
- test: tests/test_opencode_server.py::test_mh_runtime_004_overlay_reservation_promotes_atomically_to_active_run
- id: MH-RUNTIME-005
name: First CLIProxyAPI cold start remains pending until both health surfaces are ready
status: covered
@@ -530,12 +512,6 @@ scenarios:
kind: timeout_cancel
layer: unit
test: tests/test_model_hub_runtime.py::test_mh_runtime_006_timeout_stops_engine_with_bounded_structured_diagnostics
- - id: MH-RUNTIME-007
- name: An OpenCode overlay change retires drained durable owners without replacing an active native Turn
- status: covered
- kind: concurrency
- layer: unit
- test: tests/test_runtime_activation.py::test_mh_runtime_007_opencode_overlay_restart_retires_pre_native_start_owner
- id: MH-RUNTIME-008
name: Avibe startup converges CPA to its packaged pin without enabling or starting Model Hub
status: covered
@@ -1339,11 +1315,11 @@ scenarios:
related_tests:
- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
- id: MH-MIG-011
- name: Switching back to direct interrupts running gateway work instead of leaving it to fail on the Hub's refusal
+ name: A mode switch interrupts nothing, and a Hub turn admitted before a switch to Direct keeps resolving its routes
status: covered
kind: migration
layer: unit
- test: tests/test_model_hub_api.py::test_mode_switch_commits_only_inside_the_interrupting_guard
+ test: tests/test_model_hub_api.py::test_mode_switch_interrupts_nothing_and_keeps_admitted_hub_turns_served
- id: MH-MIG-012
name: Work interrupted by a runtime refresh is reported to the user as that interruption on every backend
status: covered
diff --git a/tests/scenarios/runtime_generations/catalog.yaml b/tests/scenarios/runtime_generations/catalog.yaml
new file mode 100644
index 000000000..2226707af
--- /dev/null
+++ b/tests/scenarios/runtime_generations/catalog.yaml
@@ -0,0 +1,254 @@
+version: 1
+capability:
+ id: runtime_generations
+ name: Configuration changes reach backend runtimes through generations
+ plan: docs/plans/runtime-generations.md
+ canonical_tests:
+ - tests/test_runtime_generations.py
+ - tests/test_claude_cli_path.py
+ - tests/test_backend_restart.py
+ - tests/test_controller_idle_cleanup.py
+ - tests/test_codex_runtime_generations.py
+ - tests/test_opencode_generations.py
+ - tests/test_internal_server.py
+ - tests/test_claude_agent_sessions.py
+ shared_harness: []
+status_legend:
+ covered: deterministic scenario or contract coverage exists
+ manual: validated in the local Incus black-box environment
+scenarios:
+ - id: RUNTIME-GEN-001
+ name: A Claude launch change never makes a session's turn wait; a busy client stays until idle unless the turn needs a different Model Hub launch
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: claude
+ test: tests/test_claude_cli_path.py::test_claude_launch_change_keeps_a_busy_client_until_its_session_is_idle
+ - id: RUNTIME-GEN-002
+ name: A changed launch spec replaces an idle generation in place and lets a busy one finish while new turns use a new one
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: shared
+ test: tests/test_runtime_generations.py::test_runtime_gen_002_a_busy_generation_finishes_while_new_turns_use_a_new_one
+ - id: RUNTIME-GEN-003
+ name: At the generation cap a new turn still starts at once and the oldest retiring generation gives way
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: shared
+ test: tests/test_runtime_generations.py::test_runtime_gen_003_at_the_cap_the_oldest_retiring_generation_gives_way
+ related_tests:
+ - tests/test_opencode_generations.py::test_a_cap_forced_stop_settles_the_activities_of_the_sessions_it_interrupts
+ - tests/test_opencode_generations.py::test_the_cap_stops_the_oldest_adopted_generation_whatever_its_record_order
+ - id: RUNTIME-GEN-004
+ name: A routine restart request renews in place and never drains, holds a turn, or interrupts
+ status: covered
+ kind: lifecycle
+ layer: contract
+ backend: shared
+ test: tests/test_backend_restart.py::test_runtime_gen_004_a_restart_request_never_drains_holds_or_interrupts
+ - id: RUNTIME-GEN-005
+ name: A saved idle timeout applies without a backend restart, and retiring generations are swept regardless of idle timeouts
+ status: covered
+ kind: lifecycle
+ layer: unit
+ backend: shared
+ test: tests/test_controller_idle_cleanup.py::test_a_saved_idle_timeout_applies_without_a_backend_restart
+ related_tests:
+ - tests/test_opencode_generations.py::test_a_failed_start_whose_process_survives_is_reaped_until_it_is_gone
+ - tests/test_claude_cli_path.py::test_a_config_save_that_only_changes_live_fields_renews_no_client
+ - tests/test_claude_cli_path.py::test_runtime_gen_005_a_client_from_before_a_renewal_is_reclaimed_once_idle
+ - id: RUNTIME-GEN-006
+ name: Disabling a backend is the user's own interruption; new messages see it disabled at once, running work settles with the interruption notice, and every process stops now
+ status: covered
+ kind: lifecycle
+ layer: contract
+ backend: shared
+ test: tests/test_backend_restart.py::test_runtime_gen_006_disabling_a_backend_stops_its_work_at_once
+ related_tests:
+ - tests/test_internal_server.py::test_runtime_gen_006_a_disabled_backend_tells_the_turn_it_was_turned_off
+ - tests/test_agent_service.py::test_runtime_gen_006_a_disabled_agents_retried_stop_spares_the_re_enabled_agents_turn
+ - tests/test_claude_agent_sessions.py::test_runtime_gen_006_a_turn_reaching_a_disabled_claude_starts_nothing
+ - tests/test_claude_cli_path.py::test_runtime_gen_006_a_disabled_claude_client_whose_disconnect_fails_still_exits
+ - tests/test_claude_cli_path.py::test_runtime_gen_006_a_client_connecting_when_claude_is_disabled_never_serves
+ - tests/test_claude_cli_path.py::test_runtime_gen_006_a_turn_cancelled_while_its_client_connects_stops_the_cli
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_006_disabling_codex_ends_every_app_server_and_admits_nothing
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_006_a_disable_whose_stop_fails_is_retried_until_the_app_server_is_gone
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_006_a_retried_disable_settles_only_the_disabled_agents_work
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_006_a_reenabled_agent_starts_beside_a_teardown_that_holds_its_activation
+ - tests/test_opencode_generations.py::test_runtime_gen_006_disabling_opencode_stops_every_generation_now_and_refuses_a_late_turn
+ - tests/test_opencode_generations.py::test_a_disable_shutdown_that_leaves_a_process_raises_and_its_retry_finishes
+ - tests/test_opencode_generations.py::test_runtime_gen_006_a_disable_retried_after_a_re_enable_settles_only_the_disabled_agents_work
+ - id: RUNTIME-GEN-007
+ name: Re-enabling a backend registers a fresh agent at once; disabling already stopped the old one
+ status: covered
+ kind: lifecycle
+ layer: contract
+ backend: shared
+ test: tests/test_backend_restart.py::test_runtime_gen_007_re_enabling_starts_a_fresh_agent_at_once
+ - id: RUNTIME-GEN-008
+ name: An unattended CLI update closes admission only for its install, then renews in place instead of tearing the runtime down
+ status: covered
+ kind: lifecycle
+ layer: contract
+ backend: shared
+ test: tests/test_backend_restart.py::test_runtime_gen_008_idle_maintenance_runs_behind_closed_admission_then_renews
+ related_tests:
+ - tests/test_opencode_generations.py::test_a_leased_generation_counts_as_active_runtime_work
+ - id: RUNTIME-GEN-010
+ name: A Codex turn on a new launch spec starts at once on a new app-server while a busy one in the same directory finishes on its own
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_010_a_busy_directory_never_holds_a_turn_on_a_new_spec
+ related_tests:
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_010_a_cancelled_admission_never_pins_its_generation
+ - id: RUNTIME-GEN-011
+ name: A Codex Session leaving an app-server releases its thread there before resuming it on the new one, and the old process keeps serving its other Sessions; only thread/closed, Codex reporting it unloaded, or the old process's exit proves the release, so a closed reader alone holds the input
+ status: covered
+ kind: lifecycle
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_011_a_session_releases_its_thread_before_resuming_elsewhere
+ related_tests:
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_011_a_closed_reader_is_no_proof_of_release
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_011_a_resume_whose_answer_was_lost_is_released_before_resuming_elsewhere
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_011_end_releases_the_thread_of_a_process_already_being_stopped
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_011_new_releases_a_session_that_started_while_it_cleared
+ - id: RUNTIME-GEN-012
+ name: A new message to a busy Codex Session interrupts its own turn and proceeds on the new launch spec, and a refused interrupt changes nothing and holds the input
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_012_a_busy_session_moves_after_its_own_turn_is_interrupted
+ - id: RUNTIME-GEN-013
+ name: At the cap a fourth Codex launch spec starts at once and only the oldest app-server's turns are interrupted
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_013_at_the_cap_the_oldest_busy_generation_gives_way
+ related_tests:
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_013_a_session_leaving_a_force_stopped_generation_waits_for_its_teardown
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_013_a_child_whose_reader_closed_is_settled_before_it_is_killed
+ - id: RUNTIME-GEN-014
+ name: A direct Codex launch with Model Hub enabled keeps the desktop-managed environment
+ status: covered
+ kind: regression
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_014_a_direct_launch_with_model_hub_keeps_the_managed_environment
+ - id: RUNTIME-GEN-015
+ name: Direct and native-CLI Codex launches with identical process inputs share one app-server, and an equal spec never reuses a process that can no longer serve
+ status: covered
+ kind: regression
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_015_direct_and_native_cli_launches_share_one_process
+ related_tests:
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_015_a_dead_retiring_generation_is_never_reused
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_015_a_generation_that_dies_while_its_spec_is_prepared_is_not_reused
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_015_a_renewal_during_hub_catalog_preparation_leaves_one_coherent_spec
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_015_a_renewal_during_hub_launch_resolution_leaves_one_coherent_spec
+ - tests/test_codex_config.py::test_credential_identity_tells_legacy_oauth_accounts_apart_but_not_their_refreshes
+ - id: RUNTIME-GEN-016
+ name: Retiring a Codex Hub app-server, by renewal or a switch to Direct, keeps the directory's gateway credential until the last Hub app-server stops, and a switch to Direct never holds a new turn behind a running Hub turn
+ status: covered
+ kind: lifecycle
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_016_hub_scope_is_revoked_only_with_the_last_hub_generation
+ related_tests:
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_016_a_starting_hub_process_keeps_the_scope
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_016_a_failed_hub_start_is_cleaned_up
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_016_a_retried_disable_never_revokes_a_reenabled_agents_hub_credential
+ - tests/test_codex_runtime_generations.py::test_runtime_gen_016_a_process_whose_post_start_setup_fails_is_stopped_by_the_sweep
+ - id: RUNTIME-GEN-017
+ name: A Codex Session that moved app-servers never receives late thread-level events from the one it left
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_017_late_thread_events_from_a_previous_generation_are_dropped
+ - id: RUNTIME-GEN-018
+ name: A Codex fork reads its boundary from the app-server running the source turn
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: codex
+ test: tests/test_codex_runtime_generations.py::test_runtime_gen_018_fork_boundary_reads_the_source_sessions_generation
+ - id: RUNTIME-GEN-019
+ name: The real Codex CLI moves a thread between two app-servers in one directory only after release, without touching its rollout
+ status: covered
+ kind: contract
+ layer: e2e
+ backend: codex
+ test: tests/e2e/test_codex_runtime_generations_contract.py::test_runtime_gen_019_a_thread_moves_between_app_servers_only_after_release
+ - id: RUNTIME-GEN-020
+ name: An OpenCode launch change starts a new generation while a busy one finishes its native run, and the old one stops only once that run is cleared
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: opencode
+ test: tests/test_opencode_generations.py::test_runtime_gen_020_a_busy_generation_finishes_its_run_while_new_turns_move_on
+ related_tests:
+ - tests/test_opencode_generations.py::test_an_in_place_binary_upgrade_changes_the_launch_spec
+ - tests/test_opencode_generations.py::test_credential_digest_ignores_token_refresh_but_sees_new_credentials
+ - tests/test_opencode_generations.py::test_a_renewal_during_overlay_preparation_leaves_the_launch_one_coherent_spec
+ - tests/test_opencode_generations.py::test_a_turn_keeps_the_opencode_settings_it_was_admitted_with
+ - id: RUNTIME-GEN-021
+ name: An OpenCode turn is aborted and steered on the generation that runs it while a newer generation is current
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: opencode
+ test: tests/test_opencode_generations.py::test_runtime_gen_021_a_live_turn_is_aborted_on_its_own_generation
+ related_tests:
+ - tests/test_opencode_generations.py::test_runtime_gen_021_a_steer_reaches_the_generation_running_the_turn
+ - id: RUNTIME-GEN-022
+ name: After a controller restart an OpenCode poll resumes on the adopted generation that runs it, including a poll from before generations
+ status: covered
+ kind: recovery
+ layer: unit
+ backend: opencode
+ test: tests/test_opencode_generations.py::test_runtime_gen_022_a_restored_poll_resumes_on_the_generation_that_runs_it
+ related_tests:
+ - tests/test_opencode_generations.py::test_adoption_keeps_every_proven_serving_process_and_drops_the_rest
+ - tests/test_opencode_restore_polls.py::test_a_cancelled_restore_releases_the_binding_its_poll_task_never_took
+ - tests/test_opencode_restore_polls.py::test_two_overlapping_restores_of_one_durable_poll_start_exactly_one_loop
+ - tests/test_opencode_restore_polls.py::test_a_restore_whose_generation_rewrite_fails_runs_nothing_and_the_sweep_restores_it
+ - tests/test_opencode_restore_polls.py::test_a_poll_task_whose_rebind_cannot_be_recorded_leaves_its_turn_live_for_the_sweep
+ - tests/test_opencode_restore_polls.py::test_a_restore_whose_publication_fails_leaves_no_poll_task_waiting_on_it
+ - id: RUNTIME-GEN-023
+ name: The UI process never launches OpenCode; it leases the controller's generation over control IPC
+ status: covered
+ kind: lifecycle
+ layer: contract
+ backend: opencode
+ test: tests/test_opencode_generations.py::test_runtime_gen_023_the_ui_process_leases_the_controllers_generation_over_control_ipc
+ related_tests:
+ - tests/test_save_opencode_provider_auth.py::test_save_provider_model_fails_closed_when_an_enabled_opencode_cannot_be_leased
+ - tests/test_opencode_generations.py::test_a_ui_request_running_past_its_lease_window_keeps_its_generation_until_release
+ - id: RUNTIME-GEN-024
+ name: A Hub-to-Direct mode switch while a Hub run is live moves new OpenCode turns to a Direct generation and lets the Hub one finish its run
+ status: covered
+ kind: concurrency
+ layer: unit
+ backend: opencode
+ test: tests/test_opencode_generations.py::test_runtime_gen_024_a_mode_switch_during_a_hub_run_moves_new_turns_to_direct
+ - id: RUNTIME-GEN-025
+ name: A controller that starts with OpenCode disabled stops the OpenCode servers a crashed controller recorded and leaves them for adoption when OpenCode is enabled; shutdown stops only what this controller owns, nothing adopts, stops, forgets, or cleans another desktop Runtime's records, and restore never binds, rewrites, or settles a poll whose run another desktop Runtime's live server executes
+ status: covered
+ kind: recovery
+ layer: unit
+ backend: opencode
+ test: tests/test_opencode_generations.py::test_a_controller_starting_with_opencode_disabled_stops_a_crashed_controllers_servers
+ related_tests:
+ - tests/test_opencode_generations.py::test_shutdown_stops_only_the_generations_this_controller_owns
+ - tests/test_opencode_generations.py::test_service_shutdown_stops_a_started_process_whose_record_was_never_written
+ - tests/test_opencode_generations.py::test_adoption_leaves_every_record_of_another_desktop_runtime_alone
+ - tests/test_opencode_restore_polls.py::test_restore_leaves_every_poll_whose_run_another_desktop_runtimes_live_server_executes
+ - tests/test_opencode_generations.py::test_a_malformed_record_never_disables_opencode
diff --git a/tests/scenarios/runtime_generations/observations.yaml b/tests/scenarios/runtime_generations/observations.yaml
new file mode 100644
index 000000000..f773ff360
--- /dev/null
+++ b/tests/scenarios/runtime_generations/observations.yaml
@@ -0,0 +1,59 @@
+version: 1
+capability: runtime_generations
+observations:
+ - id: RUNTIME-GEN-OBS-001
+ date: 2026-10-01
+ source: local log trace
+ result: confirmed
+ detail: >-
+ An unattended Model Hub built-in snapshot refresh requested a Claude
+ restart; the coordinator drained for 300 s and then force-interrupted a
+ running turn. A Claude CLI install job interrupted three turns the same
+ way the day before.
+ - id: RUNTIME-GEN-OBS-002
+ date: 2026-10-01
+ source: hermetic probe (Claude CLI 2.1.286, Agent SDK 0.2.158)
+ result: confirmed
+ detail: >-
+ A live Claude process whose gateway discovery listed only one model
+ accepted set_model for an id added later, validating it with one gateway
+ request, and ran the next turn on it.
+ - id: RUNTIME-GEN-OBS-003
+ date: 2026-10-01
+ source: hermetic probe (OpenCode 1.18.33)
+ result: confirmed
+ detail: >-
+ Two opencode serve processes shared one SQLite (WAL) home: sessions
+ continued across servers without stale reads and concurrent prompts on
+ different sessions completed in parallel. Simultaneous first starts on a
+ fresh home failed with "database is locked", so starts are serialized.
+ - id: RUNTIME-GEN-OBS-004
+ date: 2026-10-01
+ source: hermetic probe (codex-cli 0.159.3)
+ result: confirmed
+ detail: >-
+ Two app-servers ran in one directory with concurrent turns. A thread
+ loaded in one holds a cross-process writer lock, so another can resume it
+ only after thread/unsubscribe and thread/closed, which take about 50 ms
+ with thread_unload_delay_secs=0, or after the first exits. Neither
+ unloading nor exit appends to the thread's rollout.
+ - id: RUNTIME-GEN-OBS-020
+ date: 2026-10-01
+ source: hermetic probe (OpenCode 1.16.0, 1.17.0, 1.18.33)
+ result: confirmed
+ detail: >-
+ An older and a newer opencode serve shared one home across a version
+ change. The newer one applied its database migrations while the older
+ one streamed a prompt; the older one finished that prompt and served
+ another turn afterwards, and the session continued on the newer one.
+ 1.17.0 to 1.18.33, 1.16.0 to 1.18.33, and a downgrade from 1.18.33 to
+ 1.17.0 all behaved this way, so a version change can coexist.
+ - id: RUNTIME-GEN-OBS-021
+ date: 2026-10-01
+ source: hermetic probe (OpenCode 1.18.33)
+ result: confirmed
+ detail: >-
+ opencode serve --port=0 listens on the default 4096, not an ephemeral
+ port. A second server on a taken port exits at once with ServeError
+ while the first keeps serving. Session status is per process: a server
+ reports no status for a session another server is running.
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index a22b64cf4..d309cdef7 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -4,10 +4,11 @@ import sys
import tempfile
import threading
import unittest
-from contextlib import contextmanager
+from contextlib import asynccontextmanager, contextmanager
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import ANY, AsyncMock, Mock, patch
+from tests.codex_generation_support import init_generation_state
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
@@ -23,6 +24,16 @@ from modules.claude_sdk_compat import CLAUDE_SDK_MAX_BUFFER_SIZE
from modules.im import MessageContext
+def _opencode_agent_serving(server):
+ """An OpenCode agent whose current generation is ``server``."""
+
+ @asynccontextmanager
+ async def current_server():
+ yield server
+
+ return SimpleNamespace(current_server=current_server)
+
+
class _IsolatedClaudeConfigDirMixin:
def setUp(self):
super().setUp()
@@ -132,6 +143,102 @@ class _StubController:
class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyncioTestCase):
+ async def test_claude_renews_in_place_and_disabling_it_stops_its_work(self):
+ """RUNTIME-GEN-004 and -006: Claude stays registered and renews in place.
+
+ Disabling it is the user's own interruption: its running work settles
+ with the disabled notice, and every client live at that moment closes,
+ busy ones included. Saving again while it is disabled interrupts nothing.
+ """
+ for was_enabled, enabled in ((True, True), (True, False), (False, False)):
+ controller = _StubController()
+ controller.config.claude = SimpleNamespace(enabled=was_enabled)
+ agent = SimpleNamespace(renew_runtime=AsyncMock(), refresh_auth_state=AsyncMock())
+ controller.agent_service = SimpleNamespace(agents={"claude": agent})
+ controller.backend_restart_coordinator = SimpleNamespace(interrupt_backend=AsyncMock())
+ captured = (("ses:/work", object()),)
+ controller.session_handler = SimpleNamespace(
+ capture_claude_clients=Mock(return_value=captured),
+ close_captured_claude_clients=AsyncMock(),
+ )
+ service = AgentAuthService(controller)
+ runtime_config = SimpleNamespace(enabled=enabled)
+ service._load_backend_runtime_config = lambda _backend, config=runtime_config: config
+ service._sync_builtin_default_agents = lambda: None
+
+ await service.renew_backend_runtime("claude")
+
+ agent.renew_runtime.assert_awaited_once_with(runtime_config, config_save=False)
+ assert controller.agent_service.agents["claude"] is agent
+ stopped = was_enabled and not enabled
+ assert controller.backend_restart_coordinator.interrupt_backend.await_count == int(stopped)
+ assert controller.session_handler.close_captured_claude_clients.await_args_list == (
+ [((captured,), {"reason": "backend_disabled"})] if stopped else []
+ )
+ agent.refresh_auth_state.assert_not_awaited()
+
+ async def test_a_failed_claude_disable_retry_closes_only_the_clients_it_captured(self):
+ """A failed Claude disable is retried, and once Claude is enabled again the
+ retry no longer interrupts new work; it closes only the clients that were
+ live at the disable, never the re-enabled backend's."""
+ from modules.agents.service import AgentService
+
+ controller = _StubController()
+ controller.config.claude = SimpleNamespace(enabled=True)
+ agent = SimpleNamespace(name="claude", renew_runtime=AsyncMock(), refresh_auth_state=AsyncMock())
+ controller.agent_service = AgentService(controller)
+ controller.agent_service.register(agent)
+ controller.backend_restart_coordinator = SimpleNamespace(
+ interrupt_backend=AsyncMock(side_effect=[RuntimeError("db busy"), None])
+ )
+ captured = (("ses:/work", object()),)
+ controller.session_handler = SimpleNamespace(
+ capture_claude_clients=Mock(return_value=captured),
+ close_captured_claude_clients=AsyncMock(),
+ )
+ service = AgentAuthService(controller)
+ service._sync_builtin_default_agents = lambda: None
+ service._load_backend_runtime_config = lambda _backend: SimpleNamespace(enabled=False)
+
+ await service.renew_backend_runtime("claude")
+ controller.config.claude = SimpleNamespace(enabled=False)
+ service._load_backend_runtime_config = lambda _backend: SimpleNamespace(enabled=True)
+ await service.renew_backend_runtime("claude")
+ await controller.agent_service.retry_pending()
+
+ assert controller.backend_restart_coordinator.interrupt_backend.await_count == 1
+ assert [call.args[0] for call in controller.session_handler.close_captured_claude_clients.await_args_list] == [
+ captured,
+ captured,
+ ]
+ controller.session_handler.capture_claude_clients.assert_called_once_with()
+ assert controller.agent_service._pending_operations == {}
+
+ async def test_enabling_opencode_in_a_running_controller_restores_its_durable_polls(self):
+ """Work a crashed controller left while OpenCode was off is delivered
+ once OpenCode is enabled, without waiting for a restart. Every
+ transport-ready event already ran, so a restore that fails is retried
+ by the idle sweep until it succeeds."""
+ from modules.agents.service import AgentService
+
+ controller = _StubController()
+ controller.config.opencode = None
+ controller.agent_service = AgentService(controller)
+ controller.restore_polls_on_ready_transports = AsyncMock(side_effect=[RuntimeError("database is locked"), None])
+ service = AgentAuthService(controller)
+ service._sync_builtin_default_agents = lambda: None
+ service._load_backend_runtime_config = lambda _backend: SimpleNamespace(enabled=True)
+
+ with patch("modules.agents.opencode.OpenCodeAgent", lambda _controller, config: SimpleNamespace(name="opencode", config=config)):
+ await service.renew_backend_runtime("opencode")
+
+ assert "opencode" in controller.agent_service.agents
+ assert controller.restore_polls_on_ready_transports.await_count == 1
+ await controller.agent_service.retry_pending()
+ assert controller.restore_polls_on_ready_transports.await_count == 2
+ await controller.agent_service.retry_pending()
+ assert controller.restore_polls_on_ready_transports.await_count == 2
+
async def test_handle_setup_command_submits_code(self):
controller = _StubController()
service = AgentAuthService(controller)
@@ -832,7 +939,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
get_agent_model_from_config=lambda agent_name: None,
)
controller.agent_service = SimpleNamespace(
- agents={"opencode": SimpleNamespace(_get_server=AsyncMock(return_value=mock_server))}
+ agents={"opencode": _opencode_agent_serving(mock_server)}
)
service = AgentAuthService(controller)
context = MessageContext(user_id="U1", channel_id="C1")
@@ -857,7 +964,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
get_agent_model_from_config=lambda agent_name: None,
)
controller.agent_service = SimpleNamespace(
- agents={"opencode": SimpleNamespace(_get_server=AsyncMock(return_value=mock_server))}
+ agents={"opencode": _opencode_agent_serving(mock_server)}
)
service = AgentAuthService(controller)
context = MessageContext(
@@ -996,7 +1103,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
server = SimpleNamespace(set_api_key_auth=AsyncMock(side_effect=set_api_key_auth))
controller.agent_service = SimpleNamespace(
- agents={"opencode": SimpleNamespace(_get_server=AsyncMock(return_value=server))}
+ agents={"opencode": _opencode_agent_serving(server)}
)
cleanup_calls = []
@@ -1577,22 +1684,19 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
finally:
await finisher
- async def test_refresh_backend_runtime_uses_backend_specific_runtime_refresh(self):
+ async def test_cutover_refresh_uses_backend_specific_runtime_refresh(self):
controller = _StubController()
controller.agent_service.agents["codex"] = SimpleNamespace(refresh_auth_state=AsyncMock())
controller.agent_service.agents["claude"] = SimpleNamespace(refresh_auth_state=AsyncMock())
service = AgentAuthService(controller)
- service._refresh_opencode_server = AsyncMock()
- await service._refresh_backend_runtime("codex")
- await service._refresh_backend_runtime("claude")
- await service._refresh_backend_runtime("opencode")
+ await service._apply_backend_runtime_refresh("codex")
+ await service._apply_backend_runtime_refresh("claude")
controller.agent_service.agents["codex"].refresh_auth_state.assert_awaited_once()
controller.agent_service.agents["claude"].refresh_auth_state.assert_awaited_once()
- service._refresh_opencode_server.assert_awaited_once()
- async def test_refresh_backend_runtime_prefers_runtime_config_reload(self):
+ async def test_cutover_refresh_prefers_runtime_config_reload(self):
controller = _StubController()
agent = SimpleNamespace(
refresh_runtime_config=AsyncMock(),
@@ -1603,13 +1707,13 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
runtime_config = object()
service._load_backend_runtime_config = Mock(return_value=runtime_config)
- await service._refresh_backend_runtime("codex")
+ await service._apply_backend_runtime_refresh("codex")
service._load_backend_runtime_config.assert_called_once_with("codex")
agent.refresh_runtime_config.assert_awaited_once_with(runtime_config)
agent.refresh_auth_state.assert_not_awaited()
- async def test_refresh_backend_runtime_releases_runtime_tokens_after_refresh(self):
+ async def test_cutover_refresh_releases_runtime_tokens_after_refresh(self):
controller = _StubController()
runtime_tokens = {"session:/repo": "token-1"}
controller.agent_service.runtime_turn_tokens_for_backend = Mock(return_value=runtime_tokens)
@@ -1620,7 +1724,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
runtime_config = object()
service._load_backend_runtime_config = Mock(return_value=runtime_config)
- await service._refresh_backend_runtime("codex")
+ await service._apply_backend_runtime_refresh("codex")
controller.agent_service.runtime_turn_tokens_for_backend.assert_called_once_with("codex")
controller.agent_service.refresh_runtime_config.assert_awaited_once_with("codex", runtime_config)
@@ -1692,7 +1796,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
self.assertIs(registered.codex_config, runtime_config)
self.assertIs(controller.config.codex, runtime_config)
- async def test_refresh_backend_runtime_unregisters_disabled_codex(self):
+ async def test_refresh_backend_runtime_stops_disabled_codex_at_once(self):
from modules.agent_router import AgentRouter
from modules.agents.service import AgentService
@@ -1716,7 +1820,8 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
self.assertEqual(controller.agent_router.global_default, "codex")
self.assertEqual(controller.agent_router.platform_routes["slack"].default, "codex")
self.assertEqual(controller.config.default_backend, "codex")
- agent.shutdown_runtime.assert_awaited_once()
+ # Disabling stops the agent's processes at once, settling their work as disabled.
+ agent.shutdown_runtime.assert_awaited_once_with(settle_reason="backend_disabled")
service._sync_builtin_default_agents.assert_called_once_with()
async def test_refresh_backend_runtime_does_not_restore_legacy_default_after_late_registration(self):
@@ -1758,475 +1863,22 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
controller.vibe_agent_store.ensure_builtin_default_agents.assert_called_once_with(["codex"])
- async def test_refresh_opencode_runtime_reloads_v2_cli_path(self):
- from config.v2_config import AgentsConfig, OpenCodeConfig, RuntimeConfig, SlackConfig, V2Config
- from config.v2_compat import OpenCodeCompatConfig
-
- controller = _StubController()
- previous_server = SimpleNamespace(
- reload_runtime_config=AsyncMock(),
- detach_after_deferred_refresh=AsyncMock(),
- refresh_global_config=AsyncMock(return_value=False),
- )
-
- class _FakeOpenCodeAgent:
- def __init__(self) -> None:
- self.refreshed = None
-
- async def _get_server(self):
- return previous_server
-
- async def refresh_runtime_config(self, opencode_config):
- self.refreshed = opencode_config
- controller.config.opencode = opencode_config
- await previous_server.detach_after_deferred_refresh()
- await previous_server.reload_runtime_config(
- binary=opencode_config.binary,
- port=opencode_config.port,
- request_timeout_seconds=opencode_config.request_timeout_seconds,
- )
-
- agent = _FakeOpenCodeAgent()
- controller.agent_service.agents["opencode"] = agent
- service = AgentAuthService(controller)
-
- with tempfile.TemporaryDirectory() as home:
- with _temporary_vibe_home(Path(home)):
- V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- runtime=RuntimeConfig(default_cwd="/tmp/work"),
- agents=AgentsConfig(
- opencode=OpenCodeConfig(
- enabled=True,
- cli_path="/opt/opencode/bin/opencode",
- )
- ),
- ).save()
-
- await service._refresh_backend_runtime("opencode")
-
- self.assertIsInstance(agent.refreshed, OpenCodeCompatConfig)
- self.assertEqual(agent.refreshed.binary, "/opt/opencode/bin/opencode")
- previous_server.reload_runtime_config.assert_awaited_once_with(
- binary="/opt/opencode/bin/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- previous_server.detach_after_deferred_refresh.assert_awaited_once()
- async def test_opencode_agent_refresh_runtime_config_updates_cached_server(self):
- from config.v2_compat import OpenCodeCompatConfig
- from modules.agents.opencode.agent import OpenCodeAgent
- old_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- new_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- calls: list[str] = []
- async def _detach() -> None:
- calls.append("detach")
- async def _reload_runtime_config(**kwargs) -> None:
- calls.append("reload")
- previous_server = SimpleNamespace(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- reload_runtime_config=AsyncMock(side_effect=_reload_runtime_config),
- detach_after_deferred_refresh=AsyncMock(side_effect=_detach),
- refresh_global_config=AsyncMock(return_value=False),
- )
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.opencode_config = old_config
- agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(reset_config=AsyncMock(return_value=previous_server))
- await agent.refresh_runtime_config(new_config)
- self.assertIs(agent.opencode_config, new_config)
- self.assertIs(agent.controller.config.opencode, new_config)
- agent._client_manager.reset_config.assert_awaited_once_with(new_config)
- previous_server.detach_after_deferred_refresh.assert_awaited_once()
- previous_server.reload_runtime_config.assert_awaited_once_with(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- self.assertEqual(calls, ["detach", "reload"])
- async def test_opencode_agent_refresh_runtime_config_uses_global_config_refresh(self):
- from config.v2_compat import OpenCodeCompatConfig
- from modules.agents.opencode.agent import OpenCodeAgent
- old_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- new_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- previous_server = SimpleNamespace(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- refresh_global_config=AsyncMock(return_value=True),
- detach_after_deferred_refresh=AsyncMock(),
- reload_runtime_config=AsyncMock(),
- )
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.opencode_config = old_config
- agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(reset_config=AsyncMock(return_value=previous_server))
-
- await agent.refresh_runtime_config(new_config)
-
- previous_server.refresh_global_config.assert_awaited_once()
- previous_server.detach_after_deferred_refresh.assert_not_awaited()
- previous_server.reload_runtime_config.assert_awaited_once_with(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
-
- async def test_opencode_agent_force_refresh_restarts_after_global_config_change(self):
- from config.v2_compat import OpenCodeCompatConfig
- from modules.agents.opencode.agent import OpenCodeAgent
-
- old_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- new_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- calls = []
- previous_server = SimpleNamespace(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- refresh_global_config=AsyncMock(return_value=True),
- detach_after_deferred_refresh=AsyncMock(side_effect=lambda **_kw: calls.append(("detach", restored_poll.done()))),
- reload_runtime_config=AsyncMock(),
- )
- # A poll restored after a restart has no turn owner to cancel it; left
- # running, it would poll the stopped server and surface a transport
- # error for an interruption the user chose.
- restored_poll = asyncio.create_task(asyncio.Event().wait())
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.opencode_config = old_config
- agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(
- reset_config=AsyncMock(return_value=previous_server),
- )
- agent._active_requests = {"base-restored": restored_poll}
- agent._steering_states = {}
- agent._settling_request_tasks = set()
-
- await agent.refresh_runtime_config(new_config, force=True)
-
- self.assertTrue(restored_poll.cancelled())
- self.assertEqual(calls, [("detach", True)])
- previous_server.refresh_global_config.assert_not_awaited()
- previous_server.detach_after_deferred_refresh.assert_awaited_once_with(force=True)
- previous_server.reload_runtime_config.assert_awaited_once_with(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
-
- async def test_opencode_agent_refresh_runtime_config_attaches_uncached_server(self):
- from config.v2_compat import OpenCodeCompatConfig
- from modules.agents.opencode.agent import OpenCodeAgent
- from modules.agents.opencode.server import OpenCodeServerManager
-
- old_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/old/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- new_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/new/opencode",
- port=4100,
- request_timeout_seconds=15,
- )
- live_server = SimpleNamespace(
- binary="/old/opencode",
- port=4096,
- request_timeout_seconds=60,
- refresh_global_config=AsyncMock(return_value=True),
- detach_after_deferred_refresh=AsyncMock(),
- reload_runtime_config=AsyncMock(),
- )
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.opencode_config = old_config
- agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(
- reset_config=AsyncMock(return_value=None),
- )
-
- with patch.object(
- OpenCodeServerManager,
- "get_instance_if_managed_server_exists",
- AsyncMock(return_value=live_server),
- ) as get_instance:
- await agent.refresh_runtime_config(new_config)
-
- agent._client_manager.reset_config.assert_awaited_once_with(new_config)
- get_instance.assert_awaited_once_with(
- binary="/old/opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=agent.controller._agent_resource_governor,
- )
- live_server.refresh_global_config.assert_not_awaited()
- live_server.detach_after_deferred_refresh.assert_awaited_once()
- live_server.reload_runtime_config.assert_awaited_once_with(
- binary="/new/opencode",
- port=4100,
- request_timeout_seconds=15,
- )
-
- async def test_opencode_agent_refresh_runtime_config_skips_uncached_refresh_without_managed_server(self):
- from config.v2_compat import OpenCodeCompatConfig
- from modules.agents.opencode.agent import OpenCodeAgent
- from modules.agents.opencode.server import OpenCodeServerManager
-
- old_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- new_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.opencode_config = old_config
- agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(
- reset_config=AsyncMock(return_value=None),
- )
-
- with patch.object(
- OpenCodeServerManager,
- "get_instance_if_managed_server_exists",
- AsyncMock(return_value=None),
- ) as get_instance:
- await agent.refresh_runtime_config(new_config)
-
- agent._client_manager.reset_config.assert_awaited_once_with(new_config)
- get_instance.assert_awaited_once_with(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=agent.controller._agent_resource_governor,
- )
- self.assertIs(agent.opencode_config, new_config)
- self.assertIs(agent.controller.config.opencode, new_config)
-
- async def test_web_opencode_server_uses_v2_runtime_resource_governance(self):
- from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
- from modules.agents.opencode.server import OpenCodeServerManager
-
- controller = _StubController()
- service = AgentAuthService(controller)
- v2_config = V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- agents=AgentsConfig(),
- runtime=RuntimeConfig(
- default_cwd=".",
- resource_governance={
- "mode": "enabled",
- "agent_group_name": "web-oauth-agents",
- },
- ),
- )
- server = SimpleNamespace(ensure_running=AsyncMock())
-
- with (
- patch("config.v2_config.V2Config.load", return_value=v2_config),
- patch.object(
- OpenCodeServerManager,
- "get_instance",
- AsyncMock(return_value=server),
- ) as get_instance,
- ):
- result = await service._opencode_server()
-
- self.assertIs(result, server)
- server.ensure_running.assert_awaited_once()
- self.assertNotIn(
- "model_hub_overlay_required",
- get_instance.await_args.kwargs,
- )
- governor = get_instance.await_args.kwargs["resource_governor"]
- self.assertEqual(governor.mode, "enabled")
- self.assertEqual(governor.config["agent_group_name"], "web-oauth-agents")
-
- async def test_web_opencode_server_requires_controller_overlay_in_hub_mode(self):
- from config.v2_config import (
- AgentsConfig,
- RuntimeConfig,
- SlackConfig,
- V2Config,
- )
- from modules.agents.opencode.server import (
- OpenCodeModelHubOverlayRequiredError,
- OpenCodeServerManager,
- )
-
- controller = _StubController()
- service = AgentAuthService(controller)
- v2_config = V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- agents=AgentsConfig(),
- runtime=RuntimeConfig(default_cwd="."),
- )
- v2_config.model_hub.agents["opencode"].mode = "hub"
- server = SimpleNamespace(
- ensure_running=AsyncMock(
- side_effect=OpenCodeModelHubOverlayRequiredError(
- "controller overlay is not ready"
- )
- )
- )
-
- with (
- patch("config.v2_config.V2Config.load", return_value=v2_config),
- patch.object(
- OpenCodeServerManager,
- "get_instance",
- AsyncMock(return_value=server),
- ),
- ):
- result = await service._opencode_server()
-
- self.assertIsNone(result)
- server.ensure_running.assert_awaited_once()
-
- async def test_opencode_agent_refresh_runtime_config_restarts_uncached_adopted_server_on_refresh_miss(self):
- from config.v2_compat import OpenCodeCompatConfig
- from modules.agents.opencode.agent import OpenCodeAgent
- from modules.agents.opencode.server import OpenCodeServerManager
-
- old_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- new_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- live_server = SimpleNamespace(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- refresh_global_config=AsyncMock(return_value=False),
- detach_after_deferred_refresh=AsyncMock(),
- reload_runtime_config=AsyncMock(),
- )
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.opencode_config = old_config
- agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(
- reset_config=AsyncMock(return_value=None),
- )
-
- with patch.object(
- OpenCodeServerManager,
- "get_instance_if_managed_server_exists",
- AsyncMock(return_value=live_server),
- ):
- await agent.refresh_runtime_config(new_config)
-
- live_server.refresh_global_config.assert_awaited_once()
- live_server.detach_after_deferred_refresh.assert_awaited_once()
- live_server.reload_runtime_config.assert_awaited_once_with(
- binary="/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
-
- async def test_opencode_agent_refresh_runtime_config_restarts_when_runtime_changes(self):
- from config.v2_compat import OpenCodeCompatConfig
- from modules.agents.opencode.agent import OpenCodeAgent
-
- old_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/old/opencode",
- port=4096,
- request_timeout_seconds=60,
- )
- new_config = OpenCodeCompatConfig(
- enabled=True,
- binary="/new/opencode",
- port=4100,
- request_timeout_seconds=15,
- )
- previous_server = SimpleNamespace(
- binary="/old/opencode",
- port=4096,
- request_timeout_seconds=60,
- refresh_global_config=AsyncMock(return_value=True),
- detach_after_deferred_refresh=AsyncMock(),
- reload_runtime_config=AsyncMock(),
- )
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.opencode_config = old_config
- agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(reset_config=AsyncMock(return_value=previous_server))
-
- await agent.refresh_runtime_config(new_config)
-
- previous_server.refresh_global_config.assert_not_awaited()
- previous_server.detach_after_deferred_refresh.assert_awaited_once()
- previous_server.reload_runtime_config.assert_awaited_once_with(
- binary="/new/opencode",
- port=4100,
- request_timeout_seconds=15,
- )
async def test_refresh_claude_runtime_reloads_v2_cli_path(self):
from config.v2_config import AgentsConfig, ClaudeConfig, RuntimeConfig, SlackConfig, V2Config
from config.v2_compat import ClaudeCompatConfig
controller = _StubController()
- agent = SimpleNamespace(refresh_runtime_config=AsyncMock())
+ agent = SimpleNamespace(renew_runtime=AsyncMock())
controller.agent_service.agents["claude"] = agent
service = AgentAuthService(controller)
@@ -2247,7 +1899,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
await service._refresh_backend_runtime("claude")
- runtime_config = agent.refresh_runtime_config.await_args.args[0]
+ runtime_config = agent.renew_runtime.await_args.args[0]
self.assertIsInstance(runtime_config, ClaudeCompatConfig)
self.assertEqual(runtime_config.cli_path, "/opt/claude/bin/claude")
@@ -2257,11 +1909,10 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
old_config = CodexCompatConfig(enabled=True, binary="/old/codex", extra_args=[])
new_config = CodexCompatConfig(enabled=True, binary="/new/codex", extra_args=[])
- agent = CodexAgent.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.codex_config = old_config
- agent._model_hub_catalog = SimpleNamespace(path=Path("/runtime/codex-old.json"), close=Mock())
- agent._model_hub_catalog_lock = asyncio.Lock()
- agent._model_hub_catalog_generation = 0
+ old_catalog = SimpleNamespace(path=Path("/runtime/codex-old.json"), close=Mock())
+ agent._model_hub_catalogs[("old", "models")] = old_catalog
agent.controller = SimpleNamespace(config=SimpleNamespace(codex=old_config))
agent.refresh_auth_state = AsyncMock()
@@ -2274,8 +1925,8 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
prepare_catalog.assert_not_called()
self.assertIs(agent.codex_config, new_config)
self.assertIs(agent.controller.config.codex, new_config)
- self.assertIsNone(agent._model_hub_catalog)
- self.assertEqual(agent._model_hub_catalog_generation, 1)
+ self.assertEqual(dict(agent._model_hub_catalogs), {})
+ old_catalog.close.assert_called_once_with()
agent.refresh_auth_state.assert_awaited_once()
async def test_claude_runtime_config_reload_updates_cli_path_before_refresh(self):
diff --git a/tests/test_agent_backend_alive.py b/tests/test_agent_backend_alive.py
index 704db047e..280ff3973 100644
--- a/tests/test_agent_backend_alive.py
+++ b/tests/test_agent_backend_alive.py
@@ -12,6 +12,7 @@ import types
import unittest
from pathlib import Path
from unittest.mock import patch
+from tests.codex_generation_support import init_generation_state, install_codex_transport
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -20,7 +21,7 @@ from modules.agents.service import AgentService
from modules.agents.claude_agent import ClaudeAgent
from modules.agents.codex.agent import CodexAgent
from modules.agents.opencode.agent import OpenCodeAgent
-from modules.agents.opencode.server import OpenCodeServerManager
+from modules.agents.opencode.server import OpenCodeGeneration
from core.resource_governance import AgentResourceFailure
from modules.im import MessageContext
@@ -74,11 +75,20 @@ class ClaudeBackendAliveTests(unittest.TestCase):
class CodexBackendAliveTests(unittest.TestCase):
def _agent(self, *, cwd_for_session, transports):
- agent = CodexAgent.__new__(CodexAgent) # bypass heavy __init__
+ agent = init_generation_state(object.__new__(CodexAgent)) # bypass heavy __init__
agent._session_mgr = types.SimpleNamespace(get_cwd=lambda bid: cwd_for_session.get(bid))
- agent._transports = transports
+ self.cwd_for_session = cwd_for_session
+ for cwd, transport in transports.items():
+ self._replace(agent, cwd, transport)
return agent
+ def _replace(self, agent, cwd, transport):
+ """Start a new generation for ``cwd`` that its Sessions move to."""
+ sessions = {base: "thread" for base, mapped in self.cwd_for_session.items() if mapped == cwd}
+ install_codex_transport(
+ agent, cwd, transport, sessions=sessions, digest=f"spec-{id(transport)}"
+ )
+
def _ctx_base(self, base_session_id):
return MessageContext(
user_id="U1", channel_id="C1", platform="slack",
@@ -124,10 +134,10 @@ class CodexBackendAliveTests(unittest.TestCase):
probe = agent.capture_backend_liveness(context)
accepted.is_alive = False
- agent._transports["/repo"] = types.SimpleNamespace(
+ self._replace(agent, "/repo", types.SimpleNamespace(
is_alive=True,
has_pending_notifications=False,
- )
+ ))
self.assertIs(agent.backend_alive(context), True)
self.assertIs(probe(), False)
@@ -145,10 +155,10 @@ class CodexBackendAliveTests(unittest.TestCase):
diagnose = agent.capture_backend_exit_failure(self._ctx_base("b1"))
self.assertIsNotNone(diagnose)
process.returncode = 137
- agent._transports["/repo"] = types.SimpleNamespace(
+ self._replace(agent, "/repo", types.SimpleNamespace(
is_alive=True,
_process=types.SimpleNamespace(returncode=None),
- )
+ ))
pressure = AgentResourceFailure(
kind="pids",
message="shared cgroup limit event",
@@ -198,53 +208,64 @@ class CodexBackendAliveTests(unittest.TestCase):
observe.assert_called_once_with(agent.controller)
+def _opencode_generation(generation_id: str, pid: int) -> OpenCodeGeneration:
+ return OpenCodeGeneration(
+ generation_id=generation_id,
+ pid=pid,
+ port=50000 + pid,
+ spec_digest="spec",
+ process_created_at=1000.0,
+ )
+
+
+def _opencode_agent() -> OpenCodeAgent:
+ agent = OpenCodeAgent.__new__(OpenCodeAgent)
+ agent.controller = types.SimpleNamespace()
+ agent._resource_failures = {}
+ return agent
+
+
class OpenCodeResourceExitTests(unittest.TestCase):
- def test_adopted_exit_consumes_pressure_only_after_original_generation_exits(self):
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.controller = types.SimpleNamespace()
- server = OpenCodeServerManager(binary="opencode", port=4096)
+ def test_generation_exit_consumes_pressure_only_after_its_own_process_exits(self):
+ agent = _opencode_agent()
+ generation = _opencode_generation("ocg_a", 654)
pressure = AgentResourceFailure(kind="pids", message="shared cgroup limit event")
with patch(
"modules.agents.opencode.server.runtime.process_create_time",
- side_effect=[1000.0, 1000.0, 2000.0],
+ # Alive, then the pid belongs to a later process.
+ side_effect=[1000.0, 2000.0],
), patch(
"modules.agents.opencode.agent.observe_agent_resource_pressure",
return_value=pressure,
) as observe:
- server._observe_runtime_generation({"pid": 654, "started_at": 1.0})
- self.assertIsNone(agent._resource_failure_for_server(server))
+ self.assertIsNone(agent._resource_failure_for_server(generation))
observe.assert_not_called()
- self.assertIs(agent._resource_failure_for_server(server), pressure)
+ self.assertIs(agent._resource_failure_for_server(generation), pressure)
observe.assert_called_once_with(agent.controller)
- def test_pressure_checks_are_cached_per_observed_server_generation(self):
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.controller = types.SimpleNamespace()
- server = OpenCodeServerManager(binary="opencode", port=4096)
- server.observed_runtime_exit_pid = (
- lambda: server._runtime_generation_token[0]
- )
+ def test_pressure_checks_are_cached_per_generation(self):
+ agent = _opencode_agent()
+ first = _opencode_generation("ocg_a", 654)
+ second = _opencode_generation("ocg_b", 655)
pressure = AgentResourceFailure(kind="pids", message="first exit")
- later_pressure = AgentResourceFailure(kind="memory", message="third exit")
with patch(
"modules.agents.opencode.server.runtime.process_create_time",
- return_value=1000.0,
+ return_value=None,
+ ), patch(
+ "modules.agents.opencode.server.runtime.pid_alive",
+ return_value=False,
), patch(
"modules.agents.opencode.agent.observe_agent_resource_pressure",
- side_effect=[pressure, None, later_pressure],
+ side_effect=[pressure, None],
) as observe:
- server._observe_runtime_generation({"pid": 654, "started_at": 1.0})
- self.assertIs(agent._resource_failure_for_server(server), pressure)
- self.assertIs(agent._resource_failure_for_server(server), pressure)
- server._observe_runtime_generation({"pid": 655, "started_at": 2.0})
- self.assertIsNone(agent._resource_failure_for_server(server))
- self.assertIsNone(agent._resource_failure_for_server(server))
- server._observe_runtime_generation({"pid": 656, "started_at": 3.0})
- self.assertIs(agent._resource_failure_for_server(server), later_pressure)
-
- self.assertEqual(observe.call_count, 3)
+ self.assertIs(agent._resource_failure_for_server(first), pressure)
+ self.assertIs(agent._resource_failure_for_server(first), pressure)
+ self.assertIsNone(agent._resource_failure_for_server(second))
+ self.assertIsNone(agent._resource_failure_for_server(second))
+
+ self.assertEqual(observe.call_count, 2)
class AgentServiceBackendAliveTests(unittest.TestCase):
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index 85f1b9ae6..865b665ed 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -386,18 +386,6 @@ def test_agent_service_reports_missing_runtime_refresh_contract() -> None:
assert asyncio.run(service.refresh_runtime_config("claude", object())) is False
-def test_agent_service_dispatches_model_hub_runtime_invalidation() -> None:
- service = AgentService(controller=SimpleNamespace())
- agent = SimpleNamespace(name="codex", invalidate_model_hub_runtime=AsyncMock())
- service.register(agent)
-
- handled = asyncio.run(service.invalidate_model_hub_runtime("codex"))
-
- assert handled is True
- agent.invalidate_model_hub_runtime.assert_awaited_once_with()
- assert asyncio.run(service.invalidate_model_hub_runtime("claude")) is False
-
-
def test_agent_service_notifies_run_owner_when_activity_runtime_disconnects() -> None:
settle = Mock()
controller = SimpleNamespace(
@@ -719,6 +707,31 @@ def test_force_end_backend_activities_waits_for_run_settlement_before_ack() -> N
service.activities.ack_recovered_terminal.assert_not_called()
+def test_a_runtime_force_end_keeps_the_activity_until_its_run_settles() -> None:
+ """A replaced runtime's killed Activity survives a failed Run settlement for a retry."""
+ controller = SimpleNamespace(
+ scheduled_task_service=SimpleNamespace(
+ settle_activity_runs=Mock(side_effect=RuntimeError("store unavailable")),
+ ),
+ )
+ service = AgentService(controller=controller)
+ service.activities.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-active",
+ kind="background_task",
+ run_id="run-active",
+ )
+
+ completed = service.force_end_runtime_activities("claude", "runtime-1")
+
+ assert [(item.id, item.status) for item in completed] == [("task-active", "killed")]
+ assert [item.id for item in service.activities.terminal_snapshots_for_runtime("claude", "runtime-1")] == [
+ "task-active"
+ ]
+
+
def test_force_cancel_backend_turns_emits_terminal_before_release() -> None:
async def _run():
controller = _Controller()
@@ -748,6 +761,108 @@ def test_force_cancel_backend_turns_emits_terminal_before_release() -> None:
asyncio.run(_run())
+def test_a_runtime_force_end_spares_the_next_turn_admitted_while_it_settles() -> None:
+ """Only the turns running when a runtime is force-ended are its work."""
+
+ async def _run():
+ controller = _Controller()
+ controller.emit_agent_message = AsyncMock()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ agent = _RuntimeAgent()
+ running: dict[str, asyncio.Event] = {}
+
+ async def handle_message(request):
+ running[request.message] = asyncio.Event()
+ await running[request.message].wait()
+
+ agent.handle_message = handle_message
+ service.register(agent)
+ first, second = _request("first"), _request("second")
+ first.base_session_id = second.base_session_id = "s1"
+ first_task = asyncio.create_task(service.handle_message("claude", first))
+ await asyncio.sleep(0)
+ second_task = asyncio.create_task(service.handle_message("claude", second))
+ await asyncio.sleep(0)
+
+ async def release_for_backend_refresh(**_kwargs):
+ # The first turn finishes meanwhile, so the Session's next one starts.
+ service.release_runtime_turn(first.context)
+ running["first"].set()
+ await first_task
+ await asyncio.wait_for(_until_started("second"), 1)
+
+ async def _until_started(message):
+ while message not in running:
+ await asyncio.sleep(0.01)
+
+ controller.session_turns = SimpleNamespace(
+ on_running=lambda _context: None,
+ release_for_backend_refresh=release_for_backend_refresh,
+ )
+
+ await service.force_end_runtime_work("claude", base_session_ids={"s1"}, activation_identities=())
+
+ assert not second_task.done()
+ controller.emit_agent_message.assert_not_awaited()
+ assert service.runtime_turn_tokens_for_backend("claude")
+ running["second"].set()
+ await asyncio.wait_for(second_task, 1)
+
+ asyncio.run(_run())
+
+
+def test_runtime_gen_006_a_disabled_agents_retried_stop_spares_the_re_enabled_agents_turn() -> None:
+ """RUNTIME-GEN-006: a disabled agent's stop names a Session whose next turn runs on a new agent.
+
+ The backend was enabled again before the retry, and the new agent now runs
+ the Session's next turn: that turn is not the stopping agent's work.
+ """
+
+ async def _run():
+ controller = _Controller()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ disabled, enabled = _RuntimeAgent(), _RuntimeAgent()
+ running = asyncio.Event()
+
+ async def handle_message(_request):
+ running.set()
+ await asyncio.Event().wait()
+
+ enabled.handle_message = handle_message
+ service.register(enabled)
+ request = _request("next")
+ request.base_session_id = "s1"
+ task = asyncio.create_task(service.handle_message("claude", request))
+ await asyncio.wait_for(running.wait(), 1)
+ released = []
+
+ async def release_for_backend_refresh(**kwargs):
+ released.append(kwargs)
+
+ controller.session_turns = SimpleNamespace(
+ on_running=lambda _context: None,
+ release_for_backend_refresh=release_for_backend_refresh,
+ )
+
+ await service.force_end_runtime_work(
+ "claude",
+ base_session_ids={"s1"},
+ activation_identities=(),
+ reason="backend_disabled",
+ agent=disabled,
+ )
+ await asyncio.sleep(0)
+
+ assert released == []
+ assert not task.done()
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+ asyncio.run(_run())
+
+
class _RecordingIndicator:
"""Records the queued/promote/finish reaction calls the gate drives."""
@@ -2358,3 +2473,29 @@ def test_real_child_exit_after_acceptance_recovers_runtime_fifo() -> None:
service.release_runtime_turn(second.context)
asyncio.run(_run())
+
+
+def test_a_failed_teardown_is_retried_until_it_finishes() -> None:
+ """A disabled backend's processes stop eventually even if the first stop fails.
+
+ The agent is already out of routing, so nothing else would ever stop them.
+ """
+
+ async def run() -> None:
+ attempts: list[int] = []
+
+ async def stop() -> None:
+ attempts.append(len(attempts))
+ if len(attempts) < 3:
+ raise RuntimeError("process survived its stop")
+
+ service = AgentService(controller=SimpleNamespace())
+ assert await service.run_until_done("disabled:codex", stop) is False
+ await service.retry_pending()
+ assert len(attempts) == 2
+ await service.retry_pending()
+ assert len(attempts) == 3
+ await service.retry_pending()
+ assert len(attempts) == 3
+
+ asyncio.run(run())
diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.py
index 5bff6528d..33753beec 100644
--- a/tests/test_agent_steering.py
+++ b/tests/test_agent_steering.py
@@ -33,10 +33,12 @@ from modules.agents.opencode.server import OpenCodePromptRejectedError
from modules.im import MessageContext
from modules.im.base import FileAttachment
+from tests.opencode_generation_fakes import serve_opencode_agent
from tests.test_session_delivery_fsm import (
_context, _seed_session,
_fsm_schema_template, managers, # noqa: F401 -- hermetic durable delivery fixtures
)
+from tests.codex_generation_support import init_generation_state, install_codex_transport
STEER_TEXT = "补充:**不要改写**\n```python\nprint('λ')\n```"
@@ -304,10 +306,10 @@ async def test_native_steer_uses_normal_attachment_input_without_replacing_prima
client = _ClaudeClient()
server = _OpenCodeServer()
if backend == "codex":
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
elif backend == "claude":
agent = object.__new__(ClaudeAgent)
agent.claude_sessions = {"runtime-key": client}
@@ -367,11 +369,11 @@ async def test_codex_steers_expected_active_turn_without_starting_another_turn(n
primary = _primary_request(backend="codex")
gate_task = await _held_task()
transport = _CodexTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.config = SimpleNamespace(include_time_info=True, include_user_info=True)
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
try:
identity = active_steer_identity(controller, "codex", "avibe-session")
@@ -394,7 +396,7 @@ async def test_codex_steers_expected_active_turn_without_starting_another_turn(n
)
]
assert len(agent._turn_registry.active_turns) == 1
- assert primary.working_path in agent._transport_last_activity
+ assert agent.transport_for_session(primary.base_session_id) is transport
assert not gate_task.done()
finally:
await _cancel_tasks(gate_task)
@@ -427,14 +429,14 @@ async def test_codex_steer_reconciliation_uses_persisted_client_message_id() ->
return {"turnId": "codex-turn"}
transport = _ReconcileTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(
primary.base_session_id,
"codex-thread",
primary.working_path,
)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
target = ActiveSteerTarget(
runtime_key="runtime-key",
@@ -511,15 +513,14 @@ async def test_codex_steer_reconciliation_survives_completed_native_turn() -> No
}
transport = _CompletedTurnTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(
primary.base_session_id,
"codex-thread",
primary.working_path,
)
- agent._transports = {primary.working_path: transport}
- agent._transport_last_activity = {}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
request = SteerRequest(
target_session_id="avibe-session",
@@ -583,14 +584,14 @@ async def test_codex_steer_reconciliation_uses_durable_binding_after_restart(mon
),
)
transport = _CompletedTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "different-turn")
agent._session_mgr = _CodexSessionManager(
primary.base_session_id,
"stale-thread",
primary.working_path,
)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
agent._steer_reconciliation_targets = {}
request = SteerReconcileRequest(
@@ -617,15 +618,14 @@ async def test_codex_steer_reconciliation_cache_keeps_only_unknown_receipts() ->
async def run(error: Exception | None, response: dict | None) -> dict:
gate_task = await _held_task()
transport = _CodexTransport(error=error, response=response)
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(
primary.base_session_id,
"codex-thread",
primary.working_path,
)
- agent._transports = {primary.working_path: transport}
- agent._transport_last_activity = {}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
try:
await steer_active_turn(
@@ -661,7 +661,7 @@ async def test_codex_start_renders_now_after_runtime_prompt_preparation(monkeypa
))
request = _primary_request(backend="codex")
request.input_metadata = AgentInputMetadata(user_id="sender", user_name="Sender")
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.config = SimpleNamespace(include_time_info=True, include_user_info=True)
agent.controller = SimpleNamespace()
agent._prompt_state_agent_session_id = lambda _request: None
@@ -693,10 +693,10 @@ async def test_shared_gate_remains_steerable_after_dispatch_task_returns() -> No
completed_dispatch = asyncio.create_task(asyncio.sleep(0))
await completed_dispatch
transport = _CodexTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, completed_dispatch)
identity = active_steer_identity(controller, "codex", "avibe-session")
@@ -722,19 +722,19 @@ async def test_codex_maps_native_failures_without_turn_start(error: Exception, e
primary = _primary_request(backend="codex")
gate_task = await _held_task()
transport = _CodexTransport(error=error)
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: transport}
+ agent_generation = install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
try:
receipt = await steer_active_turn(controller, "codex", _steer_request("codex-turn"))
assert receipt.outcome is expected
assert [method for method, _params in transport.calls] == ["turn/steer"]
if expected is SteerOutcome.UNKNOWN:
- assert primary.working_path in agent._transport_last_activity
+ assert agent_generation.runtime.last_activity > 0.0
else:
- assert primary.working_path not in getattr(agent, "_transport_last_activity", {})
+ assert agent_generation.runtime.last_activity == 0.0
finally:
await _cancel_tasks(gate_task)
@@ -744,17 +744,17 @@ async def test_codex_rejects_stale_native_turn_and_unavailable_runtime() -> None
primary = _primary_request(backend="codex")
gate_task = await _held_task()
transport = _CodexTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
try:
stale = await steer_active_turn(controller, "codex", _steer_request("stale-turn"))
assert stale.outcome is SteerOutcome.NOT_ACTIVE
assert transport.calls == []
- agent._transports.clear()
+ agent._session_generations.clear()
unavailable = await steer_active_turn(controller, "codex", _steer_request("codex-turn"))
assert unavailable.outcome is SteerOutcome.REFUSED
assert unavailable.reason == "runtime_unavailable"
@@ -1015,7 +1015,9 @@ def _opencode_agent(primary: AgentRequest, task: asyncio.Task, server: _OpenCode
"opencode-session",
primary.working_path,
)
- agent._client_manager = SimpleNamespace(_server_manager=server)
+ serve_opencode_agent(agent, server)
+ if server is not None:
+ agent._session_generations[primary.base_session_id] = server
agent._user_stopped_sessions = set()
agent._steering_states = {
primary.base_session_id: _OpenCodeSteerState(
@@ -1030,6 +1032,7 @@ def _opencode_agent(primary: AgentRequest, task: asyncio.Task, server: _OpenCode
reasoning_effort="high",
system="primary system prompt",
baseline_message_ids=set(),
+ generation=server,
)
}
return agent
@@ -1210,7 +1213,6 @@ async def test_opencode_stop_waits_for_in_flight_steering_write() -> None:
agent = _opencode_agent(primary, gate_task, server)
controller = _controller_with_active_gate(agent, primary, gate_task)
controller.emit_agent_message = AsyncMock()
- agent._get_server = AsyncMock(return_value=server)
removed_polls: list[str] = []
agent.sessions = SimpleNamespace(
get_all_active_polls=lambda: {"opencode-session": object()},
@@ -1273,7 +1275,6 @@ async def test_opencode_replacement_waits_for_in_flight_steering_write() -> None
primary.working_path,
)
agent.controller = controller
- agent._get_server = AsyncMock(return_value=server)
agent._process_message = AsyncMock(return_value=None)
try:
identity = active_steer_identity(controller, "opencode", "avibe-session")
@@ -1409,8 +1410,7 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanu
agent._poll_loop = SimpleNamespace()
agent._steering_states = {}
agent._active_requests = {}
- agent._client_manager = SimpleNamespace(_server_manager=server)
- agent._get_server = AsyncMock(return_value=server)
+ serve_opencode_agent(agent, server)
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
agent._prepare_message_with_files = lambda request: request.message
@@ -1539,8 +1539,7 @@ async def test_opencode_ambiguous_start_failure_preserves_recovery_poll(
agent._poll_loop = SimpleNamespace()
agent._steering_states = {}
agent._active_requests = {}
- agent._client_manager = SimpleNamespace(_server_manager=server)
- agent._get_server = AsyncMock(return_value=server)
+ serve_opencode_agent(agent, server)
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
agent._prepare_message_with_files = lambda request: request.message
@@ -2714,7 +2713,8 @@ async def test_opencode_rejects_stale_runner_and_unavailable_runtime() -> None:
assert stale.outcome is SteerOutcome.NOT_ACTIVE
assert server.prompt_calls == []
- agent._client_manager._server_manager = None
+ # The native turn has no generation that could take the steer.
+ agent._steering_states[primary.base_session_id].generation = None
identity = agent.steering_native_turn_id(
SimpleNamespace(runtime_key="runtime-key", agent_request=primary)
)
@@ -2730,10 +2730,10 @@ async def test_shared_guard_rejects_stale_logical_or_missing_active_turn() -> No
primary = _primary_request(backend="codex")
gate_task = await _held_task()
transport = _CodexTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
try:
stale = await steer_active_turn(
@@ -2757,10 +2757,10 @@ async def test_shared_guard_requires_the_avibe_session_identity() -> None:
primary.base_session_id = "backend-anchor"
gate_task = await _held_task()
transport = _CodexTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
request = _steer_request("codex-turn")
request = SteerRequest(
@@ -2782,24 +2782,23 @@ async def test_shared_service_uses_the_active_runtime_generation_after_registry_
primary = _primary_request(backend="codex")
gate_task = await _held_task()
active_transport = _CodexTransport()
- active_agent = object.__new__(CodexAgent)
+ active_agent = init_generation_state(object.__new__(CodexAgent))
active_agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
active_agent._session_mgr = _CodexSessionManager(
primary.base_session_id,
"codex-thread",
primary.working_path,
)
- active_agent._transports = {primary.working_path: active_transport}
+ install_codex_transport(active_agent, primary.working_path, active_transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(active_agent, primary, gate_task)
- replacement_agent = object.__new__(CodexAgent)
+ replacement_agent = init_generation_state(object.__new__(CodexAgent))
replacement_agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "replacement-turn")
replacement_agent._session_mgr = _CodexSessionManager(
primary.base_session_id,
"replacement-thread",
primary.working_path,
)
- replacement_agent._transports = {}
controller.agent_service.agents["codex"] = replacement_agent
try:
identity = active_steer_identity(controller, "codex", "avibe-session")
@@ -2821,20 +2820,20 @@ async def test_shared_guard_disambiguates_concurrent_gates_by_expected_turn_iden
second_task = await _held_task()
first_transport = _CodexTransport(response={"turnId": "codex-turn-1"})
- first_agent = object.__new__(CodexAgent)
+ first_agent = init_generation_state(object.__new__(CodexAgent))
first_agent._turn_registry = _CodexTurnRegistry(first.base_session_id, "codex-turn-1")
first_agent._session_mgr = _CodexSessionManager(first.base_session_id, "codex-thread-1", first.working_path)
- first_agent._transports = {first.working_path: first_transport}
+ install_codex_transport(first_agent, first.working_path, first_transport, sessions={first.base_session_id: "codex-thread"}, last_activity=0.0)
second_transport = _CodexTransport(response={"turnId": "codex-turn-2"})
- second_agent = object.__new__(CodexAgent)
+ second_agent = init_generation_state(object.__new__(CodexAgent))
second_agent._turn_registry = _CodexTurnRegistry(second.base_session_id, "codex-turn-2")
second_agent._session_mgr = _CodexSessionManager(
second.base_session_id,
"codex-thread-2",
second.working_path,
)
- second_agent._transports = {second.working_path: second_transport}
+ install_codex_transport(second_agent, second.working_path, second_transport, sessions={second.base_session_id: "codex-thread"}, last_activity=0.0)
gates = {
"main": SimpleNamespace(
@@ -2889,14 +2888,14 @@ async def test_shared_service_prefers_explicit_session_target_over_legacy_id() -
primary.context.platform_specific["agent_session_id"] = "stale-session"
gate_task = await _held_task()
transport = _CodexTransport()
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(
primary.base_session_id,
"codex-thread",
primary.working_path,
)
- agent._transports = {primary.working_path: transport}
+ install_codex_transport(agent, primary.working_path, transport, sessions={primary.base_session_id: "codex-thread"}, last_activity=0.0)
controller = _controller_with_active_gate(agent, primary, gate_task)
try:
assert active_steer_identity(controller, "codex", "stale-session") is None
@@ -3052,8 +3051,7 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(
agent._poll_loop = _PollLoop()
agent._steering_states = {}
agent._active_requests = {}
- agent._client_manager = SimpleNamespace(_server_manager=server)
- agent._get_server = AsyncMock(return_value=server)
+ serve_opencode_agent(agent, server)
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
agent._prepare_message_with_files = lambda request: request.message
diff --git a/tests/test_agent_stop_settlement.py b/tests/test_agent_stop_settlement.py
index 9858ef88a..6f4f428f0 100644
--- a/tests/test_agent_stop_settlement.py
+++ b/tests/test_agent_stop_settlement.py
@@ -20,6 +20,7 @@ import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock
+from tests.codex_generation_support import init_generation_state, install_codex_transport
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -108,13 +109,16 @@ class AgentStopSettlementTests(unittest.IsolatedAsyncioTestCase):
def _codex_stop_case():
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = SimpleNamespace(get_thread_id=lambda base_session_id: "thread-1")
agent._turn_registry = _StubTurnRegistry()
agent._turn_registry._active_turns["session-1"] = "turn-1"
- agent._transports = {
- "/tmp": SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={}))
- }
+ install_codex_transport(
+ agent,
+ "/tmp",
+ SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={})),
+ sessions={"session-1": "thread-1"},
+ )
agent._event_handler = SimpleNamespace(clear_pending=lambda turn_id: SimpleNamespace())
agent._user_stopped_turn_ids = set()
agent._remove_ack_reaction = AsyncMock()
@@ -154,6 +158,7 @@ def _opencode_stop_case():
get_request_session=lambda _base: None,
)
agent._user_stopped_sessions = set()
+ agent._session_generations = {}
async def _in_flight():
await asyncio.Event().wait()
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index f5d4d0a8f..10cf43bab 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -120,8 +120,8 @@ def test_opencode_permission_does_not_gate_another_backend_or_launch_daemon(conn
monkeypatch.setattr(api, "_read_opencode_config_api_key_provider_ids", AsyncMock(return_value={"provider"}))
monkeypatch.setattr(opencode_config, "read_opencode_provider_auth_entries", lambda **_: {})
monkeypatch.setattr(api, "opencode_permission_status", lambda: {"ok": True, "permission_allowed": False})
- daemon = AsyncMock(side_effect=AssertionError("readiness must not launch a daemon"))
- monkeypatch.setattr(api, "_opencode_get_server", daemon)
+ daemon = AsyncMock(side_effect=AssertionError("readiness must not lease an OpenCode server"))
+ monkeypatch.setattr(api, "_opencode_lease", daemon)
state = asyncio.run(api.get_backend_connection("opencode"))
assert state["auth"] == "api_key" and state["permission_required"] and not state["entry_eligible"]
assert asyncio.run(api.get_backend_connection("claude"))["ready"]
@@ -150,9 +150,12 @@ def test_only_confirmed_new_controller_clears_old_failed_delivery(connection, mo
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
[email protected]("application", ["applied", "draining", "failed", "stopped"])
[email protected]("application", ["applied", "busy", "failed", "stopped"])
def test_install_job_applies_persisted_path_before_admitting_connection(monkeypatch, tmp_path, backend, application):
- """The real install-job result and readiness consume the same rolling apply."""
+ """The real install-job result and readiness consume the same in-place renewal.
+
+ Work running on the backend never holds the install's application back.
+ """
from core.backend_restart import BackendRestartCoordinator
from vibe import opencode_config
@@ -185,7 +188,7 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
async def run():
service = SimpleNamespace(
agents={name: object() for name in ("claude", "codex", "opencode")},
- active=application == "draining",
+ active=application == "busy",
begin_backend_drain=Mock(), end_backend_drain=Mock(),
prepare_backend_restart=AsyncMock(),
)
@@ -195,13 +198,13 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
))
applied = []
- async def refresh(name, _forced):
+ async def renew(name, _config_save):
applied.append(name)
if application == "failed":
raise RuntimeError("fixture apply failed")
controller.config = V2Config.load()
- coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ coordinator = BackendRestartCoordinator(controller, AsyncMock(), renew=renew, poll_interval=0.001)
loop = asyncio.get_running_loop()
def marker(name, **_kwargs):
@@ -228,20 +231,14 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
assert job["path"] == installed_path
assert getattr(V2Config.load().agents, backend).cli_path == installed_path
state = await api.get_backend_connection(backend)
- assert state["application"] == application, (job, state)
- assert state["ready"] is (application == "applied")
- assert state["entry_eligible"] is (application in {"applied", "stopped"})
+ expected = "applied" if application == "busy" else application
+ assert state["application"] == expected, (job, state)
+ assert state["ready"] is (expected == "applied")
+ assert state["entry_eligible"] is (expected in {"applied", "stopped"})
assert job["ok"] is (application != "failed")
if application == "stopped":
assert job["restart"]["apply_on_next_start"] and not applied
- elif application == "draining":
- assert getattr(controller.config.agents, backend).cli_path == "/old/missing-cli"
- service.active = False
- await coordinator.wait(backend)
- assert (await api.get_backend_connection(backend))["ready"]
- assert getattr(controller.config.agents, backend).cli_path == installed_path
- assert applied == [backend]
- elif application == "applied":
+ elif expected == "applied":
assert getattr(controller.config.agents, backend).cli_path == installed_path
assert applied == [backend]
else:
@@ -284,18 +281,21 @@ def test_disabled_applied_configuration_stays_saved_without_readiness(monkeypatc
session_turns=SimpleNamespace(begin_backend_drain=Mock(), end_backend_drain=AsyncMock()))
# Claude's loaded compat object remains registered even when disabled.
claude = SimpleNamespace(config=controller.config, controller=controller, refresh_auth_state=AsyncMock())
- claude.refresh_runtime_config = lambda value: ClaudeAgent.refresh_runtime_config(claude, value)
+ claude.renew_runtime = lambda value, config_save=False: ClaudeAgent.renew_runtime(
+ claude, value, config_save=config_save
+ )
service.agents["claude"] = claude
if backend != "claude":
service.agents[backend] = SimpleNamespace(shutdown_runtime=AsyncMock())
- async def refresh(name, value):
- if name == "claude":
- await claude.refresh_runtime_config(value)
- return True
- return False
- service.refresh_runtime_config = refresh
owner = AgentAuthService(controller)
- coordinator = BackendRestartCoordinator(controller, owner._apply_backend_runtime_refresh)
+ failure = []
+
+ async def renew(name, config_save):
+ if failure:
+ raise failure[0]
+ await owner.renew_backend_runtime(name, config_save)
+
+ coordinator = BackendRestartCoordinator(controller, owner._apply_backend_runtime_refresh, renew=renew)
async def projection(name):
return {"status_code": 200, "body": {"ok": True, **coordinator.snapshot(name)}}
monkeypatch.setattr(internal_client, "backend_application", projection)
@@ -331,7 +331,7 @@ def test_disabled_applied_configuration_stays_saved_without_readiness(monkeypatc
assert state["application"] == "applied"
assert not state["enabled"] and not state["ready"] and not state["entry_eligible"]
# Startup from the same loaded disabled shape is also authoritative.
- startup = BackendRestartCoordinator(controller, owner._apply_backend_runtime_refresh)
+ startup = BackendRestartCoordinator(controller, owner._apply_backend_runtime_refresh, renew=renew)
assert startup.snapshot(backend) == {"state": "applied", "disabled": True}
# A concurrent disk enable cannot borrow the disabled controller's
# applied state before that enablement is reconciled.
@@ -341,8 +341,8 @@ def test_disabled_applied_configuration_stays_saved_without_readiness(monkeypatc
assert stale["application"] == "unknown" and not stale["ready"] and not stale["entry_eligible"]
getattr(config.agents, backend).enabled = False
config.save()
- # A failed subsequent prepare retains the failure even when disabled.
- service.prepare_backend_restart.side_effect = RuntimeError("fixture failure")
+ # A failed subsequent application retains the failure even when disabled.
+ failure.append(RuntimeError("fixture failure"))
with pytest.raises(RuntimeError, match="fixture failure"):
await coordinator.request_restart(backend)
assert (await api.get_backend_connection(backend))["application"] == "failed"
diff --git a/tests/test_backend_restart.py b/tests/test_backend_restart.py
index c38f40dd4..4ea77b9f6 100644
--- a/tests/test_backend_restart.py
+++ b/tests/test_backend_restart.py
@@ -8,6 +8,7 @@ import pytest
from core.backend_restart import BackendRestartCoordinator, NativeCredentialLease, NativeMigrationBlockedError
from core.controller import Controller
+from core.run_settlement import SETTLED_BY_BACKEND_DISABLED
class _AgentService:
@@ -15,6 +16,7 @@ class _AgentService:
self.active = False
self.runtime_active = False
self.draining = False
+ self.agents: dict = {}
def begin_backend_drain(self, backend: str) -> None:
assert backend == "opencode"
@@ -33,7 +35,7 @@ class _AgentService:
def backend_runtime_active(self, backend: str) -> bool:
return self.runtime_active
- def force_end_backend_activities(self, backend: str) -> list:
+ def force_end_backend_activities(self, backend: str, *, reason: str = "backend_refresh") -> list:
assert backend == "opencode"
return []
@@ -56,117 +58,49 @@ def _controller(service: _AgentService):
return SimpleNamespace(agent_service=service, session_turns=session_turns)
-def test_restart_drains_active_turn_before_refresh() -> None:
- async def run() -> None:
- service = _AgentService()
- service.active = True
- controller = _controller(service)
- refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)
+def test_runtime_gen_004_a_restart_request_never_drains_holds_or_interrupts() -> None:
+ """RUNTIME-GEN-004: a routine restart request interrupts nothing and holds no turn.
- assert await coordinator.request_restart("opencode") == "draining"
- assert service.draining is True
- refresh.assert_not_awaited()
-
- service.active = False
- await coordinator.wait("opencode")
+ Work is running, yet the request renews at once: admission never closes,
+ no turn is interrupted, and nothing is torn down. A renewal that fails is
+ reported, never shown as applied.
+ """
- refresh.assert_awaited_once_with("opencode", False)
- controller.session_turns.release_for_backend_refresh.assert_not_awaited()
- controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=True)
- assert service.draining is False
-
- asyncio.run(run())
-
-
-def test_restart_timeout_forces_cutover_and_releases_workbench_turns() -> None:
async def run() -> None:
service = _AgentService()
+ service.agents = {"opencode": object()}
service.active = True
service.runtime_active = True
controller = _controller(service)
-
- async def refresh(_backend: str, forced: bool) -> None:
- assert forced is True
- service.runtime_active = False
-
- coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=0, poll_interval=0.001)
-
- await coordinator.request_restart("opencode")
- await coordinator.wait("opencode")
-
- controller.session_turns.release_for_backend_refresh.assert_awaited_once_with(
- backend="opencode",
- base_session_ids={"ses-1"},
- )
- assert service.draining is False
-
- asyncio.run(run())
-
-
-def test_concurrent_restart_requests_coalesce() -> None:
- async def run() -> None:
- service = _AgentService()
- service.active = True
- controller = _controller(service)
refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)
-
- first, second = await asyncio.gather(
- coordinator.request_restart("opencode"),
- coordinator.request_restart("opencode"),
- )
- assert first == second == "draining"
- controller.session_turns.begin_backend_drain.assert_called_once_with("opencode")
-
- service.active = False
- await coordinator.wait("opencode")
- refresh.assert_awaited_once()
+ renew = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, renew=renew, poll_interval=0.001)
- asyncio.run(run())
-
-
-def test_refresh_failure_reopens_barrier() -> None:
- async def run() -> None:
- service = _AgentService()
- service.active = True
- controller = _controller(service)
- refresh = AsyncMock(side_effect=RuntimeError("refresh failed"))
- coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)
-
- await coordinator.request_restart("opencode")
- service.active = False
- with pytest.raises(RuntimeError, match="refresh failed"):
- await coordinator.wait("opencode")
+ assert await coordinator.request_restart("opencode", config_save=True) == "restarted"
+ assert await coordinator.request_restart("opencode") == "restarted"
+ assert [awaited.args for awaited in renew.await_args_list] == [("opencode", True), ("opencode", False)]
assert service.draining is False
- controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=False)
-
- asyncio.run(run())
-
-
-def test_idle_refresh_failure_is_propagated_before_ack() -> None:
- async def run() -> None:
- service = _AgentService()
- controller = _controller(service)
- refresh = AsyncMock(side_effect=RuntimeError("invalid config"))
- coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1)
+ refresh.assert_not_awaited()
+ controller.session_turns.begin_backend_drain.assert_not_called()
+ controller.session_turns.release_for_backend_refresh.assert_not_awaited()
+ assert coordinator.snapshot("opencode")["state"] == "applied"
- with pytest.raises(RuntimeError, match="invalid config"):
+ renew.side_effect = RuntimeError("config rejected")
+ with pytest.raises(RuntimeError, match="config rejected"):
await coordinator.request_restart("opencode")
+ assert coordinator.snapshot("opencode") == {"state": "failed", "error": "config rejected"}
- assert service.draining is False
- controller.session_turns.end_backend_drain.assert_awaited_once_with(
- "opencode",
- resume_deferred=False,
- )
+ renew.side_effect = None
+ await coordinator.request_restart("opencode")
+ assert coordinator.snapshot("opencode") == {"state": "applied"}
asyncio.run(run())
def test_controller_reconciles_requested_backends_once_in_order() -> None:
async def run() -> None:
- coordinator = SimpleNamespace(request_restart=AsyncMock(side_effect=["restarted", "draining"]))
+ coordinator = SimpleNamespace(request_restart=AsyncMock(side_effect=["restarted", "restarted"]))
controller = SimpleNamespace(backend_restart_coordinator=coordinator)
result = await Controller.reconcile_agent_backends(
@@ -177,7 +111,7 @@ def test_controller_reconciles_requested_backends_once_in_order() -> None:
assert result == {
"ok": True,
"backends": ["codex", "opencode"],
- "states": {"codex": "restarted", "opencode": "draining"},
+ "states": {"codex": "restarted", "opencode": "restarted"},
}
assert [awaited.args for awaited in coordinator.request_restart.await_args_list] == [
("codex",),
@@ -196,134 +130,57 @@ def test_controller_rejects_unknown_backend_reconcile() -> None:
controller.backend_restart_coordinator.request_restart.assert_not_awaited()
-def test_application_projection_tracks_prepare_drain_failure_retry_and_registration():
- async def run():
- service = _AgentService()
- service.agents = {"opencode": object(), "claude": object()}
- controller = _controller(service)
- refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
- assert coordinator.snapshot("opencode") == {"state": "applied"}
- assert coordinator.snapshot("codex") == {"state": "unavailable"}
-
- preparing = asyncio.Event()
- release = asyncio.Event()
-
- async def prepare(_backend):
- preparing.set()
- await release.wait()
-
- service.prepare_backend_restart = prepare
- request = asyncio.create_task(coordinator.request_restart("opencode"))
- await preparing.wait()
- assert coordinator.snapshot("opencode") == {"state": "draining"}
- assert coordinator.snapshot("claude") == {"state": "applied"}
- service.active = True
- release.set()
- assert await request == "draining"
- assert coordinator.snapshot("opencode") == {"state": "draining"}
- refresh.side_effect = RuntimeError("application failed")
- service.active = False
- with pytest.raises(RuntimeError, match="application failed"):
- await coordinator.wait("opencode")
- assert coordinator.snapshot("opencode") == {"state": "failed", "error": "application failed"}
- assert coordinator.snapshot("claude") == {"state": "applied"}
-
- refresh.side_effect = None
- assert await coordinator.request_restart("opencode") == "restarted"
- assert coordinator.snapshot("opencode") == {"state": "applied"}
- service.agents.pop("opencode")
- assert coordinator.snapshot("opencode") == {"state": "unavailable"}
-
- asyncio.run(run())
+def test_runtime_gen_008_idle_maintenance_runs_behind_closed_admission_then_renews():
+ """RUNTIME-GEN-008: an unattended CLI update renews after its install.
+ Admission is closed only while the CLI is replaced, so no turn launches a
+ half-installed binary. The runtime then renews in place rather than being
+ torn down, and messages held meanwhile resume on it.
+ """
[email protected]("failure", [RuntimeError("prepare failed"), asyncio.CancelledError()])
-def test_application_projection_retains_prepare_failure_and_cancellation(failure):
- async def run():
- service = _AgentService()
- service.agents = {"opencode": object()}
- service.prepare_backend_restart = AsyncMock(side_effect=failure)
- controller = _controller(service)
- coordinator = BackendRestartCoordinator(controller, AsyncMock())
- with pytest.raises(type(failure)):
- await coordinator.request_restart("opencode")
- assert coordinator.snapshot("opencode")["state"] == "failed"
- assert not service.draining
- controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=False)
-
- asyncio.run(run())
-
-
-def test_cancelled_application_remains_failed_after_task_is_removed():
- async def run():
- service = _AgentService()
- service.agents = {"opencode": object()}
- service.active = True
- coordinator = BackendRestartCoordinator(_controller(service), AsyncMock())
- await coordinator.request_restart("opencode")
- await asyncio.sleep(0)
- task = coordinator._tasks["opencode"]
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
- assert coordinator.snapshot("opencode") == {"state": "failed", "error": "cancelled"}
- assert not service.draining
-
- asyncio.run(run())
-
-
-def test_idle_maintenance_runs_behind_closed_admission_then_refreshes():
async def run():
service = _AgentService()
controller = _controller(service)
refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ renew = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, renew=renew, poll_interval=0.001)
async def install():
# Nothing may start a turn on the CLI while it is being replaced.
assert service.draining is True
controller.session_turns.begin_backend_drain.assert_called_once_with("opencode")
- refresh.assert_not_awaited()
+ renew.assert_not_awaited()
return {"ok": True}
assert await coordinator.run_when_idle("opencode", install) == {"ok": True}
- refresh.assert_awaited_once_with("opencode", False)
+ renew.assert_awaited_once_with("opencode", False)
+ refresh.assert_not_awaited()
controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=True)
assert service.draining is False
asyncio.run(run())
[email protected]("holder", ["active_turn", "restart_draining"])
-def test_maintenance_yields_to_a_busy_backend_without_touching_its_work(holder):
+def test_maintenance_yields_to_a_busy_backend_without_touching_its_work():
async def run():
service = _AgentService()
service.active = True
controller = _controller(service)
refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)
- if holder == "restart_draining":
- assert await coordinator.request_restart("opencode") == "draining"
- controller.session_turns.end_backend_drain.reset_mock()
+ renew = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, renew=renew, poll_interval=0.001)
operation = AsyncMock()
assert await coordinator.run_when_idle("opencode", operation) is None
operation.assert_not_awaited()
refresh.assert_not_awaited()
+ renew.assert_not_awaited()
controller.session_turns.release_for_backend_refresh.assert_not_awaited()
- if holder == "active_turn":
- # The turn keeps running; messages held meanwhile resume unchanged.
- controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode")
- assert service.draining is False
- else:
- controller.session_turns.end_backend_drain.assert_not_awaited()
- assert service.draining is True
- service.active = False
- await coordinator.wait("opencode")
- refresh.assert_awaited_once_with("opencode", False)
+ # The turn keeps running; messages held meanwhile resume unchanged.
+ controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode")
+ assert service.draining is False
asyncio.run(run())
@@ -333,7 +190,7 @@ def test_maintenance_and_a_native_login_exclude_each_other():
service = _AgentService()
controller = _controller(service)
refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ coordinator = BackendRestartCoordinator(controller, refresh, renew=AsyncMock(), poll_interval=0.001)
operation = AsyncMock()
# A login in the Web process holds the backend's lease for its whole flow.
@@ -357,12 +214,12 @@ def test_maintenance_and_a_native_login_exclude_each_other():
asyncio.run(run())
-def test_cancelled_requester_waits_for_maintenance_and_its_refresh():
+def test_cancelled_requester_waits_for_maintenance_and_its_renewal():
async def run():
service = _AgentService()
controller = _controller(service)
- refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ renew = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, AsyncMock(), renew=renew, poll_interval=0.001)
installing = asyncio.Event()
finish = asyncio.Event()
@@ -381,19 +238,19 @@ def test_cancelled_requester_waits_for_maintenance_and_its_refresh():
finish.set()
with pytest.raises(asyncio.CancelledError):
await requester
- refresh.assert_awaited_once_with("opencode", False)
+ renew.assert_awaited_once_with("opencode", False)
assert service.draining is False
asyncio.run(run())
-def test_restart_requested_during_maintenance_is_applied_by_its_refresh():
+def test_a_restart_requested_during_maintenance_renews_without_waiting_for_it():
async def run():
service = _AgentService()
service.agents = {"opencode": object()}
controller = _controller(service)
- refresh = AsyncMock()
- coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ renew = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, AsyncMock(), renew=renew, poll_interval=0.001)
installing = asyncio.Event()
finish = asyncio.Event()
@@ -405,12 +262,157 @@ def test_restart_requested_during_maintenance_is_applied_by_its_refresh():
maintenance = asyncio.create_task(coordinator.run_when_idle("opencode", install))
await installing.wait()
assert coordinator.snapshot("opencode") == {"state": "draining"}
- assert await coordinator.request_restart("opencode") == "draining"
- controller.session_turns.begin_backend_drain.assert_called_once_with("opencode")
+ assert await asyncio.wait_for(coordinator.request_restart("opencode"), timeout=1) == "restarted"
+ renew.assert_awaited_once_with("opencode", False)
finish.set()
assert await maintenance == {"ok": True}
- refresh.assert_awaited_once_with("opencode", False)
+ # The install renews again, so the replaced CLI is what new turns use.
+ assert renew.await_count == 2
assert coordinator.snapshot("opencode") == {"state": "applied"}
asyncio.run(run())
+
+
+class _DisabledAgent:
+ """An agent whose turn is still running when its backend is disabled."""
+
+ def __init__(self, name: str) -> None:
+ self.name = name
+ self.shutdown_runtime = AsyncMock()
+
+
+def _disabling_controller(agent: _DisabledAgent):
+ from core.agent_auth_service import AgentAuthService
+ from modules.agents.service import AgentService
+
+ service = _AgentService()
+ controller = _controller(service)
+ controller.config = SimpleNamespace(codex=object())
+ controller.agent_service = AgentService(controller)
+ controller.agent_service.register(agent)
+ auth = AgentAuthService(controller)
+ auth._load_backend_runtime_config = Mock(return_value=None)
+ auth._sync_builtin_default_agents = Mock()
+ coordinator = BackendRestartCoordinator(controller, AsyncMock(), renew=auth.renew_backend_runtime)
+ controller.backend_restart_coordinator = coordinator
+ return controller, auth, coordinator
+
+
+def test_runtime_gen_006_disabling_a_backend_stops_its_work_at_once():
+ """RUNTIME-GEN-006: disabling a backend is the user's own interruption.
+
+ The agent leaves the registry first, so a new message sees the backend
+ disabled immediately and nothing is held. Its running turns and Activities
+ settle with the runtime-interruption notice, and every process of the
+ backend stops. Nothing waits for the work to finish.
+ """
+
+ async def run() -> None:
+ agent = _DisabledAgent("codex")
+ controller, _auth, coordinator = _disabling_controller(agent)
+ controller.agent_service.force_cancel_backend_turns = AsyncMock(
+ side_effect=lambda backend: order.append(("cancel", backend))
+ )
+ order: list = []
+ agent.shutdown_runtime.side_effect = lambda **_kwargs: order.append(("stop", "codex"))
+ controller.session_turns.active_runtime_session_ids_for_backend = Mock(return_value={"ses-1"})
+
+ assert await asyncio.wait_for(coordinator.request_restart("codex", config_save=True), timeout=1) == "restarted"
+
+ assert "codex" not in controller.agent_service.agents
+ assert controller.config.codex is None
+ # The user's own interruption is reported as such, not as a runtime refresh.
+ controller.session_turns.release_for_backend_refresh.assert_awaited_once_with(
+ backend="codex", base_session_ids={"ses-1"}, settled_by=SETTLED_BY_BACKEND_DISABLED
+ )
+ assert order == [("cancel", "codex"), ("stop", "codex")]
+ controller.session_turns.begin_backend_drain.assert_not_called()
+
+ asyncio.run(run())
+
+
+def test_a_disable_whose_interruption_fails_still_stops_and_retries_the_processes():
+ """Disabling never leaves a backend's processes unowned.
+
+ An interruption failure does not skip the stop, and a stop that fails is
+ retried by the idle sweep, because the agent is already out of routing.
+ """
+
+ async def run() -> None:
+ agent = _DisabledAgent("codex")
+ controller, _auth, coordinator = _disabling_controller(agent)
+ controller.session_turns.release_for_backend_refresh = AsyncMock(side_effect=[RuntimeError("db busy"), 0])
+ agent.shutdown_runtime.side_effect = [RuntimeError("process survived"), None]
+
+ assert await coordinator.request_restart("codex", config_save=True) == "restarted"
+
+ assert "codex" not in controller.agent_service.agents
+ assert agent.shutdown_runtime.await_count == 1
+ # The retry settles the work that failed to settle and stops the process.
+ await controller.agent_service.retry_pending()
+ assert controller.session_turns.release_for_backend_refresh.await_count == 2
+ assert agent.shutdown_runtime.await_count == 2
+ await controller.agent_service.retry_pending()
+ assert agent.shutdown_runtime.await_count == 2
+
+ asyncio.run(run())
+
+
+def test_a_cancelled_disable_still_hands_the_process_stop_to_the_teardown_owner():
+ """A requester cancelled while the disable interrupts work never leaves the
+ disabled backend's processes without an owner."""
+
+ async def run() -> None:
+ agent = _DisabledAgent("codex")
+ controller, _auth, coordinator = _disabling_controller(agent)
+ interrupting = asyncio.Event()
+ finish = asyncio.Event()
+
+ async def slow_release(**_kwargs):
+ interrupting.set()
+ await finish.wait()
+ return 0
+
+ controller.session_turns.release_for_backend_refresh = slow_release
+ disabling = asyncio.create_task(coordinator.request_restart("codex", config_save=True))
+ await interrupting.wait()
+ disabling.cancel()
+ await asyncio.sleep(0)
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await disabling
+
+ agent.shutdown_runtime.assert_awaited_once_with(settle_reason="backend_disabled")
+ assert controller.config.codex is None
+
+ asyncio.run(run())
+
+
+def test_runtime_gen_007_re_enabling_starts_a_fresh_agent_at_once(monkeypatch):
+ """RUNTIME-GEN-007: re-enabling registers a new agent without waiting.
+
+ Disabling already stopped the old agent's work, so nothing old remains and
+ the new agent is the backend's only one.
+ """
+ import modules.agents.codex as codex_module
+
+ async def run() -> None:
+ old = _DisabledAgent("codex")
+ controller, auth, coordinator = _disabling_controller(old)
+ await coordinator.request_restart("codex", config_save=True)
+ old.shutdown_runtime.assert_awaited_once_with(settle_reason="backend_disabled")
+
+ runtime_config = SimpleNamespace(enabled=True)
+ auth._load_backend_runtime_config = Mock(return_value=runtime_config)
+ monkeypatch.setattr(
+ codex_module, "CodexAgent", lambda _controller, config: SimpleNamespace(name="codex", config=config)
+ )
+
+ assert await asyncio.wait_for(coordinator.request_restart("codex", config_save=True), timeout=1) == "restarted"
+
+ fresh = controller.agent_service.agents["codex"]
+ assert fresh is not old and fresh.config is runtime_config
+ controller.session_turns.begin_backend_drain.assert_not_called()
+
+ asyncio.run(run())
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index c6588fe36..1a74a36e3 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -7,6 +7,8 @@ from pathlib import Path
from types import SimpleNamespace
from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from modules.agents.base import BaseAgent
@@ -68,6 +70,43 @@ async def test_skill_catalog_is_offered_once_per_accepted_claude_client(monkeypa
await task
[email protected]("disabled_while_connecting", [False, True], ids=["before-admission", "while-connecting"])
+async def test_runtime_gen_006_a_turn_reaching_a_disabled_claude_starts_nothing(monkeypatch, disabled_while_connecting):
+ """RUNTIME-GEN-006 (Claude): Claude stays registered while disabled, so a turn
+ queued behind the one a disable interrupted still reaches it. It must start
+ no client and tell the user Claude was turned off, also when Claude was
+ turned off while the turn's client was connecting."""
+ from core.handlers.session_handler import ClaudeBackendDisabledError
+
+ controller = _StubController()
+ controller.session_handler.get_or_create_claude_session = AsyncMock(
+ side_effect=ClaudeBackendDisabledError("claude backend disabled")
+ )
+ agent = ClaudeAgent(controller)
+ # Turned off while connecting: still enabled when the turn was admitted.
+ agent.config.claude = SimpleNamespace(enabled=disabled_while_connecting)
+ agent._remove_ack_reaction = AsyncMock()
+ failures = []
+
+ async def emit_backend_failure(_controller, _context, backend, _diagnostic, *, display_text=None, **_kwargs):
+ failures.append((backend, display_text))
+ return False
+
+ monkeypatch.setattr("modules.agents.claude_agent.emit_backend_failure", emit_backend_failure)
+ request = SimpleNamespace(
+ context=SimpleNamespace(platform_specific={}), message="queued", base_session_id="ses",
+ composite_session_id="runtime", session_key="scope", subagent_name=None, subagent_model=None,
+ subagent_reasoning_effort=None, ack_message_id=None, ack_reaction_message_id=None,
+ ack_reaction_emoji=None, files=None, working_path="/fixture",
+ )
+
+ await agent.handle_message(request)
+
+ assert controller.session_handler.get_or_create_claude_session.await_count == (1 if disabled_while_connecting else 0)
+ assert len(failures) == 1 and failures[0][0] == "claude"
+ assert "ClaudeCode was turned off" in failures[0][1]
+
+
class _StubSessions:
@staticmethod
def list_agent_sessions(settings_key, agent_name):
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 34177dd14..4b71ce3de 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -8,7 +8,7 @@ import sys
import threading
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import pytest
@@ -597,8 +597,20 @@ def test_cached_claude_rechecks_effective_reasoning_and_preserves_resume(
asyncio.run(run())
-def test_claude_reasoning_change_waits_for_idle_before_recreation(monkeypatch, tmp_path) -> None:
[email protected]("change", ["reasoning_effort", "runtime_renewal", "model_hub_launch", "caller"])
+def test_claude_launch_change_keeps_a_busy_client_until_its_session_is_idle(monkeypatch, tmp_path, change) -> None:
+ """RUNTIME-GEN-001: a launch change never makes a session's turn wait.
+
+ While background work the session started still runs, its next turn stays
+ on the current client, and the first turn after the session is idle gets a
+ new client built from the changed inputs. A turn whose Model Hub launch the
+ current client cannot carry, or that comes from a different caller, replaces
+ it at once and interrupts that work.
+ """
+ from modules.agents.model_hub import ModelHubLaunch
+
clients = []
+ tokens = ["first-launch-token"]
class Client:
def __init__(self, options):
@@ -613,6 +625,15 @@ def test_claude_reasoning_change_waits_for_idle_before_recreation(monkeypatch, t
assert self._vibe_runtime_session_key not in handler.active_sessions
self.disconnected = True
+ class Runtime:
+ async def resolve(self, backend, requested_model, **_kwargs):
+ return ModelHubLaunch(
+ backend=backend, channel="hub", requested_model=requested_model,
+ target_model=requested_model, runtime_model=requested_model,
+ source_id="src_launchfixture", gateway_base_url="http://127.0.0.1:18443/claude",
+ gateway_token=tokens[0], reasoning_efforts=("none", "medium"),
+ )
+
monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", Client)
monkeypatch.setattr(
@@ -620,37 +641,146 @@ def test_claude_reasoning_change_waits_for_idle_before_recreation(monkeypatch, t
lambda *_args: ["none", "medium"],
)
controller = _Controller(tmp_path)
+ controller.model_hub_runtime = Runtime()
+ controller.agent_service = SimpleNamespace(force_end_runtime_activities=Mock())
routing = RoutingSettings(model="claude-opus-4-6", reasoning_effort="none")
controller.settings_manager.get_channel_routing = lambda _key: routing
handler = SessionHandler(controller)
context = MessageContext(user_id="U123", channel_id="C123")
+ callers = [{"AVIBE_CALLER_FIXTURE": "first"}]
+ monkeypatch.setattr(handler, "_caller_env_for_context", lambda _context: dict(callers[0]))
async def run():
first = await handler.get_or_create_claude_session(context)
key = first._vibe_runtime_session_key
handler.active_sessions.add(key)
- routing.reasoning_effort = "medium"
- entered_wait = asyncio.Event()
- wait_for_idle = handler._wait_for_claude_session_idle
-
- async def observe_wait(composite_key):
- entered_wait.set()
- await wait_for_idle(composite_key)
-
- monkeypatch.setattr(handler, "_wait_for_claude_session_idle", observe_wait)
- pending = asyncio.create_task(handler.get_or_create_claude_session(context))
- await asyncio.wait_for(entered_wait.wait(), timeout=1)
- assert not pending.done()
- assert not first.disconnected
+ if change == "reasoning_effort":
+ routing.reasoning_effort = "medium"
+ elif change == "runtime_renewal":
+ handler.renew_runtime()
+ elif change == "caller":
+ callers[0] = {"AVIBE_CALLER_FIXTURE": "second"}
+ else:
+ tokens[0] = "second-launch-token"
+
+ during = await asyncio.wait_for(handler.get_or_create_claude_session(context), timeout=1)
+ if change in {"model_hub_launch", "caller"}:
+ assert during is not first and first.disconnected
+ controller.agent_service.force_end_runtime_activities.assert_called_once_with("claude", key)
+ return
+ assert during is first and not first.disconnected
+ controller.agent_service.force_end_runtime_activities.assert_not_called()
+
handler.active_sessions.remove(key)
- second = await asyncio.wait_for(pending, timeout=1)
- assert first.disconnected
- assert second.options.effort == "medium"
+ after = await asyncio.wait_for(handler.get_or_create_claude_session(context), timeout=1)
+ assert first.disconnected and after is not first
+ if change == "reasoning_effort":
+ assert after.options.effort == "medium"
assert len(clients) == 2
+ assert await handler.get_or_create_claude_session(context) is after
asyncio.run(run())
+def test_a_renewal_during_client_creation_leaves_one_coherent_launch_config(monkeypatch, tmp_path) -> None:
+ """RUNTIME-GEN-001: a client is launched from the config it started with.
+
+ A save that lands while the client is being created changes neither its
+ CLI path nor its epoch midway; the session's next turn moves it.
+ """
+ captured = {}
+
+ class Client:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self):
+ pass
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", Client)
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ build_prompt = handler._build_claude_system_prompt
+
+ async def renew_while_building(*args, **kwargs):
+ controller.config.claude = _ClaudeRuntimeConfig(cli_path="/opt/renewed/claude")
+ handler.renew_runtime()
+ return await build_prompt(*args, **kwargs)
+
+ monkeypatch.setattr(handler, "_build_claude_system_prompt", renew_while_building)
+
+ client = _run_session(handler, MessageContext(user_id="U123", channel_id="C123"))
+
+ assert captured["options"].cli_path == "/usr/local/bin/claude-proxy"
+ assert client._vibe_runtime_epoch == 0
+
+
+def test_a_renewal_during_hub_launch_resolution_leaves_one_coherent_launch_config(monkeypatch, tmp_path) -> None:
+ """RUNTIME-GEN-001: a turn's whole configuration is one load at admission.
+
+ A save and renewal that land while the turn is still resolving its Model Hub
+ launch, before any client exists, change neither the CLI path nor the
+ epoch it launches with; the session's next turn moves it.
+ """
+ from modules.agents import model_hub as model_hub_module
+
+ captured = {}
+
+ class Client:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self):
+ pass
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", Client)
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ resolve = model_hub_module.resolve_model_hub_launch
+
+ async def renew_while_resolving(*args, **kwargs):
+ controller.config.claude = _ClaudeRuntimeConfig(cli_path="/opt/renewed/claude")
+ handler.renew_runtime()
+ return await resolve(*args, **kwargs)
+
+ monkeypatch.setattr(model_hub_module, "resolve_model_hub_launch", renew_while_resolving)
+
+ client = _run_session(handler, MessageContext(user_id="U123", channel_id="C123"))
+
+ assert captured["options"].cli_path == "/usr/local/bin/claude-proxy"
+ assert client._vibe_runtime_epoch == 0
+
+
+def test_a_config_save_that_only_changes_live_fields_renews_no_client() -> None:
+ """RUNTIME-GEN-005: an idle-timeout save keeps every cached client; other changes renew."""
+ from modules.agents.claude_agent import ClaudeAgent
+
+ def agent_with(config):
+ agent = ClaudeAgent.__new__(ClaudeAgent)
+ agent.config = SimpleNamespace(claude=config)
+ agent.controller = SimpleNamespace(config=SimpleNamespace(claude=config), claude_runtime_epoch=0)
+ agent.session_handler = SimpleNamespace(config=None, renew_runtime=Mock())
+ return agent
+
+ base = _ClaudeRuntimeConfig()
+ cases = [
+ (_ClaudeRuntimeConfig(), True, False),
+ (_ClaudeRuntimeConfig(cli_path="/opt/other/claude"), True, True),
+ (_ClaudeRuntimeConfig(), False, True),
+ ]
+ for saved, config_save, renews in cases:
+ saved.idle_timeout_seconds = 60
+ agent = agent_with(base)
+ base.idle_timeout_seconds = 3600
+
+ asyncio.run(agent.renew_runtime(saved, config_save=config_save))
+
+ assert agent.controller.config.claude is saved
+ assert agent.session_handler.renew_runtime.called is renews
+
+
@pytest.mark.parametrize("channel", ["hub", "native_cli"])
@pytest.mark.parametrize("explicit", [None, "", "333333"])
@pytest.mark.parametrize("has_metadata", [False, True])
@@ -2391,6 +2521,241 @@ def test_session_handler_uses_scheduled_turn_source_for_dm_anchor(monkeypatch, t
assert getattr(client, "_vibe_runtime_session_key") == f"{base_session_id}:{tmp_path}"
+def test_runtime_gen_005_a_client_from_before_a_renewal_is_reclaimed_once_idle(monkeypatch, tmp_path: Path) -> None:
+ """RUNTIME-GEN-005: a client from before a renewal stops at the first idle sweep.
+
+ It can never serve another turn, so it is disconnected as soon as a sweep
+ finds it idle, even with idle eviction off. A busy one keeps running.
+ """
+ disconnects: list[str] = []
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ pass
+
+ async def connect(self) -> None:
+ pass
+
+ async def disconnect(self) -> None:
+ disconnects.append("disconnect")
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ controller.runtime_activation = RuntimeActivationRegistry()
+ handler = SessionHandler(controller)
+ _run_session(handler, MessageContext(user_id="U123", channel_id="C123"))
+ composite_key = f"slack_C123:{tmp_path}"
+ handler.session_last_activity[composite_key] = 1000.0
+
+ # Idle eviction is off and the client is current: it stays.
+ assert asyncio.run(handler.evict_idle_sessions(0)) == 0
+
+ handler.renew_runtime()
+ handler.active_sessions.add(composite_key)
+ # Its own background work still runs, so the stale client keeps serving it.
+ assert asyncio.run(handler.evict_idle_sessions(0)) == 0
+ assert disconnects == []
+
+ handler.active_sessions.discard(composite_key)
+ assert asyncio.run(handler.evict_idle_sessions(0)) == 1
+ assert disconnects == ["disconnect"]
+ assert composite_key not in controller.claude_sessions
+
+
+def test_runtime_gen_006_disabling_claude_closes_its_busy_clients_and_only_those(monkeypatch, tmp_path: Path) -> None:
+ """RUNTIME-GEN-006 (Claude): a disable closes every client live at that moment.
+
+ A client still running a turn is closed too, its work settled as disabled.
+ A client created after the capture, such as one of a re-enabled backend, is
+ never touched by a retry.
+ """
+ disconnects: list[str] = []
+ ended: list[tuple[str, str]] = []
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ pass
+
+ async def connect(self) -> None:
+ pass
+
+ async def disconnect(self) -> None:
+ disconnects.append("disconnect")
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ controller = _Controller(tmp_path)
+ controller.runtime_activation = RuntimeActivationRegistry()
+ controller.agent_service = SimpleNamespace(
+ force_end_runtime_activities=lambda backend, key, *, reason: ended.append((key, reason)),
+ )
+ handler = SessionHandler(controller)
+ client = _run_session(handler, MessageContext(user_id="U123", channel_id="C123"))
+ composite_key = f"slack_C123:{tmp_path}"
+ handler.active_sessions.add(composite_key)
+
+ captured = handler.capture_claude_clients()
+ asyncio.run(handler.close_captured_claude_clients(captured, reason="backend_disabled"))
+
+ assert disconnects == ["disconnect"]
+ assert composite_key not in handler.claude_sessions
+ assert ended == [(composite_key, "backend_disabled")]
+
+ fresh = _run_session(handler, MessageContext(user_id="U123", channel_id="C123"))
+ asyncio.run(handler.close_captured_claude_clients(captured, reason="backend_disabled"))
+ assert handler.claude_sessions[composite_key] is fresh is not client
+ assert disconnects == ["disconnect"]
+
+
+def test_runtime_gen_006_a_disabled_claude_client_whose_disconnect_fails_still_exits(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """RUNTIME-GEN-006 (Claude): a captured client counts as closed only once its CLI has exited.
+
+ Its disconnect fails after it left ``claude_sessions``, so the close stops
+ its process directly instead of reporting the backend stopped.
+ """
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ pass
+
+ async def connect(self) -> None:
+ pass
+
+ async def disconnect(self) -> None:
+ raise RuntimeError("transport wedged")
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ controller = _Controller(tmp_path)
+ controller.runtime_activation = RuntimeActivationRegistry()
+ controller.agent_service = SimpleNamespace(force_end_runtime_activities=lambda *_args, **_kwargs: None)
+ handler = SessionHandler(controller)
+ client = _run_session(handler, MessageContext(user_id="U123", channel_id="C123"))
+
+ async def scenario():
+ # A test-owned child stands in for the Claude CLI.
+ process = await asyncio.create_subprocess_exec("sleep", "30")
+ client._transport = SimpleNamespace(_process=process)
+ captured = handler.capture_claude_clients()
+ try:
+ await handler.close_captured_claude_clients(captured, reason="backend_disabled")
+ return process.returncode
+ finally:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+
+ assert asyncio.run(scenario()) is not None
+ assert f"slack_C123:{tmp_path}" not in handler.claude_sessions
+
+
+def test_runtime_gen_006_a_client_connecting_when_claude_is_disabled_never_serves(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """RUNTIME-GEN-006 (Claude): a client still connecting when the disable
+ captured the live clients is not among them. Once connected it finds
+ Claude disabled, stops its CLI, and refuses the turn instead of serving it."""
+ disconnects: list[str] = []
+ connecting = asyncio.Event()
+ finish_connect = asyncio.Event()
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ pass
+
+ async def connect(self) -> None:
+ connecting.set()
+ await finish_connect.wait()
+
+ async def disconnect(self) -> None:
+ disconnects.append("disconnect")
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ controller = _Controller(tmp_path)
+ controller.runtime_activation = RuntimeActivationRegistry()
+ handler = SessionHandler(controller)
+
+ async def scenario():
+ turn = asyncio.create_task(
+ handler.get_or_create_claude_session(MessageContext(user_id="U123", channel_id="C123"))
+ )
+ await asyncio.wait_for(connecting.wait(), 1)
+ # The disable: Claude is turned off, then the live clients are captured.
+ controller.config.claude.enabled = False
+ assert handler.capture_claude_clients() == ()
+ finish_connect.set()
+ with pytest.raises(session_handler_module.ClaudeBackendDisabledError):
+ await turn
+
+ asyncio.run(scenario())
+
+ assert disconnects == ["disconnect"]
+ assert handler.claude_sessions == {}
+
+
+def test_runtime_gen_006_a_turn_cancelled_while_its_client_connects_stops_the_cli(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """RUNTIME-GEN-006 (Claude): a disable cancels a turn whose client is still
+ connecting, and so is not among the clients it captured. The connect's own
+ cleanup can drop the CLI without stopping it, so the turn stops the CLI
+ process it spawned before the cancellation reaches the caller."""
+ started = asyncio.Event()
+ spawned: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self._transport = None
+
+ async def connect(self) -> None:
+ # The CLI spawns, then the handshake waits.
+ self._transport = SimpleNamespace(_process=spawned["process"])
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ except BaseException:
+ # Like the SDK before its query exists: the transport is
+ # dropped without closing the process.
+ self._transport = None
+ raise
+
+ async def disconnect(self) -> None:
+ self._transport = None
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ controller = _Controller(tmp_path)
+ controller.runtime_activation = RuntimeActivationRegistry()
+ handler = SessionHandler(controller)
+
+ async def scenario():
+ # A test-owned child stands in for the Claude CLI.
+ process = await asyncio.create_subprocess_exec("sleep", "30")
+ spawned["process"] = process
+ try:
+ turn = asyncio.create_task(
+ handler.get_or_create_claude_session(MessageContext(user_id="U123", channel_id="C123"))
+ )
+ await asyncio.wait_for(started.wait(), 1)
+ turn.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await turn
+ return process.returncode
+ finally:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+
+ assert asyncio.run(scenario()) is not None
+ assert handler.claude_sessions == {}
+
+
def test_session_handler_evicts_idle_claude_session(monkeypatch, tmp_path: Path) -> None:
captured: dict[str, Any] = {}
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index d0706b91d..f2da6a783 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -21,6 +21,14 @@ from core.runtime_ownership import RuntimeTargetOwnershipSnapshot, SessionRuntim
from modules.agents.base import BaseAgent as RealBaseAgent
from modules.agents.codex.transport import CodexResponseTooLargeError, CodexRPCError
from modules.agents.codex.session import CodexSessionManager as RealCodexSessionManager
+from tests.codex_generation_support import (
+ acquire_returning,
+ bind_installed,
+ codex_transports,
+ init_generation_state,
+ install_codex_transport,
+)
+import modules.agents.runtime_generations # noqa: F401 -- real module before the stubs below
from core.native_dispatch_phase import (
DISPATCH_PHASE_ATTEMPTING,
DISPATCH_PHASE_PREWRITE,
@@ -207,10 +215,10 @@ for name, module in _saved_modules.items():
class CodexExitPressureCacheTests(unittest.TestCase):
def _agent_with_transport(self, transport):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(language="en"))
agent._session_mgr = SimpleNamespace(get_cwd=lambda _base: "/work")
- agent._transports = {"/work": transport}
+ install_codex_transport(agent, "/work", transport, sessions={"one": "t1", "two": "t2"})
return agent
def test_concurrent_sessions_share_positive_exit_observation(self):
@@ -250,8 +258,11 @@ class CodexExitPressureCacheTests(unittest.TestCase):
) as observe:
assert first() is None
assert second() is None
- agent._transports["/work"] = SimpleNamespace(
- _process=SimpleNamespace(returncode=137)
+ install_codex_transport(
+ agent,
+ "/work",
+ SimpleNamespace(_process=SimpleNamespace(returncode=137)),
+ sessions={"three": "t3"},
)
third = agent.capture_backend_exit_failure(
SimpleNamespace(platform_specific={"turn_base_session_id": "three"})
@@ -301,7 +312,7 @@ class _StubTurnRegistry:
class CodexAgentNotificationRoutingTests(unittest.TestCase):
def test_find_request_prefers_turn_mapping_over_replaced_active_request(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = _StubSessionManager()
agent._turn_registry = _StubTurnRegistry()
@@ -316,7 +327,7 @@ class CodexAgentNotificationRoutingTests(unittest.TestCase):
self.assertIs(request, old_request)
def test_find_request_falls_back_to_thread_mapping_without_turn_id(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = _StubSessionManager()
agent._turn_registry = _StubTurnRegistry()
@@ -329,7 +340,7 @@ class CodexAgentNotificationRoutingTests(unittest.TestCase):
self.assertIs(resolved, request)
def test_find_request_does_not_fall_back_to_thread_when_turn_is_unknown(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = _StubSessionManager()
agent._turn_registry = _StubTurnRegistry()
@@ -344,7 +355,7 @@ class CodexAgentNotificationRoutingTests(unittest.TestCase):
self.assertIsNone(resolved)
def test_find_request_bootstraps_pending_turn_start(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = _StubSessionManager()
agent._turn_registry = _StubTurnRegistry()
@@ -360,7 +371,7 @@ class CodexAgentNotificationRoutingTests(unittest.TestCase):
self.assertIs(resolved, request)
def test_find_request_does_not_bootstrap_items_for_pending_turn(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = _StubSessionManager()
agent._turn_registry = _StubTurnRegistry()
@@ -375,33 +386,30 @@ class CodexAgentNotificationRoutingTests(unittest.TestCase):
class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
- def _agent(self, cwd: str, transport):
- agent = object.__new__(CodexAgent)
- agent._transports = {cwd: transport}
- agent._transport_last_activity = {}
+ def _agent(self, cwd: str, transport, *, direct=True):
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._connection_probes = {}
agent._connection_probe_turns = {}
- agent._connection_probe_cwds = {}
- agent.can_reuse_direct_connection_probe = Mock(
- return_value=getattr(transport, "runtime_fingerprint", "direct") == "direct"
- )
- agent._get_or_create_transport = AsyncMock(return_value=transport)
+ self.generation = install_codex_transport(agent, cwd, transport, hub=not direct)
+ agent._direct_probe_generation = Mock(return_value=self.generation if direct else None)
return agent
- def test_live_probe_requires_a_cached_direct_transport_and_existing_cwd(self):
- agent = object.__new__(CodexAgent)
- agent._transports = {}
+ def test_live_probe_requires_a_direct_generation_and_existing_cwd(self):
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent.codex_config = SimpleNamespace(binary="codex-probe-fixture", extra_args=[])
with tempfile.TemporaryDirectory() as cwd:
self.assertFalse(agent.can_reuse_direct_connection_probe(cwd))
+ direct_digest = asyncio.run(agent._launch_spec(cwd)).digest
- direct = SimpleNamespace(runtime_fingerprint="direct")
- agent._transports[cwd] = direct
- self.assertTrue(agent.can_reuse_direct_connection_probe(cwd))
-
- direct.runtime_fingerprint = "hub:openai/gpt-5.4-mini"
+ install_codex_transport(
+ agent, cwd, SimpleNamespace(is_initialized=True), digest="hub-spec", hub=True
+ )
self.assertFalse(agent.can_reuse_direct_connection_probe(cwd))
- direct.runtime_fingerprint = "direct"
+ install_codex_transport(
+ agent, cwd, SimpleNamespace(is_initialized=True), digest=direct_digest
+ )
+ self.assertTrue(agent.can_reuse_direct_connection_probe(cwd))
self.assertFalse(agent.can_reuse_direct_connection_probe(cwd))
async def test_reuses_existing_transport_with_isolated_ephemeral_thread(self):
@@ -441,13 +449,6 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
agent = self._agent(cwd, transport)
diagnostics = []
- async def acquire_transport(_cwd, *, allow_runtime_replacement):
- self.assertEqual(agent._connection_probe_cwds, {})
- self.assertFalse(allow_runtime_replacement)
- return transport
-
- agent._get_or_create_transport = AsyncMock(side_effect=acquire_transport)
-
with patch.object(
_MODULE.paths,
"get_runtime_dir",
@@ -460,10 +461,8 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(result, "hello")
- agent._get_or_create_transport.assert_awaited_once_with(
- cwd,
- allow_runtime_replacement=False,
- )
+ self.assertIs(agent._current_generation(cwd), self.generation)
+ self.assertEqual(self.generation.bindings, 0)
self.assertEqual(requests[0][0], "thread/start")
self.assertEqual(
requests[0][1],
@@ -498,7 +497,6 @@ 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):
@@ -534,7 +532,7 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._connection_probes, {})
self.assertEqual(agent._connection_probe_turns, {})
- self.assertEqual(agent._connection_probe_cwds, {})
+ self.assertEqual(self.generation.bindings, 0)
async def test_cancellation_interrupts_started_probe_and_clears_ownership(self):
cwd = "/tmp/user-project"
@@ -582,7 +580,7 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(agent._connection_probes, {})
self.assertEqual(agent._connection_probe_turns, {})
- self.assertEqual(agent._connection_probe_cwds, {})
+ self.assertEqual(self.generation.bindings, 0)
async def test_retriable_errors_are_preserved_as_diagnostics(self):
cwd = "/tmp/user-project"
@@ -634,46 +632,58 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
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)
+ transport = SimpleNamespace(is_initialized=True)
+ agent = self._agent(cwd, transport, direct=False)
with self.assertRaises(CodexConnectionProbeRuntimeMismatchError):
await agent.probe_connection(cwd, model="gpt-fixture")
- self.assertEqual(agent._connection_probe_cwds, {})
+ self.assertEqual(self.generation.bindings, 0)
- async def test_runtime_fingerprint_race_does_not_replace_model_hub_transport(self):
+ async def test_probe_binds_a_retiring_direct_generation_without_promoting_it(self):
cwd = "/tmp/user-project"
- transport = SimpleNamespace(is_initialized=True, runtime_fingerprint="direct")
- agent = self._agent(cwd, transport)
- agent._get_or_create_transport = AsyncMock(
- side_effect=CodexConnectionProbeRuntimeMismatchError("runtime changed")
- )
+ runtime_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(runtime_dir.cleanup)
- with self.assertRaises(CodexConnectionProbeRuntimeMismatchError):
- await agent.probe_connection(cwd, model="gpt-fixture")
+ class _Transport:
+ is_initialized = True
- agent._get_or_create_transport.assert_awaited_once_with(
- cwd,
- allow_runtime_replacement=False,
- )
- self.assertEqual(agent._connection_probe_cwds, {})
+ async def send_request(inner_self, 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": "hi"}},
+ )
+ 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())
+ direct = self.generation
+ hub = install_codex_transport(agent, cwd, SimpleNamespace(is_initialized=True), digest="hub", hub=True)
+ self.assertTrue(direct.retiring)
+
+ with patch.object(_MODULE.paths, "get_runtime_dir", return_value=Path(runtime_dir.name)):
+ self.assertEqual(await agent.probe_connection(cwd, model="gpt-fixture"), "hi")
+
+ self.assertIs(agent._current_generation(cwd), hub)
+ self.assertTrue(direct.retiring)
+ self.assertEqual(direct.bindings, 0)
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)
+ transport = SimpleNamespace(stop=AsyncMock(), _process=None)
+ agent = init_generation_state(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: [])
@@ -683,10 +693,9 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
runtime_activation=activation,
model_hub_runtime=SimpleNamespace(retire_process_scope=retire_scope),
)
+ generation = install_codex_transport(agent, cwd, transport, hub=True)
- self.assertIsNone(agent._attach_transport_activation(cwd, transport))
- agent._model_hub_catalog_generation = 0
- agent._model_hub_catalog = None
+ self.assertIsNone(agent._attach_runtime_activation(generation.runtime))
await agent.shutdown_runtime()
transport.stop.assert_awaited_once_with()
@@ -696,26 +705,36 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):
class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
- ownership = SimpleNamespace(
+ self.ownership = SimpleNamespace(
disposition="reclaimable",
blocks_reclamation=False,
- )
- patcher = patch.object(
- CodexAgent,
- "_runtime_ownership_snapshot_for_cwd",
- new=lambda _agent, _cwd: ownership,
- )
+ blocks_transport_replacement=False,
+ blocks_dead_transport_replacement=False,
+ )
+ self.snapshot_calls = 0
+ # Holding this gate pauses the given snapshot call, the way a racing
+ # turn could act while ownership is read off the event loop.
+ self.snapshot_gate = None
+ self.gated_call = 2
+
+ async def snapshots(_agent, generations):
+ self.snapshot_calls += 1
+ if self.snapshot_gate is not None and self.snapshot_calls == self.gated_call:
+ await self.snapshot_gate.wait()
+ return tuple(self.ownership for _ in generations)
+
+ patcher = patch.object(CodexAgent, "_ownership_snapshots", new=snapshots)
patcher.start()
self.addCleanup(patcher.stop)
async def test_handle_stop_does_not_hide_turn_before_interrupt_succeeds(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = SimpleNamespace(get_thread_id=lambda base_session_id: "thread-1")
agent._turn_registry = _StubTurnRegistry()
agent._turn_registry._active_turns["session-1"] = "turn-1"
agent._user_stopped_turn_ids = set()
transport = SimpleNamespace(is_alive=True, send_request=AsyncMock(side_effect=RuntimeError("boom")))
- agent._transports = {"/tmp": transport}
+ install_codex_transport(agent, "/tmp", transport, sessions={"session-1": "thread-1"})
agent._event_handler = SimpleNamespace(clear_pending=Mock(return_value=SimpleNamespace()))
agent._remove_ack_reaction = AsyncMock()
agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())
@@ -731,7 +750,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._user_stopped_turn_ids, set())
async def test_handle_stop_hides_turn_after_interrupt_succeeds(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = SimpleNamespace(get_thread_id=lambda base_session_id: "thread-1")
agent._turn_registry = _StubTurnRegistry()
agent._turn_registry._active_turns["session-1"] = "turn-1"
@@ -747,7 +766,12 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
events.append(("clear", turn_id))
return SimpleNamespace()
- agent._transports = {"/tmp": SimpleNamespace(is_alive=True, send_request=send_request)}
+ install_codex_transport(
+ agent,
+ "/tmp",
+ SimpleNamespace(is_alive=True, send_request=send_request),
+ sessions={"session-1": "thread-1"},
+ )
agent._event_handler = SimpleNamespace(clear_pending=clear_pending)
agent._remove_ack_reaction = AsyncMock(
side_effect=lambda request, *, terminal_emoji=None: events.append(("ack", terminal_emoji))
@@ -766,13 +790,40 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(events[2], ("ack", STOPPED_REACTION_EMOJI))
self.assertEqual(agent._user_stopped_turn_ids, set())
+ async def test_handle_stop_uses_the_generation_running_the_turn(self):
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent._session_mgr = SimpleNamespace(get_thread_id=lambda base_session_id: "thread-1")
+ agent._turn_registry = _StubTurnRegistry()
+ agent._turn_registry._active_turns["session-1"] = "turn-1"
+ agent._user_stopped_turn_ids = set()
+ running = SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={}))
+ install_codex_transport(agent, "/tmp", running, sessions={"session-1": "thread-1"})
+ newer = SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={}))
+ install_codex_transport(agent, "/tmp", newer, digest="newer")
+ agent._event_handler = SimpleNamespace(clear_pending=Mock(return_value=SimpleNamespace()))
+ agent._remove_ack_reaction = AsyncMock()
+ agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())
+
+ request = SimpleNamespace(base_session_id="session-1", working_path="/tmp", context=object())
+
+ self.assertTrue(await agent.handle_stop(request))
+ running.send_request.assert_awaited_once_with(
+ "turn/interrupt", {"threadId": "thread-1", "turnId": "turn-1"}
+ )
+ newer.send_request.assert_not_awaited()
+
async def test_handle_stop_does_not_cancel_a_turn_that_completed_during_rpc(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = SimpleNamespace(get_thread_id=lambda base_session_id: "thread-1")
agent._turn_registry = _StubTurnRegistry()
agent._turn_registry._active_turns["session-1"] = "turn-1"
agent._user_stopped_turn_ids = set()
- agent._transports = {"/tmp": SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={}))}
+ install_codex_transport(
+ agent,
+ "/tmp",
+ SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={})),
+ sessions={"session-1": "thread-1"},
+ )
# None with the intent still present means a normal/failed completion
# popped the turn; an interrupted completion would consume the intent.
agent._event_handler = SimpleNamespace(clear_pending=Mock(return_value=None))
@@ -789,7 +840,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._user_stopped_turn_ids, set())
async def test_refresh_auth_state_stops_transports_and_invalidates_threads(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
stop_calls = []
retire_scope = Mock()
@@ -801,10 +852,8 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
invalidated = []
cleared_sessions = []
- agent._transports = {
- "/tmp/a": SimpleNamespace(stop=stop_a),
- "/tmp/b": SimpleNamespace(stop=stop_b),
- }
+ install_codex_transport(agent, "/tmp/a", SimpleNamespace(stop=stop_a), hub=True)
+ install_codex_transport(agent, "/tmp/b", SimpleNamespace(stop=stop_b), hub=True)
agent._session_mgr = SimpleNamespace(
all_base_sessions=lambda: ["session-1", "session-2"],
invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
@@ -826,30 +875,27 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(release_calls, [("codex", {"session-1", "session-2"})])
self.assertEqual(stop_calls, ["a", "b"])
- self.assertEqual(agent._transports, {})
+ self.assertEqual(codex_transports(agent), {})
self.assertEqual(invalidated, ["session-1", "session-2"])
self.assertEqual(cleared_sessions, ["session-1", "session-2"])
self.assertEqual(
retire_scope.call_args_list,
[
- call("codex", "/tmp/a"),
- call("codex", "/tmp/b"),
+ call("codex", agent._hub_process_scope("/tmp/a")),
+ call("codex", agent._hub_process_scope("/tmp/b")),
],
)
async def test_refresh_auth_state_retires_generation_before_transport_stop(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
activation = RuntimeActivationRegistry()
transport = SimpleNamespace()
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 1.0}
agent._session_last_activity = {}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._transport_cwd_inodes = {"/tmp/work": 1}
agent._session_mgr = SimpleNamespace(all_base_sessions=lambda: [])
agent._turn_registry = SimpleNamespace()
agent.controller = SimpleNamespace(runtime_activation=activation)
- identity = agent._attach_transport_activation("/tmp/work", transport)
+ identity = activation.attach("codex", "/tmp/work#1")
+ install_codex_transport(agent, "/tmp/work", transport, activation=identity)
late_commit = Mock(return_value="started")
async def stop_transport():
@@ -861,59 +907,36 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
await agent.refresh_auth_state()
late_commit.assert_not_called()
- self.assertNotIn("/tmp/work", agent._transports)
- self.assertIsNone(activation.current("codex", "/tmp/work"))
-
- async def test_prepare_resume_binding_restarts_unshared_transport(self):
- agent = object.__new__(CodexAgent)
- stop_calls = []
- retire_scope = Mock()
-
- async def stop_transport():
- stop_calls.append("stop")
+ self.assertEqual(codex_transports(agent), {})
+ self.assertIsNone(activation.current("codex", "/tmp/work#1"))
- transport = SimpleNamespace(stop=stop_transport)
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 1.0}
- invalidated = []
- cleared_sessions = []
+ def _resume_agent(self, transport, *, sessions):
+ agent = init_generation_state(object.__new__(CodexAgent))
+ self.invalidated = []
+ self.cleared_sessions = []
+ self.retire_scope = Mock()
agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
+ sessions_for_cwd=lambda cwd: list(sessions) if cwd == "/tmp/work" else [],
+ get_thread_id=lambda base_session_id: sessions.get(base_session_id),
+ invalidate_thread=lambda base_session_id: self.invalidated.append(base_session_id),
)
- agent._turn_registry = SimpleNamespace(clear_session=lambda base_session_id: cleared_sessions.append(base_session_id))
- agent.controller = SimpleNamespace(
- model_hub_runtime=SimpleNamespace(
- retire_process_scope=retire_scope,
- )
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=lambda base_session_id: None,
+ clear_session=lambda base_session_id: self.cleared_sessions.append(base_session_id),
)
-
- await agent.prepare_resume_binding(
- base_session_id="session-1",
- session_key="scope-1",
- working_path="/tmp/work",
+ agent.controller = SimpleNamespace(
+ model_hub_runtime=SimpleNamespace(retire_process_scope=self.retire_scope)
)
+ self.generation = install_codex_transport(agent, "/tmp/work", transport, sessions=sessions)
+ return agent
- self.assertEqual(stop_calls, ["stop"])
- self.assertEqual(agent._transports, {})
- self.assertEqual(agent._transport_last_activity, {})
- self.assertEqual(invalidated, ["session-1"])
- self.assertEqual(cleared_sessions, ["session-1"])
- retire_scope.assert_called_once_with("codex", "/tmp/work")
-
- async def test_prepare_resume_binding_skips_shared_transport(self):
- agent = object.__new__(CodexAgent)
- stop_transport = AsyncMock()
- transport = SimpleNamespace(stop=stop_transport)
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 1.0}
- invalidated = []
- cleared_sessions = []
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1", "session-2"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
+ async def test_prepare_resume_binding_releases_only_the_sessions_thread(self):
+ transport = SimpleNamespace(
+ is_alive=True,
+ stop=AsyncMock(),
+ send_request=AsyncMock(return_value={"status": "notLoaded"}),
)
- agent._turn_registry = SimpleNamespace(clear_session=lambda base_session_id: cleared_sessions.append(base_session_id))
+ agent = self._resume_agent(transport, sessions={"session-1": "thread-1", "session-2": "thread-2"})
await agent.prepare_resume_binding(
base_session_id="session-1",
@@ -921,66 +944,100 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
working_path="/tmp/work",
)
- stop_transport.assert_not_awaited()
- self.assertIs(agent._transports["/tmp/work"], transport)
- self.assertEqual(agent._transport_last_activity, {"/tmp/work": 1.0})
- self.assertEqual(invalidated, [])
- self.assertEqual(cleared_sessions, [])
-
- async def test_prepare_resume_binding_retains_generation_when_stop_fails(self):
- agent = object.__new__(CodexAgent)
- activation = RuntimeActivationRegistry()
- transport = SimpleNamespace()
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 1.0}
- agent._transport_cwd_inodes = {"/tmp/work": 1}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- invalidated = []
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
- )
- agent._turn_registry = SimpleNamespace(clear_session=Mock())
- agent.controller = SimpleNamespace(runtime_activation=activation)
- identity = agent._attach_transport_activation("/tmp/work", transport)
- late_commit = Mock(return_value="started")
+ transport.send_request.assert_awaited_once_with("thread/unsubscribe", {"threadId": "thread-1"})
+ transport.stop.assert_not_awaited()
+ self.assertIs(codex_transports(agent)["/tmp/work"], transport)
+ self.assertIsNone(agent.transport_for_session("session-1"))
+ self.assertIs(agent.transport_for_session("session-2"), transport)
+ self.assertEqual(self.invalidated, ["session-1"])
+ self.assertEqual(self.cleared_sessions, ["session-1"])
+ self.retire_scope.assert_not_called()
+
+ async def test_resume_and_clear_wait_out_a_turn_admission_for_the_session(self):
+ """Neither unloads a Session's thread while a turn for it is being admitted."""
+ for operation in ("resume", "clear"):
+ with self.subTest(operation=operation):
+ agent = init_generation_state(object.__new__(CodexAgent))
+ unsubscribed = asyncio.Event()
+ unload = asyncio.Event()
- async def stop_transport():
- self.assertFalse(
- activation.commit_if_current(identity, late_commit).admitted
- )
- raise RuntimeError("stop failed")
+ async def send_request(method, params):
+ unsubscribed.set()
+ await unload.wait()
+ return {"status": "notLoaded"}
+
+ transport = SimpleNamespace(is_alive=True, _process=None, send_request=send_request, stop=AsyncMock())
+ session_mgr = RealCodexSessionManager()
+ session_mgr.set_session_key("session-1", "key-a")
+ session_mgr.set_cwd("session-1", "/tmp/work")
+ session_mgr.set_thread_id("session-1", "thread-1")
+ agent._session_mgr = session_mgr
+ agent.sessions = SimpleNamespace(clear_agent_sessions=Mock())
+ agent._turn_registry = SimpleNamespace(get_active_turn=lambda _base: None, clear_session=Mock())
+ install_codex_transport(
+ agent, "/tmp/work", transport, sessions={"session-1": "thread-1", "session-2": "thread-2"}
+ )
+ order = []
- transport.stop = stop_transport
+ async def admit_turn():
+ # Turn admission serializes on the Session's registered lock.
+ async with agent._session_locks.setdefault("session-1", asyncio.Lock()):
+ order.append("admitted")
- await agent.prepare_resume_binding(
- base_session_id="session-1",
- session_key="scope-1",
- working_path="/tmp/work",
+ if operation == "resume":
+ pending = asyncio.create_task(
+ agent.prepare_resume_binding(
+ base_session_id="session-1", session_key="key-a", working_path="/tmp/work"
+ )
+ )
+ else:
+ pending = asyncio.create_task(agent.clear_sessions("key-a"))
+ await asyncio.wait_for(unsubscribed.wait(), 1)
+ admission = asyncio.create_task(admit_turn())
+ await asyncio.sleep(0.01)
+ order.append("released")
+ unload.set()
+ await pending
+ await admission
+
+ self.assertEqual(order, ["released", "admitted"])
+
+ async def test_prepare_resume_binding_aborts_the_resume_when_the_thread_stays_loaded(self):
+ transport = SimpleNamespace(
+ is_alive=True,
+ stop=AsyncMock(),
+ send_request=AsyncMock(
+ side_effect=CodexRPCError({"code": -32603, "message": "unsubscribe failed"})
+ ),
)
+ agent = self._resume_agent(transport, sessions={"session-1": "thread-1"})
- late_commit.assert_not_called()
- self.assertIs(agent._transports["/tmp/work"], transport)
- self.assertEqual(invalidated, [])
- self.assertIs(activation.current("codex", "/tmp/work"), identity)
- self.assertTrue(activation.commit_if_current(identity, late_commit).admitted)
- late_commit.assert_called_once_with()
+ # The resume must fail before its mapping changes, or the next turn
+ # would still reach the old thread.
+ with self.assertRaises(_MODULE.CodexThreadReleaseUnavailableError):
+ await agent.prepare_resume_binding(
+ base_session_id="session-1",
+ session_key="scope-1",
+ working_path="/tmp/work",
+ )
+
+ self.assertIs(agent.transport_for_session("session-1"), transport)
+ self.assertEqual(self.invalidated, [])
+ self.assertEqual(self.cleared_sessions, [])
+ transport.stop.assert_not_awaited()
async def test_shutdown_runtime_retires_generation_before_transport_stop(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
activation = RuntimeActivationRegistry()
transport = SimpleNamespace()
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 1.0}
agent._session_last_activity = {}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._transport_cwd_inodes = {"/tmp/work": 1}
agent._session_locks = {}
agent._session_mgr = SimpleNamespace(all_base_sessions=lambda: [])
agent._turn_registry = SimpleNamespace()
agent.sessions = SimpleNamespace()
agent.controller = SimpleNamespace(runtime_activation=activation)
- identity = agent._attach_transport_activation("/tmp/work", transport)
+ identity = activation.attach("codex", "/tmp/work#1")
+ install_codex_transport(agent, "/tmp/work", transport, activation=identity)
late_commit = Mock(return_value="started")
async def stop_transport():
@@ -990,19 +1047,289 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
transport.stop = stop_transport
- agent._model_hub_catalog_generation = 0
- agent._model_hub_catalog = None
await agent.shutdown_runtime()
late_commit.assert_not_called()
- self.assertNotIn("/tmp/work", agent._transports)
- self.assertIsNone(activation.current("codex", "/tmp/work"))
+ self.assertEqual(codex_transports(agent), {})
+ self.assertIsNone(activation.current("codex", "/tmp/work#1"))
+
+ async def test_shutdown_runtime_ends_busy_generations_without_the_update_notice(self):
+ agent = init_generation_state(object.__new__(CodexAgent))
+ transport = SimpleNamespace(stop=AsyncMock())
+ agent._session_locks = {}
+ agent._session_mgr = SimpleNamespace(all_base_sessions=lambda: [])
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=lambda base_session_id: "turn-1",
+ clear_session=Mock(),
+ )
+ agent.sessions = SimpleNamespace()
+ agent.controller = SimpleNamespace(
+ agent_service=SimpleNamespace(force_end_runtime_work=AsyncMock())
+ )
+ install_codex_transport(agent, "/tmp/work", transport, sessions={"session-1": "thread-1"})
+
+ await agent.shutdown_runtime()
+
+ transport.stop.assert_awaited_once_with()
+ agent.controller.agent_service.force_end_runtime_work.assert_not_awaited()
+
+ async def test_refresh_keeps_sessions_bound_to_a_process_that_failed_to_stop(self):
+ """A surviving process still holds its threads, so its Sessions stay bound to it."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ transport = SimpleNamespace(stop=AsyncMock(side_effect=RuntimeError("stop failed")), _process=None)
+ invalidated = []
+ agent._session_mgr = SimpleNamespace(
+ all_base_sessions=lambda: ["session-1", "session-2"],
+ invalidate_thread=invalidated.append,
+ )
+ agent._turn_registry = SimpleNamespace(clear_session=Mock())
+ agent.controller = SimpleNamespace()
+ install_codex_transport(
+ agent, "/tmp/work", transport, sessions={"session-1": "thread-1", "session-2": "thread-2"}
+ )
+
+ await agent.refresh_auth_state()
+
+ self.assertIs(agent.transport_for_session("session-1"), transport)
+ self.assertIs(agent.transport_for_session("session-2"), transport)
+ self.assertEqual(invalidated, [])
+
+ async def test_clearing_a_session_releases_its_thread_on_a_shared_app_server(self):
+ """A cleared conversation must not leave its thread loaded in a shared process."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ sent = []
+
+ async def send_request(method, params):
+ sent.append((method, params))
+ return {"status": "notLoaded"}
+
+ transport = SimpleNamespace(is_alive=True, send_request=send_request, stop=AsyncMock())
+ session_mgr = RealCodexSessionManager()
+ for base, key in (("session-1", "key-a"), ("session-2", "key-b")):
+ session_mgr.set_session_key(base, key)
+ session_mgr.set_cwd(base, "/tmp/work")
+ session_mgr.set_thread_id(base, f"thread-{base}")
+ agent._session_mgr = session_mgr
+ agent.sessions = SimpleNamespace(clear_agent_sessions=Mock())
+ agent._turn_registry = SimpleNamespace(get_active_turn=lambda _base: None, clear_session=Mock())
+ agent._session_locks = {}
+ install_codex_transport(
+ agent,
+ "/tmp/work",
+ transport,
+ sessions={"session-1": "thread-session-1", "session-2": "thread-session-2"},
+ )
+
+ await agent.clear_sessions("key-a")
+
+ self.assertEqual(sent, [("thread/unsubscribe", {"threadId": "thread-session-1"})])
+ self.assertIsNone(agent.transport_for_session("session-1"))
+ self.assertIs(agent.transport_for_session("session-2"), transport)
+ transport.stop.assert_not_awaited()
+
+ async def test_clearing_a_session_keeps_it_when_its_thread_stays_loaded(self):
+ """A failed release fails the clear before anything is forgotten, so it can be retried."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ transport = SimpleNamespace(
+ is_alive=True,
+ send_request=AsyncMock(side_effect=CodexRPCError({"code": -32603, "message": "unsubscribe failed"})),
+ stop=AsyncMock(),
+ )
+ session_mgr = RealCodexSessionManager()
+ session_mgr.set_session_key("session-1", "key-a")
+ session_mgr.set_cwd("session-1", "/tmp/work")
+ session_mgr.set_thread_id("session-1", "thread-session-1")
+ agent._session_mgr = session_mgr
+ agent.sessions = SimpleNamespace(clear_agent_sessions=Mock())
+ agent._turn_registry = SimpleNamespace(get_active_turn=lambda _base: None, clear_session=Mock())
+ install_codex_transport(agent, "/tmp/work", transport, sessions={"session-1": "thread-session-1"})
+
+ with self.assertRaises(_MODULE.CodexThreadReleaseUnavailableError):
+ await agent.clear_sessions("key-a")
+
+ agent.sessions.clear_agent_sessions.assert_not_called()
+ self.assertEqual(session_mgr.get_thread_id("session-1"), "thread-session-1")
+ self.assertEqual(session_mgr.get_sessions_by_session_key("key-a"), ["session-1"])
+ self.assertIs(agent.transport_for_session("session-1"), transport)
+
+ async def test_forced_stop_fences_owner_commits_before_settling(self):
+ """No durable owner can commit to a generation while its forced stop settles work."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ activation = RuntimeActivationRegistry()
+ identity = activation.attach("codex", "/tmp/work#1")
+ transport = SimpleNamespace(stop=AsyncMock(), _process=None)
+ agent._session_mgr = SimpleNamespace(invalidate_thread=Mock())
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=Mock(return_value="turn-1"), get_request_for_turn=Mock(return_value=None), clear_session=Mock()
+ )
+ commits = []
+
+ async def settle(*_args, **_kwargs):
+ # A queued turn tries to register its owner while the work settles.
+ commits.append(activation.commit_if_current(identity, lambda: "owner").admitted)
+
+ agent.controller = SimpleNamespace(
+ runtime_activation=activation,
+ agent_service=SimpleNamespace(force_end_runtime_work=AsyncMock(side_effect=settle)),
+ )
+ generation = install_codex_transport(
+ agent, "/tmp/work", transport, sessions={"session-1": "thread-1"}, activation=identity
+ )
+
+ self.assertTrue(await agent._stop_generation(generation, True))
+
+ self.assertEqual(commits, [False])
+ transport.stop.assert_awaited_once_with()
+
+ async def test_a_graceful_stop_waits_for_an_activity_its_sessions_no_longer_name(self):
+ """The Session moved its thread to a newer process, but an Activity it
+ started here still runs: the old process stays until that Activity ends."""
+ from core.session_activities import SessionActivityRegistry
+ from modules.agents.service import AgentService
+
+ activation = RuntimeActivationRegistry()
+ service = AgentService(
+ controller=SimpleNamespace(),
+ activities=SessionActivityRegistry(activation_registry=activation),
+ activation_registry=activation,
+ )
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent._session_mgr = SimpleNamespace(invalidate_thread=Mock())
+ agent._turn_registry = SimpleNamespace(get_active_turn=Mock(return_value=None), clear_session=Mock())
+ agent.controller = SimpleNamespace(runtime_activation=activation, agent_service=service)
+ identity = activation.attach("codex", "/tmp/work#1")
+ transport = SimpleNamespace(stop=AsyncMock(), is_alive=True, _process=None)
+ generation = install_codex_transport(agent, "/tmp/work", transport, activation=identity)
+ service.activities.start(
+ backend="codex",
+ runtime_key="session-1:/tmp/work",
+ session_id="ses-1",
+ activity_id="task-1",
+ kind="task",
+ activation_identity=identity,
+ )
+
+ async def drained(_agent, generations):
+ # No Session binding names the Activity any longer.
+ return tuple(SimpleNamespace(blocks_transport_replacement=False) for _ in generations)
+
+ with patch.object(CodexAgent, "_ownership_snapshots", new=drained):
+ self.assertFalse(await agent._stop_generation(generation, False))
+ transport.stop.assert_not_awaited()
+ service.activities.complete(
+ backend="codex",
+ runtime_key="session-1:/tmp/work",
+ activity_id="task-1",
+ status="completed",
+ activation_identity=identity,
+ )
+ self.assertTrue(await agent._stop_generation(generation, False))
+
+ transport.stop.assert_awaited_once_with()
+
+ async def test_graceful_stop_rechecks_ownership_inside_the_fence(self):
+ """An owner that commits after the drained check keeps its process."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ activation = RuntimeActivationRegistry()
+ identity = activation.attach("codex", "/tmp/work#1")
+ transport = SimpleNamespace(stop=AsyncMock(), is_alive=True, _process=None)
+ agent._session_mgr = SimpleNamespace(invalidate_thread=Mock())
+ agent._turn_registry = SimpleNamespace(get_active_turn=Mock(return_value=None), clear_session=Mock())
+ agent.controller = SimpleNamespace(runtime_activation=activation)
+ generation = install_codex_transport(
+ agent, "/tmp/work", transport, sessions={"session-1": "thread-1"}, activation=identity
+ )
+ drained = SimpleNamespace(blocks_transport_replacement=False)
+ # An Activity commits right after the first, drained snapshot.
+ owned = SimpleNamespace(blocks_transport_replacement=True)
+ snapshots = iter([drained, owned])
+
+ async def snapshot(_agent, generations):
+ return (next(snapshots),)
+
+ with patch.object(CodexAgent, "_ownership_snapshots", new=snapshot):
+ self.assertFalse(await agent._stop_generation(generation, False))
+
+ transport.stop.assert_not_awaited()
+ # The aborted reservation leaves the generation admitting owners.
+ self.assertTrue(activation.commit_if_current(identity, lambda: "owner").admitted)
+
+ async def test_last_session_end_settles_activity_owners_before_the_kill(self):
+ """End kills the process only after the ending Session's Activities settle."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ events = []
+ activation = object()
+
+ async def stop():
+ events.append("stop")
+
+ async def end_work(backend, *, base_session_ids, activation_identities, reason, agent):
+ events.append(("settle", backend, set(base_session_ids), activation_identities, reason))
+
+ transport = SimpleNamespace(stop=stop, _process=None)
+ agent._session_mgr = SimpleNamespace(invalidate_thread=Mock(), clear=Mock())
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=lambda _base: None,
+ has_pending_turn_start=lambda _base: False,
+ clear_session=Mock(),
+ )
+ agent.controller = SimpleNamespace(agent_service=SimpleNamespace(force_end_runtime_work=end_work))
+ install_codex_transport(
+ agent, "/tmp/work", transport, sessions={"session-1": "thread-1"}, activation=activation
+ )
+
+ self.assertTrue((await agent.end_session("session-1"))["process_killed"])
+
+ self.assertEqual(
+ events,
+ [("settle", "codex", set(), {activation}, "stopped"), "stop"],
+ )
+
+ async def test_a_forced_stop_settles_activities_its_sessions_no_longer_name(self):
+ """An Activity outlives its turn and its Session's thread move; a forced stop still ends it.
+
+ The process's Activities are found by its activation, not by the
+ Sessions still bound to it.
+ """
+ from core.session_activities import SessionActivityRegistry
+ from modules.agents.service import AgentService
+
+ activation = RuntimeActivationRegistry()
+ service = AgentService(
+ controller=SimpleNamespace(),
+ activities=SessionActivityRegistry(activation_registry=activation),
+ activation_registry=activation,
+ )
+ settled = []
+ service.on_activity_terminal = settled.append
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent._session_mgr = SimpleNamespace(invalidate_thread=Mock())
+ agent._turn_registry = SimpleNamespace(get_active_turn=Mock(return_value=None), clear_session=Mock())
+ agent.controller = SimpleNamespace(agent_service=service)
+ identity = activation.attach("codex", "/tmp/work#1")
+ transport = SimpleNamespace(stop=AsyncMock(), _process=None)
+ # The Session's thread already moved to a newer process: none is bound here.
+ generation = install_codex_transport(agent, "/tmp/work", transport, activation=identity)
+ service.activities.start(
+ backend="codex",
+ runtime_key="session-1:/tmp/work",
+ session_id="ses-1",
+ activity_id="task-1",
+ kind="task",
+ activation_identity=identity,
+ )
+
+ self.assertTrue(await agent._stop_generation(generation, True))
+
+ self.assertEqual(
+ [(activity.id, activity.status, activity.metadata.get("interrupt_reason")) for activity in settled],
+ [("task-1", "killed", "backend_refresh")],
+ )
+ transport.stop.assert_awaited_once_with()
def test_request_activation_resolves_one_live_session_key_transport(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
activation = RuntimeActivationRegistry()
- live = SimpleNamespace()
- agent._transports = {"/tmp/live": live}
agent._session_mgr = SimpleNamespace(
get_sessions_by_session_key=lambda session_key: ["base-dead", "base-live"],
get_cwd=lambda base_session_id: {
@@ -1011,7 +1338,8 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
}[base_session_id],
)
agent.controller = SimpleNamespace(runtime_activation=activation)
- identity = agent._attach_transport_activation("/tmp/live", live)
+ identity = activation.attach("codex", "/tmp/live#1")
+ install_codex_transport(agent, "/tmp/live", SimpleNamespace(), activation=identity)
resolved = agent.runtime_activation_identity_for_request(
SimpleNamespace(working_path=None, metadata={}, session_key="route:base")
@@ -1019,12 +1347,39 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(resolved, identity)
+ def test_request_activation_prefers_the_generation_holding_the_session(self):
+ agent = init_generation_state(object.__new__(CodexAgent))
+ activation = RuntimeActivationRegistry()
+ agent._session_mgr = SimpleNamespace(get_cwd=lambda base_session_id: "/tmp/work")
+ running = activation.attach("codex", "/tmp/work#1")
+ install_codex_transport(
+ agent, "/tmp/work", SimpleNamespace(), activation=running, sessions={"base-1": "thread-1"}
+ )
+ newer = activation.attach("codex", "/tmp/work#2")
+ install_codex_transport(agent, "/tmp/work", SimpleNamespace(), activation=newer, digest="newer")
+
+ self.assertIs(
+ agent.runtime_activation_identity_for_request(
+ SimpleNamespace(base_session_id="base-1", working_path="/tmp/work")
+ ),
+ running,
+ )
+ self.assertIs(
+ agent.runtime_activation_identity_for_request(
+ SimpleNamespace(base_session_id="base-2", working_path="/tmp/work")
+ ),
+ newer,
+ )
+ self.assertIs(
+ agent.runtime_activation_identity_for_session_binding(
+ session_anchor="base-1", workdir="/tmp/work"
+ ),
+ running,
+ )
+
def test_request_activation_fails_closed_for_multiple_live_session_key_transports(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
activation = RuntimeActivationRegistry()
- first = SimpleNamespace()
- second = SimpleNamespace()
- agent._transports = {"/tmp/a": first, "/tmp/b": second}
agent._session_mgr = SimpleNamespace(
get_sessions_by_session_key=lambda session_key: ["base-a", "base-b"],
get_cwd=lambda base_session_id: {
@@ -1033,8 +1388,8 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
}[base_session_id],
)
agent.controller = SimpleNamespace(runtime_activation=activation)
- agent._attach_transport_activation("/tmp/a", first)
- agent._attach_transport_activation("/tmp/b", second)
+ install_codex_transport(agent, "/tmp/a", SimpleNamespace(), activation=activation.attach("codex", "/tmp/a#1"))
+ install_codex_transport(agent, "/tmp/b", SimpleNamespace(), activation=activation.attach("codex", "/tmp/b#1"))
with self.assertRaisesRegex(ValueError, "multiple live Codex runtime"):
agent.runtime_activation_identity_for_request(
@@ -1042,8 +1397,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
)
def test_request_activation_returns_none_when_session_key_has_no_live_transport(self):
- agent = object.__new__(CodexAgent)
- agent._transports = {}
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = SimpleNamespace(
get_sessions_by_session_key=lambda session_key: ["base-dead"],
get_cwd=lambda base_session_id: "/tmp/dead",
@@ -1055,260 +1409,174 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(resolved)
- async def test_evict_idle_transports_stops_idle_codex_runtime(self):
- agent = object.__new__(CodexAgent)
- stop_calls = []
- invalidated_sessions = []
- cleared_turns = []
- retire_scope = Mock()
+ def _evict_agent(self, transport, *, active_turn=None, pending=False, last_activity=0.0):
+ """Build a bare CodexAgent wired for evict_idle_transports tests."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ self.invalidated = []
+ self.cleared_turns = []
+ self.retire_scope = Mock()
+ active_turns = {"session-1": active_turn}
+ request = SimpleNamespace(context="ctx-1", base_session_id="session-1")
- async def stop_transport():
- stop_calls.append("stop")
+ def clear_session(base_session_id):
+ self.cleared_turns.append(base_session_id)
+ active_turns[base_session_id] = None
- transport = SimpleNamespace(stop=stop_transport)
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 0.0}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
+ agent._session_last_activity = {"session-1": last_activity}
agent._session_mgr = SimpleNamespace(
sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: invalidated_sessions.append(base_session_id),
+ invalidate_thread=lambda base_session_id: self.invalidated.append(base_session_id),
)
agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: None,
- clear_session=lambda base_session_id: cleared_turns.append(base_session_id),
+ get_active_turn=lambda base_session_id: active_turns.get(base_session_id),
+ has_pending_turn_start=lambda base_session_id: pending,
+ get_request_for_turn=lambda turn_id: request if turn_id == active_turn else None,
+ get_latest_request=lambda base_session_id: request,
+ clear_session=clear_session,
+ )
+ self.release_calls = []
+ agent._event_handler = SimpleNamespace(
+ _release_stream_turn=lambda context: self.release_calls.append(context),
)
agent._session_locks = {"session-1": asyncio.Lock()}
agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
- activation = RuntimeActivationRegistry()
+ self.activation = RuntimeActivationRegistry()
+ self.identity = self.activation.attach("codex", "/tmp/work#1")
agent.controller = SimpleNamespace(
- runtime_activation=activation,
- model_hub_runtime=SimpleNamespace(
- retire_process_scope=retire_scope,
- )
+ runtime_activation=self.activation,
+ emit_agent_message=AsyncMock(),
+ model_hub_runtime=SimpleNamespace(retire_process_scope=self.retire_scope),
)
- identity = agent._attach_transport_activation("/tmp/work", transport)
+ self.generation = install_codex_transport(
+ agent,
+ "/tmp/work",
+ transport,
+ sessions={"session-1": "thread-1"},
+ activation=self.identity,
+ hub=True,
+ last_activity=last_activity,
+ )
+ return agent
+
+ def _stopping_transport(self):
+ self.stop_calls = []
+
+ async def stop_transport():
+ self.stop_calls.append("stop")
+
+ return SimpleNamespace(stop=stop_transport)
+
+ async def test_evict_idle_transports_stops_idle_codex_runtime(self):
+ agent = self._evict_agent(self._stopping_transport())
with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 1)
- self.assertEqual(stop_calls, ["stop"])
- self.assertEqual(invalidated_sessions, ["session-1"])
- self.assertEqual(cleared_turns, ["session-1"])
+ self.assertEqual(self.stop_calls, ["stop"])
+ self.assertEqual(self.invalidated, ["session-1"])
+ self.assertEqual(self.cleared_turns, ["session-1"])
agent.sessions.clear_agent_session_mapping.assert_not_called()
- self.assertEqual(agent._transports, {})
- self.assertIn("/tmp/work", agent._transport_locks)
- self.assertIsNone(activation.current("codex", "/tmp/work"))
+ self.assertEqual(codex_transports(agent), {})
+ self.assertIsNone(self.activation.current("codex", "/tmp/work#1"))
self.assertEqual(
- activation.current("codex", "/tmp/work", include_retired=True),
- identity,
+ self.activation.current("codex", "/tmp/work#1", include_retired=True),
+ self.identity,
)
- self.assertEqual(agent._transport_last_activity, {})
- retire_scope.assert_called_once_with("codex", "/tmp/work")
+ self.assertNotIn("session-1", agent._session_locks)
+ self.retire_scope.assert_called_once_with("codex", agent._hub_process_scope("/tmp/work"))
async def test_evict_idle_transports_keeps_active_codex_runtime(self):
- agent = object.__new__(CodexAgent)
-
- async def stop_transport():
- raise AssertionError("active transport should not be stopped")
-
- agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}
- agent._transport_last_activity = {"/tmp/work": 0.0}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: None,
- )
- agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: "turn-1",
- clear_session=lambda base_session_id: None,
- )
- agent._session_locks = {"session-1": asyncio.Lock()}
- agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
+ transport = SimpleNamespace(stop=AsyncMock(side_effect=AssertionError("active transport should not be stopped")))
+ agent = self._evict_agent(transport, active_turn="turn-1", last_activity=500.0)
- with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
+ with patch.object(_MODULE.time, "monotonic", return_value=1200.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 0)
- self.assertIn("/tmp/work", agent._transports)
+ self.assertIs(codex_transports(agent)["/tmp/work"], transport)
agent.sessions.clear_agent_session_mapping.assert_not_called()
async def test_evict_idle_transports_keeps_pending_turn_start_runtime(self):
- agent = object.__new__(CodexAgent)
+ transport = SimpleNamespace(stop=AsyncMock(side_effect=AssertionError("pending start should not be stopped")))
+ agent = self._evict_agent(transport, pending=True)
- async def stop_transport():
- raise AssertionError("pending turn-start transport should not be stopped")
+ with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
+ evicted = await agent.evict_idle_transports(600)
- agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}
- agent._transport_last_activity = {"/tmp/work": 0.0}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: None,
- )
- agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: None,
- has_pending_turn_start=lambda base_session_id: True,
- clear_session=lambda base_session_id: None,
- )
- agent._session_locks = {"session-1": asyncio.Lock()}
- agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
+ self.assertEqual(evicted, 0)
+ self.assertIs(codex_transports(agent)["/tmp/work"], transport)
+
+ async def test_evict_idle_transports_keeps_a_generation_a_turn_is_binding(self):
+ transport = self._stopping_transport()
+ agent = self._evict_agent(transport)
+ binding = bind_installed(agent, self.generation)
with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 0)
- self.assertIn("/tmp/work", agent._transports)
- agent.sessions.clear_agent_session_mapping.assert_not_called()
+ self.assertEqual(self.stop_calls, [])
+ await binding.release()
async def test_evict_idle_transports_retains_generation_when_stop_fails(self):
- agent = object.__new__(CodexAgent)
- invalidated_sessions = []
- cleared_turns = []
-
- async def stop_transport():
- raise RuntimeError("boom")
-
- transport = SimpleNamespace(stop=stop_transport)
- lock = asyncio.Lock()
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 0.0}
- agent._transport_locks = {"/tmp/work": lock}
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: invalidated_sessions.append(base_session_id),
- )
- agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: None,
- has_pending_turn_start=lambda base_session_id: False,
- clear_session=lambda base_session_id: cleared_turns.append(base_session_id),
- )
- agent._session_locks = {"session-1": asyncio.Lock()}
- agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
+ transport = SimpleNamespace(stop=AsyncMock(side_effect=RuntimeError("boom")))
+ agent = self._evict_agent(transport)
with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 0)
- self.assertIs(agent._transports["/tmp/work"], transport)
- self.assertIs(agent._transport_locks["/tmp/work"], lock)
- self.assertEqual(agent._transport_last_activity["/tmp/work"], 0.0)
- self.assertEqual(invalidated_sessions, [])
- self.assertEqual(cleared_turns, [])
+ # The generation stays for the next sweep and keeps its Session bound.
+ self.assertIn(self.generation, agent._units["/tmp/work"].generations)
+ self.assertIs(agent.transport_for_session("session-1"), transport)
+ self.assertEqual(self.invalidated, [])
+ self.assertEqual(self.cleared_turns, [])
+ self.retire_scope.assert_not_called()
agent.sessions.clear_agent_session_mapping.assert_not_called()
async def test_evict_idle_transports_revalidates_activity_before_stop(self):
- agent = object.__new__(CodexAgent)
- stop_calls = []
-
- async def stop_transport():
- stop_calls.append("stop")
-
- lock = asyncio.Lock()
- await lock.acquire()
- agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}
- agent._transport_last_activity = {"/tmp/work": 0.0}
- agent._transport_locks = {"/tmp/work": lock}
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: None,
- )
- agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: None,
- has_pending_turn_start=lambda base_session_id: False,
- clear_session=lambda base_session_id: None,
- )
- agent._session_locks = {"session-1": asyncio.Lock()}
- agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
+ agent = self._evict_agent(self._stopping_transport())
+ self.snapshot_gate = asyncio.Event()
with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
eviction_task = asyncio.create_task(agent.evict_idle_transports(600))
await asyncio.sleep(0)
- agent._transport_last_activity["/tmp/work"] = 950.0
- lock.release()
+ self.generation.runtime.last_activity = 950.0
+ self.snapshot_gate.set()
evicted = await eviction_task
self.assertEqual(evicted, 0)
- self.assertEqual(stop_calls, [])
- self.assertIn("/tmp/work", agent._transports)
- self.assertEqual(agent._transport_last_activity["/tmp/work"], 950.0)
+ self.assertEqual(self.stop_calls, [])
+ self.assertIs(codex_transports(agent)["/tmp/work"], self.generation.runtime.transport)
agent.sessions.clear_agent_session_mapping.assert_not_called()
- @staticmethod
- def _make_evict_agent(*, active_turn, last_activity=0.0):
- """Build a bare CodexAgent wired for evict_idle_transports tests."""
- agent = object.__new__(CodexAgent)
- stop_calls = []
-
- async def stop_transport():
- stop_calls.append("stop")
-
- agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}
- agent._transport_last_activity = {"/tmp/work": last_activity}
- agent._session_last_activity = {"session-1": last_activity}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- invalidated = []
- cleared_turns = []
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
- )
- request = SimpleNamespace(context="ctx-1", base_session_id="session-1")
- active_turns = {"session-1": active_turn}
-
- def clear_session(base_session_id):
- cleared_turns.append(base_session_id)
- active_turns[base_session_id] = None
-
- agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: active_turns.get(base_session_id),
- has_pending_turn_start=lambda base_session_id: False,
- get_request_for_turn=lambda turn_id: request if turn_id == active_turn else None,
- get_latest_request=lambda base_session_id: request,
- clear_session=clear_session,
- )
- release_calls = []
- agent._event_handler = SimpleNamespace(
- _release_stream_turn=lambda context: release_calls.append(context),
- release_calls=release_calls,
- )
- agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())
- agent._session_locks = {"session-1": asyncio.Lock()}
- agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
- return agent, stop_calls, invalidated, cleared_turns
-
async def test_hfr_144_stuck_active_settles_only_exact_codex_owner(self):
"""HFR-144: the exact owner settles through the terminal chokepoint."""
# active turn that has been idle WAY past the stuck-active cap
# (max(600*3, 1800) = 1800s) must be force-evicted — the leak fix.
- agent, stop_calls, invalidated, cleared_turns = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0
- )
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
agent.handle_message = AsyncMock()
with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 1)
- self.assertEqual(stop_calls, ["stop"])
- self.assertEqual(invalidated, ["session-1"])
- self.assertEqual(cleared_turns, ["session-1"])
- self.assertEqual(agent._transports, {})
- self.assertEqual(agent._transport_last_activity, {})
+ self.assertEqual(self.stop_calls, ["stop"])
+ self.assertEqual(self.invalidated, ["session-1"])
+ self.assertEqual(codex_transports(agent), {})
# Force-reaped stuck turns must settle Workbench status + runtime gate
# through the shared terminal-result chokepoint.
agent.controller.emit_agent_message.assert_awaited_once_with(
"ctx-1", "result", "", is_error=True, level="silent", output=ANY
)
agent.handle_message.assert_not_awaited()
- self.assertEqual(agent._event_handler.release_calls, [])
+ self.assertEqual(self.release_calls, [])
async def test_evict_idle_transports_force_evict_release_falls_back_to_latest_request(self):
# Defensive path: if the active turn has no per-turn request mapping,
# the runtime gate is still settled via get_latest_request.
- agent, stop_calls, _invalidated, _cleared = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0
- )
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
fallback_request = SimpleNamespace(context="ctx-latest", base_session_id="session-1")
agent._turn_registry.get_request_for_turn = lambda turn_id: None
agent._turn_registry.get_latest_request = lambda base_session_id: fallback_request
@@ -1317,63 +1585,55 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 1)
- self.assertEqual(stop_calls, ["stop"])
+ self.assertEqual(self.stop_calls, ["stop"])
agent.controller.emit_agent_message.assert_awaited_once_with(
"ctx-latest", "result", "", is_error=True, level="silent", output=ANY
)
- self.assertEqual(agent._event_handler.release_calls, [])
+ self.assertEqual(self.release_calls, [])
async def test_evict_idle_transports_keeps_active_transport_under_stuck_cap(self):
# active turn idle past idle_timeout (600) but under the cap (1800):
# still vetoed, NOT force-evicted.
- agent, stop_calls, _invalidated, cleared_turns = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0
- )
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 0)
- self.assertEqual(stop_calls, [])
- self.assertIn("/tmp/work", agent._transports)
- self.assertEqual(cleared_turns, [])
+ self.assertEqual(self.stop_calls, [])
+ self.assertIn("/tmp/work", codex_transports(agent))
+ self.assertEqual(self.cleared_turns, [])
async def test_evict_idle_transports_stuck_cap_floor_dominates_small_timeout(self):
# With a tiny idle_timeout (100s) the multiplier window (300s) is below
# the 1800s floor, so the floor governs: idle 1000s < 1800s stays vetoed.
- agent, stop_calls, _invalidated, _cleared = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0
- )
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
evicted = await agent.evict_idle_transports(100)
self.assertEqual(evicted, 0)
- self.assertEqual(stop_calls, [])
- self.assertIn("/tmp/work", agent._transports)
+ self.assertEqual(self.stop_calls, [])
+ self.assertIn("/tmp/work", codex_transports(agent))
async def test_evict_idle_transports_stuck_backstop_disabled(self):
# multiplier <= 0 disables the backstop: an active turn is an absolute
# veto again, no matter how long it has been idle.
- agent, stop_calls, _invalidated, cleared_turns = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0
- )
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
with patch.object(_MODULE, "DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER", 0):
with patch.object(_MODULE.time, "monotonic", return_value=1_000_000.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 0)
- self.assertEqual(stop_calls, [])
- self.assertIn("/tmp/work", agent._transports)
- self.assertEqual(cleared_turns, [])
+ self.assertEqual(self.stop_calls, [])
+ self.assertIn("/tmp/work", codex_transports(agent))
+ self.assertEqual(self.cleared_turns, [])
async def test_silent_owned_codex_turn_survives_both_reclamation_checks(self):
for ownership_arrives_during_check in (False, True):
with self.subTest(ownership_arrives_during_check=ownership_arrives_during_check):
- agent, stops, invalidated, cleared = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0,
- )
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
def snapshot(disposition):
return RuntimeTargetOwnershipSnapshot(
@@ -1387,27 +1647,27 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
)
active = snapshot(SessionRuntimeDisposition.ACTIVE)
- snapshots = (
+ snapshots = iter(
[snapshot(SessionRuntimeDisposition.RECLAIMABLE), active]
if ownership_arrives_during_check else [active]
)
- agent._runtime_ownership_snapshot_for_cwd = Mock(side_effect=snapshots)
+
+ async def ownership(generations, snapshots=snapshots, active=active):
+ return tuple(next(snapshots, active) for _ in generations)
+
+ agent._ownership_snapshots = ownership
with patch.object(_MODULE.time, "monotonic", return_value=1_000_000.0):
self.assertEqual(await agent.evict_idle_transports(600), 0)
- self.assertEqual(stops, [])
- self.assertEqual(invalidated, [])
- self.assertEqual(cleared, [])
+ self.assertEqual(self.stop_calls, [])
+ self.assertEqual(self.invalidated, [])
+ self.assertEqual(self.cleared_turns, [])
self.assertEqual(agent._turn_registry.get_active_turn("session-1"), "turn-1")
agent.controller.emit_agent_message.assert_not_awaited()
async def test_hfr_143_observable_session_progress_wins_locked_recheck(self):
"""HFR-143: attributable progress keeps a productive turn alive."""
- agent, stop_calls, _invalidated, _cleared = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0
- )
- lock = asyncio.Lock()
- await lock.acquire()
- agent._transport_locks = {"/tmp/work": lock}
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
+ self.snapshot_gate = asyncio.Event()
request = SimpleNamespace(
base_session_id="session-1",
working_path="/tmp/work",
@@ -1423,99 +1683,54 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
await agent._on_notification(
"item/agentMessage/delta",
{"threadId": "thread-1", "turnId": "turn-1"},
+ runtime=self.generation.runtime,
)
- lock.release()
+ self.snapshot_gate.set()
evicted = await eviction_task
self.assertEqual(evicted, 0)
- self.assertEqual(stop_calls, [])
- self.assertIn("/tmp/work", agent._transports)
+ self.assertEqual(self.stop_calls, [])
+ self.assertIn("/tmp/work", codex_transports(agent))
agent.controller.emit_agent_message.assert_not_awaited()
async def test_evict_idle_transports_reclassifies_when_turn_clears_between_passes(self):
# Race: pass 1 sees a stuck-active candidate, but the turn completes
- # (active flag clears) before the locked recheck while activity stays
- # stale. The recheck reclassifies it as a NORMAL idle eviction.
- agent, stop_calls, invalidated, cleared_turns = self._make_evict_agent(
- active_turn="turn-1", last_activity=0.0
- )
- lock = asyncio.Lock()
- await lock.acquire()
- agent._transport_locks = {"/tmp/work": lock}
+ # (active flag clears) before the recheck while activity stays stale.
+ # The recheck reclassifies it as a NORMAL idle eviction.
+ agent = self._evict_agent(self._stopping_transport(), active_turn="turn-1")
+ self.snapshot_gate = asyncio.Event()
with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
eviction_task = asyncio.create_task(agent.evict_idle_transports(600))
await asyncio.sleep(0)
# turn finished between the two passes; activity unchanged (stale)
agent._turn_registry.get_active_turn = lambda base_session_id: None
- lock.release()
+ self.snapshot_gate.set()
evicted = await eviction_task
self.assertEqual(evicted, 1)
- self.assertEqual(stop_calls, ["stop"])
- self.assertEqual(invalidated, ["session-1"])
- self.assertEqual(cleared_turns, ["session-1"])
+ self.assertEqual(self.stop_calls, ["stop"])
+ self.assertEqual(self.invalidated, ["session-1"])
# reclassified as normal idle: the prior turn already settled itself,
# so no spurious terminal result or runtime-gate release fires here.
agent.controller.emit_agent_message.assert_not_awaited()
- self.assertEqual(agent._event_handler.release_calls, [])
+ self.assertEqual(self.release_calls, [])
async def test_evict_idle_transports_force_evict_preserves_state_when_stop_fails(self):
# Stuck-active force-eviction path: if transport.stop() raises, the
- # transport and its bookkeeping must be left intact (next sweep retries).
- agent = object.__new__(CodexAgent)
- invalidated = []
- cleared_turns = []
-
- async def stop_transport():
- raise RuntimeError("boom")
-
- transport = SimpleNamespace(stop=stop_transport)
- lock = asyncio.Lock()
- agent._transports = {"/tmp/work": transport}
- agent._transport_last_activity = {"/tmp/work": 0.0}
- agent._session_last_activity = {"session-1": 0.0}
- agent._transport_locks = {"/tmp/work": lock}
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
- invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
- )
- agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: "turn-1",
- has_pending_turn_start=lambda base_session_id: False,
- clear_session=lambda base_session_id: cleared_turns.append(base_session_id),
- )
- agent._session_locks = {"session-1": asyncio.Lock()}
- agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
+ # generation and its Session binding stay for the next sweep.
+ transport = SimpleNamespace(stop=AsyncMock(side_effect=RuntimeError("boom")))
+ agent = self._evict_agent(transport, active_turn="turn-1")
agent._settle_stuck_active_request = AsyncMock()
with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
evicted = await agent.evict_idle_transports(600)
self.assertEqual(evicted, 0)
- self.assertIs(agent._transports["/tmp/work"], transport)
- self.assertEqual(agent._transport_last_activity["/tmp/work"], 0.0)
- self.assertEqual(invalidated, [])
- self.assertEqual(cleared_turns, ["session-1"])
-
- async def test_get_or_create_transport_fast_path_waits_for_transport_lock(self):
- agent = object.__new__(CodexAgent)
- lock = asyncio.Lock()
- await lock.acquire()
- transport = SimpleNamespace(is_initialized=True)
- agent._transports = {"/tmp/work": transport}
- agent._transport_locks = {"/tmp/work": lock}
- agent._transport_last_activity = {}
-
- with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
- transport_task = asyncio.create_task(agent._get_or_create_transport("/tmp/work"))
- await asyncio.sleep(0)
- self.assertFalse(transport_task.done())
- lock.release()
- resolved = await transport_task
-
- self.assertIs(resolved, transport)
- self.assertEqual(agent._transport_last_activity["/tmp/work"], 1000.0)
+ self.assertIn(self.generation, agent._units["/tmp/work"].generations)
+ self.assertIs(agent.transport_for_session("session-1"), transport)
+ self.assertEqual(self.invalidated, [])
+ self.assertEqual(self.cleared_turns, ["session-1"])
class _HandleMessageTurnRegistry:
@@ -1544,7 +1759,7 @@ class _HandleMessageTurnRegistry:
class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
async def test_handle_message_refreshes_cached_thread_instructions_before_turn(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(
base_session_id="session-1",
working_path="/tmp/work",
@@ -1563,8 +1778,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
emit_agent_message=AsyncMock(),
agent_auth_service=SimpleNamespace(maybe_emit_auth_recovery_message=AsyncMock(return_value=False)),
)
- agent._get_or_create_transport = AsyncMock(return_value=transport)
- agent._touch_transport_activity = Mock()
+ agent._acquire_generation = acquire_returning(agent, transport)
agent.ensure_agent_session_id = Mock(
side_effect=lambda existing_request: events.append(
("ensure", existing_request)
@@ -1603,7 +1817,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._start_or_resume_thread.assert_not_awaited()
async def test_prompt_refresh_failure_display_is_localized(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(language="zh"))
display = agent._error_display_text(
@@ -1629,7 +1843,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
}
for language, expected in messages.items():
with self.subTest(language=language):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
context = SimpleNamespace(platform_specific={})
request = SimpleNamespace(
base_session_id="session-1",
@@ -1649,8 +1863,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._session_mgr = SimpleNamespace(
set_session_key=Mock(), set_cwd=Mock(), get_thread_id=Mock(return_value=None),
)
- agent._get_or_create_transport = AsyncMock(return_value=transport)
- agent._touch_transport_activity = Mock()
+ agent._acquire_generation = acquire_returning(agent, transport)
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())
@@ -1660,7 +1873,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
side_effect=CodexForkBoundaryUnavailableError(diagnostic),
)
agent._start_turn = AsyncMock()
- agent._drop_transport_after_failure = AsyncMock()
+ agent._drop_generation_after_failure = AsyncMock()
await agent.handle_message(request)
@@ -1671,12 +1884,12 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
self.assertIn(diagnostic, calls[1].kwargs["terminal_error"])
agent._start_or_resume_thread.assert_awaited_once()
agent._start_turn.assert_not_awaited()
- agent._drop_transport_after_failure.assert_not_awaited()
+ agent._drop_generation_after_failure.assert_not_awaited()
transport.stop.assert_not_awaited()
agent._event_handler._release_stream_turn.assert_called_once_with(context)
async def test_handle_message_does_not_hide_turn_before_interrupt_succeeds(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(
base_session_id="session-1",
working_path="/tmp",
@@ -1696,7 +1909,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
)
agent._remove_ack_reaction = AsyncMock()
agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())
- agent._get_or_create_transport = AsyncMock(return_value=transport)
+ agent._acquire_generation = acquire_returning(agent, transport)
agent._session_mgr = SimpleNamespace(
set_session_key=lambda base_session_id, session_key: None,
set_cwd=lambda base_session_id, cwd: None,
@@ -1723,7 +1936,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(terminal_call.kwargs["terminal_error"], "interrupt failed")
async def test_handle_message_recovers_from_broken_transport_once(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(
base_session_id="session-1",
working_path="/tmp/work",
@@ -1758,16 +1971,12 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
emit_agent_message=AsyncMock(),
agent_auth_service=SimpleNamespace(maybe_emit_auth_recovery_message=AsyncMock(return_value=False)),
)
- agent._transports = {"/tmp/work": bad_transport}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._transport_last_activity = {"/tmp/work": 1.0}
- agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(
- return_value=SimpleNamespace(blocks_dead_transport_replacement=False)
+ agent._ownership_snapshots = AsyncMock(
+ return_value=(SimpleNamespace(blocks_dead_transport_replacement=False),)
)
agent._session_mgr = session_mgr
agent.sessions = sessions
- agent._get_or_create_transport = AsyncMock(side_effect=[bad_transport, fresh_transport])
- agent._touch_transport_activity = Mock()
+ agent._acquire_generation = acquire_returning(agent, bad_transport, fresh_transport)
agent._build_thread_developer_instructions = AsyncMock(return_value="stable prompt")
agent._start_or_resume_thread = AsyncMock(
side_effect=[
@@ -1783,12 +1992,11 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
observe_pressure.assert_not_called()
bad_transport.stop.assert_awaited_once()
- self.assertEqual(agent._transports, {})
- self.assertEqual(agent._transport_last_activity, {})
+ self.assertEqual(codex_transports(agent), {"/tmp/work": fresh_transport})
self.assertEqual(invalidated, ["session-1"])
self.assertEqual(agent._turn_registry.cleared_sessions, ["session-1"])
sessions.clear_agent_session_mapping.assert_not_called()
- agent._get_or_create_transport.assert_any_await("/tmp/work")
+ self.assertEqual(agent._acquire_generation.await_count, 2)
self.assertEqual(agent._start_or_resume_thread.await_args_list[-1].args, (fresh_transport, request))
agent._start_thread.assert_not_awaited()
agent._start_turn.assert_awaited_once_with(
@@ -1801,7 +2009,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._remove_ack_reaction.assert_not_awaited()
async def test_handle_message_reraises_recoverable_interrupt_error_for_retry(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(
base_session_id="session-1",
working_path="/tmp/work",
@@ -1826,11 +2034,8 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
emit_agent_message=AsyncMock(),
agent_auth_service=SimpleNamespace(maybe_emit_auth_recovery_message=AsyncMock(return_value=False)),
)
- agent._transports = {"/tmp/work": bad_transport}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._transport_last_activity = {"/tmp/work": 1.0}
- agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(
- return_value=SimpleNamespace(blocks_dead_transport_replacement=False)
+ agent._ownership_snapshots = AsyncMock(
+ return_value=(SimpleNamespace(blocks_dead_transport_replacement=False),)
)
agent._session_mgr = SimpleNamespace(
set_session_key=Mock(),
@@ -1840,8 +2045,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
invalidate_thread=Mock(),
)
agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
- agent._get_or_create_transport = AsyncMock(side_effect=[bad_transport, fresh_transport])
- agent._touch_transport_activity = Mock()
+ agent._acquire_generation = acquire_returning(agent, bad_transport, fresh_transport)
agent._build_thread_developer_instructions = AsyncMock(return_value="stable prompt")
agent._start_or_resume_thread = AsyncMock(return_value="thread-new")
agent._start_thread = AsyncMock(return_value="thread-new")
@@ -1863,7 +2067,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
async def test_cold_resume_failure_binds_session_before_ownership_checks(self):
for incomplete_prior_binding in (False, True):
with self.subTest(incomplete_prior_binding=incomplete_prior_binding):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(
base_session_id="session-1", working_path="/tmp/work",
context=SimpleNamespace(platform_specific={}),
@@ -1873,9 +2077,6 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
bad = SimpleNamespace(stop=AsyncMock(), is_alive=False)
fresh = SimpleNamespace(is_alive=True)
agent._session_locks = {}
- agent._transport_locks = {}
- agent._transports = {request.working_path: bad}
- agent._transport_last_activity = {}
agent._session_mgr = RealCodexSessionManager()
if incomplete_prior_binding:
agent._session_mgr.set_session_key("session-1", "settings-1")
@@ -1887,7 +2088,6 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
- agent._touch_transport_activity = Mock()
agent._build_thread_developer_instructions = AsyncMock(return_value="prompt")
agent._start_or_resume_thread = AsyncMock(
side_effect=[ConnectionError("stdout closed"), "thread-restored"],
@@ -1895,7 +2095,9 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._start_turn = AsyncMock()
def snapshot(target):
- self.assertEqual([binding.session_id for binding in target.bindings], ["ses-durable"])
+ # The retired broken generation answers only for Sessions
+ # holding a thread there; the resume never loaded one.
+ self.assertEqual(target.bindings, ())
return SimpleNamespace(blocks_dead_transport_replacement=False)
agent.controller = SimpleNamespace(
@@ -1903,74 +2105,85 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
runtime_ownership=SimpleNamespace(snapshot=Mock(side_effect=snapshot)),
)
- async def get_transport(_cwd):
+ served = iter([bad, fresh])
+
+ async def acquire(cwd, launch=None, *, inputs=None):
+ generation = install_codex_transport(
+ agent, cwd, next(served), digest=f"spec-{agent._acquire_generation.await_count}"
+ )
# Both initial acquisition and failure recovery must see a
# complete producer-side binding, not a mocked predicate.
- target = agent._runtime_ownership_target_for_cwd(request.working_path)
+ target = agent._runtime_ownership_target_for_generation(generation)
self.assertIsNotNone(target)
self.assertEqual([binding.session_id for binding in target.bindings], ["ses-durable"])
- return agent._transports.get(request.working_path, fresh)
+ return bind_installed(agent, generation)
- agent._get_or_create_transport = AsyncMock(side_effect=get_transport)
+ # Acquisition is stubbed, so the launch load it alone consumes is too.
+ agent._launch_inputs = lambda cwd, *, hub_config=None: SimpleNamespace(hub_config=hub_config)
+ agent._acquire_generation = AsyncMock(side_effect=acquire)
await agent.handle_message(request)
bad.stop.assert_awaited_once()
- agent.controller.runtime_ownership.snapshot.assert_called_once()
- self.assertEqual(agent._get_or_create_transport.await_count, 2)
+ # Checked before the fence and again inside it.
+ self.assertEqual(agent.controller.runtime_ownership.snapshot.call_count, 2)
+ self.assertEqual(agent._acquire_generation.await_count, 2)
agent._start_turn.assert_awaited_once()
agent.controller.emit_agent_message.assert_not_awaited()
- async def test_drop_transport_after_failure_keeps_other_sessions_when_transport_was_replaced(self):
- agent = object.__new__(CodexAgent)
+ async def test_drop_generation_after_failure_keeps_a_newer_generation_and_its_sessions(self):
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(base_session_id="session-1")
activation = RuntimeActivationRegistry()
- old_identity = activation.attach("codex", "/tmp/work")
- old_transport = SimpleNamespace(
- stop=AsyncMock(),
- _vibe_runtime_activation_identity=old_identity,
- )
- fresh_identity = activation.attach("codex", "/tmp/work")
- fresh_transport = SimpleNamespace()
- fresh_transport._vibe_runtime_activation_identity = fresh_identity
+ old_identity = activation.attach("codex", "/tmp/work#1")
+ old_transport = SimpleNamespace(stop=AsyncMock(), is_alive=False)
+ fresh_identity = activation.attach("codex", "/tmp/work#2")
+ fresh_transport = SimpleNamespace(is_alive=True)
invalidated = []
cleared = []
- agent._transports = {"/tmp/work": fresh_transport}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._transport_last_activity = {"/tmp/work": 1.0}
agent._session_mgr = SimpleNamespace(
sessions_for_cwd=Mock(return_value=["session-1", "session-2"]),
+ get_cwd=Mock(return_value="/tmp/work"),
invalidate_thread=Mock(side_effect=lambda base_session_id: invalidated.append(base_session_id)),
)
agent._turn_registry = SimpleNamespace(
- clear_session=Mock(side_effect=lambda base_session_id: cleared.append(base_session_id))
+ get_active_turn=Mock(return_value=None),
+ clear_session=Mock(side_effect=lambda base_session_id: cleared.append(base_session_id)),
)
agent.controller = SimpleNamespace(runtime_activation=activation)
+ agent._ownership_snapshots = AsyncMock(
+ return_value=(SimpleNamespace(blocks_dead_transport_replacement=False),)
+ )
+ old = install_codex_transport(
+ agent, "/tmp/work", old_transport, activation=old_identity, sessions={"session-1": "thread-1"}
+ )
+ install_codex_transport(
+ agent, "/tmp/work", fresh_transport, activation=fresh_identity, digest="fresh",
+ sessions={"session-2": "thread-2"},
+ )
- await agent._drop_transport_after_failure("/tmp/work", old_transport, request)
+ self.assertTrue(await agent._drop_generation_after_failure(old, request, bind_installed(agent, old)))
old_transport.stop.assert_awaited_once()
- self.assertIs(agent._transports["/tmp/work"], fresh_transport)
- self.assertEqual(agent._transport_last_activity, {"/tmp/work": 1.0})
+ self.assertIs(codex_transports(agent)["/tmp/work"], fresh_transport)
+ self.assertIs(agent.transport_for_session("session-2"), fresh_transport)
self.assertEqual(invalidated, ["session-1"])
self.assertEqual(cleared, ["session-1"])
- self.assertEqual(activation.current("codex", "/tmp/work"), fresh_identity)
+ self.assertIsNone(activation.current("codex", "/tmp/work#1"))
+ self.assertEqual(activation.current("codex", "/tmp/work#2"), fresh_identity)
- async def test_drop_transport_after_failure_retires_current_generation_before_stop(self):
- agent = object.__new__(CodexAgent)
+ async def test_drop_generation_after_failure_retires_its_identity_before_stop(self):
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(base_session_id="session-1")
activation = RuntimeActivationRegistry()
observed_current = []
transport = SimpleNamespace(is_alive=False)
+ identity = activation.attach("codex", "/tmp/work#1")
async def stop_transport():
observed_current.append(activation.is_current(identity))
transport.stop = stop_transport
- agent._transports = {"/tmp/work": transport}
- agent._transport_locks = {"/tmp/work": asyncio.Lock()}
- agent._transport_last_activity = {"/tmp/work": 1.0}
- agent._transport_cwd_inodes = {"/tmp/work": 1}
- agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(
- return_value=SimpleNamespace(blocks_dead_transport_replacement=False)
+ agent._ownership_snapshots = AsyncMock(
+ return_value=(SimpleNamespace(blocks_dead_transport_replacement=False),)
)
agent._session_mgr = SimpleNamespace(
sessions_for_cwd=Mock(return_value=["session-1"]),
@@ -1978,16 +2191,16 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
)
agent._turn_registry = SimpleNamespace(clear_session=Mock())
agent.controller = SimpleNamespace(runtime_activation=activation)
- identity = agent._attach_transport_activation("/tmp/work", transport)
+ generation = install_codex_transport(agent, "/tmp/work", transport, activation=identity)
- await agent._drop_transport_after_failure("/tmp/work", transport, request)
+ await agent._drop_generation_after_failure(generation, request, bind_installed(agent, generation))
self.assertEqual(observed_current, [False])
- self.assertNotIn("/tmp/work", agent._transports)
- self.assertIsNone(activation.current("codex", "/tmp/work"))
+ self.assertEqual(codex_transports(agent), {})
+ self.assertIsNone(activation.current("codex", "/tmp/work#1"))
async def test_start_or_resume_thread_reraises_recoverable_transport_error(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-old"))
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
agent._build_thread_developer_instructions = AsyncMock(return_value=None)
@@ -2000,9 +2213,9 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._start_thread.assert_not_awaited()
- async def test_blocked_runtime_change_holds_unwritten_input_without_hub_cooldown(self):
- """#2148: a blocked runtime switch settles as a visible, retryable prewrite failure."""
- agent = object.__new__(CodexAgent)
+ async def test_unreleased_thread_holds_unwritten_input_without_hub_cooldown(self):
+ """A thread its old generation cannot release settles as a visible, retryable prewrite failure."""
+ agent = init_generation_state(object.__new__(CodexAgent))
context = SimpleNamespace(platform_specific={})
set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)
request = SimpleNamespace(
@@ -2016,8 +2229,9 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._session_mgr = SimpleNamespace(set_session_key=Mock(), set_cwd=Mock())
agent.ensure_agent_session_id = Mock()
agent._bind_runtime_agent_session_id = Mock()
- agent._get_or_create_transport = AsyncMock(
- side_effect=_MODULE.CodexRuntimeChangeBlockedError("blocked")
+ agent._acquire_generation = acquire_returning(agent, SimpleNamespace(), session=None)
+ agent._move_session_to = AsyncMock(
+ side_effect=_MODULE.CodexThreadReleaseUnavailableError("still loaded")
)
agent._record_model_hub_native_failure = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
@@ -2027,13 +2241,15 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
prewrite_failure_evidence(context),
- {"reason": "transport_runtime_change_blocked", "requires_explicit_retry": True},
+ {"reason": "codex_thread_release_unavailable", "requires_explicit_retry": True},
)
agent._record_model_hub_native_failure.assert_not_awaited()
notify = agent.controller.emit_agent_message.await_args_list[0]
self.assertEqual(notify.args[1], "notify")
- self.assertIn("different model runtime", notify.args[2])
+ self.assertIn("could not move this conversation", notify.args[2])
agent._event_handler._release_stream_turn.assert_called_once_with(context)
+ # The admission binding is released, so the generation can retire.
+ self.assertEqual(agent._units["/tmp/work"].current.bindings, 0)
async def test_permanent_resume_failure_holds_only_proven_unwritten_input(self):
for error in (
@@ -2042,7 +2258,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
):
for phase in (DISPATCH_PHASE_PREWRITE, DISPATCH_PHASE_ATTEMPTING, None):
with self.subTest(error=type(error).__name__, phase=phase):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
context = SimpleNamespace(platform_specific={})
if phase:
set_dispatch_phase(context, phase)
@@ -2060,23 +2276,22 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._session_mgr = SimpleNamespace(
set_session_key=Mock(), set_cwd=Mock(), get_thread_id=Mock(return_value=None),
)
- agent._get_or_create_transport = AsyncMock(return_value=transport)
- agent._touch_transport_activity = Mock()
+ agent._acquire_generation = acquire_returning(agent, transport)
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())
agent._build_thread_developer_instructions = AsyncMock(return_value="prompt")
agent._start_or_resume_thread = AsyncMock(side_effect=error)
agent._start_turn = AsyncMock()
- agent._drop_transport_after_failure = AsyncMock(return_value=False)
+ agent._drop_generation_after_failure = AsyncMock(return_value=False)
await agent.handle_message(request)
- agent._get_or_create_transport.assert_awaited_once()
+ agent._acquire_generation.assert_awaited_once()
if isinstance(error, TimeoutError) and phase == DISPATCH_PHASE_PREWRITE:
- agent._drop_transport_after_failure.assert_awaited_once()
+ agent._drop_generation_after_failure.assert_awaited_once()
else:
- agent._drop_transport_after_failure.assert_not_awaited()
+ agent._drop_generation_after_failure.assert_not_awaited()
agent._start_turn.assert_not_awaited()
transport.stop.assert_not_awaited()
self.assertEqual(
@@ -2097,42 +2312,53 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
(True, False, False, True), # Idle process can be reclaimed.
):
with self.subTest(live=live, blocked=blocked, active=active):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
activation = RuntimeActivationRegistry()
transport = SimpleNamespace(stop=AsyncMock(), is_alive=live)
agent.controller = SimpleNamespace(runtime_activation=activation)
- agent._transports = {"/tmp/work": transport}
- agent._transport_locks = {}
- agent._transport_last_activity = {"/tmp/work": 1.0}
agent._session_mgr = SimpleNamespace(
sessions_for_cwd=Mock(return_value=["failed", "neighbour"]),
invalidate_thread=Mock(),
)
- agent._turn_registry = SimpleNamespace(clear_session=Mock())
- agent._has_active_turns_for_cwd = Mock(return_value=active)
- agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(
- return_value=None if blocked is None else SimpleNamespace(
+ agent._turn_registry = SimpleNamespace(
+ clear_session=Mock(),
+ get_active_turn=lambda base_session_id, active=active: (
+ "turn-neighbour" if active and base_session_id == "neighbour" else None
+ ),
+ )
+ agent._ownership_snapshots = AsyncMock(
+ return_value=None if blocked is None else (SimpleNamespace(
blocks_transport_replacement=blocked,
blocks_dead_transport_replacement=blocked,
- )
+ ),)
+ )
+ identity = activation.attach("codex", "/tmp/work#1")
+ generation = install_codex_transport(
+ agent, "/tmp/work", transport, activation=identity,
+ sessions={"failed": "thread-failed", "neighbour": "thread-neighbour"},
)
- identity = agent._attach_transport_activation("/tmp/work", transport)
- result = await agent._drop_transport_after_failure(
- "/tmp/work", transport, SimpleNamespace(base_session_id="failed"),
+ result = await agent._drop_generation_after_failure(
+ generation,
+ SimpleNamespace(base_session_id="failed"),
+ bind_installed(agent, generation),
)
self.assertIs(result, allowed)
- if allowed:
+ if result:
transport.stop.assert_awaited_once()
- self.assertNotIn("/tmp/work", agent._transports)
+ self.assertEqual(agent._units["/tmp/work"].generations, ())
else:
transport.stop.assert_not_awaited()
agent._session_mgr.invalidate_thread.assert_not_called()
agent._turn_registry.clear_session.assert_not_called()
- self.assertIs(agent._transports["/tmp/work"], transport)
+ # Retired, so no new turn binds to it, but the neighbour's
+ # process keeps running until its work drains.
+ self.assertIn(generation, agent._units["/tmp/work"].generations)
+ self.assertTrue(generation.closed)
+ self.assertFalse(generation.runtime.ended)
self.assertTrue(activation.is_current(identity))
async def test_start_or_resume_preserves_oversized_response_identity(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-old"))
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
agent._build_thread_developer_instructions = AsyncMock(return_value=None)
@@ -2147,7 +2373,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
agent._start_thread.assert_not_awaited()
def test_find_request_does_not_bootstrap_turn_completed_for_pending_turn(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_mgr = _StubSessionManager()
agent._turn_registry = _StubTurnRegistry()
@@ -2165,7 +2391,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
def test_inject_caller_env_config_preserves_private_codex_helpers_with_vendored_git(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.codex_config = SimpleNamespace(binary="/private/codex")
params = {}
request = SimpleNamespace(
@@ -2180,15 +2406,8 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
env["PATH"] = f"/managed/git/bin:{base_env['PATH']}"
return True
- with (
- patch.object(
- _MODULE,
- "desktop_backend_subprocess_environment",
- return_value=managed_env,
- ),
- patch("core.git_runtime.prepend_vendored_git_to_path", side_effect=inject_git),
- ):
- agent._inject_caller_env_config(params, request)
+ with patch("core.git_runtime.prepend_vendored_git_to_path", side_effect=inject_git):
+ agent._inject_caller_env_config(params, request, managed_env)
self.assertEqual(
params["config"]["shell_environment_policy"]["set"]["PATH"],
@@ -2196,7 +2415,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
def test_inject_caller_env_config_adds_vendored_git_for_gitless_session(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
params = {"config": {"shell_environment_policy": {"set": {"PATH": ""}}}}
request = SimpleNamespace(
working_path="/tmp/workspace",
@@ -2211,7 +2430,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
return True
with patch("core.git_runtime.prepend_vendored_git_to_path", side_effect=inject_git):
- agent._inject_caller_env_config(params, request)
+ agent._inject_caller_env_config(params, request, os.environ)
set_env = params["config"]["shell_environment_policy"]["set"]
self.assertEqual(set_env["PATH"], "/managed/git/bin")
@@ -2220,7 +2439,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(params["config"]["skills.include_instructions"])
def test_inject_caller_env_config_merges_shell_environment_policy(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
params = {"config": {"shell_environment_policy": {"set": {"KEEP": "1"}}}}
request = SimpleNamespace(
context=SimpleNamespace(
@@ -2237,7 +2456,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
with patch("core.git_runtime.prepend_vendored_git_to_path", return_value=False):
- agent._inject_caller_env_config(params, request)
+ agent._inject_caller_env_config(params, request, os.environ)
set_env = params["config"]["shell_environment_policy"]["set"]
self.assertEqual(set_env["KEEP"], "1")
@@ -2251,7 +2470,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(params["config"]["skills.include_instructions"])
def test_write_caller_env_script_refreshes_reused_thread_run_id(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
request = SimpleNamespace(
base_session_id="session-1",
context=SimpleNamespace(
@@ -2282,7 +2501,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("export AVIBE_RUN_ID=run-one", second)
async def test_start_thread_requests_danger_full_access(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -2333,7 +2552,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
agent.sessions.bind_agent_session.assert_called_once_with("channel-1", "codex", "session-1", "thread-1")
async def test_start_thread_includes_codex_agent_developer_instructions(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -2379,7 +2598,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("## Quick-reply buttons", developer_instructions)
async def test_start_thread_adds_codex_generated_image_prompt_to_thread_instructions(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -2418,7 +2637,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_thread_includes_show_pages_despite_legacy_opt_out(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
config=SimpleNamespace(platform="slack", reply_enhancements=True, show_pages_prompt=False)
)
@@ -2456,7 +2675,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("vibe show path", developer_instructions)
async def test_resume_thread_refreshes_developer_instructions_without_appending(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -2509,7 +2728,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("developerInstructions", params)
async def test_resume_thread_rebinds_managed_provider_when_thread_id_matches_config(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(
default_model=None,
@@ -2557,7 +2776,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(params["modelProvider"], "openai-managed")
async def test_resume_thread_overrides_stale_session_model_provider(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -2603,7 +2822,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
async def test_resume_thread_prefers_reserved_native_for_main_turn(self):
# avibe main turn: resume the native bound to the reserved row (by PK),
# NOT the (session_key, anchor) projection — the restart-resume fix.
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-projection"))
agent.bind_agent_session_id = Mock()
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -2635,7 +2854,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(params["threadId"], "native-reserved")
async def test_start_or_resume_thread_forks_pending_native_source(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -2707,7 +2926,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_fork_carries_persisted_fallback_prompt_strategy(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
config=SimpleNamespace(platform="avibe", reply_enhancements=False)
)
@@ -2786,7 +3005,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_fork_finalizes_a_source_prompt_with_pending_marker_persistence(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.ensure_agent_session_id = Mock(return_value="ses-target")
agent._fork_source_prompt_state = Mock(
return_value=("injected_pending_persist", None, None)
@@ -2841,7 +3060,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_fork_persists_carried_collaboration_strategy_for_target(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.ensure_agent_session_id = Mock(return_value="ses-target")
agent._fork_source_prompt_state = Mock(
return_value=("collaboration", None, None)
@@ -2886,7 +3105,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_fork_does_not_cache_unpersisted_collaboration_strategy(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.ensure_agent_session_id = Mock(return_value="ses-target")
agent._fork_source_prompt_state = Mock(
return_value=("collaboration", None, None)
@@ -2923,7 +3142,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_or_resume_thread_does_not_bind_failed_fork_correction(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -2979,7 +3198,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(agent.is_fork_correction_pending("ses-target"))
async def test_fork_rejects_trim_without_native_turn_boundary(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
config=SimpleNamespace(platform="avibe", reply_enhancements=False),
session_turns=SimpleNamespace(
@@ -3042,7 +3261,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
agent._clear_fork_correction_pending.assert_called_once_with("ses-target")
async def test_fork_boundary_requires_a_completed_predecessor(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = SimpleNamespace(
get_active_turn=Mock(return_value="turn-source"),
)
@@ -3076,7 +3295,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_fork_boundary_keeps_completed_reserved_turn_inclusive(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = SimpleNamespace(
get_active_turn=Mock(return_value="turn-source"),
)
@@ -3113,7 +3332,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
async def test_fork_keeps_boundary_when_source_completes_before_rpc_write(self):
for status in ("completed", "interrupted", "failed"):
with self.subTest(status=status):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(
ensure_agent_session_id=Mock(return_value="ses-target"),
bind_agent_session=Mock(return_value="ses-target"),
@@ -3169,7 +3388,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_fork_boundary_pages_to_find_terminal_predecessor(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = SimpleNamespace(
get_active_turn=Mock(return_value="turn-source"),
)
@@ -3227,7 +3446,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_fork_boundary_searches_older_pages_for_reserved_turn(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = SimpleNamespace(get_active_turn=Mock(return_value="turn-source"))
transport = SimpleNamespace(
send_request=AsyncMock(
@@ -3273,7 +3492,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
]
for response in responses:
with self.subTest(response=response):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = SimpleNamespace(get_active_turn=Mock(return_value="turn-source"))
transport = SimpleNamespace(send_request=AsyncMock(side_effect=[response]))
boundary = await agent._fork_source_last_completed_turn_id(
@@ -3284,7 +3503,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
transport.send_request.assert_awaited_once()
async def test_fork_boundary_rejects_repeated_pagination_cursor(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._turn_registry = SimpleNamespace(get_active_turn=Mock(return_value="turn-source"))
transport = SimpleNamespace(
send_request=AsyncMock(return_value={"data": [], "nextCursor": "same"}),
@@ -3297,7 +3516,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(transport.send_request.await_count, 2)
async def test_start_or_resume_thread_trims_running_fork_before_correction(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3362,7 +3581,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_or_resume_thread_keeps_running_fork_before_native_start(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3417,7 +3636,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
])
async def test_start_or_resume_thread_trims_pre_start_fork_after_source_started(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3501,7 +3720,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(fork_params["lastTurnId"], "turn-before")
async def test_start_or_resume_thread_trims_pre_start_fork_after_source_output(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3570,7 +3789,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(fork_params["lastTurnId"], "turn-before")
async def test_start_or_resume_thread_keeps_running_fork_when_anchor_completed(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3636,7 +3855,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
])
async def test_start_or_resume_thread_keeps_running_fork_after_source_completed(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3699,7 +3918,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
])
async def test_start_or_resume_thread_trims_reserved_user_anchor_after_source_completed(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3770,7 +3989,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(fork_params["lastTurnId"], "turn-before")
async def test_start_or_resume_thread_trims_user_anchor_completed_before_native_start_flag(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3842,7 +4061,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(fork_params["lastTurnId"], "turn-before")
async def test_start_or_resume_thread_does_not_trim_when_new_user_after_anchor(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -3908,7 +4127,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
])
async def test_should_roll_back_forked_running_harness_turn(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
fork = {
"source_session_id": "ses-source",
"source_message_id": "msg-harness",
@@ -3933,7 +4152,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(should_trim)
async def test_start_or_resume_thread_does_not_trim_user_anchor_before_native_start(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(
@@ -4007,7 +4226,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
async def test_resume_thread_skips_reserved_native_for_explicit_subagent(self):
# Explicit per-turn subagent: it has its own thread; must NOT resume the
# reserved MAIN native.
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-subagent"))
agent.bind_agent_session_id = Mock()
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -4040,7 +4259,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
async def test_resume_thread_fails_loud_on_non_transport_resume_error(self):
# An associated thread that won't resume for a non-transport reason
# (expired/gone) must RAISE, not silently start a fresh thread.
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-old"))
agent.bind_agent_session_id = Mock()
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -4061,7 +4280,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
agent._start_thread.assert_not_awaited() # must NOT silently fork a fresh thread
async def test_resume_thread_preserves_unmanaged_cross_provider_session(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -4102,7 +4321,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("modelProvider", params)
async def test_resume_thread_omits_model_provider_when_provider_read_fails(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -4143,7 +4362,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("modelProvider", params)
async def test_resume_thread_omits_model_provider_when_config_read_fails(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -4183,7 +4402,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("modelProvider", params)
async def test_resume_thread_clears_legacy_thread_prompt_before_turn_strategy(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
@@ -4218,7 +4437,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(params["developerInstructions"])
async def test_resume_thread_routes_prompt_marker_read_failure_through_i18n(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(
get_agent_session_id=Mock(return_value="thread-existing"),
get_agent_session_runtime_marker=Mock(
@@ -4246,7 +4465,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
def test_build_input_does_not_add_codex_generated_image_prompt_to_each_turn(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(reply_enhancements=True))
request = SimpleNamespace(message="hello", files=None)
@@ -4256,7 +4475,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(items, [{"type": "text", "text": "hello"}])
async def test_refresh_thread_developer_instructions_updates_cached_thread_once(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))
@@ -4291,7 +4510,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("developerInstructions", params)
async def test_refresh_thread_developer_instructions_refreshes_caller_env_when_prompt_cached(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))
@@ -4338,7 +4557,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(second_params["threadId"], "thread-existing")
async def test_refresh_thread_developer_instructions_refreshes_git_path_state(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))
agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)
agent._build_thread_developer_instructions = AsyncMock(return_value="stable instructions")
@@ -4390,7 +4609,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_refresh_thread_developer_instructions_clears_stale_vendored_path(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))
agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)
agent._build_thread_developer_instructions = AsyncMock(return_value="stable instructions")
@@ -4430,7 +4649,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_refresh_thread_developer_instructions_preserves_resume_model_provider_override(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.codex_config = SimpleNamespace(default_model=None)
agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))
@@ -4467,7 +4686,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("developerInstructions", params)
async def test_start_turn_injects_stable_developer_instructions_once(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, None, None)),
)
@@ -4546,7 +4765,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_persists_subagent_strategy_on_backend_session(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -4604,7 +4823,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_honors_explicit_null_model_instead_of_cached_route(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "routing-model", "high")),
)
@@ -4653,7 +4872,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("session-1", agent._thread_model_settings)
async def test_start_turn_fails_when_fallback_strategy_cannot_persist(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -4706,7 +4925,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("session-1", getattr(agent, "_thread_developer_instructions", {}))
async def test_start_turn_repairs_marker_without_reinjecting_known_prompt(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, None, None)),
)
@@ -4770,7 +4989,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("session-1", agent._thread_unpersisted_prompts)
async def test_start_turn_reuses_persisted_fallback_prompt_after_process_restart(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -4835,7 +5054,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_disables_refresh_for_invalid_persisted_prompt_marker(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -4894,7 +5113,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
def test_prompt_marker_read_failure_uses_localized_error_path(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(
get_agent_session_runtime_marker=Mock(side_effect=OSError("database busy"))
)
@@ -4909,7 +5128,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_migrates_persisted_collaboration_after_inconclusive_probe(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -4972,7 +5191,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_fails_closed_when_collaboration_reprobe_is_negative(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -5015,7 +5234,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
transport.send_request.assert_awaited_once_with("collaborationMode/list", {})
async def test_start_turn_clears_sticky_collaboration_mode_with_explicit_null_model(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "routing-model", "high")),
)
@@ -5079,7 +5298,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_clears_persisted_collaboration_before_model_less_fallback(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, None, None)),
)
@@ -5136,7 +5355,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_retries_a_pending_collaboration_clear_after_restart(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, None, None)),
)
@@ -5229,7 +5448,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_clears_collaboration_without_reinjecting_after_unknown_injection(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, None, None)),
)
@@ -5321,7 +5540,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
def test_prompt_strategy_rebinds_a_stale_native_session_before_retry(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.sessions = SimpleNamespace(
set_agent_session_runtime_marker=Mock(side_effect=[False, True]),
)
@@ -5347,7 +5566,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_persists_changed_fallback_prompt(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -5425,7 +5644,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_does_not_reuse_cached_effort_for_an_explicit_model_change(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.5", None)),
)
@@ -5468,7 +5687,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("collaborationMode", params)
async def test_start_turn_preserves_explicit_effort_while_restoring_cached_model(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, None, "xhigh")),
)
@@ -5511,7 +5730,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("collaborationMode", params)
async def test_start_turn_injects_updated_instructions_when_prompt_changes(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -5564,7 +5783,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(latest, "<avibe_runtime_instructions>\n\nprompt two\n</avibe_runtime_instructions>")
async def test_start_turn_does_not_reinject_when_explicit_model_reset_is_unsupported(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -5619,7 +5838,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(transport.supports_turn_collaboration_mode)
async def test_start_turn_uses_injection_after_collaboration_probe_fails(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),
)
@@ -5670,7 +5889,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
set_dispatch_phase,
)
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))
agent.codex_config = SimpleNamespace(default_model=None)
agent.ensure_agent_session_id = Mock()
@@ -5713,7 +5932,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
agent.controller.get_codex_overrides.assert_called_once_with(request.context)
async def test_start_turn_writes_current_caller_env_script_for_reused_threads(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))
agent.codex_config = SimpleNamespace(default_model=None)
agent.ensure_agent_session_id = Mock()
@@ -5760,7 +5979,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("export AVIBE_NATIVE_SESSION_ID=thread-existing", script_text)
async def test_start_turn_uses_controller_codex_overrides(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.settings_manager = SimpleNamespace(
get_channel_settings=Mock(side_effect=AssertionError("Codex must use controller routing overrides"))
)
@@ -5804,7 +6023,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
def test_model_hub_filters_every_codex_effort_source_at_the_adapter_boundary(self):
from modules.agents.model_hub import ModelHubLaunch, bind_launch
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(),
model_hub_runtime=object(),
@@ -5876,7 +6095,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
def test_model_hub_keeps_supported_codex_effort_and_does_not_filter_direct(self):
from modules.agents.model_hub import ModelHubLaunch, bind_launch
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=(None, None, "high")),
model_hub_runtime=object(),
@@ -5907,7 +6126,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._resolve_codex_agent_settings(request)[2], "high")
async def test_start_turn_uses_codex_dm_user_effort_from_shared_overrides(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.settings_manager = SimpleNamespace(
get_channel_settings=Mock(side_effect=AssertionError("Codex must not read scope storage directly"))
)
@@ -5950,7 +6169,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
async def test_start_turn_uses_codex_agent_defaults_when_routing_selects_agent(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(
get_codex_overrides=Mock(return_value=("reviewer", None, None)),
)
@@ -6132,33 +6351,53 @@ class CodexTransportCommandTests(unittest.IsolatedAsyncioTestCase):
)
-class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
- """#561: a cached app-server whose spawn directory was deleted (and possibly
+class CodexGenerationAcquisitionTests(unittest.IsolatedAsyncioTestCase):
+ """Turns bind to the generation their launch spec needs, started on demand.
+
+ #561: an app-server whose spawn directory was deleted (and possibly
re-created at the same path) sits in a dead inode and fails every
- thread/start with "failed to load configuration"."""
+ thread/start with "failed to load configuration"; the inode is part of
+ the launch spec, so such a directory gets a new generation.
+ """
def _agent(self):
- agent = object.__new__(CodexAgent)
- agent._transports = {}
- agent._transport_locks = {}
- agent._transport_last_activity = {}
- agent._transport_cwd_inodes = {}
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_locks = {}
agent._session_mgr = SimpleNamespace(sessions_for_cwd=lambda cwd: [])
- agent.codex_config = SimpleNamespace(binary="codex", extra_args=[])
- agent._model_hub_catalog = None
- agent._model_hub_catalog_lock = asyncio.Lock()
- agent._model_hub_catalog_generation = 0
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=Mock(return_value=None),
+ has_pending_turn_start=Mock(return_value=False),
+ clear_session=Mock(),
+ )
+ agent.codex_config = SimpleNamespace(binary="codex-acquisition-fixture", extra_args=[])
agent.controller = SimpleNamespace(config=SimpleNamespace(codex=agent.codex_config))
- agent._runtime_ownership_snapshot_for_cwd = Mock(
- return_value=SimpleNamespace(blocks_transport_replacement=False)
+ self.ownership = SimpleNamespace(
+ blocks_transport_replacement=False,
+ blocks_dead_transport_replacement=False,
)
+
+ async def ownership(generations):
+ return tuple(self.ownership for _ in generations)
+
+ agent._ownership_snapshots = ownership
return agent
+ @staticmethod
+ def _fresh(**extra):
+ return SimpleNamespace(
+ is_initialized=True,
+ pid=2468,
+ start=AsyncMock(),
+ stop=AsyncMock(),
+ on_notification=Mock(),
+ on_server_request=Mock(),
+ **extra,
+ )
+
async def test_hfr_142_server_request_does_not_refresh_progress_activity(self):
"""HFR-142: protocol approval frames are not real Session progress."""
agent = self._agent()
- agent._transport_last_activity = {"/tmp/work": 0.0}
+ generation = install_codex_transport(agent, "/tmp/work", SimpleNamespace(), last_activity=0.0)
agent._session_last_activity = {}
with patch.object(_MODULE.time, "monotonic", return_value=1234.0):
@@ -6170,7 +6409,7 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(result, {"approved": True})
- self.assertEqual(agent._transport_last_activity["/tmp/work"], 0.0)
+ self.assertEqual(generation.runtime.last_activity, 0.0)
self.assertEqual(agent._session_last_activity, {})
async def test_request_user_input_returns_valid_empty_answers(self):
@@ -6218,9 +6457,11 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
{"itemId": "item-1"},
)
- def test_turn_start_refreshes_the_cwd_transport_clock(self):
+ def test_turn_start_refreshes_the_sessions_generation_clock(self):
agent = self._agent()
- agent._transport_last_activity = {"/tmp/work": 0.0}
+ generation = install_codex_transport(
+ agent, "/tmp/work", SimpleNamespace(), sessions={"session-1": "thread-1"}, last_activity=0.0
+ )
agent._session_last_activity = {"session-1": 0.0}
request = SimpleNamespace(
working_path="/tmp/work",
@@ -6233,50 +6474,33 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
request=request,
)
- self.assertEqual(agent._transport_last_activity, {"/tmp/work": 1234.0})
+ self.assertEqual(generation.runtime.last_activity, 1234.0)
self.assertEqual(agent._session_last_activity, {"session-1": 1234.0})
async def test_hfr_142_server_request_callback_does_not_create_progress(self):
- """HFR-142: the cwd-bound callback preserves the prior progress clock."""
- import tempfile
-
+ """HFR-142: the generation-bound callback preserves the prior progress clock."""
agent = self._agent()
captured = {}
with tempfile.TemporaryDirectory() as cwd:
- fresh = SimpleNamespace(
- is_initialized=True,
- start=AsyncMock(),
- on_notification=Mock(),
- on_server_request=Mock(side_effect=lambda cb: captured.update(cb=cb)),
- )
+ fresh = self._fresh()
+ fresh.on_server_request = Mock(side_effect=lambda cb: captured.update(cb=cb))
with patch.object(_MODULE, "CodexTransport", return_value=fresh):
- await agent._get_or_create_transport(cwd)
+ binding = await agent._acquire_generation(cwd)
self.assertIn("cb", captured)
- before = agent._transport_last_activity[cwd]
+ before = binding.generation.runtime.last_activity
with patch.object(_MODULE.time, "monotonic", return_value=999.0):
result = await captured["cb"](1, "item/fileChange/requestApproval", {"itemId": "x"})
self.assertEqual(result, {"approved": True})
- self.assertEqual(agent._transport_last_activity[cwd], before)
-
- async def test_get_or_create_transport_moves_app_server_into_agent_cgroup(self):
- import tempfile
+ self.assertEqual(binding.generation.runtime.last_activity, before)
+ async def test_acquire_moves_app_server_into_agent_cgroup(self):
agent = self._agent()
calls = []
- agent.controller._agent_resource_governor = SimpleNamespace(
- apply_to_pid=lambda pid, label="agent": calls.append((pid, label)) or True
- )
with tempfile.TemporaryDirectory() as cwd:
- fresh = SimpleNamespace(
- is_initialized=True,
- pid=2468,
- start=AsyncMock(),
- on_notification=Mock(),
- on_server_request=Mock(),
- )
+ fresh = self._fresh()
with (
patch.object(_MODULE, "CodexTransport", return_value=fresh),
patch.object(
@@ -6287,40 +6511,29 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
),
),
):
- result = await agent._get_or_create_transport(cwd)
+ binding = await agent._acquire_generation(cwd)
- self.assertIs(result, fresh)
+ self.assertIs(binding.generation.runtime.transport, fresh)
self.assertEqual(calls, [(2468, "codex app-server")])
- async def test_get_or_create_transport_launches_with_private_codex_helpers(self):
- import tempfile
-
+ async def test_acquire_launches_with_private_codex_helpers(self):
agent = self._agent()
agent.codex_config.binary = "/private/release/vendor/target/bin/codex"
managed_env = {"PATH": "/private/release/vendor/target/codex-path:/usr/bin"}
with tempfile.TemporaryDirectory() as cwd:
- fresh = SimpleNamespace(
- is_initialized=True,
- pid=2468,
- start=AsyncMock(),
- on_notification=Mock(),
- on_server_request=Mock(),
- )
with (
- patch.object(_MODULE, "CodexTransport", return_value=fresh) as constructor,
+ patch.object(_MODULE, "CodexTransport", return_value=self._fresh()) as constructor,
patch.object(
_MODULE,
"desktop_backend_subprocess_environment",
return_value=managed_env,
),
):
- await agent._get_or_create_transport(cwd)
+ await agent._acquire_generation(cwd)
self.assertEqual(constructor.call_args.kwargs["runtime_env"], managed_env)
async def test_model_hub_transport_preserves_private_codex_helpers(self):
- import tempfile
-
agent = self._agent()
agent.codex_config.binary = "/private/release/vendor/target/bin/codex"
managed_env = {
@@ -6331,18 +6544,10 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
channel="hub",
gateway_base_url="http://127.0.0.1:18443",
gateway_token="gateway-token",
- fingerprint="hub:test",
)
with tempfile.TemporaryDirectory() as cwd:
- fresh = SimpleNamespace(
- is_initialized=True,
- pid=2468,
- start=AsyncMock(),
- on_notification=Mock(),
- on_server_request=Mock(),
- )
with (
- patch.object(_MODULE, "CodexTransport", return_value=fresh) as constructor,
+ patch.object(_MODULE, "CodexTransport", return_value=self._fresh()) as constructor,
patch.object(
_MODULE,
"desktop_backend_subprocess_environment",
@@ -6353,7 +6558,7 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
return_value=_catalog_reference(Path(cwd) / "codex-hub-catalog.json"),
) as prepare_catalog,
):
- await agent._get_or_create_transport(cwd, launch)
+ await agent._acquire_generation(cwd, launch)
runtime_env = constructor.call_args.kwargs["runtime_env"]
self.assertEqual(runtime_env["PATH"], managed_env["PATH"])
@@ -6361,247 +6566,169 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("OPENAI_API_KEY", runtime_env)
prepare_catalog.assert_called_once_with(agent.codex_config.binary, None, None)
- async def test_cached_transport_evicted_when_cwd_inode_changes(self):
- import tempfile
+ async def test_cached_transport_reused_while_launch_inputs_are_unchanged(self):
+ agent = self._agent()
+ with tempfile.TemporaryDirectory() as cwd:
+ cached = self._fresh()
+ with patch.object(_MODULE, "CodexTransport", return_value=cached) as ctor:
+ first = await agent._acquire_generation(cwd)
+ await first.release()
+ second = await agent._acquire_generation(cwd)
+
+ self.assertIs(second.generation, first.generation)
+ cached.stop.assert_not_awaited()
+ ctor.assert_called_once()
+ async def test_replaced_cwd_inode_starts_a_new_generation(self):
agent = self._agent()
with tempfile.TemporaryDirectory() as cwd:
- stale = SimpleNamespace(is_initialized=True, stop=AsyncMock())
- agent._transports[cwd] = stale
- # Simulate "spawned in a directory that was since replaced": the
- # recorded spawn-time inode differs from the current one.
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino + 1
-
- fresh = SimpleNamespace(
- is_initialized=True,
- start=AsyncMock(),
- on_notification=Mock(),
- on_server_request=Mock(),
- )
- with patch.object(_MODULE, "CodexTransport", return_value=fresh):
- result = await agent._get_or_create_transport(cwd)
+ stale = self._fresh()
+ with patch.object(_MODULE, "CodexTransport", return_value=stale):
+ await (await agent._acquire_generation(cwd)).release()
+ inode = os.stat(cwd).st_ino
+ fresh = self._fresh()
+ with (
+ patch.object(_MODULE, "CodexTransport", return_value=fresh),
+ patch.object(CodexAgent, "_cwd_inode", staticmethod(lambda _cwd: inode + 1)),
+ ):
+ binding = await agent._acquire_generation(cwd)
+ await agent._units[cwd].settled()
- stale.stop.assert_awaited_once()
- self.assertIs(result, fresh)
+ self.assertIs(binding.generation.runtime.transport, fresh)
fresh.start.assert_awaited_once()
- # The new spawn re-records the CURRENT inode.
- self.assertEqual(agent._transport_cwd_inodes[cwd], os.stat(cwd).st_ino)
-
- async def test_stale_cwd_preserves_transport_with_durable_native_owner(self):
- import tempfile
+ # The idle predecessor stops once the new one serves.
+ stale.stop.assert_awaited_once()
+ async def test_replaced_cwd_keeps_a_predecessor_with_a_durable_owner(self):
agent = self._agent()
with tempfile.TemporaryDirectory() as cwd:
- stale = SimpleNamespace(is_initialized=True, stop=AsyncMock())
- agent._transports[cwd] = stale
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino + 1
- agent._runtime_ownership_snapshot_for_cwd = Mock(
- return_value=SimpleNamespace(blocks_transport_replacement=True)
- )
-
- with self.assertRaisesRegex(RuntimeError, "durable owner"):
- await agent._get_or_create_transport(cwd)
+ stale = self._fresh()
+ with patch.object(_MODULE, "CodexTransport", return_value=stale):
+ previous = await agent._acquire_generation(cwd)
+ await previous.release()
+ self.ownership.blocks_transport_replacement = True
+ fresh = self._fresh()
+ inode = os.stat(cwd).st_ino
+ with (
+ patch.object(_MODULE, "CodexTransport", return_value=fresh),
+ patch.object(CodexAgent, "_cwd_inode", staticmethod(lambda _cwd: inode + 1)),
+ ):
+ binding = await agent._acquire_generation(cwd)
+ self.assertIs(binding.generation.runtime.transport, fresh)
stale.stop.assert_not_awaited()
- self.assertIs(agent._transports[cwd], stale)
+ self.assertIn(previous.generation, agent._units[cwd].generations)
+ self.assertTrue(previous.generation.retiring)
async def test_hfr_473_dead_transport_restarts_past_stale_turn_ownership(self):
- import tempfile
-
agent = self._agent()
with tempfile.TemporaryDirectory() as cwd:
dead = SimpleNamespace(
is_initialized=False,
is_alive=False,
has_pending_notifications=False,
- runtime_fingerprint="direct",
stop=AsyncMock(),
)
- agent._transports[cwd] = dead
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
- agent._runtime_ownership_snapshot_for_cwd = Mock(
- return_value=SimpleNamespace(
- blocks_transport_replacement=True,
- blocks_dead_transport_replacement=False,
- )
- )
+ self.ownership.blocks_transport_replacement = True
agent._session_mgr = SimpleNamespace(
sessions_for_cwd=Mock(return_value=["session-1"]),
invalidate_thread=Mock(),
)
- agent._turn_registry = SimpleNamespace(
- get_active_turn=Mock(return_value="turn-from-dead-generation"),
- has_pending_turn_start=Mock(return_value=False),
- clear_session=Mock(),
- )
+ agent._turn_registry.get_active_turn = Mock(return_value="turn-from-dead-generation")
agent._clear_thread_developer_instructions = Mock()
- fresh = SimpleNamespace(
- is_initialized=True,
- pid=2468,
- start=AsyncMock(),
- on_notification=Mock(),
- on_server_request=Mock(),
- )
+ install_codex_transport(agent, cwd, dead, sessions={"session-1": "thread-1"})
+ fresh = self._fresh()
with patch.object(_MODULE, "CodexTransport", return_value=fresh):
- result = await agent._get_or_create_transport(cwd)
+ binding = await agent._acquire_generation(cwd)
+ await agent._units[cwd].settled()
- self.assertIs(result, fresh)
+ self.assertIs(binding.generation.runtime.transport, fresh)
dead.stop.assert_awaited_once()
fresh.start.assert_awaited_once()
agent._session_mgr.invalidate_thread.assert_called_once_with("session-1")
agent._turn_registry.clear_session.assert_called_once_with("session-1")
- async def test_dead_transport_preserves_generation_with_active_activity_owner(self):
- import tempfile
-
+ async def test_dead_transport_with_an_activity_owner_never_holds_new_turns(self):
agent = self._agent()
with tempfile.TemporaryDirectory() as cwd:
dead = SimpleNamespace(
is_initialized=False,
is_alive=False,
has_pending_notifications=False,
- runtime_fingerprint="direct",
stop=AsyncMock(),
)
- agent._transports[cwd] = dead
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
- agent._runtime_ownership_snapshot_for_cwd = Mock(
- return_value=SimpleNamespace(
- blocks_transport_replacement=True,
- blocks_dead_transport_replacement=True,
- )
- )
+ self.ownership.blocks_transport_replacement = True
+ self.ownership.blocks_dead_transport_replacement = True
+ dead_generation = install_codex_transport(agent, cwd, dead)
+ fresh = self._fresh()
- with self.assertRaisesRegex(RuntimeError, "durable owner"):
- await agent._get_or_create_transport(cwd)
+ with patch.object(_MODULE, "CodexTransport", return_value=fresh):
+ binding = await agent._acquire_generation(cwd)
+ self.assertIs(binding.generation.runtime.transport, fresh)
dead.stop.assert_not_awaited()
- self.assertIs(agent._transports[cwd], dead)
-
- async def test_runtime_change_preserves_transport_with_pid_run_owner(self):
- import tempfile
+ self.assertIn(dead_generation, agent._units[cwd].generations)
+ async def test_runtime_change_keeps_a_predecessor_with_a_pid_run_owner(self):
agent = self._agent()
with tempfile.TemporaryDirectory() as cwd:
- existing = SimpleNamespace(
- is_initialized=True,
- runtime_fingerprint="direct",
- stop=AsyncMock(),
- )
- agent._transports[cwd] = existing
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
- agent._runtime_ownership_snapshot_for_cwd = Mock(
- return_value=SimpleNamespace(blocks_transport_replacement=True)
- )
+ existing = self._fresh()
+ with patch.object(_MODULE, "CodexTransport", return_value=existing):
+ previous = await agent._acquire_generation(cwd)
+ await previous.release()
+ self.ownership.blocks_transport_replacement = True
launch = SimpleNamespace(
channel="hub",
- fingerprint="hub:replacement",
gateway_base_url="http://127.0.0.1:8317",
gateway_token="ephemeral-token",
)
- agent._model_hub_catalog = _catalog_reference(Path(cwd) / "codex-hub-catalog.json")
+ fresh = self._fresh()
- with patch(
- "vibe.backend_model_catalog.prepare_codex_hub_catalog",
- ) as prepare_catalog:
- with self.assertRaisesRegex(RuntimeError, "durable owner"):
- await agent._get_or_create_transport(cwd, launch)
+ with (
+ patch.object(_MODULE, "CodexTransport", return_value=fresh),
+ patch(
+ "vibe.backend_model_catalog.prepare_codex_hub_catalog",
+ return_value=_catalog_reference(Path(cwd) / "codex-hub-catalog.json"),
+ ),
+ ):
+ binding = await agent._acquire_generation(cwd, launch)
- prepare_catalog.assert_not_called()
+ self.assertIs(binding.generation.runtime.transport, fresh)
existing.stop.assert_not_awaited()
- self.assertIs(agent._transports[cwd], existing)
-
- async def test_runtime_change_wait_for_active_neighbour_is_bounded(self):
- """#2148: a Hub runtime change never waits forever on another Session's turn."""
- for releases in (False, True):
- with self.subTest(releases=releases):
- agent = self._agent()
- with tempfile.TemporaryDirectory() as cwd:
- existing = SimpleNamespace(
- is_initialized=True,
- is_alive=True,
- runtime_fingerprint="direct",
- stop=AsyncMock(),
- )
- agent._transports[cwd] = existing
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
- agent._session_mgr = SimpleNamespace(
- sessions_for_cwd=Mock(return_value=["long-job"]),
- invalidate_thread=Mock(),
- )
- active = {"long-job": "turn-running"}
- agent._turn_registry = SimpleNamespace(
- get_active_turn=lambda base_session_id: active.get(base_session_id),
- has_pending_turn_start=lambda _base_session_id: False,
- clear_session=Mock(),
- )
- agent._clear_thread_developer_instructions = Mock()
- launch = SimpleNamespace(
- channel="hub",
- fingerprint="hub:replacement",
- gateway_base_url="http://127.0.0.1:8317",
- gateway_token="ephemeral-token",
- )
- agent._model_hub_catalog = _catalog_reference(Path(cwd) / "codex-hub-catalog.json")
- fresh = SimpleNamespace(
- is_initialized=True,
- runtime_fingerprint="hub:replacement",
- start=AsyncMock(),
- on_notification=Mock(),
- on_server_request=Mock(),
- )
- if releases:
- asyncio.get_running_loop().call_later(0.1, active.clear)
-
- with (
- patch.object(_MODULE, "_RUNTIME_CHANGE_WAIT_SECONDS", 0.3),
- patch.object(_MODULE, "CodexTransport", return_value=fresh),
- patch(
- "modules.agents.model_hub.build_codex_hub_launch",
- return_value=([], {}),
- ),
- ):
- acquire = agent._get_or_create_transport(cwd, launch)
- if releases:
- result = await asyncio.wait_for(acquire, timeout=2)
- else:
- with self.assertRaises(_MODULE.CodexRuntimeChangeBlockedError):
- await asyncio.wait_for(acquire, timeout=2)
-
- if releases:
- self.assertIs(result, fresh)
- existing.stop.assert_awaited_once()
- else:
- existing.stop.assert_not_awaited()
- self.assertIs(agent._transports[cwd], existing)
- agent._session_mgr.invalidate_thread.assert_not_called()
- self.assertEqual(active, {"long-job": "turn-running"})
+ self.assertTrue(previous.generation.retiring)
- async def test_runtime_config_switches_binary_without_catalog_export(self):
+ async def test_renewal_switches_binary_without_catalog_export(self):
agent = self._agent()
- previous_catalog = _catalog_reference("/runtime/codex-old.json")
- agent._model_hub_catalog = previous_catalog
+ transport = SimpleNamespace(stop=AsyncMock())
+ install_codex_transport(agent, "/repo", transport)
next_config = SimpleNamespace(binary="/opt/codex-next", extra_args=[])
- agent.refresh_auth_state = AsyncMock()
with patch(
"vibe.backend_model_catalog.prepare_codex_hub_catalog",
side_effect=RuntimeError("catalog export must not run"),
) as prepare_catalog:
- await agent.refresh_runtime_config(next_config)
+ await agent.renew_runtime(next_config)
prepare_catalog.assert_not_called()
+ transport.stop.assert_not_awaited()
self.assertIs(agent.codex_config, next_config)
self.assertIs(agent.controller.config.codex, next_config)
- self.assertIsNone(agent._model_hub_catalog)
- self.assertEqual(agent._model_hub_catalog_generation, 1)
- agent.refresh_auth_state.assert_awaited_once_with()
+ self.assertEqual(agent._runtime_epoch, 1)
+
+ async def test_plain_config_save_adopts_config_without_renewing(self):
+ agent = self._agent()
+ next_config = SimpleNamespace(binary=agent.codex_config.binary, extra_args=[], idle_timeout_seconds=60)
- async def test_runtime_config_same_binary_invalidates_prepared_catalog(self):
+ await agent.renew_runtime(next_config, config_save=True)
+
+ self.assertIs(agent.codex_config, next_config)
+ self.assertEqual(agent._runtime_epoch, 0)
+
+ async def test_runtime_config_refresh_stops_everything_without_catalog_export(self):
agent = self._agent()
previous_catalog = _catalog_reference("/runtime/codex-old.json")
- agent._model_hub_catalog = previous_catalog
+ agent._model_hub_catalogs[("old", "models")] = previous_catalog
agent.refresh_auth_state = AsyncMock()
next_config = SimpleNamespace(binary=agent.codex_config.binary, extra_args=["--next"])
@@ -6613,29 +6740,27 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
prepare_catalog.assert_not_called()
self.assertIs(agent.codex_config, next_config)
- self.assertIsNone(agent._model_hub_catalog)
- self.assertEqual(agent._model_hub_catalog_generation, 1)
+ self.assertEqual(dict(agent._model_hub_catalogs), {})
agent.refresh_auth_state.assert_awaited_once_with()
- async def test_model_hub_catalog_invalidation_preserves_direct_transports(self):
+ async def test_model_hub_catalog_adoption_preserves_running_transports(self):
agent = self._agent()
transport = SimpleNamespace(stop=AsyncMock())
- agent._transports["/repo"] = transport
- agent._model_hub_catalog = _catalog_reference("/runtime/codex-old.json")
+ install_codex_transport(agent, "/repo", transport)
+ agent._model_hub_catalogs[("old", "models")] = _catalog_reference("/runtime/codex-old.json")
- await agent.invalidate_model_hub_runtime()
+ await agent.adopt_model_hub_catalog()
- self.assertIsNone(agent._model_hub_catalog)
- self.assertEqual(agent._model_hub_catalog_generation, 1)
+ self.assertEqual(dict(agent._model_hub_catalogs), {})
transport.stop.assert_not_awaited()
+ self.assertIs(codex_transports(agent)["/repo"], transport)
- async def test_startup_catalog_preparation_cannot_overwrite_new_runtime_generation(self):
+ async def test_catalog_prepared_for_a_previous_binary_stays_keyed_to_it(self):
agent = self._agent()
previous_config = agent.codex_config
previous_catalog = _catalog_reference("/runtime/codex-old.json")
next_catalog = _catalog_reference("/runtime/codex-new.json")
next_config = SimpleNamespace(binary="/opt/codex-next", extra_args=[])
- agent.refresh_auth_state = AsyncMock()
previous_started = threading.Event()
release_previous = threading.Event()
calls = []
@@ -6654,12 +6779,10 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
):
startup = asyncio.create_task(agent.prepare_model_hub_runtime())
self.assertTrue(await asyncio.to_thread(previous_started.wait, 1))
- await agent.refresh_runtime_config(next_config)
- self.assertIs(agent.codex_config, next_config)
- self.assertIsNone(agent._model_hub_catalog)
+ await agent.renew_runtime(next_config)
release_previous.set()
- with self.assertRaises(_MODULE.CodexModelHubCatalogUnavailableError):
- await startup
+ # The turn that asked first keeps a catalog for the binary it captured.
+ self.assertIs(await startup, previous_catalog)
recovered = await agent.prepare_model_hub_runtime()
self.assertEqual(
@@ -6669,9 +6792,7 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
(next_config.binary, None, None),
],
)
- self.assertIs(agent.codex_config, next_config)
- self.assertEqual(agent._model_hub_catalog, next_catalog)
- self.assertEqual(recovered, next_catalog)
+ self.assertIs(recovered, next_catalog)
async def test_model_hub_catalog_preparation_retries_after_transient_failure(self):
agent = self._agent()
@@ -6683,35 +6804,25 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
) as prepare_catalog:
with self.assertRaises(_MODULE.CodexModelHubCatalogUnavailableError):
await agent.prepare_model_hub_runtime()
- self.assertIsNone(agent._model_hub_catalog)
+ self.assertEqual(dict(agent._model_hub_catalogs), {})
recovered = await agent.prepare_model_hub_runtime()
self.assertEqual(recovered, catalog)
- self.assertEqual(agent._model_hub_catalog, catalog)
+ self.assertEqual(list(agent._model_hub_catalogs.values()), [catalog])
self.assertEqual(prepare_catalog.call_count, 2)
async def test_missing_prepared_hub_catalog_preserves_existing_transport_and_threads(self):
agent = self._agent()
with tempfile.TemporaryDirectory() as cwd:
- existing = SimpleNamespace(
- is_initialized=True,
- runtime_fingerprint="direct",
- stop=AsyncMock(),
- )
- agent._transports[cwd] = existing
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
+ existing = SimpleNamespace(is_initialized=True, stop=AsyncMock())
+ install_codex_transport(agent, cwd, existing, sessions={"session-1": "thread-1"})
agent._session_mgr = SimpleNamespace(
sessions_for_cwd=Mock(return_value=["session-1"]),
invalidate_thread=Mock(),
)
- agent._turn_registry = SimpleNamespace(
- clear_session=Mock(),
- get_active_turn=Mock(return_value=None),
- )
agent._clear_thread_developer_instructions = Mock()
launch = SimpleNamespace(
channel="hub",
- fingerprint="hub:replacement",
gateway_base_url="http://127.0.0.1:8317",
gateway_token="ephemeral-token",
)
@@ -6721,7 +6832,7 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
side_effect=RuntimeError("transient export failure"),
) as prepare_catalog:
with self.assertRaises(_MODULE.CodexModelHubCatalogUnavailableError):
- await agent._get_or_create_transport(cwd, launch)
+ await agent._acquire_generation(cwd, launch)
prepare_catalog.assert_called_once_with(
agent.codex_config.binary,
@@ -6729,89 +6840,43 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
None,
)
existing.stop.assert_not_awaited()
- self.assertIs(agent._transports[cwd], existing)
+ self.assertIs(codex_transports(agent)[cwd], existing)
+ self.assertIs(agent.transport_for_session("session-1"), existing)
agent._session_mgr.invalidate_thread.assert_not_called()
agent._turn_registry.clear_session.assert_not_called()
- async def test_stale_transport_stop_failure_retains_exact_generation(self):
- import tempfile
-
+ async def test_predecessor_stop_failure_retains_its_exact_generation(self):
agent = self._agent()
activation = RuntimeActivationRegistry()
agent.controller.runtime_activation = activation
with tempfile.TemporaryDirectory() as cwd:
observed_current = []
- stale = SimpleNamespace(is_initialized=True)
- agent._transports[cwd] = stale
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino + 1
- identity = agent._attach_transport_activation(cwd, stale)
+ stale = self._fresh()
+ with patch.object(_MODULE, "CodexTransport", return_value=stale):
+ previous = await agent._acquire_generation(cwd)
+ await previous.release()
+ identity = previous.generation.runtime.activation
async def stop_stale():
observed_current.append(activation.is_current(identity))
raise RuntimeError("stop failed")
stale.stop = stop_stale
-
- with self.assertRaisesRegex(RuntimeError, "stop failed"):
- await agent._get_or_create_transport(cwd)
+ inode = os.stat(cwd).st_ino
+ with (
+ patch.object(_MODULE, "CodexTransport", return_value=self._fresh()),
+ patch.object(CodexAgent, "_cwd_inode", staticmethod(lambda _cwd: inode + 1)),
+ ):
+ await agent._acquire_generation(cwd)
+ await agent._units[cwd].settled()
self.assertEqual(observed_current, [False])
- self.assertIs(agent._transports[cwd], stale)
- self.assertIs(activation.current("codex", cwd), identity)
-
- async def test_cached_transport_reused_while_cwd_unchanged(self):
- import tempfile
-
- agent = self._agent()
- with tempfile.TemporaryDirectory() as cwd:
- cached = SimpleNamespace(is_initialized=True, stop=AsyncMock())
- agent._transports[cwd] = cached
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
-
- with patch.object(_MODULE, "CodexTransport") as ctor:
- result = await agent._get_or_create_transport(cwd)
-
- self.assertIs(result, cached)
- cached.stop.assert_not_awaited()
- ctor.assert_not_called()
-
- async def test_probe_validation_does_not_replace_incompatible_runtime(self):
- import tempfile
-
- agent = self._agent()
- with tempfile.TemporaryDirectory() as cwd:
- cached = SimpleNamespace(
- is_initialized=True,
- runtime_fingerprint="hub:openai/gpt-5.4-mini",
- stop=AsyncMock(),
- )
- agent._transports[cwd] = cached
- agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
-
- with self.assertRaises(CodexConnectionProbeRuntimeMismatchError):
- await agent._get_or_create_transport(
- cwd,
- allow_runtime_replacement=False,
- )
-
- cached.stop.assert_not_awaited()
- self.assertIs(agent._transports[cwd], cached)
-
- async def test_untracked_legacy_entry_reuses_without_inode(self):
- import tempfile
-
- agent = self._agent()
- with tempfile.TemporaryDirectory() as cwd:
- cached = SimpleNamespace(is_initialized=True, stop=AsyncMock())
- agent._transports[cwd] = cached
- # No recorded inode (legacy entry) -> reuse as before, no eviction.
- with patch.object(_MODULE, "CodexTransport") as ctor:
- result = await agent._get_or_create_transport(cwd)
- self.assertIs(result, cached)
- ctor.assert_not_called()
+ self.assertIn(previous.generation, agent._units[cwd].generations)
+ self.assertTrue(previous.generation.closed)
+ self.assertTrue(activation.is_current(identity))
def test_config_load_failure_is_recoverable(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
err = RuntimeError(
"Codex RPC error: {'code': -32600, 'message': "
"'failed to load configuration: No such file or directory (os error 2)'}"
@@ -6842,7 +6907,7 @@ class CodexPromptSnapshotRecoveryTests(unittest.IsolatedAsyncioTestCase):
return self._agent()
def _agent(self):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
def persist(*_args, **kwargs):
self.marker.clear()
diff --git a/tests/test_codex_catalog_retention.py b/tests/test_codex_catalog_retention.py
index 0e86a6d6e..aa97bb81a 100644
--- a/tests/test_codex_catalog_retention.py
+++ b/tests/test_codex_catalog_retention.py
@@ -17,9 +17,10 @@ from unittest.mock import AsyncMock
import pytest
from config import paths
-from modules.agents.codex.agent import CodexAgent, CodexModelHubCatalogUnavailableError
+from modules.agents.codex.agent import CodexAgent
from modules.agents.codex.transport import CodexTransport
from vibe import backend_model_catalog as catalogs
+from tests.codex_generation_support import init_generation_state
def publish(slug):
@@ -38,10 +39,7 @@ def churn(count=6):
def agent():
- value = CodexAgent.__new__(CodexAgent)
- value._model_hub_catalog = None
- value._model_hub_catalog_lock = asyncio.Lock()
- value._model_hub_catalog_generation = 0
+ value = init_generation_state(object.__new__(CodexAgent))
value.codex_config = SimpleNamespace(binary="fixture-codex", extra_args=[])
value.controller = SimpleNamespace()
return value
@@ -215,16 +213,16 @@ async def test_cache_invalidation_during_pending_launch_keeps_local_reference(mo
monkeypatch.setattr(catalogs, "_export_codex_bundled_catalog", lambda *_: b'{"models":[{"slug":"first"}]}')
starting = (await value.prepare_model_hub_runtime()).retain()
path = starting.path
- await value.invalidate_model_hub_runtime()
+ await value.adopt_model_hub_catalog()
churn()
- assert value._model_hub_catalog is None and path in retained()
+ assert not value._model_hub_catalogs and path in retained()
starting.close()
churn()
assert len(retained()) <= 1
@pytest.mark.asyncio
-async def test_invalidated_export_releases_unpublished_pin(monkeypatch):
+async def test_export_finishing_after_adoption_stays_releasable(monkeypatch):
value = agent()
entered = threading.Event()
released = threading.Event()
@@ -237,12 +235,13 @@ async def test_invalidated_export_releases_unpublished_pin(monkeypatch):
monkeypatch.setattr(catalogs, "_export_codex_bundled_catalog", export)
preparation = asyncio.create_task(value.prepare_model_hub_runtime())
assert await asyncio.to_thread(entered.wait, 2)
- await value.invalidate_model_hub_runtime()
+ await value.adopt_model_hub_catalog()
released.set()
- with pytest.raises(CodexModelHubCatalogUnavailableError, match="generation changed"):
- await preparation
- assert value._model_hub_catalog is None
- del preparation
+ # Keyed to the snapshot it was prepared for, the result is still valid.
+ prepared = await preparation
+ assert list(value._model_hub_catalogs.values()) == [prepared]
+ await value.adopt_model_hub_catalog()
+ del preparation, prepared
churn()
assert len(retained()) <= 1
@@ -274,7 +273,7 @@ async def test_cancelled_export_closes_its_eventual_result(monkeypatch):
await preparation
finish.set()
await asyncio.wait_for(closed.wait(), 5)
- assert value._model_hub_catalog is None
+ assert not value._model_hub_catalogs
churn()
assert len(retained()) <= 1
@@ -295,9 +294,6 @@ for line in sys.stdin:
@pytest.mark.asyncio
async def test_agent_launch_keeps_pin_across_invalidation_and_reuses_transport(monkeypatch, tmp_path):
value = agent()
- value._transports = {}
- value._transport_locks = {}
- value._transport_cwd_inodes = {}
initialized = asyncio.Event()
finish = asyncio.Event()
spawn = asyncio.create_subprocess_exec
@@ -319,28 +315,31 @@ async def test_agent_launch_keeps_pin_across_invalidation_and_reuses_transport(m
# An extra argument must not override the path whose lifetime we protect.
value.codex_config.extra_args = ["-c", 'model_catalog_json="/obsolete/catalog.json"']
launch = SimpleNamespace(
- channel="hub", fingerprint="hub:test",
+ channel="hub",
gateway_base_url="http://127.0.0.1:1", gateway_token="fixture-only",
)
- starting = asyncio.create_task(value._get_or_create_transport(str(tmp_path), launch))
+ starting = asyncio.create_task(value._acquire_generation(str(tmp_path), launch))
try:
await asyncio.wait_for(initialized.wait(), 5)
- path = value._model_hub_catalog.path
+ path = next(iter(value._model_hub_catalogs.values())).path
assert argv[-1] == f"model_catalog_json={json.dumps(str(path))}"
- await value.invalidate_model_hub_runtime()
+ await value.adopt_model_hub_catalog()
churn()
assert path in retained()
finish.set()
- transport = await starting
- assert (await value._get_or_create_transport(str(tmp_path), launch)) is transport
+ transport = (await starting).generation.runtime.transport
+ # Same catalog content, same spec: the running generation is reused.
+ reused = await value._acquire_generation(str(tmp_path), launch)
+ assert reused.generation.runtime.transport is transport
assert path in retained()
+ await value.adopt_model_hub_catalog()
await transport.stop()
await transport._catalog_exit_task
churn()
assert len(retained()) <= 1
finally:
finish.set()
- transport = await starting
+ transport = (await starting).generation.runtime.transport
await transport.stop()
diff --git a/tests/test_codex_config.py b/tests/test_codex_config.py
index b34145500..7a53bb7bd 100644
--- a/tests/test_codex_config.py
+++ b/tests/test_codex_config.py
@@ -14,6 +14,8 @@ import json
import sys
from pathlib import Path
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
try:
@@ -567,3 +569,40 @@ def test_apply_api_key_restore_falls_back_when_provider_gone(tmp_path: Path) ->
toml = config_path.read_text(encoding="utf-8")
assert 'model_provider = "openai-managed"' in toml
assert 'base_url = "https://relay.example/v1"' in toml
+
+
+def _id_token(**claims: object) -> str:
+ import base64
+
+ payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=")
+ return f"e30.{payload}.signature"
+
+
+def _credential_identity(tmp_path: Path, name: str, tokens: dict) -> str:
+ codex_home = tmp_path / name
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(
+ json.dumps({"auth_mode": "chatgpt", "tokens": tokens}),
+ encoding="utf-8",
+ )
+ return codex_config.codex_credential_identity(codex_home)
+
+
[email protected]("claim", ["sub", "email"])
+def test_credential_identity_tells_legacy_oauth_accounts_apart_but_not_their_refreshes(
+ tmp_path: Path, claim: str
+) -> None:
+ """RUNTIME-GEN-015: an id_token-only bag names no account id, yet an account switch still needs a new process.
+
+ A token refresh keeps the identity, so the running app-server is reused.
+ """
+ alice = _credential_identity(tmp_path, "alice", {"id_token": _id_token(**{claim: "alice"}, iat=1)})
+ refreshed = _credential_identity(
+ tmp_path,
+ "alice-refreshed",
+ {"id_token": _id_token(**{claim: "alice"}, iat=2), "access_token": "access-2", "refresh_token": "refresh-2"},
+ )
+ bob = _credential_identity(tmp_path, "bob", {"id_token": _id_token(**{claim: "bob"}, iat=1)})
+
+ assert alice != bob
+ assert alice == refreshed
diff --git a/tests/test_codex_native_prompt_baseline.py b/tests/test_codex_native_prompt_baseline.py
index 16f5d1855..ec2545417 100644
--- a/tests/test_codex_native_prompt_baseline.py
+++ b/tests/test_codex_native_prompt_baseline.py
@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, Mock, call, patch
import pytest
from modules.agents.codex.agent import CodexAgent, CodexPromptRefreshUnavailableError
+from tests.codex_generation_support import acquire_returning, init_generation_state
PROMPT_A = "完整的 Avibe baseline A.\nKeep the user's preferences."
@@ -27,7 +28,7 @@ def _request():
def _agent(marker):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))
agent.codex_config = SimpleNamespace(default_model=None)
native_binding = {}
@@ -191,11 +192,10 @@ async def test_dispatch_renders_once_even_for_empty_prompt_and_transport_recover
agent._turn_registry.remember_request = Mock()
agent._turn_registry.get_active_turn = Mock(return_value=None)
agent._delete_ack = AsyncMock()
- agent._touch_transport_activity = Mock()
transport = _transport()
fresh = _transport()
- agent._get_or_create_transport = AsyncMock(side_effect=[transport, fresh])
- agent._drop_transport_after_failure = AsyncMock(return_value=True)
+ agent._acquire_generation = acquire_returning(agent, transport, fresh, session=request.base_session_id)
+ agent._drop_generation_after_failure = AsyncMock(return_value=True)
agent._refresh_thread_developer_instructions_if_needed = AsyncMock()
agent._bind_runtime_agent_session_id = Mock()
agent._build_thread_developer_instructions = AsyncMock(return_value=prompt)
diff --git a/tests/test_codex_prompt_delivery_contract.py b/tests/test_codex_prompt_delivery_contract.py
index dfa994f81..28443fd05 100644
--- a/tests/test_codex_prompt_delivery_contract.py
+++ b/tests/test_codex_prompt_delivery_contract.py
@@ -22,6 +22,7 @@ from core.prompt_registry import prompt_text
from modules.agents.codex.agent import CodexAgent
from modules.agents.codex.transport import CodexTransport
from modules.im import MessageContext
+from tests.codex_generation_support import init_generation_state
BINARY = os.environ.get("CODEX_PROMPT_CONTRACT_BINARY")
@@ -35,7 +36,7 @@ PROMPT = "\n\n".join(
def _agent(marker):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, MODEL, "high")))
agent.codex_config = SimpleNamespace(default_model=None)
diff --git a/tests/test_codex_request_routing.py b/tests/test_codex_request_routing.py
index 085d68e8f..133fb1958 100644
--- a/tests/test_codex_request_routing.py
+++ b/tests/test_codex_request_routing.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import inspect
import json
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
@@ -37,6 +38,7 @@ from tests.scenario_harness.model_hub import (
unlisted_model_copy,
unlisted_model_runtime,
)
+from tests.codex_generation_support import init_generation_state, install_codex_transport
METADATA = "x-codex-turn-metadata"
@@ -126,21 +128,21 @@ async def test_codex_shared_transport_routes_overlapping_aliases(runtime):
assert first.gateway_token == second.gateway_token
assert first.fingerprint == second.fingerprint
assert first.gateway_request_metadata != second.gateway_request_metadata
- cached = SimpleNamespace(is_initialized=True, runtime_fingerprint=first.fingerprint, stop=AsyncMock())
- agent = object.__new__(CodexAgent)
- agent._transports = {runtime.cwd: cached}
- agent._transport_locks = {}
- agent._transport_cwd_inodes = {}
- agent._transport_last_activity = {}
- agent._attach_transport_activation = Mock()
- agent._has_active_turns_for_cwd = Mock(return_value=True)
- agent._runtime_ownership_snapshot_for_cwd = Mock(
- return_value=SimpleNamespace(blocks_transport_replacement=True),
- )
- assert await asyncio.wait_for(agent._get_or_create_transport(runtime.cwd, second), 1) is cached
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent.codex_config = SimpleNamespace(binary="codex-routing-fixture", extra_args=[])
+ agent.controller = SimpleNamespace()
+ catalog = SimpleNamespace(path=Path(runtime.cwd) / "catalog.json", close=Mock())
+ catalog.retain = Mock(return_value=catalog)
+ agent.prepare_model_hub_runtime = AsyncMock(return_value=catalog)
+ first_spec = await agent._launch_spec(runtime.cwd, first)
+ second_spec = await agent._launch_spec(runtime.cwd, second)
+ # Per-turn routes ride on each request, so both aliases need one process.
+ assert first_spec.digest == second_spec.digest
+ cached = SimpleNamespace(is_initialized=True, stop=AsyncMock())
+ generation = install_codex_transport(agent, runtime.cwd, cached, digest=first_spec.digest)
+ binding = await asyncio.wait_for(agent._unit(runtime.cwd).acquire(second_spec), 1)
+ assert binding.generation is generation
cached.stop.assert_not_awaited()
- agent._has_active_turns_for_cwd.assert_not_called()
- agent._runtime_ownership_snapshot_for_cwd.assert_not_called()
results = await asyncio.gather(_post(first), _post(second))
assert [status for status, _ in results] == [200, 200]
@@ -303,7 +305,7 @@ async def test_codex_adapter_keeps_request_metadata_on_compatibility_retry(runti
launch = await _launch(runtime, "adapter")
context = SimpleNamespace(platform_specific={})
bind_launch(context, launch)
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace()
agent._prompt_state_agent_session_id = Mock(return_value="session")
agent._resolve_codex_agent_settings = Mock(return_value=(None, launch.runtime_model, None, None))
@@ -349,20 +351,22 @@ async def test_codex_turn_on_an_unlisted_model_fails_once_with_the_shared_copy(t
base_session_id="session-1", working_path=str(tmp_path),
context=context, session_key="settings-1", ack_message_id=None,
)
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = controller
agent._session_locks = {}
agent._session_mgr = SimpleNamespace(set_session_key=Mock(), set_cwd=Mock())
agent.ensure_agent_session_id = Mock()
agent._bind_runtime_agent_session_id = Mock()
agent._resolve_codex_agent_settings = Mock(return_value=(None, UNLISTED_MODEL, None, None))
- agent._get_or_create_transport = AsyncMock()
+ # Acquisition is stubbed, so the launch load it alone consumes is too.
+ agent._launch_inputs = lambda cwd, *, hub_config=None: SimpleNamespace(hub_config=hub_config)
+ agent._acquire_generation = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())
await agent.handle_message(request)
- agent._get_or_create_transport.assert_not_awaited()
+ agent._acquire_generation.assert_not_awaited()
controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_not_awaited()
notify = controller.emit_agent_message.await_args_list[0]
assert notify.args[1:3] == ("notify", f"❌ {unlisted_model_copy('codex', language)}")
diff --git a/tests/test_codex_runtime_generations.py b/tests/test_codex_runtime_generations.py
new file mode 100644
index 000000000..c28050e08
--- /dev/null
+++ b/tests/test_codex_runtime_generations.py
@@ -0,0 +1,1377 @@
+"""RUNTIME-GEN-006, RUNTIME-GEN-010..018, and HFR-144: Codex app-server generations per working directory.
+
+The fake app-server enforces Codex's cross-process thread writer lock: a thread
+loaded in one process cannot be resumed in another until the first releases it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import itertools
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+import modules.agents.codex.agent as codex_agent_module
+from core.native_dispatch_phase import DISPATCH_PHASE_PREWRITE, set_dispatch_phase
+from core.handlers.model_hub.provenance import BoundedProvenanceStore, TurnCorrelationRegistry
+from core.runtime_activation import RuntimeActivationRegistry
+from core.session_activities import SessionActivityRegistry
+from core.runtime_ownership import RuntimeTargetOwnershipSnapshot, SessionRuntimeDisposition
+from modules.agents.codex.agent import CodexAgent
+from modules.agents.codex.session import CodexSessionManager
+from modules.agents.codex.transport import CodexRPCError
+from modules.agents.codex.turn_state import CodexTurnRegistry
+from modules.agents.model_hub import ModelHubLaunch
+from modules.agents.runtime_generations import RuntimeUnitStopping
+from modules.agents.service import AgentService
+from tests.codex_generation_support import init_generation_state
+from vibe.i18n import t as i18n_t
+
+
+CWD_NAME = "项目 work"
+
+
+class _FakeProcess:
+ def __init__(self):
+ self.returncode = None
+ self._exited = asyncio.Event()
+
+ def exit(self, code=0):
+ self.returncode = code
+ self._exited.set()
+
+ async def wait(self):
+ await self._exited.wait()
+ return self.returncode
+
+
+class FakeAppServer:
+ """One ``codex app-server`` process sharing a ``CODEX_HOME`` with its peers."""
+
+ writers: dict[str, "FakeAppServer"] = {}
+ started: list["FakeAppServer"] = []
+ # Awaited by every start before the server is up; it may raise.
+ on_start = None
+ # The next thread/resume loads its thread, then its answer is lost.
+ lose_next_resume = False
+ _ids = itertools.count(1)
+
+ def __init__(self, binary, cwd, extra_args=None, runtime_args=None, runtime_env=None, model_hub_catalog=None):
+ self.binary = binary
+ self.cwd = cwd
+ self.runtime_args = list(runtime_args or [])
+ self.runtime_env = runtime_env
+ self.loaded: set[str] = set()
+ self.active: dict[str, str] = {}
+ self.requests: list[tuple[str, dict]] = []
+ self.alive = False
+ self.stopped = False
+ self.pid = next(self._ids) + 40000
+ self._process = _FakeProcess()
+ self._notify = None
+ self._closed = asyncio.Event()
+ self.supports_turn_collaboration_mode = False
+ self.has_pending_notifications = False
+ self.refuse_interrupt = False
+ self.wedged = False
+
+ def on_notification(self, callback):
+ self._notify = callback
+
+ def on_server_request(self, callback):
+ self._server_request = callback
+
+ async def start(self):
+ FakeAppServer.started.append(self)
+ if FakeAppServer.on_start is not None:
+ await FakeAppServer.on_start(self)
+ self.alive = True
+
+ async def stop(self):
+ # Like the real transport, this ends the process even after its reader closed.
+ if self._process.returncode is not None:
+ return
+ self.alive = False
+ self.stopped = True
+ self._process.exit()
+ for thread_id in list(self.loaded):
+ self._release(thread_id)
+ self._closed.set()
+
+ async def wait_closed(self):
+ await self._closed.wait()
+
+ @property
+ def is_alive(self):
+ return self.alive
+
+ @property
+ def is_initialized(self):
+ return self.alive and not self.wedged
+
+ def _release(self, thread_id):
+ self.loaded.discard(thread_id)
+ if FakeAppServer.writers.get(thread_id) is self:
+ del FakeAppServer.writers[thread_id]
+
+ def _load(self, thread_id):
+ owner = FakeAppServer.writers.get(thread_id)
+ if owner is not None and owner is not self:
+ raise CodexRPCError({"code": -32600, "message": f"thread {thread_id} already has an active writer"})
+ FakeAppServer.writers[thread_id] = self
+ self.loaded.add(thread_id)
+
+ async def send_request(self, method, params):
+ self.requests.append((method, params))
+ if not self.alive:
+ raise ConnectionError("Codex app-server transport is not available")
+ if method == "thread/start":
+ thread_id = f"thread-{next(self._ids)}"
+ self._load(thread_id)
+ return {"thread": {"id": thread_id}}
+ if method == "thread/resume":
+ self._load(params["threadId"])
+ if FakeAppServer.lose_next_resume:
+ FakeAppServer.lose_next_resume = False
+ self.wedged = True
+ raise TimeoutError("Codex RPC thread/resume timed out after 120s")
+ return {"thread": {"id": params["threadId"]}}
+ if method == "thread/unsubscribe":
+ thread_id = params["threadId"]
+ if thread_id not in self.loaded:
+ return {"status": "notLoaded"}
+ self._release(thread_id)
+ asyncio.get_running_loop().call_soon(
+ lambda: asyncio.ensure_future(self._notify("thread/closed", {"threadId": thread_id}))
+ )
+ return {"status": "unsubscribed"}
+ if method == "thread/loaded/list":
+ return {"data": sorted(self.loaded)}
+ if method == "turn/start":
+ thread_id = params["threadId"]
+ assert thread_id in self.loaded, f"{thread_id} is not loaded in this process"
+ turn_id = f"turn-{next(self._ids)}"
+ self.active[thread_id] = turn_id
+ return {"turn": {"id": turn_id}}
+ if method == "turn/interrupt":
+ if self.refuse_interrupt:
+ raise CodexRPCError({"code": -32603, "message": "interrupt refused"})
+ self.active.pop(params["threadId"], None)
+ return {}
+ return {}
+
+ def close_reader(self):
+ """Stdout closes, but the process lives on and keeps its writer locks."""
+ self.alive = False
+
+ def exit(self):
+ for thread_id in list(self.loaded):
+ self._release(thread_id)
+ self._process.exit(-9)
+
+ async def complete(self, thread_id):
+ turn_id = self.active.pop(thread_id)
+ await self._notify(
+ "turn/completed",
+ {"threadId": thread_id, "turn": {"id": turn_id, "status": "completed"}},
+ )
+
+
+class _EventHandler:
+ def __init__(self, agent):
+ self.agent = agent
+ self.released = []
+
+ async def handle_notification(self, method, params, request):
+ if method == "turn/completed":
+ self.agent._turn_registry.pop_turn(params["turn"]["id"])
+
+ def clear_pending(self, turn_id):
+ state = self.agent._turn_registry.hide_turn(turn_id)
+ return state.request if state is not None else None
+
+ def _release_stream_turn(self, context):
+ self.released.append(context)
+
+ def snapshot_generated_images(self, *_args):
+ return None
+
+ def bind_generated_image_snapshot(self, *_args):
+ return None
+
+
[email protected](autouse=True)
+def fake_app_servers(monkeypatch):
+ FakeAppServer.writers = {}
+ FakeAppServer.started = []
+ FakeAppServer.on_start = None
+ FakeAppServer.lose_next_resume = False
+ monkeypatch.setattr(codex_agent_module, "CodexTransport", FakeAppServer)
+ return FakeAppServer
+
+
+class _Ownership:
+ """Durable state with no owner, so only live turns keep a generation busy."""
+
+ def snapshot_many(self, targets):
+ return tuple(
+ RuntimeTargetOwnershipSnapshot(
+ backend=target.backend,
+ resource_key=target.resource_key,
+ activity_runtime_keys=(),
+ sessions=(),
+ sessionless_active_activity_ids=(),
+ sessionless_fallback_run_ids=(),
+ disposition=SessionRuntimeDisposition.RECLAIMABLE,
+ )
+ for target in targets
+ )
+
+
+class _Router:
+ """Model Hub runtime router whose launch for each model a test chooses."""
+
+ def __init__(self):
+ self.launches = {}
+ self.scopes = []
+ self.retired = []
+
+ def snapshot(self):
+ return SimpleNamespace(agents={"codex": SimpleNamespace(models=[])})
+
+ async def resolve(self, backend, requested_model, *, process_scope=None, turn_id=None, config=None):
+ self.scopes.append((backend, process_scope))
+ return self.launches[requested_model]
+
+ def retire_process_scope(self, backend, process_scope, **_kwargs):
+ self.retired.append((backend, process_scope))
+
+
+def _launch(model, channel="direct", token=None):
+ hub = channel == "hub"
+ return ModelHubLaunch(
+ backend="codex",
+ channel=channel,
+ requested_model=model,
+ target_model=model,
+ runtime_model=model,
+ source_id="source-1" if channel != "direct" else None,
+ gateway_base_url="http://127.0.0.1:9/codex" if hub else None,
+ gateway_token=token if hub else None,
+ )
+
+
+def _agent(tmp_path, *, router=None):
+ agent = object.__new__(CodexAgent)
+ init_generation_state(agent)
+ agent.name = "codex"
+ service = SimpleNamespace(
+ mark_runtime_turn_started=Mock(),
+ force_end_runtime_work=AsyncMock(),
+ )
+ agent.controller = SimpleNamespace(
+ config=SimpleNamespace(language="en"),
+ model_hub_runtime=router,
+ runtime_activation=RuntimeActivationRegistry(),
+ runtime_ownership=_Ownership(),
+ agent_service=service,
+ get_codex_overrides=Mock(return_value=(None, None, None)),
+ )
+ agent.codex_config = SimpleNamespace(binary="codex-generation-fake", extra_args=[])
+ agent._registered_runtime = True
+ agent._session_mgr = CodexSessionManager()
+ agent._turn_registry = CodexTurnRegistry()
+ agent._event_handler = _EventHandler(agent)
+ agent._session_locks = {}
+ agent._session_last_activity = {}
+ agent._steer_reconciliation_targets = {}
+ agent._user_stopped_turn_ids = set()
+ agent._connection_probes = {}
+ agent._connection_probe_turns = {}
+ agent.sessions = SimpleNamespace(
+ get_agent_session_id=lambda *_args: None,
+ get_agent_session_runtime_marker=lambda *_args, **_kwargs: None,
+ clear_agent_session_mapping=Mock(),
+ )
+ agent.ensure_agent_session_id = Mock()
+ agent.bind_agent_session_id = Mock()
+ agent._reserved_native_session_id = Mock(return_value=None)
+ agent._delete_ack = AsyncMock()
+ agent._remove_ack_reaction = AsyncMock()
+ agent._build_thread_developer_instructions = AsyncMock(return_value=None)
+ agent._refresh_thread_developer_instructions_if_needed = AsyncMock()
+ agent._inject_caller_env_config = Mock(return_value=("", False))
+ agent._caller_env_for_request = Mock(return_value={})
+ agent._write_caller_env_script = Mock()
+ agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)
+ agent._record_model_hub_native_failure = AsyncMock(return_value=False)
+ # Resume binds the thread the previous turn created.
+ threads = {}
+
+ def remember(request, thread_id):
+ threads[request.base_session_id] = thread_id
+ return thread_id
+
+ agent.bind_agent_session_id = Mock(side_effect=remember)
+ agent.sessions.get_agent_session_id = lambda _key, base, _name: threads.get(base)
+ workdir = tmp_path / CWD_NAME
+ workdir.mkdir(exist_ok=True)
+ return agent, str(workdir)
+
+
+def _request(cwd, session, model="model-a"):
+ return SimpleNamespace(
+ context=SimpleNamespace(platform_specific={"agent_session_id": f"agent-{session}"}),
+ message="继续处理 café",
+ user_message="继续处理 café",
+ working_path=cwd,
+ base_session_id=session,
+ composite_session_id=f"avibe:{session}",
+ session_key=f"key-{session}",
+ ack_message_id=None,
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ vibe_agent_model=model,
+ vibe_agent_model_explicit=True,
+ vibe_agent_reasoning_effort=None,
+ vibe_agent_reasoning_effort_explicit=False,
+ vibe_agent_system_prompt=None,
+ files=None,
+ input_metadata=None,
+ )
+
+
+def _server_for(agent, session):
+ return agent.transport_for_session(session)
+
+
+async def _until(condition, *, timeout=1.0):
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeout
+ while not condition():
+ assert loop.time() < deadline, "condition not reached"
+ await asyncio.sleep(0.01)
+
+
+async def test_runtime_gen_006_disabling_codex_ends_every_app_server_and_admits_nothing(tmp_path, monkeypatch):
+ """RUNTIME-GEN-006: disabling Codex ends every app-server at once, a busy one included.
+
+ The core has already interrupted the backend's work with its own notice,
+ so the stop shows none. A turn that captured the agent before it left
+ routing fails visibly with the localized error and starts no process,
+ whether its directory has an app-server or not.
+ """
+ failures = AsyncMock()
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", failures)
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a")
+ agent, cwd = _agent(tmp_path, router=router)
+ elsewhere = tmp_path / "elsewhere"
+ elsewhere.mkdir()
+ await agent.handle_message(_request(cwd, "s1"))
+ busy = _server_for(agent, "s1")
+ await agent.handle_message(_request(str(elsewhere), "s2"))
+ idle = _server_for(agent, "s2")
+ await idle.complete(agent._session_mgr.get_thread_id("s2"))
+ started = len(FakeAppServer.started)
+ # One turn for a directory with no app-server yet is resolving its launch.
+ fresh = tmp_path / "fresh"
+ fresh.mkdir()
+ resolving, resolved = asyncio.Event(), asyncio.Event()
+ resolve = router.resolve
+ resolutions = []
+
+ async def slow_resolve(*args, **kwargs):
+ resolutions.append(args)
+ resolving.set()
+ await resolved.wait()
+ return await resolve(*args, **kwargs)
+
+ router.resolve = slow_resolve
+ in_flight = asyncio.create_task(agent.handle_message(_request(str(fresh), "s3")))
+ await asyncio.wait_for(resolving.wait(), 1)
+
+ await asyncio.wait_for(agent.shutdown_runtime(), 1)
+
+ assert busy.stopped and idle.stopped
+ assert not any(agent._runtimes.values())
+ agent.controller.agent_service.force_end_runtime_work.assert_not_awaited()
+ resolved.set()
+ await asyncio.wait_for(in_flight, 1)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s4")), 1)
+ assert [type(call.kwargs["cause"]) for call in failures.await_args_list] == [RuntimeUnitStopping] * 2
+ assert {call.kwargs["display_text"] for call in failures.await_args_list} == {
+ f"❌ {i18n_t('error.agentRuntimeRetired', 'en', agent='Codex')}"
+ }
+ assert len(FakeAppServer.started) == started
+ assert len(resolutions) == 1 # The late turn resolved no launch.
+
+
+async def test_runtime_gen_006_a_disable_whose_stop_fails_is_retried_until_the_app_server_is_gone(tmp_path):
+ """RUNTIME-GEN-006: a disable that leaves an app-server running fails, so the idle sweep retries it.
+
+ The agent is already out of routing, so the teardown is the only owner of
+ that process; a shutdown that returned normally would lose it.
+ """
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ server = _server_for(agent, "s1")
+ stop = server.stop
+ server.stop = AsyncMock(side_effect=RuntimeError("the child did not stop"))
+ service = AgentService(controller=SimpleNamespace())
+ attempts = []
+
+ async def disable():
+ attempts.append(len(attempts) + 1)
+ await agent.shutdown_runtime()
+
+ assert not await service.run_until_done("codex", disable)
+ assert server.alive
+
+ server.stop = stop
+ await service.retry_pending()
+ await service.retry_pending() # A finished teardown is not run again.
+
+ assert server.stopped and not any(agent._runtimes.values())
+ assert attempts == [1, 2]
+
+
+async def test_runtime_gen_006_a_retried_disable_settles_only_the_disabled_agents_work(tmp_path):
+ """RUNTIME-GEN-006: a disable settles its own agent's work even after Codex is enabled again.
+
+ The core's interrupt failed and the first teardown failed before settling.
+ Re-enabled meanwhile, a new agent runs the same Session in the same
+ directory, so its Activity has the same runtime key. The retried teardown
+ settles the old agent's Activity with the disable reason and leaves the
+ new agent's work alone.
+ """
+ activation = RuntimeActivationRegistry()
+ activities = SessionActivityRegistry(activation_registry=activation)
+ service = AgentService(controller=SimpleNamespace(), activities=activities, activation_registry=activation)
+ end_work = service.force_end_runtime_work
+ service.force_end_runtime_work = AsyncMock(side_effect=RuntimeError("settlement store unavailable"))
+
+ def enabled_agent():
+ agent, cwd = _agent(tmp_path)
+ agent.controller.runtime_activation = activation
+ agent.controller.agent_service = service
+ return agent, cwd
+
+ def start_activity(agent, activity_id):
+ activities.start(
+ backend="codex",
+ runtime_key=f"s1:{cwd}",
+ session_id="ses-1",
+ activity_id=activity_id,
+ kind="task",
+ activation_identity=agent._generation_for_session("s1").runtime.activation,
+ )
+
+ disabled, cwd = enabled_agent()
+ await disabled.handle_message(_request(cwd, "s1"))
+ old = _server_for(disabled, "s1")
+ start_activity(disabled, "old-task")
+ with pytest.raises(RuntimeError, match="survived shutdown"):
+ await disabled.shutdown_runtime(settle_reason="backend_disabled")
+ assert old.alive
+
+ reenabled, _ = enabled_agent()
+ await reenabled.handle_message(_request(cwd, "s1"))
+ new = _server_for(reenabled, "s1")
+ start_activity(reenabled, "new-task")
+ turns_settled = []
+
+ async def recorded_end_work(backend, *, base_session_ids, reason, **kwargs):
+ turns_settled.append((set(base_session_ids), reason))
+ await end_work(backend, base_session_ids=base_session_ids, reason=reason, **kwargs)
+
+ service.force_end_runtime_work = recorded_end_work
+ settled = []
+ service.on_activity_terminal = settled.append
+
+ await disabled.shutdown_runtime(settle_reason="backend_disabled")
+
+ assert [(item.id, item.status, item.metadata.get("interrupt_reason")) for item in settled] == [
+ ("old-task", "killed", "backend_disabled")
+ ]
+ assert [item["id"] for item in activities.session_state("ses-1")["background_activities"]] == ["new-task"]
+ # The disabled agent still knew its own running turn, so it settled it too.
+ assert turns_settled == [({"s1"}, "backend_disabled")]
+ assert old.stopped and new.alive
+ assert reenabled._turn_registry.get_active_turn("s1")
+
+
+async def test_runtime_gen_016_a_retried_disable_never_revokes_a_reenabled_agents_hub_credential(tmp_path):
+ """RUNTIME-GEN-016: a disabled agent's retried teardown retires only its own Hub scope.
+
+ Its first teardown left a Hub app-server running, and the re-enabled
+ agent started its own in the same directory. When the retry stops the old
+ process, the old credential is revoked and the new process's still
+ authenticates at the gateway.
+ """
+ correlation = TurnCorrelationRegistry(BoundedProvenanceStore(tmp_path / "provenance.json"))
+
+ class _GatewayRouter(_Router):
+ async def resolve(self, backend, requested_model, *, process_scope=None, turn_id=None, config=None):
+ token = correlation.credentials(backend, process_scope, None, request_scoped=True)
+ return _launch(requested_model, "hub", token=token)
+
+ def retire_process_scope(self, backend, process_scope, **_kwargs):
+ correlation.retire_scope(backend, process_scope)
+
+ router = _GatewayRouter()
+ catalog = SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ disabled, cwd = _agent(tmp_path, router=router)
+ reenabled, _ = _agent(tmp_path, router=router)
+ for agent in (disabled, reenabled):
+ agent.prepare_model_hub_runtime = AsyncMock(return_value=catalog)
+
+ await disabled.handle_message(_request(cwd, "s1"))
+ old = _server_for(disabled, "s1")
+ stop = old.stop
+ old.stop = AsyncMock(side_effect=RuntimeError("the child did not stop"))
+ with pytest.raises(RuntimeError, match="survived shutdown"):
+ await disabled.shutdown_runtime(settle_reason="backend_disabled")
+ await reenabled.handle_message(_request(cwd, "s2"))
+ new = _server_for(reenabled, "s2")
+ old.stop = stop
+
+ await disabled.shutdown_runtime(settle_reason="backend_disabled")
+
+ assert old.stopped and new.alive
+ assert not correlation.authenticates("codex", old.runtime_env["AVIBE_MODEL_HUB_TOKEN"])
+ assert correlation.authenticates("codex", new.runtime_env["AVIBE_MODEL_HUB_TOKEN"])
+
+
+async def test_runtime_gen_006_a_reenabled_agent_starts_beside_a_teardown_that_holds_its_activation(tmp_path, monkeypatch):
+ """RUNTIME-GEN-006: a re-enabled agent's first generation never aliases a disabled agent's.
+
+ Both number their first generation in a directory as serial 1. While the
+ disabled agent's retried teardown holds that generation's activation
+ reserved for retirement, the re-enabled agent's turn in the same
+ directory still attaches its own and runs.
+ """
+ failures = AsyncMock()
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", failures)
+ activation = RuntimeActivationRegistry()
+ disabled, cwd = _agent(tmp_path)
+ reenabled, _ = _agent(tmp_path)
+ for agent in (disabled, reenabled):
+ agent.controller.runtime_activation = activation
+ await disabled.handle_message(_request(cwd, "s1"))
+ old = _server_for(disabled, "s1")
+ stopping, release = asyncio.Event(), asyncio.Event()
+ stop = old.stop
+
+ async def slow_stop():
+ stopping.set()
+ await release.wait()
+ await stop()
+
+ old.stop = slow_stop
+ teardown = asyncio.create_task(disabled.shutdown_runtime(settle_reason="backend_disabled"))
+ await asyncio.wait_for(stopping.wait(), 1)
+
+ await asyncio.wait_for(reenabled.handle_message(_request(cwd, "s2")), 1)
+
+ failures.assert_not_awaited()
+ assert reenabled._turn_registry.get_active_turn("s2")
+ release.set()
+ await asyncio.wait_for(teardown, 1)
+ assert old.stopped and _server_for(reenabled, "s2").alive
+
+
+async def test_runtime_gen_016_a_process_whose_post_start_setup_fails_is_stopped_by_the_sweep(tmp_path, monkeypatch):
+ """RUNTIME-GEN-016: whatever fails after the spawn, the started app-server stays the sweep's to stop."""
+ agent, cwd = _agent(tmp_path)
+ failures = AsyncMock()
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", failures)
+ monkeypatch.setattr(
+ agent, "_attach_runtime_activation", Mock(side_effect=RuntimeError("activation unavailable"))
+ )
+
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s1")), 1)
+
+ failures.assert_awaited_once()
+ started = FakeAppServer.started[-1]
+ assert started.alive
+ await agent.reap_runtime_generations()
+ assert started.stopped and not any(agent._runtimes.values())
+
+
+async def test_runtime_gen_010_a_busy_directory_never_holds_a_turn_on_a_new_spec(tmp_path):
+ """RUNTIME-GEN-010: S1's long turn keeps its process; S2 starts at once on a new one."""
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ old = _server_for(agent, "s1")
+ old_thread = agent._session_mgr.get_thread_id("s1")
+ assert agent._turn_registry.get_active_turn("s1")
+
+ await agent.renew_runtime(agent.codex_config)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s2")), 1)
+
+ new = _server_for(agent, "s2")
+ assert new is not old
+ assert agent._turn_registry.get_active_turn("s2")
+ assert old.alive and old.active == {old_thread: agent._turn_registry.get_active_turn("s1")}
+
+ await old.complete(old_thread)
+ await _until(lambda: not old.alive)
+ assert new.alive
+ agent.controller.agent_service.force_end_runtime_work.assert_not_awaited()
+
+
+async def test_runtime_gen_011_a_session_releases_its_thread_before_resuming_elsewhere(tmp_path):
+ """RUNTIME-GEN-011: the old process unloads the thread; the next turn resumes it on the new one."""
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ await agent.handle_message(_request(cwd, "s2"))
+ old = _server_for(agent, "s1")
+ assert _server_for(agent, "s2") is old
+ s1_thread = agent._session_mgr.get_thread_id("s1")
+ s2_thread = agent._session_mgr.get_thread_id("s2")
+ await old.complete(s1_thread)
+
+ await agent.renew_runtime(agent.codex_config)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s1")), 1)
+
+ new = _server_for(agent, "s1")
+ assert new is not old
+ assert ("thread/unsubscribe", {"threadId": s1_thread}) in old.requests
+ assert ("thread/resume", s1_thread) in [(m, p.get("threadId")) for m, p in new.requests]
+ assert agent._session_mgr.get_thread_id("s1") == s1_thread
+ # S2's turn still runs where it started.
+ assert old.alive and s2_thread in old.loaded
+ assert _server_for(agent, "s2") is old
+
+
[email protected]("process_exits", [False, True], ids=["process-lives", "process-exits"])
+async def test_runtime_gen_011_a_closed_reader_is_no_proof_of_release(tmp_path, monkeypatch, process_exits):
+ """RUNTIME-GEN-011: only the old process's exit releases a thread its closed reader can no longer unload."""
+ monkeypatch.setattr(codex_agent_module, "_THREAD_RELEASE_TIMEOUT_SECONDS", 0.2)
+ failures = AsyncMock()
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", failures)
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ old = _server_for(agent, "s1")
+ thread = agent._session_mgr.get_thread_id("s1")
+ await old.complete(thread)
+ old_generation = agent._generation_for_session("s1")
+ old.close_reader()
+ if process_exits:
+ asyncio.get_running_loop().call_later(0.02, old.exit)
+ else:
+ # Avibe ends a child whose reader closed, but here that stop fails.
+ old.stop = AsyncMock(side_effect=RuntimeError("the child did not stop"))
+
+ await agent.renew_runtime(agent.codex_config)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s1")), 1)
+
+ resumed = [
+ server for server in FakeAppServer.started
+ if server is not old and ("thread/resume", thread) in [(m, p.get("threadId")) for m, p in server.requests]
+ ]
+ if process_exits:
+ assert resumed and _server_for(agent, "s1") is resumed[0]
+ failures.assert_not_awaited()
+ else:
+ # The process still holds the thread: the input is held, nothing moved.
+ assert resumed == []
+ assert agent._generation_for_session("s1") is old_generation
+ assert isinstance(failures.await_args.kwargs["cause"], codex_agent_module.CodexThreadReleaseUnavailableError)
+
+
[email protected]("interrupt", ["accepted", "refused"])
+async def test_runtime_gen_012_a_busy_session_moves_after_its_own_turn_is_interrupted(tmp_path, monkeypatch, interrupt):
+ """RUNTIME-GEN-012: a new message to a busy session interrupts it and proceeds on the new spec.
+
+ A refused interrupt changes nothing: the running turn stays tracked on its
+ process and the new input is held.
+ """
+ failures = AsyncMock()
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", failures)
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="token-a")
+ agent, cwd = _agent(tmp_path, router=router)
+ agent.prepare_model_hub_runtime = AsyncMock(
+ return_value=SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog-a.json", close=Mock()))
+ )
+ await agent.handle_message(_request(cwd, "s1"))
+ old = _server_for(agent, "s1")
+ thread = agent._session_mgr.get_thread_id("s1")
+ first_turn = agent._turn_registry.get_active_turn("s1")
+ first_context = agent._turn_registry.get_request_for_turn(first_turn).context
+ assert first_turn
+
+ router.launches["model-a"] = _launch("model-a", "hub", token="token-b")
+ old.refuse_interrupt = interrupt == "refused"
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s1")), 1)
+
+ methods = [method for method, _ in old.requests]
+ if interrupt == "refused":
+ assert "thread/unsubscribe" not in methods
+ assert _server_for(agent, "s1") is old
+ assert agent._turn_registry.get_active_turn("s1") == first_turn
+ assert old.active == {thread: first_turn}
+ assert all(context is not first_context for context in agent._event_handler.released)
+ assert isinstance(failures.await_args.kwargs["cause"], codex_agent_module.CodexThreadReleaseUnavailableError)
+ return
+ new = _server_for(agent, "s1")
+ assert new is not old
+ assert methods.index("turn/interrupt") < methods.index("thread/unsubscribe")
+ assert agent._turn_registry.get_active_turn("s1") not in (None, first_turn)
+ assert new.active.get(thread) == agent._turn_registry.get_active_turn("s1")
+ assert len(agent._event_handler.released) == 1
+
+
+async def test_runtime_gen_013_at_the_cap_the_oldest_busy_generation_gives_way(tmp_path):
+ """RUNTIME-GEN-013: a fourth spec starts at once; only the oldest generation's turn is interrupted."""
+ agent, cwd = _agent(tmp_path)
+ servers = []
+ for session in ("s1", "s2", "s3"):
+ await agent.handle_message(_request(cwd, session))
+ servers.append(_server_for(agent, session))
+ await agent.renew_runtime(agent.codex_config)
+ assert len({id(server) for server in servers}) == 3
+
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s4")), 1)
+ await _until(lambda: not servers[0].alive)
+
+ assert servers[1].alive and servers[2].alive
+ assert _server_for(agent, "s4").alive
+ agent.controller.agent_service.force_end_runtime_work.assert_awaited_once()
+ assert agent.controller.agent_service.force_end_runtime_work.await_args.kwargs["base_session_ids"] == {"s1"}
+ assert agent.transport_for_session("s1") is None
+
+
+async def test_runtime_gen_013_a_session_leaving_a_force_stopped_generation_waits_for_its_teardown(tmp_path):
+ """RUNTIME-GEN-013: a turn admitted while the cap's forced stop settles work is never part of that work."""
+ agent, cwd = _agent(tmp_path)
+ servers = []
+ for session in ("s1", "s2", "s3"):
+ await agent.handle_message(_request(cwd, session))
+ servers.append(_server_for(agent, session))
+ await agent.renew_runtime(agent.codex_config)
+ events = []
+ oldest = servers[0]
+ stop_oldest = oldest.stop
+
+ async def stop():
+ events.append("oldest stopped")
+ await stop_oldest()
+
+ oldest.stop = stop
+ start_turn = agent._start_turn
+
+ async def recording_start_turn(transport, request, *args, **kwargs):
+ if request.base_session_id == "s1":
+ events.append("s1 turn started")
+ return await start_turn(transport, request, *args, **kwargs)
+
+ agent._start_turn = recording_start_turn
+ follow_up = []
+
+ async def settle(*_args, **_kwargs):
+ # S1 sends again while its generation's work is being settled.
+ follow_up.append(asyncio.create_task(agent.handle_message(_request(cwd, "s1"))))
+ await asyncio.sleep(0.05)
+ events.append("settled")
+
+ agent.controller.agent_service.force_end_runtime_work = AsyncMock(side_effect=settle)
+
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s4")), 1)
+ await _until(lambda: bool(follow_up))
+ await asyncio.wait_for(follow_up[0], 2)
+
+ assert events == ["settled", "oldest stopped", "s1 turn started"]
+ assert agent._turn_registry.get_active_turn("s1")
+
+
[email protected]("gate_taken", [False, True], ids=["turn-holds-its-gate", "a-later-turn-holds-the-gate"])
+async def test_runtime_gen_013_a_child_whose_reader_closed_is_settled_before_it_is_killed(tmp_path, gate_taken):
+ """RUNTIME-GEN-013: a process that can no longer report its turn is ended like a forced stop.
+
+ Once the liveness monitor settled that turn and the Session's next turn took
+ its gate, settling the Session again would cancel the next turn instead.
+ """
+ agent, cwd = _agent(tmp_path)
+ first = _request(cwd, "s1")
+ await agent.handle_message(first)
+ old = _server_for(agent, "s1")
+ old.close_reader()
+ agent.controller.agent_service.emit_matches_runtime_turn = lambda context: not (
+ gate_taken and context is first.context
+ )
+
+ await agent.renew_runtime(agent.codex_config)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s2")), 1)
+ await _until(lambda: old.stopped)
+
+ agent.controller.agent_service.force_end_runtime_work.assert_awaited_once()
+ settled = agent.controller.agent_service.force_end_runtime_work.await_args.kwargs["base_session_ids"]
+ assert settled == (set() if gate_taken else {"s1"})
+
+
+async def test_runtime_gen_014_a_direct_launch_with_model_hub_keeps_the_managed_environment(tmp_path, monkeypatch):
+ """RUNTIME-GEN-014: Model Hub enabled must not drop the desktop-managed environment."""
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "direct")
+ agent, cwd = _agent(tmp_path, router=router)
+ managed = {"PATH": "/opt/avibe-managed/bin", "HOME": str(tmp_path)}
+ monkeypatch.setattr(agent, "_codex_runtime_environment", lambda: managed)
+
+ await agent.handle_message(_request(cwd, "s1"))
+
+ assert _server_for(agent, "s1").runtime_env == managed
+
+
+async def test_runtime_gen_015_direct_and_native_cli_launches_share_one_process(tmp_path):
+ """RUNTIME-GEN-015: identical process inputs never replace the app-server."""
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "direct")
+ router.launches["model-b"] = _launch("model-b", "native_cli")
+ agent, cwd = _agent(tmp_path, router=router)
+
+ await agent.handle_message(_request(cwd, "s1", model="model-a"))
+ first = _server_for(agent, "s1")
+ await first.complete(agent._session_mgr.get_thread_id("s1"))
+ await agent.handle_message(_request(cwd, "s1", model="model-b"))
+
+ assert _server_for(agent, "s1") is first
+ assert len(FakeAppServer.started) == 1
+
+
+async def test_runtime_gen_015_a_renewal_during_hub_catalog_preparation_leaves_one_coherent_spec(tmp_path):
+ """RUNTIME-GEN-015: a Hub turn's spec derives from one load of its launch inputs.
+
+ A renewal that lands while the turn's catalog is prepared changes neither
+ its binary nor its epoch midway: the turn runs on the app-server its inputs
+ describe, and the directory's next turn moves to the renewed one.
+ """
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="hub-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ catalog = SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ agent.prepare_model_hub_runtime = AsyncMock(return_value=catalog)
+ await agent.handle_message(_request(cwd, "s1"))
+ first = _server_for(agent, "s1")
+ await first.complete(agent._session_mgr.get_thread_id("s1"))
+
+ async def renewed_while_preparing(*_args, **_kwargs):
+ await agent.renew_runtime(SimpleNamespace(binary="codex-renewed", extra_args=[]))
+ return catalog
+
+ agent.prepare_model_hub_runtime = AsyncMock(side_effect=renewed_while_preparing)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s2")), 1)
+
+ assert _server_for(agent, "s2") is first
+ assert [server.binary for server in FakeAppServer.started] == ["codex-generation-fake"]
+
+ agent.prepare_model_hub_runtime = AsyncMock(return_value=catalog)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s3")), 1)
+ assert [server.binary for server in FakeAppServer.started] == ["codex-generation-fake", "codex-renewed"]
+
+
+async def test_runtime_gen_015_a_renewal_during_hub_launch_resolution_leaves_one_coherent_spec(tmp_path):
+ """RUNTIME-GEN-015: a Hub turn's launch and spec derive from the one load taken at admission.
+
+ A renewal that lands while the turn's Model Hub launch is resolved changes
+ neither its binary nor its epoch: the turn runs on the app-server its
+ admission load describes, and the directory's next turn moves.
+ """
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="hub-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ catalog = SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ agent.prepare_model_hub_runtime = AsyncMock(return_value=catalog)
+ await agent.handle_message(_request(cwd, "s1"))
+ first = _server_for(agent, "s1")
+ await first.complete(agent._session_mgr.get_thread_id("s1"))
+ resolve = router.resolve
+
+ async def renewed_while_resolving(*args, **kwargs):
+ await agent.renew_runtime(SimpleNamespace(binary="codex-renewed", extra_args=[]))
+ return await resolve(*args, **kwargs)
+
+ router.resolve = renewed_while_resolving
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s2")), 1)
+
+ assert _server_for(agent, "s2") is first
+ assert [server.binary for server in FakeAppServer.started] == ["codex-generation-fake"]
+
+ router.resolve = resolve
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s3")), 1)
+ assert [server.binary for server in FakeAppServer.started] == ["codex-generation-fake", "codex-renewed"]
+
+
+async def test_runtime_gen_015_a_dead_retiring_generation_is_never_reused(tmp_path):
+ """RUNTIME-GEN-015: an equal spec reuses a process only while that process can serve."""
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="shared-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ agent.controller.emit_agent_message = AsyncMock()
+ agent.prepare_model_hub_runtime = AsyncMock(
+ return_value=SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ )
+ await agent.handle_message(_request(cwd, "s1"))
+ hub = _server_for(agent, "s1")
+ # A switch to Direct leaves the busy Hub process retiring, then it dies.
+ router.launches["model-a"] = _launch("model-a")
+ await agent.handle_message(_request(cwd, "s2"))
+ assert _server_for(agent, "s2") is not hub
+ hub.close_reader()
+ hub.exit()
+ hub_requests = len(hub.requests)
+
+ router.launches["model-a"] = _launch("model-a", "hub", token="shared-token")
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s3")), 1)
+
+ assert hub.requests[hub_requests:] == []
+ served = _server_for(agent, "s3")
+ assert served not in (hub, _server_for(agent, "s2")) and served.alive
+ assert agent._turn_registry.get_active_turn("s3")
+
+
+async def test_runtime_gen_015_a_generation_that_dies_while_its_spec_is_prepared_is_not_reused(tmp_path):
+ """RUNTIME-GEN-015: usability is checked again where the equal-spec process is acquired."""
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="shared-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ agent.controller.emit_agent_message = AsyncMock()
+ catalog = SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ agent.prepare_model_hub_runtime = AsyncMock(return_value=catalog)
+ await agent.handle_message(_request(cwd, "s1"))
+ hub = _server_for(agent, "s1")
+ await hub.complete(agent._session_mgr.get_thread_id("s1"))
+ await agent.adopt_model_hub_catalog()
+
+ async def prepare(*_args, **_kwargs):
+ # The equal-spec process dies while the next turn prepares its catalog.
+ hub.close_reader()
+ hub.exit()
+ return catalog
+
+ agent.prepare_model_hub_runtime = AsyncMock(side_effect=prepare)
+ hub_requests = len(hub.requests)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s2")), 1)
+
+ assert hub.requests[hub_requests:] == []
+ assert _server_for(agent, "s2") is not hub and agent._turn_registry.get_active_turn("s2")
+
+
+async def test_runtime_gen_016_a_starting_hub_process_keeps_the_scope(tmp_path):
+ """RUNTIME-GEN-016: a Hub process still starting counts as the directory's Hub process."""
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="shared-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ agent.prepare_model_hub_runtime = AsyncMock(
+ return_value=SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ )
+ await agent.handle_message(_request(cwd, "s1"))
+ retiring_hub = _server_for(agent, "s1")
+ # A switch to Direct leaves the busy Hub process retiring.
+ router.launches["model-a"] = _launch("model-a")
+ await agent.handle_message(_request(cwd, "s2"))
+ # Back to the Hub on a new spec: its process takes a while to start.
+ router.launches["model-a"] = _launch("model-a", "hub", token="shared-token")
+ await agent.renew_runtime(agent.codex_config)
+ started = asyncio.Event()
+ up = asyncio.Event()
+
+ async def slow_start(_server):
+ started.set()
+ await up.wait()
+
+ FakeAppServer.on_start = slow_start
+ s3 = asyncio.create_task(agent.handle_message(_request(cwd, "s3")))
+ await asyncio.wait_for(started.wait(), 1)
+
+ await retiring_hub.complete(agent._session_mgr.get_thread_id("s1"))
+ await _until(lambda: not retiring_hub.alive)
+ assert router.retired == []
+
+ up.set()
+ await asyncio.wait_for(s3, 1)
+ assert router.retired == []
+
+
[email protected]("child", ["exited", "alive"])
+async def test_runtime_gen_016_a_failed_hub_start_is_cleaned_up(tmp_path, monkeypatch, child):
+ """RUNTIME-GEN-016: a Hub start that fails still revokes the scope and never leaks its child."""
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", AsyncMock())
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="shared-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ agent.prepare_model_hub_runtime = AsyncMock(
+ return_value=SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ )
+
+ async def failing_start(server):
+ if child == "exited":
+ server._process.exit(1)
+ raise RuntimeError("initialize failed")
+
+ FakeAppServer.on_start = failing_start
+ await agent.handle_message(_request(cwd, "s1"))
+ [server] = FakeAppServer.started
+ if child == "alive":
+ # Its own cleanup failed; the sweep stops it.
+ assert router.retired == []
+ await agent.reap_runtime_generations()
+ assert server.stopped
+
+ assert router.retired == [router.scopes[0]]
+
+
[email protected]("successor", ["hub", "direct"], ids=["hub-renewal", "switch-to-direct"])
+async def test_runtime_gen_016_hub_scope_is_revoked_only_with_the_last_hub_generation(tmp_path, successor):
+ """RUNTIME-GEN-016: retiring one Hub process keeps the credential its running turn or successor uses.
+
+ A switch to Direct is a spec change: the next turn starts at once on a
+ Direct process while the Hub turn finishes on its own process and keeps the
+ gateway credential until it ends.
+ """
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", "hub", token="shared-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ agent.prepare_model_hub_runtime = AsyncMock(
+ return_value=SimpleNamespace(retain=lambda: SimpleNamespace(path=tmp_path / "catalog.json", close=Mock()))
+ )
+ await agent.handle_message(_request(cwd, "s1"))
+ old = _server_for(agent, "s1")
+ if successor == "hub":
+ await agent.renew_runtime(agent.codex_config)
+ else:
+ # The mode switch commits, then the catalog hook adopts it.
+ router.launches["model-a"] = _launch("model-a")
+ await agent.adopt_model_hub_catalog()
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s2")), 1)
+
+ new = _server_for(agent, "s2")
+ assert new is not old and agent._turn_registry.get_active_turn("s2")
+ assert ("AVIBE_MODEL_HUB_TOKEN" in new.runtime_env) is (successor == "hub")
+ assert old.alive and agent._turn_registry.get_active_turn("s1")
+ assert router.retired == []
+
+ await old.complete(agent._session_mgr.get_thread_id("s1"))
+ await _until(lambda: not old.alive)
+ agent.controller.agent_service.force_end_runtime_work.assert_not_awaited()
+ if successor == "hub":
+ assert router.retired == []
+ await agent.shutdown_runtime()
+ assert router.retired == [router.scopes[0]]
+
+
[email protected]("cancelled_on", ["first-attempt", "retry"])
+async def test_runtime_gen_010_a_cancelled_admission_never_pins_its_generation(tmp_path, fake_app_servers, cancelled_on):
+ """RUNTIME-GEN-010: a turn start cancelled before Codex answered leaves nothing that keeps its process.
+
+ That holds on the retry too, after the first attempt failed before Codex saw it.
+ """
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ old = _server_for(agent, "s1")
+ await old.complete(agent._session_mgr.get_thread_id("s1"))
+ hung = []
+
+ def hang_turn_start(server):
+ send = server.send_request
+
+ async def hanging_send(method, params):
+ if method == "turn/start":
+ hung.append(server)
+ await asyncio.Event().wait()
+ return await send(method, params)
+
+ server.send_request = hanging_send
+
+ if cancelled_on == "first-attempt":
+ hang_turn_start(old)
+ else:
+ send = old.send_request
+
+ async def broken_send(method, params):
+ if method == "thread/start":
+ raise ConnectionError("Codex app-server transport is not available")
+ return await send(method, params)
+
+ old.send_request = broken_send
+
+ async def on_start(server):
+ hang_turn_start(server)
+
+ fake_app_servers.on_start = on_start
+ request = _request(cwd, "s2")
+ # As AgentService marks a turn before handing it over.
+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)
+ admission = asyncio.create_task(agent.handle_message(request))
+ await _until(lambda: bool(hung))
+ admission.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await admission
+
+ fake_app_servers.on_start = None
+ await agent.renew_runtime(agent.codex_config)
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s3")), 1)
+ await agent.reap_runtime_generations()
+ assert not hung[0].alive
+
+
+async def test_runtime_gen_011_end_releases_the_thread_of_a_process_already_being_stopped(tmp_path):
+ """RUNTIME-GEN-011: End proves the release of a thread whose process the reconciler took over.
+
+ That stop may still decline, so the process can outlive End.
+ """
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ old = _server_for(agent, "s1")
+ thread = agent._session_mgr.get_thread_id("s1")
+ await old.complete(thread)
+ checking, decide = asyncio.Event(), asyncio.Event()
+
+ async def drained(_generation):
+ checking.set()
+ await decide.wait()
+ return False # Something still owns the process, so the stop declines.
+
+ agent._generation_drained = drained
+ unit = agent._units[cwd]
+ await unit.retire(unit.current)
+ await asyncio.wait_for(checking.wait(), 1)
+
+ ended = await asyncio.wait_for(agent.end_session("s1"), 1)
+ decide.set()
+ await unit.settled()
+
+ assert ended["process_killed"] is False
+ assert old.alive and thread not in old.loaded
+ assert agent._generation_for_session("s1") is None
+
+
+async def test_runtime_gen_011_new_releases_a_session_that_started_while_it_cleared(tmp_path):
+ """RUNTIME-GEN-011: ``/new`` clears a whole session key, so it releases every Session it clears."""
+ agent, cwd = _agent(tmp_path)
+ agent.sessions.clear_agent_sessions = Mock()
+ await agent.handle_message(_request(cwd, "s1"))
+ server = _server_for(agent, "s1")
+ await server.complete(agent._session_mgr.get_thread_id("s1"))
+ joining = _request(cwd, "s2")
+ joining.session_key = "key-s1"
+ send = server.send_request
+
+ async def send_while_another_session_starts(method, params):
+ if method == "thread/unsubscribe" and not agent._session_mgr.get_sessions_by_session_key("key-s1")[1:]:
+ # Another Session of the same key starts while the first is released.
+ await agent.handle_message(joining)
+ return await send(method, params)
+
+ server.send_request = send_while_another_session_starts
+
+ await asyncio.wait_for(agent.clear_sessions("key-s1"), 2)
+
+ assert server.loaded == set()
+ assert agent._generation_for_session("s2") is None
+ assert agent._session_mgr.get_sessions_by_session_key("key-s1") == []
+
+
+async def test_runtime_gen_011_a_resume_whose_answer_was_lost_is_released_before_resuming_elsewhere(tmp_path, monkeypatch):
+ """RUNTIME-GEN-011: a process that may have loaded the thread releases it before another resumes it."""
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", AsyncMock())
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ thread = agent._session_mgr.get_thread_id("s1")
+ await _server_for(agent, "s1").complete(thread)
+ await agent.renew_runtime(agent.codex_config)
+ # S2's running turn keeps the next process alive after it fails S1.
+ await agent.handle_message(_request(cwd, "s2"))
+ lost = _server_for(agent, "s2")
+ FakeAppServer.lose_next_resume = True
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s1")), 2)
+ assert lost.alive and thread in lost.loaded
+
+ await asyncio.wait_for(agent.handle_message(_request(cwd, "s1")), 2)
+
+ served = _server_for(agent, "s1")
+ assert served not in (None, lost)
+ assert ("thread/unsubscribe", {"threadId": thread}) in lost.requests
+ assert served.active.get(thread) == agent._turn_registry.get_active_turn("s1")
+
+
+async def test_a_new_thread_serves_turns_only_once_it_is_persisted(tmp_path, monkeypatch):
+ """A thread the durable mapping lacks would vanish from resume history."""
+ monkeypatch.setattr(codex_agent_module, "emit_backend_failure", AsyncMock())
+ agent, cwd = _agent(tmp_path)
+ remember = agent.bind_agent_session_id.side_effect
+ writes = iter([RuntimeError("database is locked")])
+
+ def bind(request, thread_id):
+ failure = next(writes, None)
+ if failure is not None:
+ raise failure
+ return remember(request, thread_id)
+
+ agent.bind_agent_session_id.side_effect = bind
+
+ await agent.handle_message(_request(cwd, "s1"))
+ assert agent._turn_registry.get_active_turn("s1") is None
+ await agent.handle_message(_request(cwd, "s1"))
+
+ thread = agent._session_mgr.get_thread_id("s1")
+ assert agent.sessions.get_agent_session_id("key-s1", "s1", "codex") == thread
+ assert _server_for(agent, "s1").active.get(thread) == agent._turn_registry.get_active_turn("s1")
+
+
+async def test_runtime_gen_017_late_thread_events_from_a_previous_generation_are_dropped(tmp_path):
+ """RUNTIME-GEN-017: a moved session never receives thread-level events from the process it left."""
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ await agent.handle_message(_request(cwd, "s2"))
+ old = _server_for(agent, "s1")
+ thread = agent._session_mgr.get_thread_id("s1")
+ await old.complete(thread)
+ await agent.renew_runtime(agent.codex_config)
+ await agent.handle_message(_request(cwd, "s1"))
+ handled = []
+ agent._event_handler.handle_notification = AsyncMock(side_effect=lambda *args: handled.append(args[0]))
+
+ await old._notify("error", {"threadId": thread, "error": {"message": "late"}})
+ await _server_for(agent, "s1")._notify("error", {"threadId": thread, "error": {"message": "current"}})
+
+ assert handled == ["error"]
+ assert agent._event_handler.handle_notification.await_args.args[1]["error"]["message"] == "current"
+
+
[email protected]("holder", ["serving", "stopped-answering"])
+async def test_runtime_gen_018_fork_boundary_reads_the_source_sessions_generation(tmp_path, holder):
+ """RUNTIME-GEN-018: only the process running the source turn reports it in progress.
+
+ That holds even after one of its requests timed out: the process and its
+ turn still run, and any other process would read the turn as interrupted.
+ """
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "source"))
+ source_server = _server_for(agent, "source")
+ await agent.renew_runtime(agent.codex_config)
+ await agent.handle_message(_request(cwd, "other"))
+ target_server = _server_for(agent, "other")
+ assert target_server is not source_server
+ running = agent._turn_registry.get_active_turn("source")
+ source_thread = agent._session_mgr.get_thread_id("source")
+
+ async def turns(method, params):
+ source_server.requests.append((method, params))
+ return {"data": [{"id": running, "status": "inProgress"}, {"id": "turn-done", "status": "completed"}]}
+
+ source_server.send_request = turns
+ source_server.wedged = holder == "stopped-answering"
+ target_server.send_request = AsyncMock(
+ return_value={"data": [{"id": running, "status": "interrupted"}]}
+ )
+
+ # Fork metadata names the durable Session id, never the base session; the
+ # running turn is found through the persisted fork boundary.
+ agent.controller.session_turns = SimpleNamespace(
+ native_turn_id_for_initial_message=lambda session_id, message_id: (
+ running if (session_id, message_id) == ("ses-source-durable", "message-1") else None
+ )
+ )
+ still_running, boundary = await agent._fork_source_last_completed_turn_id(
+ target_server,
+ {
+ "source_session_id": "ses-source-durable",
+ "source_native_session_id": source_thread,
+ "source_message_id": "message-1",
+ },
+ )
+
+ assert (still_running, boundary) == (True, "turn-done")
+ target_server.send_request.assert_not_awaited()
+
+
[email protected]("stuck_on", ["retiring", "current"])
+async def test_hfr_144_a_stuck_turn_settles_on_the_generation_that_runs_it(tmp_path, stuck_on):
+ """HFR-144: the stuck-turn backstop settles a turn only through the generation holding it.
+
+ That generation is retired, so a native turn that may still run ends with
+ its process, while a busy neighbour's turn finishes first.
+ """
+ agent, cwd = _agent(tmp_path)
+ agent.controller.emit_agent_message = AsyncMock()
+ await agent.handle_message(_request(cwd, "s1"))
+ old = _server_for(agent, "s1")
+ if stuck_on == "retiring":
+ await agent.renew_runtime(agent.codex_config)
+ await agent.handle_message(_request(cwd, "s2"))
+ neighbour = _server_for(agent, "s2")
+ stuck_turn = agent._turn_registry.get_active_turn("s1")
+ running_turn = agent._turn_registry.get_active_turn("s2")
+ # S1's turn made no progress for longer than the backstop (1800 s for a
+ # 600 s idle timeout); S2 is busy.
+ agent._session_last_activity["s1"] = codex_agent_module.time.monotonic() - 10_000
+
+ await agent.evict_idle_transports(600)
+
+ agent.controller.emit_agent_message.assert_awaited_once()
+ assert agent._turn_registry.get_active_turn("s1") is None
+ assert agent._turn_registry.get_active_turn("s2") == running_turn != stuck_turn
+ if stuck_on == "retiring":
+ assert not old.alive
+ assert agent._units[cwd].current.runtime.transport is neighbour and neighbour.alive
+ else:
+ assert neighbour is old and agent._units[cwd].current is None and old.alive
+ await old.complete(agent._session_mgr.get_thread_id("s2"))
+ await _until(lambda: not old.alive)
+
+
+async def test_hfr_144_the_stuck_turn_backstop_never_forgets_a_turn_admitted_meanwhile(tmp_path):
+ """HFR-144: only the exact stuck turn is forgotten, not the one its Session started meanwhile."""
+ agent, cwd = _agent(tmp_path)
+ await agent.handle_message(_request(cwd, "s1"))
+ await agent.renew_runtime(agent.codex_config)
+ await agent.handle_message(_request(cwd, "s2"))
+ agent._session_last_activity["s1"] = codex_agent_module.time.monotonic() - 10_000
+
+ async def emit(*_args, **_kwargs):
+ # The settled request's terminal result lets S1's next message in.
+ await agent.handle_message(_request(cwd, "s1"))
+
+ agent.controller.emit_agent_message = AsyncMock(side_effect=emit)
+ await agent.evict_idle_transports(600)
+
+ new_turn = agent._turn_registry.get_active_turn("s1")
+ assert new_turn and _server_for(agent, "s1").active.get(agent._session_mgr.get_thread_id("s1")) == new_turn
+
diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py
index b4b4eff87..f0385cd13 100644
--- a/tests/test_codex_transport.py
+++ b/tests/test_codex_transport.py
@@ -303,28 +303,33 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):
await transport.send_notification("initialized")
async def test_cancelled_request_does_not_leave_pending_rpc(self):
- request_written = asyncio.Event()
+ # Cancelled while its write is still draining, or while awaiting the answer.
+ for phase in ("writing", "awaiting_response"):
+ with self.subTest(phase=phase):
+ request_written = asyncio.Event()
- class _Stdin:
- def is_closing(self):
- return False
+ class _Stdin:
+ def is_closing(self):
+ return False
- def write(self, _payload):
- return None
+ def write(self, _payload):
+ return None
- async def drain(self):
- request_written.set()
+ async def drain(self):
+ request_written.set()
+ if phase == "writing":
+ await asyncio.Event().wait()
- transport = CodexTransport(binary="codex", cwd="/tmp")
- transport._process = SimpleNamespace(returncode=None, stdin=_Stdin())
+ 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
+ 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, {})
+ self.assertEqual(transport._pending, {})
async def test_pending_notification_keeps_terminal_pipeline_alive(self):
transport = CodexTransport(binary="codex", cwd="/tmp")
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
index 76ce75823..7976b21a4 100644
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@ -875,3 +875,48 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:
assert stop_order[0] == "quiesce"
assert set(stop_order[1:3]) == {"tasks", "watch"}
assert stop_order[3] == "supervisor"
+
+
+def test_cleanup_sync_makes_a_last_attempt_at_pending_backend_teardowns() -> None:
+ """A disabled backend's failed stop has no owner once the idle sweep is gone.
+
+ Its agent is out of routing, so service shutdown must retry it rather than
+ leave the process running without any controller.
+ """
+ from modules.agents.service import AgentService
+
+ controller = Controller.__new__(Controller)
+ loop = asyncio.new_event_loop()
+ controller._loop = loop
+
+ class _Stopper:
+ async def stop(self) -> None:
+ return None
+
+ controller.scheduled_task_service = _Stopper()
+ controller.watch_service = _Stopper()
+ controller.runtime_command_watcher = _Stopper()
+ controller.update_checker = type("UpdateChecker", (), {"stop": lambda self: None})()
+ controller.receiver_tasks = {}
+ controller.im_client = None
+ controller._im_thread = None
+ controller.agent_service = AgentService(controller=controller)
+ attempts: list[str] = []
+
+ async def stop_disabled_codex() -> None:
+ attempts.append("stop")
+ if len(attempts) == 1:
+ raise RuntimeError("app-server survived")
+
+ loop.run_until_complete(controller.agent_service.run_until_done("disabled:codex", stop_disabled_codex))
+ thread = threading.Thread(target=loop.run_forever, daemon=True)
+ thread.start()
+ try:
+ controller.cleanup_sync()
+ finally:
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join(timeout=5)
+ loop.close()
+
+ assert attempts == ["stop", "stop"]
+ assert controller.agent_service._pending_operations == {}
diff --git a/tests/test_controller_idle_cleanup.py b/tests/test_controller_idle_cleanup.py
index 6fcdc3ca6..52e75b3de 100644
--- a/tests/test_controller_idle_cleanup.py
+++ b/tests/test_controller_idle_cleanup.py
@@ -1,5 +1,7 @@
from types import SimpleNamespace
+import pytest
+
from config.v2_config import DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
from core.controller import Controller
@@ -41,3 +43,44 @@ def test_idle_cleanup_timeouts_fall_back_to_shared_default_when_backend_config_o
assert claude_timeout == DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
assert codex_timeout == DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
+
+
+def test_a_saved_idle_timeout_applies_without_a_backend_restart(monkeypatch) -> None:
+ """RUNTIME-GEN-005: the idle sweep reads timeouts live and always sweeps generations.
+
+ Saving an idle timeout renews the backend in place rather than restarting
+ it, so the sweep must not keep the value, or an interval derived from the
+ value, it started with.
+ """
+ import asyncio
+ from unittest.mock import AsyncMock
+
+ controller = object.__new__(Controller)
+ controller.config = SimpleNamespace(claude=SimpleNamespace(idle_timeout_seconds=86400), codex=None)
+ controller.session_handler = SimpleNamespace(
+ evict_idle_sessions=AsyncMock(),
+ reap_orphaned_claude_sessions=AsyncMock(),
+ )
+ reap = AsyncMock()
+ controller.agent_service = SimpleNamespace(agents={"codex": SimpleNamespace(name="codex", reap_runtime_generations=reap)})
+ sweeps = []
+
+ async def sleep(_seconds):
+ sweeps.append(_seconds)
+ if len(sweeps) == 2:
+ controller.config.claude.idle_timeout_seconds = 600
+ if len(sweeps) == 3:
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr("core.controller.asyncio.sleep", sleep)
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(Controller.periodic_cleanup(controller))
+
+ assert [call.args for call in controller.session_handler.evict_idle_sessions.await_args_list] == [
+ (86400,),
+ (600,),
+ ]
+ assert reap.await_count == 2
+ # A one-day timeout must not stretch the interval before the new value is read.
+ assert sweeps == [60, 60, 60]
diff --git a/tests/test_controller_model_hub_gate.py b/tests/test_controller_model_hub_gate.py
index 89bc988ad..b6bb6f25b 100644
--- a/tests/test_controller_model_hub_gate.py
+++ b/tests/test_controller_model_hub_gate.py
@@ -220,41 +220,20 @@ def test_controller_builds_one_model_hub_aggregate_by_default_or_explicit_enable
asyncio.run(drain_refresh())
assert service.reconcile_builtin_models.await_count == 2
- runtime_config = object()
- latest = SimpleNamespace(
- model_hub=SimpleNamespace(
- agents={"codex": SimpleNamespace(mode="hub")},
- ),
- agents=SimpleNamespace(codex=runtime_config),
- )
- controller.backend_restart_coordinator = SimpleNamespace(
- request_restart=AsyncMock(return_value="restarted"),
- )
- controller.agent_service = SimpleNamespace(
- invalidate_model_hub_runtime=AsyncMock(),
- refresh_runtime_config=AsyncMock(),
- )
+ # A catalog change moves each runtime at its next turn: the agent adopts
+ # the committed catalog, and nothing restarts.
+ latest = SimpleNamespace(model_hub=SimpleNamespace(agents={"codex": SimpleNamespace(mode="hub")}))
+ controller.backend_restart_coordinator = SimpleNamespace(request_restart=AsyncMock())
+ codex = SimpleNamespace(adopt_model_hub_catalog=AsyncMock())
+ controller.agent_service = SimpleNamespace(agents={"codex": codex})
monkeypatch.setattr(V2Config, "load", classmethod(lambda _cls: latest))
asyncio.run(captured["backend_catalog_changed"]("codex"))
+ asyncio.run(captured["backend_catalog_changed"]("opencode"))
assert controller.config.model_hub is latest.model_hub
- controller.backend_restart_coordinator.request_restart.assert_awaited_once_with(
- "codex"
- )
- controller.agent_service.invalidate_model_hub_runtime.assert_not_awaited()
- controller.agent_service.refresh_runtime_config.assert_not_awaited()
-
- latest.model_hub.agents["codex"].mode = "direct"
- controller.backend_restart_coordinator.request_restart.reset_mock()
-
- asyncio.run(captured["backend_catalog_changed"]("codex"))
-
- controller.agent_service.invalidate_model_hub_runtime.assert_awaited_once_with(
- "codex"
- )
+ codex.adopt_model_hub_catalog.assert_awaited_once_with()
controller.backend_restart_coordinator.request_restart.assert_not_awaited()
- controller.agent_service.refresh_runtime_config.assert_not_awaited()
@pytest.mark.anyio
diff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.py
index b70653198..834d4966c 100644
--- a/tests/test_desktop_runtime_stop.py
+++ b/tests/test_desktop_runtime_stop.py
@@ -159,12 +159,12 @@ def stop_env(monkeypatch):
monkeypatch.setattr(os, "kill", recording_kill)
monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=5: effects["stop_pid"].append(pid) or False)
# The OpenCode server is stopped with its tool tree; record that stop the same way.
- from modules.agents.opencode.server import OpenCodeServerManager
+ from modules.agents.opencode import server as opencode_server
monkeypatch.setattr(
- OpenCodeServerManager,
- "_terminate_pid_tree_sync",
- staticmethod(lambda pid, timeout=5.0: effects["stop_pid"].append(pid) or False),
+ opencode_server,
+ "terminate_pid_tree_sync",
+ lambda pid, timeout=5.0: effects["stop_pid"].append(pid) or False,
)
monkeypatch.setattr(remote_access, "stop", lambda: effects["remote_access"].append(True) or {"ok": True})
# The full stop reaps the installers of this process's own Runtime id,
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index deba534ad..8af3f1967 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -739,7 +739,7 @@ def test_backend_application_uses_verified_socket_and_real_projection(socket_pat
service = _AgentService()
service.agents = {"claude": object()}
controller = _controller(service)
- controller.backend_restart_coordinator = BackendRestartCoordinator(controller, AsyncMock())
+ controller.backend_restart_coordinator = BackendRestartCoordinator(controller, AsyncMock(), renew=AsyncMock())
app = create_app(controller)
async def run():
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index f2c11d0c8..714cd350c 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -3212,7 +3212,49 @@ def test_release_for_backend_refresh_names_the_interruption(harness, decided_by)
assert len(notices) == 1
channel, kind, text = notices[0]
assert (channel, kind) == ("ses_opencode", "notify")
- assert text.startswith("⚠️ This turn was interrupted — its Agent runtime was restarted")
+ assert text.startswith("⚠️ This turn was interrupted — its Agent runtime had to be replaced")
+
+
+def test_runtime_gen_006_a_disabled_backend_tells_the_turn_it_was_turned_off():
+ """RUNTIME-GEN-006: disabling a backend names itself as the cause.
+
+ The turn settles as ``backend_disabled``, not as a runtime refresh, and the
+ conversation is told which backend was turned off.
+ """
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ controller.set_agent_status = lambda *_args: None
+ notices = []
+
+ async def _emit(context, kind, text, **_kwargs):
+ notices.append((context.channel_id, kind, text))
+ return "notice-1"
+
+ controller.emit_agent_message = _emit
+
+ async def _go():
+ ctx = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
+ ctx.platform_specific = {
+ "agent_session_id": "ses_codex",
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+ sink_key = resolve_turn_sink_key(controller, ctx)
+ controller.register_turn_sink(sink_key, on_chunk=None, done_event=asyncio.Event())
+ task = asyncio.create_task(asyncio.sleep(60))
+ await asyncio.sleep(0)
+ manager.in_flight["ses_codex"] = session_turns.Turn(task=task, context=ctx, logical_turn_id="turn-1")
+ await manager.release_for_backend_refresh(
+ backend="codex", base_session_ids={"ses_codex"}, settled_by="backend_disabled"
+ )
+ for _ in range(5):
+ await asyncio.sleep(0)
+ return controller.get_turn_sink(sink_key)
+
+ sink = asyncio.run(_go())
+
+ assert sink["settled_by"] == "backend_disabled"
+ assert [(channel, kind) for channel, kind, _text in notices] == [("ses_codex", "notify")]
+ assert notices[0][2].startswith("⏹ This turn was stopped because Codex was turned off.")
def test_release_for_backend_refresh_leaves_other_backend_turn_running():
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 1b7f3c529..299fb28ba 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -1,3 +1,4 @@
+from contextlib import asynccontextmanager
import asyncio
import importlib.util
import os
@@ -366,14 +367,16 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
)
controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())
server = types.SimpleNamespace(
- ensure_running=AsyncMock(),
get_available_agents=AsyncMock(return_value=[{"name": "reviewer"}]),
get_explicit_subagent_model=Mock(return_value="anthropic/claude-reviewer"),
)
+
+ @asynccontextmanager
+ async def current_server():
+ yield server
+
controller.agent_service.agents = {
- "opencode": types.SimpleNamespace(
- _get_server=AsyncMock(return_value=server)
- )
+ "opencode": types.SimpleNamespace(current_server=current_server)
}
controller.get_cwd = Mock(return_value="/tmp")
controller.resolve_vibe_agent_for_context = Mock(
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index b0e325402..e60f19811 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -4958,42 +4958,63 @@ def test_hub_to_direct_fallback_does_not_require_engine_sync(tmp_path):
@pytest.mark.parametrize(("start", "target"), [("direct", "hub"), ("hub", "direct")])
-def test_mode_switch_commits_only_inside_the_interrupting_guard(tmp_path, start, target):
- """MH-MIG-011: either direction retires the managed runtime under the
- migration guard, which interrupts running work. Switching back to direct
- outside it left a running gateway turn to fail later on the Hub's refusal."""
+def test_mode_switch_interrupts_nothing_and_keeps_admitted_hub_turns_served(tmp_path, start, target):
+ """MH-MIG-011: a mode switch is a launch-input change, not an exclusive cutover.
+
+ It never enters the interrupting migration guard; it commits and lets each
+ runtime move at its next turn. A Hub turn admitted before a switch to Direct
+ keeps resolving its routes, so it is not failed by a later refusal.
+ """
service, store, _adapter = _service(tmp_path)
service.migration_home = tmp_path / "native-home"
store.config.agents["claude"].mode = start
- observed = []
+ _set_claude_route_fixture(store, ("src_first0001",), "claude-opus-4-6")
+ entered = []
+ refreshed = []
@asynccontextmanager
async def guard(backends, *, external_processes=True):
- observed.append(("enter", backends, external_processes, store.config.agents["claude"].mode))
+ entered.append(backends)
+ yield lambda: None
- async def verify_idle():
- pass
-
- yield verify_idle
- observed.append(("exit", store.config.agents["claude"].mode))
+ async def catalog_changed(backend):
+ refreshed.append((backend, store.config.agents[backend].mode))
service.migration_guard = guard
+ service.backend_catalog_changed = catalog_changed
+
switched = asyncio.run(service.set_agent_mode("claude", target))
assert switched["mode"] == target
- assert observed == [("enter", ("claude",), False, start), ("exit", target)]
+ assert store.config.agents["claude"].mode == target
+ assert entered == []
+ assert refreshed == [("claude", target)]
+ resolution = service._invocation_resolution(store.config, "claude", "claude-opus-4-6")
+ assert resolution.requested_model == "claude-opus-4-6"
- @asynccontextmanager
- async def refusing(backends, *, external_processes=True):
- raise NativeMigrationBlockedError("native_runtime_busy", backends)
- yield # pragma: no cover - required async context-manager shape
- service.migration_guard = refusing
- with pytest.raises(ModelHubError) as refusal:
- asyncio.run(service.set_agent_mode("claude", start))
+def test_a_mode_switch_whose_runtime_adoption_failed_is_finished_by_a_retry(tmp_path):
+ """MH-MIG-011: a committed switch counts as applied only once the runtime adopted it."""
+ service, store, _adapter = _service(tmp_path)
+ service.migration_home = tmp_path / "native-home"
+ store.config.agents["claude"].mode = "hub"
+ attempts = []
- assert refusal.value.code == "mode_switch_blocked"
- assert store.config.agents["claude"].mode == target
+ async def catalog_changed(backend):
+ attempts.append(backend)
+ if len(attempts) == 1:
+ raise RuntimeError("runtime refresh failed")
+
+ service.backend_catalog_changed = catalog_changed
+
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.set_agent_mode("claude", "direct"))
+ assert store.config.agents["claude"].mode == "direct"
+
+ assert asyncio.run(service.set_agent_mode("claude", "direct"))["mode"] == "direct"
+ assert attempts == ["claude", "claude"]
+ asyncio.run(service.set_agent_mode("claude", "direct"))
+ assert attempts == ["claude", "claude"]
async def _confirm_guard(call):
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 5457bf626..31598a5e1 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -85,6 +85,7 @@ from core.handlers.model_hub.turn_gateway import (
from core.handlers.model_hub.stream_wire import ProtocolSSEState, ProtocolUsageReport
from core.handlers.model_hub.usage import BoundedUsageLedger, UsageWriter, _ledger_executor
from core.run_settlement import (
+ SETTLED_BY_BACKEND_DISABLED,
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLED_BY_STOPPED,
SETTLED_BY_TERMINAL_RESULT,
@@ -1883,8 +1884,11 @@ def test_gateway_attributes_a_request_only_to_a_turn_that_claims_its_model(
}
+# Both are the user's own cancellation: a Stop, or turning the backend off.
[email protected]("settled_by", [SETTLED_BY_STOPPED, SETTLED_BY_BACKEND_DISABLED])
def test_a_canceled_turn_reports_the_attempt_it_waited_on_longest(
tmp_path: Path,
+ settled_by: str,
) -> None:
"""A turn holding several requests reports the one in flight the longest.
@@ -1925,7 +1929,7 @@ def test_a_canceled_turn_reports_the_attempt_it_waited_on_longest(
# Cancelled while both are open, before either has settled.
registry.settle(
"turn_live01",
- settled_by=SETTLED_BY_STOPPED,
+ settled_by=settled_by,
ts=NOW.isoformat(),
)
diff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.py
index 54c8cae13..6519e8f1f 100644
--- a/tests/test_model_hub_native_takeover.py
+++ b/tests/test_model_hub_native_takeover.py
@@ -27,44 +27,26 @@ from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
@pytest.mark.parametrize("native_present", [False, True])
[email protected]("boundary", ["entry", "verify"])
def test_mode_only_adoption_never_imports_native_auth(
- monkeypatch, tmp_path, backend, native_present, boundary,
+ monkeypatch, tmp_path, backend, native_present,
):
home = tmp_path / "native"
_isolate_native_home(monkeypatch, home)
service, store, adapter = _service(tmp_path, migration_home=home)
store.config.agents[backend].mode = "direct"
assert service.migration_scan()["items"] == []
- checks = []
-
- def login():
- if native_present:
- if backend == "claude":
- _write_claude_oauth(home)
- elif backend == "codex":
- _write_codex_oauth(home)
- else:
- _write(home / ".local/share/opencode/auth.json",
- '{"openai":{"type":"api","key":"fixture-key"}}')
+ if native_present:
+ if backend == "claude":
+ _write_claude_oauth(home)
+ elif backend == "codex":
+ _write_codex_oauth(home)
+ else:
+ _write(home / ".local/share/opencode/auth.json",
+ '{"openai":{"type":"api","key":"fixture-key"}}')
- @asynccontextmanager
- async def guard(backends, *, external_processes=True):
- assert backends == (backend,)
- assert not service._mutation_lock.locked()
- if boundary == "entry":
- login()
- async def verify():
- checks.append(True)
- if boundary == "verify":
- login()
- yield verify
-
- service.migration_guard = guard
# Migration is optional: native auth stays native beside the Hub and is
# still offered for takeover afterwards.
assert asyncio.run(service.set_agent_mode(backend, "hub"))["mode"] == "hub"
- assert checks
assert bool(service.migration_scan()["items"]) is native_present
assert not store.config.sources
assert not adapter.provisioned and not adapter.oauth_provisioned
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 8b726dc89..31ce9af56 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -30,8 +30,6 @@ from modules.agents.model_hub import OpenCodeOverlay, launch_for_context
from modules.agents.service import AgentService
from modules.agents.opencode.agent import OpenCodeAgent
from modules.agents.opencode.server import (
- OpenCodeManagedPolicyRefreshPendingError,
- OpenCodeModelHubOverlayRequiredError,
OpenCodeRuntimeConfigInvalidError,
)
from modules.agents.opencode.poll_loop import (
@@ -40,6 +38,7 @@ from modules.agents.opencode.poll_loop import (
)
from modules.agents.opencode.utils import resolve_opencode_reasoning_effort
from core.native_dispatch_phase import prewrite_failure_evidence
+from tests.opencode_generation_fakes import serve_opencode_agent
from tests.scenario_harness.model_hub import (
UNLISTED_MODEL,
unlisted_model_copy,
@@ -56,22 +55,6 @@ class _StubConfig(BaseIMConfig):
return None
-def test_opencode_policy_refresh_failure_is_localized() -> None:
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.controller = type(
- "Controller",
- (),
- {"config": type("Config", (), {"language": "zh"})()},
- )()
-
- display = agent._server_start_error_display_text(
- OpenCodeManagedPolicyRefreshPendingError("internal diagnostic")
- )
-
- assert "仍在完成已有回合" in display
- assert "internal diagnostic" not in display
-
-
def test_opencode_runtime_config_failure_is_localized() -> None:
agent = OpenCodeAgent.__new__(OpenCodeAgent)
agent.controller = type(
@@ -88,22 +71,6 @@ def test_opencode_runtime_config_failure_is_localized() -> None:
assert "internal diagnostic" not in display
-def test_opencode_model_hub_overlay_failure_is_localized() -> None:
- agent = OpenCodeAgent.__new__(OpenCodeAgent)
- agent.controller = type(
- "Controller",
- (),
- {"config": type("Config", (), {"language": "zh"})()},
- )()
-
- display = agent._server_start_error_display_text(
- OpenCodeModelHubOverlayRequiredError("internal diagnostic")
- )
-
- assert "准备 Gateway 模式" in display
- assert "internal diagnostic" not in display
-
-
def test_opencode_resource_failure_preserves_zero_pid_count() -> None:
agent = OpenCodeAgent.__new__(OpenCodeAgent)
agent.controller = type(
@@ -128,7 +95,6 @@ def test_opencode_hub_turn_with_empty_menu_uses_overlay_and_keeps_server_running
monkeypatch,
) -> None:
calls: list[str] = []
- reservation = object()
empty_overlay = OpenCodeOverlay(
path=Path("/tmp/opencode-empty-overlay.json"),
content_hash="empty-overlay-hash",
@@ -153,23 +119,12 @@ def test_opencode_hub_turn_with_empty_menu_uses_overlay_and_keeps_server_running
return empty_overlay
class _Server:
- async def configure_model_hub_overlay(self, overlay):
- assert overlay is empty_overlay
- calls.append("configure")
- return reservation
-
- async def release_model_hub_overlay_reservation(self, value):
- assert value is reservation
- calls.append("release")
-
- async def ensure_running(self):
- calls.append("ensure")
+ async def ensure_directory_ready(self, _path):
+ calls.append("ready")
+ raise RuntimeError("test boundary after server start")
server = _Server()
- async def _get_server():
- return server
-
async def _emit_failure(*_args, **_kwargs):
calls.append("failure")
@@ -191,14 +146,9 @@ def test_opencode_hub_turn_with_empty_menu_uses_overlay_and_keeps_server_running
agent = OpenCodeAgent.__new__(OpenCodeAgent)
agent.controller = controller
agent.config = controller.config
- agent._get_server = _get_server
+ runtime = serve_opencode_agent(agent, server)
+ agent._session_manager = SimpleNamespace(ensure_working_dir=AsyncMock())
agent._remove_ack_reaction = _remove_ack
-
- def _finish_after_start(_server):
- calls.append("attach")
- raise RuntimeError("test boundary after server start")
-
- agent._attach_server_activation = _finish_after_start
request = AgentRequest(
context=MessageContext(
user_id="user",
@@ -214,9 +164,17 @@ def test_opencode_hub_turn_with_empty_menu_uses_overlay_and_keeps_server_running
session_key="slack::channel",
)
- asyncio.run(agent._process_message(request))
+ async def _run():
+ await agent._process_message(request)
+ await asyncio.gather(*agent._lifecycle_tasks)
+
+ asyncio.run(_run())
- assert calls == ["configure", "ensure", "attach", "release", "failure", "ack"]
+ # An empty Hub menu still launches on its overlay: the overlay is the
+ # spec input, the turn reaches the generation, and its binding is released.
+ assert [spec.overlay for spec in runtime.specs] == [empty_overlay]
+ assert calls == ["ready", "failure", "ack"]
+ assert [binding.released for binding in runtime.bindings] == [True]
@pytest.mark.parametrize("language", ["en", "zh"])
@@ -231,12 +189,6 @@ def test_opencode_turn_on_an_unlisted_model_fails_once_with_the_shared_copy(
explicit retry."""
class _Server:
- async def configure_model_hub_overlay(self, overlay):
- return None
-
- async def ensure_running(self):
- return None
-
async def ensure_directory_ready(self, _path):
return None
@@ -246,9 +198,6 @@ def test_opencode_turn_on_an_unlisted_model_fails_once_with_the_shared_copy(
async def abort_session(self, _session_id, _path):
return None
- async def _get_server():
- return server
-
async def _noop(*_args, **_kwargs):
return None
@@ -265,7 +214,7 @@ def test_opencode_turn_on_an_unlisted_model_fails_once_with_the_shared_copy(
agent = OpenCodeAgent.__new__(OpenCodeAgent)
agent.controller = controller
agent.config = controller.config
- agent._get_server = _get_server
+ serve_opencode_agent(agent, server)
agent._delete_ack = _noop
agent._remove_ack_reaction = _noop
agent.record_model_hub_native_failure = _noop
@@ -1180,8 +1129,6 @@ def test_opencode_fork_prompt_marks_target_session_id_authoritative():
calls = []
class _Server:
- async def ensure_running(self):
- return None
async def ensure_directory_ready(self, directory):
return None
@@ -1234,8 +1181,7 @@ def test_opencode_fork_prompt_marks_target_session_id_authoritative():
async def run_prompt_poll(self, *args, **kwargs):
return "done", True
- async def _get_server():
- return _Server()
+ server = _Server()
async def _async_noop():
return None
@@ -1279,7 +1225,7 @@ def test_opencode_fork_prompt_marks_target_session_id_authoritative():
agent._session_manager = _SessionManager()
agent._poll_loop = _PollLoop()
agent._steering_states = {}
- agent._get_server = _get_server
+ serve_opencode_agent(agent, server)
agent._delete_ack = lambda request: _async_noop()
agent._remove_ack_reaction = lambda request: _async_noop()
agent.emit_result_message = lambda *args, **kwargs: _async_noop()
@@ -1384,8 +1330,6 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(
set_dispatch_phase(request_context, DISPATCH_PHASE_PREWRITE)
class _Server:
- async def ensure_running(self):
- return None
async def ensure_directory_ready(self, directory):
return None
@@ -1461,8 +1405,7 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(
def get_opencode_overrides(self, context):
return None, None, None
- async def _get_server():
- return _Server()
+ server = _Server()
async def _async_noop():
return None
@@ -1480,7 +1423,7 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(
agent._session_manager = _SessionManager()
agent._poll_loop = _PollLoop()
agent._steering_states = {}
- agent._get_server = _get_server
+ serve_opencode_agent(agent, server)
agent._delete_ack = lambda request: _async_noop()
agent._remove_ack_reaction = _remove_ack
@@ -2724,8 +2667,6 @@ def test_opencode_restored_poll_settles_error_after_retry_budget(monkeypatch):
controller = _Controller()
sessions = _Sessions()
- async def _get_server(self):
- return server
def _extract_response_text(self, message):
return ""
@@ -2751,7 +2692,7 @@ def test_opencode_restored_poll_settles_error_after_retry_budget(monkeypatch):
prompt_started_at=time.time(),
)
- terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))
+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll, server))
assert terminal is True
assert removed == []
@@ -2849,8 +2790,6 @@ def test_opencode_restored_poll_keeps_empty_completion_successful():
sessions = _Sessions()
im_client = type("IM", (), {"formatter": _Formatter()})()
- async def _get_server(self):
- return server
def _get_formatter(self, context):
return _Formatter()
@@ -2882,7 +2821,7 @@ def test_opencode_restored_poll_keeps_empty_completion_successful():
)
loop = OpenCodePollLoop(_Agent())
- terminal = asyncio.run(loop.run_restored_poll_loop(poll))
+ terminal = asyncio.run(loop.run_restored_poll_loop(poll, server))
assert diagnostics == []
assert terminal is True
@@ -2955,8 +2894,6 @@ def test_opencode_restored_poll_emits_intermediate_assistant_once():
controller = _Controller()
sessions = _Sessions()
- async def _get_server(self):
- return server
def _extract_response_text(self, message):
return "".join(part.get("text", "") for part in message.get("parts", []))
@@ -2980,7 +2917,7 @@ def test_opencode_restored_poll_emits_intermediate_assistant_once():
prompt_started_at=time.time(),
)
- assert asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll)) is True
+ assert asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll, server)) is True
assert [item for item in emitted if item[0] == "assistant"] == [("assistant", "msg-new")]
assert ("result", "done") in emitted
@@ -3058,8 +2995,6 @@ def test_opencode_restored_poll_settles_after_consecutive_transport_failures(
controller = _Controller()
sessions = _Sessions()
- async def _get_server(self):
- return server
async def _remove_ack_reaction(self, request):
return None
@@ -3079,7 +3014,7 @@ def test_opencode_restored_poll_settles_after_consecutive_transport_failures(
prompt_started_at=time.time(),
)
- terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))
+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll, server))
assert aborted == [("oc-restored-transport-dead", "/tmp/work")]
assert terminal is True
@@ -3154,8 +3089,6 @@ def test_opencode_restored_poll_consumes_original_timeout_budget():
controller = _Controller()
sessions = _Sessions()
- async def _get_server(self):
- return server
async def _remove_ack_reaction(self, request):
return None
@@ -3175,7 +3108,7 @@ def test_opencode_restored_poll_consumes_original_timeout_budget():
prompt_started_at=time.time() - 1,
)
- terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))
+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll, server))
assert list_calls == []
assert aborted == [("oc-restored-timeout", "/tmp/work")]
@@ -3650,8 +3583,6 @@ def test_mh_chan_001_opencode_restored_poll_records_source_failure():
controller = _Controller()
sessions = _Sessions()
- async def _get_server(self):
- return server
def _extract_response_text(self, message):
return ""
@@ -3691,7 +3622,7 @@ def test_mh_chan_001_opencode_restored_poll_records_source_failure():
},
)
- terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))
+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll, server))
assert model_hub_failures == [
(
@@ -3987,10 +3918,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
active_polls = []
active_poll_updates = []
recovery_order = []
- overlay_reservation = object()
- configured_overlays = []
active_registrations = []
- released_reservations = []
prompt_skill_cwds = []
def build_prompt(**kwargs):
@@ -4003,13 +3931,6 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
)
class _Server:
- async def configure_model_hub_overlay(self, overlay):
- configured_overlays.append(overlay)
- return overlay_reservation
-
- async def ensure_running(self):
- return None
-
async def ensure_directory_ready(self, directory):
return None
@@ -4034,11 +3955,8 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
recovery_order.append("prompt")
calls.append(kwargs)
- async def mark_run_active(self, session_id, *, overlay_reservation=None):
- active_registrations.append((session_id, overlay_reservation))
-
- async def release_model_hub_overlay_reservation(self, reservation):
- released_reservations.append(reservation)
+ async def mark_run_active(self, session_id):
+ active_registrations.append(session_id)
async def mark_run_inactive(self, session_id):
return None
@@ -4085,8 +4003,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
async def run_prompt_poll(self, *args, **kwargs):
return "done", True
- async def _get_server():
- return _Server()
+ server = _Server()
async def _async_noop():
return None
@@ -4107,6 +4024,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
{
"default_provider": "openai",
"default_reasoning_effort": "high",
+ "error_retry_limit": 0,
},
)(),
},
@@ -4125,11 +4043,12 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
agent.im_client = agent.controller.im_client
agent.settings_manager = agent.controller.settings_manager
agent.sessions = agent.controller.sessions
- agent.opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()
+ # One ``agents.opencode`` object, as in production.
+ agent.opencode_config = agent.controller.config.opencode
agent._session_manager = _SessionManager()
agent._poll_loop = _PollLoop()
agent._steering_states = {}
- agent._get_server = _get_server
+ runtime = serve_opencode_agent(agent, server)
agent._delete_ack = lambda request: _async_noop()
agent._remove_ack_reaction = lambda request: _async_noop()
agent.emit_result_message = lambda *args, **kwargs: _async_noop()
@@ -4155,6 +4074,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
vibe_agent_system_prompt=custom_prompt,
)
await agent._process_message(request)
+ await asyncio.gather(*agent._lifecycle_tasks)
asyncio.run(_run())
@@ -4169,9 +4089,12 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, c
assert calls[0]["attempt_id"] == ATTEMPT_ID
assert "message_id" not in calls[0]
assert recovery_order[:3] == ["poll", "prompt", "accepted"]
- assert configured_overlays == [None]
- assert active_registrations == [("oc-session", overlay_reservation)]
- assert released_reservations == []
+ # A Direct turn's spec has no overlay; its run is marked on its own
+ # generation, which the turn pins until it settles.
+ assert [spec.overlay for spec in runtime.specs] == [None]
+ assert active_registrations == ["oc-session"]
+ assert [binding.released for binding in runtime.bindings] == [True]
+ assert active_polls[0]["processing_indicator"]["opencode_generation_id"] == "ocg_test"
assert active_poll_updates[0][0] == "oc-session"
assert isinstance(active_poll_updates[0][1]["prompt_started_at"], float)
steering_snapshot = active_polls[0]["processing_indicator"]["opencode_native_steering"]
diff --git a/tests/test_native_login_single_flight.py b/tests/test_native_login_single_flight.py
index f64253570..c4e0cc756 100644
--- a/tests/test_native_login_single_flight.py
+++ b/tests/test_native_login_single_flight.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock
import pytest
+from tests.opencode_generation_fakes import lease_returning
from core.agent_auth_service import (
OPENCODE_DIRECT_SETUP_URLS,
AgentAuthFlow,
@@ -104,7 +105,7 @@ async def test_every_web_backend_publishes_deadline_after_startup_with_waiter(
)
service._start_codex_process = start_codex
service._start_claude_control_flow = start_claude
- service._opencode_server = AsyncMock(return_value=server)
+ service._lease_opencode_server = lease_returning(server)
service._wait_for_codex_completion_web = AsyncMock()
service._wait_for_claude_completion_web = AsyncMock()
service._wait_for_opencode_oauth_web = AsyncMock()
diff --git a/tests/test_native_takeover_lifecycle.py b/tests/test_native_takeover_lifecycle.py
index 7925f1749..f588d4c8a 100644
--- a/tests/test_native_takeover_lifecycle.py
+++ b/tests/test_native_takeover_lifecycle.py
@@ -23,6 +23,7 @@ from core.backend_restart import (
native_cli_processes,
pending_native_backends,
)
+from tests.codex_generation_support import init_generation_state, install_codex_transport
def controller_fixture(*, backends=("claude", "codex", "opencode"), busy=False):
@@ -52,7 +53,7 @@ def controller_fixture(*, backends=("claude", "codex", "opencode"), busy=False):
config=SimpleNamespace(),
)
coordinator = BackendRestartCoordinator(
- controller, AsyncMock(), process_inventory=Mock(return_value=()), drain_timeout=0.01, settle_timeout=0.01,
+ controller, AsyncMock(), renew=AsyncMock(), process_inventory=Mock(return_value=()), settle_timeout=0.01,
poll_interval=0.001,
)
controller.backend_restart_coordinator = coordinator
@@ -175,15 +176,11 @@ async def test_guard_closes_both_admissions_before_retirement_and_retains_only_b
@pytest.mark.asyncio
[email protected]("drain_timeout", [1, 0])
-async def test_busy_guard_interrupts_running_work_then_retires_and_yields(drain_timeout):
+async def test_busy_guard_interrupts_running_work_then_retires_and_yields():
"""MH-MIG-009: every caller applies an explicit user switch, so live work is
- interrupted, not awaited; a guard that waits for idle leaves the switch spinning.
- The settle window is independent of the drain timeout, which only decides when
- a restart stops waiting: an immediate drain must not refuse a brief teardown."""
+ interrupted, not awaited; a guard that waits for idle leaves the switch spinning."""
controller, coordinator, admissions, turns = controller_fixture(busy=True)
service = controller.agent_service
- coordinator._drain_timeout = drain_timeout
coordinator._settle_timeout = 1
controller.session_turns.active_runtime_session_ids_for_backend.return_value = {"session-1"}
order = []
@@ -201,7 +198,7 @@ async def test_busy_guard_interrupts_running_work_then_retires_and_yields(drain_
order.append("mutate")
assert order == [("cancel", "codex"), ("refresh", "codex", True), "retire", "mutate"]
controller.session_turns.release_for_backend_refresh.assert_awaited_once_with(
- backend="codex", base_session_ids={"session-1"},
+ backend="codex", base_session_ids={"session-1"}, settled_by="backend_refresh",
)
assert not admissions and not turns
@@ -216,7 +213,7 @@ async def test_switch_waits_out_a_teardown_that_takes_its_bounded_worst_case(mon
controller, _, admissions, turns = controller_fixture(busy=True)
service = controller.agent_service
coordinator = BackendRestartCoordinator(
- controller, AsyncMock(), process_inventory=Mock(return_value=()), drain_timeout=0.01, poll_interval=0.001,
+ controller, AsyncMock(), renew=AsyncMock(), process_inventory=Mock(return_value=()), poll_interval=0.001,
)
controller.backend_restart_coordinator = coordinator
loop = asyncio.get_running_loop()
@@ -436,15 +433,23 @@ async def test_live_auth_lease_refuses_migration_before_admission_closes():
@pytest.mark.asyncio
-async def test_restart_task_and_migration_have_one_owner():
- controller, coordinator, admissions, turns = controller_fixture(busy=True)
- coordinator._drain_timeout = 1
- assert await coordinator.request_restart("codex") == "draining"
+async def test_maintenance_and_migration_have_one_owner():
+ controller, coordinator, admissions, turns = controller_fixture()
+ installing = asyncio.Event()
+ finish = asyncio.Event()
+
+ async def install():
+ installing.set()
+ await finish.wait()
+ return {"ok": True}
+
+ maintenance = asyncio.create_task(coordinator.run_when_idle("codex", install))
+ await installing.wait()
with pytest.raises(NativeMigrationBlockedError, match="backend_restart_in_progress"):
async with coordinator.migration_guard(("codex",)):
- pytest.fail("competing restart")
- controller.agent_service.backend_runtime_active.return_value = False
- await coordinator.wait("codex")
+ pytest.fail("competing maintenance")
+ finish.set()
+ assert await maintenance == {"ok": True}
assert not admissions and not turns
@@ -795,36 +800,65 @@ async def test_terminal_ttl_does_not_drop_failed_cleanup_owner(monkeypatch):
await service._cleanup_native_flow(flow)
-async def test_codex_strict_retirement_propagates_stop_failure():
+def _codex_migration_agent(transport, *, activation=None):
from modules.agents.codex.agent import CodexAgent
- transport = SimpleNamespace()
- agent = CodexAgent.__new__(CodexAgent)
- agent._transports = {"cwd": transport}
- agent._transport_locks = {}
- agent._stop_and_detach_transport_generation = AsyncMock(side_effect=RuntimeError("stop failed"))
- agent._session_mgr = SimpleNamespace(all_base_sessions=Mock(return_value=["session"]), invalidate_thread=Mock())
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent.controller = SimpleNamespace(runtime_activation=activation)
+ agent._session_mgr = SimpleNamespace(
+ all_base_sessions=Mock(return_value=["session"]),
+ sessions_for_cwd=Mock(return_value=["session"]),
+ invalidate_thread=Mock(),
+ )
+ agent._turn_registry = SimpleNamespace(get_active_turn=Mock(return_value=None), clear_session=Mock())
+ agent._ownership_snapshots = AsyncMock(
+ return_value=(SimpleNamespace(blocks_transport_replacement=False, blocks_dead_transport_replacement=False),)
+ )
+ identity = activation.attach("codex", "cwd#1") if activation is not None else None
+ install_codex_transport(agent, "cwd", transport, activation=identity, sessions={"session": "thread"})
+ return agent, identity
+
+
+async def test_codex_strict_retirement_propagates_stop_failure():
+ transport = SimpleNamespace(stop=AsyncMock(side_effect=RuntimeError("stop failed")), _process=None)
+ agent, _identity = _codex_migration_agent(transport)
with pytest.raises(RuntimeError, match="stop failed"):
await agent.retire_for_native_migration()
- assert agent._transports["cwd"] is transport
+ assert [generation.runtime.transport for generation in agent._units["cwd"].generations] == [transport]
+ assert agent.transport_for_session("session") is transport
agent._session_mgr.invalidate_thread.assert_not_called()
+async def test_codex_strict_retirement_ignores_a_turn_left_on_an_exited_process():
+ # A crash mid-turn leaves the turn registered; it cannot run on, so it must
+ # not refuse the migration on every retry.
+ process = SimpleNamespace(returncode=-9, wait=AsyncMock())
+ transport = SimpleNamespace(_process=process, stop=AsyncMock(), is_alive=False)
+ agent, _identity = _codex_migration_agent(transport)
+ agent._turn_registry.get_active_turn = Mock(return_value="turn-lost-with-the-process")
+
+ await agent.retire_for_native_migration()
+
+ assert agent._units["cwd"].generations == ()
+ assert agent.transport_for_session("session") is None
+
+
@pytest.mark.asyncio
async def test_codex_strict_retirement_checks_exit_before_detaching():
- from modules.agents.codex.agent import CodexAgent
+ from core.runtime_activation import RuntimeActivationRegistry
process = SimpleNamespace(returncode=None, wait=AsyncMock())
transport = SimpleNamespace(_process=process, stop=AsyncMock())
- agent = CodexAgent.__new__(CodexAgent)
- agent._reserve_transport_retirement = Mock(return_value="generation")
- agent._finish_transport_retirement = Mock(return_value=True)
- agent._detach_transport_bookkeeping = Mock(return_value=True)
+ activation = RuntimeActivationRegistry()
+ agent, identity = _codex_migration_agent(transport, activation=activation)
with pytest.raises(RuntimeError, match="did not exit"):
- await agent._stop_and_detach_transport_generation("cwd", transport, require_process_exit=True)
- agent._finish_transport_retirement.assert_called_once_with("generation", retire=False)
- agent._detach_transport_bookkeeping.assert_not_called()
+ await agent.retire_for_native_migration()
+ # The aborted retirement leaves the exact generation live and bound.
+ assert activation.is_current(identity)
+ assert agent.transport_for_session("session") is transport
+ agent._session_mgr.invalidate_thread.assert_not_called()
@pytest.mark.asyncio
@@ -859,41 +893,51 @@ async def test_claude_retirement_never_uses_broad_reaper_or_swallows_disconnect(
@pytest.mark.asyncio
-async def test_opencode_unproven_pid_file_is_blocker_not_kill_target():
- from modules.agents.opencode.server import OpenCodeServerManager
-
- server = OpenCodeServerManager.__new__(OpenCodeServerManager)
- server._get_lock = lambda: asyncio.Lock()
- server._active_requests = 0
- server._has_active_run_sessions = Mock(return_value=False)
- server._runtime_activation_retire = Mock(return_value=True)
- server._process = None
- server.port = 4096
- server._read_pid_file = Mock(return_value={"pid": 123})
- server._pid_exists = Mock(return_value=True)
- server._terminate_pid_tree_sync = Mock(side_effect=AssertionError("must not kill"))
- server._clear_pid_file = Mock()
- with pytest.raises(RuntimeError, match="ownership cannot be proven"):
- await server.retire_for_native_migration()
- server._terminate_pid_tree_sync.assert_not_called()
- server._clear_pid_file.assert_not_called()
+async def test_opencode_reused_pid_record_is_dropped_not_killed(tmp_path, monkeypatch):
+ from modules.agents.opencode import server as opencode_server
+
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: tmp_path)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: tmp_path / "legacy.json")
+ record = tmp_path / "ocg_reused.json"
+ record.write_text(
+ json.dumps({"generation_id": "ocg_reused", "pid": os.getpid(), "port": 4100, "process_created_at": 1.0}),
+ encoding="utf-8",
+ )
+ terminate = Mock(side_effect=AssertionError("must not kill"))
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", terminate)
+
+ # The pid now belongs to another process born later than the record says.
+ assert await opencode_server.adopt_recorded_generations() == []
+
+ terminate.assert_not_called()
+ assert not record.exists()
@pytest.mark.asyncio
-async def test_opencode_strict_stop_failure_retains_tracking():
- from modules.agents.opencode.server import OpenCodeServerManager
-
- server = OpenCodeServerManager.__new__(OpenCodeServerManager)
- server._get_lock = lambda: asyncio.Lock()
- server._active_requests = 0
- server._has_active_run_sessions = Mock(return_value=False)
- server._runtime_activation_retire = Mock(return_value=True)
- process = SimpleNamespace(pid=123, returncode=None, wait=AsyncMock())
- server._process = process
- server._read_pid_file = Mock(return_value={"pid": 123})
- server._terminate_pid_tree_sync = Mock(return_value=False)
- server._clear_pid_file = Mock()
+async def test_opencode_strict_stop_failure_retains_tracking(tmp_path, monkeypatch):
+ from modules.agents.opencode import server as opencode_server
+ from modules.agents.opencode.client_manager import OpenCodeRuntime
+
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: tmp_path)
+ generation = opencode_server.OpenCodeGeneration(
+ generation_id="ocg_stuck",
+ pid=4321,
+ port=4100,
+ spec_digest="spec",
+ process_created_at=1.0,
+ )
+ generation.write_record()
+ monkeypatch.setattr(generation, "process_alive", lambda: True)
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", Mock(return_value=False))
+ runtime = OpenCodeRuntime(SimpleNamespace(binary="opencode", request_timeout_seconds=60))
+ runtime._adopted = True
+ wrapper = await runtime._generations.adopt(SimpleNamespace(digest="spec"), generation, current=True)
+ runtime._wrappers[generation.generation_id] = wrapper
+
with pytest.raises(RuntimeError, match="did not exit"):
- await server.retire_for_native_migration()
- assert server._process is process
- server._clear_pid_file.assert_not_called()
+ await runtime.retire_all_strict()
+
+ # The survivor stays tracked and recorded, never to serve again.
+ assert runtime.generations() == (generation,)
+ assert wrapper.closed
+ assert generation.record_path.exists()
diff --git a/tests/test_native_writer_custody.py b/tests/test_native_writer_custody.py
index 4526b42b2..9433229a4 100644
--- a/tests/test_native_writer_custody.py
+++ b/tests/test_native_writer_custody.py
@@ -32,7 +32,7 @@ def no_live_operations(monkeypatch):
monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
monkeypatch.setattr(psutil, "process_iter", forbidden)
monkeypatch.setattr(api, "restart_backend", Mock(return_value={"ok": True}))
- monkeypatch.setattr(api, "_opencode_get_server", AsyncMock(return_value=None))
+ monkeypatch.setattr(api, "_opencode_lease", AsyncMock(return_value=None))
monkeypatch.setattr(api, "_config_recovery_message", lambda: None)
@@ -305,7 +305,7 @@ async def test_non_auth_rmw_is_excluded_before_first_read(monkeypatch, kind, blo
"native_auth_in_progress" if blocker == "lease" else "migration_recovery_pending"
)
assert path.read_bytes() == before
- api._opencode_get_server.assert_not_awaited()
+ api._opencode_lease.assert_not_awaited()
finally:
lease.release()
diff --git a/tests/test_opencode_client_manager.py b/tests/test_opencode_client_manager.py
deleted file mode 100644
index cce4e1c5a..000000000
--- a/tests/test_opencode_client_manager.py
+++ /dev/null
@@ -1,73 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import sys
-from pathlib import Path
-from types import SimpleNamespace
-
-sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-
-from modules.agents.opencode import client_manager as client_manager_module
-from modules.agents.opencode.client_manager import OpenCodeClientManager
-
-
-def test_reset_config_keeps_existing_server_manager_until_refresh_completes(monkeypatch) -> None:
- old_config = SimpleNamespace(binary="/old/opencode", port=4096, request_timeout_seconds=60)
- new_config = SimpleNamespace(binary="/new/opencode", port=4100, request_timeout_seconds=15)
- existing_server = SimpleNamespace()
- created = []
-
- async def _get_instance(**kwargs):
- created.append(kwargs)
- return existing_server
-
- monkeypatch.setattr(client_manager_module.OpenCodeServerManager, "get_instance", _get_instance)
-
- async def _run():
- manager = OpenCodeClientManager(old_config)
- first = await manager.get_server()
- previous = await manager.reset_config(new_config)
- second = await manager.get_server()
- return first, previous, second
-
- first, previous, second = asyncio.run(_run())
- assert first is existing_server
- assert previous is existing_server
- assert second is existing_server
- assert created == [
- {
- "binary": "/old/opencode",
- "port": 4096,
- "request_timeout_seconds": 60,
- "resource_governor": None,
- }
- ]
-
-
-def test_model_hub_overlay_preparer_is_attached_to_lazy_server(monkeypatch) -> None:
- config = SimpleNamespace(binary="opencode", port=4096, request_timeout_seconds=60)
- server = SimpleNamespace(set_model_hub_overlay_preparer=lambda preparer: None)
- attached = []
- server.set_model_hub_overlay_preparer = attached.append
-
- async def _get_instance(**kwargs):
- return server
-
- async def _prepare_overlay():
- return None
-
- monkeypatch.setattr(
- client_manager_module.OpenCodeServerManager,
- "get_instance",
- _get_instance,
- )
-
- async def _run():
- manager = OpenCodeClientManager(config)
- manager.set_model_hub_overlay_preparer(_prepare_overlay)
- return await manager.get_server()
-
- result = asyncio.run(_run())
-
- assert result is server
- assert attached == [_prepare_overlay]
diff --git a/tests/test_opencode_config_reconciler.py b/tests/test_opencode_config_reconciler.py
deleted file mode 100644
index b466c9cf9..000000000
--- a/tests/test_opencode_config_reconciler.py
+++ /dev/null
@@ -1,388 +0,0 @@
-from modules.agents.opencode.config_reconciler import OpenCodeConfigReconciler
-
-
-def _reconcile(user_config, live_config=None, auth_entries=None):
- return OpenCodeConfigReconciler().reconcile(
- user_config=user_config,
- live_config=live_config or {},
- auth_entries=auth_entries or {},
- )
-
-
-def test_user_config_is_top_level_source_of_truth():
- assert _reconcile(
- {"provider": {"deepseek": {"options": {"baseURL": "https://api.deepseek.com"}}}},
- {
- "permission": "allow",
- "model": "openai/gpt-5",
- "provider": {"deepseek": {"options": {"baseURL": "https://old.example"}}},
- },
- ) == {
- "provider": {"deepseek": {"options": {"baseURL": "https://api.deepseek.com"}}}
- }
-
-
-def test_user_options_do_not_resurrect_live_deleted_keys():
- assert _reconcile(
- {"provider": {"openai": {"options": {"apiKey": "sk-config"}}}},
- {
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-config",
- "baseURL": "https://deleted.example/v1",
- }
- }
- }
- },
- )["provider"]["openai"]["options"] == {"apiKey": "sk-config"}
-
-
-def test_missing_user_options_drops_live_options_without_auth():
- provider = _reconcile(
- {"provider": {"deepseek": {"models": {"deepseek-v4": {"id": "deepseek-v4"}}}}},
- {
- "provider": {
- "deepseek": {
- "options": {
- "apiKey": "sk-stale",
- "baseURL": "https://stale.example",
- },
- "models": {"deepseek-v4": {"id": "deepseek-v4"}},
- }
- }
- },
- )["provider"]["deepseek"]
-
- assert "options" not in provider
- assert provider["models"] == {"deepseek-v4": {"id": "deepseek-v4"}}
-
-
-def test_missing_user_options_preserves_auth_json_api_key():
- provider = _reconcile(
- {"provider": {"deepseek": {"models": {"deepseek-v4": {"id": "deepseek-v4"}}}}},
- {
- "provider": {
- "deepseek": {
- "options": {
- "apiKey": "sk-stale-live",
- "baseURL": "https://stale.example",
- },
- "models": {"deepseek-v4": {"id": "deepseek-v4"}},
- }
- }
- },
- {"deepseek": {"type": "api", "key": "sk-auth-json"}},
- )["provider"]["deepseek"]
-
- assert provider["options"] == {"apiKey": "sk-auth-json"}
- assert provider["models"] == {"deepseek-v4": {"id": "deepseek-v4"}}
-
-
-def test_auth_json_key_overrides_stale_live_key_when_user_has_options():
- assert _reconcile(
- {"provider": {"openai": {"options": {"baseURL": "https://relay.example/v1"}}}},
- {
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-old-live",
- "baseURL": "https://old.example/v1",
- }
- }
- }
- },
- {"openai": {"type": "api", "key": "sk-new-auth"}},
- )["provider"]["openai"]["options"] == {
- "baseURL": "https://relay.example/v1",
- "apiKey": "sk-new-auth",
- }
-
-
-def test_oauth_user_provider_does_not_reintroduce_stale_api_key():
- assert _reconcile(
- {"provider": {"openai": {"options": {"baseURL": "https://relay.example/v1"}}}},
- {
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-stale",
- "baseURL": "https://old.example/v1",
- }
- }
- }
- },
- {"openai": {"type": "oauth", "refresh": "oauth-refresh"}},
- )["provider"]["openai"]["options"] == {"baseURL": "https://relay.example/v1"}
-
-
-def test_user_models_do_not_resurrect_live_deleted_models():
- assert _reconcile(
- {
- "provider": {
- "deepseek": {
- "options": {"baseURL": "https://api.deepseek.com"},
- "models": {"keep-model": {"id": "keep-model"}},
- }
- }
- },
- {
- "provider": {
- "deepseek": {
- "options": {"baseURL": "https://api.deepseek.com"},
- "models": {
- "keep-model": {"id": "keep-model"},
- "deleted-model": {"id": "deleted-model"},
- },
- }
- }
- },
- )["provider"]["deepseek"]["models"] == {"keep-model": {"id": "keep-model"}}
-
-
-def test_empty_user_models_block_drops_live_models():
- assert _reconcile(
- {
- "provider": {
- "deepseek": {
- "options": {"baseURL": "https://api.deepseek.com"},
- "models": {},
- }
- }
- },
- {
- "provider": {
- "deepseek": {
- "options": {"baseURL": "https://api.deepseek.com"},
- "models": {
- "deleted-model": {"id": "deleted-model"},
- },
- }
- }
- },
- )["provider"]["deepseek"]["models"] == {}
-
-
-def test_provider_absent_from_user_config_is_dropped_unless_auth_or_local():
- assert set(
- _reconcile(
- {"provider": {"anthropic": {"options": {"baseURL": "https://relay.example/v1"}}}},
- {
- "provider": {
- "anthropic": {"options": {"baseURL": "https://relay.example/v1"}},
- "openai": {"options": {"apiKey": "sk-stale"}},
- }
- },
- )["provider"].keys()
- ) == {"anthropic"}
-
-
-def test_auth_backed_provider_absent_from_user_config_is_preserved():
- assert set(
- _reconcile(
- {"provider": {"claude-relay": {"options": {"baseURL": "https://relay.example/v1"}}}},
- {
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-live",
- "baseURL": "https://api.openai.com/v1",
- }
- },
- "claude-relay": {"options": {"baseURL": "https://old.example/v1"}},
- }
- },
- {"openai": {"type": "oauth", "refresh": "oauth-refresh"}},
- )["provider"].keys()
- ) == {"claude-relay", "openai"}
-
-
-def test_auth_backed_provider_absent_from_user_config_uses_auth_json_key():
- openai = _reconcile(
- {"provider": {"claude-relay": {"options": {"baseURL": "https://relay.example/v1"}}}},
- {
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-old-live",
- "baseURL": "https://api.openai.com/v1",
- }
- }
- }
- },
- {"openai": {"type": "api", "key": "sk-new-auth"}},
- )["provider"]["openai"]
-
- assert openai["options"] == {
- "apiKey": "sk-new-auth",
- "baseURL": "https://api.openai.com/v1",
- }
-
-
-def test_auth_api_provider_missing_from_live_snapshot_is_preserved_from_auth_json():
- assert _reconcile(
- {"provider": {"claude-relay": {"options": {"baseURL": "https://relay.example/v1"}}}},
- {"provider": {"claude-relay": {"options": {"baseURL": "https://old.example/v1"}}}},
- {"openai": {"type": "api", "key": "sk-auth-json"}},
- )["provider"]["openai"] == {"options": {"apiKey": "sk-auth-json"}}
-
-
-def test_local_provider_absent_from_user_config_is_preserved():
- assert set(
- _reconcile(
- {"provider": {"claude-relay": {"options": {"baseURL": "https://relay.example/v1"}}}},
- {
- "provider": {
- "ollama": {
- "options": {"baseURL": "http://localhost:11434/v1"},
- "models": {"llama3.1": {"id": "llama3.1"}},
- },
- "claude-relay": {"options": {"baseURL": "https://old.example/v1"}},
- }
- },
- )["provider"].keys()
- ) == {"claude-relay", "ollama"}
-
-
-def test_local_provider_models_config_preserves_live_options():
- ollama = _reconcile(
- {"provider": {"ollama": {"models": {"custom-local": {"id": "custom-local"}}}}},
- {
- "provider": {
- "ollama": {
- "options": {"baseURL": "http://localhost:11434/v1"},
- "models": {"llama3.1": {"id": "llama3.1"}},
- }
- }
- },
- )["provider"]["ollama"]
-
- assert ollama["options"] == {"baseURL": "http://localhost:11434/v1"}
- assert ollama["models"]["custom-local"] == {"id": "custom-local"}
-
-
-def test_local_provider_user_models_are_added_to_live_models():
- ollama = _reconcile(
- {"provider": {"ollama": {"models": {"custom-local": {"id": "custom-local"}}}}},
- {
- "provider": {
- "ollama": {
- "options": {"baseURL": "http://localhost:11434/v1"},
- "models": {
- "llama3.1": {"id": "llama3.1"},
- "qwen3": {"id": "qwen3"},
- },
- }
- }
- },
- )["provider"]["ollama"]
-
- assert ollama["models"] == {
- "llama3.1": {"id": "llama3.1"},
- "qwen3": {"id": "qwen3"},
- "custom-local": {"id": "custom-local"},
- }
-
-
-def test_local_provider_deleted_user_model_is_not_restored_from_live_models():
- ollama = _reconcile(
- {"provider": {"ollama": {"models": {"kept-user-model": {"id": "kept-user-model"}}}}},
- {
- "provider": {
- "ollama": {
- "options": {"baseURL": "http://localhost:11434/v1"},
- "models": {
- "runtime-model": {"id": "runtime-model"},
- "deleted-user-model": {
- "id": "deleted-user-model",
- "name": "deleted-user-model",
- "vibe_remote": {"user_model": True},
- },
- },
- }
- }
- },
- )["provider"]["ollama"]
-
- assert ollama["models"] == {
- "runtime-model": {"id": "runtime-model"},
- "kept-user-model": {"id": "kept-user-model"},
- }
-
-
-def test_local_provider_unmarked_runtime_model_with_matching_name_is_preserved():
- ollama = _reconcile(
- {"provider": {"ollama": {"models": {"custom-local": {"id": "custom-local"}}}}},
- {
- "provider": {
- "ollama": {
- "options": {"baseURL": "http://localhost:11434/v1"},
- "models": {
- "runtime-model": {"id": "runtime-model", "name": "runtime-model"},
- },
- }
- }
- },
- )["provider"]["ollama"]
-
- assert ollama["models"] == {
- "runtime-model": {"id": "runtime-model", "name": "runtime-model"},
- "custom-local": {"id": "custom-local"},
- }
-
-
-def test_no_user_provider_section_preserves_only_auth_and_local_runtime_providers():
- assert set(
- _reconcile(
- {"model": "openai/gpt-5"},
- {
- "provider": {
- "openai": {"options": {"apiKey": "sk-old-live"}},
- "ollama": {"options": {"baseURL": "http://localhost:11434/v1"}},
- "deleted-custom": {"options": {"apiKey": "sk-deleted"}},
- }
- },
- {"openai": {"type": "api", "key": "sk-new-auth"}},
- )["provider"].keys()
- ) == {"openai", "ollama"}
-
-
-def test_local_provider_absent_from_user_config_drops_stale_user_models():
- ollama = _reconcile(
- {"model": "openai/gpt-5"},
- {
- "provider": {
- "ollama": {
- "options": {"baseURL": "http://localhost:11434/v1"},
- "models": {
- "runtime-model": {"id": "runtime-model", "name": "runtime-model"},
- "deleted-user-model": {
- "id": "deleted-user-model",
- "name": "deleted-user-model",
- "vibe_remote": {"user_model": True},
- },
- },
- }
- }
- },
- )["provider"]["ollama"]
-
- assert ollama["models"] == {
- "runtime-model": {"id": "runtime-model", "name": "runtime-model"},
- }
-
-
-def test_no_user_provider_section_preserves_auth_api_provider_missing_from_live_snapshot():
- assert _reconcile(
- {"model": "openai/gpt-5"},
- {"provider": {"ollama": {"options": {"baseURL": "http://localhost:11434/v1"}}}},
- {"openai": {"type": "api", "key": "sk-auth-json"}},
- )["provider"]["openai"] == {"options": {"apiKey": "sk-auth-json"}}
-
-
-def test_explicit_non_object_user_provider_removes_provider_payload():
- assert "provider" not in _reconcile(
- {"provider": None},
- {"provider": {"openai": {"options": {"apiKey": "sk-live"}}}},
- {"openai": {"type": "api", "key": "sk-auth"}},
- )
diff --git a/tests/test_opencode_directory_bootstrap.py b/tests/test_opencode_directory_bootstrap.py
index 27214dab6..1ee79f8e6 100644
--- a/tests/test_opencode_directory_bootstrap.py
+++ b/tests/test_opencode_directory_bootstrap.py
@@ -20,9 +20,10 @@ from config.v2_config import V2Config
from core.agent_auth_service import AgentAuthService
from modules.agents.base import AgentRequest
from modules.agents.opencode.agent import OpenCodeAgent
-from modules.agents.opencode.server import OpenCodeServerManager
+from modules.agents.opencode.server import OpenCodeServerClient
from modules.agents.opencode.session import OpenCodeSessionManager
from modules.im import MessageContext
+from tests.opencode_generation_fakes import lease_returning, serve_opencode_agent
REQUEST_TIMEOUT_SECONDS = 1
@@ -111,9 +112,8 @@ async def _first_turn(tmp_path, port: int, monkeypatch):
monkeypatch.setattr("modules.agents.opencode.agent.emit_backend_failure", emit_backend_failure)
- server = OpenCodeServerManager(port=port, request_timeout_seconds=REQUEST_TIMEOUT_SECONDS)
# The process is up and healthy; its lifecycle is not what this covers.
- server.ensure_running = AsyncMock(return_value=server.base_url)
+ server = OpenCodeServerClient(f"http://127.0.0.1:{port}", request_timeout_seconds=REQUEST_TIMEOUT_SECONDS)
agent = object.__new__(OpenCodeAgent)
sessions = SimpleNamespace(
@@ -134,7 +134,7 @@ async def _first_turn(tmp_path, port: int, monkeypatch):
get_opencode_overrides=stop_before_prompt,
)
agent.config = agent.controller.config
- agent._get_server = AsyncMock(return_value=server)
+ serve_opencode_agent(agent, server)
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
agent.record_model_hub_native_failure = AsyncMock()
@@ -193,17 +193,24 @@ def test_provider_probe_lists_models_after_directory_bootstrap_longer_than_reque
async def scenario():
async with _cold_opencode(bootstrap_seconds=REQUEST_TIMEOUT_SECONDS + 1) as opencode:
- server = OpenCodeServerManager(port=opencode.port, request_timeout_seconds=REQUEST_TIMEOUT_SECONDS)
+ server = OpenCodeServerClient(
+ f"http://127.0.0.1:{opencode.port}",
+ request_timeout_seconds=REQUEST_TIMEOUT_SECONDS,
+ )
service = AgentAuthService(SimpleNamespace(config=SimpleNamespace(language="en")))
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=server))
+ lease = lease_returning(server)
+ monkeypatch.setattr(service, "_lease_opencode_server", lease)
try:
- result = await service.test_opencode_provider("openai")
+ result = await service.test_opencode_provider("openai", timeout=30.0)
finally:
await server.close_http_session()
- return result, opencode.prompts
+ return result, opencode.prompts, lease.ttls
- result, prompts = asyncio.run(scenario())
+ result, prompts, lease_ttls = asyncio.run(scenario())
assert result["ok"] is True, result
+ # A renewal retiring the generation cannot stop it while the probe still
+ # waits for the bootstrap or for its reply.
+ assert lease_ttls and lease_ttls[0] > server_module.DIRECTORY_BOOTSTRAP_TIMEOUT + 30.0
assert result["model"] == "gpt-cold"
assert [prompt["model"] for prompt in prompts] == [{"providerID": "openai", "modelID": "gpt-cold"}]
diff --git a/tests/test_opencode_generations.py b/tests/test_opencode_generations.py
new file mode 100644
index 000000000..9c0839565
--- /dev/null
+++ b/tests/test_opencode_generations.py
@@ -0,0 +1,2236 @@
+"""OpenCode runtime generations: launch specs, processes, adoption, and routing.
+
+The OpenCode instance is one runtime unit. Each ``opencode serve`` process is a
+generation started from one launch spec; a turn stays on the generation it
+started on while new turns move to the generation that serves the current
+spec. These tests pin the adapter half of that contract.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import os
+import stat
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from modules.agents.opencode import client_manager
+from modules.agents.opencode import server as opencode_server
+from modules.agents.opencode.agent import OpenCodeAgent, _OpenCodeSteerState
+from modules.agents.opencode.client_manager import OpenCodeRuntime, compute_launch_spec, read_launch_inputs
+from modules.agents.opencode.server import OpenCodeGeneration, OpenCodeLaunchSpec
+from tests.fake_pid_helpers import fake_pid
+
+_WRITE_RECORD = OpenCodeGeneration.write_record
+
+
+def opencode_home(tmp_path, monkeypatch):
+ """A home whose OpenCode config, credentials, and binary are the test's own."""
+
+ home = Path.home()
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(home / ".config"))
+ binary = tmp_path / "bin" / "opencode"
+ binary.parent.mkdir(parents=True)
+ binary.write_text("#!/bin/sh\necho 1.18.33\n", encoding="utf-8")
+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)
+ probes: list[str] = []
+
+ def probe(path: str) -> str:
+ probes.append(path)
+ return Path(path).read_text(encoding="utf-8").split()[-1]
+
+ monkeypatch.setattr(client_manager, "_probe_binary_version", probe)
+ monkeypatch.setattr(client_manager, "_binary_versions", {})
+ config = home / ".config" / "opencode" / "opencode.json"
+ config.parent.mkdir(parents=True, exist_ok=True)
+ auth = home / ".local" / "share" / "opencode" / "auth.json"
+ auth.parent.mkdir(parents=True, exist_ok=True)
+ return SimpleNamespace(binary=binary, config=config, auth=auth, probes=probes)
+
+
+def _spec(home, *, overlay=None, renew_epoch: int = 0) -> OpenCodeLaunchSpec:
+ return compute_launch_spec(read_launch_inputs(str(home.binary), renew_epoch), overlay)
+
+
+def _current_spec(runtime: OpenCodeRuntime, overlay=None) -> OpenCodeLaunchSpec:
+ return asyncio.run(runtime.launch_spec(overlay, runtime.launch_inputs()))
+
+
+def _overlay(content: str = '{"provider":{"avibe-openai":{}}}'):
+ inline = opencode_server._managed_runtime_config_content(content)
+ return SimpleNamespace(
+ content=content.encode(),
+ content_hash=hashlib.sha256(inline.encode()).hexdigest(),
+ provider_ids=("avibe-openai",),
+ )
+
+
+# ---------------------------------------------------------------- launch spec
+
+
+def test_an_in_place_binary_upgrade_changes_the_launch_spec(opencode_home):
+ before = _spec(opencode_home)
+ again = _spec(opencode_home)
+ # The same path now holds a newer build, as an in-place upgrade leaves it.
+ opencode_home.binary.write_text("#!/bin/sh\n# upgraded build\necho 1.18.34\n", encoding="utf-8")
+ after = _spec(opencode_home)
+
+ assert again.digest == before.digest
+ assert after.digest != before.digest
+ assert (before.binary_version, after.binary_version) == ("1.18.33", "1.18.34")
+ # The version is probed once per file identity, never on every turn.
+ assert len(opencode_home.probes) == 2
+
+
+def test_credential_digest_ignores_token_refresh_but_sees_new_credentials(opencode_home):
+ def write_auth(entries):
+ opencode_home.auth.write_text(json.dumps(entries), encoding="utf-8")
+
+ write_auth({"anthropic": {"type": "oauth", "access": "a1", "refresh": "r1", "expires": 1}})
+ signed_in = _spec(opencode_home)
+ # OpenCode refreshes the token in place; each process reads it per request.
+ write_auth({"anthropic": {"type": "oauth", "access": "a2", "refresh": "r2", "expires": 2}})
+ refreshed = _spec(opencode_home)
+ write_auth({
+ "anthropic": {"type": "oauth", "access": "a2", "refresh": "r2", "expires": 2},
+ "openai": {"type": "api", "key": "sk-one"},
+ })
+ keyed = _spec(opencode_home)
+ write_auth({
+ "anthropic": {"type": "oauth", "access": "a2", "refresh": "r2", "expires": 2},
+ "openai": {"type": "api", "key": "sk-two"},
+ })
+ rekeyed = _spec(opencode_home)
+
+ assert refreshed.digest == signed_in.digest
+ assert len({signed_in.digest, keyed.digest, rekeyed.digest}) == 3
+
+
+def test_config_digest_ignores_schema_insertion_but_sees_edits(opencode_home):
+ opencode_home.config.write_text('{\n // comment\n "provider": {"x": {}}\n}', encoding="utf-8")
+ original = _spec(opencode_home)
+ opencode_home.config.write_text(
+ json.dumps({"$schema": "https://opencode.ai/config.json", "provider": {"x": {}}}),
+ encoding="utf-8",
+ )
+ with_schema = _spec(opencode_home)
+ opencode_home.config.write_text(json.dumps({"provider": {"x": {"options": {"baseURL": "https://b"}}}}))
+ edited = _spec(opencode_home)
+
+ assert with_schema.digest == original.digest
+ assert edited.digest != original.digest
+
+
+def test_overlay_and_renewal_are_launch_spec_inputs(opencode_home):
+ direct = _spec(opencode_home)
+ hub = _spec(opencode_home, overlay=_overlay())
+ renewed = _spec(opencode_home, renew_epoch=1)
+
+ assert len({direct.digest, hub.digest, renewed.digest}) == 3
+ assert hub.overlay_provider_ids == ("avibe-openai",)
+ assert json.loads(hub.overlay_inline_content)["provider"] == {"avibe-openai": {}}
+ tampered = _overlay()
+ tampered.content_hash = "0" * 64
+ with pytest.raises(RuntimeError, match="hash changed"):
+ _spec(opencode_home, overlay=tampered)
+
+
+# -------------------------------------------------------------- start & stop
+
+
+class _Process:
+ def __init__(self, pid: int, returncode: int | None = None) -> None:
+ self.pid = pid
+ self.returncode = returncode
+
+ async def wait(self) -> int:
+ return self.returncode or 0
+
+
+def isolated_launch(tmp_path, monkeypatch):
+ """Spawn fake ``opencode serve`` processes instead of real ones."""
+
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: tmp_path / "generations")
+ monkeypatch.setattr(opencode_server, "_OWNED_HERE", {})
+ monkeypatch.setattr(opencode_server, "_ADOPTION_PROBE_INTERVAL_SECONDS", 0)
+ monkeypatch.setattr(opencode_server, "ensure_plugin_installed", lambda: None)
+ monkeypatch.setattr(opencode_server.runtime, "process_create_time", lambda pid: 100.0 + pid)
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", AsyncMock(return_value=True))
+ monkeypatch.setattr(opencode_server, "_pid_listens_on", lambda pid, port: True)
+ launches: list[dict] = []
+ processes: list[_Process] = []
+
+ async def spawn(*cmd, env, **_kwargs):
+ process = processes.pop(0)
+ launches.append({"cmd": list(cmd), "env": env, "pid": process.pid})
+ return process
+
+ monkeypatch.setattr(opencode_server.asyncio, "create_subprocess_exec", spawn)
+ return SimpleNamespace(launches=launches, processes=processes, records=tmp_path / "generations")
+
+
+def test_a_start_chooses_its_port_and_retries_one_another_process_took(isolated_launch):
+ # The first server finds its port taken and exits; the second one serves.
+ isolated_launch.processes.extend([_Process(fake_pid(1), returncode=1), _Process(fake_pid(2))])
+ spec = OpenCodeLaunchSpec(digest="spec", binary="/bin/opencode")
+
+ generation = asyncio.run(opencode_server.start_generation(spec))
+
+ ports = [
+ int(next(arg for arg in launch["cmd"] if arg.startswith("--port=")).split("=", 1)[1])
+ for launch in isolated_launch.launches
+ ]
+ # ``--port=0`` would bind OpenCode's default 4096.
+ assert all(port not in (0, 4096) for port in ports)
+ assert len(set(ports)) == 2
+ assert generation.port == ports[1] and generation.pid == fake_pid(2)
+ assert [path.name for path in isolated_launch.records.glob("*.json")] == [f"{generation.generation_id}.json"]
+ record = json.loads(generation.record_path.read_text())
+ assert record["spec_digest"] == "spec" and record["process_created_at"] == 100.0 + fake_pid(2)
+ assert isolated_launch.launches[1]["env"]["AVIBE_OPENCODE_MODEL_HUB"] == "0"
+
+
+def test_a_hub_start_launches_on_its_own_overlay_copy(isolated_launch):
+ isolated_launch.processes.append(_Process(fake_pid(3)))
+ overlay = _overlay()
+ inline = opencode_server._managed_runtime_config_content(overlay.content)
+ spec = OpenCodeLaunchSpec(
+ digest="hub",
+ binary="/bin/opencode",
+ overlay_hash=overlay.content_hash,
+ overlay_provider_ids=overlay.provider_ids,
+ overlay_file_content=overlay.content,
+ overlay_inline_content=inline,
+ )
+
+ generation = asyncio.run(opencode_server.start_generation(spec))
+
+ env = isolated_launch.launches[0]["env"]
+ assert env["AVIBE_OPENCODE_MODEL_HUB"] == "1"
+ assert env["OPENCODE_CONFIG"] == str(generation.overlay_path)
+ assert generation.overlay_path.read_bytes() == overlay.content
+ assert json.loads(env["OPENCODE_CONFIG_CONTENT"]) == json.loads(inline)
+ assert generation.model_hub_provider_ids == ("avibe-openai",)
+
+
+def test_a_start_that_never_serves_is_reaped_and_leaves_no_record(isolated_launch, monkeypatch):
+ isolated_launch.processes.append(_Process(fake_pid(4)))
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", AsyncMock(return_value=False))
+ monkeypatch.setattr(opencode_server, "SERVER_START_TIMEOUT", 0.3)
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+ overlay = _overlay()
+ spec = OpenCodeLaunchSpec(
+ digest="hub",
+ binary="/bin/opencode",
+ overlay_hash=overlay.content_hash,
+ overlay_file_content=overlay.content,
+ overlay_inline_content=opencode_server._managed_runtime_config_content(overlay.content),
+ )
+
+ with pytest.raises(opencode_server.OpenCodeGenerationStartError, match="failed to start"):
+ asyncio.run(opencode_server.start_generation(spec))
+
+ assert stopped == [fake_pid(4)]
+ assert list(isolated_launch.records.iterdir()) == []
+
+
+# ------------------------------------------------------------------ adoption
+
+
+def _record(records: Path, generation_id: str, pid: int, port: int, **fields) -> Path:
+ records.mkdir(parents=True, exist_ok=True)
+ path = records / f"{generation_id}.json"
+ path.write_text(
+ json.dumps({
+ "generation_id": generation_id,
+ "pid": pid,
+ "port": port,
+ "process_created_at": 100.0 + pid,
+ "spec_digest": f"spec-{generation_id}",
+ **fields,
+ }),
+ encoding="utf-8",
+ )
+ return path
+
+
+ "legacy_shape",
+ [
+ # Every field a released single-server record could carry.
+ {
+ "process_created_at": 100.0 + fake_pid(14),
+ "caller_context_path": "/old-home/runtime/opencode_caller_context.json",
+ "model_hub_overlay_hash": "abc",
+ "model_hub_overlay_provider_ids": ["avibe-openai"],
+ "owner_pid": 1,
+ "runtime_policy_revision": "disable-native-skill-v2",
+ },
+ # The oldest shape: no birth identity and no caller context.
+ {},
+ ],
+)
+def test_adoption_keeps_every_proven_serving_process_and_drops_the_rest(isolated_launch, tmp_path, monkeypatch, legacy_shape):
+ records = isolated_launch.records
+ serving = _record(records, "ocg_serving", fake_pid(10), 50010, active_run_sessions=["ses_a"])
+ dead = _record(records, "ocg_dead", fake_pid(11), 50011)
+ reused = _record(records, "ocg_reused", fake_pid(12), 50012)
+ unhealthy = _record(records, "ocg_unhealthy", fake_pid(13), 50013)
+ legacy = tmp_path / "logs" / "opencode_server.json"
+ legacy.parent.mkdir()
+ legacy.write_text(
+ json.dumps({"pid": fake_pid(14), "port": 4096, "active_run_sessions": ["ses_legacy"], **legacy_shape}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: legacy)
+ alive = {fake_pid(10), fake_pid(12), fake_pid(13), fake_pid(14)}
+ ports = {fake_pid(10): 50010, fake_pid(12): 50012, fake_pid(13): 50013, fake_pid(14): 4096}
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in alive)
+ monkeypatch.setattr(
+ opencode_server.runtime,
+ "process_create_time",
+ # The reused pid now belongs to a process born later.
+ lambda pid: 999.0 if pid == fake_pid(12) else 100.0 + pid,
+ )
+ monkeypatch.setattr(
+ opencode_server.runtime,
+ "get_process_command",
+ lambda pid: f"/bin/opencode serve --hostname=127.0.0.1 --port={ports[pid]}",
+ )
+
+ async def healthy(generation):
+ return generation.port != 50013
+
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", healthy)
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+
+ adopted = asyncio.run(opencode_server.adopt_recorded_generations())
+
+ by_pid = {generation.pid: generation for generation in adopted}
+ assert set(by_pid) == {fake_pid(10), fake_pid(14)}
+ assert by_pid[fake_pid(10)].spec_digest == "spec-ocg_serving"
+ assert by_pid[fake_pid(10)].active_run_sessions == {"ses_a"}
+ converted = by_pid[fake_pid(14)]
+ # A pre-generations server never serves a new turn; it finishes its run.
+ assert converted.spec_digest == opencode_server.LEGACY_SPEC_DIGEST
+ assert converted.active_run_sessions == {"ses_legacy"}
+ assert converted.record_path.exists() and not legacy.exists()
+ # Only the proven process that stopped serving is signalled.
+ assert stopped == [fake_pid(13)]
+ assert serving.exists()
+ assert not dead.exists() and not reused.exists() and not unhealthy.exists()
+
+
+# ------------------------------------------------------- generation lifecycle
+
+
+def _generation(generation_id: str, index: int, digest: str) -> OpenCodeGeneration:
+ return OpenCodeGeneration(
+ generation_id=generation_id,
+ pid=fake_pid(index),
+ port=50100 + index,
+ spec_digest=digest,
+ process_created_at=1.0,
+ )
+
+
+def fake_processes(tmp_path, monkeypatch):
+ """Generations that start and stop without any process."""
+
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: tmp_path / "generations")
+ monkeypatch.setattr(opencode_server, "_OWNED_HERE", {})
+ started: list[OpenCodeGeneration] = []
+ stopped: list[OpenCodeGeneration] = []
+ alive: set[str] = set()
+
+ async def start(spec, **_kwargs):
+ generation = _generation(f"ocg_{len(started)}", len(started), spec.digest)
+ started.append(generation)
+ alive.add(generation.generation_id)
+ return generation
+
+ async def stop(generation):
+ stopped.append(generation)
+ alive.discard(generation.generation_id)
+
+ monkeypatch.setattr(client_manager, "start_generation", start)
+ monkeypatch.setattr(client_manager, "stop_generation", stop)
+ monkeypatch.setattr(client_manager, "adopt_recorded_generations", AsyncMock(return_value=[]))
+ monkeypatch.setattr(
+ OpenCodeGeneration,
+ "process_alive",
+ lambda self: self.generation_id in alive,
+ )
+ monkeypatch.setattr(OpenCodeGeneration, "write_record", lambda self: None)
+ return SimpleNamespace(started=started, stopped=stopped, alive=alive)
+
+
+def _runtime() -> OpenCodeRuntime:
+ return OpenCodeRuntime(SimpleNamespace(binary="opencode", request_timeout_seconds=60))
+
+
+def test_runtime_gen_020_a_busy_generation_finishes_its_run_while_new_turns_move_on(fake_processes):
+ """RUNTIME-GEN-020: a launch change starts a new generation without
+ interrupting the run on the old one, and the old one stops only after its
+ native run is cleared, not merely when its binding is released."""
+
+ async def scenario():
+ runtime = _runtime()
+ first = await runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ old = first.generation.runtime
+ await old.mark_run_active("ses_running")
+ second = await runtime.acquire(OpenCodeLaunchSpec(digest="v2", binary="opencode"))
+ new = second.generation.runtime
+ both_serving = (runtime.current() is new, old in runtime.generations())
+ # The turn's binding is gone, but its native run is still recorded.
+ await first.release()
+ await runtime.reap()
+ kept_for_its_run = old in runtime.generations() and old not in fake_processes.stopped
+ await old.mark_run_inactive("ses_running")
+ await runtime.reap()
+ return both_serving, kept_for_its_run, new
+
+ both_serving, kept_for_its_run, new = asyncio.run(scenario())
+
+ assert both_serving == (True, True)
+ assert kept_for_its_run
+ assert [generation.generation_id for generation in fake_processes.stopped] == ["ocg_0"]
+ assert new.generation_id in fake_processes.alive
+
+
+def test_an_old_generation_stays_until_the_activity_it_started_ends(fake_processes):
+ """A launch change retires the old generation, and its turn ends, but a
+ background Activity it started still runs there. No binding names that
+ Activity, so the graceful stop asks for it by activation and waits."""
+
+ from core.runtime_activation import RuntimeActivationRegistry
+ from core.session_activities import SessionActivityRegistry
+ from modules.agents.service import AgentService
+
+ activation = RuntimeActivationRegistry()
+ service = AgentService(
+ SimpleNamespace(),
+ activities=SessionActivityRegistry(activation_registry=activation),
+ activation_registry=activation,
+ )
+ agent = _stopping_agent(service, activation)
+
+ async def scenario():
+ runtime = agent._runtime
+ first = await runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ old = first.generation.runtime
+ service.activities.start(
+ backend="opencode",
+ runtime_key="base-1:/work",
+ session_id=None,
+ activity_id="task-1",
+ kind="task",
+ activation_identity=old.identity,
+ )
+ await runtime.acquire(OpenCodeLaunchSpec(digest="v2", binary="opencode"))
+ await first.release()
+ await runtime.reap()
+ kept_for_its_activity = old in runtime.generations() and old not in fake_processes.stopped
+ service.activities.complete(
+ backend="opencode",
+ runtime_key="base-1:/work",
+ activity_id="task-1",
+ status="completed",
+ activation_identity=old.identity,
+ )
+ await runtime.reap()
+ return old, kept_for_its_activity
+
+ old, kept_for_its_activity = asyncio.run(scenario())
+
+ assert kept_for_its_activity
+ assert fake_processes.stopped == [old]
+
+
+def test_a_current_generation_whose_process_died_is_replaced(fake_processes):
+ async def scenario():
+ runtime = _runtime()
+ first = await runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ await first.release()
+ fake_processes.alive.discard(first.generation.runtime.generation_id)
+ second = await runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ return first.generation.runtime, second.generation.runtime, runtime
+
+ dead, replacement, runtime = asyncio.run(scenario())
+
+ assert replacement is not dead
+ assert runtime.generations() == (replacement,)
+
+
+def test_a_lease_pins_its_generation_until_released_or_expired(fake_processes):
+ async def scenario():
+ runtime = _runtime()
+ lease_id, leased = await runtime.lease(OpenCodeLaunchSpec(digest="v1", binary="opencode"), ttl_seconds=60)
+ recorded = dict(leased.leases)
+ await runtime.acquire(OpenCodeLaunchSpec(digest="v2", binary="opencode"))
+ await runtime.reap()
+ pinned = leased in runtime.generations()
+ released = await runtime.release_lease(lease_id)
+ await runtime.reap()
+ expiring_id, expiring = await runtime.lease(OpenCodeLaunchSpec(digest="v3", binary="opencode"), ttl_seconds=1)
+ await runtime.acquire(OpenCodeLaunchSpec(digest="v4", binary="opencode"))
+ await asyncio.sleep(1.2)
+ await runtime.reap()
+ return lease_id, recorded, pinned, released, leased, expiring, runtime
+
+ lease_id, recorded, pinned, released, leased, expiring, runtime = asyncio.run(scenario())
+
+ assert lease_id in recorded
+ assert pinned and released
+ assert leased in fake_processes.stopped and not leased.leases
+ assert expiring in fake_processes.stopped
+
+
+# ------------------------------------------------------------------- routing
+
+
+class _Generation:
+ def __init__(self, generation_id: str) -> None:
+ self.generation_id = generation_id
+ self.identity = None
+ self.active_run_sessions: set[str] = set()
+ self.aborted: list[tuple[str, str]] = []
+ self.prompts: list[dict] = []
+
+ async def abort_session(self, session_id, directory):
+ self.aborted.append((session_id, directory))
+ return True
+
+ async def list_messages(self, session_id, directory):
+ return []
+
+ async def get_session_status(self, session_id, directory):
+ return {"type": "busy"}
+
+ async def prompt_async(self, **kwargs):
+ self.prompts.append(kwargs)
+
+
+def _routing_agent(retiring: _Generation, current: _Generation):
+ agent = object.__new__(OpenCodeAgent)
+ agent._runtime = SimpleNamespace(current=lambda: current, generations=lambda: (retiring, current))
+ agent._session_generations = {"base-old": retiring}
+ agent._steering_states = {}
+ return agent
+
+
+def test_runtime_gen_021_a_live_turn_is_aborted_on_its_own_generation():
+ """RUNTIME-GEN-021: run state lives in each process, so a session's abort
+ and steer go to the generation running its turn, not the current one."""
+
+ retiring, current = _Generation("ocg_old"), _Generation("ocg_new")
+ agent = _routing_agent(retiring, current)
+
+ async def scenario():
+ task = asyncio.get_running_loop().create_task(asyncio.sleep(10))
+ try:
+ await agent._abort_active_request("base-old", task, ("native-old", "/work", "route"))
+ # A session with no generation has no native run to abort.
+ await agent._abort_active_request("base-unbound", task, ("native-x", "/work", "route"))
+ finally:
+ task.cancel()
+
+ asyncio.run(scenario())
+
+ assert retiring.aborted == [("native-old", "/work")]
+ assert current.aborted == []
+
+
+def test_runtime_gen_021_a_steer_reaches_the_generation_running_the_turn():
+ from core.services.agent_steering import SteerOutcome, SteerRequest
+
+ retiring, current = _Generation("ocg_old"), _Generation("ocg_new")
+ agent = _routing_agent(retiring, current)
+ agent.name = "opencode"
+ agent.render_input = lambda text, _metadata=None: text
+
+ async def scenario():
+ task = asyncio.get_running_loop().create_task(asyncio.sleep(10))
+ agent._active_requests = {"base-old": task}
+ agent._session_manager = SimpleNamespace(
+ get_request_session=lambda base: ("native-old", "/work", "route") if base == "base-old" else None
+ )
+ state = _OpenCodeSteerState(
+ task=task,
+ base_session_id="base-old",
+ target_session_id="ses",
+ logical_turn_id="turn",
+ native_session_id="native-old",
+ directory="/work",
+ agent="build",
+ model=None,
+ reasoning_effort=None,
+ system=None,
+ baseline_message_ids=set(),
+ generation=retiring,
+ )
+ agent._steering_states["base-old"] = state
+ try:
+ return await agent.steer_active_turn(
+ SteerRequest(
+ target_session_id="ses",
+ expected_logical_turn_id="turn",
+ expected_native_turn_id=state.native_turn_id,
+ text="also this",
+ ),
+ SimpleNamespace(agent_request=None, runtime_key="base-old"),
+ )
+ finally:
+ task.cancel()
+
+ result = asyncio.run(scenario())
+
+ assert result.outcome is SteerOutcome.ACCEPTED
+ assert [prompt["text"] for prompt in retiring.prompts] == ["also this"]
+ assert current.prompts == []
+
+
+def test_runtime_gen_022_a_restored_poll_resumes_on_the_generation_that_runs_it():
+ """RUNTIME-GEN-022: after a controller restart, a durable poll binds to the
+ adopted generation it names. A poll from before generations binds to the
+ adopted server that recorded its run; one whose process is gone reads its
+ result through the current generation. A poll bound elsewhere than it
+ names is rewritten to name that generation, so another restart finds it."""
+
+ named, legacy, current = _Generation("ocg_named"), _Generation("ocg_legacy"), _Generation("ocg_current")
+ legacy.active_run_sessions = {"native-legacy"}
+ bound: list[object] = []
+
+ async def bind(generation):
+ bound.append(generation)
+ return SimpleNamespace(generation=SimpleNamespace(runtime=generation))
+
+ async def acquire(_spec):
+ bound.append("acquired")
+ return SimpleNamespace(generation=SimpleNamespace(runtime=current))
+
+ renamed: dict[str, str] = {}
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = SimpleNamespace(model_hub_runtime=None)
+ agent.sessions = SimpleNamespace(
+ update_active_poll_state=lambda session_id, *, processing_indicator: renamed.update(
+ {session_id: processing_indicator["opencode_generation_id"]}
+ )
+ )
+ agent._runtime = SimpleNamespace(
+ adopted=True,
+ generation=lambda generation_id: {"ocg_named": named, "ocg_legacy": legacy}.get(generation_id),
+ generations=lambda: (named, legacy, current),
+ bind=bind,
+ acquire=acquire,
+ launch_inputs=lambda: SimpleNamespace(settings=None),
+ launch_spec=AsyncMock(return_value=SimpleNamespace(digest="current")),
+ )
+
+ def poll(native_session_id, generation_id=None):
+ indicator = {"opencode_generation_id": generation_id} if generation_id else {}
+ return SimpleNamespace(opencode_session_id=native_session_id, processing_indicator=indicator)
+
+ async def scenario():
+ return [
+ (await agent._bind_restored_poll(poll("native-named", "ocg_named"))).generation.runtime,
+ (await agent._bind_restored_poll(poll("native-legacy"))).generation.runtime,
+ (await agent._bind_restored_poll(poll("native-gone", "ocg_stopped"))).generation.runtime,
+ ]
+
+ assert asyncio.run(scenario()) == [named, legacy, current]
+ assert bound == [named, legacy, "acquired"]
+ assert renamed == {"native-legacy": "ocg_legacy", "native-gone": "ocg_current"}
+
+
[email protected](("config_save", "renews"), [(True, False), (False, True)])
+def test_a_plain_config_save_renews_no_generation(config_save, renews):
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=None))
+ agent._runtime = SimpleNamespace(config=None, renew=lambda: renewals.append(True), reap=AsyncMock())
+ agent._lifecycle_tasks = set()
+ renewals: list[bool] = []
+ config = SimpleNamespace(binary="opencode")
+
+ async def scenario():
+ await agent.renew_runtime(config, config_save=config_save)
+ await asyncio.gather(*agent._lifecycle_tasks)
+
+ asyncio.run(scenario())
+
+ assert agent.opencode_config is config and agent._runtime.config is config
+ assert bool(renewals) is renews
+
+
+# ---------------------------------------------------------- UI-process leases
+
+
+def test_runtime_gen_023_the_ui_process_leases_the_controllers_generation_over_control_ipc():
+ """RUNTIME-GEN-023: the UI process never launches OpenCode. It leases the
+ controller's current generation and talks to it over HTTP."""
+
+ import httpx
+
+ from core.internal_server import create_app
+
+ generation = _generation("ocg_ui", 30, "spec")
+ generation.model_hub_provider_ids = ("avibe-openai",)
+ released: list[str] = []
+
+ async def lease_generation(purpose, *, ttl_seconds):
+ assert (purpose, ttl_seconds) == ("web OAuth", 960.0)
+ return {"lease_id": "ocl_1", "server": generation}
+
+ async def release_generation_lease(lease_id):
+ released.append(lease_id)
+ return True
+
+ agent = SimpleNamespace(lease_generation=lease_generation, release_generation_lease=release_generation_lease)
+ app = create_app(
+ SimpleNamespace(
+ agent_service=SimpleNamespace(agents={"opencode": agent})
+ )
+ )
+
+ async def scenario():
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://localhost") as client:
+ created = await client.post(
+ "/internal/opencode/generation-leases",
+ json={"purpose": "web OAuth", "ttl_seconds": 960},
+ )
+ release = await client.post("/internal/opencode/generation-leases/ocl_1/release")
+ invalid = await client.post("/internal/opencode/generation-leases", json={"purpose": "x"})
+ return created, release, invalid
+
+ created, release, invalid = asyncio.run(scenario())
+
+ assert created.status_code == 200
+ assert created.json() == {
+ "ok": True,
+ "lease_id": "ocl_1",
+ "generation_id": "ocg_ui",
+ "base_url": generation.base_url,
+ "request_timeout_seconds": 60,
+ "model_hub_provider_ids": ["avibe-openai"],
+ }
+ assert release.json() == {"ok": True, "released": True} and released == ["ocl_1"]
+ assert invalid.status_code == 400
+
+
+def test_a_ui_request_running_past_its_lease_window_keeps_its_generation_until_release(fake_processes, monkeypatch):
+ """A UI request on a leased generation runs past the window its lease was
+ asked for, while a config change retires that generation. The controller
+ keeps the process until the UI releases the lease, and stops it then. The
+ leased client starts no request that could outlive the lease."""
+
+ import httpx
+
+ from core.internal_server import create_app
+ from modules.agents.opencode.client_manager import lease_opencode_server
+ from vibe import internal_client
+
+ runtime = _runtime()
+
+ async def lease_generation(_purpose, *, ttl_seconds):
+ lease_id, generation = await runtime.lease(OpenCodeLaunchSpec(digest="v1", binary="opencode"), ttl_seconds)
+ return {"lease_id": lease_id, "server": generation}
+
+ app = create_app(
+ SimpleNamespace(
+ agent_service=SimpleNamespace(
+ agents={
+ "opencode": SimpleNamespace(
+ lease_generation=lease_generation, release_generation_lease=runtime.release_lease
+ )
+ }
+ )
+ )
+ )
+
+ async def post(path, payload=None):
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://localhost") as client:
+ response = await client.post(path, json=payload)
+ return {"status_code": response.status_code, "body": response.json()}
+
+ async def create_lease(purpose, *, ttl_seconds):
+ return await post("/internal/opencode/generation-leases", {"purpose": purpose, "ttl_seconds": ttl_seconds})
+
+ async def release_lease(lease_id):
+ return await post(f"/internal/opencode/generation-leases/{lease_id}/release")
+
+ reached: list[str] = []
+
+ async def no_server_in_this_test(self):
+ reached.append(self.base_url)
+ raise ConnectionError("no OpenCode server in this test")
+
+ monkeypatch.setattr(internal_client, "create_opencode_generation_lease", create_lease)
+ monkeypatch.setattr(internal_client, "release_opencode_generation_lease", release_lease)
+ monkeypatch.setattr(opencode_server.OpenCodeServerClient, "_get_http_session", no_server_in_this_test)
+
+ async def scenario():
+ # The shortest window a lease is granted for.
+ lease = await lease_opencode_server("provider catalog", ttl_seconds=1.0)
+ leased = runtime.current()
+ # A config change: the next turn starts a new generation, and the
+ # leased one retires.
+ await runtime.acquire(OpenCodeLaunchSpec(digest="v2", binary="opencode"))
+ # The UI request runs past the window the lease was asked for.
+ await asyncio.sleep(1.2)
+ await runtime.reap()
+ during_the_request = list(fake_processes.stopped)
+ try:
+ await lease.server.get_providers()
+ except (TimeoutError, ConnectionError) as exc:
+ late_request = type(exc).__name__
+ await lease.release()
+ await runtime.reap()
+ return leased, during_the_request, late_request
+
+ leased, during_the_request, late_request = asyncio.run(scenario())
+
+ assert during_the_request == []
+ assert fake_processes.stopped == [leased]
+ # Past its window, a request whose timeout could outlive the lease never starts.
+ assert (late_request, reached) == ("TimeoutError", [])
+
+
+def test_a_ui_lease_release_reaches_its_runtime_after_the_backend_is_disabled(fake_processes):
+ import httpx
+
+ from core.internal_server import create_app
+
+ runtime = _runtime()
+
+ async def lease_generation(purpose, *, ttl_seconds):
+ lease_id, generation = await runtime.lease(OpenCodeLaunchSpec(digest="v1", binary="opencode"), ttl_seconds)
+ return {"lease_id": lease_id, "server": generation}
+
+ async def release_generation_lease(lease_id):
+ return await runtime.release_lease(lease_id)
+
+ agents = {
+ "opencode": SimpleNamespace(
+ lease_generation=lease_generation,
+ release_generation_lease=release_generation_lease,
+ )
+ }
+ app = create_app(SimpleNamespace(agent_service=SimpleNamespace(agents=agents)))
+
+ async def scenario():
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://localhost") as client:
+ created = await client.post(
+ "/internal/opencode/generation-leases",
+ json={"purpose": "web OAuth", "ttl_seconds": 960},
+ )
+ # Disabling OpenCode unregisters its agent, then stops its
+ # runtime at once; the UI's flow ends with the process.
+ agents.pop("opencode")
+ await runtime.shutdown()
+ stopped_at_disable = list(fake_processes.stopped)
+ release = await client.post(f"/internal/opencode/generation-leases/{created.json()['lease_id']}/release")
+ return stopped_at_disable, release, runtime
+
+ stopped_at_disable, release, runtime = asyncio.run(scenario())
+
+ assert len(stopped_at_disable) == 1
+ # The release still reaches the runtime that held the lease, and frees it.
+ assert release.json() == {"ok": True, "released": True}
+ assert runtime._leases == {}
+
+
+def test_a_ui_lease_client_carries_the_generations_private_providers(monkeypatch):
+ from vibe import internal_client
+
+ released: list[str] = []
+ monkeypatch.setattr(
+ internal_client,
+ "create_opencode_generation_lease",
+ AsyncMock(
+ return_value={
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "lease_id": "ocl_2",
+ "base_url": "http://127.0.0.1:50999",
+ "request_timeout_seconds": 30,
+ "model_hub_provider_ids": ["avibe-openai"],
+ },
+ }
+ ),
+ )
+ monkeypatch.setattr(
+ internal_client,
+ "release_opencode_generation_lease",
+ AsyncMock(side_effect=lambda lease_id: released.append(lease_id)),
+ )
+
+ async def scenario():
+ # A controller-shaped object without an Agent service is a UI process.
+ async with client_manager.leased_opencode_server("catalog", controller=SimpleNamespace()) as server:
+ return server.base_url, server.model_hub_provider_ids, server.request_timeout_seconds
+
+ assert asyncio.run(scenario()) == ("http://127.0.0.1:50999", ("avibe-openai",), 30)
+ assert released == ["ocl_2"]
+
+
+def test_a_disabled_backend_leases_nothing_in_the_controller():
+ async def scenario():
+ await client_manager.lease_opencode_server(
+ "catalog",
+ ttl_seconds=60,
+ controller=SimpleNamespace(agent_service=SimpleNamespace(agents={})),
+ )
+
+ with pytest.raises(client_manager.OpenCodeRuntimeUnavailableError) as raised:
+ asyncio.run(scenario())
+ assert raised.value.reason == "opencode_disabled"
+
+
+def test_records_live_under_the_runtime_dir():
+ assert str(opencode_server.generation_records_dir()).startswith(str(os.environ["AVIBE_HOME"]))
+
+
+# --------------------------------------------------------- review regressions
+
+_LAUNCHER = """
+import socket, subprocess, sys
+child = subprocess.Popen([sys.executable, "-c", (
+ "import socket, sys, time\\n"
+ "s = socket.socket(); s.bind(('127.0.0.1', 0)); s.listen()\\n"
+ "print(s.getsockname()[1], flush=True); time.sleep(30)\\n"
+)], stdout=subprocess.PIPE, text=True)
+print(child.stdout.readline().strip(), flush=True)
+child.wait()
+"""
+
+
[email protected](os.name == "nt", reason="POSIX process trees")
+def test_a_launcher_whose_child_serves_counts_as_listening():
+ # npm shims and .cmd wrappers start the real server as their child.
+ import subprocess
+ import sys
+
+ launcher = subprocess.Popen(
+ [sys.executable, "-c", _LAUNCHER],
+ stdout=subprocess.PIPE,
+ text=True,
+ start_new_session=True,
+ )
+ try:
+ port = int(launcher.stdout.readline())
+ assert opencode_server._pid_listens_on(launcher.pid, port)
+ assert not opencode_server._pid_listens_on(launcher.pid, port + 1)
+ finally:
+ opencode_server.terminate_pid_tree_sync(launcher.pid, timeout=2.0)
+ launcher.wait(timeout=5)
+ launcher.stdout.close()
+
+
+def test_adoption_leaves_another_runtime_of_this_controller_its_generations(isolated_launch, monkeypatch):
+ records = isolated_launch.records
+ _record(records, "ocg_crashed", fake_pid(21), 50021)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(21))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=50021")
+ isolated_launch.processes.append(_Process(fake_pid(20)))
+
+ spec = OpenCodeLaunchSpec(digest="spec-ocg_crashed", binary="/bin/opencode")
+
+ async def scenario():
+ started = await opencode_server.start_generation(OpenCodeLaunchSpec(digest="v1", binary="/bin/opencode"))
+ old = _runtime()
+ await old.ensure_adopted(spec)
+ # The OpenCode backend is disabled and enabled again while the old
+ # runtime's turn still runs: that runtime keeps and later stops both.
+ new = _runtime()
+ await new.ensure_adopted(spec)
+ return started, old.generations(), new.generations()
+
+ started, old, new = asyncio.run(scenario())
+
+ assert started.record_path.exists()
+ assert [generation.generation_id for generation in old] == ["ocg_crashed"]
+ assert new == ()
+
+
+def test_strict_retirement_retries_a_stop_that_declined_while_a_request_ran(fake_processes):
+ async def scenario():
+ runtime = _runtime()
+ first = await runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ old = first.generation.runtime
+ old._active_requests = 1
+ second = await runtime.acquire(OpenCodeLaunchSpec(digest="v2", binary="opencode"))
+ await second.release()
+ await first.release()
+ await runtime._generations.settled()
+ declined = old in runtime.generations()
+ old._active_requests = 0
+ await runtime.retire_all_strict()
+ return declined, runtime
+
+ declined, runtime = asyncio.run(scenario())
+
+ assert declined
+ assert runtime.generations() == ()
+
+
+def test_a_renewal_outlives_a_controller_restart(opencode_home):
+ before = OpenCodeRuntime(SimpleNamespace(binary=str(opencode_home.binary), request_timeout_seconds=60))
+ original = _current_spec(before)
+ before.renew()
+ # A restarted controller must not promote a generation the renewal retired.
+ after = OpenCodeRuntime(SimpleNamespace(binary=str(opencode_home.binary), request_timeout_seconds=60))
+
+ assert _current_spec(after).digest == _current_spec(before).digest
+ assert _current_spec(after).digest != original.digest
+
+
+def test_shutdown_keeps_the_record_of_a_server_that_survived(isolated_launch, monkeypatch):
+ record = _record(isolated_launch.records, "ocg_stuck", fake_pid(22), 50022)
+ gone = _record(isolated_launch.records, "ocg_gone", fake_pid(23), 50023)
+ # Both were this controller's, the one a runtime here started or adopted.
+ for generation_id, pid in (("ocg_stuck", fake_pid(22)), ("ocg_gone", fake_pid(23))):
+ opencode_server._OWNED_HERE[generation_id] = (pid, 100.0 + pid)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(22))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=50022")
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: False)
+
+ opencode_server.stop_owned_generations_sync()
+
+ assert record.exists()
+ assert not gone.exists()
+
+
+# ------------------------------------------------- review round 1 regressions
+
+
+def test_a_renewal_that_cannot_be_persisted_fails_without_taking_effect(opencode_home, monkeypatch):
+ runtime = OpenCodeRuntime(SimpleNamespace(binary=str(opencode_home.binary), request_timeout_seconds=60))
+ before = _current_spec(runtime).digest
+
+ def unwritable(*_args, **_kwargs):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(client_manager, "write_atomic", unwritable)
+
+ # A crash after an unpersisted renewal would promote the retired generation.
+ with pytest.raises(OSError):
+ runtime.renew()
+ assert _current_spec(runtime).digest == before
+
+
+def test_a_lease_released_before_adoption_never_pins_its_generation(fake_processes, monkeypatch):
+ generation = _generation("ocg_leased", 40, "spec")
+ generation.leases = {"ocl_ui": 4_000_000_000.0}
+ monkeypatch.setattr(client_manager, "adopt_recorded_generations", AsyncMock(return_value=[generation]))
+ fake_processes.alive.add(generation.generation_id)
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = SimpleNamespace(model_hub_runtime=None)
+ agent._runtime = _runtime()
+ agent._runtime.launch_spec = AsyncMock(return_value=OpenCodeLaunchSpec(digest="spec", binary="opencode"))
+
+ async def scenario():
+ # The UI finishes its OAuth flow right after a controller restart.
+ released = await agent.release_generation_lease("ocl_ui")
+ wrapper = agent._runtime._wrappers[generation.generation_id]
+ return released, wrapper.bindings
+
+ released, bindings = asyncio.run(scenario())
+
+ assert released is True
+ assert bindings == 0 and generation.leases == {}
+
+
+def test_runtime_gen_006_disabling_opencode_stops_every_generation_now_and_refuses_a_late_turn(fake_processes, monkeypatch):
+ """RUNTIME-GEN-006, at the OpenCode adapter: disabling OpenCode is the
+ user's own interruption. Once the core has interrupted the backend's work
+ and unregistered the agent, ``shutdown_runtime()`` stops every generation
+ at once, a busy one included. A turn that raced the disable fails with
+ the localized retired error instead of starting a process."""
+
+ from modules.agents.base import AgentRequest
+ from modules.im import MessageContext
+ from vibe.i18n import t as i18n_t
+
+ failures: list[str] = []
+
+ async def emit_backend_failure(_controller, _context, _backend, _error, *, display_text, request, **_kwargs):
+ failures.append(display_text)
+
+ monkeypatch.setattr("modules.agents.opencode.agent.emit_backend_failure", emit_backend_failure)
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = SimpleNamespace(config=SimpleNamespace(language="zh", platform="slack"))
+ agent._runtime = _runtime()
+ agent._session_generations = {}
+ agent._resource_failures = {}
+ agent._remove_ack_reaction = AsyncMock()
+ late = AgentRequest(
+ context=MessageContext(user_id="U1", channel_id="C1", platform="slack", platform_specific={}),
+ message="hello",
+ user_message="hello",
+ working_path="/work",
+ base_session_id="base-late",
+ composite_session_id="base-late:/work",
+ session_key="slack::channel::C1",
+ )
+
+ async def scenario():
+ retiring = await agent._runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ current = await agent._runtime.acquire(OpenCodeLaunchSpec(digest="v2", binary="opencode"))
+ await agent.shutdown_runtime()
+ stopped_at_once = set(fake_processes.stopped)
+ await agent._process_message(late)
+ return {retiring.generation.runtime, current.generation.runtime}, stopped_at_once
+
+ running, stopped_at_once = asyncio.run(scenario())
+
+ assert stopped_at_once == running
+ assert len(fake_processes.started) == 2
+ assert failures == [f"❌ {i18n_t('error.agentRuntimeRetired', 'zh', agent='OpenCode')}"]
+
+
+def test_a_start_whose_process_survives_its_stop_keeps_record_and_overlay(isolated_launch, monkeypatch):
+ isolated_launch.processes.append(_Process(fake_pid(41)))
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", AsyncMock(return_value=False))
+ monkeypatch.setattr(opencode_server, "SERVER_START_TIMEOUT", 0.3)
+ monkeypatch.setattr(opencode_server, "_terminate_started_process", AsyncMock(return_value=False))
+ overlay = _overlay()
+ spec = OpenCodeLaunchSpec(
+ digest="hub",
+ binary="/bin/opencode",
+ overlay_hash=overlay.content_hash,
+ overlay_file_content=overlay.content,
+ overlay_inline_content=opencode_server._managed_runtime_config_content(overlay.content),
+ )
+
+ with pytest.raises(opencode_server.OpenCodeGenerationStartError):
+ asyncio.run(opencode_server.start_generation(spec))
+
+ # The late process stays recorded, so adoption or ``vibe stop`` finds it.
+ names = sorted(path.name for path in isolated_launch.records.iterdir())
+ assert len(names) == 2 and names[0].endswith(".json") and names[1].endswith(".overlay.json")
+
+
+def test_adoption_keeps_the_record_of_an_unhealthy_server_that_survives_its_stop(isolated_launch, monkeypatch):
+ record = _record(isolated_launch.records, "ocg_stubborn", fake_pid(42), 50042)
+ overlay = isolated_launch.records / "ocg_stubborn.overlay.json"
+ overlay.write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(42))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=50042")
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", AsyncMock(return_value=False))
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: False)
+
+ assert asyncio.run(opencode_server.adopt_recorded_generations()) == []
+ assert record.exists() and overlay.exists()
+
+
+def test_runtime_gen_024_a_mode_switch_during_a_hub_run_moves_new_turns_to_direct(fake_processes, opencode_home):
+ """RUNTIME-GEN-024: switching OpenCode from Hub to Direct while a Hub run is
+ live starts a Direct generation for the next turn and lets the Hub
+ generation finish its run before it stops."""
+
+ async def scenario():
+ runtime = OpenCodeRuntime(SimpleNamespace(binary=str(opencode_home.binary), request_timeout_seconds=60))
+ hub_turn = await runtime.acquire(await runtime.launch_spec(_overlay(), runtime.launch_inputs()))
+ hub = hub_turn.generation.runtime
+ await hub.mark_run_active("ses_hub")
+ # The mode switch commits Direct; the next turn's snapshot has no overlay.
+ direct_turn = await runtime.acquire(await runtime.launch_spec(None, runtime.launch_inputs()))
+ direct = direct_turn.generation.runtime
+ both = (hub in runtime.generations(), runtime.current() is direct)
+ await hub_turn.release()
+ await runtime.reap()
+ hub_kept_for_its_run = hub in runtime.generations()
+ await hub.mark_run_inactive("ses_hub")
+ await runtime.reap()
+ return both, hub_kept_for_its_run, hub, direct
+
+ both, hub_kept_for_its_run, hub, direct = asyncio.run(scenario())
+
+ assert both == (True, True)
+ assert hub_kept_for_its_run
+ assert fake_processes.stopped == [hub]
+ assert direct.spec_digest != hub.spec_digest
+
+
+# ------------------------------------------------- review round 2 regressions
+
+
+def test_a_confirmed_retirement_of_a_leased_generation_reports_it_draining(fake_processes):
+ from modules.agents.opencode.server import StopOutcome
+
+ agent = object.__new__(OpenCodeAgent)
+ agent._runtime = _runtime()
+
+ async def scenario():
+ lease_id, leased = await agent._runtime.lease(OpenCodeLaunchSpec(digest="v1", binary="opencode"), 60)
+ outcome = await agent.retire_current_generation()
+ still_running = leased not in fake_processes.stopped
+ await agent._runtime.release_lease(lease_id)
+ await agent._runtime._generations.settled()
+ return outcome, still_running, leased
+
+ outcome, still_running, leased = asyncio.run(scenario())
+
+ # Retiring a leased generation is no stop until the lease drains.
+ assert outcome is StopOutcome.DRAINING and still_running
+ assert fake_processes.stopped == [leased]
+
+
+def test_a_confirmed_retirement_of_an_idle_generation_reports_it_stopped(fake_processes):
+ from modules.agents.opencode.server import StopOutcome
+
+ agent = object.__new__(OpenCodeAgent)
+ agent._runtime = _runtime()
+
+ async def scenario():
+ turn = await agent._runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ running = turn.generation.runtime
+ await turn.release()
+ return running, await agent.retire_current_generation(), await agent.retire_current_generation()
+
+ running, stopped, nothing = asyncio.run(scenario())
+
+ assert stopped is StopOutcome.STOPPED
+ assert fake_processes.stopped == [running]
+ assert nothing is None
+
+
+def test_an_orphaned_run_marker_is_reconciled_again_by_a_later_sweep(fake_processes, monkeypatch):
+ generation = _generation("ocg_orphan", 50, "spec-old")
+ generation.active_run_sessions = {"ses_without_poll"}
+ fake_processes.alive.add(generation.generation_id)
+ monkeypatch.setattr(client_manager, "adopt_recorded_generations", AsyncMock(return_value=[generation]))
+ reads = {"count": 0}
+
+ def durable_polls():
+ reads["count"] += 1
+ if reads["count"] == 1:
+ raise OSError("session store briefly unreadable")
+ return {}
+
+ runtime = _runtime()
+ runtime.durable_poll_generations = durable_polls
+
+ async def scenario():
+ # Adoption cannot tell the marker is orphaned, so it keeps it for now.
+ await runtime.ensure_adopted(OpenCodeLaunchSpec(digest="spec-new", binary="opencode"))
+ pinned = generation in runtime.generations()
+ await runtime.reap()
+ return pinned
+
+ assert asyncio.run(scenario())
+ assert fake_processes.stopped == [generation]
+ assert generation.active_run_sessions == set()
+
+
+# ------------------------------------------------- review round 3 regressions
+
+
+def test_a_lease_release_whose_write_fails_reaches_the_record_at_the_next_sweep(fake_processes, monkeypatch):
+ monkeypatch.setattr(OpenCodeGeneration, "write_record", _WRITE_RECORD)
+ real_write = opencode_server.write_atomic
+ unwritable = {"now": False}
+
+ def write_atomic(path, content):
+ if unwritable["now"]:
+ raise OSError("state dir briefly unwritable")
+ real_write(path, content)
+
+ monkeypatch.setattr(opencode_server, "write_atomic", write_atomic)
+
+ async def scenario():
+ runtime = _runtime()
+ lease_id, leased = await runtime.lease(OpenCodeLaunchSpec(digest="v1", binary="opencode"), ttl_seconds=600)
+ unwritable["now"] = True
+ released = await runtime.release_lease(lease_id)
+ bindings = runtime._wrappers[leased.generation_id].bindings
+ stale = json.loads(leased.record_path.read_text())["leases"]
+ unwritable["now"] = False
+ await runtime.reap()
+ return lease_id, released, bindings, stale, json.loads(leased.record_path.read_text())["leases"]
+
+ lease_id, released, bindings, stale, swept = asyncio.run(scenario())
+
+ # The release holds the process no longer, though its record still shows it.
+ assert released is True and bindings == 0
+ assert lease_id in stale
+ # A controller adopting the record after the sweep honors no stale lease.
+ assert swept == {}
+
+
[email protected]("legacy", [False, True], ids=["generation-record", "legacy-record"])
+def test_adoption_tracks_a_serving_process_whose_record_cannot_be_rewritten(
+ isolated_launch, tmp_path, monkeypatch, legacy
+):
+ legacy_path = tmp_path / "opencode_server.json"
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: legacy_path)
+ if legacy:
+ legacy_path.write_text(json.dumps({"pid": fake_pid(43), "port": 50043}), encoding="utf-8")
+ recorded = legacy_path
+ else:
+ recorded = _record(isolated_launch.records, "ocg_crashed", fake_pid(43), 50043)
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(43))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=50043")
+ real_write = opencode_server.write_atomic
+
+ def unwritable(*_args, **_kwargs):
+ raise OSError("state dir briefly unwritable")
+
+ monkeypatch.setattr(opencode_server, "write_atomic", unwritable)
+
+ adopted = asyncio.run(opencode_server.adopt_recorded_generations())
+
+ # Tracked, so it counts against the cap and stops once it drains.
+ assert [generation.pid for generation in adopted] == [fake_pid(43)]
+ # The record that finds it after another crash stays until one replaces it.
+ assert recorded.exists()
+ monkeypatch.setattr(opencode_server, "write_atomic", real_write)
+ adopted[0].flush_record()
+ assert adopted[0].record_path.exists()
+ assert not legacy_path.exists()
+
+
+# ------------------------------------------------- review round 5 regressions
+
+
+def test_an_unreadable_record_is_kept_for_its_possibly_running_process(isolated_launch, monkeypatch):
+ records = isolated_launch.records
+ records.mkdir(parents=True)
+ corrupt = records / "ocg_corrupt.json"
+ corrupt.write_text('{"generation_id": "ocg_corrupt", "pid": ', encoding="utf-8")
+ overlay = records / "ocg_corrupt.overlay.json"
+ overlay.write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: records / "absent.json")
+
+ assert asyncio.run(opencode_server.adopt_recorded_generations()) == []
+ opencode_server.forget_dead_records()
+
+ # Generation ports are dynamic: without its record nothing finds the server.
+ assert corrupt.exists() and overlay.exists()
+
+
+def test_adoption_applies_resource_governance_to_every_adopted_generation(fake_processes, monkeypatch):
+ generation = _generation("ocg_adopted", 44, "spec")
+ fake_processes.alive.add(generation.generation_id)
+ monkeypatch.setattr(client_manager, "adopt_recorded_generations", AsyncMock(return_value=[generation]))
+ governed: list[tuple[int, str]] = []
+ runtime = OpenCodeRuntime(
+ SimpleNamespace(binary="opencode", request_timeout_seconds=60),
+ resource_governor=SimpleNamespace(apply_to_pid=lambda pid, label: governed.append((pid, label))),
+ )
+
+ asyncio.run(runtime.ensure_adopted(OpenCodeLaunchSpec(digest="spec", binary="opencode")))
+
+ assert governed == [(generation.pid, "opencode serve")]
+
+
+def test_an_adoption_cut_short_leaves_every_record_to_its_retry(isolated_launch, monkeypatch):
+ records = isolated_launch.records
+ for generation_id, index in (("ocg_a", 45), ("ocg_b", 46)):
+ _record(records, generation_id, fake_pid(index), 50000 + index, active_run_sessions=[f"ses_{generation_id}"])
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: records / "absent.json")
+ ports = {fake_pid(45): 50045, fake_pid(46): 50046}
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in ports)
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: f"/bin/opencode serve --port={ports[pid]}")
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: True)
+ probing_b = asyncio.Event()
+ probes = {"ocg_b": 0}
+
+ async def is_healthy(generation):
+ if generation.generation_id == "ocg_b":
+ probes["ocg_b"] += 1
+ if probes["ocg_b"] == 1:
+ probing_b.set()
+ await asyncio.Event().wait()
+ return True
+
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", is_healthy)
+ runtime = _runtime()
+ # Each record's run has a durable poll, so neither generation stops here.
+ runtime.durable_poll_generations = lambda: {"ses_ocg_a": "ocg_a", "ses_ocg_b": "ocg_b"}
+ spec = OpenCodeLaunchSpec(digest="spec-ocg_b", binary="/bin/opencode")
+
+ async def scenario():
+ # A turn's /stop cancels it while adoption probes the second record.
+ first = asyncio.get_running_loop().create_task(runtime.ensure_adopted(spec))
+ await probing_b.wait()
+ first.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first
+ await runtime.ensure_adopted(spec)
+ return {generation.generation_id for generation in runtime.generations()}
+
+ assert asyncio.run(scenario()) == {"ocg_a", "ocg_b"}
+
+
+# ---------------------------------------------- lifecycle audit regressions
+
+
+def _leftover_record(records: Path, monkeypatch, generation_id: str, index: int) -> tuple[Path, int]:
+ """A server a crashed controller recorded, proven live by its record."""
+
+ pid = fake_pid(index)
+ record = _record(records, generation_id, pid, 50000 + index)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda candidate: candidate == pid)
+ monkeypatch.setattr(opencode_server.runtime, "process_create_time", lambda candidate: 100.0 + candidate)
+ monkeypatch.setattr(
+ opencode_server.runtime,
+ "get_process_command",
+ lambda candidate: f"/bin/opencode serve --port={50000 + index}",
+ )
+ return record, pid
+
+
+def test_disabling_the_backend_stops_a_previous_controllers_generations(fake_processes, tmp_path, monkeypatch):
+ record, pid = _leftover_record(tmp_path / "generations", monkeypatch, "ocg_leftover", 47)
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda candidate, timeout=5.0: stopped.append(candidate) or True)
+
+ # The backend is disabled before anything used OpenCode since a crash.
+ asyncio.run(_runtime().shutdown())
+
+ assert stopped == [pid] and not record.exists()
+
+
+def test_a_disable_shutdown_that_leaves_a_process_raises_and_its_retry_finishes(fake_processes, tmp_path, monkeypatch):
+ """A disable's teardown owner retries a shutdown only if it raises: one
+ whose forced stop or leftover stop left a process must not report success.
+ The retry stops what is left."""
+
+ record, leftover_pid = _leftover_record(tmp_path / "generations", monkeypatch, "ocg_leftover", 48)
+ survives = {"attached": True, "leftover": True}
+ stop = client_manager.stop_generation
+
+ async def stop_generation(generation):
+ if survives["attached"]:
+ raise RuntimeError("process did not exit")
+ await stop(generation)
+
+ monkeypatch.setattr(client_manager, "stop_generation", stop_generation)
+ monkeypatch.setattr(
+ opencode_server,
+ "terminate_pid_tree_sync",
+ lambda candidate, timeout=5.0: not survives["leftover"],
+ )
+ runtime = _runtime()
+
+ async def scenario():
+ turn = await runtime.acquire(OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+ attached = turn.generation.runtime
+ with pytest.raises(RuntimeError, match="incomplete"):
+ await runtime.shutdown()
+ incomplete = (attached in runtime.generations(), record.exists())
+ survives.update(attached=False, leftover=False)
+ await runtime.shutdown()
+ return attached, incomplete
+
+ attached, incomplete = asyncio.run(scenario())
+
+ assert incomplete == (True, True)
+ assert fake_processes.stopped == [attached]
+ assert runtime.generations() == () and not record.exists()
+
+
+def _stopping_agent(agent_service, runtime_activation=None) -> OpenCodeAgent:
+ """An agent whose forced generation stops settle their work through ``agent_service``."""
+
+ from modules.agents.opencode.session import OpenCodeSessionManager
+
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = SimpleNamespace(agent_service=agent_service, runtime_activation=runtime_activation)
+ agent._session_manager = OpenCodeSessionManager(SimpleNamespace(sessions=None), "opencode")
+ agent._session_generations = {}
+ agent._active_requests = {}
+ agent._steering_states = {}
+ agent._settling_request_tasks = set()
+ agent._runtime = _runtime()
+ agent._runtime.on_generation_ready = agent._attach_generation_activation
+ agent._runtime.on_generation_stopping = agent._on_generation_stopping
+ agent._runtime.holds_activities = agent._generation_holds_activities
+ return agent
+
+
+async def _bind_turn(agent: OpenCodeAgent, digest: str, base: str, workdir: str) -> OpenCodeGeneration:
+ binding = await agent._runtime.acquire(OpenCodeLaunchSpec(digest=digest, binary="opencode"))
+ agent._session_generations[base] = binding.generation.runtime
+ agent._session_manager.set_request_session(base, f"ses-{base}", workdir, "slack::channel::C1")
+ return binding.generation.runtime
+
+
+def test_a_cap_forced_stop_settles_the_turns_and_activities_of_its_process(fake_processes):
+ """A fourth launch spec force-stops the oldest busy generation as a
+ runtime update: the turn of the session bound to it, and every Activity
+ its process started, including one whose session it no longer serves."""
+
+ from core.runtime_activation import RuntimeActivationRegistry
+ from core.session_activities import SessionActivityRegistry
+ from modules.agents.service import AgentService
+
+ releases: list[tuple[set[str], str]] = []
+
+ async def release_for_backend_refresh(*, backend, base_session_ids, settled_by):
+ releases.append((set(base_session_ids), settled_by))
+
+ activation = RuntimeActivationRegistry()
+ service = AgentService(
+ SimpleNamespace(session_turns=SimpleNamespace(release_for_backend_refresh=release_for_backend_refresh)),
+ activities=SessionActivityRegistry(activation_registry=activation),
+ activation_registry=activation,
+ )
+ settled = []
+ service.on_activity_terminal = settled.append
+ agent = _stopping_agent(service, activation)
+
+ async def scenario():
+ generations = [
+ await _bind_turn(agent, digest, f"base-{index}", f"/work/{index}")
+ for index, digest in enumerate(("v1", "v2", "v3"))
+ ]
+ oldest = generations[0]
+ for runtime_key, activity_id in (("base-0:/work/0", "task-0"), ("base-moved:/work/0", "task-moved")):
+ service.activities.start(
+ backend="opencode",
+ runtime_key=runtime_key,
+ session_id=None,
+ activity_id=activity_id,
+ kind="task",
+ activation_identity=oldest.identity,
+ )
+ await agent._runtime.acquire(OpenCodeLaunchSpec(digest="v4", binary="opencode"))
+ await agent._runtime._generations.settled()
+ return oldest
+
+ oldest = asyncio.run(scenario())
+
+ assert fake_processes.stopped == [oldest]
+ assert releases == [({"base-0"}, "backend_refresh")]
+ assert sorted((task.id, task.status, task.metadata.get("interrupt_reason")) for task in settled) == [
+ ("task-0", "killed", "backend_refresh"),
+ ("task-moved", "killed", "backend_refresh"),
+ ]
+
+
+def test_runtime_gen_006_a_disable_retried_after_a_re_enable_settles_only_the_disabled_agents_work(
+ fake_processes, monkeypatch
+):
+ """RUNTIME-GEN-006, at the OpenCode adapter: the core's interrupt of a
+ disable failed, and OpenCode was enabled again before the retry, so the
+ retry skips that interrupt. The disabled agent's forced stop settles the
+ work bound to its process as disabled, once across every retry, and never
+ the re-enabled agent's work: not its Activities under the same runtime
+ key, nor the next turn of a session the stop already settled."""
+
+ from core.runtime_activation import RuntimeActivationRegistry
+ from core.session_activities import SessionActivityRegistry
+ from modules.agents.service import AgentService
+
+ releases: list[tuple[set[str], str]] = []
+ terminals = []
+
+ async def release_for_backend_refresh(*, backend, base_session_ids, settled_by):
+ releases.append((set(base_session_ids), settled_by))
+ if len(releases) == 1:
+ # The failure that also made the core's interrupt fail.
+ raise RuntimeError("database is locked")
+
+ activation = RuntimeActivationRegistry()
+ service = AgentService(
+ SimpleNamespace(
+ session_turns=SimpleNamespace(release_for_backend_refresh=release_for_backend_refresh),
+ scheduled_task_service=SimpleNamespace(settle_activity_runs=terminals.append),
+ ),
+ activities=SessionActivityRegistry(activation_registry=activation),
+ activation_registry=activation,
+ )
+ # The process survives the first stop that reaches it.
+ exits = iter([False, True])
+ stop = client_manager.stop_generation
+
+ async def stop_generation(generation):
+ if not next(exits):
+ raise RuntimeError("process did not exit")
+ await stop(generation)
+
+ monkeypatch.setattr(client_manager, "stop_generation", stop_generation)
+
+ def start_task(generation: OpenCodeGeneration, activity_id: str) -> None:
+ service.activities.start(
+ backend="opencode",
+ runtime_key="base-old:/work/old",
+ session_id=None,
+ activity_id=activity_id,
+ kind="task",
+ activation_identity=generation.identity,
+ )
+
+ disabled = _stopping_agent(service, activation)
+
+ async def shutdown() -> None:
+ await disabled.shutdown_runtime(settle_reason="backend_disabled")
+
+ async def scenario():
+ old = await _bind_turn(disabled, "v1", "base-old", "/work/old")
+ start_task(old, "old-task")
+ with pytest.raises(RuntimeError, match="incomplete"):
+ await shutdown()
+ enabled = _stopping_agent(service, activation)
+ new = await _bind_turn(enabled, "v1", "base-new", "/work/new")
+ start_task(new, "new-task")
+ with pytest.raises(RuntimeError, match="incomplete"):
+ await shutdown()
+ # The settled session's next turn runs on the re-enabled agent.
+ await _bind_turn(enabled, "v1", "base-old", "/work/old")
+ start_task(new, "next-task")
+ await shutdown()
+ return old, new, enabled
+
+ old, new, enabled = asyncio.run(scenario())
+
+ assert releases == [({"base-old"}, "backend_disabled")] * 2
+ assert [(task.id, task.status, task.metadata.get("interrupt_reason")) for task in terminals] == [
+ ("old-task", "killed", "backend_disabled")
+ ]
+ assert sorted(task.id for task in service.activities.active_for_runtime("opencode", "base-old:/work/old")) == [
+ "new-task",
+ "next-task",
+ ]
+ assert fake_processes.stopped == [old]
+ assert enabled._runtime.current() is new and new.generation_id in fake_processes.alive
+
+def test_the_cap_stops_the_oldest_adopted_generation_whatever_its_record_order(fake_processes, monkeypatch):
+ """After a restart, records come in filename order, which says nothing
+ about age. Adoption keeps process age, so when a new turn's generation
+ takes the unit past the cap, the oldest adopted process gives way."""
+
+ def recorded(generation_id: str, index: int, started_at: float) -> OpenCodeGeneration:
+ generation = OpenCodeGeneration(
+ generation_id=generation_id,
+ pid=fake_pid(80 + index),
+ port=50180 + index,
+ spec_digest=f"old-{index}",
+ process_created_at=started_at,
+ started_at=started_at,
+ # Each still runs a restored turn, so none stops on its own.
+ active_run_sessions=(f"ses-{index}",),
+ )
+ fake_processes.alive.add(generation_id)
+ return generation
+
+ young, middle, old = recorded("ocg_0a", 0, 300.0), recorded("ocg_1b", 1, 200.0), recorded("ocg_2c", 2, 100.0)
+ monkeypatch.setattr(client_manager, "adopt_recorded_generations", AsyncMock(return_value=[young, middle, old]))
+ runtime = _runtime()
+
+ async def scenario():
+ await runtime.acquire(OpenCodeLaunchSpec(digest="new", binary="opencode"))
+ await runtime._generations.settled()
+
+ asyncio.run(scenario())
+
+ assert [generation.generation_id for generation in fake_processes.stopped] == [old.generation_id]
+ assert set(runtime.generations()) == {young, middle, *fake_processes.started}
+
+
+def test_adoption_takes_a_converted_legacy_server_once(isolated_launch, tmp_path, monkeypatch):
+ converted = _record(isolated_launch.records, "ocg_converted", fake_pid(48), 4096)
+ # The crash came after the converted record was written and before the
+ # legacy file it replaces was removed.
+ legacy = tmp_path / "opencode_server.json"
+ legacy.write_text(json.dumps({"pid": fake_pid(48), "port": 4096}), encoding="utf-8")
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: legacy)
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(48))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=4096")
+
+ adopted = asyncio.run(opencode_server.adopt_recorded_generations())
+
+ assert [generation.generation_id for generation in adopted] == ["ocg_converted"]
+ assert converted.exists() and not legacy.exists()
+
+
+def test_a_native_migration_never_overlaps_an_opencode_start_outside_a_turn(fake_processes, monkeypatch):
+ ready = asyncio.Event()
+ starting = asyncio.Event()
+ finish_start = asyncio.Event()
+ start = client_manager.start_generation
+
+ async def slow_start(spec, **kwargs):
+ starting.set()
+ await finish_start.wait()
+ return await start(spec, **kwargs)
+
+ monkeypatch.setattr(client_manager, "start_generation", slow_start)
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = SimpleNamespace(
+ model_hub_runtime=None,
+ agent_service=SimpleNamespace(
+ is_backend_ready=lambda _backend: ready.is_set(),
+ wait_backend_ready=lambda _backend: ready.wait(),
+ ),
+ )
+ agent._active_requests = {}
+ agent._runtime = _runtime()
+ agent._runtime.launch_spec = AsyncMock(return_value=OpenCodeLaunchSpec(digest="v1", binary="opencode"))
+
+ async def settings_request():
+ async with agent.current_server():
+ pass
+
+ async def scenario():
+ ready.set()
+ # A settings request is starting a process when the migration checks.
+ request = asyncio.get_running_loop().create_task(settings_request())
+ await starting.wait()
+ busy_while_starting = agent.runtime_has_active_turns()
+ # The migration drains the backend; a UI lease now waits for it.
+ ready.clear()
+ lease = asyncio.get_running_loop().create_task(agent.lease_generation("catalog", ttl_seconds=60))
+ finish_start.set()
+ await request
+ await asyncio.sleep(0)
+ held = not lease.done() and len(fake_processes.started) == 1
+ ready.set()
+ await lease
+ return busy_while_starting, held
+
+ busy_while_starting, held = asyncio.run(scenario())
+
+ assert busy_while_starting
+ assert held
+
+
+def test_a_reenabled_backend_leaves_a_legacy_server_another_runtime_here_owns(isolated_launch, tmp_path, monkeypatch):
+ legacy = tmp_path / "opencode_server.json"
+ legacy.write_text(
+ json.dumps({"pid": fake_pid(49), "port": 4096, "active_run_sessions": ["ses_restored"]}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: legacy)
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(49))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=4096")
+
+ def unwritable(*_args, **_kwargs):
+ raise OSError("state dir briefly unwritable")
+
+ # The conversion is deferred, so the legacy file is still the only record.
+ monkeypatch.setattr(opencode_server, "write_atomic", unwritable)
+ spec = OpenCodeLaunchSpec(digest="current", binary="/bin/opencode")
+
+ async def scenario():
+ old = _runtime()
+ old.durable_poll_generations = lambda: {"ses_restored": None}
+ await old.ensure_adopted(spec)
+ # The backend is disabled and enabled again while the restored run continues.
+ new = _runtime()
+ new.durable_poll_generations = lambda: {"ses_restored": None}
+ await new.ensure_adopted(spec)
+ return old.generations(), new.generations()
+
+ old, new = asyncio.run(scenario())
+
+ assert [generation.pid for generation in old] == [fake_pid(49)]
+ assert new == ()
+ assert legacy.exists()
+
+
+def test_adoption_gives_a_busy_server_more_than_one_health_probe(isolated_launch, monkeypatch):
+ _record(isolated_launch.records, "ocg_busy", fake_pid(50), 50050, active_run_sessions=["ses_busy"])
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(50))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=50050")
+ probes: list[str] = []
+
+ async def is_healthy(generation):
+ # A long tool output stalls the first answer after the crash.
+ probes.append(generation.generation_id)
+ return len(probes) > 1
+
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", is_healthy)
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+
+ adopted = asyncio.run(opencode_server.adopt_recorded_generations())
+
+ assert [generation.generation_id for generation in adopted] == ["ocg_busy"]
+ assert stopped == []
+
+
+def test_adoption_never_holds_a_recorded_lease_longer_than_any_lease_is_granted(fake_processes, monkeypatch):
+ generation = _generation("ocg_leased", 51, "spec")
+ # Written before the clock stepped back across a controller crash.
+ generation.leases = {"ocl_far": time.time() + 10 * 86400}
+ fake_processes.alive.add(generation.generation_id)
+ monkeypatch.setattr(client_manager, "adopt_recorded_generations", AsyncMock(return_value=[generation]))
+ runtime = _runtime()
+
+ async def scenario():
+ await runtime.ensure_adopted(OpenCodeLaunchSpec(digest="spec", binary="opencode"))
+ _binding, timer = runtime._leases["ocl_far"]
+ return timer.when() - asyncio.get_running_loop().time()
+
+ assert asyncio.run(scenario()) <= client_manager.MAX_LEASE_SECONDS
+
+
[email protected]("opencode_enabled", [False, True], ids=["disabled", "enabled"])
+def test_a_controller_starting_with_opencode_disabled_stops_a_crashed_controllers_servers(
+ isolated_launch, monkeypatch, opencode_enabled
+):
+ """A controller that crashed left a server recorded. Started with OpenCode
+ disabled, no agent will ever adopt it, so startup stops it. Started with
+ OpenCode enabled, the agent adopts it and its restorable runs."""
+
+ from core import controller as controller_module
+ from tests.test_service_readiness import _install_runtime_ready_dependencies
+
+ record = _record(isolated_launch.records, "ocg_left", fake_pid(52), 50052)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == fake_pid(52))
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=50052")
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+ controller = controller_module.Controller.__new__(controller_module.Controller)
+ _install_runtime_ready_dependencies(controller, [])
+ from modules.agents.service import AgentService
+
+ controller.agent_service = AgentService(controller=SimpleNamespace())
+ if opencode_enabled:
+ controller.agent_service.agents["opencode"] = object()
+ controller._publish_readiness_unless_im_runtime_failed = lambda: None
+ controller._start_model_hub_snapshot_reconcile_loop = lambda: None
+ controller.periodic_cleanup = AsyncMock()
+ controller.trace_retention_task = None
+ controller._agent_events_retention_loop = AsyncMock()
+
+ asyncio.run(controller_module.Controller._on_runtime_ready(controller))
+
+ if opencode_enabled:
+ assert stopped == [] and record.exists()
+ else:
+ assert stopped == [fake_pid(52)] and not record.exists()
+
+
+def test_a_renewal_during_overlay_preparation_leaves_the_launch_one_coherent_spec(fake_processes, opencode_home):
+ """A save that moves the CLI path, with its renewal, and a Model Hub
+ catalog save both land while a launch awaits its overlay. That launch
+ stays on the spec it snapshotted and starts no spare generation; the next
+ launch moves to the new one."""
+
+ upgraded = opencode_home.binary.with_name("opencode-next")
+ upgraded.write_bytes(opencode_home.binary.read_bytes() + b"# next\n")
+ upgraded.chmod(opencode_home.binary.stat().st_mode)
+ hub = {"overlay": _overlay('{"provider":{"avibe-openai":{"models":{"a":{}}}}}')}
+ preparing, release = asyncio.Event(), asyncio.Event()
+ hold = {"next": False}
+
+ async def prepare_opencode_overlay(*, config):
+ # The snapshot is the overlay this launch derives.
+ if hold["next"]:
+ hold["next"] = False
+ preparing.set()
+ await release.wait()
+ return config
+
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = SimpleNamespace(
+ model_hub_runtime=SimpleNamespace(
+ snapshot=lambda: hub["overlay"],
+ prepare_opencode_overlay=prepare_opencode_overlay,
+ ),
+ config=SimpleNamespace(opencode=None),
+ )
+ agent._lifecycle_tasks = set()
+ agent._runtime = OpenCodeRuntime(SimpleNamespace(binary=str(opencode_home.binary), request_timeout_seconds=60))
+
+ async def launch():
+ async with agent.current_server() as server:
+ return server
+
+ async def scenario():
+ before = await launch()
+ hold["next"] = True
+ racing = asyncio.get_running_loop().create_task(launch())
+ await preparing.wait()
+ hub["overlay"] = _overlay('{"provider":{"avibe-openai":{"models":{"b":{}}}}}')
+ await agent.renew_runtime(SimpleNamespace(binary=str(upgraded), request_timeout_seconds=60))
+ release.set()
+ return before, await racing, await launch()
+
+ before, during, after = asyncio.run(scenario())
+
+ assert during is before
+ assert after is not before and after.spec_digest == _spec(
+ SimpleNamespace(binary=upgraded), overlay=_overlay('{"provider":{"avibe-openai":{"models":{"b":{}}}}}'), renew_epoch=1
+ ).digest
+ assert fake_processes.started == [before, after]
+
+
+def test_a_leased_generation_counts_as_active_runtime_work(fake_processes):
+ """A UI lease between its HTTP requests keeps its process in use, so a CLI
+ replacement waits for it."""
+
+ agent = object.__new__(OpenCodeAgent)
+ agent._active_requests = {}
+ agent._runtime = _runtime()
+
+ async def scenario():
+ lease_id, _generation = await agent._runtime.lease(
+ OpenCodeLaunchSpec(digest="v1", binary="opencode"), ttl_seconds=600
+ )
+ leased = agent.runtime_has_active_turns()
+ await agent._runtime.release_lease(lease_id)
+ return leased, agent.runtime_has_active_turns()
+
+ assert asyncio.run(scenario()) == (True, False)
+
+
+def test_shutdown_stops_only_the_generations_this_controller_owns(isolated_launch, monkeypatch):
+ """Another desktop Runtime shares this state directory: stopping this
+ controller leaves that Runtime's OpenCode generation running."""
+
+ own = _record(isolated_launch.records, "ocg_own", fake_pid(56), 50056)
+ foreign = _record(isolated_launch.records, "ocg_foreign", fake_pid(57), 50057)
+ opencode_server._OWNED_HERE["ocg_own"] = (fake_pid(56), 100.0 + fake_pid(56))
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")
+ ports = {fake_pid(56): 50056, fake_pid(57): 50057}
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in ports)
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: f"/bin/opencode serve --port={ports[pid]}")
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+
+ opencode_server.stop_owned_generations_sync()
+
+ assert stopped == [fake_pid(56)]
+ assert not own.exists() and foreign.exists()
+
+
+def test_adoption_leaves_every_record_of_another_desktop_runtime_alone(isolated_launch, monkeypatch):
+ """Two desktop Runtimes share this state directory. After a restart, this
+ controller adopts the server it started, known by the Runtime id its record
+ carries, and never adopts, stops, forgets, or cleans another Runtime's
+ records: a live one recorded with that Runtime's id, a live one recorded
+ before ids were recorded, whose process says it is that Runtime's, and a
+ dead one."""
+
+ records = isolated_launch.records
+ own_pid, foreign_pid, released_pid, dead_pid = fake_pid(62), fake_pid(63), fake_pid(64), fake_pid(65)
+ monkeypatch.setattr(opencode_server, "desktop_caller_provenance", lambda: frozenset({"rt-a"}))
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: records / "absent.json")
+ isolated_launch.processes.append(_Process(own_pid))
+ started = asyncio.run(opencode_server.start_generation(OpenCodeLaunchSpec(digest="v1", binary="/bin/opencode")))
+ foreign = _record(records, "ocg_foreign", foreign_pid, 50063, desktop_runtime_id="rt-b")
+ released = _record(records, "ocg_released", released_pid, 50064)
+ dead = _record(records, "ocg_dead", dead_pid, 50065, desktop_runtime_id="rt-b")
+ overlay = records / "ocg_foreign.overlay.json"
+ overlay.write_text("{}", encoding="utf-8")
+ before = {path.name: path.read_bytes() for path in records.iterdir()}
+ ports = {own_pid: started.port, foreign_pid: 50063, released_pid: 50064}
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in ports)
+ monkeypatch.setattr(opencode_server.runtime, "get_process_command", lambda pid: f"/bin/opencode serve --port={ports[pid]}")
+ # A process environment carries its Runtime id; the released record's
+ # process belongs to the other Runtime, and so would this controller's own
+ # process to a check that read only environments.
+ monkeypatch.setattr(
+ opencode_server.runtime,
+ "_desktop_runtime_mismatch",
+ lambda pid, runtime_ids: "runtime_id_mismatch" if pid in (released_pid, own_pid) else None,
+ )
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+ # The restarted controller owns nothing yet.
+ opencode_server._OWNED_HERE.clear()
+
+ adopted = asyncio.run(opencode_server.adopt_recorded_generations())
+
+ assert [generation.generation_id for generation in adopted] == [started.generation_id]
+ assert stopped == []
+ for path in (foreign, released, dead, overlay):
+ assert path.read_bytes() == before[path.name]
+
+
+ ("malformed", "ours"),
+ [
+ ({"desktop_runtime_id": ["rt-a"]}, False),
+ ({"desktop_runtime_id": {"id": "rt-a"}}, False),
+ ({"generation_id": ["ocg_bad"]}, True),
+ ({"process_created_at": 10**400}, True),
+ ],
+)
+def test_a_malformed_record_never_disables_opencode(isolated_launch, monkeypatch, malformed, ours):
+ """A readable record whose field has the wrong type degrades to a record
+ without that field. Adoption, a lease, a restore's ownership check, and
+ shutdown still work, and the record's process is still judged and handled:
+ a malformed Runtime id is judged by the live process, which belongs here to
+ another Runtime, and a record of this Runtime is adopted and stopped."""
+
+ records = isolated_launch.records
+ own_pid, bad_pid = fake_pid(90), fake_pid(91)
+ monkeypatch.setattr(opencode_server, "desktop_caller_provenance", lambda: frozenset({"rt-a"}))
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in (own_pid, bad_pid))
+ monkeypatch.setattr(opencode_server, "_get_pid_command", lambda pid: None)
+ monkeypatch.setattr(
+ opencode_server.runtime,
+ "_desktop_runtime_mismatch",
+ lambda pid, runtime_ids: "runtime_id_mismatch" if pid == bad_pid else None,
+ )
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+ record = _record(records, "ocg_bad", bad_pid, 50091, desktop_runtime_id="rt-a")
+ record.write_text(json.dumps({**json.loads(record.read_text()), **malformed}), encoding="utf-8")
+ isolated_launch.processes.append(_Process(own_pid))
+ runtime = OpenCodeRuntime(SimpleNamespace(binary="/bin/opencode", request_timeout_seconds=60))
+
+ async def lease():
+ _lease_id, generation = await runtime.lease(OpenCodeLaunchSpec(digest="v1", binary="/bin/opencode"), 60)
+ # An adopted generation of this Runtime retires and, idle, stops.
+ await runtime._generations.settled()
+ return generation
+
+ leased = asyncio.run(lease())
+ foreign = [info["generation_id"] for info in opencode_server.other_runtimes_live_records()]
+ opencode_server.stop_owned_generations_sync()
+
+ assert leased.pid == own_pid
+ assert foreign == ([] if ours else ["ocg_bad"])
+ assert sorted(stopped) == sorted([own_pid, bad_pid] if ours else [own_pid])
+
+
+def test_a_failed_start_whose_process_survives_is_reaped_until_it_is_gone(isolated_launch, monkeypatch):
+ """A start times out and its process survives the stop. The runtime that
+ spawned it keeps it owned and stops it at a later reap, record and Hub
+ overlay included, instead of leaving it running beside later generations."""
+
+ pid = fake_pid(66)
+ isolated_launch.processes.append(_Process(pid))
+ monkeypatch.setattr(opencode_server.OpenCodeGeneration, "is_healthy", AsyncMock(return_value=False))
+ monkeypatch.setattr(opencode_server, "SERVER_START_TIMEOUT", 0.3)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda candidate: candidate == pid)
+ killable = {"now": False}
+ stopped: list[int] = []
+
+ def terminate(candidate, timeout=5.0):
+ if killable["now"]:
+ stopped.append(candidate)
+ return killable["now"]
+
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", terminate)
+ monkeypatch.setattr(opencode_server, "_terminate_started_process", AsyncMock(return_value=False))
+ overlay = _overlay()
+ spec = OpenCodeLaunchSpec(
+ digest="hub",
+ binary="/bin/opencode",
+ overlay_hash=overlay.content_hash,
+ overlay_file_content=overlay.content,
+ overlay_inline_content=opencode_server._managed_runtime_config_content(overlay.content),
+ )
+ runtime = _runtime()
+
+ async def scenario():
+ with pytest.raises(opencode_server.OpenCodeGenerationStartError):
+ await runtime.acquire(spec)
+ await runtime.reap()
+ still_running = sorted(path.name for path in isolated_launch.records.iterdir())
+ killable["now"] = True
+ await runtime.reap()
+ return still_running
+
+ still_running = asyncio.run(scenario())
+
+ assert len(still_running) == 2
+ assert stopped == [pid]
+ assert list(isolated_launch.records.iterdir()) == []
+
+
+def test_service_shutdown_stops_a_started_process_whose_record_was_never_written(isolated_launch, monkeypatch):
+ """A start's record write fails and its process survives the stop. Avibe
+ stops before any reap retries it: the controller's shutdown still stops
+ that process, proven by its pid and create time, and drops its Hub
+ overlay. It never signals a pid whose create time changed or cannot be read."""
+
+ proven, reused, unreadable = fake_pid(67), fake_pid(68), fake_pid(69)
+ isolated_launch.processes.extend(_Process(pid) for pid in (proven, reused, unreadable))
+ create_times = {proven: 1.0, reused: 2.0, unreadable: 3.0}
+ monkeypatch.setattr(opencode_server.runtime, "process_create_time", create_times.get)
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in create_times)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")
+
+ def disk_full(_generation):
+ raise OSError("No space left on device")
+
+ monkeypatch.setattr(OpenCodeGeneration, "write_record", disk_full)
+ monkeypatch.setattr(opencode_server, "_terminate_started_process", AsyncMock(return_value=False))
+ stopped: list[int] = []
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5.0: stopped.append(pid) or True)
+ overlay = _overlay()
+ spec = OpenCodeLaunchSpec(
+ digest="hub",
+ binary="/bin/opencode",
+ overlay_hash=overlay.content_hash,
+ overlay_file_content=overlay.content,
+ overlay_inline_content=opencode_server._managed_runtime_config_content(overlay.content),
+ )
+ survivors: list[OpenCodeGeneration] = []
+
+ async def start_three():
+ for _ in range(3):
+ with pytest.raises(OSError, match="No space"):
+ await opencode_server.start_generation(spec, on_survivor=survivors.append)
+
+ asyncio.run(start_three())
+ create_times[reused] = 9.0
+ create_times[unreadable] = None
+
+ opencode_server.stop_owned_generations_sync()
+
+ assert stopped == [proven]
+ kept = next(generation for generation in survivors if generation.pid == unreadable)
+ assert list(opencode_server._OWNED_HERE) == [kept.generation_id]
+ assert [path.name for path in isolated_launch.records.iterdir()] == [kept.overlay_path.name]
+
+
+def test_a_turn_keeps_the_opencode_settings_it_was_admitted_with(monkeypatch):
+ """An ``agents.opencode`` save lands after a turn's admission snapshot and
+ before the turn resolves its model. The turn runs on the generation its
+ snapshot names, so it also takes its default provider, reasoning effort,
+ and poll settings from that snapshot; the next turn moves to the new ones."""
+
+ from modules.agents.base import AgentRequest
+ from modules.im import MessageContext
+ from tests.opencode_generation_fakes import serve_opencode_agent
+
+ admitted = SimpleNamespace(
+ default_provider="openai",
+ default_reasoning_effort="high",
+ error_retry_limit=0,
+ active_turn_timeout_seconds=0,
+ )
+ saved = SimpleNamespace(
+ default_provider="anthropic",
+ default_reasoning_effort="low",
+ error_retry_limit=5,
+ active_turn_timeout_seconds=600,
+ )
+ prompts: list[dict] = []
+ polled: list[object] = []
+ bootstrapping, proceed = asyncio.Event(), asyncio.Event()
+ agent = object.__new__(OpenCodeAgent)
+
+ class _Server:
+ async def ensure_directory_ready(self, directory):
+ bootstrapping.set()
+ await proceed.wait()
+
+ async def list_messages(self, session_id, directory):
+ return []
+
+ async def get_available_models(self, directory):
+ return {"providers": []}
+
+ async def prompt_async(self, **kwargs):
+ prompts.append(kwargs)
+
+ async def mark_run_active(self, session_id):
+ return None
+
+ async def mark_run_inactive(self, session_id):
+ return None
+
+ def get_default_agent_from_config(self):
+ return None
+
+ def get_agent_model_from_config(self, _agent):
+ return None
+
+ def get_agent_reasoning_effort_from_config(self, _agent):
+ return None
+
+ class _SessionManager:
+ async def ensure_working_dir(self, path):
+ return None
+
+ async def get_or_create_session_id(self, request, server):
+ return "oc-session"
+
+ def set_request_session(self, *args):
+ return None
+
+ def set_agent_session_id(self, *_args):
+ return None
+
+ def mark_initialized(self, session_id):
+ return False
+
+ class _Sessions:
+ def add_active_poll(self, **kwargs):
+ return None
+
+ def remove_active_poll(self, session_id):
+ return None
+
+ def update_active_poll_state(self, session_id, **kwargs):
+ return None
+
+ class _PollLoop:
+ async def run_prompt_poll(self, *args, settings=None, **kwargs):
+ polled.append(settings)
+ return "done", False
+
+ async def _async_noop(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr("modules.agents.opencode.agent.build_system_prompt_injection", lambda **kwargs: "")
+ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", lambda *args, **kwargs: None)
+ agent.controller = SimpleNamespace(
+ config=SimpleNamespace(platform="slack", reply_enhancements=False, remote_access=None, language="en", opencode=admitted),
+ processing_indicator=SimpleNamespace(snapshot_request=lambda request: {}),
+ get_opencode_overrides=lambda context: (None, "gpt-5.4", None),
+ )
+ agent.config = agent.controller.config
+ agent.sessions = _Sessions()
+ agent.opencode_config = admitted
+ agent._session_manager = _SessionManager()
+ agent._poll_loop = _PollLoop()
+ agent._steering_states = {}
+ agent._active_requests = {}
+ serve_opencode_agent(agent, _Server())
+ agent._delete_ack = _async_noop
+ agent._remove_ack_reaction = _async_noop
+ request = AgentRequest(
+ context=MessageContext(user_id="u", channel_id="c", platform="slack", platform_specific={}),
+ message="hello",
+ user_message="hello",
+ working_path="/tmp/work",
+ base_session_id="base",
+ composite_session_id="base:/tmp/work",
+ session_key="slack::c",
+ )
+
+ async def scenario():
+ turn = asyncio.get_running_loop().create_task(agent._process_message(request))
+ await bootstrapping.wait()
+ # A save of agents.opencode adopts its config the way a renewal does.
+ agent._adopt_runtime_config(saved)
+ proceed.set()
+ await turn
+
+ asyncio.run(scenario())
+
+ assert prompts and prompts[0]["model"] == {"providerID": "openai", "modelID": "gpt-5.4"}
+ assert prompts[0]["reasoning_effort"] == "high"
+ assert polled == [admitted]
diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.py
index 3b80e84cb..ec76bfc4f 100644
--- a/tests/test_opencode_restore_polls.py
+++ b/tests/test_opencode_restore_polls.py
@@ -24,6 +24,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config.v2_sessions import ActivePollInfo # noqa: E402
from core.services.agent_steering import SteerOutcome, SteerRequest, active_steer_identity, steer_active_turn # noqa: E402
from modules.agents.opencode.agent import OpenCodeAgent # noqa: E402
+from tests.opencode_generation_fakes import FakeBinding, serve_opencode_agent # noqa: E402
ATTEMPT_ID = "atm_1234567890abcdef1234567890abcdef"
@@ -90,7 +91,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
prompt_calls.append(kwargs)
class _PollLoop:
- async def run_restored_poll_loop(self, poll_info):
+ async def run_restored_poll_loop(self, poll_info, server):
return True
async def remove_restored_ack(self, poll_info):
@@ -112,9 +113,18 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
return self.request_sessions.pop(args[0], None)
class _Sessions:
+ def __init__(self):
+ self.update_errors: list[Exception] = []
+
def get_all_active_polls(self):
return dict(active_polls)
+ def update_active_poll_state(self, session_id, *, processing_indicator):
+ if self.update_errors:
+ raise self.update_errors.pop(0)
+ if session_id in active_polls:
+ active_polls[session_id].processing_indicator = processing_indicator
+
def remove_active_poll(self, session_id):
active_polls.pop(session_id, None)
removed.append(session_id)
@@ -143,15 +153,11 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
agent._steering_states = {}
agent._restored_poll_servers = {}
agent._settling_request_tasks = set()
+ agent._restore_lock = asyncio.Lock()
+ agent._polls_awaiting_restore = set()
server = _Server()
- agent._client_manager = SimpleNamespace(_server_manager=server)
-
- async def _get_server():
- current_task = asyncio.current_task()
- return agent._restored_poll_servers.get(current_task, server)
-
- agent._get_server = _get_server
+ serve_opencode_agent(agent, server)
agent.controller.agent_service = SimpleNamespace(agents={"opencode": agent}, _turn_gates={})
agent._test_prompt_calls = prompt_calls
agent._test_inactive_runs = inactive_runs
@@ -266,7 +272,7 @@ def test_restore_retries_binding_for_the_active_poll_lifetime(monkeypatch) -> No
return True
class _WaitForBindingPollLoop:
- async def run_restored_poll_loop(self, _poll_info):
+ async def run_restored_poll_loop(self, _poll_info, _server):
for _ in range(100):
if attempts >= 4:
return True
@@ -309,7 +315,7 @@ def test_restore_delayed_binding_does_not_replace_a_newer_turn(monkeypatch) -> N
return False
class _WaitForConditionalAttemptPollLoop:
- async def run_restored_poll_loop(self, _poll_info):
+ async def run_restored_poll_loop(self, _poll_info, _server):
for _ in range(100):
if len(attempts) >= 4:
return True
@@ -398,7 +404,7 @@ def test_restore_im_registration_failure_retries_before_releasing_poll() -> None
raise RuntimeError("temporary registration failure")
class _HeldPollLoop:
- async def run_restored_poll_loop(self, _poll_info):
+ async def run_restored_poll_loop(self, _poll_info, _server):
poll_started.set()
await release_poll.wait()
@@ -451,7 +457,7 @@ def test_restored_poll_exposes_the_persisted_guarded_steering_owner() -> None:
agent.controller._delivery_recovery_complete = recovery_complete
class _HeldPollLoop:
- async def run_restored_poll_loop(self, poll_info):
+ async def run_restored_poll_loop(self, poll_info, server):
poll_started.set()
await release_poll.wait()
@@ -559,7 +565,7 @@ def test_restore_preserves_durable_poll_when_verification_is_temporarily_unavail
agent._test_server.messages_error = TimeoutError("temporary verification failure")
class _RecoveredPollLoop:
- async def run_restored_poll_loop(self, poll_info):
+ async def run_restored_poll_loop(self, poll_info, server):
agent._test_server.messages_error = None
async def remove_restored_ack(self, poll_info):
@@ -612,7 +618,7 @@ def test_restore_rebuilds_completed_exact_start_attempt() -> None:
agent.controller._delivery_recovery_complete = recovery_complete
class _HeldPollLoop:
- async def run_restored_poll_loop(self, _poll_info):
+ async def run_restored_poll_loop(self, _poll_info, _server):
poll_started.set()
await release_poll.wait()
@@ -690,8 +696,7 @@ def test_restore_keeps_accepted_steer_with_post_assistant_user_evidence() -> Non
reconciled_messages: list[dict] = []
class _ReconcilePollLoop:
- async def run_restored_poll_loop(self, poll_info):
- server = await agent._get_server()
+ async def run_restored_poll_loop(self, poll_info, server):
reconciled_messages.extend(
await server.list_messages(
poll_info.opencode_session_id,
@@ -813,9 +818,8 @@ def test_restore_preserves_user_only_poll_when_native_status_is_unknown() -> Non
reconciled_messages: list[dict] = []
class _ReconcilePollLoop:
- async def run_restored_poll_loop(self, poll_info):
+ async def run_restored_poll_loop(self, poll_info, server):
agent._test_server.status_error = None
- server = await agent._get_server()
reconciled_messages.extend(
await server.list_messages(
poll_info.opencode_session_id,
@@ -878,8 +882,7 @@ def test_busy_restore_reconciles_inserted_user_that_later_becomes_idle() -> None
agent._test_server.get_session_status = _transitioning_status
class _ReconcilePollLoop:
- async def run_restored_poll_loop(self, poll_info):
- server = await agent._get_server()
+ async def run_restored_poll_loop(self, poll_info, server):
while True:
batch = await server.list_messages(
poll_info.opencode_session_id,
@@ -932,8 +935,7 @@ def test_busy_restore_preserves_completed_answer_without_later_user() -> None:
agent._test_server.get_session_status = _busy_then_idle
class _ReconcilePollLoop:
- async def run_restored_poll_loop(self, poll_info):
- server = await agent._get_server()
+ async def run_restored_poll_loop(self, poll_info, server):
reconciled_messages.extend(
await server.list_messages(
poll_info.opencode_session_id,
@@ -985,8 +987,7 @@ def test_busy_restore_preserves_completed_answer_when_status_becomes_unavailable
agent._test_server.get_session_status = _busy_then_unavailable
class _ReconcilePollLoop:
- async def run_restored_poll_loop(self, poll_info):
- server = await agent._get_server()
+ async def run_restored_poll_loop(self, poll_info, server):
reconciled_messages.extend(
await server.list_messages(
poll_info.opencode_session_id,
@@ -1042,10 +1043,9 @@ def test_unknown_restore_seeds_boundary_when_status_recovers_busy() -> None:
return {"type": "busy" if status_calls == 1 else "idle"}
class _ReconcilePollLoop:
- async def run_restored_poll_loop(self, poll_info):
+ async def run_restored_poll_loop(self, poll_info, server):
agent._test_server.status_error = None
agent._test_server.get_session_status = _busy_then_idle
- server = await agent._get_server()
reconciled_messages.extend(
await server.list_messages(
poll_info.opencode_session_id,
@@ -1083,9 +1083,8 @@ def test_restore_settles_incomplete_assistant_when_unknown_status_recovers_idle(
reconciled_messages: list[dict] = []
class _ReconcilePollLoop:
- async def run_restored_poll_loop(self, poll_info):
+ async def run_restored_poll_loop(self, poll_info, server):
agent._test_server.status_error = None
- server = await agent._get_server()
reconciled_messages.extend(
await server.list_messages(
poll_info.opencode_session_id,
@@ -1137,7 +1136,7 @@ def test_forced_refresh_neither_waits_on_nor_strands_a_stuck_restored_poll(stall
agent._test_server.mark_run_inactive = slow_mark_run_inactive
- async def run_restored_poll_loop(poll_info):
+ async def run_restored_poll_loop(poll_info, _server):
if stall == "retiring":
return True
if stall == "steering_lock":
@@ -1370,3 +1369,335 @@ def test_workbench_session_id_for_poll_resolution():
slack = _make_poll(platform="slack", base_session_id="slack:thread", opencode_session_id="oc-2")
assert OpenCodeAgent._workbench_session_id_for_poll(avibe) == "ses_wb"
assert OpenCodeAgent._workbench_session_id_for_poll(slack) is None
+
+
+def test_a_cancel_during_restored_cleanup_still_releases_its_generation(monkeypatch) -> None:
+ import threading
+
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ agent, _, _, _ = _build_agent({"oc-1": poll})
+ unbinding, finish_unbind = threading.Event(), threading.Event()
+
+ def unbind(*_args, **_kwargs):
+ unbinding.set()
+ finish_unbind.wait(5)
+ return True
+
+ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", lambda *a, **k: True)
+ monkeypatch.setattr("modules.agents.opencode.agent.unbind_caller_context_session", unbind)
+
+ async def run() -> None:
+ assert await agent.restore_active_polls() == 1
+ task = agent._active_requests["ses_wb"]
+ await asyncio.to_thread(unbinding.wait, 5)
+ # A supersede or /stop cancels the poll while its cleanup awaits.
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finish_unbind.set()
+
+ asyncio.run(run())
+
+ assert [binding.released for binding in agent._runtime.bindings] == [True]
+ assert agent._session_generations == {}
+ assert agent._active_requests == {}
+
+
+def test_restore_releases_a_poll_binding_its_task_never_took(monkeypatch) -> None:
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ agent, _, _, _ = _build_agent({"oc-1": poll})
+
+ def unreadable_skills(*_args, **_kwargs):
+ raise RuntimeError("skills root unreadable")
+
+ monkeypatch.setattr("modules.agents.opencode.agent.managed_skill_environment", unreadable_skills)
+
+ with pytest.raises(RuntimeError):
+ asyncio.run(agent.restore_active_polls())
+
+ # A held binding would keep the generation from ever stopping.
+ assert agent._runtime.bindings and all(binding.released for binding in agent._runtime.bindings)
+
+
+def test_a_restored_poll_whose_generation_was_force_stopped_rebinds_before_registering() -> None:
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ agent, _, _, _ = _build_agent({"oc-1": poll})
+ # The cap force-stopped the generation restore bound, before the poll task registered.
+ stopped = FakeBinding(agent._test_server)
+ stopped.generation.stopped = True
+
+ asyncio.run(agent._run_restored_poll_loop_with_tracking(poll, generation_binding=stopped))
+
+ assert stopped.released
+ assert len(agent._runtime.bindings) == 1 and agent._runtime.bindings[0].released
+
+
[email protected]("stage", ["listing messages", "reading status"])
+def test_a_cancelled_restore_releases_the_binding_its_poll_task_never_took(stage) -> None:
+ """An IM-ready restoration is cancelled while it still verifies a poll.
+ The generation binding it took must be released, or every retry keeps
+ that generation from ever draining."""
+
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ agent, _, _, _ = _build_agent({"oc-1": poll})
+ waiting = asyncio.Event()
+
+ async def hang(*_args, **_kwargs):
+ waiting.set()
+ await asyncio.Event().wait()
+
+ if stage == "listing messages":
+ agent._test_server.list_messages = hang
+ else:
+ agent._test_server.get_session_status = hang
+
+ async def run() -> None:
+ restore = asyncio.get_running_loop().create_task(agent.restore_active_polls())
+ await waiting.wait()
+ restore.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await restore
+
+ asyncio.run(run())
+
+ assert agent._runtime.bindings and all(binding.released for binding in agent._runtime.bindings)
+
+
+def test_two_overlapping_restores_of_one_durable_poll_start_exactly_one_loop() -> None:
+ """OpenCode is enabled in a running controller while an IM transport
+ reconnects: two restores overlap. The durable poll gets exactly one loop,
+ so its result is delivered once."""
+
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ agent, _, _, _ = _build_agent({"oc-1": poll})
+ listing = asyncio.Event()
+ proceed = asyncio.Event()
+ finish_loop = asyncio.Event()
+ loops: list[str] = []
+ list_messages = agent._test_server.list_messages
+
+ async def slow_list_messages(*args, **kwargs):
+ listing.set()
+ await proceed.wait()
+ return await list_messages(*args, **kwargs)
+
+ class _HeldPollLoop:
+ async def run_restored_poll_loop(self, poll_info, _server):
+ loops.append(poll_info.opencode_session_id)
+ await finish_loop.wait()
+ return True
+
+ async def remove_restored_ack(self, _poll_info):
+ return None
+
+ agent._test_server.list_messages = slow_list_messages
+ agent._poll_loop = _HeldPollLoop()
+
+ async def run() -> list[str]:
+ first = asyncio.get_running_loop().create_task(agent.restore_active_polls())
+ await listing.wait()
+ second = asyncio.get_running_loop().create_task(agent.restore_active_polls())
+ await asyncio.sleep(0)
+ proceed.set()
+ await asyncio.gather(first, second)
+ started = list(loops)
+ finish_loop.set()
+ await asyncio.gather(*agent._active_requests.values())
+ return started
+
+ assert asyncio.run(run()) == ["oc-1"]
+
+
+def test_restore_leaves_every_poll_whose_run_another_desktop_runtimes_live_server_executes(
+ tmp_path, monkeypatch
+) -> None:
+ """Two desktop Runtimes share this state directory, and the other one's
+ OpenCode server still runs two native turns: one its poll names by
+ generation, one from before generations that its record marks as running.
+ Restore here binds, rewrites, and settles neither, so that Runtime's
+ controller resumes both. A poll naming that Runtime's server after it
+ exited is resumed here, as after any restart."""
+
+ import json
+
+ from modules.agents.opencode import server as opencode_server
+
+ other_runtime, this_runtime = "a" * 64, "b" * 64
+ live_pid, gone_pid = 4_100_001, 4_100_002
+ records = tmp_path / "generations"
+ records.mkdir()
+ for generation_id, pid, port, runs in (
+ ("ocg_live", live_pid, 50201, ["oc-legacy"]),
+ ("ocg_exited", gone_pid, 50202, []),
+ ):
+ (records / f"{generation_id}.json").write_text(
+ json.dumps(
+ {
+ "generation_id": generation_id,
+ "pid": pid,
+ "port": port,
+ "process_created_at": 100.0 + pid,
+ "desktop_runtime_id": other_runtime,
+ "active_run_sessions": runs,
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: records)
+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: tmp_path / "absent.json")
+ monkeypatch.setattr(opencode_server, "desktop_caller_provenance", lambda: frozenset({this_runtime}))
+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid == live_pid)
+ monkeypatch.setattr(opencode_server.runtime, "process_create_time", lambda pid: 100.0 + pid)
+ monkeypatch.setattr(
+ opencode_server.runtime, "get_process_command", lambda pid: "/bin/opencode serve --port=50201"
+ )
+
+ def poll(native_session_id: str, generation_id: str | None = None) -> ActivePollInfo:
+ info = _make_poll(platform="slack", base_session_id=f"base-{native_session_id}", opencode_session_id=native_session_id)
+ info.processing_indicator = {"opencode_generation_id": generation_id} if generation_id else {}
+ return info
+
+ polls = {
+ "oc-live": poll("oc-live", "ocg_live"),
+ "oc-legacy": poll("oc-legacy"),
+ "oc-exited": poll("oc-exited", "ocg_exited"),
+ }
+ agent, _status_writes, removed, request_sessions = _build_agent(polls)
+ rewritten: list[str] = []
+ agent.sessions.update_active_poll_state = lambda session_id, *, processing_indicator: rewritten.append(session_id)
+
+ async def run() -> int:
+ restored = await agent.restore_active_polls()
+ await asyncio.gather(*agent._active_requests.values())
+ return restored
+
+ restored = asyncio.run(run())
+
+ assert restored == 1
+ assert [entry[1] for entry in request_sessions] == ["oc-exited"]
+ assert rewritten == ["oc-exited"]
+ # The exited server's poll settled here; the live server's two stay durable.
+ assert removed == ["oc-exited"] and set(polls) == {"oc-live", "oc-legacy"}
+
+
+def _poll_of_a_gone_generation(native_session_id: str = "oc-1", **indicator) -> ActivePollInfo:
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id=native_session_id)
+ poll.processing_indicator = {"opencode_generation_id": "ocg_gone", **indicator}
+ return poll
+
+
+def _retry_restores_at_the_sweep(agent) -> None:
+ async def restore_polls_on_ready_transports() -> None:
+ await agent.restore_active_polls()
+
+ agent.controller.restore_polls_on_ready_transports = restore_polls_on_ready_transports
+
+
+def test_a_restore_whose_generation_rewrite_fails_runs_nothing_and_the_sweep_restores_it() -> None:
+ """A durable poll names a process that is gone, so restore binds it to the
+ current generation and must record that first. When the write fails, the
+ poll never runs bound elsewhere than it names: its binding is released and
+ it stays durable, still naming the old process. The next sweep restores
+ it again, records the generation, and runs it."""
+
+ polls = {"oc-1": _poll_of_a_gone_generation()}
+ agent, _status_writes, removed, request_sessions = _build_agent(polls)
+ agent.sessions.update_errors.append(RuntimeError("database is locked"))
+ _retry_restores_at_the_sweep(agent)
+
+ async def run():
+ first = await agent.restore_active_polls()
+ left = (
+ first,
+ dict(agent._active_requests),
+ [binding.released for binding in agent._runtime.bindings],
+ polls["oc-1"].processing_indicator["opencode_generation_id"],
+ )
+ await agent.reap_runtime_generations()
+ await asyncio.gather(*agent._active_requests.values())
+ return left
+
+ first, running, released, named = asyncio.run(run())
+
+ assert (first, running, released, named) == (0, {}, [True], "ocg_gone")
+ # The sweep's restore recorded the generation it bound, then ran the poll.
+ assert [entry[1] for entry in request_sessions] == ["oc-1"]
+ assert removed == ["oc-1"] and agent._polls_awaiting_restore == set()
+
+
+def test_a_poll_task_whose_rebind_cannot_be_recorded_leaves_its_turn_live_for_the_sweep() -> None:
+ """The generation restore bound was force-stopped before the poll task
+ registered, so the task binds again, and that rebind cannot be recorded.
+ The task runs nothing and fails no Turn: the poll stays durable with its
+ Turn live, and the next sweep restores it."""
+
+ poll = _poll_of_a_gone_generation(
+ opencode_native_steering={"target_session_id": "ses_wb", "logical_turn_id": "turn-1"},
+ )
+ agent, _status_writes, removed, request_sessions = _build_agent({"oc-1": poll})
+ agent.sessions.update_errors.append(RuntimeError("database is locked"))
+ failed: list[str] = []
+ agent.controller.session_turns.fail_restored_backend_turn = lambda turn_id, **_: failed.append(turn_id) or True
+ _retry_restores_at_the_sweep(agent)
+ stopped = FakeBinding(agent._test_server)
+ stopped.generation.stopped = True
+
+ async def run():
+ await agent._run_restored_poll_loop_with_tracking(poll, generation_binding=stopped)
+ left = (failed[:], list(removed), [binding.released for binding in agent._runtime.bindings])
+ await agent.reap_runtime_generations()
+ await asyncio.gather(*agent._active_requests.values())
+ return left
+
+ assert asyncio.run(run()) == ([], [], [True])
+ assert failed == [] and removed == ["oc-1"]
+ assert [entry[1] for entry in request_sessions] == ["oc-1"]
+
+
+def test_a_restore_whose_publication_fails_leaves_no_poll_task_waiting_on_it() -> None:
+ """Two polls are handed off, and marking the first one's session running
+ fails. The restore publishes the first and fails, and must not leave the
+ second waiting for a publication that never comes: that task is cancelled
+ before its loop, releasing its binding and request, and the poll stays
+ durable until the next sweep restores it."""
+
+ polls = {
+ "oc-1": _make_poll(platform="avibe", base_session_id="ses_1", opencode_session_id="oc-1"),
+ "oc-2": _make_poll(platform="avibe", base_session_id="ses_2", opencode_session_id="oc-2"),
+ }
+ agent, _status_writes, removed, _request_sessions = _build_agent(polls)
+ marked: list[str] = []
+
+ def restore_running(session_id: str) -> None:
+ marked.append(session_id)
+ if len(marked) == 1:
+ raise RuntimeError("database is locked")
+
+ agent.controller.session_turns.restore_running = restore_running
+ _retry_restores_at_the_sweep(agent)
+
+ async def run():
+ with pytest.raises(RuntimeError, match="database is locked"):
+ await agent.restore_active_polls()
+ handed_off = dict(agent._active_requests)
+ await asyncio.wait(handed_off.values(), timeout=1.0)
+ left = (
+ sorted(key for key, task in handed_off.items() if not task.done()),
+ sorted(agent._active_requests),
+ [binding.released for binding in agent._runtime.bindings],
+ sorted(polls),
+ )
+ # Only a task that would wait forever is still running here.
+ for task in handed_off.values():
+ task.cancel()
+ await asyncio.wait(handed_off.values())
+ await agent.reap_runtime_generations()
+ await asyncio.gather(*agent._active_requests.values())
+ return left
+
+ waiting, requests, released, durable = asyncio.run(run())
+
+ assert (waiting, requests, released, durable) == ([], [], [True, True], ["oc-2"])
+ # The first poll ran once published; the sweep restored and ran the second.
+ assert marked == ["ses_1", "ses_2"]
+ assert removed == ["oc-1", "oc-2"] and polls == {}
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 6aa91d0cc..912395459 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -14,7 +14,7 @@ import types
import unittest
from contextlib import suppress
from pathlib import Path
-from unittest.mock import AsyncMock, Mock, patch
+from unittest.mock import AsyncMock, patch
import psutil
import pytest
@@ -22,7 +22,6 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from storage import message_deliveries as delivery_store
-from tests.fake_pid_helpers import fake_pid
from vibe.opencode_config import OPENCODE_REASONING_VARIANTS
@@ -39,6 +38,8 @@ def _load_server_module():
spec = importlib.util.spec_from_file_location("opencode_server_for_test", MODULE_PATH)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
+ # Dataclasses resolve their annotations through the module registry.
+ sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
finally:
@@ -49,36 +50,8 @@ def _load_server_module():
SERVER_MODULE = _load_server_module()
-OpenCodeManagedPolicyRefreshPendingError = (
- SERVER_MODULE.OpenCodeManagedPolicyRefreshPendingError
-)
-OpenCodeModelHubOverlayRequiredError = (
- SERVER_MODULE.OpenCodeModelHubOverlayRequiredError
-)
OpenCodeRuntimeConfigInvalidError = SERVER_MODULE.OpenCodeRuntimeConfigInvalidError
-OpenCodeServerManager = SERVER_MODULE.OpenCodeServerManager
-
-
-def _model_hub_overlay(path: str, model_id: str | None):
- models = {} if model_id is None else {model_id: {"id": model_id}}
- content = json.dumps(
- {
- "enabled_providers": ["avibe-openai"],
- "provider": {
- "avibe-openai": {
- "models": models,
- }
- }
- },
- sort_keys=True,
- )
- composed = SERVER_MODULE._managed_runtime_config_content(content)
- return types.SimpleNamespace(
- path=Path(path),
- content_hash=hashlib.sha256(composed.encode()).hexdigest(),
- content=content,
- provider_ids=("avibe-openai",),
- )
+OpenCodeServerClient = SERVER_MODULE.OpenCodeServerClient
class _FakeResponse:
@@ -195,96 +168,6 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
with self.assertRaises(OpenCodeRuntimeConfigInvalidError):
SERVER_MODULE._managed_runtime_config_content(content)
- async def test_start_server_reaps_a_live_process_after_cold_start_timeout(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- process = types.SimpleNamespace(pid=fake_pid(), returncode=None)
- manager._is_healthy = AsyncMock(return_value=False) # type: ignore[method-assign]
- manager._write_pid_file = Mock() # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
- manager._apply_resource_governance = Mock() # type: ignore[method-assign]
- manager._terminate_tracked_process = AsyncMock() # type: ignore[method-assign]
- create_process = AsyncMock(return_value=process)
- user_config = '{"permission":"ask"}'
-
- with (
- patch.object(
- SERVER_MODULE.asyncio,
- "create_subprocess_exec",
- create_process,
- ),
- patch.object(SERVER_MODULE.asyncio, "sleep", AsyncMock()),
- patch.object(SERVER_MODULE.time, "monotonic", side_effect=[0.0, 0.0, 121.0]),
- patch.object(SERVER_MODULE, "server_environment", return_value={}),
- patch.dict(os.environ, {"OPENCODE_CONFIG_CONTENT": user_config, "AVIBE_OPENCODE_MODEL_HUB": "1"}),
- ):
- with self.assertRaisesRegex(RuntimeError, "failed to start within 120s"):
- await manager._start_server()
-
- manager._terminate_tracked_process.assert_awaited_once_with(process, reason="startup timeout")
- self.assertEqual(manager._clear_pid_file.call_count, 2)
- self.assertEqual(create_process.await_args.kwargs["env"]["AVIBE_OPENCODE_MODEL_HUB"], "0")
- self.assertIsNone(manager._process)
- self.assertIsNone(manager._process_loop)
- self.assertIsNone(manager._last_start_failure_pid)
- self.assertEqual(
- json.loads(create_process.await_args.kwargs["env"]["OPENCODE_CONFIG_CONTENT"]),
- {
- "permission": {"*": "ask", "skill": "deny"},
- "tools": {"skill": False},
- },
- )
- self.assertEqual(
- create_process.await_args.kwargs["env"]["OPENCODE_DISABLE_EXTERNAL_SKILLS"],
- "1",
- )
- # A desktop Runtime's scoped stop knows the server by this stamp.
- self.assertEqual(create_process.await_args.kwargs["env"]["AVIBE_DESKTOP_ROLE"], "opencode")
-
- def test_terminate_instance_sync_stops_unadopted_managed_server(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- pid_file = Path(tmp_dir) / "opencode_server.json"
- pid_file.write_text(json.dumps({"pid": 4321, "port": 4096}), encoding="utf-8")
- terminate = Mock(return_value=True)
- previous = OpenCodeServerManager._instance
- OpenCodeServerManager._instance = None
- try:
- with (
- patch.object(SERVER_MODULE.paths, "get_logs_dir", return_value=Path(tmp_dir)),
- patch.object(
- SERVER_MODULE.runtime,
- "get_process_command",
- return_value="opencode serve --port=4096",
- ),
- patch.object(OpenCodeServerManager, "_terminate_pid_tree_sync", terminate),
- ):
- OpenCodeServerManager.terminate_instance_sync()
- finally:
- OpenCodeServerManager._instance = previous
-
- terminate.assert_called_once_with(4321)
- self.assertFalse(pid_file.exists())
-
- def test_terminate_instance_sync_trusts_pid_file_port_owner_without_command(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- pid_file = Path(tmp_dir) / "opencode_server.json"
- pid_file.write_text(json.dumps({"pid": 4321, "port": 4096}), encoding="utf-8")
- terminate = Mock(return_value=True)
- previous = OpenCodeServerManager._instance
- OpenCodeServerManager._instance = None
- try:
- with (
- patch.object(SERVER_MODULE.paths, "get_logs_dir", return_value=Path(tmp_dir)),
- patch.object(SERVER_MODULE.runtime, "get_process_command", return_value=None),
- patch.object(OpenCodeServerManager, "_pid_owns_listening_port", return_value=True),
- patch.object(OpenCodeServerManager, "_terminate_pid_tree_sync", terminate),
- ):
- OpenCodeServerManager.terminate_instance_sync()
- finally:
- OpenCodeServerManager._instance = previous
-
- terminate.assert_called_once_with(4321)
- self.assertFalse(pid_file.exists())
-
def test_percent_encode_path_preserves_round_trip_sensitive_paths(self):
self.assertEqual(
SERVER_MODULE._percent_encode_path("/tmp/小说"),
@@ -313,7 +196,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
},
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
manager._get_http_session = AsyncMock(return_value=_CatalogSession()) # type: ignore[method-assign]
models = await manager.get_available_models(
@@ -405,11 +288,12 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
}
return _FakeResponse(status=200, json_data=payload)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._model_hub_overlay_provider_ids = runtime_ids
+ manager = OpenCodeServerClient(
+ "http://127.0.0.1:4096",
+ model_hub_provider_ids=runtime_ids,
+ )
session = _CatalogSession()
manager._get_http_session = AsyncMock(return_value=session) # type: ignore[method-assign]
- manager.ensure_running = AsyncMock() # type: ignore[method-assign]
models = await manager.get_available_models(
"/tmp/work",
@@ -480,651 +364,8 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
},
)
- async def test_ensure_running_restarts_healthy_server_when_caller_context_plugin_changes(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- restarted = []
- started = []
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock(side_effect=lambda: restarted.append(True)) # type: ignore[method-assign]
- manager._start_server = AsyncMock(side_effect=lambda: started.append(True)) # type: ignore[method-assign]
- manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID, "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION} # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=True),
- ):
- base_url = await manager.ensure_running()
-
- self.assertEqual(base_url, "http://127.0.0.1:4096")
- self.assertEqual(restarted, [True])
- self.assertEqual(started, [True])
- self.assertFalse(manager._caller_context_plugin_refresh_pending)
-
- async def test_hub_mode_refuses_unconfigured_launch_and_logs_once(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- config = SERVER_MODULE.V2Config.load()
- config.model_hub.agents["opencode"].mode = "hub"
- config.save()
-
- with (
- patch.dict(os.environ),
- patch.object(SERVER_MODULE.logger, "error") as log_error,
- patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- side_effect=AssertionError("Hub refusal must precede server setup"),
- ),
- ):
- os.environ.pop("VIBE_MODEL_HUB_ENABLED", None)
- for _attempt in range(2):
- with self.assertRaises(OpenCodeModelHubOverlayRequiredError):
- await manager.ensure_running()
-
- log_error.assert_called_once()
- manager._start_server.assert_not_awaited()
-
- async def test_ui_hub_mode_refuses_even_when_controller_overlay_is_running(self):
- overlay = _model_hub_overlay("/tmp/opencode-overlay.json", "gpt-5")
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._model_hub_overlay_path = str(overlay.path)
- manager._model_hub_overlay_hash = overlay.content_hash
- manager._model_hub_overlay_content = SERVER_MODULE._managed_runtime_config_content(
- overlay.content
- )
- manager._model_hub_overlay_provider_ids = overlay.provider_ids
- manager._start_server = AsyncMock() # type: ignore[method-assign]
-
- with (
- patch.object(SERVER_MODULE, "is_model_hub_enabled", return_value=True),
- patch.object(
- SERVER_MODULE.V2Config,
- "load",
- return_value=types.SimpleNamespace(
- model_hub=types.SimpleNamespace(
- agents={
- "opencode": types.SimpleNamespace(mode="hub"),
- }
- )
- ),
- ),
- patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- side_effect=AssertionError("UI process must refuse before server setup"),
- ),
- ):
- with self.assertRaises(OpenCodeModelHubOverlayRequiredError):
- await manager.ensure_running()
-
- manager._start_server.assert_not_awaited()
-
- async def test_launch_rechecks_mode_inside_lock_immediately_before_spawn(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- events = []
- modes = iter((False, True))
-
- def current_mode():
- events.append(("mode", manager._get_lock().locked()))
- return next(modes)
-
- async def cleanup():
- events.append(("cleanup", manager._get_lock().locked()))
-
- manager._model_hub_mode_enabled = Mock(side_effect=current_mode) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(return_value=False) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock(side_effect=cleanup) # type: ignore[method-assign]
- manager._is_port_available = Mock(return_value=True) # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(
- path=Path("/tmp/plugin.js"),
- changed=False,
- ),
- ):
- with self.assertRaises(OpenCodeModelHubOverlayRequiredError):
- await manager.ensure_running()
-
- self.assertEqual(
- events,
- [("mode", False), ("cleanup", True), ("mode", True)],
- )
- manager._start_server.assert_not_awaited()
-
- async def test_controller_probe_prepares_overlay_before_launch(self):
- from core.resource_governance import mark_controller_resource_governor
-
- governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- mark_controller_resource_governor(governor)
- manager = OpenCodeServerManager(
- binary="opencode",
- port=4096,
- resource_governor=governor,
- )
- overlay = _model_hub_overlay("/tmp/opencode-overlay.json", "gpt-5")
- prepare_overlay = AsyncMock(return_value=overlay)
- manager.set_model_hub_overlay_preparer(prepare_overlay)
- manager._read_pid_file = Mock(return_value=None) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(side_effect=[False, False, True]) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._is_port_available = Mock(return_value=True) # type: ignore[method-assign]
- manager._write_pid_file = Mock() # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
- manager._observe_runtime_generation = Mock() # type: ignore[method-assign]
- launched = {}
-
- async def create_subprocess_exec(*args, **kwargs):
- launched["args"] = args
- launched["env"] = kwargs["env"]
- return types.SimpleNamespace(pid=fake_pid(), returncode=None)
-
- with (
- patch.object(SERVER_MODULE, "is_model_hub_enabled", return_value=True),
- patch.object(
- SERVER_MODULE.V2Config,
- "load",
- return_value=types.SimpleNamespace(
- model_hub=types.SimpleNamespace(
- agents={
- "opencode": types.SimpleNamespace(mode="hub"),
- }
- )
- ),
- ),
- patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(
- path=Path("/tmp/plugin.js"),
- changed=False,
- ),
- ),
- patch.object(
- SERVER_MODULE,
- "server_environment",
- return_value={},
- ),
- patch.object(
- SERVER_MODULE.asyncio,
- "create_subprocess_exec",
- side_effect=create_subprocess_exec,
- ),
- ):
- base_url = await manager.ensure_running()
-
- self.assertEqual(base_url, "http://127.0.0.1:4096")
- prepare_overlay.assert_awaited_once_with()
- self.assertEqual(launched["env"]["OPENCODE_CONFIG"], str(overlay.path))
- self.assertEqual(launched["env"]["AVIBE_OPENCODE_MODEL_HUB"], "1")
- inline_config = json.loads(launched["env"]["OPENCODE_CONFIG_CONTENT"])
- self.assertEqual(
- inline_config["provider"]["avibe-openai"]["models"],
- {"gpt-5": {"id": "gpt-5"}},
- )
- self.assertEqual(manager._model_hub_overlay_reservations, {})
-
- async def test_feature_gate_off_keeps_persisted_hub_in_direct_mode(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._ensure_running_with_current_overlay = AsyncMock( # type: ignore[method-assign]
- return_value="http://127.0.0.1:4096"
- )
-
- with (
- patch.object(SERVER_MODULE, "is_model_hub_enabled", return_value=False),
- patch.object(
- SERVER_MODULE.V2Config,
- "load",
- side_effect=AssertionError("disabled Model Hub must not read its mode"),
- ),
- ):
- base_url = await manager.ensure_running()
-
- self.assertEqual(base_url, "http://127.0.0.1:4096")
- manager._ensure_running_with_current_overlay.assert_awaited_once_with()
-
- async def test_ensure_running_defers_plugin_restart_while_run_active(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._active_run_sessions.add("ses-active")
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID, "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION} # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=True),
- ):
- with self.assertRaisesRegex(RuntimeError, "caller-context plugin refresh is pending"):
- await manager.ensure_running()
-
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
- manager._start_server.assert_not_awaited()
- self.assertTrue(manager._caller_context_plugin_refresh_pending)
-
- async def test_ensure_running_restarts_adopted_server_without_caller_context_env(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- restarted = []
- started = []
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock(side_effect=lambda: restarted.append(True)) # type: ignore[method-assign]
- manager._start_server = AsyncMock(side_effect=lambda: started.append(True)) # type: ignore[method-assign]
- manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "active_run_sessions": []} # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- base_url = await manager.ensure_running()
-
- self.assertEqual(base_url, "http://127.0.0.1:4096")
- self.assertEqual(restarted, [True])
- self.assertEqual(started, [True])
- self.assertFalse(manager._caller_context_plugin_refresh_pending)
-
- async def test_ensure_running_restarts_idle_adopted_server_with_stale_runtime_policy(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": 123,
- "port": 4096,
- "caller_context_path": manager._caller_context_path(),
- "active_run_sessions": [],
- "runtime_policy_revision": "previous-policy",
- }
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- base_url = await manager.ensure_running()
-
- self.assertEqual(base_url, "http://127.0.0.1:4096")
- manager._restart_for_auth_refresh_locked.assert_awaited_once()
- manager._start_server.assert_awaited_once()
-
- async def test_ensure_running_reconciles_orphaned_adopted_run_before_policy_refresh(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._pid_file = Path(tmp_dir) / "opencode_server.json"
- manager._pid_file.write_text(
- json.dumps(
- {
- "pid": 123,
- "port": 4096,
- "caller_context_path": manager._caller_context_path(),
- "active_run_sessions": ["ses-orphan"],
- "runtime_policy_revision": "previous-policy",
- }
- ),
- encoding="utf-8",
- )
- manager.set_active_poll_session_ids_provider(set)
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- base_url = await manager.ensure_running()
-
- self.assertEqual(base_url, "http://127.0.0.1:4096")
- manager._restart_for_auth_refresh_locked.assert_awaited_once()
- manager._start_server.assert_awaited_once()
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertEqual(payload["active_run_sessions"], [])
-
- async def test_ensure_running_keeps_adopted_run_with_durable_poll(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager.set_active_poll_session_ids_provider(lambda: {"ses-active"})
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": 123,
- "port": 4096,
- "caller_context_path": manager._caller_context_path(),
- "active_run_sessions": ["ses-active"],
- "runtime_policy_revision": "previous-policy",
- }
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- with self.assertRaises(OpenCodeManagedPolicyRefreshPendingError):
- await manager.ensure_running()
-
- self.assertEqual(manager._active_run_sessions, {"ses-active"})
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
- manager._start_server.assert_not_awaited()
-
- async def test_ensure_running_keeps_adopted_run_when_poll_reconciliation_fails(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
-
- def unavailable_polls() -> set[str]:
- raise OSError("sessions unavailable")
-
- manager.set_active_poll_session_ids_provider(unavailable_polls)
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": 123,
- "port": 4096,
- "caller_context_path": manager._caller_context_path(),
- "active_run_sessions": ["ses-unknown"],
- "runtime_policy_revision": "previous-policy",
- }
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- with self.assertRaises(OpenCodeManagedPolicyRefreshPendingError):
- await manager.ensure_running()
-
- self.assertEqual(manager._active_run_sessions, set())
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
- manager._start_server.assert_not_awaited()
-
- async def test_ensure_running_defers_adopted_server_without_caller_context_env(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "active_run_sessions": ["ses-active"]} # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- with self.assertRaisesRegex(
- OpenCodeManagedPolicyRefreshPendingError,
- "adopted or active server",
- ):
- await manager.ensure_running()
-
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
- manager._start_server.assert_not_awaited()
- self.assertTrue(manager._caller_context_plugin_refresh_pending)
-
- async def test_ensure_running_defers_adopted_server_with_unknown_active_state(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: {"pid": 123, "port": 4096} # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- with self.assertRaisesRegex(RuntimeError, "adopted or active server"):
- await manager.ensure_running()
-
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
- manager._start_server.assert_not_awaited()
- self.assertTrue(manager._caller_context_plugin_refresh_pending)
-
- async def test_ensure_running_preserves_an_adopted_absolute_caller_context_path(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- adopted_path = "/old-avibe-home/runtime/opencode_caller_context.json"
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": fake_pid(),
- "port": 4096,
- "caller_context_path": adopted_path,
- "active_run_sessions": ["ses-active"],
- "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,
- }
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- manager._caller_context_path = lambda: "/new-avibe-home/runtime/opencode_caller_context.json" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- base_url = await manager.ensure_running()
-
- self.assertEqual(base_url, "http://127.0.0.1:4096")
- self.assertEqual(manager.caller_context_binding_path(), Path(adopted_path))
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
- manager._start_server.assert_not_awaited()
- self.assertFalse(manager._caller_context_plugin_refresh_pending)
-
- async def test_mark_run_active_persists_pid_file_active_sessions(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- with tempfile.TemporaryDirectory() as tmp_dir:
- manager._pid_file = Path(tmp_dir) / "opencode_server.json"
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- manager._write_pid_file(123)
-
- await manager.mark_run_active("ses-active")
-
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertEqual(payload["active_run_sessions"], ["ses-active"])
- self.assertEqual(
- payload["runtime_policy_revision"],
- SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,
- )
-
- await manager.mark_run_inactive("ses-active")
-
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertEqual(payload["active_run_sessions"], [])
-
- def test_pid_file_records_birth_only_when_supplied_by_spawn(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- with tempfile.TemporaryDirectory() as tmp_dir:
- manager._pid_file = Path(tmp_dir) / "opencode_server.json"
- manager._write_pid_file(123)
- legacy = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertNotIn("process_created_at", legacy)
-
- manager._write_pid_file(123, process_created_at=1000.0)
- spawned = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertEqual(spawned["process_created_at"], 1000.0)
-
- async def test_mark_run_inactive_preserves_active_state_when_pid_write_fails(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- with tempfile.TemporaryDirectory() as tmp_dir:
- manager._pid_file = Path(tmp_dir) / "opencode_server.json"
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- manager._write_pid_file(123)
- await manager.mark_run_active("ses-active")
-
- with patch.object(
- SERVER_MODULE,
- "write_atomic",
- side_effect=OSError("read-only pid file"),
- ):
- with self.assertRaisesRegex(OSError, "read-only pid file"):
- await manager.mark_run_inactive("ses-active")
-
- self.assertEqual(manager._active_run_sessions, {"ses-active"})
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertEqual(payload["active_run_sessions"], ["ses-active"])
-
- async def test_mark_run_inactive_preserves_other_adopted_active_sessions(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- with tempfile.TemporaryDirectory() as tmp_dir:
- manager._pid_file = Path(tmp_dir) / "opencode_server.json"
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- manager._write_pid_file(123)
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- payload["active_run_sessions"] = ["ses-completed", "ses-other-platform"]
- manager._pid_file.write_text(json.dumps(payload), encoding="utf-8")
-
- await manager.mark_run_inactive("ses-completed")
-
- self.assertEqual(manager._active_run_sessions, {"ses-other-platform"})
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertEqual(payload["active_run_sessions"], ["ses-other-platform"])
-
- async def test_mark_run_active_preserves_adopted_active_sessions(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- with tempfile.TemporaryDirectory() as tmp_dir:
- manager._pid_file = Path(tmp_dir) / "opencode_server.json"
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- manager._write_pid_file(123)
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- payload["active_run_sessions"] = ["ses-other-platform"]
- manager._pid_file.write_text(json.dumps(payload), encoding="utf-8")
-
- await manager.mark_run_active("ses-new")
-
- self.assertEqual(manager._active_run_sessions, {"ses-new", "ses-other-platform"})
- payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
- self.assertEqual(
- payload["active_run_sessions"],
- ["ses-new", "ses-other-platform"],
- )
-
- async def test_cleanup_stale_managed_pid_does_not_inherit_caller_context_for_new_pid(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- pid_info = {"pid": 111, "port": 4096, "caller_context_path": manager._caller_context_path()}
- writes = []
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._read_pid_file = lambda: pid_info # type: ignore[method-assign]
- manager._find_opencode_serve_pids = lambda port: [222] # type: ignore[method-assign]
-
- def _write_pid_file(
- pid,
- *,
- caller_context_path=SERVER_MODULE._USE_CURRENT_CALLER_CONTEXT_PATH,
- owner_pid=SERVER_MODULE._CURRENT_OWNER_PID,
- runtime_policy_revision=SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,
- ):
- writes.append((pid, caller_context_path, owner_pid, runtime_policy_revision))
- pid_info.clear()
- pid_info.update({"pid": pid, "port": 4096})
- if isinstance(caller_context_path, str) and caller_context_path:
- pid_info["caller_context_path"] = caller_context_path
-
- manager._write_pid_file = _write_pid_file # type: ignore[method-assign]
-
- await manager._cleanup_orphaned_managed_server()
-
- self.assertEqual(writes, [(222, None, None, None)])
- self.assertNotIn("caller_context_path", pid_info)
-
- async def test_ensure_running_rejects_unmanaged_healthy_server(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- manager._start_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: None # type: ignore[method-assign]
- manager._write_pid_file = lambda pid: self.fail("unmanaged server must not be adopted as Avibe-managed") # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- with self.assertRaisesRegex(RuntimeError, "not managed by Avibe"):
- await manager.ensure_running()
-
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
- manager._start_server.assert_not_awaited()
-
- async def test_ensure_running_retires_generation_before_process_replacement(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- events = []
- manager._runtime_generation_token = (111, 1.0)
- manager.set_runtime_activation_retire(
- lambda force, native_turns_drained: events.append(
- ("retire", force, native_turns_drained)
- )
- or True
- )
- manager._is_healthy = AsyncMock(return_value=False) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._is_port_available = lambda: True # type: ignore[method-assign]
- manager._start_server = AsyncMock( # type: ignore[method-assign]
- side_effect=lambda: events.append(("start", True))
- )
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- await manager.ensure_running()
-
- self.assertEqual(events, [("retire", True, False), ("start", True)])
-
- async def test_ensure_running_retires_generation_when_adopted_pid_changes(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- retired = []
- manager._runtime_generation_token = (fake_pid(0), 1.0)
- manager.set_runtime_activation_retire(
- lambda force, native_turns_drained: retired.append(
- (force, native_turns_drained)
- )
- or True
- )
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": fake_pid(1),
- "port": 4096,
- "started_at": 2.0,
- "caller_context_path": manager._caller_context_path(),
- "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,
- }
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
-
- with patch.object(
- SERVER_MODULE,
- "ensure_plugin_installed",
- return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
- ):
- await manager.ensure_running()
-
- self.assertEqual(retired, [(True, False)])
- self.assertEqual(manager._runtime_generation_token, (fake_pid(1), 2.0))
-
async def test_prompt_async_percent_encodes_directory_header(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _FakeSession()
async def _fake_get_http_session():
@@ -1153,7 +394,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
json_data={"ses-active": {"type": "busy"}, "ses-idle": {"type": "idle"}},
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _StatusSession()
async def _fake_get_http_session():
@@ -1168,1466 +409,234 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(missing)
self.assertEqual(fake_session.gets[0]["url"], "http://127.0.0.1:4096/session/status")
self.assertEqual(
- fake_session.gets[0]["headers"],
- {"x-opencode-directory": "/tmp/%E5%B0%8F%E8%AF%B4"},
- )
-
- async def test_get_version_uses_health_endpoint(self):
- class _HealthSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={"healthy": True, "version": "1.18.5"},
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _HealthSession()
-
- async def _fake_get_http_session():
- return fake_session
-
- manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
-
- with patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()):
- version = await manager.get_version()
-
- self.assertEqual(version, "1.18.5")
- self.assertEqual(fake_session.gets[0]["url"], "http://127.0.0.1:4096/global/health")
-
- async def test_prompt_async_includes_tools_when_provided(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
-
- async def _fake_get_http_session():
- return fake_session
-
- manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
-
- await manager.prompt_async(
- session_id="ses-1",
- directory="/tmp/work",
- text="hello",
- tools={"question": False},
- )
-
- self.assertEqual(len(fake_session.posts), 1)
- body = fake_session.posts[0]["json"]
- self.assertEqual(body["tools"], {"question": False})
-
- async def test_prompt_async_uses_opencode_native_attempt_part(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
-
- async def _fake_get_http_session():
- return fake_session
-
- manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
-
- await manager.prompt_async(
- session_id="ses-1",
- directory="/tmp/work",
- text="hello",
- attempt_id="atm_1234567890abcdef1234567890abcdef",
- )
-
- body = fake_session.posts[0]["json"]
- self.assertNotIn("messageID", body)
- self.assertEqual(
- body["parts"],
- [
- {
- "type": "text",
- "text": "hello",
- "id": "prt_1234567890abcdef1234567890abcdef",
- }
- ],
- )
-
- def test_durable_attempt_maps_to_opencode_part_evidence(self):
- attempt_id = delivery_store.new_attempt_id()
-
- self.assertRegex(attempt_id, r"^atm_[0-9a-f]{32}$")
- self.assertEqual(
- SERVER_MODULE.native_part_id_for_attempt(attempt_id),
- f"prt_{attempt_id.removeprefix('atm_')}",
- )
-
- def test_unreleased_ordered_attempt_identity_is_rejected(self):
- with self.assertRaises(ValueError):
- SERVER_MODULE.native_part_id_for_attempt(
- "atm_1234567890000123456789abcd"
- )
-
- async def test_prompt_async_exposes_definitive_http_rejection(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
-
- def _post(url, json=None, headers=None):
- fake_session.posts.append({"url": url, "json": json, "headers": headers})
- return _FakeResponse(status=409, text="active input refused")
-
- fake_session.post = _post
-
- async def _fake_get_http_session():
- return fake_session
-
- manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
-
- with self.assertRaises(SERVER_MODULE.OpenCodePromptRejectedError) as raised:
- await manager.prompt_async(
- session_id="ses-1",
- directory="/tmp/work",
- text="hello",
- )
-
- self.assertEqual(raised.exception.status, 409)
- self.assertEqual(raised.exception.response_text, "active input refused")
-
- async def test_prompt_async_omits_default_variant(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
-
- async def _fake_get_http_session():
- return fake_session
-
- manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
-
- await manager.prompt_async(
- session_id="ses-1",
- directory="/tmp/work",
- text="hello",
- reasoning_effort="default",
- )
-
- self.assertEqual(len(fake_session.posts), 1)
- body = fake_session.posts[0]["json"]
- self.assertNotIn("variant", body)
-
- async def test_fork_session_sends_message_id_when_provided(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
-
- def _post(url, json=None, headers=None):
- fake_session.posts.append({"url": url, "json": json, "headers": headers})
- return _FakeResponse(status=200, json_data={"id": "oc-fork"})
-
- fake_session.post = _post
-
- async def _fake_get_http_session():
- return fake_session
-
- manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
-
- result = await manager.fork_session("oc-source", directory="/tmp/work", message_id="oc-msg-prev")
-
- self.assertEqual(result, {"id": "oc-fork"})
- self.assertEqual(len(fake_session.posts), 1)
- self.assertEqual(fake_session.posts[0]["json"], {"messageID": "oc-msg-prev"})
- self.assertEqual(
- fake_session.posts[0]["headers"],
- {"x-opencode-directory": "/tmp/work"},
- )
-
- async def test_load_opencode_user_config_supports_jsonc(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- """{
- // Preserve defaults from JSONC config.
- "model": "openai/gpt-5",
- "reasoningEffort": "high",
-}
-""",
- encoding="utf-8",
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- with patch("vibe.opencode_config.Path.home", return_value=tmp_home):
- config = manager._load_opencode_user_config()
-
- self.assertEqual(
- config,
- {
- "model": "openai/gpt-5",
- "reasoningEffort": "high",
- },
- )
-
- async def test_explicit_subagent_model_is_independent_of_native_defaults(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- for native_model in (None, "openai/native-one", "anthropic/native-two"):
- for declared in (None, "", " ", {"id": "invalid"}, " provider/reviewer "):
- with self.subTest(native_model=native_model, declared=declared):
- config = {
- "model": native_model,
- "agent": {
- "build": {"model": native_model},
- "reviewer": {"model": declared},
- },
- }
- with patch.object(manager, "_load_opencode_user_config", return_value=config):
- expected = (declared.strip() or None) if isinstance(declared, str) else None
- self.assertEqual(manager.get_explicit_subagent_model("reviewer"), expected)
- self.assertIsNone(manager.get_explicit_subagent_model("missing"))
- self.assertIsNone(manager.get_explicit_subagent_model(""))
-
- async def test_agent_reasoning_effort_reads_back_every_savable_variant(self):
- # A tier the save path can write must never be dropped here as unknown
- # (#1840: catalog-declared `ultra` was rejected by both halves).
- for effort in OPENCODE_REASONING_VARIANTS:
- with self.subTest(effort=effort):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- json.dumps({"reasoningEffort": effort}),
- encoding="utf-8",
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- with patch("vibe.opencode_config.Path.home", return_value=tmp_home):
- resolved = manager.get_agent_reasoning_effort_from_config(None)
-
- self.assertEqual(resolved, effort)
-
- async def test_refresh_global_config_patches_live_server(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"deepseek":{"options":{"baseURL":"https://api.deepseek.com"}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "deepseek": {
- "options": {
- "apiKey": "sk-live",
- "baseURL": "https://stale.example",
- }
- },
- "openai": {"options": {"apiKey": "sk-openai"}},
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertTrue(fake_session.closed)
- self.assertEqual(len(fake_session.gets), 1)
- self.assertEqual(len(fake_session.patches), 1)
- self.assertEqual(
- fake_session.patches[0]["url"],
- "http://127.0.0.1:4096/global/config",
- )
- self.assertEqual(
- fake_session.patches[0]["json"],
- {
- "provider": {
- "deepseek": {
- "options": {
- "baseURL": "https://api.deepseek.com",
- }
- }
- }
- },
- )
-
- async def test_refresh_global_config_preserves_auth_json_api_key(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"anthropic":{"options":{"baseURL":"https://relay.example/v1"}}}}',
- encoding="utf-8",
- )
- auth_path = tmp_home / ".local" / "share" / "opencode" / "auth.json"
- auth_path.parent.mkdir(parents=True, exist_ok=True)
- auth_path.write_text(
- '{"anthropic":{"type":"api","key":"sk-auth-json"}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "anthropic": {
- "options": {
- "apiKey": "sk-auth-json",
- "baseURL": "https://stale.example",
- }
- }
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertEqual(
- fake_session.patches[0]["json"]["provider"]["anthropic"]["options"],
- {
- "apiKey": "sk-auth-json",
- "baseURL": "https://relay.example/v1",
- },
- )
-
- async def test_refresh_global_config_does_not_resurrect_deleted_provider_options(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"openai":{"options":{"apiKey":"sk-config"}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-config",
- "baseURL": "https://deleted.example/v1",
- }
- }
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertEqual(
- fake_session.patches[0]["json"]["provider"]["openai"]["options"],
- {"apiKey": "sk-config"},
- )
-
- async def test_refresh_global_config_oauth_entry_clears_stale_api_key(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"openai":{"options":{"baseURL":"https://relay.example/v1"}}}}',
- encoding="utf-8",
- )
- auth_path = tmp_home / ".local" / "share" / "opencode" / "auth.json"
- auth_path.parent.mkdir(parents=True, exist_ok=True)
- auth_path.write_text(
- '{"openai":{"type":"oauth","refresh":"oauth-refresh"}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-stale",
- "baseURL": "https://old.example/v1",
- }
- }
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertEqual(
- fake_session.patches[0]["json"]["provider"]["openai"]["options"],
- {"baseURL": "https://relay.example/v1"},
- )
-
- async def test_refresh_global_config_drops_live_provider_missing_from_user_config(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"anthropic":{"options":{"baseURL":"https://relay.example/v1"}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "anthropic": {"options": {"baseURL": "https://relay.example/v1"}},
- "openai": {
- "options": {
- "apiKey": "sk-stale",
- "baseURL": "https://deleted.example/v1",
- }
- },
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertEqual(
- set(fake_session.patches[0]["json"]["provider"].keys()),
- {"anthropic"},
- )
-
- async def test_refresh_global_config_preserves_new_provider_options(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"claude-relay":{"name":"Claude Relay","npm":"@ai-sdk/anthropic","options":{"baseURL":"https://relay.example/v1","apiKey":"sk-new"},"models":{"claude-opus-4.8":{"id":"claude-opus-4.8"}}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(status=200, json_data={"provider": {}})
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- provider = fake_session.patches[0]["json"]["provider"]["claude-relay"]
- self.assertEqual(
- provider["options"],
- {"baseURL": "https://relay.example/v1", "apiKey": "sk-new"},
- )
- self.assertIn("claude-opus-4.8", provider["models"])
-
- async def test_refresh_global_config_uses_auth_json_api_key_over_stale_live_key(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"openai":{"options":{"baseURL":"https://relay.example/v1"}}}}',
- encoding="utf-8",
- )
- auth_path = tmp_home / ".local" / "share" / "opencode" / "auth.json"
- auth_path.parent.mkdir(parents=True, exist_ok=True)
- auth_path.write_text(
- '{"openai":{"type":"api","key":"sk-new-auth"}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "openai": {
- "options": {
- "apiKey": "sk-old-live",
- "baseURL": "https://old.example/v1",
- }
- }
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertEqual(
- fake_session.patches[0]["json"]["provider"]["openai"]["options"],
- {"baseURL": "https://relay.example/v1", "apiKey": "sk-new-auth"},
- )
-
- async def test_refresh_global_config_drops_live_options_when_user_options_section_is_absent(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"deepseek":{"models":{"deepseek-v4-flash":{"id":"deepseek-v4-flash"}}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "deepseek": {
- "options": {
- "apiKey": "sk-stale",
- "baseURL": "https://stale.example",
- },
- "models": {"deepseek-v4-flash": {"id": "deepseek-v4-flash"}},
- }
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- provider = fake_session.patches[0]["json"]["provider"]["deepseek"]
- self.assertNotIn("options", provider)
- self.assertIn("deepseek-v4-flash", provider["models"])
-
- async def test_refresh_global_config_preserves_auth_key_when_only_models_configured(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"deepseek":{"models":{"deepseek-v4-flash":{"id":"deepseek-v4-flash"}}}}}',
- encoding="utf-8",
- )
- auth_path = tmp_home / ".local" / "share" / "opencode" / "auth.json"
- auth_path.parent.mkdir(parents=True, exist_ok=True)
- auth_path.write_text(
- '{"deepseek":{"type":"api","key":"sk-auth-json"}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "deepseek": {
- "options": {
- "apiKey": "sk-stale-live",
- "baseURL": "https://stale.example",
- },
- "models": {"deepseek-v4-flash": {"id": "deepseek-v4-flash"}},
- }
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- provider = fake_session.patches[0]["json"]["provider"]["deepseek"]
- self.assertEqual(provider["options"], {"apiKey": "sk-auth-json"})
- self.assertIn("deepseek-v4-flash", provider["models"])
-
- async def test_refresh_global_config_drops_deleted_user_models(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"deepseek":{"options":{"baseURL":"https://api.deepseek.com"},"models":{"keep-model":{"id":"keep-model"}}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "deepseek": {
- "options": {"baseURL": "https://api.deepseek.com"},
- "models": {
- "keep-model": {"id": "keep-model"},
- "deleted-model": {"id": "deleted-model"},
- },
- }
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertEqual(
- fake_session.patches[0]["json"]["provider"]["deepseek"]["models"],
- {"keep-model": {"id": "keep-model"}},
- )
-
- async def test_refresh_global_config_keeps_auth_backed_provider_absent_from_user_config(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"claude-relay":{"options":{"baseURL":"https://relay.example/v1"}}}}',
- encoding="utf-8",
- )
- auth_path = tmp_home / ".local" / "share" / "opencode" / "auth.json"
- auth_path.parent.mkdir(parents=True, exist_ok=True)
- auth_path.write_text(
- '{"openai":{"type":"oauth","refresh":"oauth-refresh"}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "openai": {"options": {"baseURL": "https://api.openai.com/v1"}},
- "claude-relay": {"options": {"baseURL": "https://old.example/v1"}},
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- self.assertEqual(
- set(fake_session.patches[0]["json"]["provider"].keys()),
- {"claude-relay", "openai"},
- )
- self.assertEqual(
- fake_session.patches[0]["json"]["provider"]["openai"]["options"],
- {"baseURL": "https://api.openai.com/v1"},
- )
- self.assertEqual(
- fake_session.patches[0]["json"]["provider"]["claude-relay"]["options"],
- {"baseURL": "https://relay.example/v1"},
- )
-
- async def test_refresh_global_config_preserves_local_provider_absent_from_user_config(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"claude-relay":{"options":{"baseURL":"https://relay.example/v1"}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "provider": {
- "ollama": {
- "name": "Ollama",
- "options": {"baseURL": "http://localhost:11434/v1"},
- "models": {"llama3.1": {"id": "llama3.1"}},
- },
- "claude-relay": {"options": {"baseURL": "https://old.example/v1"}},
- }
- },
- )
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
-
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
-
- self.assertTrue(refreshed)
- providers = fake_session.patches[0]["json"]["provider"]
- self.assertEqual(set(providers.keys()), {"claude-relay", "ollama"})
- self.assertEqual(
- providers["ollama"]["models"],
- {"llama3.1": {"id": "llama3.1"}},
- )
- self.assertEqual(
- providers["claude-relay"]["options"],
- {"baseURL": "https://relay.example/v1"},
- )
-
- async def test_refresh_global_config_drops_removed_top_level_settings(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(
- '{"provider":{"deepseek":{"options":{"baseURL":"https://api.deepseek.com"}}}}',
- encoding="utf-8",
- )
-
- class _SnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- return _FakeResponse(
- status=200,
- json_data={
- "permission": "allow",
- "model": "openai/gpt-5",
- "provider": {
- "deepseek": {"options": {"baseURL": "https://old.example"}}
- },
- },
- )
+ fake_session.gets[0]["headers"],
+ {"x-opencode-directory": "/tmp/%E5%B0%8F%E8%AF%B4"},
+ )
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _SnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ async def test_get_version_uses_health_endpoint(self):
+ class _HealthSession(_FakeSession):
+ def get(self, url, headers=None, timeout=None):
+ self.gets.append({"url": url, "headers": headers, "timeout": timeout})
+ return _FakeResponse(
+ status=200,
+ json_data={"healthy": True, "version": "1.18.5"},
+ )
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
+ fake_session = _HealthSession()
- self.assertTrue(refreshed)
- patched_config = fake_session.patches[0]["json"]
- self.assertNotIn("permission", patched_config)
- self.assertNotIn("model", patched_config)
- self.assertEqual(
- patched_config["provider"]["deepseek"]["options"],
- {"baseURL": "https://api.deepseek.com"},
- )
+ async def _fake_get_http_session():
+ return fake_session
- async def test_refresh_global_config_returns_false_when_global_endpoint_is_unavailable(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text('{"provider":{"deepseek":{"models":{}}}}', encoding="utf-8")
+ manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
- class _UnavailableSession(_FakeSession):
- def patch(self, url, json=None, headers=None):
- self.patches.append({"url": url, "json": json, "headers": headers})
- return _FakeResponse(status=404)
+ with patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()):
+ version = await manager.get_version()
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _UnavailableSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ self.assertEqual(version, "1.18.5")
+ self.assertEqual(fake_session.gets[0]["url"], "http://127.0.0.1:4096/global/health")
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
+ async def test_prompt_async_includes_tools_when_provided(self):
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
+ fake_session = _FakeSession()
- self.assertFalse(refreshed)
- self.assertEqual(
- [call["url"] for call in fake_session.patches],
- ["http://127.0.0.1:4096/global/config"],
- )
+ async def _fake_get_http_session():
+ return fake_session
- async def test_refresh_global_config_returns_false_when_snapshot_unavailable(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text('{"provider":{"deepseek":{"models":{}}}}', encoding="utf-8")
+ manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
- class _UnavailableSnapshotSession(_FakeSession):
- def get(self, url, headers=None, timeout=None):
- self.gets.append({"url": url, "headers": headers, "timeout": timeout})
- if url.endswith("/global/config"):
- return _FakeResponse(status=404)
- return _FakeResponse(status=200, json_data={"healthy": True})
+ await manager.prompt_async(
+ session_id="ses-1",
+ directory="/tmp/work",
+ text="hello",
+ tools={"question": False},
+ )
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _UnavailableSnapshotSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ self.assertEqual(len(fake_session.posts), 1)
+ body = fake_session.posts[0]["json"]
+ self.assertEqual(body["tools"], {"question": False})
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refreshed = await manager.refresh_global_config()
+ async def test_prompt_async_uses_opencode_native_attempt_part(self):
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
+ fake_session = _FakeSession()
- self.assertFalse(refreshed)
- self.assertEqual(fake_session.patches, [])
+ async def _fake_get_http_session():
+ return fake_session
- async def test_refresh_global_config_defers_when_request_active(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text('{"provider":{"deepseek":{"models":{}}}}', encoding="utf-8")
+ manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._active_requests = 1
+ await manager.prompt_async(
+ session_id="ses-1",
+ directory="/tmp/work",
+ text="hello",
+ attempt_id="atm_1234567890abcdef1234567890abcdef",
+ )
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- ):
- refreshed = await manager.refresh_global_config()
+ body = fake_session.posts[0]["json"]
+ self.assertNotIn("messageID", body)
+ self.assertEqual(
+ body["parts"],
+ [
+ {
+ "type": "text",
+ "text": "hello",
+ "id": "prt_1234567890abcdef1234567890abcdef",
+ }
+ ],
+ )
- self.assertFalse(refreshed)
- self.assertEqual(fake_session.patches, [])
+ def test_durable_attempt_maps_to_opencode_part_evidence(self):
+ attempt_id = delivery_store.new_attempt_id()
- async def test_refresh_global_config_blocks_new_request_scope_while_patching(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_home = Path(tmp_dir)
- config_path = tmp_home / ".config" / "opencode" / "opencode.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text('{"provider":{"deepseek":{"models":{}}}}', encoding="utf-8")
-
- class _BlockingResponse(_FakeResponse):
- def __init__(self, entered: asyncio.Event, release: asyncio.Event):
- super().__init__(status=200)
- self._entered = entered
- self._release = release
-
- async def __aenter__(self):
- self._entered.set()
- await self._release.wait()
- return self
-
- class _BlockingSession(_FakeSession):
- def __init__(self, entered: asyncio.Event, release: asyncio.Event):
- super().__init__()
- self._entered = entered
- self._release = release
-
- def patch(self, url, json=None, headers=None):
- self.patches.append({"url": url, "json": json, "headers": headers})
- return _BlockingResponse(self._entered, self._release)
-
- entered = asyncio.Event()
- release = asyncio.Event()
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _BlockingSession(entered, release)
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ self.assertRegex(attempt_id, r"^atm_[0-9a-f]{32}$")
+ self.assertEqual(
+ SERVER_MODULE.native_part_id_for_attempt(attempt_id),
+ f"prt_{attempt_id.removeprefix('atm_')}",
+ )
- with (
- patch("vibe.opencode_config.Path.home", return_value=tmp_home),
- patch.object(SERVER_MODULE.aiohttp, "ClientSession", return_value=fake_session),
- patch.object(SERVER_MODULE.aiohttp, "ClientTimeout", return_value=object()),
- ):
- refresh_task = asyncio.create_task(manager.refresh_global_config())
- await entered.wait()
- request_scope = manager._request_scope()
- request_task = asyncio.create_task(request_scope.__aenter__())
- await asyncio.sleep(0)
-
- self.assertFalse(request_task.done())
- release.set()
- self.assertTrue(await refresh_task)
- await request_task
- self.assertEqual(manager._active_requests, 1)
- await request_scope.__aexit__(None, None, None)
- self.assertEqual(manager._active_requests, 0)
-
- async def test_find_opencode_serve_pids_windows_uses_netstat_and_command_lookup(self):
- netstat_output = """
- TCP 127.0.0.1:4096 0.0.0.0:0 LISTENING 1234
- TCP 127.0.0.1:7777 0.0.0.0:0 LISTENING 7777
-"""
+ def test_unreleased_ordered_attempt_identity_is_rejected(self):
+ with self.assertRaises(ValueError):
+ SERVER_MODULE.native_part_id_for_attempt(
+ "atm_1234567890000123456789abcd"
+ )
- with patch.object(SERVER_MODULE.os, "name", "nt"):
- with patch.object(
- SERVER_MODULE.subprocess,
- "run",
- return_value=types.SimpleNamespace(stdout=netstat_output),
- ):
- with patch.object(
- SERVER_MODULE.runtime,
- "get_process_command",
- side_effect=lambda pid: "opencode serve --port=4096" if pid == 1234 else "python app.py",
- ):
- pids = OpenCodeServerManager._find_opencode_serve_pids(4096)
+ async def test_prompt_async_exposes_definitive_http_rejection(self):
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
+ fake_session = _FakeSession()
- self.assertEqual(pids, [1234])
+ def _post(url, json=None, headers=None):
+ fake_session.posts.append({"url": url, "json": json, "headers": headers})
+ return _FakeResponse(status=409, text="active input refused")
- async def test_restart_for_auth_refresh_stops_known_server_and_clears_state(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
- manager._http_session = fake_session
- manager._http_session_loop = object()
- manager._process = object()
- manager._base_url = "http://127.0.0.1:4096"
- manager._read_pid_file = lambda: {"pid": 321} # type: ignore[method-assign]
- manager._pid_exists = lambda pid: pid == 321 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- terminated = []
- manager._terminate_pid = lambda pid, reason: terminated.append((pid, reason)) or _async_none() # type: ignore[method-assign]
- manager._clear_pid_file = lambda: terminated.append(("cleared", "")) # type: ignore[method-assign]
+ fake_session.post = _post
- await manager.restart_for_auth_refresh()
+ async def _fake_get_http_session():
+ return fake_session
- self.assertTrue(fake_session.closed)
- self.assertIn((321, "auth refresh"), terminated)
- self.assertIn(("cleared", ""), terminated)
- self.assertIsNone(manager._process)
- self.assertIsNone(manager._base_url)
+ manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
- async def test_restart_for_auth_refresh_trusts_pid_file_when_command_lookup_unavailable(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
- manager._http_session = fake_session
- manager._http_session_loop = object()
- manager._process = object()
- manager._base_url = "http://127.0.0.1:4096"
- manager._read_pid_file = lambda: {"pid": 654, "port": 4096} # type: ignore[method-assign]
- manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: None # type: ignore[method-assign]
- manager._pid_owns_listening_port = lambda pid, port: pid == 654 and port == 4096 # type: ignore[method-assign]
- terminated = []
- manager._terminate_pid = lambda pid, reason: terminated.append((pid, reason)) or _async_none() # type: ignore[method-assign]
- manager._clear_pid_file = lambda: terminated.append(("cleared", "")) # type: ignore[method-assign]
-
- await manager.restart_for_auth_refresh()
+ with self.assertRaises(SERVER_MODULE.OpenCodePromptRejectedError) as raised:
+ await manager.prompt_async(
+ session_id="ses-1",
+ directory="/tmp/work",
+ text="hello",
+ )
- self.assertTrue(fake_session.closed)
- self.assertIn((654, "auth refresh"), terminated)
- self.assertIn(("cleared", ""), terminated)
+ self.assertEqual(raised.exception.status, 409)
+ self.assertEqual(raised.exception.response_text, "active input refused")
- async def test_restart_for_auth_refresh_does_not_trust_pid_file_without_port_ownership(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ async def test_prompt_async_omits_default_variant(self):
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _FakeSession()
- manager._http_session = fake_session
- manager._http_session_loop = object()
- manager._process = object()
- manager._base_url = "http://127.0.0.1:4096"
- manager._read_pid_file = lambda: {"pid": 654, "port": 4096} # type: ignore[method-assign]
- manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: None # type: ignore[method-assign]
- manager._pid_owns_listening_port = lambda pid, port: False # type: ignore[method-assign]
- manager._find_opencode_serve_pids = lambda port: [] # type: ignore[method-assign]
- terminated = []
- manager._terminate_pid = lambda pid, reason: terminated.append((pid, reason)) or _async_none() # type: ignore[method-assign]
- manager._clear_pid_file = lambda: terminated.append(("cleared", "")) # type: ignore[method-assign]
-
- await manager.restart_for_auth_refresh()
- self.assertTrue(fake_session.closed)
- self.assertNotIn((654, "auth refresh"), terminated)
- self.assertEqual(terminated, [("cleared", "")])
+ async def _fake_get_http_session():
+ return fake_session
- async def test_restart_for_auth_refresh_defers_while_requests_are_active(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- fake_session = _FakeSession()
- manager._http_session = fake_session
- manager._http_session_loop = object()
- manager._process = object()
- manager._base_url = "http://127.0.0.1:4096"
- manager._active_requests = 2
- terminated = []
- manager._terminate_pid = lambda pid, reason: terminated.append((pid, reason)) or _async_none() # type: ignore[method-assign]
- manager._clear_pid_file = lambda: terminated.append(("cleared", "")) # type: ignore[method-assign]
+ manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
- await manager.restart_for_auth_refresh()
+ await manager.prompt_async(
+ session_id="ses-1",
+ directory="/tmp/work",
+ text="hello",
+ reasoning_effort="default",
+ )
- self.assertFalse(fake_session.closed)
- self.assertEqual(terminated, [])
- self.assertTrue(manager._auth_refresh_pending)
- self.assertIsNotNone(manager._process)
- self.assertEqual(manager._base_url, "http://127.0.0.1:4096")
+ self.assertEqual(len(fake_session.posts), 1)
+ body = fake_session.posts[0]["json"]
+ self.assertNotIn("variant", body)
- async def test_restart_for_auth_refresh_defers_while_runs_are_active(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ async def test_fork_session_sends_message_id_when_provided(self):
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _FakeSession()
- manager._http_session = fake_session
- manager._http_session_loop = object()
- manager._process = object()
- manager._base_url = "http://127.0.0.1:4096"
- manager._active_run_sessions.add("sess-1")
- terminated = []
- manager._terminate_pid = lambda pid, reason: terminated.append((pid, reason)) or _async_none() # type: ignore[method-assign]
- manager._clear_pid_file = lambda: terminated.append(("cleared", "")) # type: ignore[method-assign]
- await manager.restart_for_auth_refresh()
+ def _post(url, json=None, headers=None):
+ fake_session.posts.append({"url": url, "json": json, "headers": headers})
+ return _FakeResponse(status=200, json_data={"id": "oc-fork"})
- self.assertFalse(fake_session.closed)
- self.assertEqual(terminated, [])
- self.assertTrue(manager._auth_refresh_pending)
- self.assertIsNotNone(manager._process)
- self.assertEqual(manager._base_url, "http://127.0.0.1:4096")
-
- async def test_restart_for_auth_refresh_force_clears_stale_activity(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._active_requests = 2
- manager._active_run_sessions.add("sess-stale")
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
-
- await manager.restart_for_auth_refresh(force=True)
-
- self.assertEqual(manager._active_requests, 2)
- self.assertEqual(manager._active_run_sessions, set())
- manager._restart_for_auth_refresh_locked.assert_awaited_once()
-
- def test_runtime_has_active_turns_reads_adopted_pid_state(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": 321,
- "port": 4096,
- "active_run_sessions": ["sess-live"],
- }
- manager._pid_exists = lambda pid: pid == 321 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
+ fake_session.post = _post
- self.assertTrue(manager.runtime_has_active_turns())
+ async def _fake_get_http_session():
+ return fake_session
- def test_runtime_ignores_active_runs_from_reused_pid(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": 321,
- "port": 4096,
- "active_run_sessions": ["sess-stale"],
- }
- manager._pid_exists = lambda pid: pid == 321 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "python unrelated.py" # type: ignore[method-assign]
-
- self.assertFalse(manager.runtime_has_active_turns())
-
- def test_terminate_sync_falls_back_to_tracked_process_without_pid_file(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._process = types.SimpleNamespace(pid=654, returncode=None)
- manager._read_pid_file = lambda: None # type: ignore[method-assign]
- manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]
-
- manager.terminate_sync()
-
- manager._terminate_pid_tree_sync.assert_called_once_with(654)
- self.assertIsNone(manager._process)
-
- def test_terminate_sync_does_not_kill_reused_tracked_pid(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._process = types.SimpleNamespace(pid=654, returncode=None)
- manager._read_pid_file = lambda: None # type: ignore[method-assign]
- manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "python unrelated.py" # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]
-
- manager.terminate_sync()
-
- manager._terminate_pid_tree_sync.assert_not_called()
- self.assertIsNone(manager._process)
-
- def test_terminate_sync_trusts_pid_file_port_owner_without_command(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = lambda: {"pid": 654, "port": 4096} # type: ignore[method-assign]
- manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: None # type: ignore[method-assign]
- manager._pid_owns_listening_port = lambda pid, port: pid == 654 and port == 4096 # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]
-
- manager.terminate_sync()
-
- manager._terminate_pid_tree_sync.assert_called_once_with(654)
-
- async def test_retire_adopted_server_requires_command_or_port_proof(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = Mock(return_value={"pid": 654, "port": 4096, "process_created_at": 1000.0}) # type: ignore[method-assign]
- manager._pid_exists = Mock(side_effect=[True, True, False]) # type: ignore[method-assign]
- manager._get_pid_command = Mock(return_value="opencode serve --port=4096") # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
-
- with patch.object(SERVER_MODULE.runtime, "process_create_time", return_value=1000.0):
- await manager.retire_for_native_migration()
-
- manager._terminate_pid_tree_sync.assert_called_once_with(654)
- manager._clear_pid_file.assert_called_once()
- self.assertIsNone(manager._base_url)
-
- async def test_retire_adopted_server_refuses_reused_pid(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = Mock(return_value={"pid": 654, "port": 4096}) # type: ignore[method-assign]
- manager._pid_exists = Mock(return_value=True) # type: ignore[method-assign]
- manager._get_pid_command = Mock(return_value="python unrelated.py") # type: ignore[method-assign]
- manager._pid_owns_listening_port = Mock(return_value=False) # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
-
- with self.assertRaisesRegex(RuntimeError, "ownership cannot be proven"):
- await manager.retire_for_native_migration()
-
- manager._terminate_pid_tree_sync.assert_not_called()
- manager._clear_pid_file.assert_not_called()
-
- async def test_retire_adopted_server_uses_port_owner_when_command_unavailable(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = Mock(return_value={"pid": 654, "port": 4096, "process_created_at": 1000.0}) # type: ignore[method-assign]
- manager._pid_exists = Mock(side_effect=[True, True, False]) # type: ignore[method-assign]
- manager._get_pid_command = Mock(return_value=None) # type: ignore[method-assign]
- manager._pid_owns_listening_port = Mock(return_value=True) # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]
- manager._clear_pid_file = Mock() # type: ignore[method-assign]
-
- with patch.object(SERVER_MODULE.runtime, "process_create_time", return_value=1000.0):
- await manager.retire_for_native_migration()
-
- self.assertEqual(manager._pid_owns_listening_port.call_count, 2)
- manager._pid_owns_listening_port.assert_called_with(654, 4096)
- manager._terminate_pid_tree_sync.assert_called_once_with(654)
-
- async def test_retire_adopted_server_refuses_reused_pid_even_when_command_matches(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = Mock(return_value={
- "pid": 654, "port": 4096, "process_created_at": 1000.0
- }) # type: ignore[method-assign]
- manager._pid_exists = Mock(return_value=True) # type: ignore[method-assign]
- manager._get_pid_command = Mock(return_value="opencode serve --port=4096") # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock() # type: ignore[method-assign]
- retire = Mock(return_value=True)
- manager.set_runtime_activation_retire(retire)
-
- with patch.object(SERVER_MODULE.runtime, "process_create_time", return_value=2000.0):
- with self.assertRaisesRegex(RuntimeError, "ownership cannot be proven"):
- await manager.retire_for_native_migration()
-
- manager._terminate_pid_tree_sync.assert_not_called()
- retire.assert_not_called()
-
- async def test_retire_adopted_server_refuses_legacy_pid_file_without_birth_identity(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = Mock(return_value={"pid": 654, "port": 4096}) # type: ignore[method-assign]
- manager._pid_exists = Mock(return_value=True) # type: ignore[method-assign]
- manager._get_pid_command = Mock(return_value="opencode serve --port=4096") # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock() # type: ignore[method-assign]
-
- with self.assertRaisesRegex(RuntimeError, "ownership cannot be proven"):
- await manager.retire_for_native_migration()
-
- manager._terminate_pid_tree_sync.assert_not_called()
-
- async def test_retire_adopted_server_refuses_identity_change_before_signal(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._read_pid_file = Mock(return_value={
- "pid": 654, "port": 4096, "process_created_at": 1000.0
- }) # type: ignore[method-assign]
- manager._pid_exists = Mock(side_effect=[True, True]) # type: ignore[method-assign]
- manager._get_pid_command = Mock(return_value="opencode serve --port=4096") # type: ignore[method-assign]
- manager._terminate_pid_tree_sync = Mock() # type: ignore[method-assign]
-
- with patch.object(SERVER_MODULE.runtime, "process_create_time", side_effect=[1000.0, 2000.0]):
- with self.assertRaisesRegex(RuntimeError, "ownership cannot be proven"):
- await manager.retire_for_native_migration()
-
- manager._terminate_pid_tree_sync.assert_not_called()
-
- def test_observed_adopted_server_reports_only_the_original_generation_exit(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- info = {"pid": 654, "port": 4096, "started_at": 1.0}
- manager._pid_exists = Mock(return_value=True) # type: ignore[method-assign]
-
- with patch.object(SERVER_MODULE.runtime, "process_create_time", side_effect=[1000.0, 1000.0, 2000.0]):
- manager._observe_runtime_generation(info)
- self.assertIsNone(manager.observed_runtime_exit_pid())
- self.assertEqual(manager.observed_runtime_exit_pid(), 654)
-
- async def test_request_scope_does_not_restart_pending_auth_refresh_while_run_active(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._auth_refresh_pending = True
- manager._active_run_sessions.add("sess-1")
- restarted = []
- manager._restart_for_auth_refresh_locked = lambda: restarted.append(True) or _async_none() # type: ignore[method-assign]
-
- async with manager._request_scope():
- self.assertEqual(manager._active_requests, 1)
-
- self.assertEqual(restarted, [])
- self.assertEqual(manager._active_requests, 0)
- self.assertTrue(manager._auth_refresh_pending)
-
- async def test_reload_runtime_config_updates_singleton_binary(self):
- manager = OpenCodeServerManager(binary="/old/opencode", port=4096, request_timeout_seconds=60)
-
- await manager.reload_runtime_config(
- binary="/new/opencode",
- port=4100,
- request_timeout_seconds=15,
- )
+ manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
- self.assertEqual(manager.binary, "/new/opencode")
- self.assertEqual(manager.port, 4100)
- self.assertEqual(manager.request_timeout_seconds, 15)
+ result = await manager.fork_session("oc-source", directory="/tmp/work", message_id="oc-msg-prev")
- def test_apply_resource_governance_moves_managed_server_pid(self):
- calls = []
- governor = types.SimpleNamespace(
- apply_to_pid=lambda pid, label="agent": calls.append((pid, label)) or True
+ self.assertEqual(result, {"id": "oc-fork"})
+ self.assertEqual(len(fake_session.posts), 1)
+ self.assertEqual(fake_session.posts[0]["json"], {"messageID": "oc-msg-prev"})
+ self.assertEqual(
+ fake_session.posts[0]["headers"],
+ {"x-opencode-directory": "/tmp/work"},
)
- manager = OpenCodeServerManager(binary="opencode", port=4096, resource_governor=governor)
-
- manager._apply_resource_governance(1357)
- self.assertEqual(calls, [(1357, "opencode serve")])
+ async def test_load_opencode_user_config_supports_jsonc(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tmp_home = Path(tmp_dir)
+ config_path = tmp_home / ".config" / "opencode" / "opencode.json"
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(
+ """{
+ // Preserve defaults from JSONC config.
+ "model": "openai/gpt-5",
+ "reasoningEffort": "high",
+}
+""",
+ encoding="utf-8",
+ )
- async def test_get_instance_attaches_resource_governor_when_existing_params_differ(self):
- first = OpenCodeServerManager(binary="/old/opencode", port=4096, request_timeout_seconds=60)
- governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- previous = OpenCodeServerManager._instance
- OpenCodeServerManager._instance = first
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
+ with patch("vibe.opencode_config.Path.home", return_value=tmp_home):
+ config = manager._load_opencode_user_config()
- try:
- manager = await OpenCodeServerManager.get_instance(
- binary="/new/opencode",
- port=4100,
- request_timeout_seconds=15,
- resource_governor=governor,
- )
- finally:
- OpenCodeServerManager._instance = previous
-
- self.assertIs(manager, first)
- self.assertIs(first.resource_governor, governor)
- self.assertEqual(first.binary, "/old/opencode")
- self.assertEqual(first.port, 4096)
-
- async def test_get_instance_preserves_controller_owned_resource_governor(self):
- from core.resource_governance import mark_controller_resource_governor
-
- controller_governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- ui_governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- mark_controller_resource_governor(controller_governor)
- first = OpenCodeServerManager(
- binary="opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=controller_governor,
- )
- previous = OpenCodeServerManager._instance
- OpenCodeServerManager._instance = first
-
- try:
- manager = await OpenCodeServerManager.get_instance(
- binary="opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=ui_governor,
- )
- finally:
- OpenCodeServerManager._instance = previous
-
- self.assertIs(manager, first)
- self.assertIs(first.resource_governor, controller_governor)
-
- async def test_get_instance_allows_controller_resource_governor_to_take_over(self):
- from core.resource_governance import mark_controller_resource_governor
-
- ui_governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- controller_governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- mark_controller_resource_governor(controller_governor)
- first = OpenCodeServerManager(
- binary="opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=ui_governor,
- )
- previous = OpenCodeServerManager._instance
- OpenCodeServerManager._instance = first
-
- try:
- manager = await OpenCodeServerManager.get_instance(
- binary="opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=controller_governor,
- )
- finally:
- OpenCodeServerManager._instance = previous
-
- self.assertIs(manager, first)
- self.assertIs(first.resource_governor, controller_governor)
-
- async def test_get_instance_if_managed_server_exists_allows_controller_governor_takeover(self):
- from core.resource_governance import mark_controller_resource_governor
-
- ui_governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- controller_governor = types.SimpleNamespace(apply_to_pid=lambda pid, label="agent": True)
- mark_controller_resource_governor(controller_governor)
- first = OpenCodeServerManager(
- binary="opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=ui_governor,
- )
- previous = OpenCodeServerManager._instance
- OpenCodeServerManager._instance = first
-
- try:
- manager = await OpenCodeServerManager.get_instance_if_managed_server_exists(
- binary="opencode",
- port=4096,
- request_timeout_seconds=60,
- resource_governor=controller_governor,
+ self.assertEqual(
+ config,
+ {
+ "model": "openai/gpt-5",
+ "reasoningEffort": "high",
+ },
)
- finally:
- OpenCodeServerManager._instance = previous
-
- self.assertIs(manager, first)
- self.assertIs(first.resource_governor, controller_governor)
-
- async def test_pending_detach_defers_runtime_reload_until_old_port_cleanup(self):
- manager = OpenCodeServerManager(binary="/old/opencode", port=4096, request_timeout_seconds=60)
- terminated = []
- manager._active_run_sessions.add("sess-1")
- manager._read_pid_file = lambda: {"pid": 654, "port": 4096} # type: ignore[method-assign]
- manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]
- manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]
- manager._terminate_pid = lambda pid, reason: terminated.append((pid, reason)) or _async_none() # type: ignore[method-assign]
-
- await manager.detach_after_deferred_refresh()
- await manager.reload_runtime_config(
- binary="/new/opencode",
- port=4100,
- request_timeout_seconds=15,
- )
- self.assertEqual(manager.binary, "/old/opencode")
- self.assertEqual(manager.port, 4096)
- self.assertEqual(manager.request_timeout_seconds, 60)
+ async def test_explicit_subagent_model_is_independent_of_native_defaults(self):
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
+ for native_model in (None, "openai/native-one", "anthropic/native-two"):
+ for declared in (None, "", " ", {"id": "invalid"}, " provider/reviewer "):
+ with self.subTest(native_model=native_model, declared=declared):
+ config = {
+ "model": native_model,
+ "agent": {
+ "build": {"model": native_model},
+ "reviewer": {"model": declared},
+ },
+ }
+ with patch.object(manager, "_load_opencode_user_config", return_value=config):
+ expected = (declared.strip() or None) if isinstance(declared, str) else None
+ self.assertEqual(manager.get_explicit_subagent_model("reviewer"), expected)
+ self.assertIsNone(manager.get_explicit_subagent_model("missing"))
+ self.assertIsNone(manager.get_explicit_subagent_model(""))
+
+ async def test_agent_reasoning_effort_reads_back_every_savable_variant(self):
+ # A tier the save path can write must never be dropped here as unknown
+ # (#1840: catalog-declared `ultra` was rejected by both halves).
+ for effort in OPENCODE_REASONING_VARIANTS:
+ with self.subTest(effort=effort):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tmp_home = Path(tmp_dir)
+ config_path = tmp_home / ".config" / "opencode" / "opencode.json"
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(
+ json.dumps({"reasoningEffort": effort}),
+ encoding="utf-8",
+ )
- manager._active_run_sessions.clear()
- await manager._restart_for_auth_refresh_locked()
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
+ with patch("vibe.opencode_config.Path.home", return_value=tmp_home):
+ resolved = manager.get_agent_reasoning_effort_from_config(None)
- self.assertEqual(terminated, [(654, "auth refresh")])
- self.assertFalse(manager._auth_refresh_pending)
- self.assertIsNone(manager._auth_refresh_pending_port)
- self.assertEqual(manager.binary, "/new/opencode")
- self.assertEqual(manager.port, 4100)
- self.assertEqual(manager.request_timeout_seconds, 15)
- self.assertIsNone(manager._pending_runtime_config)
+ self.assertEqual(resolved, effort)
async def test_close_http_session_skips_session_owned_by_another_loop(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _FakeSession()
manager._http_session = fake_session
manager._http_session_loop = object()
@@ -2638,7 +647,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
self.assertIs(manager._http_session, fake_session)
async def test_close_http_session_closes_session_for_matching_loop(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _FakeSession()
current_loop = asyncio.get_running_loop()
manager._http_session = fake_session
@@ -2649,43 +658,17 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(fake_session.closed)
self.assertIsNone(manager._http_session)
- async def test_get_instance_if_managed_server_exists_rejects_reused_pid(self):
- with tempfile.TemporaryDirectory() as tmp_dir:
- logs_dir = Path(tmp_dir)
- pid_file = logs_dir / "opencode_server.json"
- pid_file.write_text('{"pid": 654, "port": 4096}', encoding="utf-8")
-
- previous = OpenCodeServerManager._instance
- OpenCodeServerManager._instance = None
- try:
- with (
- patch.object(SERVER_MODULE.paths, "get_logs_dir", return_value=logs_dir),
- patch.object(SERVER_MODULE.runtime, "pid_alive", return_value=True),
- patch.object(SERVER_MODULE.runtime, "get_process_command", return_value="python app.py"),
- ):
- manager = await OpenCodeServerManager.get_instance_if_managed_server_exists(
- binary="opencode",
- port=4096,
- )
- finally:
- OpenCodeServerManager._instance = previous
-
- self.assertIsNone(manager)
-
async def test_set_api_key_auth_uses_official_auth_endpoint(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _FakeSession()
async def _fake_get_http_session():
return fake_session
manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
- manager.ensure_running = AsyncMock() # type: ignore[method-assign]
- manager._base_url = "http://127.0.0.1:4096"
await manager.set_api_key_auth("opencode", "sk-test-key")
- manager.ensure_running.assert_awaited_once()
self.assertEqual(
fake_session.puts,
[
@@ -2719,7 +702,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
+ f"ERROR service=llm session.id=ses_test error={SERVER_MODULE.json.dumps(line_payload)} stream error\n",
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]):
summary = manager._recent_session_error_sync("ses_test")
@@ -2749,7 +732,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
f"ERROR 2026-06-19T04:10:03 +1ms service=llm session.id=ses_test error={SERVER_MODULE.json.dumps(line_payload)} stream error\n",
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]):
summary = manager._recent_session_error_sync("ses_test")
@@ -2786,7 +769,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
f"session.id=ses_test error={SERVER_MODULE.json.dumps(line_payload)} stream error\n",
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]):
summary = manager._recent_session_error_sync("ses_test")
@@ -2810,7 +793,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
"utf-8"
)
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with (
patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]),
@@ -2846,7 +829,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
f"ERROR 2026-06-19T04:10:03 +1ms service=llm session.id=ses_test error={SERVER_MODULE.json.dumps(current_payload)} stream error\n",
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]):
summary = manager._recent_session_error_sync(
@@ -2874,7 +857,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
f"ERROR 2026-06-19T04:09:49 +1ms service=llm session.id=ses_test error={SERVER_MODULE.json.dumps(payload)} stream error\n",
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]):
summary = manager._recent_session_error_sync(
@@ -2897,7 +880,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
f"ERROR 2026-06-19T04:09:59 +1ms service=llm session.id=ses_test error={SERVER_MODULE.json.dumps(payload)} stream error\n",
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]):
summary = manager._recent_session_error_sync(
@@ -2920,7 +903,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
f"ERROR 2026-06-19T04:10:03 +1ms service=llm session.id=ses_test error={SERVER_MODULE.json.dumps(payload)} stream error\n",
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
with patch.object(manager, "_opencode_log_dirs", return_value=[log_dir]):
summary = manager._recent_session_error_sync(
@@ -2932,7 +915,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("current-secret", summary or "")
async def test_prompt_async_records_prompt_start_time_for_log_correlation(self):
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
fake_session = _FakeSession()
async def _fake_get_http_session():
@@ -2974,7 +957,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
),
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
class _UrlOpen:
def __call__(self, request, timeout=None):
@@ -3021,7 +1004,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
),
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
def _raise_http_error(request, timeout=None):
response = io.BytesIO(
@@ -3072,7 +1055,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
),
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
def _raise_url_error(request, timeout=None):
raise SERVER_MODULE.urllib.error.URLError("timed out with api_key=sk-url-secret")
@@ -3099,7 +1082,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
}
}
- detail = OpenCodeServerManager._diagnostic_payload_message(payload)
+ detail = OpenCodeServerClient._diagnostic_payload_message(payload)
self.assertIn("Bearer [redacted]", detail)
self.assertIn("https://relay.example/messages", detail)
@@ -3129,7 +1112,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
encoding="utf-8",
)
auth_path.write_text('{"glm":{"type":"api","key":"sk-auth-json"}}', encoding="utf-8")
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
class _UrlOpen:
def __call__(self, request, timeout=None):
@@ -3167,7 +1150,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
),
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
class _UrlOpen:
def __call__(self, request, timeout=None):
@@ -3206,7 +1189,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
),
encoding="utf-8",
)
- manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager = OpenCodeServerClient("http://127.0.0.1:4096")
calls = []
def _unexpected_urlopen(request, timeout=None):
@@ -3275,7 +1258,7 @@ def test_stopping_the_server_stops_tool_commands_in_their_own_session(tmp_path):
# Reaps the server the moment it exits, as Avibe's asyncio child watcher does.
threading.Thread(target=server.wait, daemon=True).start()
- assert OpenCodeServerManager._terminate_pid_tree_sync(server.pid, timeout=2.0)
+ assert SERVER_MODULE.terminate_pid_tree_sync(server.pid, timeout=2.0)
assert _exited(tool)
assert _running_group_members(tool_pid) == []
@@ -3304,8 +1287,8 @@ worker = subprocess.Popen(["/bin/sh", "-c", "while :; do sleep 1; done", "tool",
print(worker.pid, flush=True)
stopper = (
"import sys\\n"
- "from modules.agents.opencode.server import OpenCodeServerManager\\n"
- "stopped = OpenCodeServerManager._terminate_pid_tree_sync(int(sys.argv[1]), timeout=2.0)\\n"
+ "from modules.agents.opencode.server import terminate_pid_tree_sync\\n"
+ "stopped = terminate_pid_tree_sync(int(sys.argv[1]), timeout=2.0)\\n"
"open(sys.argv[2], 'w').write(str(stopped))\\n"
)
subprocess.Popen([sys.executable, "-c", stopper, str(os.getpid()), done, marker], start_new_session=True)
@@ -3347,181 +1330,5 @@ def test_a_stop_run_from_inside_the_tree_survives_to_finish_it(tmp_path):
server.stdout.close()
-def test_mh_runtime_002_matching_overlay_does_not_wait_for_an_unrelated_active_run():
- """MH-RUNTIME-002: unchanged direct mode cannot head-of-line block another Session."""
-
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._active_run_sessions.add("sess-unrelated")
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": 321,
- "port": 4096,
- "active_run_sessions": ["sess-unrelated"],
- }
- manager._pid_file_references_current_server = Mock(return_value=True) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
-
- reservation = asyncio.run(
- asyncio.wait_for(
- manager.configure_model_hub_overlay(None),
- timeout=0.1,
- )
- )
- asyncio.run(manager.release_model_hub_overlay_reservation(reservation))
-
- assert manager._model_hub_overlay_path is None
- assert manager._model_hub_overlay_hash is None
- assert manager._model_hub_overlay_content is None
- manager._is_healthy.assert_not_awaited()
- manager._restart_for_auth_refresh_locked.assert_not_awaited()
-
-
-def test_changed_overlay_still_waits_for_active_run_before_restart():
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._model_hub_overlay_path = "/tmp/old-overlay.json"
- manager._model_hub_overlay_hash = "old-hash"
- manager._active_run_sessions.add("sess-active")
- manager._read_pid_file = lambda: {} # type: ignore[method-assign]
- manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")
-
- async def exercise():
- configuring = asyncio.create_task(manager.configure_model_hub_overlay(overlay))
- await asyncio.sleep(0.01)
- assert not configuring.done()
- manager._active_run_sessions.clear()
- reservation = await asyncio.wait_for(configuring, timeout=0.2)
- await manager.release_model_hub_overlay_reservation(reservation)
-
- asyncio.run(exercise())
-
- assert manager._model_hub_overlay_path == str(overlay.path)
- assert manager._model_hub_overlay_hash == overlay.content_hash
- manager._restart_for_auth_refresh_locked.assert_awaited_once()
-
-
-def test_empty_model_hub_overlay_uses_the_normal_change_path():
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._model_hub_overlay_path = "/tmp/old-overlay.json"
- manager._model_hub_overlay_hash = "old-hash"
- manager._read_pid_file = lambda: {} # type: ignore[method-assign]
- manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- overlay = _model_hub_overlay("/tmp/empty-overlay.json", None)
-
- reservation = asyncio.run(manager.configure_model_hub_overlay(overlay))
- asyncio.run(manager.release_model_hub_overlay_reservation(reservation))
-
- assert json.loads(overlay.content)["provider"]["avibe-openai"]["models"] == {}
- assert manager._model_hub_overlay_path == str(overlay.path)
- assert manager._model_hub_overlay_hash == overlay.content_hash
- manager._restart_for_auth_refresh_locked.assert_awaited_once_with(
- native_turns_drained=True,
- )
-
-
-def test_changed_overlay_passes_completed_persisted_drain_to_retirement():
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._model_hub_overlay_path = "/tmp/old-overlay.json"
- manager._model_hub_overlay_hash = "old-hash"
- manager._model_hub_overlay_drain_timeout_seconds = 0
- manager._read_pid_file = lambda: { # type: ignore[method-assign]
- "pid": 321,
- "port": 4096,
- "active_run_sessions": ["sess-stale"],
- }
- manager._pid_file_references_current_server = Mock(return_value=True) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")
-
- reservation = asyncio.run(manager.configure_model_hub_overlay(overlay))
- asyncio.run(manager.release_model_hub_overlay_reservation(reservation))
-
- manager._restart_for_auth_refresh_locked.assert_awaited_once_with(
- native_turns_drained=True,
- )
-
-
-def test_mh_runtime_003_pending_overlay_transition_blocks_new_turns_on_the_old_overlay():
- """MH-RUNTIME-003: a queued change drains without old-overlay starvation."""
-
- old_overlay = _model_hub_overlay("/tmp/old-overlay.json", "old-model")
- new_overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._model_hub_overlay_path = "/tmp/old-overlay.json"
- manager._model_hub_overlay_hash = old_overlay.content_hash
- manager._active_run_sessions.add("sess-active")
- manager._read_pid_file = lambda: {} # type: ignore[method-assign]
- manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- async def exercise():
- configuring = asyncio.create_task(
- manager.configure_model_hub_overlay(new_overlay)
- )
- await asyncio.sleep(0.01)
- matching_old_turn = asyncio.create_task(
- manager.configure_model_hub_overlay(old_overlay)
- )
- await asyncio.sleep(0.01)
- assert not matching_old_turn.done()
- matching_old_turn.cancel()
- await asyncio.gather(matching_old_turn, return_exceptions=True)
- manager._active_run_sessions.clear()
- reservation = await asyncio.wait_for(configuring, timeout=0.2)
- await manager.release_model_hub_overlay_reservation(reservation)
-
- asyncio.run(exercise())
-
- assert manager._model_hub_overlay_path == str(new_overlay.path)
- assert manager._model_hub_overlay_hash == new_overlay.content_hash
- assert manager._model_hub_overlay_transition is None
- manager._restart_for_auth_refresh_locked.assert_awaited_once()
-
-
-def test_mh_runtime_004_overlay_reservation_promotes_atomically_to_active_run():
- """MH-RUNTIME-004: selection stays leased through active-run registration."""
-
- old_overlay = _model_hub_overlay("/tmp/old-overlay.json", "old-model")
- new_overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")
- manager = OpenCodeServerManager(binary="opencode", port=4096)
- manager._model_hub_overlay_path = "/tmp/old-overlay.json"
- manager._model_hub_overlay_hash = old_overlay.content_hash
- manager._read_pid_file = lambda: {} # type: ignore[method-assign]
- manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]
- manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
- manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
- async def exercise():
- reservation = await manager.configure_model_hub_overlay(new_overlay)
- reverting = asyncio.create_task(
- manager.configure_model_hub_overlay(old_overlay)
- )
- await asyncio.sleep(0.01)
- assert not reverting.done()
-
- await manager.mark_run_active(
- "sess-new",
- overlay_reservation=reservation,
- )
- await asyncio.sleep(0.01)
- assert not reverting.done()
-
- await manager.mark_run_inactive("sess-new")
- old_reservation = await asyncio.wait_for(reverting, timeout=0.2)
- await manager.release_model_hub_overlay_reservation(old_reservation)
-
- asyncio.run(exercise())
-
- assert manager._model_hub_overlay_path == str(old_overlay.path)
- assert manager._model_hub_overlay_hash == old_overlay.content_hash
- assert manager._model_hub_overlay_reservations == {}
- assert manager._active_run_sessions == set()
- assert manager._restart_for_auth_refresh_locked.await_count == 2
-
-
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_opencode_steer_superseded_reply.py b/tests/test_opencode_steer_superseded_reply.py
index 1dd099981..05fbaa947 100644
--- a/tests/test_opencode_steer_superseded_reply.py
+++ b/tests/test_opencode_steer_superseded_reply.py
@@ -111,7 +111,6 @@ async def _live_poll(messages, agent):
async def _restored_poll(messages, agent, results, *, emitted=()):
server = _server(messages)
- agent._get_server = AsyncMock(return_value=server)
poll = ActivePollInfo(
opencode_session_id="native-session",
base_session_id="base",
@@ -124,7 +123,7 @@ async def _restored_poll(messages, agent, results, *, emitted=()):
emitted_assistant_messages=list(emitted),
prompt_started_at=time.time(),
)
- assert await asyncio.wait_for(OpenCodePollLoop(agent).run_restored_poll_loop(poll), timeout=2)
+ assert await asyncio.wait_for(OpenCodePollLoop(agent).run_restored_poll_loop(poll, server), timeout=2)
assert len(results) == 1
return results[0]
diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.py
index 411a568fb..3d8c5a5a0 100644
--- a/tests/test_opencode_stop_receipt.py
+++ b/tests/test_opencode_stop_receipt.py
@@ -29,12 +29,14 @@ from modules.agents.opencode.agent import OpenCodeAgent
from modules.agents.opencode.poll_loop import OpenCodePollLoop
from modules.agents.opencode.session import OpenCodeSessionManager
from modules.im.base import MessageContext
+from tests.opencode_generation_fakes import serve_opencode_agent
def _agent():
agent = object.__new__(OpenCodeAgent)
agent._active_requests = {}
agent._user_stopped_sessions = set()
+ agent._session_generations = {}
session_lock = asyncio.Lock()
agent._session_manager = SimpleNamespace(
get_request_session=lambda _base: None,
@@ -230,25 +232,14 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(result)
self.assertEqual(agent._user_stopped_sessions, set())
- async def test_prestart_cancellation_releases_overlay_and_stamps_stop_receipt(self):
+ async def test_prestart_cancellation_stamps_stop_receipt(self):
agent = _agent()
request = _request()
- reservation = object()
- server = SimpleNamespace(
- release_model_hub_overlay_reservation=AsyncMock()
- )
agent._remove_ack_reaction = AsyncMock()
mark_prewrite_user_stop(request.context)
- await agent._finish_prestart_cancellation(
- request,
- server,
- reservation,
- )
+ await agent._finish_prestart_cancellation(request)
- server.release_model_hub_overlay_reservation.assert_awaited_once_with(
- reservation
- )
agent._remove_ack_reaction.assert_awaited_once_with(
request,
terminal_emoji=STOPPED_REACTION_EMOJI,
@@ -283,16 +274,12 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):
_user_stopped_sessions={"session-1"},
)
- async def _get_server():
- return _Server()
-
async def _remove_ack_reaction(request, *, terminal_emoji=None):
cleanups.append((request, terminal_emoji))
def _consume(session_id):
return OpenCodeAgent.consume_user_stop_intent(agent, session_id)
- agent._get_server = _get_server
agent._remove_ack_reaction = _remove_ack_reaction
agent.consume_user_stop_intent = _consume
poll = ActivePollInfo(
@@ -309,7 +296,7 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):
"message_id": "m1",
},
)
- task = asyncio.create_task(OpenCodePollLoop(agent).run_restored_poll_loop(poll))
+ task = asyncio.create_task(OpenCodePollLoop(agent).run_restored_poll_loop(poll, _Server()))
await entered.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
@@ -328,11 +315,6 @@ class _StubOpenCodeServer:
self.start_entered = asyncio.Event()
self.aborted: list[tuple[str, str]] = []
- async def ensure_running(self):
- if self.block_start:
- self.start_entered.set()
- await asyncio.Event().wait()
-
async def ensure_directory_ready(self, _directory):
return None
@@ -403,10 +385,14 @@ def _process_message_agent(server, poll_loop=None):
agent._delete_ack = AsyncMock()
agent._remove_ack_reaction = AsyncMock()
- async def _get_server():
- return server
+ runtime = serve_opencode_agent(agent, server)
+ if server.block_start:
+ # The generation this turn needs is still starting.
+ async def _starting(_spec):
+ server.start_entered.set()
+ await asyncio.Event().wait()
- agent._get_server = _get_server
+ runtime.acquire = _starting
return agent
@@ -464,6 +450,9 @@ class OpenCodeProcessMessageStopReceiptTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(server.aborted, [("oc-session", "/tmp/work")])
self.assertEqual(agent.sessions.get_all_active_polls(), {})
self.assertEqual(agent._user_stopped_sessions, set())
+ # The stopped turn no longer pins its generation.
+ await asyncio.gather(*agent._lifecycle_tasks)
+ self.assertEqual([binding.released for binding in agent._runtime.bindings], [True])
async def test_stop_before_the_server_starts_leaves_the_stopped_receipt(self):
server = _StubOpenCodeServer(block_start=True)
diff --git a/tests/test_queued_image_delivery.py b/tests/test_queued_image_delivery.py
index 41ac02a74..fde13d3a4 100644
--- a/tests/test_queued_image_delivery.py
+++ b/tests/test_queued_image_delivery.py
@@ -29,6 +29,7 @@ from tests.test_agent_steering import (
from tests.test_internal_server import _build_controller_double, _reserve_submission
from tests.test_ui_session_stream import _make_session, isolated_state # noqa: F401
from tests.ui_server_test_helpers import csrf_headers
+from tests.codex_generation_support import init_generation_state, install_codex_transport
PNG = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
@@ -116,11 +117,11 @@ def test_uploaded_image_survives_real_queue_admission_and_send_now(isolated_stat
"unknown_refused": TimeoutError("native write acknowledgement lost"),
"refused": RuntimeError("activeTurnNotSteerable"),
}[receipt])
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.config = SimpleNamespace(include_time_info=False, include_user_info=False)
agent._turn_registry = _CodexTurnRegistry(session_id, "codex-turn")
agent._session_mgr = _CodexSessionManager(session_id, "codex-thread", primary.working_path)
- agent._transports = {primary.working_path: native}
+ install_codex_transport(agent, primary.working_path, native, sessions={session_id: "codex-thread"})
controller = _build_controller_double()
controller.agent_service = SimpleNamespace(
agents={"codex": agent},
diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.py
index 7495ba6e7..b64943e7b 100644
--- a/tests/test_running_agents_service.py
+++ b/tests/test_running_agents_service.py
@@ -14,6 +14,7 @@ import pytest
from core.message_context import build_context_turn_sink_key
from core.services import running_agents
+from tests.codex_generation_support import codex_transports, init_generation_state, install_codex_transport
class _AsyncFlag:
@@ -266,14 +267,18 @@ def test_subagent_composite_key_base_parsing():
assert row["workdir"] == "/srv/app"
+def _transport_by_cwd(mgr, transports):
+ """Codex test double: every Session uses its directory's app-server."""
+ return lambda base: transports.get(mgr.get_cwd(base))
+
+
def test_codex_shared_pid_one_row_per_session():
mgr = _FakeSessionMgr({"base-1": "/work/x", "base-2": "/work/x", "base-3": "/work/y"})
turns = _FakeTurnRegistry({"base-1": "turn-1"}) # base-1 active, others idle
codex = types.SimpleNamespace(
_session_mgr=mgr,
_turn_registry=turns,
- _transports={"/work/x": _FakeTransport(7001), "/work/y": _FakeTransport(7002)},
- _transport_last_activity={"/work/x": 0.0, "/work/y": 0.0},
+ transport_for_session=_transport_by_cwd(mgr, {"/work/x": _FakeTransport(7001), "/work/y": _FakeTransport(7002)}),
)
controller = _make_controller(codex=codex)
snap = running_agents.snapshot_running_agents(controller)
@@ -293,7 +298,7 @@ def test_codex_skips_evicted_idle_base_without_transport():
codex = types.SimpleNamespace(
_session_mgr=mgr,
_turn_registry=turns,
- _transports={"/work/live": _FakeTransport(7001)},
+ transport_for_session=_transport_by_cwd(mgr, {"/work/live": _FakeTransport(7001)}),
)
controller = _make_controller(codex=codex)
snap = running_agents.snapshot_running_agents(controller)
@@ -307,14 +312,14 @@ def test_codex_skips_evicted_idle_base_without_transport():
def test_codex_skips_dead_transport_object():
# A transport whose app-server already exited (is_alive False) can linger in
- # _transports; such a base must not surface as a phantom idle row, nor count
+ # its bound generation; such a base must not surface as a phantom idle row, nor count
# toward pid_shared for a sibling on the same cwd.
mgr = _FakeSessionMgr({"dead": "/work/x", "alive": "/work/y"})
turns = _FakeTurnRegistry({})
codex = types.SimpleNamespace(
_session_mgr=mgr,
_turn_registry=turns,
- _transports={"/work/x": _FakeTransport(8001, is_alive=False), "/work/y": _FakeTransport(8002)},
+ transport_for_session=_transport_by_cwd(mgr, {"/work/x": _FakeTransport(8001, is_alive=False), "/work/y": _FakeTransport(8002)}),
)
controller = _make_controller(codex=codex)
snap = running_agents.snapshot_running_agents(controller)
@@ -393,7 +398,7 @@ def test_codex_pending_turn_start_counts_as_active():
codex = types.SimpleNamespace(
_session_mgr=mgr,
_turn_registry=turns,
- _transports={"/work/p": _FakeTransport(9100)},
+ transport_for_session=_transport_by_cwd(mgr, {"/work/p": _FakeTransport(9100)}),
)
controller = _make_controller(codex=codex)
snap = running_agents.snapshot_running_agents(controller)
@@ -798,241 +803,300 @@ def test_end_claude_session_not_live():
assert res["error"] == "session_not_live"
-def test_end_codex_interrupts_clears_and_stops_last_transport():
+def _codex_shell(session_mgr, turn_registry, **attributes):
+ """A real ``CodexAgent`` without ``__init__``, holding the given registries."""
from modules.agents.codex.agent import CodexAgent
- send = _AsyncFlag()
- stop = _AsyncFlag()
- transport = types.SimpleNamespace(send_request=send, stop=stop)
- cleared = {}
- transports = {"/w": transport}
- mgr = types.SimpleNamespace(
- get_cwd=lambda b: "/w",
- get_thread_id=lambda b: "th1",
- clear=lambda b: cleared.__setitem__("inv", b),
- sessions_for_cwd=lambda cwd: [], # this was the last session on the cwd
- )
- treg = types.SimpleNamespace(
- get_active_turn=lambda b: "turn1",
- clear_session=lambda b: cleared.__setitem__("clr", b),
- )
- async def retire(cwd, *, ending_session_id=None):
- assert cwd == "/w"
- assert ending_session_id == "b1"
- await transport.stop()
- transports.pop(cwd)
- return True
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent._registered_runtime = False
+ agent._session_mgr = session_mgr
+ agent._turn_registry = turn_registry
+ for name, value in attributes.items():
+ setattr(agent, name, value)
+ return agent
- codex = types.SimpleNamespace(
- _session_mgr=mgr,
- _turn_registry=treg,
- _transports=transports,
- _transport_last_activity={"/w": 0.0},
- _session_locks={"b1": asyncio.Lock()},
- _session_last_activity={"b1": 1.0},
- _thread_developer_instructions={"b1": ("th1", "instructions")},
- _thread_prompt_strategies={"b1": ("th1", "fallback")},
- _thread_unpersisted_prompts={"b1": ("th1", "instructions", "fallback")},
- _thread_model_settings={"b1": ("th1", "model", None)},
- _thread_caller_env_configs={"b1": ("th1", {})},
- _thread_git_path_configs={"b1": ("th1", "", False)},
- _clear_thread_developer_instructions=lambda bid: CodexAgent._clear_thread_developer_instructions(codex, bid),
- retire_unowned_session_transport=retire,
- )
- res = asyncio.run(
- running_agents.end_running_agent(_make_controller(codex=codex), backend="codex", base_session_id="b1")
- )
- assert res["ok"] is True
- assert send.called # turn/interrupt RPC sent
- assert cleared.get("inv") == "b1" and cleared.get("clr") == "b1"
- # Last session on the cwd → the shared app-server transport is stopped + dropped.
- assert stop.called and res["process_killed"] is True and "/w" not in transports
- assert codex._session_locks == {}
- assert codex._session_last_activity == {}
- assert codex._thread_developer_instructions == {}
- assert codex._thread_prompt_strategies == {}
- assert codex._thread_unpersisted_prompts == {}
- assert codex._thread_model_settings == {}
- assert codex._thread_caller_env_configs == {}
- assert codex._thread_git_path_configs == {}
-
-
-def test_end_codex_keeps_transport_when_other_sessions_share_cwd():
- transport = types.SimpleNamespace(send_request=_AsyncFlag(), stop=_AsyncFlag())
- transports = {"/w": transport}
- mgr = types.SimpleNamespace(
- get_cwd=lambda b: "/w",
- get_thread_id=lambda b: "th1",
- clear=lambda b: None,
- sessions_for_cwd=lambda cwd: ["other-base"], # another session still uses it
- )
- treg = types.SimpleNamespace(get_active_turn=lambda b: None, clear_session=lambda b: None)
- codex = types.SimpleNamespace(_session_mgr=mgr, _turn_registry=treg, _transports=transports)
- res = asyncio.run(
- running_agents.end_running_agent(_make_controller(codex=codex), backend="codex", base_session_id="b1")
- )
- assert res["ok"] is True
- # Shared transport stays up; not stopped, still registered.
- assert res["process_killed"] is False and "/w" in transports
+def _codex_session_mgr(sessions):
+ from modules.agents.codex.session import CodexSessionManager
-def test_end_codex_reports_transport_retirement_failure():
- async def retire(_cwd, *, ending_session_id=None):
- assert ending_session_id == "b1"
- raise RuntimeError("transport still alive")
+ mgr = CodexSessionManager()
+ for base, (cwd, thread) in sessions.items():
+ mgr.set_cwd(base, cwd)
+ mgr.set_session_key(base, f"key-{base}")
+ if thread:
+ mgr.set_thread_id(base, thread)
+ return mgr
- cleared = []
- mgr = types.SimpleNamespace(
- get_cwd=lambda _base: "/w",
- get_thread_id=lambda _base: None,
- clear=cleared.append,
- sessions_for_cwd=lambda _cwd: ["b1"],
- )
- treg = types.SimpleNamespace(
- get_active_turn=lambda _base: None,
- clear_session=lambda _base: None,
- )
- codex = types.SimpleNamespace(
- _session_mgr=mgr,
- _turn_registry=treg,
- _transports={"/w": object()},
- retire_unowned_session_transport=retire,
- )
- result = asyncio.run(
- running_agents.end_running_agent(
- _make_controller(codex=codex), backend="codex", base_session_id="b1"
+def test_end_codex_settles_clears_and_stops_the_last_users_app_server():
+ # The ending Session was the app-server's only user: its running turn and
+ # Activities settle, the process stops, and the Session's state is cleared.
+ from unittest.mock import AsyncMock
+
+ async def exercise():
+ mgr = _codex_session_mgr({"b1": ("/w", "th1")})
+ cleared = []
+ active = {"b1": "turn1"}
+
+ def clear_session(base):
+ cleared.append(base)
+ active.pop(base, None)
+
+ treg = types.SimpleNamespace(
+ get_active_turn=active.get, get_request_for_turn=lambda _turn: None, clear_session=clear_session
)
- )
- assert result == {
- "ok": False,
- "error": "transport_retire_failed",
- "detail": "transport still alive",
- }
- assert cleared == []
+ caches = {
+ name: {"b1": ("th1", "cached")}
+ for name in (
+ "_thread_developer_instructions",
+ "_thread_prompt_strategies",
+ "_thread_unpersisted_prompts",
+ "_thread_model_settings",
+ "_thread_caller_env_configs",
+ "_thread_git_path_configs",
+ )
+ }
+ end_work = AsyncMock()
+ agent = _codex_shell(
+ mgr,
+ treg,
+ _session_last_activity={"b1": 1.0},
+ controller=types.SimpleNamespace(agent_service=types.SimpleNamespace(force_end_runtime_work=end_work)),
+ **caches,
+ )
+ transport = types.SimpleNamespace(is_alive=True, _process=None, stop=AsyncMock())
+ install_codex_transport(agent, "/w", transport, sessions={"b1": "th1"})
+
+ res = await running_agents.end_running_agent(_make_controller(codex=agent), backend="codex", base_session_id="b1")
+
+ assert res["ok"] is True and res["process_killed"] is True
+ end_work.assert_awaited_once_with(
+ "codex",
+ base_session_ids={"b1"},
+ activation_identities={None},
+ reason="stopped",
+ agent=agent,
+ )
+ transport.stop.assert_awaited_once()
+ assert "b1" in cleared and mgr.get_cwd("b1") is None
+ assert codex_transports(agent) == {}
+ assert agent._session_locks == {} and agent._session_last_activity == {}
+ assert all(getattr(agent, name) == {} for name in caches)
+ asyncio.run(exercise())
-def test_end_codex_can_retry_failed_last_transport_retirement():
- from modules.agents.codex.session import CodexSessionManager
- mgr = CodexSessionManager()
- mgr.set_cwd("b1", "/w")
- mgr.set_session_key("b1", "session-key")
- attempts = []
-
- async def retire(cwd, *, ending_session_id=None):
- attempts.append((cwd, ending_session_id))
- if len(attempts) == 1:
- raise RuntimeError("transport still alive")
- return True
+def test_end_codex_reports_a_failed_stop_and_can_retry_it():
+ from unittest.mock import AsyncMock
- codex = types.SimpleNamespace(
- _session_mgr=mgr,
- _turn_registry=types.SimpleNamespace(
- get_active_turn=lambda _base: None,
- clear_session=lambda _base: None,
- ),
- _transports={"/w": object()},
- retire_unowned_session_transport=retire,
- )
- controller = _make_controller(codex=codex)
- first = asyncio.run(
- running_agents.end_running_agent(
- controller, backend="codex", base_session_id="b1"
+ async def exercise():
+ mgr = _codex_session_mgr({"b1": ("/w", "th1")})
+ treg = types.SimpleNamespace(get_active_turn=lambda _b: None, clear_session=lambda _b: None)
+ agent = _codex_shell(mgr, treg)
+ transport = types.SimpleNamespace(
+ is_alive=True, _process=None, stop=AsyncMock(side_effect=[RuntimeError("transport still alive"), None])
)
- )
- assert first["error"] == "transport_retire_failed"
- assert mgr.get_cwd("b1") == "/w"
- assert mgr.get_session_key("b1") == "session-key"
- second = asyncio.run(
- running_agents.end_running_agent(
- controller, backend="codex", base_session_id="b1"
+ install_codex_transport(agent, "/w", transport, sessions={"b1": "th1"})
+ controller = _make_controller(codex=agent)
+
+ first = await running_agents.end_running_agent(controller, backend="codex", base_session_id="b1")
+ assert first == {"ok": False, "error": "transport_retire_failed", "detail": "transport still alive"}
+ # Nothing is forgotten, so End can be retried on the same row.
+ assert mgr.get_cwd("b1") == "/w" and mgr.get_session_key("b1") == "key-b1"
+ assert agent.transport_for_session("b1") is transport
+
+ second = await running_agents.end_running_agent(controller, backend="codex", base_session_id="b1")
+ assert second["ok"] is True and second["process_killed"] is True
+ assert mgr.get_cwd("b1") is None and agent._units["/w"].generations == ()
+
+ asyncio.run(exercise())
+
+
+def test_end_codex_on_a_shared_app_server_releases_only_that_sessions_thread():
+ """Codex holds one writer per thread: an ended Session must not keep its thread loaded."""
+ from unittest.mock import AsyncMock
+
+ async def exercise():
+ mgr = _codex_session_mgr({"b1": ("/w", "thread-b1"), "b2": ("/w", "thread-b2")})
+ agent = _codex_shell(
+ mgr, types.SimpleNamespace(get_active_turn=lambda _base: None, clear_session=lambda _base: None)
)
- )
- assert second["ok"] is True
- assert second["process_killed"] is True
- assert mgr.get_cwd("b1") is None
- assert attempts == [("/w", "b1"), ("/w", "b1")]
+ sent = []
+ async def send_request(method, params):
+ sent.append((method, params))
+ return {"status": "notLoaded"}
-def test_codex_idle_retirement_serializes_successor_transport_generation():
- from modules.agents.codex.agent import CodexAgent
+ transport = types.SimpleNamespace(is_alive=True, send_request=send_request, stop=AsyncMock())
+ install_codex_transport(agent, "/w", transport, sessions={"b1": "thread-b1", "b2": "thread-b2"})
+
+ result = await running_agents.end_running_agent(
+ _make_controller(codex=agent), backend="codex", base_session_id="b1"
+ )
+
+ assert result["ok"] is True and result["process_killed"] is False
+ assert sent == [("thread/unsubscribe", {"threadId": "thread-b1"})]
+ assert agent.transport_for_session("b1") is None
+ assert agent.transport_for_session("b2") is transport
+ transport.stop.assert_not_awaited()
+
+ asyncio.run(exercise())
+
+
+def test_end_codex_on_a_shared_app_server_keeps_a_turn_codex_refused_to_interrupt():
+ # Unsubscribing a running turn would silence it, so End refuses instead of
+ # forgetting a turn Codex did not stop.
+ from unittest.mock import AsyncMock
+
+ from modules.agents.codex.transport import CodexRPCError
+
+ async def exercise():
+ mgr = _codex_session_mgr({"b1": ("/w", "thread-b1"), "b2": ("/w", "thread-b2")})
+ cleared = []
+ active = {"b1": "turn-b1"}
+
+ def clear_session(base):
+ cleared.append(base)
+ active.pop(base, None)
+
+ agent = _codex_shell(mgr, types.SimpleNamespace(get_active_turn=active.get, clear_session=clear_session))
+ sent = []
+
+ async def send_request(method, params):
+ sent.append(method)
+ raise CodexRPCError({"code": -32603, "message": "interrupt refused"})
+
+ transport = types.SimpleNamespace(is_alive=True, _process=None, send_request=send_request, stop=AsyncMock())
+ install_codex_transport(agent, "/w", transport, sessions={"b1": "thread-b1", "b2": "thread-b2"})
+
+ result = await running_agents.end_running_agent(
+ _make_controller(codex=agent), backend="codex", state="idle", base_session_id="b1"
+ )
+
+ assert result["ok"] is False and result["error"] == "thread_release_failed"
+ assert cleared == [] and active == {"b1": "turn-b1"}
+ assert "thread/unsubscribe" not in sent and mgr.get_thread_id("b1") == "thread-b1"
+ assert agent.transport_for_session("b1") is transport
+
+ asyncio.run(exercise())
+
+
+def test_end_codex_acts_on_the_directory_whose_app_server_holds_the_thread():
+ # The Session's channel moved to /b, but its thread is still loaded in /a.
+ from unittest.mock import AsyncMock
+
+ async def exercise():
+ mgr = _codex_session_mgr({"b1": ("/b", "th1")})
+ agent = _codex_shell(mgr, types.SimpleNamespace(get_active_turn=lambda _b: None, clear_session=lambda _b: None))
+ holder = types.SimpleNamespace(is_alive=True, _process=None, stop=AsyncMock())
+ bystander = types.SimpleNamespace(is_alive=True, _process=None, stop=AsyncMock())
+ install_codex_transport(agent, "/a", holder, sessions={"b1": "th1"})
+ install_codex_transport(agent, "/b", bystander)
+
+ result = await running_agents.end_running_agent(
+ _make_controller(codex=agent), backend="codex", base_session_id="b1"
+ )
+
+ assert result["ok"] is True and result["process_killed"] is True
+ holder.stop.assert_awaited_once()
+ bystander.stop.assert_not_awaited()
+
+ asyncio.run(exercise())
+
+
+def test_codex_end_cancelled_midway_keeps_every_unstopped_generation_attached():
+ async def exercise():
+ mgr = _codex_session_mgr({"b1": ("/w", "thread-1")})
+ agent = _codex_shell(mgr, types.SimpleNamespace(get_active_turn=lambda _b: None, clear_session=lambda _b: None))
+ stopping = asyncio.Event()
+
+ class Transport:
+ _process = None
+
+ async def stop(self):
+ stopping.set()
+ await asyncio.Event().wait()
+
+ first, second = Transport(), Transport()
+ install_codex_transport(agent, "/w", first, digest="older", current=False)
+ install_codex_transport(agent, "/w", second, digest="current", sessions={"b1": "thread-1"})
+ end = asyncio.create_task(
+ running_agents.end_running_agent(_make_controller(codex=agent), backend="codex", base_session_id="b1")
+ )
+ await asyncio.wait_for(stopping.wait(), timeout=1)
+ end.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await end
+
+ # Both processes still run, so a later End or sweep can stop them.
+ assert {generation.runtime.transport for generation in agent._units["/w"].generations} == {first, second}
+ assert agent.transport_for_session("b1") is second
+
+ asyncio.run(exercise())
+
+
+def test_codex_end_detaches_every_generation_before_its_first_stop():
+ """A turn arriving during End never binds to a generation End is about to kill."""
+ from tests.codex_generation_support import FakeLaunchSpec
async def exercise():
- agent = object.__new__(CodexAgent)
- agent._registered_runtime = False
- agent._transport_locks = {}
- agent._transport_last_activity = {"/w": 1.0}
- agent._transport_cwd_inodes = {}
- agent._session_mgr = types.SimpleNamespace(sessions_for_cwd=lambda _cwd: [])
- agent._has_active_turns_for_cwd = lambda _cwd: False
+ mgr = _codex_session_mgr({"b1": ("/w", "thread-1")})
+ agent = _codex_shell(mgr, types.SimpleNamespace(get_active_turn=lambda _b: None, clear_session=lambda _b: None))
+ fresh = object()
+
+ async def start(_spec):
+ return types.SimpleNamespace(cwd="/w", threads={}, transport=fresh, hub=False, ended=False)
+
+ agent._start_generation = start
stopping = asyncio.Event()
resume_stop = asyncio.Event()
class Transport:
+ _process = None
+
async def stop(self):
stopping.set()
await resume_stop.wait()
- old_transport = Transport()
- successor = Transport()
- agent._transports = {"/w": old_transport}
- retirement = asyncio.create_task(agent.retire_unowned_session_transport("/w"))
+ install_codex_transport(agent, "/w", Transport(), digest="older")
+ current = install_codex_transport(agent, "/w", Transport(), digest="current", sessions={"b1": "thread-1"})
+ end = asyncio.create_task(agent.end_session("b1"))
await asyncio.wait_for(stopping.wait(), timeout=1)
- async def install_successor():
- async with agent._transport_locks["/w"]:
- agent._transports["/w"] = successor
-
- installation = asyncio.create_task(install_successor())
- await asyncio.sleep(0)
- assert not installation.done()
+ # The turn needs exactly the spec End's current generation was started from.
+ binding = await agent._units["/w"].acquire(FakeLaunchSpec("current"))
+ assert binding.generation is not current
+ assert binding.generation.runtime.transport is fresh
resume_stop.set()
- assert await asyncio.wait_for(retirement, timeout=1) is True
- await asyncio.wait_for(installation, timeout=1)
- assert agent._transports["/w"] is successor
+ assert (await asyncio.wait_for(end, timeout=1))["process_killed"] is True
asyncio.run(exercise())
-def test_codex_last_session_retirement_keeps_generation_on_failed_stop():
- from modules.agents.codex.agent import CodexAgent
- from modules.agents.codex.session import CodexSessionManager
-
+def test_codex_end_keeps_a_successor_started_during_its_stop():
async def exercise():
- agent = object.__new__(CodexAgent)
- agent._registered_runtime = False
- agent._transport_locks = {}
- agent._transport_last_activity = {"/w": 1.0}
- agent._transport_cwd_inodes = {}
- agent._retire_model_hub_process_scope = lambda _cwd: None
- agent._session_mgr = CodexSessionManager()
- agent._session_mgr.set_cwd("b1", "/w")
- agent._has_active_turns_for_cwd = lambda _cwd: False
+ mgr = _codex_session_mgr({"b1": ("/w", "thread-1")})
+ agent = _codex_shell(mgr, types.SimpleNamespace(get_active_turn=lambda _b: None, clear_session=lambda _b: None))
+ stopping = asyncio.Event()
+ resume_stop = asyncio.Event()
class Transport:
_process = None
- def __init__(self):
- self.attempts = 0
-
async def stop(self):
- self.attempts += 1
- if self.attempts == 1:
- raise RuntimeError("stop failed")
-
- transport = Transport()
- agent._transports = {"/w": transport}
- with pytest.raises(RuntimeError, match="stop failed"):
- await agent.retire_unowned_session_transport(
- "/w", ending_session_id="b1"
- )
- assert agent._transports["/w"] is transport
- assert agent._session_mgr.get_cwd("b1") == "/w"
- assert await agent.retire_unowned_session_transport(
- "/w", ending_session_id="b1"
- )
- assert "/w" not in agent._transports
+ stopping.set()
+ await resume_stop.wait()
+
+ install_codex_transport(agent, "/w", Transport(), sessions={"b1": "thread-1"})
+ successor = Transport()
+ end = asyncio.create_task(agent.end_session("b1"))
+ await asyncio.wait_for(stopping.wait(), timeout=1)
+
+ # A turn arriving meanwhile starts its own generation at once.
+ install_codex_transport(agent, "/w", successor, digest="successor")
+ resume_stop.set()
+ assert (await asyncio.wait_for(end, timeout=1))["process_killed"] is True
+ assert codex_transports(agent) == {"/w": successor}
asyncio.run(exercise())
@@ -1072,14 +1136,13 @@ def test_end_opencode_cancels_active_task():
@pytest.mark.parametrize("has_other_session", [False, True])
-def test_end_idle_opencode_retires_only_last_shared_server(has_other_session):
+def test_end_idle_opencode_retires_the_current_generation_after_its_last_session(has_other_session):
sessions = {
"b1": ("oc-1", "/work", "channel-1"),
}
if has_other_session:
sessions["b2"] = ("oc-2", "/work", "channel-2")
- retired = _AsyncFlag()
- server = types.SimpleNamespace(retire_for_native_migration=retired)
+ retired = _AsyncFlag(ret="stopped")
manager = types.SimpleNamespace(
get_request_session=lambda base: sessions.get(base),
pop_request_session=lambda base: sessions.pop(base, None),
@@ -1088,7 +1151,7 @@ def test_end_idle_opencode_retires_only_last_shared_server(has_other_session):
agent = types.SimpleNamespace(
_active_requests={},
_session_manager=manager,
- _client_manager=types.SimpleNamespace(_server_manager=server),
+ retire_current_generation=retired,
)
result = asyncio.run(
@@ -1106,6 +1169,82 @@ def test_end_idle_opencode_retires_only_last_shared_server(has_other_session):
assert ("b2" in sessions) is has_other_session
+ ("outcome", "expected"),
+ [
+ # A lease still binds the process; it stops once the lease drains.
+ ("draining", {"ok": True, "process_killed": False}),
+ ("failed", {"ok": False, "error": "runtime_retirement_failed"}),
+ ],
+)
+def test_end_idle_opencode_reports_only_a_confirmed_stop_as_killed(outcome, expected):
+ manager = types.SimpleNamespace(
+ get_request_session=lambda base: ("oc-1", "/work", "channel-1") if base == "b1" else None,
+ pop_request_session=lambda base: None,
+ list_all=lambda: {},
+ )
+ agent = types.SimpleNamespace(
+ _active_requests={},
+ _session_manager=manager,
+ retire_current_generation=_AsyncFlag(ret=outcome),
+ )
+
+ result = asyncio.run(
+ running_agents.end_running_agent(
+ _make_controller(opencode=agent),
+ backend="opencode",
+ base_session_id="b1",
+ )
+ )
+
+ assert {key: result.get(key) for key in expected} == expected
+
+
+def test_end_active_opencode_reports_a_retirement_that_failed():
+ """End stops the active turn, then retires the server it was the last user
+ of. A server that survives its stop is reported, not hidden behind the
+ successful turn stop."""
+
+ class _Task:
+ finished = False
+
+ def done(self):
+ return self.finished
+
+ def cancel(self):
+ self.finished = True
+
+ task = _Task()
+ manager = types.SimpleNamespace(
+ get_request_session=lambda base: ("oc-1", "/work", "channel-1") if base == "b1" else None,
+ pop_request_session=lambda base: None,
+ list_all=lambda: {},
+ )
+ agent = types.SimpleNamespace(
+ _active_requests={"b1": task},
+ _session_manager=manager,
+ retire_current_generation=_AsyncFlag(ret="failed"),
+ )
+
+ async def _handle_stop(_context):
+ # The canonical stop ends the native poll.
+ task.finished = True
+ return True
+
+ controller = _make_controller(opencode=agent)
+ controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False)
+ controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+
+ result = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="opencode", state="active", session_id="oc-s", base_session_id="b1"
+ )
+ )
+
+ assert agent.retire_current_generation.called
+ assert {key: result.get(key) for key in ("ok", "error")} == {"ok": False, "error": "runtime_retirement_failed"}
+
+
def test_end_idle_opencode_clears_disposable_session_caches():
from modules.agents.opencode.session import OpenCodeSessionManager
@@ -1122,7 +1261,6 @@ def test_end_idle_opencode_clears_disposable_session_caches():
_active_requests={},
_session_manager=manager,
_session_last_activity={"b1": 1.0, "b2": 2.0},
- _client_manager=types.SimpleNamespace(_server_manager=None),
)
result = asyncio.run(
@@ -1505,37 +1643,22 @@ def test_end_active_codex_frees_runtime_after_stop():
# Active Codex End must FREE the runtime after the canonical stop (which only
# interrupts the turn): clear the session mappings + stop the now-unused shared
# transport so the row disappears instead of forcing a second Disconnect.
+ from unittest.mock import AsyncMock
+
async def _handle_stop(context):
return True
- cleared = {}
- transport = types.SimpleNamespace(send_request=_AsyncFlag(), stop=_AsyncFlag())
- transports = {"/w": transport}
- mgr = types.SimpleNamespace(
- get_cwd=lambda b: "/w",
- get_thread_id=lambda b: "th1",
- clear=lambda b: cleared.__setitem__("clr", b),
- sessions_for_cwd=lambda cwd: [], # this was the last session on the cwd
- )
+ mgr = _codex_session_mgr({"b1": ("/w", "th1")})
+ cleared = []
treg = types.SimpleNamespace(
get_active_turn=lambda b: "turn1", # genuinely active per the live registry
- clear_session=lambda b: cleared.__setitem__("treg", b),
+ get_request_for_turn=lambda _turn: None,
+ clear_session=cleared.append,
)
- codex = types.SimpleNamespace(
- _session_mgr=mgr,
- _turn_registry=treg,
- _transports=transports,
- _transport_last_activity={"/w": 0.0},
- _runtime_turn_key_for_base_session=lambda b: f"{b}:/w",
- )
- async def retire(_cwd, *, ending_session_id=None):
- assert ending_session_id == "b1"
- await transport.stop()
- transports.pop("/w")
- return True
-
- codex.retire_unowned_session_transport = retire
- controller = _make_controller(codex=codex)
+ agent = _codex_shell(mgr, treg, _runtime_turn_key_for_base_session=lambda b: f"{b}:/w")
+ transport = types.SimpleNamespace(is_alive=True, _process=None, stop=AsyncMock())
+ install_codex_transport(agent, "/w", transport, sessions={"b1": "th1"})
+ controller = _make_controller(codex=agent)
controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False, cancel=_AsyncFlag())
controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
@@ -1546,11 +1669,97 @@ def test_end_active_codex_frees_runtime_after_stop():
)
assert res["ok"] is True
# Canonical stop ran, THEN teardown cleared mappings + stopped the shared transport.
- assert cleared.get("clr") == "b1" and cleared.get("treg") == "b1"
- assert transport.stop.called and "/w" not in transports
+ assert mgr.get_cwd("b1") is None and "b1" in cleared
+ transport.stop.assert_awaited_once()
+ assert codex_transports(agent) == {}
assert res["process_killed"] is True
+def test_end_active_codex_reports_a_teardown_failure_after_a_successful_stop():
+ # The turn stopped, but the Session still holds its thread and its row, so
+ # End did not finish and must not report success.
+ from unittest.mock import AsyncMock
+
+ from modules.agents.codex.transport import CodexRPCError
+
+ active = {"b1": "turn1"}
+
+ async def _handle_stop(context):
+ active.pop("b1") # The canonical stop ends the turn.
+ return True
+
+ mgr = _codex_session_mgr({"b1": ("/w", "th1"), "b2": ("/w", "th2")})
+ treg = types.SimpleNamespace(get_active_turn=active.get, clear_session=lambda b: None)
+ agent = _codex_shell(mgr, treg, _runtime_turn_key_for_base_session=lambda b: f"{b}:/w")
+ transport = types.SimpleNamespace(
+ is_alive=True,
+ _process=None,
+ send_request=AsyncMock(side_effect=CodexRPCError({"code": -32603, "message": "unsubscribe failed"})),
+ stop=AsyncMock(),
+ )
+ # The app-server serves another Session.
+ install_codex_transport(agent, "/w", transport, sessions={"b1": "th1", "b2": "th2"})
+ controller = _make_controller(codex=agent)
+ controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False, cancel=_AsyncFlag())
+ controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="codex", state="active", session_id="ses-im", base_session_id="b1"
+ )
+ )
+
+ assert res["ok"] is False and res["error"] == "thread_release_failed"
+
+
+async def test_end_codex_holds_the_session_lifecycle_against_a_new_turn():
+ # A turn admitted for the same Session while End releases its thread would
+ # be unsubscribed and then wiped by End's state clear.
+ from unittest.mock import AsyncMock
+
+ from modules.agents.codex.agent import CodexAgent
+ from tests.codex_generation_support import init_generation_state, install_codex_transport
+
+ from modules.agents.codex.session import CodexSessionManager
+
+ agent = init_generation_state(object.__new__(CodexAgent))
+ mgr = CodexSessionManager()
+ for base in ("b1", "b2"):
+ mgr.set_cwd(base, "/w")
+ mgr.set_thread_id(base, f"thread-{base}")
+ agent._session_mgr = mgr
+ agent._turn_registry = types.SimpleNamespace(get_active_turn=lambda _base: None, clear_session=lambda _base: None)
+ unsubscribed = asyncio.Event()
+ unload = asyncio.Event()
+
+ async def send_request(method, params):
+ unsubscribed.set()
+ await unload.wait()
+ return {"status": "notLoaded"}
+
+ transport = types.SimpleNamespace(is_alive=True, send_request=send_request, stop=AsyncMock())
+ install_codex_transport(agent, "/w", transport, sessions={"b1": "thread-b1", "b2": "thread-b2"})
+ order = []
+
+ async def admit_turn():
+ # Turn admission serializes on the Session's registered lock.
+ async with agent._session_locks.setdefault("b1", asyncio.Lock()):
+ order.append("admitted")
+
+ end = asyncio.create_task(running_agents.end_running_agent(_make_controller(codex=agent), backend="codex", base_session_id="b1"))
+ await asyncio.wait_for(unsubscribed.wait(), 1)
+ admission = asyncio.create_task(admit_turn())
+ await asyncio.sleep(0.01)
+ order.append("released")
+ unload.set()
+ result = await end
+ await admission
+
+ assert result["ok"] is True
+ assert order == ["released", "admitted"]
+
+
def test_end_active_codex_clears_stale_row_even_when_stop_fails():
# A stale-active codex row (turn still in the registry but the app-server died)
# makes the canonical stop fail; End must still tear it down + release the gate
@@ -1558,25 +1767,12 @@ def test_end_active_codex_clears_stale_row_even_when_stop_fails():
async def _handle_stop(context):
return False
- cleared = {}
- mgr = types.SimpleNamespace(
- get_cwd=lambda b: "/w",
- get_thread_id=lambda b: None,
- clear=lambda b: cleared.__setitem__("clr", b),
- sessions_for_cwd=lambda cwd: [],
- )
- treg = types.SimpleNamespace(
- get_active_turn=lambda b: "stale-turn",
- clear_session=lambda b: cleared.__setitem__("treg", b),
- )
- codex = types.SimpleNamespace(
- _session_mgr=mgr,
- _turn_registry=treg,
- _transports={}, # app-server already gone
- _transport_last_activity={},
- _runtime_turn_key_for_base_session=lambda b: f"{b}:/w",
- )
- controller = _make_controller(codex=codex)
+ mgr = _codex_session_mgr({"b1": ("/w", None)})
+ cleared = []
+ treg = types.SimpleNamespace(get_active_turn=lambda b: "stale-turn", clear_session=cleared.append)
+ # The app-server is already gone.
+ agent = _codex_shell(mgr, treg, _runtime_turn_key_for_base_session=lambda b: f"{b}:/w")
+ controller = _make_controller(codex=agent)
controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False, cancel=_AsyncFlag())
controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
@@ -1586,7 +1782,7 @@ def test_end_active_codex_clears_stale_row_even_when_stop_fails():
)
)
assert res["ok"] is True # teardown cleared the stale row despite the failed stop
- assert cleared.get("clr") == "b1" and cleared.get("treg") == "b1"
+ assert mgr.get_cwd("b1") is None and "b1" in cleared
def test_end_unknown_target():
@@ -1703,13 +1899,12 @@ def test_end_does_not_cancel_unrelated_inflight_turn_of_other_backend():
get_cwd=lambda b: "/w",
get_thread_id=lambda b: None,
clear=lambda b: cleared.__setitem__("clr", b),
+ invalidate_thread=lambda b: None,
sessions_for_cwd=lambda cwd: [],
)
treg = _FakeTurnRegistry({}, pending=set()) # the codex base is genuinely idle
treg.clear_session = lambda b: cleared.__setitem__("treg", b)
- codex = types.SimpleNamespace(
- _session_mgr=mgr, _turn_registry=treg, _transports={"/w": transport}, _transport_last_activity={"/w": 0.0}
- )
+ codex = _codex_shell(mgr, treg, transport_for_session=_transport_by_cwd(mgr, {"/w": transport}))
controller = _make_controller(codex=codex)
controller.session_turns = manager
@@ -1746,13 +1941,12 @@ def test_end_does_not_promote_unrelated_durable_owner_of_other_backend(monkeypat
get_cwd=lambda b: "/w",
get_thread_id=lambda b: None,
clear=lambda b: cleared.__setitem__("clr", b),
+ invalidate_thread=lambda b: None,
sessions_for_cwd=lambda cwd: [],
)
treg = _FakeTurnRegistry({}, pending=set())
treg.clear_session = lambda b: cleared.__setitem__("treg", b)
- codex = types.SimpleNamespace(
- _session_mgr=mgr, _turn_registry=treg, _transports={"/w": transport}, _transport_last_activity={"/w": 0.0}
- )
+ codex = _codex_shell(mgr, treg, transport_for_session=_transport_by_cwd(mgr, {"/w": transport}))
controller = _make_controller(codex=codex)
controller.session_turns = manager
monkeypatch.setattr(
@@ -1801,13 +1995,12 @@ def test_end_does_not_cancel_unrelated_durable_owner_when_clicked_row_is_live(
get_cwd=lambda b: "/w",
get_thread_id=lambda b: None,
clear=lambda b: cleared.__setitem__("clr", b),
+ invalidate_thread=lambda b: None,
sessions_for_cwd=lambda cwd: [],
)
treg = _FakeTurnRegistry({"codex-base": "turn-live"}, pending=set())
treg.clear_session = lambda b: cleared.__setitem__("treg", b)
- codex = types.SimpleNamespace(
- _session_mgr=mgr, _turn_registry=treg, _transports={"/w": transport}, _transport_last_activity={"/w": 0.0}
- )
+ codex = _codex_shell(mgr, treg, transport_for_session=_transport_by_cwd(mgr, {"/w": transport}))
controller = _make_controller(codex=codex)
controller.session_turns = manager
monkeypatch.setattr(
@@ -1881,13 +2074,12 @@ def test_end_rechecks_live_state_active_to_idle():
get_cwd=lambda b: "/w",
get_thread_id=lambda b: None,
clear=lambda b: cleared.__setitem__("clr", b),
+ invalidate_thread=lambda b: None,
sessions_for_cwd=lambda cwd: [],
)
treg = _FakeTurnRegistry({}, pending=set()) # no active turn, no pending start
treg.clear_session = lambda b: cleared.__setitem__("treg", b)
- codex = types.SimpleNamespace(
- _session_mgr=mgr, _turn_registry=treg, _transports={"/w": transport}, _transport_last_activity={"/w": 0.0}
- )
+ codex = _codex_shell(mgr, treg, transport_for_session=_transport_by_cwd(mgr, {"/w": transport}))
controller = _make_controller(codex=codex)
controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False)
diff --git a/tests/test_runtime_activation.py b/tests/test_runtime_activation.py
index 8c512dbe2..4be19cde1 100644
--- a/tests/test_runtime_activation.py
+++ b/tests/test_runtime_activation.py
@@ -19,7 +19,10 @@ from modules.agents.base import AGENT_RUNTIME_TURN_KEY, AGENT_RUNTIME_TURN_TOKEN
from modules.agents.claude_agent import ClaudeAgent
from modules.agents.codex.agent import CodexAgent
from modules.agents.opencode.agent import OpenCodeAgent
+from modules.agents.opencode.server import OpenCodeGeneration
from modules.agents.service import AgentService
+from tests.codex_generation_support import init_generation_state, install_codex_transport
+from tests.fake_pid_helpers import fake_pid
def _join(thread: threading.Thread) -> None:
@@ -219,12 +222,11 @@ def test_backend_binding_resolvers_use_exact_anchor_and_workdir() -> None:
workdir="/other",
)
- codex_identity = registry.attach("codex", "/work")
- codex_transport = SimpleNamespace(
- _vibe_runtime_activation_identity=codex_identity,
+ codex_identity = registry.attach("codex", "/work#1")
+ codex = init_generation_state(object.__new__(CodexAgent))
+ install_codex_transport(
+ codex, "/work", SimpleNamespace(), activation=codex_identity, sessions={"anchor": "thread"}
)
- codex = object.__new__(CodexAgent)
- codex._transports = {"/work": codex_transport}
codex._session_mgr = SimpleNamespace(
get_cwd=lambda anchor: "/work" if anchor == "anchor" else None,
)
@@ -239,143 +241,58 @@ def test_backend_binding_resolvers_use_exact_anchor_and_workdir() -> None:
)
-def test_opencode_binding_resolver_returns_pre_prompt_shared_generation() -> None:
+def test_opencode_binding_resolver_follows_each_sessions_generation() -> None:
registry = RuntimeActivationRegistry()
- class _Server:
- base_url = "http://127.0.0.1:4096"
-
- def set_runtime_activation_retire(self, callback) -> None:
- self.retire_activation = callback
+ def generation(generation_id: str, port: int) -> OpenCodeGeneration:
+ return OpenCodeGeneration(
+ generation_id=generation_id,
+ pid=fake_pid(port),
+ port=port,
+ spec_digest=generation_id,
+ process_created_at=1.0,
+ )
- server = _Server()
+ retiring = generation("ocg_old", 1)
+ current = generation("ocg_new", 2)
opencode = object.__new__(OpenCodeAgent)
opencode.controller = SimpleNamespace(runtime_activation=registry)
- opencode._client_manager = SimpleNamespace(_server_manager=server)
+ opencode._runtime = SimpleNamespace(current=lambda: current)
+ opencode._session_generations = {"anchor": retiring}
opencode._session_manager = SimpleNamespace(
get_request_session=lambda anchor: (
("", "/work", "route") if anchor == "anchor" else None
)
)
+ opencode._attach_generation_activation(retiring)
+ opencode._attach_generation_activation(current)
- identity = opencode._attach_server_activation(server)
-
- assert identity is not None
- assert opencode.runtime_activation_identity_for_request(SimpleNamespace()) == identity
+ # A session's live turn commits against the process that runs it; any
+ # other session would start its next turn on the current generation.
+ assert retiring.identity != current.identity
assert opencode.runtime_activation_identity_for_session_binding(
session_anchor="anchor",
workdir="/work",
- ) == identity
+ ) == retiring.identity
+ assert opencode.runtime_activation_identity_for_request(
+ SimpleNamespace(base_session_id="anchor")
+ ) == retiring.identity
+ assert opencode.runtime_activation_identity_for_session_binding(
+ session_anchor="other",
+ workdir="/work",
+ ) == current.identity
with pytest.raises(ValueError, match="changed workdir"):
opencode.runtime_activation_identity_for_session_binding(
session_anchor="anchor",
workdir="/other",
)
- assert server.retire_activation(True, False)
- replacement = opencode.runtime_activation_identity_for_request(SimpleNamespace())
- late_prompt_commit = registry.commit_if_current(identity, lambda: "accepted")
-
- assert replacement is not None and replacement != identity
- assert late_prompt_commit == RuntimeActivationCommit(admitted=False)
- assert registry.is_current(replacement)
-
-
-def test_mh_runtime_007_opencode_overlay_restart_retires_pre_native_start_owner() -> None:
- """MH-RUNTIME-007: a claimed pre-native Turn cannot block its overlay change."""
-
- registry = RuntimeActivationRegistry()
-
- class _Server:
- base_url = "http://127.0.0.1:4096"
-
- def set_runtime_activation_retire(self, callback) -> None:
- self.retire_activation = callback
-
- def runtime_has_active_turns(self) -> bool:
- return False
-
- server = _Server()
- opencode = object.__new__(OpenCodeAgent)
- opencode.controller = SimpleNamespace(runtime_activation=registry)
- opencode.runtime_ownership_snapshots = lambda: (
- SimpleNamespace(
- blocks_reclamation=True,
- blocks_transport_replacement=False,
- blocks_transport_replacement_after_turn_drain=False,
- has_active_turn_evidence=False,
- ),
- )
-
- identity = opencode._attach_server_activation(server)
-
- assert identity is not None
- assert server.retire_activation(False, False)
- assert not registry.is_current(identity)
-
-
-def test_opencode_overlay_restart_preserves_native_active_owner() -> None:
- registry = RuntimeActivationRegistry()
-
- class _Server:
- base_url = "http://127.0.0.1:4096"
-
- def set_runtime_activation_retire(self, callback) -> None:
- self.retire_activation = callback
+ asyncio.run(opencode._on_generation_stopping(retiring, False))
- def runtime_has_active_turns(self) -> bool:
- return False
-
- server = _Server()
- opencode = object.__new__(OpenCodeAgent)
- opencode.controller = SimpleNamespace(runtime_activation=registry)
- opencode.runtime_ownership_snapshots = lambda: (
- SimpleNamespace(
- blocks_reclamation=True,
- blocks_transport_replacement=True,
- blocks_transport_replacement_after_turn_drain=False,
- has_active_turn_evidence=True,
- ),
+ assert registry.commit_if_current(retiring.identity, lambda: "accepted") == RuntimeActivationCommit(
+ admitted=False
)
-
- identity = opencode._attach_server_activation(server)
-
- assert identity is not None
- assert not server.retire_activation(False, False)
- assert registry.is_current(identity)
-
-
-def test_mh_runtime_007_opencode_overlay_restart_ignores_drained_durable_active_turn() -> None:
- """MH-RUNTIME-007: a stale durable Turn cannot outvote the server drain."""
-
- registry = RuntimeActivationRegistry()
-
- class _Server:
- base_url = "http://127.0.0.1:4096"
-
- def set_runtime_activation_retire(self, callback) -> None:
- self.retire_activation = callback
-
- def runtime_has_active_turns(self) -> bool:
- raise AssertionError("explicit drain must not reread PID turn metadata")
-
- server = _Server()
- opencode = object.__new__(OpenCodeAgent)
- opencode.controller = SimpleNamespace(runtime_activation=registry)
- opencode.runtime_ownership_snapshots = lambda: (
- SimpleNamespace(
- blocks_reclamation=True,
- blocks_transport_replacement=True,
- blocks_transport_replacement_after_turn_drain=False,
- has_active_turn_evidence=True,
- ),
- )
-
- identity = opencode._attach_server_activation(server)
-
- assert identity is not None
- assert server.retire_activation(False, True)
- assert not registry.is_current(identity)
+ assert registry.is_current(current.identity)
def test_session_binding_lookup_failure_is_not_resource_absence() -> None:
@@ -522,10 +439,9 @@ def test_hfr_137_codex_session_key_claim_observes_retired_generation() -> None:
"""HFR-137: legacy routes cannot bypass the exact Codex generation."""
registry = RuntimeActivationRegistry()
- identity = registry.attach("codex", "/work")
- transport = SimpleNamespace(_vibe_runtime_activation_identity=identity)
- codex = object.__new__(CodexAgent)
- codex._transports = {"/work": transport}
+ identity = registry.attach("codex", "/work#1")
+ codex = init_generation_state(object.__new__(CodexAgent))
+ install_codex_transport(codex, "/work", SimpleNamespace(), activation=identity, sessions={"base": "thread"})
codex._session_mgr = SimpleNamespace(
get_sessions_by_session_key=lambda _route: ["base"],
get_cwd=lambda _base: "/work",
diff --git a/tests/test_runtime_generations.py b/tests/test_runtime_generations.py
new file mode 100644
index 000000000..016a6ed51
--- /dev/null
+++ b/tests/test_runtime_generations.py
@@ -0,0 +1,465 @@
+"""Runtime generation sets: new turns never wait for, nor interrupt, old work."""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+
+import pytest
+
+from modules.agents.runtime_generations import RuntimeGenerationSet, RuntimeUnitStopping
+
+
+@dataclass(frozen=True)
+class _Spec:
+ digest: str
+
+
+class _Runtimes:
+ """Fake runtimes; the test controls how their teardown behaves."""
+
+ def __init__(self) -> None:
+ self.live: list[str] = []
+ self.stopped: list[tuple[str, bool]] = []
+ self.fail_start = False
+ self.fail_stops = 0
+ self.decline_stops = 0
+ self.stop_gate: asyncio.Event | None = None
+ self.before_stop = None
+ self.start_gate: asyncio.Event | None = None
+ self.started = 0
+
+ async def start(self, spec: _Spec) -> str:
+ if self.start_gate is not None:
+ await self.start_gate.wait()
+ if self.fail_start:
+ raise RuntimeError("start failed")
+ runtime = f"{spec.digest}#{self.started}"
+ self.started += 1
+ self.live.append(runtime)
+ return runtime
+
+ async def stop(self, generation, force: bool) -> bool:
+ if self.stop_gate is not None:
+ await self.stop_gate.wait()
+ if self.before_stop is not None:
+ await self.before_stop(generation)
+ if self.fail_stops:
+ self.fail_stops -= 1
+ raise RuntimeError("teardown failed")
+ if self.decline_stops and not force:
+ self.decline_stops -= 1
+ return False
+ self.live.remove(generation.runtime)
+ self.stopped.append((generation.runtime, force))
+ return True
+
+ def generation_set(self, **kwargs) -> RuntimeGenerationSet[_Spec, str]:
+ return RuntimeGenerationSet(start=self.start, stop=self.stop, **kwargs)
+
+
+def test_runtime_gen_002_a_busy_generation_finishes_while_new_turns_use_a_new_one():
+ """RUNTIME-GEN-002: generation admission never waits for or interrupts old work.
+
+ The same spec shares the current generation. A changed spec starts a new
+ generation first; an unbound predecessor then stops, and a bound one keeps
+ serving its work and stops when the last binding is released.
+ """
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ first = await generations.acquire(_Spec("a"))
+ same = await generations.acquire(_Spec("a"))
+ assert same.generation is first.generation
+ await first.release()
+ await same.release()
+
+ replaced = await generations.acquire(_Spec("b"))
+ await generations.settled()
+ assert runtimes.stopped == [(first.generation.runtime, False)]
+ assert runtimes.live == [replaced.generation.runtime]
+
+ new = await asyncio.wait_for(generations.acquire(_Spec("c")), timeout=1)
+ await generations.reap()
+ assert generations.current is new.generation
+ assert replaced.generation.retiring and replaced.generation.runtime in runtimes.live
+
+ await replaced.release()
+ await replaced.release()
+ await generations.settled()
+ assert runtimes.stopped[-1] == (replaced.generation.runtime, False)
+ assert generations.generations == (new.generation,)
+
+ asyncio.run(run())
+
+
+def test_runtime_gen_003_at_the_cap_the_oldest_retiring_generation_gives_way():
+ """RUNTIME-GEN-003: at the cap a new turn still starts at once.
+
+ The oldest retiring generation is force-stopped, even while its adapter
+ still reports work and its stop settles that work's bindings, and the unit
+ is back at the cap.
+ """
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set(cap=3)
+
+ async def run():
+ oldest = await generations.acquire(_Spec("1"))
+ middle = await generations.acquire(_Spec("2"))
+ current = await generations.acquire(_Spec("3"))
+
+ async def settle_bound_work(generation):
+ if generation is oldest.generation:
+ await oldest.release()
+
+ runtimes.before_stop = settle_bound_work
+
+ newest = await asyncio.wait_for(generations.acquire(_Spec("4")), timeout=1)
+ await generations.settled()
+
+ assert runtimes.stopped == [(oldest.generation.runtime, True)]
+ assert generations.generations == (middle.generation, current.generation, newest.generation)
+ assert len(runtimes.live) == 3
+
+ asyncio.run(run())
+
+
+def test_the_cap_holds_when_graceful_stops_decline_or_are_still_running():
+ """Generations whose adapters still report work, or whose stop is pending, count toward the cap."""
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set(cap=3)
+
+ async def run():
+ runtimes.decline_stops = 10
+ for digest in ("1", "2", "3", "4", "5"):
+ binding = await generations.acquire(_Spec(digest))
+ await binding.release()
+ await generations.settled()
+ assert len(runtimes.live) <= 3
+
+ assert runtimes.stopped == [("1#0", True), ("2#1", True)]
+ assert [generation.spec.digest for generation in generations.generations] == ["3", "4", "5"]
+
+ # A graceful stop still pending when more generations arrive is
+ # rechecked against the cap once it declines.
+ runtimes.stop_gate = asyncio.Event()
+ for digest in ("6", "7"):
+ await generations.acquire(_Spec(digest))
+ runtimes.stop_gate.set()
+ await generations.settled()
+ assert len(runtimes.live) == 3
+
+ asyncio.run(run())
+
+
+def test_the_cap_still_reclaims_a_generation_whose_forced_stop_failed():
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set(cap=3)
+
+ async def run():
+ for digest in ("1", "2", "3"):
+ await generations.acquire(_Spec(digest))
+ runtimes.fail_stops = 1
+ await generations.acquire(_Spec("4"))
+ await generations.settled()
+ # The oldest could not be stopped, so the next one gives way instead.
+ assert runtimes.live == ["1#0", "3#2", "4#3"]
+ assert runtimes.stopped == [("2#1", True)]
+
+ # The failed generation stays eligible: the next pass reclaims it first.
+ await generations.acquire(_Spec("5"))
+ await generations.settled()
+ assert runtimes.live == ["3#2", "4#3", "5#4"]
+ assert runtimes.stopped == [("2#1", True), ("1#0", True)]
+
+ asyncio.run(run())
+
+
+def test_admission_never_waits_for_a_teardown():
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ first = await generations.acquire(_Spec("a"))
+ await first.release()
+ runtimes.stop_gate = asyncio.Event()
+
+ second = await asyncio.wait_for(generations.acquire(_Spec("b")), timeout=1)
+ assert generations.current is second.generation
+ assert first.generation.runtime in runtimes.live
+
+ runtimes.stop_gate.set()
+ await generations.settled()
+ assert runtimes.stopped == [(first.generation.runtime, False)]
+
+ asyncio.run(run())
+
+
+def test_a_live_generation_with_the_needed_spec_serves_again():
+ """Sessions alternating between two launch specs keep two processes, not more."""
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ hub = await generations.acquire(_Spec("hub"))
+ native = await generations.acquire(_Spec("native"))
+ again = await generations.acquire(_Spec("hub"))
+ await generations.settled()
+ assert again.generation is hub.generation
+ assert generations.current is hub.generation and native.generation.retiring
+ assert len(runtimes.live) == 2 and runtimes.stopped == []
+
+ asyncio.run(run())
+
+
+def test_adopted_and_restored_work_keep_their_generation_alive():
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ runtimes.live.append("previous")
+ previous = await generations.adopt(_Spec("old"), "previous", current=False)
+ restored = await generations.bind(previous)
+ current = await generations.acquire(_Spec("new"))
+ await generations.settled()
+ assert previous.retiring and "previous" in runtimes.live
+
+ await restored.release()
+ await generations.settled()
+ assert runtimes.stopped == [("previous", False)]
+ assert generations.generations == (current.generation,)
+
+ asyncio.run(run())
+
+
+def test_a_retired_generation_stops_once_unbound_and_admits_no_new_turn():
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ bound = await generations.acquire(_Spec("a"))
+ await generations.retire(bound.generation)
+ await generations.settled()
+ assert generations.current is None and bound.generation.runtime in runtimes.live
+
+ fresh = await generations.acquire(_Spec("a"))
+ assert fresh.generation is not bound.generation
+ await bound.release()
+ await generations.settled()
+ assert runtimes.stopped == [(bound.generation.runtime, False)]
+
+ await fresh.release()
+ await generations.retire_current()
+ await generations.settled()
+ assert runtimes.stopped[-1] == (fresh.generation.runtime, False)
+ await generations.retire(fresh.generation)
+ await generations.retire_current()
+ await generations.settled()
+ assert len(runtimes.stopped) == 2
+
+ asyncio.run(run())
+
+
[email protected]("outcome", ["fails", "declines", "cancelled"])
+def test_a_generation_whose_teardown_does_not_finish_stays_tracked(outcome):
+ """A failed, declined, or cancelled stop keeps the process in the set for the next sweep.
+
+ A generation whose teardown failed is never promoted back to serve a turn.
+ """
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ old = await generations.acquire(_Spec("a"))
+ await generations.acquire(_Spec("b"))
+ if outcome == "fails":
+ runtimes.fail_stops = 1
+ elif outcome == "declines":
+ runtimes.decline_stops = 1
+ else:
+ async def cancel_teardown(_generation):
+ raise asyncio.CancelledError
+
+ runtimes.before_stop = cancel_teardown
+
+ await old.release()
+ if outcome == "cancelled":
+ with pytest.raises(asyncio.CancelledError):
+ await generations.settled()
+ runtimes.before_stop = None
+ else:
+ await generations.settled()
+ assert old.generation in generations.generations and not old.generation.stopped
+
+ again = await generations.acquire(_Spec("a"))
+ assert (again.generation is old.generation) is (outcome == "declines")
+ if again.generation is not old.generation:
+ await generations.reap()
+ assert runtimes.stopped[-1] == (old.generation.runtime, False)
+ assert old.generation not in generations.generations
+
+ asyncio.run(run())
+
+
[email protected]("force", [True, False])
+def test_stop_all_closes_admission_and_keeps_bound_work_on_a_graceful_stop(force):
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ serving = await generations.acquire(_Spec("a"))
+ runtimes.start_gate = asyncio.Event()
+ starting = asyncio.create_task(generations.acquire(_Spec("b")))
+ await asyncio.sleep(0)
+
+ stopping = asyncio.create_task(generations.stop_all(force=force))
+ await asyncio.sleep(0.05)
+ with pytest.raises(RuntimeUnitStopping):
+ await generations.acquire(_Spec("a"))
+ # Stop-all covers the start that was already in flight.
+ assert not stopping.done()
+ runtimes.start_gate.set()
+ await stopping
+ with pytest.raises(RuntimeUnitStopping):
+ await starting
+ assert "b#1" not in runtimes.live
+
+ if force:
+ assert runtimes.live == []
+ else:
+ # The bound generation keeps its work until that work is released.
+ assert runtimes.live == [serving.generation.runtime]
+ await serving.release()
+ await generations.settled()
+ assert runtimes.live == []
+
+ asyncio.run(run())
+
+
+def test_a_start_that_lands_after_a_graceful_stop_all_costs_no_running_work():
+ """A unit at the cap that stops gracefully never force-stops bound work for a late start."""
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set(cap=3)
+
+ async def run():
+ bound = [await generations.acquire(_Spec(digest)) for digest in ("1", "2", "3")]
+ runtimes.start_gate = asyncio.Event()
+ late = asyncio.create_task(generations.acquire(_Spec("4")))
+ await asyncio.sleep(0)
+
+ stopping = asyncio.create_task(generations.stop_all(force=False))
+ await asyncio.sleep(0)
+ runtimes.start_gate.set()
+ await stopping
+ with pytest.raises(RuntimeUnitStopping):
+ await late
+
+ # Only the late, unbound start stops; the bound work keeps running.
+ assert runtimes.stopped == [("4#3", False)]
+ for binding in bound:
+ await binding.release()
+ await generations.settled()
+ assert runtimes.live == []
+ assert all(not force for _runtime, force in runtimes.stopped)
+
+ asyncio.run(run())
+
+
+def test_a_forced_stop_all_forces_a_generation_whose_graceful_stop_was_in_flight():
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ old = await generations.acquire(_Spec("a"))
+ await generations.acquire(_Spec("b"))
+ runtimes.stop_gate = asyncio.Event()
+ runtimes.decline_stops = 1
+ await old.release()
+ await asyncio.sleep(0)
+
+ stopping = asyncio.create_task(generations.stop_all(force=True))
+ await asyncio.sleep(0)
+ runtimes.stop_gate.set()
+ await asyncio.wait_for(stopping, timeout=1)
+
+ assert runtimes.live == []
+ assert (old.generation.runtime, True) in runtimes.stopped
+
+ asyncio.run(run())
+
+
+def test_a_forced_stop_all_retries_a_forced_stop_that_was_in_flight_and_failed():
+ """A forced stop-all stops every process, even one whose earlier forced stop failed mid-pass."""
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set(cap=2)
+
+ async def run():
+ oldest = await generations.acquire(_Spec("1"))
+ await generations.acquire(_Spec("2"))
+ runtimes.stop_gate = asyncio.Event()
+ runtimes.fail_stops = 1
+ # The cap force-stops the oldest; that stop is still running.
+ await generations.acquire(_Spec("3"))
+ await asyncio.sleep(0)
+
+ stopping = asyncio.create_task(generations.stop_all(force=True))
+ await asyncio.sleep(0)
+ runtimes.stop_gate.set()
+ await asyncio.wait_for(stopping, timeout=1)
+
+ assert runtimes.live == []
+ assert (oldest.generation.runtime, True) in runtimes.stopped
+
+ asyncio.run(run())
+
+
+def test_a_reap_during_a_pass_retries_a_stop_that_pass_already_declined():
+ """A sweep that arrives mid-pass still retries a generation that pass declined earlier."""
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ first = await generations.acquire(_Spec("a"))
+ second = await generations.acquire(_Spec("b"))
+ await generations.acquire(_Spec("c"))
+ runtimes.decline_stops = 1
+ gate = asyncio.Event()
+
+ async def hold_the_pass(generation):
+ if generation is second.generation:
+ await gate.wait()
+
+ runtimes.before_stop = hold_the_pass
+ await first.release()
+ await second.release()
+ for _ in range(5):
+ await asyncio.sleep(0)
+ # The pass declined the first stop and is now stopping the second.
+ assert first.generation.deferred and first.generation.runtime in runtimes.live
+
+ sweep = asyncio.create_task(generations.reap())
+ await asyncio.sleep(0)
+ gate.set()
+ await asyncio.wait_for(sweep, timeout=1)
+
+ assert first.generation.runtime not in runtimes.live
+ assert second.generation.runtime not in runtimes.live
+
+ asyncio.run(run())
+
+
+def test_a_failed_start_leaves_the_current_generation_serving():
+ runtimes = _Runtimes()
+ generations = runtimes.generation_set()
+
+ async def run():
+ first = await generations.acquire(_Spec("a"))
+ runtimes.fail_start = True
+ with pytest.raises(RuntimeError, match="start failed"):
+ await generations.acquire(_Spec("b"))
+ assert generations.current is first.generation
+ assert not first.generation.retiring
+ assert runtimes.live == [first.generation.runtime]
+
+ asyncio.run(run())
diff --git a/tests/test_runtime_ownership.py b/tests/test_runtime_ownership.py
index 9474c2058..53495facd 100644
--- a/tests/test_runtime_ownership.py
+++ b/tests/test_runtime_ownership.py
@@ -25,6 +25,8 @@ from core.session_turns import SessionTurnManager
from modules.agents.codex.agent import CodexAgent
from modules.agents.codex.session import CodexSessionManager
from modules.agents.opencode.agent import OpenCodeAgent
+from modules.agents.opencode.server import OpenCodeGeneration
+from tests.fake_pid_helpers import fake_pid
from modules.agents.service import AgentService
from storage import message_deliveries as delivery_store
from storage import workbench_sessions_service as workbench_sessions
@@ -38,6 +40,7 @@ from storage.models import (
runtime_records,
)
from storage.session_activities import ACTIVE_PHASE, AWAITING_OUTPUT_PHASE
+from tests.codex_generation_support import init_generation_state, install_codex_transport
NOW = "2026-08-03T00:00:00+00:00"
@@ -171,9 +174,9 @@ async def test_hfr_137_new_pin_between_reclaimer_passes_wins_locked_check(
engine,
[("ses-a", "base-a", "/work", "route:a")],
)
- lock = agent._transport_locks["/work"]
- await lock.acquire()
first_snapshot = asyncio.Event()
+ proceed = threading.Event()
+ loop = asyncio.get_running_loop()
delegate = agent.controller.runtime_ownership
calls = 0
@@ -183,7 +186,9 @@ async def test_hfr_137_new_pin_between_reclaimer_passes_wins_locked_check(
calls += 1
result = delegate.snapshot(target)
if calls == 1:
- first_snapshot.set()
+ # Hold the reclaimer between its two passes.
+ loop.call_soon_threadsafe(first_snapshot.set)
+ assert proceed.wait(timeout=5)
return result
agent.controller.runtime_ownership = _BarrierProvider()
@@ -202,7 +207,7 @@ async def test_hfr_137_new_pin_between_reclaimer_passes_wins_locked_check(
dispatch_text="delivery-a",
attempt_id="attempt-a",
)
- lock.release()
+ proceed.set()
assert await eviction == 0
assert calls >= 2
assert stopped == []
@@ -220,7 +225,7 @@ def test_hfr_141_repeated_wakes_do_not_refresh_progress_clocks(tmp_path: Path) -
[("ses-a", "base-a", "/work", "route:a")],
)
agent._session_last_activity = {"base-a": 17.0}
- snapshot = agent._runtime_ownership_snapshot_for_cwd("/work")
+ snapshot = asyncio.run(agent._ownership_snapshot(agent._current_generation("/work")))
wake_runtime_ownership(agent.controller, snapshot)
wake_runtime_ownership(agent.controller, snapshot)
assert agent._session_last_activity == {"base-a": 17.0}
@@ -284,7 +289,7 @@ async def test_hfr_146_shared_codex_target_and_claude_mapping_use_exact_bindings
assert target.bindings[0].session_anchor == "base-active"
assert target.bindings[0].workdir == "/work"
manager.set_agent_session_id("base-active", None)
- assert agent._runtime_ownership_target_for_cwd("/work") is None
+ assert agent._runtime_ownership_target_for_generation(agent._current_generation("/work")) is None
del claude_client._vibe_agent_session_id
assert (
handler._claude_runtime_ownership_target(
@@ -328,32 +333,55 @@ def test_hfr_145_every_backend_invalidation_path_consumes_exact_ownership() -> N
runtime_ownership=SimpleNamespace(snapshot=snapshot),
runtime_work_supervisor=SimpleNamespace(notify=Mock()),
)
- opencode = object.__new__(OpenCodeAgent)
- opencode._client_manager = SimpleNamespace(
- _server_manager=SimpleNamespace(
- base_url="http://127.0.0.1:4096",
- runtime_has_active_turns=lambda: False,
+ def generation(generation_id: str, index: int) -> OpenCodeGeneration:
+ return OpenCodeGeneration(
+ generation_id=generation_id,
+ pid=fake_pid(index),
+ port=50000 + index,
+ spec_digest=generation_id,
+ process_created_at=1.0,
)
+
+ retiring, current = generation("ocg_old", 1), generation("ocg_new", 2)
+ opencode = object.__new__(OpenCodeAgent)
+ opencode._runtime = SimpleNamespace(
+ generations=lambda: (retiring, current),
+ current=lambda: current,
+ outside_turn_acquisitions=0,
+ has_bound_work=lambda: False,
)
+ # base-a still runs on the retiring generation; base-b is between turns.
+ opencode._session_generations = {"base-a": retiring}
opencode._session_manager = SimpleNamespace(
- list_all=lambda: {"base-a": ("native-a", "/work", "route:a")},
- get_agent_session_id=lambda _base: "ses-a",
+ list_all=lambda: {
+ "base-a": ("native-a", "/work", "route:a"),
+ "base-b": ("native-b", "/work", "route:b"),
+ },
+ get_agent_session_id=lambda base: {"base-a": "ses-a", "base-b": "ses-b"}[base],
)
opencode._active_requests = {}
- opencode.runtime_turn_keys = lambda: {"base-a:/work"}
opencode.controller = controller
service = AgentService(controller)
service.register(opencode)
assert not asyncio.run(service.backend_runtime_active("opencode"))
- target = target_snapshots[0]
- assert target.resource_key == "http://127.0.0.1:4096"
- assert target.include_all_backend_sessions
- assert target.maps_all_backend_activities
- assert target.maps_all_backend_fallback_runs
- assert target.bindings[0].session_id == "ses-a"
- assert target.bindings[0].fallback_route_keys == ("route:a",)
- assert target.known_fallback_route_keys == ("route:a",)
+ old_target, current_target = target_snapshots
+ assert old_target.resource_key == "opencode:ocg_old"
+ assert not old_target.include_all_backend_sessions
+ assert not old_target.maps_all_backend_activities
+ assert not old_target.maps_all_backend_fallback_runs
+ assert [binding.session_id for binding in old_target.bindings] == ["ses-a"]
+ assert old_target.bindings[0].fallback_route_keys == ("route:a",)
+ assert old_target.known_fallback_route_keys == ("route:a",)
+ assert old_target.known_activity_runtime_keys == ("base-a:/work",)
+ # Unbound sessions acquire the current generation, so its target keeps
+ # every backend session in view for exclusive operations.
+ assert current_target.resource_key == "opencode:ocg_new"
+ assert current_target.include_all_backend_sessions
+ assert current_target.maps_all_backend_activities
+ assert current_target.maps_all_backend_fallback_runs
+ assert [binding.session_id for binding in current_target.bindings] == ["ses-a", "ses-b"]
+ assert current_target.known_fallback_route_keys == ("route:a", "route:b")
opencode._session_manager.get_agent_session_id = lambda _base: None
assert opencode.runtime_ownership_snapshots() is None
@@ -372,13 +400,14 @@ def test_codex_ownership_probe_batches_off_the_event_loop() -> None:
batch_sizes.append(len(targets))
return snapshots
- agent = object.__new__(CodexAgent)
- agent._transports = {"/a": object(), "/b": object()}
+ agent = init_generation_state(object.__new__(CodexAgent))
+ install_codex_transport(agent, "/a", object())
+ install_codex_transport(agent, "/b", object())
agent.controller = SimpleNamespace(
runtime_ownership=SimpleNamespace(snapshot_many=snapshot_many),
)
- agent._runtime_ownership_target_for_cwd = Mock(
- side_effect=lambda cwd: SimpleNamespace(resource_key=cwd)
+ agent._runtime_ownership_target_for_generation = Mock(
+ side_effect=lambda generation: SimpleNamespace(resource_key=generation.runtime.cwd)
)
result = asyncio.run(agent.runtime_ownership_snapshots())
@@ -724,12 +753,8 @@ def _codex_reclaimer(engine, bindings: list[tuple[str, str, str, str]]):
manager.set_cwd(base_session_id, cwd)
manager.set_session_key(base_session_id, session_key)
manager.set_agent_session_id(base_session_id, agent_session_id)
- agent = object.__new__(CodexAgent)
- agent._transports = {"/work": SimpleNamespace(stop=stop_transport)}
- agent._transport_last_activity = {"/work": 0.0}
+ agent = init_generation_state(object.__new__(CodexAgent))
agent._session_last_activity = {}
- agent._transport_locks = {"/work": asyncio.Lock()}
- agent._transport_cwd_inodes = {}
agent._session_locks = {}
agent._session_mgr = manager
agent._turn_registry = SimpleNamespace(
@@ -744,6 +769,9 @@ def _codex_reclaimer(engine, bindings: list[tuple[str, str, str, str]]):
),
model_hub_runtime=None,
)
+ install_codex_transport(
+ agent, "/work", SimpleNamespace(stop=stop_transport, _process=None), last_activity=0.0
+ )
return agent, manager, stopped, wakes
@@ -1543,7 +1571,7 @@ async def test_hfr_150_reused_route_run_blocks_codex_cwd_reclamation(
assert await agent.evict_idle_transports(600) == 0
assert stopped == []
- assert "/work" in agent._transports
+ assert agent._current_generation("/work") is not None
engine.dispose()
diff --git a/tests/test_save_opencode_provider_auth.py b/tests/test_save_opencode_provider_auth.py
index 55e435734..a2b91ddcb 100644
--- a/tests/test_save_opencode_provider_auth.py
+++ b/tests/test_save_opencode_provider_auth.py
@@ -20,6 +20,7 @@ from typing import Any, List, Tuple
import pytest
+from tests.opencode_generation_fakes import ui_lease
from vibe import api
@@ -132,7 +133,7 @@ def fake_save_env(monkeypatch, tmp_path):
async def _fake_get_server():
return server
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
monkeypatch.setattr(api, "restart_backend", lambda backend: {"ok": True})
monkeypatch.setattr(api, "_OPENCODE_OPTIONS_CACHE", {})
@@ -146,7 +147,7 @@ def fake_model_env(monkeypatch, tmp_path):
async def _fake_get_server():
return server
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
monkeypatch.setattr(api, "restart_backend", lambda backend: {"ok": True})
monkeypatch.setattr(api, "_OPENCODE_OPTIONS_CACHE", {"x": {"data": {}, "updated_at": 1}})
@@ -536,7 +537,7 @@ def test_save_provider_model_rejects_builtin_duplicate_from_list_models(monkeypa
}
)
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
monkeypatch.setattr(api, "restart_backend", lambda backend: {"ok": True})
monkeypatch.setattr(api, "_OPENCODE_OPTIONS_CACHE", {})
@@ -667,7 +668,7 @@ def test_save_custom_provider_rejects_reserved_id_when_catalog_unavailable(monke
async def _fail_get_server():
raise RuntimeError("daemon unavailable")
- monkeypatch.setattr(api, "_opencode_get_server", _fail_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fail_get_server))
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
result = _save_custom(
@@ -926,7 +927,7 @@ def test_base_url_persist_failure_surfaces_to_caller(monkeypatch, tmp_path) -> N
async def _fake_get_server():
return server
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
def _explode(*args, **kwargs):
@@ -943,3 +944,27 @@ def test_base_url_persist_failure_surfaces_to_caller(monkeypatch, tmp_path) -> N
# Credential persistence is config-file based; the daemon auth API
# is not called for Settings-entered API keys.
assert server.set_calls == []
+
+
+def test_save_provider_model_fails_closed_when_an_enabled_opencode_cannot_be_leased(monkeypatch, tmp_path) -> None:
+ """OpenCode is enabled, but the controller cannot lease a generation right
+ now. Without the live catalog the save could shadow a built-in model, so it
+ fails instead of persisting as it would for a disabled OpenCode."""
+
+ import config.v2_compat as v2_compat
+ from modules.agents.opencode import client_manager
+ from vibe.opencode_config import read_opencode_provider_user_models
+
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+ monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: object()))
+ monkeypatch.setattr(v2_compat, "to_app_config", lambda _config: type("App", (), {"opencode": object()})())
+
+ async def unreachable(purpose, *, ttl_seconds, controller=None):
+ raise client_manager.OpenCodeRuntimeUnavailableError("controller_unavailable", "control IPC timed out")
+
+ monkeypatch.setattr(client_manager, "lease_opencode_server", unreachable)
+
+ result = _save_model("deepseek", {"model_id": "deepseek-chat"})
+
+ assert result == {"ok": False, "message": "provider model catalog is unavailable"}
+ assert read_opencode_provider_user_models("deepseek", home=tmp_path) == {}
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 17e750d91..46f93acd9 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -8256,7 +8256,7 @@ def test_refresh_ending_the_last_activity_keeps_the_runs_first_cause(
False,
"failed",
"backend_refresh",
- "[Avibe Harness] This run was interrupted because its Agent runtime was refreshed",
+ "[Avibe Harness] This run was interrupted because its Agent runtime had to be replaced",
),
# A user's cancellation that wins the race is still the user's stop.
("killed", "backend_refresh", True, "canceled", "stopped", "[Avibe Harness] This run was stopped"),
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 664bcf5cd..f7e3a68d3 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -5460,15 +5460,27 @@ def test_forced_refresh_tells_a_restored_conversation_turn_why_it_stopped(manage
assert asyncio.run(restarted.notify_transport_ready("avibe")) == 1
assert [kind for kind, _text in emitted] == ["notify"] * (1 if first_send_delivers else 2)
assert all(
- text.startswith("⚠️ This turn was interrupted — its Agent runtime was restarted")
+ text.startswith("⚠️ This turn was interrupted — its Agent runtime had to be replaced")
for _kind, text in emitted
)
assert stamped == [("m-origin", INTERRUPTED_REACTION_EMOJI)]
+ ("settled_by", "outcome", "session_status", "notice"),
+ [
+ ("backend_refresh", "failed", "failed", "⚠️ This turn was interrupted — its Agent runtime had to be replaced"),
+ ("backend_disabled", "canceled", "idle", "⏹ This turn was stopped because Codex was turned off."),
+ # Running Agents End: the user's own stop, which needs no explanation.
+ ("stopped", "canceled", "idle", None),
+ ],
+ ids=["refresh", "disable", "end"],
+)
def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(
- managers,
+ managers, settled_by, outcome, session_status, notice,
) -> None:
+ """A forced refresh fails an unresolved start, while a disable (RUNTIME-GEN-006)
+ or an End cancels it, since the user chose it. None leaves the start blocking."""
manager, _other, engine, _engine_b, _starts = managers
delivery_id = delivery_store.new_delivery_id()
turn_id = delivery_store.new_turn_id()
@@ -5505,6 +5517,7 @@ def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(
released = await manager.release_for_backend_refresh(
backend="codex",
base_session_ids={"ses_fsm"},
+ settled_by=settled_by,
)
for _ in range(5):
await asyncio.sleep(0)
@@ -5515,8 +5528,9 @@ def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(
assert released == 1
assert _row(engine, delivery_id)["state"] == "retired"
# MH-MIG-012: the refresh retired this conversation's input, so it says so.
- assert [kind for kind, _text in emitted] == ["notify"]
- assert emitted[0][1].startswith("⚠️ This turn was interrupted — its Agent runtime was restarted")
+ assert [kind for kind, _text in emitted] == (["notify"] if notice else [])
+ if notice:
+ assert emitted[0][1].startswith(notice)
with engine.connect() as conn:
turn = delivery_store.get_turn(conn, turn_id)
status = conn.execute(
@@ -5526,9 +5540,9 @@ def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(
).scalar_one()
assert turn is not None
assert turn["state"] == "terminal"
- assert turn["terminal_outcome"] == "failed"
+ assert turn["terminal_outcome"] == outcome
assert turn["terminal_evidence_kind"] == "backend_refresh_start_failed"
- assert status == "failed"
+ assert status == session_status
def test_backend_refresh_defers_successor_activated_by_old_turn_cancellation(
diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.py
index d0bf48fcc..76e6407bd 100644
--- a/tests/test_settings_handler.py
+++ b/tests/test_settings_handler.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock
from unittest.mock import patch
@@ -460,9 +461,6 @@ class _FakeOpenCodeServer:
self.calls: list[str] = []
self.model_hub_models: list[dict | None] = []
- async def ensure_running(self) -> None:
- self.calls.append("ensure_running")
-
async def get_available_agents(self, directory: str) -> list[dict]:
self.calls.append(f"agents:{directory}")
return [{"name": "build"}]
@@ -486,8 +484,10 @@ class _FakeOpenCodeAgent:
def __init__(self, server: _FakeOpenCodeServer) -> None:
self.server = server
- async def _get_server(self) -> _FakeOpenCodeServer:
- return self.server
+ @asynccontextmanager
+ async def current_server(self):
+ self.server.calls.append("current_server")
+ yield self.server
def _make_routing_handler() -> tuple[SettingsHandler, _FakeOpenCodeServer]:
@@ -531,7 +531,7 @@ def test_gather_routing_modal_data_only_fetches_current_backend() -> None:
assert data.current_backend == "opencode"
assert data.registered_backends == ["opencode", "claude", "codex"]
assert server.calls == [
- "ensure_running",
+ "current_server",
"agents:/tmp/workspace",
"models:/tmp/workspace",
"config:/tmp/workspace",
@@ -609,7 +609,7 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> N
"codex": {"gpt-5.4": [{"value": "ultra", "label": "Ultra"}]},
}
assert server.calls == [
- "ensure_running",
+ "current_server",
"agents:/tmp/workspace",
"models:/tmp/workspace",
"config:/tmp/workspace",
@@ -626,7 +626,7 @@ def test_gather_routing_modal_data_hides_disabled_backends() -> None:
assert data.registered_backends == ["opencode"]
assert server.calls == [
- "ensure_running",
+ "current_server",
"agents:/tmp/workspace",
"models:/tmp/workspace",
"config:/tmp/workspace",
@@ -650,7 +650,7 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_is
assert data.registered_backends == ["opencode", "codex"]
assert data.opencode_agents == [{"name": "build"}]
assert server.calls == [
- "ensure_running",
+ "current_server",
"agents:/tmp/workspace",
"models:/tmp/workspace",
"config:/tmp/workspace",
diff --git a/tests/test_skill_observability_backends.py b/tests/test_skill_observability_backends.py
index 5f33f4227..92b314e44 100644
--- a/tests/test_skill_observability_backends.py
+++ b/tests/test_skill_observability_backends.py
@@ -8,11 +8,12 @@ import pytest
from modules.agents.codex.agent import CodexAgent
from modules.agents.opencode.agent import _OpenCodeSteerState, _SteeringAwareOpenCodeServer
+from tests.codex_generation_support import init_generation_state
@pytest.mark.asyncio
async def test_codex_counts_only_positive_injection_acknowledgements(monkeypatch):
- agent = object.__new__(CodexAgent)
+ agent = init_generation_state(object.__new__(CodexAgent))
agent.controller = SimpleNamespace()
agent._read_persisted_prompt_strategy_marker = Mock(return_value=None)
agent._persist_prompt_strategy = Mock(return_value=True)
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 483792b76..bcc02119e 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -10,6 +10,9 @@ from unittest.mock import AsyncMock, Mock
import pytest
+import modules.agents.opencode.client_manager as opencode_client_manager
+from tests.opencode_generation_fakes import lease_via
+from tests.opencode_generation_fakes import ui_lease
from config.v2_config import (
AgentsConfig,
CodexConfig,
@@ -40,7 +43,7 @@ class _PopenFromRun:
return self._stdout, self._stderr
-def test_opencode_options_closes_server_http_session(monkeypatch):
+def test_opencode_options_release_their_controller_lease(monkeypatch):
import config.v2_compat as v2_compat
import modules.agents.opencode as opencode_module
@@ -49,9 +52,6 @@ def test_opencode_options_closes_server_http_session(monkeypatch):
self.closed = 0
self.closed_loop = None
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return [{"name": "build", "mode": "primary", "hidden": False}]
@@ -97,7 +97,7 @@ def test_opencode_options_closes_server_http_session(monkeypatch):
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -108,8 +108,8 @@ def test_opencode_options_closes_server_http_session(monkeypatch):
assert result["ok"] is True
assert result["data"]["defaults"] == {"model": "openai/gpt-5"}
- assert fake_manager.closed == 1
- assert fake_manager.closed_loop is not None
+ # The UI process leases the controller's generation and gives it back.
+ assert [lease.released for lease in opencode_client_manager.lease_opencode_server.leases] == [True]
def test_opencode_options_treats_disabled_model_hub_as_direct(monkeypatch):
@@ -119,9 +119,6 @@ def test_opencode_options_treats_disabled_model_hub_as_direct(monkeypatch):
captured_kwargs = {}
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -171,7 +168,7 @@ def test_opencode_options_treats_disabled_model_hub_as_direct(monkeypatch):
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -181,15 +178,11 @@ def test_opencode_options_treats_disabled_model_hub_as_direct(monkeypatch):
result = asyncio.run(api.opencode_options_async("~/workspace"))
assert result["ok"] is True
- assert "model_hub_overlay_required" not in captured_kwargs
- governor = captured_kwargs["resource_governor"]
- assert governor.mode == "enabled"
- assert governor.config["agent_group_name"] == "ui-agents"
+ assert len(opencode_client_manager.lease_opencode_server.leases) == 1
def test_opencode_options_in_hub_mode_returns_projection_without_server(monkeypatch):
import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
class _ForbiddenServerManager:
@staticmethod
@@ -236,9 +229,9 @@ def test_opencode_options_in_hub_mode_returns_projection_without_server(monkeypa
),
)
monkeypatch.setattr(
- opencode_module,
- "OpenCodeServerManager",
- _ForbiddenServerManager,
+ opencode_client_manager,
+ "lease_opencode_server",
+ lease_via(_ForbiddenServerManager.get_instance),
)
result = asyncio.run(api.opencode_options_async("~/workspace"))
@@ -272,14 +265,8 @@ def test_opencode_options_in_hub_mode_returns_projection_without_server(monkeypa
def test_opencode_empty_hub_projection_does_not_poison_direct_cache(monkeypatch):
import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
class _FakeManager:
- ensure_calls = 0
-
- async def ensure_running(self):
- self.ensure_calls += 1
-
async def get_available_agents(self, directory):
return [{"name": "build"}]
@@ -324,7 +311,7 @@ def test_opencode_empty_hub_projection_does_not_poison_direct_cache(monkeypatch)
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(api, "_read_opencode_config_api_key_provider_ids", AsyncMock(return_value=set()))
monkeypatch.setattr(api, "_read_opencode_custom_provider_ids", AsyncMock(return_value=set()))
monkeypatch.setattr(api, "_read_opencode_user_model_index", AsyncMock(return_value={}))
@@ -339,61 +326,10 @@ def test_opencode_empty_hub_projection_does_not_poison_direct_cache(monkeypatch)
assert hub_result["data"]["agents"] == []
assert direct_result["data"]["agents"] == [{"name": "build"}]
- assert manager.ensure_calls == 1
+ assert len(opencode_client_manager.lease_opencode_server.leases) == 1
assert api._OPENCODE_OPTIONS_CACHE["/tmp/workspace"]["mode"] == "direct"
-def test_opencode_options_rereads_hub_mode_at_launch_boundary(monkeypatch):
- import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
- from modules.agents.opencode import server as opencode_server_module
-
- direct_config = V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- agents=AgentsConfig(),
- runtime=RuntimeConfig(default_cwd="."),
- )
- hub_config = V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- agents=AgentsConfig(),
- runtime=RuntimeConfig(default_cwd="."),
- )
- direct_config.model_hub.agents["opencode"].mode = "direct"
- hub_config.model_hub.agents["opencode"].mode = "hub"
- configs = iter((direct_config, hub_config))
- monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
- monkeypatch.setattr(api, "_OPENCODE_OPTIONS_CACHE", {})
- monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: next(configs)))
- monkeypatch.setattr(
- v2_compat,
- "to_app_config",
- lambda config: SimpleNamespace(
- opencode=SimpleNamespace(
- binary="opencode",
- port=4096,
- request_timeout_seconds=10,
- )
- ),
- )
- monkeypatch.setattr(opencode_module.OpenCodeServerManager, "_instance", None)
- monkeypatch.setattr(
- opencode_server_module,
- "ensure_plugin_installed",
- lambda: (_ for _ in ()).throw(
- AssertionError("Hub refusal must happen before server setup")
- ),
- )
-
- result = asyncio.run(api.opencode_options_async("~/workspace"))
-
- assert result["ok"] is False
- assert "Gateway mode" in result["error"]
-
-
def test_opencode_options_cache_tracks_current_model_hub_projection(monkeypatch):
import config.v2_compat as v2_compat
import modules.agents.opencode as opencode_module
@@ -401,9 +337,6 @@ def test_opencode_options_cache_tracks_current_model_hub_projection(monkeypatch)
projections = []
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -440,7 +373,7 @@ def test_opencode_options_cache_tracks_current_model_hub_projection(monkeypatch)
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -476,19 +409,12 @@ def test_opencode_options_does_not_fall_back_across_model_hub_projections(
monkeypatch,
):
import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
-
- class _FakeManager:
- async def ensure_running(self):
- raise RuntimeError("daemon unavailable")
-
- async def close_http_session(self, *, loop=None):
- pass
class _FakeServerManager:
@staticmethod
async def get_instance(**kwargs):
- return _FakeManager()
+ # The controller has no generation to lease.
+ raise RuntimeError("daemon unavailable")
stale_projection = {"custom/old": {"id": "custom/old"}}
current_projection = {"custom/new": {"id": "custom/new"}}
@@ -520,7 +446,7 @@ def test_opencode_options_does_not_fall_back_across_model_hub_projections(
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
result = asyncio.run(
api.opencode_options_async(
@@ -547,96 +473,15 @@ def test_sync_opencode_options_delegates_snapshot_loading(monkeypatch):
assert calls == ["/tmp/workspace"]
-def test_opencode_get_server_passes_resource_governor_from_v2_runtime(monkeypatch):
- import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
-
- captured_kwargs = {}
- fake_manager = SimpleNamespace(ensure_running=AsyncMock())
-
- class _FakeServerManager:
- @staticmethod
- async def get_instance(**kwargs):
- captured_kwargs.update(kwargs)
- return fake_manager
-
- v2_config = V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- agents=AgentsConfig(),
- runtime=RuntimeConfig(
- default_cwd=".",
- resource_governance={
- "mode": "enabled",
- "agent_group_name": "provider-ui-agents",
- },
- )
- )
- monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: v2_config))
- monkeypatch.setattr(
- v2_compat,
- "to_app_config",
- lambda config: SimpleNamespace(
- opencode=SimpleNamespace(
- binary="opencode",
- port=4096,
- request_timeout_seconds=10,
- )
- ),
- )
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
-
- server = asyncio.run(api._opencode_get_server())
-
- assert server is fake_manager
- fake_manager.ensure_running.assert_awaited_once()
- assert "model_hub_overlay_required" not in captured_kwargs
- governor = captured_kwargs["resource_governor"]
- assert governor.mode == "enabled"
- assert governor.config["agent_group_name"] == "provider-ui-agents"
-
-
-def test_opencode_provider_settings_return_structured_hub_refusal(monkeypatch):
- import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
-
- refusal = opencode_module.OpenCodeModelHubOverlayRequiredError(
- "controller overlay is not ready"
- )
- fake_manager = SimpleNamespace(ensure_running=AsyncMock(side_effect=refusal))
-
- class _FakeServerManager:
- @staticmethod
- async def get_instance(**kwargs):
- return fake_manager
-
- v2_config = V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- agents=AgentsConfig(),
- runtime=RuntimeConfig(default_cwd="."),
- )
- v2_config.model_hub.agents["opencode"].mode = "hub"
- monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: v2_config))
- monkeypatch.setattr(
- v2_compat,
- "to_app_config",
- lambda config: SimpleNamespace(
- opencode=SimpleNamespace(
- binary="opencode",
- port=4096,
- request_timeout_seconds=10,
- )
- ),
- )
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+def test_opencode_provider_settings_report_no_controller_generation(monkeypatch):
+ # The controller had no generation to lease, for example while the Hub
+ # engine is down; the UI process never launches one itself.
+ monkeypatch.setattr(api, "_opencode_lease", AsyncMock(return_value=None))
result = asyncio.run(api.get_opencode_providers_async())
assert result["ok"] is False
- assert fake_manager.ensure_running.await_count == 1
+ api._opencode_lease.assert_awaited_once()
def test_opencode_options_filters_unconfigured_provider_models(monkeypatch, tmp_path):
@@ -644,9 +489,6 @@ def test_opencode_options_filters_unconfigured_provider_models(monkeypatch, tmp_
import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -712,7 +554,7 @@ def test_opencode_options_filters_unconfigured_provider_models(monkeypatch, tmp_
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -733,9 +575,6 @@ def test_opencode_options_keeps_legacy_config_api_key_provider(monkeypatch, tmp_
import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -798,7 +637,7 @@ def test_opencode_options_keeps_legacy_config_api_key_provider(monkeypatch, tmp_
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -819,9 +658,6 @@ def test_opencode_options_does_not_readd_unconfigured_user_model_provider(
import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -890,7 +726,7 @@ def test_opencode_options_does_not_readd_unconfigured_user_model_provider(
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -910,9 +746,6 @@ def test_opencode_options_filters_catalog_provider_with_only_stale_user_model(
import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -987,7 +820,7 @@ def test_opencode_options_filters_catalog_provider_with_only_stale_user_model(
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -1009,9 +842,6 @@ def test_opencode_options_preserves_models_when_provider_catalog_fails(
import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -1051,7 +881,7 @@ def test_opencode_options_preserves_models_when_provider_catalog_fails(
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
monkeypatch.setattr(
opencode_module,
"build_reasoning_effort_options",
@@ -1067,12 +897,8 @@ def test_opencode_options_preserves_models_when_provider_catalog_fails(
def test_opencode_options_overlays_user_configured_models(monkeypatch, tmp_path):
import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -1140,7 +966,7 @@ def test_opencode_options_overlays_user_configured_models(monkeypatch, tmp_path)
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
result = asyncio.run(api.opencode_options_async("/tmp/workspace"))
@@ -1156,12 +982,8 @@ def test_opencode_options_overlays_user_configured_models(monkeypatch, tmp_path)
def test_opencode_options_includes_custom_provider_models(monkeypatch, tmp_path):
import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -1240,7 +1062,7 @@ def test_opencode_options_includes_custom_provider_models(monkeypatch, tmp_path)
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
result = asyncio.run(api.opencode_options_async("/tmp/workspace"))
@@ -1258,12 +1080,8 @@ def test_opencode_options_includes_custom_provider_models(monkeypatch, tmp_path)
def test_opencode_options_includes_keyless_custom_provider_models(monkeypatch, tmp_path):
import config.v2_compat as v2_compat
- import modules.agents.opencode as opencode_module
class _FakeManager:
- async def ensure_running(self):
- return "http://127.0.0.1:4096"
-
async def get_available_agents(self, directory):
return []
@@ -1335,7 +1153,7 @@ def test_opencode_options_includes_keyless_custom_provider_models(monkeypatch, t
)
),
)
- monkeypatch.setattr(opencode_module, "OpenCodeServerManager", _FakeServerManager)
+ monkeypatch.setattr(opencode_client_manager, "lease_opencode_server", lease_via(_FakeServerManager.get_instance))
result = asyncio.run(api.opencode_options_async("/tmp/workspace"))
@@ -1395,7 +1213,7 @@ def test_opencode_provider_catalog_uses_native_models_for_provider_probes(
)
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
result = asyncio.run(api.get_opencode_providers_async())
@@ -1459,7 +1277,7 @@ def test_opencode_provider_catalog_ignores_native_default_models(
return _FakeServer()
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
monkeypatch.setattr(
api,
"load_config",
@@ -1533,7 +1351,7 @@ def test_opencode_provider_catalog_marks_keyless_custom_provider_configured(
)
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
result = asyncio.run(api.get_opencode_providers_async())
@@ -1591,7 +1409,7 @@ def test_opencode_provider_catalog_keeps_custom_provider_without_vibe_meta(
)
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
- monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr(api, "_opencode_lease", ui_lease(_fake_get_server))
result = asyncio.run(api.get_opencode_providers_async())
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 516ff188f..ff1c7e981 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1004,19 +1004,36 @@ def test_cli_stop_process_reuses_runtime_impl(tmp_path, monkeypatch):
assert cli._stop_process(pid_path) is True
-def test_cli_stop_opencode_server_uses_runtime_helpers(tmp_path, monkeypatch):
- pid_file = tmp_path / "opencode_server.json"
- pid_file.write_text('{"pid": 321}', encoding="utf-8")
+def test_cli_stop_opencode_server_stops_every_recorded_generation(tmp_path, monkeypatch):
+ from modules.agents.opencode import server as opencode_server
+ records = tmp_path / "generations"
+ records.mkdir()
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: records)
monkeypatch.setattr(paths, "get_logs_dir", lambda: tmp_path)
- monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 321)
- monkeypatch.setattr(runtime, "get_process_command", lambda pid: "C:\\opencode.exe serve --port=4096")
- from modules.agents.opencode.server import OpenCodeServerManager
-
- monkeypatch.setattr(OpenCodeServerManager, "_terminate_pid_tree_sync", staticmethod(lambda pid, timeout=5: pid == 321))
+ for generation_id, pid, port in (("ocg_a", 321, 50001), ("ocg_b", 322, 50002)):
+ (records / f"{generation_id}.json").write_text(
+ json.dumps({"generation_id": generation_id, "pid": pid, "port": port, "process_created_at": 7.0}),
+ encoding="utf-8",
+ )
+ # A server a release before generations recorded, in its released shape.
+ legacy = tmp_path / "opencode_server.json"
+ legacy.write_text('{"pid": 323, "port": 4096}', encoding="utf-8")
+ ports = {321: 50001, 322: 50002, 323: 4096}
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in ports)
+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: 7.0)
+ monkeypatch.setattr(
+ runtime, "get_process_command", lambda pid: f"C:\\opencode.exe serve --port={ports[pid]}"
+ )
+ stopped: list[int] = []
+ monkeypatch.setattr(
+ opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5: stopped.append(pid) or True
+ )
assert cli._stop_opencode_server() is True
- assert not pid_file.exists()
+ assert sorted(stopped) == [321, 322, 323]
+ assert list(records.iterdir()) == []
+ assert not legacy.exists()
# A server that starts its tool the way OpenCode's shell tool does (detached, so
@@ -5004,3 +5021,48 @@ def test_doctor_bare_dry_run_does_not_request_repair():
assert args.command == "doctor"
assert args.doctor_action is None
assert cli._doctor_repair_requested(args) is False
+
+
+def test_cli_stop_reports_a_surviving_generation_and_drops_stopped_overlays(tmp_path, monkeypatch):
+ from modules.agents.opencode import server as opencode_server
+
+ records = tmp_path / "generations"
+ records.mkdir()
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: records)
+ monkeypatch.setattr(paths, "get_logs_dir", lambda: tmp_path)
+ for generation_id, pid, port in (("ocg_a", 331, 50031), ("ocg_b", 332, 50032)):
+ (records / f"{generation_id}.json").write_text(
+ json.dumps({"generation_id": generation_id, "pid": pid, "port": port}), encoding="utf-8"
+ )
+ # A Hub generation's overlay carries the gateway credential.
+ (records / f"{generation_id}.overlay.json").write_text("{}", encoding="utf-8")
+ ports = {331: 50031, 332: 50032}
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in ports)
+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: f"opencode serve --port={ports[pid]}")
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda pid, timeout=5: pid == 331)
+
+ assert cli._stop_opencode_server() is False
+ assert sorted(path.name for path in records.iterdir()) == ["ocg_b.json", "ocg_b.overlay.json"]
+
+
+def test_cli_stop_forgets_the_record_of_an_opencode_server_that_already_exited(tmp_path, monkeypatch):
+ from modules.agents.opencode import server as opencode_server
+
+ records = tmp_path / "generations"
+ records.mkdir()
+ monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: records)
+ monkeypatch.setattr(paths, "get_logs_dir", lambda: tmp_path)
+ (records / "ocg_exited.json").write_text(
+ json.dumps({"generation_id": "ocg_exited", "pid": 341, "port": 50041}), encoding="utf-8"
+ )
+ # A Hub generation's overlay carries the gateway credential.
+ (records / "ocg_exited.overlay.json").write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: False)
+ def nothing_to_signal(pid, timeout=5):
+ raise AssertionError(f"signalled pid {pid}")
+
+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", nothing_to_signal)
+
+ # Nothing was running, so the stop reports no OpenCode stop.
+ assert cli._stop_opencode_server() is False
+ assert list(records.iterdir()) == []
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 4ec967816..21910e399 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -20,6 +20,7 @@ from unittest.mock import ANY, AsyncMock
import pytest
+from tests.opencode_generation_fakes import lease_returning
from core.agent_auth_service import (
AgentAuthService,
ClaudeOAuthAttempt,
@@ -793,8 +794,6 @@ class _FakeOpencodeServer:
self.messages: list[dict] = []
self.prompt_calls: list[dict] = []
self.abort_calls: list[tuple[str, str]] = []
- self.active_calls: list[str] = []
- self.inactive_calls: list[str] = []
self.message_sent = False
self.recent_error: str | None = None
self.default_agent = "build"
@@ -821,12 +820,6 @@ class _FakeOpencodeServer:
self.prompt_calls.append(kwargs)
self.message_sent = True
- async def mark_run_active(self, session_id):
- self.active_calls.append(session_id)
-
- async def mark_run_inactive(self, session_id):
- self.inactive_calls.append(session_id)
-
async def abort_session(self, session_id, directory):
self.abort_calls.append((session_id, directory))
@@ -868,7 +861,7 @@ def test_start_web_setup_opencode_extracts_url_and_device_code(
"url": "https://auth.openai.com/codex/device",
"instructions": "Enter code: YR8I-QJJUH",
}
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
flow = _run(_start_opencode_flow_without_waiter(service, "openai"))
@@ -899,7 +892,7 @@ def test_start_web_setup_opencode_github_copilot_passes_prompt_answer(
"url": "https://github.com/login/device",
"instructions": "Enter code: 335B-09BE",
}
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
_run(_start_opencode_flow_without_waiter(service, "github-copilot"))
@@ -920,7 +913,7 @@ def test_start_web_setup_opencode_url_only_flow_has_no_device_code(
"url": "https://gitlab.com/oauth/authorize?...",
"instructions": "Your browser will open for authentication.",
}
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
flow = _run(_start_opencode_flow_without_waiter(service, "gitlab"))
assert flow.state == "awaiting_code"
@@ -934,7 +927,7 @@ def test_start_web_setup_opencode_surfaces_server_failure(
"""When the OpenCode daemon isn't reachable, the flow lands in
``failed`` with a typed error string so the UI can render an
actionable sentence rather than ``cli_failed``."""
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=None))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(None))
flow = _run(service.start_web_setup("opencode", provider_id="openai"))
assert flow.state == "failed"
assert flow.error == "opencode_server_unavailable"
@@ -950,7 +943,7 @@ def test_opencode_oauth_success_clears_provider_options_key(
"instructions": "Enter code: YR8I-QJJUH",
}
fake.wait_provider_oauth = AsyncMock(return_value=True)
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
clear_key = AsyncMock()
monkeypatch.setattr(service, "_clear_opencode_provider_options_key_for_oauth", clear_key)
hook_calls: list[str] = []
@@ -996,7 +989,8 @@ def test_opencode_provider_test_returns_excerpt_from_non_text_part(
],
}
]
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ leaser = lease_returning(fake)
+ monkeypatch.setattr(service, "_lease_opencode_server", leaser)
result = _run(service.test_opencode_provider("anthropic"))
@@ -1007,9 +1001,9 @@ def test_opencode_provider_test_returns_excerpt_from_non_text_part(
"providerID": "anthropic",
"modelID": "claude-opus-4.8",
}
- assert fake.active_calls == ["sess_probe"]
assert fake.abort_calls == [("sess_probe", os.path.expanduser("~"))]
- assert fake.inactive_calls == ["sess_probe"]
+ # The probe pins its generation only while it runs.
+ assert [lease.released for lease in leaser.leases] == [True]
def test_opencode_provider_test_uses_provider_catalog_without_agent_model(
@@ -1039,7 +1033,7 @@ def test_opencode_provider_test_uses_provider_catalog_without_agent_model(
"parts": [{"type": "text", "text": "OK"}],
}
]
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
monkeypatch.setattr(
service,
"_resolve_backend_config",
@@ -1089,7 +1083,7 @@ def test_opencode_provider_test_ignores_native_default_models(
"parts": [{"type": "text", "text": "OK"}],
}
]
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
monkeypatch.setattr(
service,
"_resolve_backend_config",
@@ -1139,7 +1133,7 @@ def test_opencode_provider_test_rejects_hub_only_runtime_agent_model(
"parts": [{"type": "text", "text": "OK"}],
}
]
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
monkeypatch.setattr(
service,
"_resolve_backend_config",
@@ -1174,7 +1168,8 @@ def test_opencode_provider_test_surfaces_non_retryable_log_error_before_timeout(
"AI_APICallError (model_not_found) while calling "
'https://relay.example/v1/responses: Model "gpt-5.3-chat-latest" is not supported'
)
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ leaser = lease_returning(fake)
+ monkeypatch.setattr(service, "_lease_opencode_server", leaser)
result = _run(
service.test_opencode_provider(
@@ -1190,7 +1185,8 @@ def test_opencode_provider_test_surfaces_non_retryable_log_error_before_timeout(
assert "not supported" in result["detail"]
assert result["duration_ms"] < 100
assert fake.abort_calls == [("sess_probe", os.path.expanduser("~"))]
- assert fake.inactive_calls == ["sess_probe"]
+ # The probe pins its generation only while it runs.
+ assert [lease.released for lease in leaser.leases] == [True]
def test_opencode_provider_test_classifies_log_error_for_empty_terminal(
@@ -1220,7 +1216,7 @@ def test_opencode_provider_test_classifies_log_error_for_empty_terminal(
"AI_APICallError (model_not_found; HTTP 404): "
'Model "gpt-5.3-chat-latest" is not supported'
)
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
result = _run(
service.test_opencode_provider(
@@ -1271,7 +1267,8 @@ def test_opencode_provider_test_fails_on_empty_terminal_message(
],
}
]
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ leaser = lease_returning(fake)
+ monkeypatch.setattr(service, "_lease_opencode_server", leaser)
result = _run(service.test_opencode_provider("glm", model="glm-5.2"))
@@ -1280,9 +1277,9 @@ def test_opencode_provider_test_fails_on_empty_terminal_message(
assert result["model"] == "glm-5.2"
assert "glm-5.2" in result["detail"]
assert fake.prompt_calls[-1]["reasoning_effort"] is None
- assert fake.active_calls == ["sess_probe"]
assert fake.abort_calls == [("sess_probe", os.path.expanduser("~"))]
- assert fake.inactive_calls == ["sess_probe"]
+ # The probe pins its generation only while it runs.
+ assert [lease.released for lease in leaser.leases] == [True]
def test_opencode_provider_test_uses_catalog_model_casing(
@@ -1310,7 +1307,7 @@ def test_opencode_provider_test_uses_catalog_model_casing(
"parts": [{"type": "text", "text": "OK"}],
}
]
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(fake))
result = _run(service.test_opencode_provider("glm", model="GLM-5.2"))
@@ -2052,7 +2049,7 @@ def test_manual_opencode_pending_callback_has_one_cancellable_owner(service, mon
await asyncio.Event().wait()
provider.wait_provider_oauth = callback
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(provider))
commit = AsyncMock()
monkeypatch.setattr(service, "_commit_web_login", commit)
flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
@@ -2086,7 +2083,7 @@ def test_manual_opencode_expires_without_browser_and_releases_provider_slot(serv
start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
wait_provider_oauth=AsyncMock(),
)
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(provider))
commit = AsyncMock()
monkeypatch.setattr(service, "_commit_web_login", commit)
flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
@@ -2118,7 +2115,7 @@ def test_manual_opencode_cancel_after_callback_completion_preserves_success(serv
start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
wait_provider_oauth=AsyncMock(),
)
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(provider))
commit = AsyncMock()
monkeypatch.setattr(service, "_commit_web_login", commit)
flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
@@ -2149,7 +2146,7 @@ def test_manual_opencode_submission_does_not_extend_callback_deadline(service, m
start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
wait_provider_oauth=callback,
)
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(provider))
commit = AsyncMock()
monkeypatch.setattr(service, "_commit_web_login", commit)
flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
@@ -2176,7 +2173,7 @@ def test_manual_opencode_submit_keeps_start_waiter_and_cancel_before_dispatch_wi
start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
wait_provider_oauth=AsyncMock(),
)
- monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ monkeypatch.setattr(service, "_lease_opencode_server", lease_returning(provider))
commit = AsyncMock()
monkeypatch.setattr(service, "_commit_web_login", commit)
flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
@@ -2195,3 +2192,21 @@ def test_manual_opencode_submit_keeps_start_waiter_and_cancel_before_dispatch_wi
assert not (await service.submit_web_code(flow.flow_id, "stale"))["ok"]
asyncio.run(run())
+
+
+def test_start_web_setup_opencode_releases_its_lease_when_authorize_is_unusable(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # An authorize response with no URL fails setup; nothing else would ever
+ # release the generation this flow pinned for its whole budget.
+ fake = _FakeOpencodeServer()
+ fake.auth_map = {"openai": [{"type": "oauth", "label": "ChatGPT Pro/Plus"}]}
+ fake.next_authorize = {"instructions": "no url"}
+ leaser = lease_returning(fake)
+ monkeypatch.setattr(service, "_lease_opencode_server", leaser)
+
+ flow = _run(service.start_web_setup("opencode", provider_id="openai"))
+
+ assert flow.state == "failed"
+ assert [lease.released for lease in leaser.leases] == [True]
+ assert flow.opencode_lease is None
diff --git a/vibe/api.py b/vibe/api.py
index b2a5f696f..9b1c14d54 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -5784,7 +5784,6 @@ async def opencode_options_async(
model_hub_models: dict[str, Any] | None = None,
) -> dict:
# Expand ~ to user home directory
- request_loop = asyncio.get_running_loop()
expanded_cwd = os.path.expanduser(cwd)
cache_entry = _OPENCODE_OPTIONS_CACHE.get(expanded_cwd, {})
cache_data = cache_entry.get("data")
@@ -5795,17 +5794,16 @@ async def opencode_options_async(
cache_projection_matches = False
cache_mode_matches = cache_entry.get("mode") == "direct"
model_hub_mode = None
- server = None
+ lease = None
try:
from config.v2_compat import to_app_config
from config.v2_config import is_model_hub_enabled
from core.handlers.model_hub import load_opencode_public_models
- from core.resource_governance import AgentResourceGovernor, config_from_runtime
from modules.agents.opencode import (
- OpenCodeServerManager,
build_reasoning_effort_options,
project_opencode_model_hub_models,
)
+ from modules.agents.opencode.client_manager import lease_opencode_server
from modules.agents.opencode.utils import opencode_model_picker_value
v2_config = V2Config.load()
@@ -5899,13 +5897,12 @@ async def opencode_options_async(
}
return {"ok": True, "data": data}
- server = await OpenCodeServerManager.get_instance(
- binary=opencode_config.binary,
- port=opencode_config.port,
- request_timeout_seconds=opencode_config.request_timeout_seconds,
- resource_governor=AgentResourceGovernor(config_from_runtime(v2_config)),
+ # The controller owns every OpenCode process; this process only leases one.
+ lease = await asyncio.wait_for(
+ lease_opencode_server("model options", ttl_seconds=60.0),
+ timeout=timeout_seconds,
)
- await asyncio.wait_for(server.ensure_running(), timeout=timeout_seconds)
+ server = lease.server
agents = await asyncio.wait_for(server.get_available_agents(expanded_cwd), timeout=timeout_seconds)
model_request = (
server.get_available_models(expanded_cwd)
@@ -5984,8 +5981,8 @@ async def opencode_options_async(
return {"ok": True, "data": cache_data, "cached": True, "warning": str(exc)}
return {"ok": False, "error": str(exc)}
finally:
- if server is not None:
- await server.close_http_session(loop=request_loop)
+ if lease is not None:
+ await lease.release()
def _current_platform() -> str:
@@ -9849,26 +9846,13 @@ def _compare_versions(current: str | None, latest: str | None) -> bool:
return cur_is_pre and not new_is_pre
-def _opencode_server_pid() -> int | None:
- pid_path = paths.get_logs_dir() / "opencode_server.json"
- if not pid_path.exists():
- return None
- try:
- info = json.loads(pid_path.read_text(encoding="utf-8"))
- except Exception:
- return None
- pid = info.get("pid") if isinstance(info, dict) else None
- return pid if isinstance(pid, int) and pid > 0 else None
-
-
def _opencode_process_status() -> str:
- from vibe import runtime
+ from modules.agents.opencode.server import recorded_servers
- pid = _opencode_server_pid()
- if not pid or not runtime.pid_alive(pid):
- return "stopped"
- cmd = runtime.get_process_command(pid) or ""
- return "running" if "opencode" in cmd and "serve" in cmd else "unknown"
+ try:
+ return "running" if recorded_servers() else "stopped"
+ except Exception: # noqa: BLE001
+ return "unknown"
def _process_matches_codex_binary(cmdline: list[str], resolved_binary: str | None) -> bool:
@@ -11663,38 +11647,20 @@ def save_claude_auth(payload: dict, *, _native_lease=None) -> dict:
# sync across restarts.
-async def _opencode_get_server():
- """Get the OpenCode server manager for UI-process HTTP calls.
+async def _opencode_lease(purpose: str):
+ """Lease a controller-owned OpenCode generation for UI-process HTTP calls.
- Mirrors the pattern used by ``opencode_options_async``: pull the
- OpenCode config from V2Config and ensure the daemon is reachable.
- In Hub mode only the controller may launch the daemon; this caller
- can adopt an already-running overlaid server. Returns ``None`` if
- OpenCode is disabled or the controller-owned Hub overlay is not ready.
+ The UI process never launches OpenCode. Returns ``None`` only when
+ OpenCode is disabled. When it is enabled, a lease that cannot be had, for
+ example because the controller is unreachable or no generation can start,
+ raises: a caller must never take an unavailable runtime for a disabled one.
"""
from config.v2_compat import to_app_config
- from core.resource_governance import AgentResourceGovernor, config_from_runtime
- from modules.agents.opencode import (
- OpenCodeModelHubOverlayRequiredError,
- OpenCodeServerManager,
- )
+ from modules.agents.opencode.client_manager import lease_opencode_server
- v2_config = V2Config.load()
- config = to_app_config(v2_config)
- if not config.opencode:
- return None
- opencode_config = config.opencode
- server = await OpenCodeServerManager.get_instance(
- binary=opencode_config.binary,
- port=opencode_config.port,
- request_timeout_seconds=opencode_config.request_timeout_seconds,
- resource_governor=AgentResourceGovernor(config_from_runtime(v2_config)),
- )
- try:
- await server.ensure_running()
- except OpenCodeModelHubOverlayRequiredError:
+ if not to_app_config(V2Config.load()).opencode:
return None
- return server
+ return await lease_opencode_server(purpose, ttl_seconds=60.0)
_LOCAL_PROVIDER_IDS = {"ollama", "lmstudio", "lm-studio"}
@@ -12027,11 +11993,11 @@ def _coerce_opencode_provider_catalog(providers_raw) -> dict:
async def _get_opencode_providers_async() -> dict:
"""Build the merged provider catalog reported to the Settings UI."""
- server = await _opencode_get_server()
- if server is None:
+ lease = await _opencode_lease("provider catalog")
+ if lease is None:
return {"ok": False, "message": "OpenCode is disabled in V2Config"}
- request_loop = asyncio.get_running_loop()
+ server = lease.server
try:
providers_raw, auth_raw, config_raw = await asyncio.gather(
server.get_providers(),
@@ -12040,7 +12006,7 @@ async def _get_opencode_providers_async() -> dict:
return_exceptions=False,
)
finally:
- await server.close_http_session(loop=request_loop)
+ await lease.release()
all_providers = _coerce_opencode_provider_catalog(providers_raw)
@@ -12588,12 +12554,16 @@ async def save_opencode_provider_model_async(provider_id: str, payload: dict) ->
except Exception as exc:
logger.debug("OpenCode user-model lookup failed for %s: %s", pid, exc)
- server = await _opencode_get_server()
- request_loop = asyncio.get_running_loop()
try:
- if server is not None:
+ lease = await _opencode_lease("provider model save")
+ except Exception as exc:
+ # Without the live catalog the save could shadow a built-in model.
+ logger.warning("No OpenCode generation to validate %s/%s: %s", pid, model_id, exc)
+ return {"ok": False, "message": "provider model catalog is unavailable"}
+ try:
+ if lease is not None:
try:
- config_raw = await server.get_native_available_models(os.path.expanduser("~"))
+ config_raw = await lease.server.get_native_available_models(os.path.expanduser("~"))
except Exception as exc:
logger.warning(
"OpenCode provider model catalog fetch failed for %s/%s: %s",
@@ -12620,8 +12590,8 @@ async def save_opencode_provider_model_async(provider_id: str, payload: dict) ->
if model_id in model_index and model_id not in existing_user_models:
return {"ok": False, "message": "model_id already exists"}
finally:
- if server is not None:
- await server.close_http_session(loop=request_loop)
+ if lease is not None:
+ await lease.release()
try:
from vibe.opencode_config import upsert_opencode_provider_model
@@ -12931,14 +12901,17 @@ async def save_opencode_provider_auth_async(provider_id: str, payload: dict) ->
async def _delete_opencode_provider_auth_async(provider_id: str) -> dict:
- server = await _opencode_get_server()
- if server is None:
+ try:
+ lease = await _opencode_lease("provider auth removal")
+ except Exception as exc:
+ logger.warning("No OpenCode generation to remove %s auth: %s", provider_id, exc)
+ return {"ok": False, "message": f"OpenCode is unavailable: {exc}"}
+ if lease is None:
return {"ok": False, "message": "OpenCode is disabled in V2Config"}
- request_loop = asyncio.get_running_loop()
try:
- await server.remove_provider_auth(provider_id)
+ await lease.server.remove_provider_auth(provider_id)
finally:
- await server.close_http_session(loop=request_loop)
+ await lease.release()
return {"ok": True}
diff --git a/vibe/cli.py b/vibe/cli.py
index 66837f501..d0c16c275 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -13871,48 +13871,16 @@ def cmd_vibe():
def _stop_opencode_server(runtime_ids: frozenset[str] = frozenset()):
- """Terminate the OpenCode server if running; with ``runtime_ids``, only that Runtime's.
+ """Terminate every recorded OpenCode server; with ``runtime_ids``, only that Runtime's.
A server of another Runtime is left running, as the scoped stop leaves it.
"""
- pid_file = paths.get_logs_dir() / "opencode_server.json"
- if not pid_file.exists():
- return False
-
- try:
- info = json.loads(pid_file.read_text(encoding="utf-8"))
- except Exception as e:
- logger.debug("Failed to parse OpenCode PID file: %s", e)
- return False
-
- pid = info.get("pid") if isinstance(info, dict) else None
- if not isinstance(pid, int) or not _pid_alive(pid):
- pid_file.unlink(missing_ok=True)
- return False
-
- # Verify it's actually an opencode serve process
- cmd = runtime.get_process_command(pid)
- if not cmd:
- logger.debug("Failed to verify OpenCode process (pid=%s): command not available", pid)
- return False
- if "opencode" not in cmd or "serve" not in cmd:
- return False
- try:
- runtime.refuse_foreign_desktop_process(pid, "opencode", runtime_ids)
- except runtime.DesktopRuntimeClaimRefused as refusal:
- logger.warning("Leaving the OpenCode server pid=%s running: %s", pid, refusal)
- return False
-
- # OpenCode starts each tool command in its own session, so stopping only
- # the server pid would leave a running command behind. Stop the whole tree
- # the way the service's own teardown does.
- from modules.agents.opencode.server import OpenCodeServerManager
+ from modules.agents.opencode.server import StopOutcome, stop_recorded_servers_sync
- if OpenCodeServerManager._terminate_pid_tree_sync(pid, timeout=5):
- pid_file.unlink(missing_ok=True)
- return True
- logger.warning("Failed to stop OpenCode server (pid=%s)", pid)
- return False
+ # Forgetting the record of a server that already ended stops nothing.
+ outcomes = stop_recorded_servers_sync(runtime_ids)
+ # One survivor means OpenCode did not stop, however many others did.
+ return bool(outcomes) and all(outcome is StopOutcome.STOPPED for outcome in outcomes)
def _pid_file_points_to_live_process(pid_path: Path) -> bool:
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
index 04ea79d72..957078764 100644
--- a/vibe/codex_config.py
+++ b/vibe/codex_config.py
@@ -17,6 +17,7 @@ changes via ``restart_backend('codex')``.
from __future__ import annotations
import datetime as _dt
+import hashlib
import json
import logging
import os
@@ -618,6 +619,72 @@ def _extract_chatgpt_account(auth_data: dict) -> Optional[Dict[str, Any]]:
}
+def codex_credential_identity(codex_home: Path) -> str:
+ """Digest of the credentials a starting app-server adopts from ``codex_home``.
+
+ A running app-server keeps its loaded credentials. On a 401 it rereads
+ its credential store only for the ChatGPT account it already runs as, and
+ never for an API key. An account switch, a key change, a mode change, or a
+ sign-out therefore needs a new process, while a token refresh does not:
+ tokens are deliberately left out. An account is named by its ChatGPT
+ account id; an older bag that carries none is named by its id_token's
+ subject, or its email, which a refresh keeps and another account does not
+ share.
+
+ Only ``auth.json`` is read. With the ``keyring`` or ``auto`` store, Codex
+ may keep the credential in the OS keyring or in its keyring-encrypted
+ store, which Avibe never reads, so a change made there outside Avibe is
+ adopted at the next renewal. Avibe's own sign-in renews, and an API key
+ Avibe writes pins the file store.
+ """
+ auth = _load_auth(codex_home / "auth.json")
+ store = _load_toml(codex_home / "config.toml").get(CREDENTIALS_STORE_KEY)
+ api_key = auth.get("OPENAI_API_KEY")
+ tokens = auth.get("tokens")
+ account_id = None
+ subject = None
+ if _tokens_bag_is_usable(tokens):
+ claims = _id_token_claims(tokens.get("id_token"))
+ account_id = tokens.get("account_id") if isinstance(tokens.get("account_id"), str) else None
+ if account_id is None:
+ auth_claims = claims.get("https://api.openai.com/auth")
+ claimed = auth_claims.get("chatgpt_account_id") if isinstance(auth_claims, dict) else None
+ account_id = claimed if isinstance(claimed, str) else None
+ subject = next(
+ (claims[name] for name in ("sub", "email") if isinstance(claims.get(name), str) and claims[name]),
+ None,
+ )
+ identity = {
+ "store": store if isinstance(store, str) else "auto",
+ "auth_mode": auth.get("auth_mode") if isinstance(auth.get("auth_mode"), str) else None,
+ "api_key": (
+ hashlib.sha256(api_key.encode()).hexdigest()
+ if isinstance(api_key, str) and api_key
+ else None
+ ),
+ "chatgpt": bool(_tokens_bag_is_usable(tokens)),
+ "account_id": account_id,
+ "subject": subject,
+ }
+ return hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
+
+
+def _id_token_claims(id_token: object) -> Dict[str, Any]:
+ """The id_token's payload claims, unverified; empty when it cannot be read."""
+ if not isinstance(id_token, str):
+ return {}
+ parts = id_token.split(".")
+ if len(parts) < 2:
+ return {}
+ try:
+ import base64
+
+ claims = json.loads(base64.urlsafe_b64decode((parts[1] + "=" * (-len(parts[1]) % 4)).encode("ascii")))
+ except (ValueError, json.JSONDecodeError):
+ return {}
+ return claims if isinstance(claims, dict) else {}
+
+
def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
"""Return the user-visible auth state for the Settings UI.
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index db9107f8d..e3e8fc4bd 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -159,7 +159,8 @@
"noTerminalResult": "[Avibe Harness] This run ended without the Agent producing a result. The turn was released before the Agent replied, so no output was recorded. Check the Agent logs, then run it again if the work still needs doing.",
"stopped": "[Avibe Harness] This run was stopped before the Agent produced a result, so it has no final result. Any output the Agent had already sent is still kept on the run.",
"refusedConcurrentTurn": "[Avibe Harness] This run was skipped because another turn was already in flight for the same session. A session runs one turn at a time; trigger it again once the current turn finishes.",
- "backendRefresh": "[Avibe Harness] This run was interrupted because its Agent runtime was refreshed while the run was in flight, usually right after an Agent setting was saved. Nothing is wrong with the run itself — trigger it again.",
+ "backendRefresh": "[Avibe Harness] This run was interrupted because its Agent runtime had to be replaced while the run was in flight, for example by a credential migration or because too many runtime versions were running at once. Nothing is wrong with the run itself — trigger it again.",
+ "backendDisabled": "[Avibe Harness] This run was stopped because its Agent backend was turned off. Turn the backend on again in Settings, then trigger the run again if the work still needs doing.",
"restarted": "[Avibe Harness] This run was interrupted during execution. Completed work is preserved. Trigger it again if the work still needs doing.",
"interrupted": "[Avibe Harness] This run was interrupted while it was in flight. The interrupted attempt was recorded and was not requeued. Trigger it again if the work still needs doing.",
"orphaned": "[Avibe Harness] Nothing is executing this run, most likely because the service restarted during execution. Completed work is preserved. Trigger it again if the work still needs doing.",
@@ -236,6 +237,7 @@
"reason": {
"stopped": "it was stopped manually",
"backendRefresh": "its Agent runtime was refreshed",
+ "backendDisabled": "its Agent backend was turned off",
"interrupted": "its active execution was interrupted",
"evicted": "its session was evicted",
"restarted": "the service restarted",
@@ -437,10 +439,9 @@
"sessionGeneric": "An error occurred: {error}",
"codexPromptRefreshUnavailable": "Codex could not confirm that it can safely refresh Avibe's instructions for this existing session. Check or update Codex, then retry this turn.",
"codexForkBoundaryUnavailable": "Codex could not determine a safe history boundary for this fork. Wait for the source turn to finish, then retry. If the problem persists, check or update Codex.",
- "codexRuntimeChangeBlocked": "Another Codex turn in this working directory is still running on a different model runtime, so the selected model cannot start yet. Retry this input after that turn finishes, or use a different working directory.",
+ "codexThreadReleaseUnavailable": "Codex could not move this conversation off the app-server it last ran on, because that process is still holding it. Retry this input once the work still running there finishes.",
+ "agentRuntimeRetired": "{agent} was turned off, or Avibe is stopping, so this message was not started. Send it again once {agent} is enabled.",
"codexResponseTooLarge": "Codex returned a response larger than {limitMiB} MiB, so this connection cannot continue. Check or update Codex before retrying.",
- "opencodeModelHubOverlayRequired": "OpenCode is still preparing for Gateway mode. Retry in a moment.",
- "opencodePolicyRefreshPending": "OpenCode is still finishing an existing turn and cannot restart with Avibe's current Skill policy yet. Retry after that turn finishes.",
"opencodeRuntimeConfigInvalid": "OpenCode could not start because OPENCODE_CONFIG_CONTENT is invalid. Fix the runtime configuration and retry.",
"opencodeDirectoryBootstrapTimeout": "OpenCode is still finishing its first-time setup. Send your message again shortly.",
"resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?",
@@ -1040,7 +1041,8 @@
},
"turn": {
"interrupted": {
- "backendRefresh": "⚠️ This turn was interrupted — its Agent runtime was restarted while it was still running, for example after switching between the Model Hub and direct mode or saving Agent settings. Send the request again if the work still needs doing.",
+ "backendRefresh": "⚠️ This turn was interrupted — its Agent runtime had to be replaced while it was still running, for example by a credential migration. Send the request again if the work still needs doing.",
+ "backendDisabled": "⏹ This turn was stopped because {agent} was turned off. Turn it on again in Settings, then send the request again if the work still needs doing.",
"serviceRestart": "⚠️ This turn was interrupted — the Avibe service restarted while it was still running. Send the request again if the work still needs doing."
}
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index b77916c07..e6632aa2b 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -159,7 +159,8 @@
"noTerminalResult": "[Avibe Harness] 本次 run 结束时 Agent 没有产出结果。turn 在 Agent 回复前就被释放,因此没有记录任何输出。请检查 Agent 日志;如果这项工作仍需完成,请重新运行。",
"stopped": "[Avibe Harness] 本次 run 在 Agent 产出结果前被停止,因此没有最终结果。Agent 此前已经发出的输出仍会保留在这次 run 上。",
"refusedConcurrentTurn": "[Avibe Harness] 本次 run 被跳过:同一 session 已有另一个 turn 正在执行。一个 session 同时只运行一个 turn,请在当前 turn 结束后重新触发。",
- "backendRefresh": "[Avibe Harness] 本次 run 执行途中,它所用的 Agent 运行时被刷新,因此被中断,通常发生在刚保存 Agent 设置之后。这次 run 本身没有问题,请重新触发。",
+ "backendRefresh": "[Avibe Harness] 本次 run 执行途中,它所用的 Agent 运行时不得不被替换,因此被中断,例如凭据迁移,或同时运行的运行时版本过多。这次 run 本身没有问题,请重新触发。",
+ "backendDisabled": "[Avibe Harness] 本次 run 已停止,因为它所用的 Agent 后端被关闭了。请在设置中重新开启该后端;如果这项工作仍需完成,再重新触发。",
"restarted": "[Avibe Harness] 本次 run 执行途中被中断。已执行的部分不会丢失,如果这项工作仍需完成,请重新触发。",
"interrupted": "[Avibe Harness] 本次 run 在执行途中被中断。该次执行已被记录,不会重新排队。如果这项工作仍需完成,请重新触发。",
"orphaned": "[Avibe Harness] 本次 run 没有任何执行在推进它,通常是服务在它执行途中重启导致的。已执行的部分不会丢失,如果这项工作仍需完成,请重新触发。",
@@ -236,6 +237,7 @@
"reason": {
"stopped": "被手动停止",
"backendRefresh": "所用的 Agent 运行时被刷新",
+ "backendDisabled": "所用的 Agent 后端被关闭",
"interrupted": "正在执行的任务被中断",
"evicted": "所属会话被回收",
"restarted": "服务重启",
@@ -437,10 +439,9 @@
"sessionGeneric": "发生错误:{error}",
"codexPromptRefreshUnavailable": "Codex 无法确认能否安全刷新此现有会话的 Avibe 指令。请检查或升级 Codex 后重试本回合。",
"codexForkBoundaryUnavailable": "Codex 无法确定此次分叉的安全历史边界。请等待源会话当前回合结束后重试;如果问题持续,请检查或升级 Codex。",
- "codexRuntimeChangeBlocked": "此工作目录中另一个 Codex 回合仍在使用不同的模型运行时,所选模型暂时无法启动。请在该回合结束后重试这条输入,或改用其他工作目录。",
+ "codexThreadReleaseUnavailable": "Codex 无法把这个会话从它上次运行的 app-server 进程上移走,因为该进程仍占用着它。请等那里仍在运行的工作结束后重试这条输入。",
+ "agentRuntimeRetired": "{agent} 已关闭或 Avibe 正在停止,这条消息没有开始执行。请在 {agent} 启用后重新发送。",
"codexResponseTooLarge": "Codex 返回的响应超过 {limitMiB} MiB,此连接无法继续。请检查或升级 Codex 后重试。",
- "opencodeModelHubOverlayRequired": "OpenCode 仍在准备 Gateway 模式,请稍后重试。",
- "opencodePolicyRefreshPending": "OpenCode 仍在完成已有回合,暂时无法按 Avibe 当前的 Skill 策略重启。请在该回合结束后重试。",
"opencodeRuntimeConfigInvalid": "OpenCode 无法启动,因为 OPENCODE_CONFIG_CONTENT 无效。请修正运行时配置后重试。",
"opencodeDirectoryBootstrapTimeout": "OpenCode 仍在完成首次准备,请稍后重新发送消息。",
"resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?",
@@ -1040,7 +1041,8 @@
},
"turn": {
"interrupted": {
- "backendRefresh": "⚠️ 本轮执行被中断——它运行期间 Agent 运行时被重启(例如在模型网关和直连之间切换,或保存了 Agent 设置)。如果这项工作仍然需要完成,请重新发送请求。",
+ "backendRefresh": "⚠️ 本轮执行被中断——它运行期间 Agent 运行时不得不被替换(例如凭据迁移)。如果这项工作仍需完成,请重新发送请求。",
+ "backendDisabled": "⏹ 本轮执行已停止,因为 {agent} 已被关闭。请在设置中重新开启它;如果这项工作仍需完成,再重新发送请求。",
"serviceRestart": "⚠️ 本轮执行被中断——Avibe 服务在它运行期间重启。如果这项工作仍然需要完成,请重新发送请求。"
}
},
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 66ad16620..a7b660783 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -459,6 +459,55 @@ async def backend_application(
return {"status_code": response.status_code, "body": response.json() if response.content else {}}
+async def create_opencode_generation_lease(
+ purpose: str,
+ *,
+ ttl_seconds: float,
+ socket_path: Optional[Path] = None,
+ timeout: float = 180.0,
+) -> dict[str, Any]:
+ """Ask the controller to pin an OpenCode generation; it may start one first."""
+
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
+ timeout=httpx.Timeout(timeout, connect=5.0),
+ ) as client:
+ response = await client.post(
+ "/internal/opencode/generation-leases",
+ json={"purpose": purpose, "ttl_seconds": ttl_seconds},
+ )
+ _validate_response(response, endpoint)
+ 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": response.status_code, "body": response.json() if response.content else {}}
+
+
+async def release_opencode_generation_lease(
+ lease_id: str,
+ *,
+ socket_path: Optional[Path] = None,
+ timeout: float = 10.0,
+) -> dict[str, Any]:
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
+ try:
+ async with httpx.AsyncClient(
+ transport=transport, base_url=endpoint.base_url, headers=endpoint.headers, timeout=timeout,
+ ) as client:
+ response = await client.post(f"/internal/opencode/generation-leases/{lease_id}/release")
+ _validate_response(response, endpoint)
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": response.status_code, "body": response.json() if response.content else {}}
+
+
async def reconcile_agent_backends(
backends: list[str],
*,