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(opencode): unblock prewrite session turns
cyh390092cc4876
diff --git a/core/session_turns.py b/core/session_turns.pyindex 3f0039b0b..321c7ffc8 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -33,7 +33,11 @@ from core.message_context import (SCHEDULED_DISPATCH_METADATA_APPLIED_KEY,resolve_turn_sink_key,)-from core.native_dispatch_phase import backend_dispatch_attempted+from core.native_dispatch_phase import (+ DISPATCH_PHASE_PREWRITE,+ backend_dispatch_attempted,+ set_dispatch_phase,+)from core.run_settlement import (NON_COMPLETING_TURN_SETTLEMENTS,SETTLEMENTS_WITHOUT_RESULT,@@ -3284,6 +3288,7 @@ class SessionTurnManager:successor_id: str | None = Noneinterrupt_target_id: str | None = Noneshould_interrupt = False+ should_cancel_prewrite = Falsejoined = Falsewith self._runtime_start_owner(request.session_id,@@ -3567,6 +3572,24 @@ class SessionTurnManager:if claimed_control is None:raise RuntimeError("P0 control-slot claim lost")should_interrupt = current["state"] == "active"+ projected = self.in_flight.get(request.session_id)+ should_cancel_prewrite = bool(+ current["state"] == "starting"+ and projected is not None+ and projected.logical_turn_id == current_id+ and not projected.task.done()+ and backend_dispatch_attempted(projected.context) is False+ )+ if should_cancel_prewrite:+ claimed_control = delivery_store.cas_turn(+ conn,+ current_id,+ expected_version=int(claimed_control["version"]),+ expected_states=("starting",),+ values={"control_state": "interrupting"},+ )+ if claimed_control is None:+ raise RuntimeError("pre-write P0 control claim lost")if current is None and successor_id:await self._start_persisted_turn(successor_id, context=context)@@ -3584,6 +3607,18 @@ class SessionTurnManager:interrupt_target_id,"joined_existing_interrupt",)+ if should_cancel_prewrite:+ canceled = await self._cancel_prewrite_durable_turn(+ request.session_id,+ interrupt_target_id,+ )+ return DeliveryResult(+ delivery_id,+ None,+ str(canceled.get("state") or "reconciling"),+ interrupt_target_id,+ canceled.get("reason"),+ )if not should_interrupt:return DeliveryResult(delivery_id,@@ -3603,6 +3638,66 @@ class SessionTurnManager:interrupted.get("reason"),)+ async def _cancel_prewrite_durable_turn(+ self,+ session_id: str,+ logical_turn_id: str | None,+ ) -> dict[str, Any]:+ """Cancel a live Turn that has definitive evidence of no native write."""++ projected = self.in_flight.get(session_id)+ if (+ projected is None+ or not logical_turn_id+ or projected.logical_turn_id != logical_turn_id+ or projected.task.done()+ or backend_dispatch_attempted(projected.context) is not False+ ):+ return {"state": "reconciling", "reason": "prewrite_owner_changed"}++ projected.cancel_settled_by = SETTLED_BY_STOPPED+ projected.task.cancel()+ await asyncio.gather(projected.task, return_exceptions=True)++ with self._sqlite_engine().connect() as conn:+ turn = delivery_store.get_turn(conn, logical_turn_id)+ initial_delivery_ids = {+ str(row["id"])+ for row in delivery_store.initial_deliveries_for_turn(+ conn,+ logical_turn_id,+ )+ if row["state"] == "claimed"+ }+ if turn is None:+ return {"state": "reconciling", "reason": "turn_missing"}+ if turn["state"] == "terminal":+ return {+ "state": "settled",+ "reason": (+ "prewrite_canceled"+ if turn.get("settled_by") == SETTLED_BY_STOPPED+ else "already_terminal"+ ),+ }++ terminal = self._terminalize_durable_turn(+ logical_turn_id,+ "not_written",+ settled_by=SETTLED_BY_STOPPED,+ evidence_kind="user_stop_before_native_write",+ evidence={"reason": "prewrite_canceled"},+ retire_unwritten_delivery_ids=initial_delivery_ids,+ )+ if not terminal.get("changed"):+ return {"state": "reconciling", "reason": "prewrite_terminal_cas_lost"}++ successor_turn_id = str(terminal.get("successor_turn_id") or "")+ if successor_turn_id:+ await self._start_persisted_turn(successor_turn_id)+ return {"state": "claimed", "reason": "prewrite_canceled"}+ return {"state": "settled", "reason": "prewrite_canceled"}+async def _interrupt_durable_turn(self,session_id: str,@@ -4912,6 +5007,24 @@ class SessionTurnManager:outcome=SETTLED_BY_REFUSED_CONCURRENT_TURN,)if definitive_prewrite_exit:+ if settled_by == SETTLED_BY_STOPPED:+ with self._sqlite_engine().connect() as conn:+ initial_delivery_ids = {+ str(row["id"])+ for row in delivery_store.initial_deliveries_for_turn(+ conn,+ turn_id,+ )+ if row["state"] == "claimed"+ }+ return self._terminalize_durable_turn(+ turn_id,+ "not_written",+ settled_by=SETTLED_BY_STOPPED,+ evidence_kind="user_stop_before_native_write",+ evidence={"reason": "prewrite_canceled"},+ retire_unwritten_delivery_ids=initial_delivery_ids,+ )return self._settle_durable_prewrite_failure(turn_id,outcome=SETTLED_BY_NO_TERMINAL_RESULT,@@ -7056,6 +7169,7 @@ class SessionTurnManager:else:logical_turn_id = logical_turn_id or context_turn_id or uuid.uuid4().hexcontext.platform_specific["turn_token"] = logical_turn_id+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)async def _runner() -> None:cancelled = False@@ -7099,6 +7213,19 @@ class SessionTurnManager:)settled_by = outcome.settled_bydefinitive_prewrite_exit = outcome.backend_dispatch_attempted is False+ current = self.in_flight.get(str(session_id or ""))+ if (+ definitive_prewrite_exit+ and current is not None+ and current.task is asyncio.current_task()+ and current.logical_turn_id == logical_turn_id+ and current.cancel_settled_by == SETTLED_BY_STOPPED+ ):+ # OpenCode intentionally absorbs the inner cancellation after+ # cleaning up its request. Preserve the Stop attribution at+ # this outer durable boundary so the input is retired instead+ # of becoming a queued retry.+ settled_by = SETTLED_BY_STOPPEDexcept asyncio.CancelledError:cancelled = True# Do NOT decide the reason here: the canceller knows it, and it isdiff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex f14e9faf6..674de7343 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -452,7 +452,7 @@ class OpenCodeServerManager:return isinstance(active, list) and bool(active)async def configure_model_hub_overlay(self, overlay: Any | None) -> None:- """Apply a runtime-only overlay after all active OpenCode work drains."""+ """Apply a changed runtime-only overlay after active OpenCode work drains."""desired_path = str(overlay.path) if overlay is not None else Nonedesired_hash = str(overlay.content_hash) if overlay is not None else None@@ -467,11 +467,27 @@ class OpenCodeServerManager:while True:should_wait = Falseasync with self._get_lock():+ 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 because no runtime mutation+ # is required. Cache the content so a later crash still restarts+ # with the same OPENCODE_CONFIG.+ 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+ return+if self._active_requests > 0 or self._has_active_run_sessions():should_wait = Trueelse:- info = self._read_pid_file() or {}- current_server = self._pid_file_references_current_server(info)persisted_active = current_server and bool(info.get("active_run_sessions"))if persisted_active and time.monotonic() < drain_deadline:should_wait = True@@ -481,20 +497,9 @@ class OpenCodeServerManager:"Ignoring stale OpenCode active-run metadata after %.1fs overlay drain timeout",self._model_hub_overlay_drain_timeout_seconds,)- 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-- # Cache the desired state even when adopted pid metadata- # already matches. A later crash must restart with the- # same OPENCODE_CONFIG without relying on the old pid file.self._model_hub_overlay_path = desired_pathself._model_hub_overlay_hash = desired_hashself._model_hub_overlay_content = desired_content- if (effective_path, effective_hash) == (desired_path, desired_hash):- returnif await self._is_healthy():logger.info("Restarting OpenCode server after Model Hub overlay change")await self._restart_for_auth_refresh_locked()diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex cc25f1e43..79ce124ac 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -73,6 +73,7 @@ capabilities:- tests/test_model_hub_resolution.py- tests/test_model_hub_injection.py- tests/test_model_hub_runtime.py+ - tests/test_opencode_server.py- id: harness_failure_recoveryname: Harness per-Session failure recoverystatus: activediff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex a8e1932be..7cd4dcc01 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -140,6 +140,12 @@ scenarios:kind: recoverylayer: contracttest: tests/test_agent_steering.py::test_message_delivery_021_opencode_preserves_native_order_and_recovers_exact_part+ - id: MESSAGE-DELIVERY-022+ name: Stop retires a starting Turn that has not reached the native write boundary+ status: covered+ kind: lifecycle+ layer: contract+ test: tests/test_session_delivery_fsm.py::test_stop_cancels_a_starting_turn_before_native_write- id: MESSAGE-DELIVERY-101name: Unresolved fallback-capable delivery fences only later FIFO submissionsstatus: covereddiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 6a23e83a9..99af08337 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -8,6 +8,7 @@ capability:- tests/test_model_hub_resolution.py- tests/test_model_hub_injection.py- tests/test_model_hub_runtime.py+ - tests/test_opencode_server.py- tests/scenarios/model_hub/test_model_hub_catalog.py- tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py- tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -98,6 +99,12 @@ scenarios:layer: unitmissing_layer: scenariotest: 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-RES-LIVE-001name: Live turn retries an eligible backup before streaming startsstatus: covereddiff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex 7b7fb6d12..48c843b5d 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -2344,5 +2344,62 @@ async def _async_none():return None+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]++ asyncio.run(+ asyncio.wait_for(+ manager.configure_model_hub_overlay(None),+ timeout=0.1,+ )+ )++ 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 = types.SimpleNamespace(+ path=Path("/tmp/new-overlay.json"),+ content_hash="new-hash",+ content='{"provider": {}}',+ )++ 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()+ await asyncio.wait_for(configuring, timeout=0.2)++ 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()++if __name__ == "__main__":unittest.main()diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 78159a387..bdba0ddf9 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -3275,6 +3275,64 @@ def test_empty_p0_uses_the_control_slot_without_creating_a_message_delivery(manaasyncio.run(run())+def test_stop_cancels_a_starting_turn_before_native_write(managers, monkeypatch) -> None:+ """MESSAGE-DELIVERY-022: Stop retires a definitively unwritten input."""++ manager, _other, engine, _engine_b, _starts = managers+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)+ dispatch_entered = asyncio.Event()++ async def blocked_prewrite_dispatch(*_args, **_kwargs):+ dispatch_entered.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ # OpenCode absorbs cancellation after cleaning up its inner request+ # task, so lock that adapter behavior into the shared Stop contract.+ return TurnDispatchOutcome(+ error=None,+ settled_by=None,+ backend_dispatch_attempted=False,+ )++ monkeypatch.setattr(+ "core.session_turns.dispatch_turn_with_outcome",+ blocked_prewrite_dispatch,+ )++ async def run() -> tuple[dict, str, str]:+ admitted = await manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p3",+ content="stop before native write",+ ),+ context=_context(),+ )+ assert admitted.turn_id and admitted.delivery_id+ await asyncio.wait_for(dispatch_entered.wait(), timeout=1.0)+ stopped = await manager.cancel("ses_fsm")+ return stopped, str(admitted.turn_id), str(admitted.delivery_id)++ stopped, turn_id, delivery_id = asyncio.run(run())++ assert stopped == {+ "ok": True,+ "session_id": "ses_fsm",+ "status": "stale_released",+ "reason": "prewrite_canceled",+ }+ assert "ses_fsm" not in manager.in_flight+ manager.controller.command_handler.handle_stop.assert_not_awaited()+ with engine.connect() as conn:+ turn = delivery_store.get_turn(conn, turn_id)+ assert turn is not None+ assert turn["state"] == "terminal"+ assert turn["terminal_outcome"] == "not_written"+ assert turn["settled_by"] == SETTLED_BY_STOPPED+ assert _row(engine, delivery_id)["state"] == "retired"++def test_empty_p0_terminal_race_still_resumes_the_queued_head(managers,monkeypatch,