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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(codex): bound runtime-change wait behind another active turn (#2205)
Call White9e6b0b964391
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 55db850d4..9316f27c2 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -89,6 +89,10 @@ 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@dataclass(frozen=True)@@ -125,6 +129,12 @@ 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."""++ reason = "transport_runtime_change_blocked"++class CodexModelHubCatalogUnavailableError(RuntimeError):"""The configured Codex binary could not provide Hub launch metadata."""@@ -527,14 +537,20 @@ class CodexAgent(BaseAgent):returnexcept Exception as e:logger.error("Failed to start Codex transport: %s", e, exc_info=True)- await self._record_model_hub_native_failure(request.context, str(e))- if isinstance(e, CodexModelHubCatalogUnavailableError):- language = str(- getattr(getattr(self.controller, "config", None), "language", "en")- or "en"- )+ language = str(+ getattr(getattr(self.controller, "config", None), "language", "en")+ or "en"+ )+ 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)}"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,@@ -657,9 +673,12 @@ class CodexAgent(BaseAgent):# 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)- await self._record_model_hub_native_failure(request.context, str(e))+ 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)@@ -1487,6 +1506,12 @@ class CodexAgent(BaseAgent):or "en")message = i18n_t("error.codexForkBoundaryUnavailable", language)+ elif isinstance(error, CodexRuntimeChangeBlockedError):+ language = str(+ getattr(getattr(self.controller, "config", None), "language", "en")+ or "en"+ )+ message = i18n_t("error.codexRuntimeChangeBlocked", language)else:message = f"Codex error: {error}"@@ -2197,6 +2222,7 @@ class CodexAgent(BaseAgent):if cwd not in self._transport_locks:self._transport_locks[cwd] = asyncio.Lock()+ wait_deadline: float | None = Nonewhile True:wait_for_active_turns = Falseasync with self._transport_locks[cwd], AsyncExitStack() as catalog_pins:@@ -2232,7 +2258,25 @@ class CodexAgent(BaseAgent):logger.info("Restarting Codex transport after Model Hub channel change for cwd=%s", cwd)if wait_for_active_turns:- pass+ 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())diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 3d736e97a..d0706b91d 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -2000,6 +2000,41 @@ 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)+ context = SimpleNamespace(platform_specific={})+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)+ request = SimpleNamespace(+ base_session_id="session-1", working_path="/tmp/work",+ context=context, session_key="settings-1", ack_message_id=None,+ )+ agent.controller = SimpleNamespace(+ config=SimpleNamespace(language="en"), emit_agent_message=AsyncMock(),+ )+ 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._get_or_create_transport = AsyncMock(+ side_effect=_MODULE.CodexRuntimeChangeBlockedError("blocked")+ )+ agent._record_model_hub_native_failure = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())++ await agent.handle_message(request)++ self.assertEqual(+ prewrite_failure_evidence(context),+ {"reason": "transport_runtime_change_blocked", "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])+ agent._event_handler._release_stream_turn.assert_called_once_with(context)+async def test_permanent_resume_failure_holds_only_proven_unwritten_input(self):for error in (CodexResponseTooLargeError(), _MODULE.CodexResumeUnavailableError("thread-old"),@@ -6477,6 +6512,72 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):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"})+async def test_runtime_config_switches_binary_without_catalog_export(self):agent = self._agent()previous_catalog = _catalog_reference("/runtime/codex-old.json")diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 7ab570cc2..b1fc9531e 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -430,6 +430,7 @@"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.","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.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 1afc4f972..29510d707 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -430,6 +430,7 @@"sessionGeneric": "发生错误:{error}","codexPromptRefreshUnavailable": "Codex 无法确认能否安全刷新此现有会话的 Avibe 指令。请检查或升级 Codex 后重试本回合。","codexForkBoundaryUnavailable": "Codex 无法确定此次分叉的安全历史边界。请等待源会话当前回合结束后重试;如果问题持续,请检查或升级 Codex。",+ "codexRuntimeChangeBlocked": "此工作目录中另一个 Codex 回合仍在使用不同的模型运行时,所选模型暂时无法启动。请在该回合结束后重试这条输入,或改用其他工作目录。","codexResponseTooLarge": "Codex 返回的响应超过 {limitMiB} MiB,此连接无法继续。请检查或升级 Codex 后重试。","opencodeModelHubOverlayRequired": "OpenCode 仍在准备 Gateway 模式,请稍后重试。","opencodePolicyRefreshPending": "OpenCode 仍在完成已有回合,暂时无法按 Avibe 当前的 Skill 策略重启。请在该回合结束后重试。",