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): preserve native message ordering (#1208)
Call White31fea23f6e6c
diff --git a/docs/plans/session-delivery-foundation.md b/docs/plans/session-delivery-foundation.mdindex 4f57f1830..a4d2d3cf3 100644--- a/docs/plans/session-delivery-foundation.md+++ b/docs/plans/session-delivery-foundation.md@@ -92,10 +92,11 @@ that batch and releases the Session. OpenCode retains its stronger exact-attemptreconciliation. A definitive pre-write start failure requeues the entire claimedbatch in its original order. A late event for T1 cannot mutate T2.-OpenCode writes the persisted Delivery attempt ID as the native `messageID`.-After restart, reconciliation reads that exact native Message without issuing a-second prompt: exact presence accepts, while absence or transport uncertainty-remains blocked.+OpenCode generates every native `messageID` at the actual write and stores the+persisted Delivery attempt ID as the exact ID of the user Message's text part.+After restart, reconciliation lists that native Session's Messages without+issuing a second prompt: an exact user-part match accepts and returns its native+Message ID, while absence or transport uncertainty remains blocked.Terminal settlement, the next compatible FIFO claim, and the Session statusprojection share one writer transaction. Result evidence is committed only afterdiff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 456502df7..1505f034d 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -56,8 +56,7 @@ from .poll_loop import OpenCodePollLoop, restored_platform_from_poll_info, restofrom .server import (OpenCodePromptRejectedError,OpenCodeServerManager,- native_message_id_for_attempt,- native_message_ids_for_attempt,+ native_part_id_for_attempt,)from .session import OpenCodeResumeUnavailableError, OpenCodeSessionManagerfrom .utils import resolve_opencode_model_id, resolve_opencode_reasoning_effort@@ -68,6 +67,9 @@ _STATUS_RECONCILIATION_FAILURE_LIMIT = 3# OpenCode returns 204 after forking prompt work, before that worker necessarily# registers the session as busy._ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS = 5.0+# OpenCode can report idle just before the completed assistant message becomes+# visible through the message-list endpoint.+_ASYNC_PROMPT_RESULT_CONFIRMATION_TIMEOUT_SECONDS = 5.0# A prompt accepted at the end of the previous native turn can race its final# status transition. Let that transition settle before trusting the write as a# same-turn steer.@@ -100,6 +102,7 @@ class _OpenCodeSteerState:awaiting_user_text: str | None = Noneawaiting_start_confirmation_deadline: float | None = Noneawaiting_active_status_observed: bool = False+ awaiting_result_confirmation_deadline: float | None = Noneidle_reconciliation_message: str = ""restored: bool = Falsereconcile_initial_status: bool = False@@ -245,6 +248,7 @@ class _SteeringAwareOpenCodeServer:self._state.awaiting_user_text = Noneself._state.awaiting_start_confirmation_deadline = Noneself._state.awaiting_active_status_observed = False+ self._state.awaiting_result_confirmation_deadline = Nonedef _terminal_reconciliation_failure(self,@@ -345,6 +349,7 @@ class _SteeringAwareOpenCodeServer:>= 0):self._state.awaiting_active_status_observed = True+ self._state.awaiting_result_confirmation_deadline = Noneif reconcile_initial_status and awaiting is None:self._state.awaiting_after_message_ids = (self._completed_assistant_boundary(messages)@@ -400,6 +405,26 @@ class _SteeringAwareOpenCodeServer:and time.monotonic() < start_deadline):wait_for_insert = True+ elif self._state.awaiting_active_status_observed:+ result_deadline = (+ self._state.awaiting_result_confirmation_deadline+ )+ if result_deadline is None:+ self._state.awaiting_result_confirmation_deadline = (+ time.monotonic()+ + _ASYNC_PROMPT_RESULT_CONFIRMATION_TIMEOUT_SECONDS+ )+ wait_for_insert = True+ elif time.monotonic() < result_deadline:+ wait_for_insert = True+ else:+ self._clear_awaiting_reconciliation()+ return self._terminal_reconciliation_failure(+ session_id,+ messages,+ name="NativeSessionEndedBeforeResult",+ message=self._idle_reconciliation_error_text(),+ )else:self._clear_awaiting_reconciliation()return self._terminal_reconciliation_failure(@@ -1053,8 +1078,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):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 message ID can now rebuild the- # poll and Turn owner even if no post-prompt Python statement ran.+ # A crash after OpenCode accepts the exact attempt part can now rebuild+ # the poll and Turn owner even if no post-prompt Python statement ran.self.sessions.add_active_poll(opencode_session_id=session_id,base_session_id=request.base_session_id,@@ -1081,11 +1106,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):session_id=session_id,directory=request.working_path,text=prompt_text,- message_id=(- native_message_id_for_attempt(start_attempt_id)- if start_attempt_id- else None- ),+ attempt_id=start_attempt_id or None,agent=agent_to_use,model=model_dict,reasoning_effort=reasoning_effort,@@ -1408,9 +1429,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):"tools": {"question": False},}if request.attempt_id:- prompt_kwargs["message_id"] = native_message_id_for_attempt(- request.attempt_id- )+ prompt_kwargs["attempt_id"] = request.attempt_idawait server.prompt_async(**prompt_kwargs,)@@ -1515,7 +1534,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request: SteerReconcileRequest,target: ActiveSteerTarget,) -> SteerResult:- """Resolve one prior OpenCode write by its native message identity."""+ """Resolve one prior OpenCode write by its exact native part identity."""if not request.attempt_id:return steer_result(@@ -1550,40 +1569,43 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):reason="runtime_unavailable",backend=self.name,)- diagnostics: list[str] = []- observed_evidence = False- for native_message_id in native_message_ids_for_attempt(request.attempt_id):- try:- message = await server.get_message(- native_session_id,- native_message_id,- directory,- )- except Exception as exc: # noqa: BLE001 - absence is not negative proof- diagnostics.append(str(exc))- continue- observed_evidence = True+ native_part_id = native_part_id_for_attempt(request.attempt_id)+ try:+ messages = await server.list_messages(+ native_session_id,+ directory,+ )+ 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),+ )+ for message in messages:info = message.get("info") if isinstance(message, dict) else None+ parts = message.get("parts") if isinstance(message, dict) else Noneif (isinstance(info, dict)- and str(info.get("id") or "") == native_message_idand info.get("role") == "user"+ and isinstance(parts, list)+ and any(+ isinstance(part, dict)+ and str(part.get("id") or "") == native_part_id+ for part in parts+ )):return steer_result(SteerOutcome.ACCEPTED,- reason="native_message_found",+ reason="native_attempt_part_found",backend=self.name,- native_message_id=native_message_id,+ native_message_id=str(info.get("id") or ""),+ native_part_id=native_part_id,)return steer_result(SteerOutcome.UNKNOWN,- reason=(- "untrusted_attempt_evidence"- if observed_evidence- else "attempt_evidence_unavailable"- ),+ reason="untrusted_attempt_evidence",backend=self.name,- diagnostic="; ".join(diagnostics),)async def handle_stop(self, request: AgentRequest) -> bool:@@ -1762,14 +1784,19 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):verification_unknown = Truebaseline_message_ids = set(poll_info.baseline_message_ids)- start_attempt_message_ids = set(- native_message_ids_for_attempt(start_attempt_id)+ start_attempt_part_id = (+ native_part_id_for_attempt(start_attempt_id)+ if start_attempt_id+ else "")start_attempt_found = any(- start_attempt_message_ids+ start_attempt_part_idand message.get("info", {}).get("role") == "user"- and str(message.get("info", {}).get("id") or "")- in start_attempt_message_ids+ 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 = Falsediff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex da74d31d2..f14e9faf6 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -46,6 +46,7 @@ OPENCODE_LOG_TAIL_BYTES = 2_000_000MODEL_HUB_OVERLAY_DRAIN_TIMEOUT_SECONDS = 30.0_USE_CURRENT_CALLER_CONTEXT_PATH = object()_CURRENT_OWNER_PID = os.getpid()+_DURABLE_ATTEMPT_ID_RE = re.compile(r"^atm_([0-9a-f]{32})$")def _percent_encode_path(path: str) -> str:@@ -59,26 +60,14 @@ def _percent_encode_path(path: str) -> str:return _url_quote(path, safe="/")-def native_message_id_for_attempt(attempt_id: str) -> str:- """Map one durable attempt identity into OpenCode's message namespace."""+def native_part_id_for_attempt(attempt_id: str) -> str:+ """Map one durable attempt into OpenCode's part namespace."""value = str(attempt_id or "").strip()- if not value.startswith("atm") or len(value) == 3:- raise ValueError("OpenCode prompt attempt identity must start with 'atm'")- return f"msg{value[3:]}"---def native_message_ids_for_attempt(attempt_id: str) -> tuple[str, ...]:- """Return current and legacy native identities for exact evidence reads."""-- value = str(attempt_id or "").strip()- if not value:- return ()- try:- current = native_message_id_for_attempt(value)- except ValueError:- return (value,)- return (current, value) if current != value else (value,)+ match = _DURABLE_ATTEMPT_ID_RE.fullmatch(value)+ if match is None:+ raise ValueError("OpenCode prompt attempt identity is not canonical")+ return f"prt_{match.group(1)}"class OpenCodePromptRejectedError(RuntimeError):@@ -1590,7 +1579,7 @@ class OpenCodeServerManager:session_id: str,directory: str,text: str,- message_id: Optional[str] = None,+ attempt_id: Optional[str] = None,agent: Optional[str] = None,model: Optional[Dict[str, str]] = None,reasoning_effort: Optional[str] = None,@@ -1603,11 +1592,12 @@ class OpenCodeServerManager:async with self._request_scope():session = await self._get_http_session()+ text_part: Dict[str, Any] = {"type": "text", "text": text}+ if attempt_id:+ text_part["id"] = native_part_id_for_attempt(attempt_id)body: Dict[str, Any] = {- "parts": [{"type": "text", "text": text}],+ "parts": [text_part],}- if message_id:- body["messageID"] = message_idif agent:body["agent"] = agentif model:diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 6ad34bb9b..988c28421 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -134,6 +134,12 @@ scenarios:kind: recoverylayer: contracttest: tests/test_session_delivery_fsm.py::test_permanent_start_rejection_retires_delivery_without_retry+ - id: MESSAGE-DELIVERY-021+ name: Durable OpenCode attempts preserve native order through exact part evidence+ status: covered+ kind: recovery+ layer: contract+ test: tests/test_agent_steering.py::test_message_delivery_021_opencode_preserves_native_order_and_recovers_exact_part- id: MESSAGE-DELIVERY-101name: Unresolved fallback-capable delivery fences only later FIFO submissionsstatus: covereddiff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex 6cc17b99b..f173b05dc 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -32,6 +32,7 @@ from modules.im import MessageContextSTEER_TEXT = "补充:**不要改写**\n```python\nprint('λ')\n```"+ATTEMPT_ID = "atm_1234567890abcdef1234567890abcdef"def test_steer_outcomes_are_exhaustive() -> None:@@ -149,13 +150,17 @@ class _OpenCodeServer:await self.release_prompt.wait()if self.error is not None:raise self.error+ attempt_id = kwargs.get("attempt_id")+ part = {"type": "text", "text": kwargs["text"]}+ if attempt_id:+ part["id"] = f"prt_{attempt_id.removeprefix('atm_')}"self.messages.append({"info": {- "id": kwargs.get("message_id") or f"steer-user-{len(self.prompt_calls)}",+ "id": f"steer-user-{len(self.prompt_calls)}","role": "user",},- "parts": [{"type": "text", "text": kwargs["text"]}],+ "parts": [part],})@@ -653,13 +658,31 @@ async def test_opencode_keeps_reconciliation_armed_after_post_write_idle() -> No@pytest.mark.anyio-async def test_opencode_reconciles_exact_native_attempt_without_resteering() -> None:+async def test_message_delivery_021_opencode_preserves_native_order_and_recovers_exact_part() -> None:+ """Scenario: MESSAGE-DELIVERY-021."""primary = _primary_request(backend="opencode")gate_task = await _held_task()- server = _OpenCodeServer()+ server = _OpenCodeServer(+ messages=[+ {+ "info": {"id": "primary-user", "role": "user"},+ "parts": [{"type": "text", "text": "primary"}],+ },+ {+ "info": {+ "id": "primary-assistant",+ "role": "assistant",+ "parentID": "primary-user",+ "time": {"completed": 1},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "primary result"}],+ },+ ]+ )agent = _opencode_agent(primary, gate_task, server)controller = _controller_with_active_gate(agent, primary, gate_task)- attempt_id = "atm_exact_restart_evidence"+ attempt_id = ATTEMPT_IDtry:identity = active_steer_identity(controller, "opencode", "avibe-session")assert identity is not None@@ -675,41 +698,37 @@ async def test_opencode_reconciles_exact_native_attempt_without_resteering() ->),)assert receipt.outcome is SteerOutcome.ACCEPTED- assert server.prompt_calls[0]["message_id"] == "msg_exact_restart_evidence"-- reconciled = await reconcile_steer_attempt(- controller,- "opencode",- SteerReconcileRequest(- target_session_id="avibe-session",- expected_logical_turn_id=identity[0],- expected_native_turn_id=identity[1],- attempt_id=attempt_id,- ),+ assert server.prompt_calls[0]["attempt_id"] == ATTEMPT_ID+ assert "message_id" not in server.prompt_calls[0]+ inserted_user = server.messages[-1]+ server.messages.append(+ {+ "info": {+ "id": "steer-assistant-1",+ "role": "assistant",+ "parentID": inserted_user["info"]["id"],+ "time": {"completed": 2},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "steer result"}],+ })- assert reconciled.outcome is SteerOutcome.ACCEPTED- assert reconciled.details["native_message_id"] == "msg_exact_restart_evidence"- assert len(server.prompt_calls) == 1- finally:- await _cancel_tasks(gate_task)---async def test_opencode_reconciles_legacy_native_attempt_without_resteering() -> None:- primary = _primary_request(backend="opencode")- gate_task = await _held_task()- attempt_id = "atm_legacy_restart_evidence"- server = _OpenCodeServer(- messages=[- {"info": {"id": attempt_id, "role": "user"}, "parts": []},+ assert [message["info"]["id"] for message in server.messages] == [+ "primary-user",+ "primary-assistant",+ "steer-user-1",+ "steer-assistant-1",]- )- agent = _opencode_agent(primary, gate_task, server)- controller = _controller_with_active_gate(agent, primary, gate_task)- try:- identity = active_steer_identity(controller, "opencode", "avibe-session")- assert identity is not None+ assert inserted_user["parts"] == [+ {+ "type": "text",+ "text": STEER_TEXT,+ "id": "prt_1234567890abcdef1234567890abcdef",+ }+ ]+ assert server.messages[-1]["info"]["parentID"] == "steer-user-1"+reconciled = await reconcile_steer_attempt(controller,"opencode",@@ -722,8 +741,8 @@ async def test_opencode_reconciles_legacy_native_attempt_without_resteering() ->)assert reconciled.outcome is SteerOutcome.ACCEPTED- assert reconciled.details["native_message_id"] == attempt_id- assert server.prompt_calls == []+ assert reconciled.details["native_message_id"] == "steer-user-1"+ assert len(server.prompt_calls) == 1finally:await _cancel_tasks(gate_task)@@ -996,7 +1015,7 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanureconciliation_fails: bool,) -> None:primary = _primary_request(backend="opencode")- primary.context.platform_specific["delivery_start_attempt_id"] = "atm-start"+ primary.context.platform_specific["delivery_start_attempt_id"] = ATTEMPT_IDevents: list[str] = []class _Server:@@ -1117,9 +1136,9 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanuawait agent._process_message(primary)expected_reconciliation = (- "invalid:logical-turn:atm-start:opencode"+ f"invalid:logical-turn:{ATTEMPT_ID}:opencode"if status == 400- else "reconcile:logical-turn:atm-start:opencode"+ else f"reconcile:logical-turn:{ATTEMPT_ID}:opencode")assert events[:3] == ["persist_poll",@@ -1136,7 +1155,7 @@ async def test_opencode_ambiguous_start_failure_preserves_recovery_poll(monkeypatch,) -> None:primary = _primary_request(backend="opencode")- primary.context.platform_specific["delivery_start_attempt_id"] = "atm-start"+ primary.context.platform_specific["delivery_start_attempt_id"] = ATTEMPT_IDevents: list[str] = []class _Server:@@ -1526,6 +1545,57 @@ async def test_opencode_accepted_prompt_waits_for_delayed_busy_registration() ->await _cancel_tasks(gate_task)+async def test_opencode_idle_waits_for_delayed_terminal_message_visibility() -> None:+ primary = _primary_request(backend="opencode")+ gate_task = await _held_task()++ class _DelayedFinalServer(_OpenCodeServer):+ async def list_messages(self, session_id: str, directory: str) -> list[dict]:+ if self.list_calls == 2:+ self.messages.append(+ {+ "info": {+ "id": "follow-up-assistant",+ "role": "assistant",+ "time": {"completed": 2},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "answered"}],+ }+ )+ return await super().list_messages(session_id, directory)++ server = _DelayedFinalServer(+ messages=[+ {+ "info": {"id": "follow-up-user", "role": "user"},+ "parts": [{"type": "text", "text": "follow-up"}],+ }+ ],+ status_responses=[{"type": "busy"}, {"type": "idle"}, {"type": "idle"}],+ )+ agent = _opencode_agent(primary, gate_task, server)+ state = agent._steering_states[primary.base_session_id]+ state.awaiting_after_message_ids = set()+ state.awaiting_user_text = "follow-up"+ state.awaiting_start_confirmation_deadline = time.monotonic() - 1+ poll_server = _SteeringAwareOpenCodeServer(server, state)+ try:+ messages = await asyncio.wait_for(+ poll_server.list_messages("opencode-session", primary.working_path),+ timeout=1,+ )++ assert messages[-1]["info"]["id"] == "follow-up-assistant"+ assert state.terminal_status_failure_messages is None+ assert state.awaiting_after_message_ids is None+ assert state.closing is True+ assert server.list_calls == 3+ finally:+ await _cancel_tasks(gate_task)++@pytest.mark.anyioasync def test_opencode_accepted_prompt_idle_start_timeout_is_terminal() -> None:primary = _primary_request(backend="opencode")diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 7e3caee9a..2203ce381 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -30,6 +30,9 @@ from modules.agents.opencode.poll_loop import OpenCodePollLoopfrom modules.agents.opencode.utils import resolve_opencode_reasoning_effort+ATTEMPT_ID = "atm_1234567890abcdef1234567890abcdef"++@dataclassclass _StubConfig(BaseIMConfig):def validate(self) -> None:@@ -820,7 +823,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():platform_specific={"agent_session_id": "ses_test","turn_token": "logical-turn",- "delivery_start_attempt_id": "atm_initial_start",+ "delivery_start_attempt_id": ATTEMPT_ID,},),message="hello",@@ -838,7 +841,8 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():assert calls[0]["tools"] == {"question": False}assert calls[0]["model"] == {"providerID": "openai", "modelID": "gpt-5.4"}assert calls[0]["reasoning_effort"] == "high"- assert calls[0]["message_id"] == "msg_initial_start"+ assert calls[0]["attempt_id"] == ATTEMPT_ID+ assert "message_id" not in calls[0]assert recovery_order[:3] == ["poll", "prompt", "accepted"]assert active_poll_updates[0][0] == "oc-session"assert isinstance(active_poll_updates[0][1]["prompt_started_at"], float)diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.pyindex ff3d3c90a..75c08ce87 100644--- a/tests/test_opencode_restore_polls.py+++ b/tests/test_opencode_restore_polls.py@@ -26,6 +26,10 @@ from core.services.agent_steering import SteerOutcome, SteerRequest, active_steefrom modules.agents.opencode.agent import OpenCodeAgent # noqa: E402+ATTEMPT_ID = "atm_1234567890abcdef1234567890abcdef"+NATIVE_PART_ID = "prt_1234567890abcdef1234567890abcdef"++def _make_poll(*, platform: str, base_session_id: str, opencode_session_id: str) -> ActivePollInfo:return ActivePollInfo(opencode_session_id=opencode_session_id,@@ -338,7 +342,7 @@ def test_restore_preserves_durable_poll_when_verification_is_temporarily_unavail)poll.processing_indicator = {"platform": "avibe",- "delivery_start_attempt_id": "atm-unknown",+ "delivery_start_attempt_id": ATTEMPT_ID,"opencode_native_steering": {"target_session_id": "ses_wb","logical_turn_id": "turn-unknown",@@ -365,18 +369,7 @@ def test_restore_preserves_durable_poll_when_verification_is_temporarily_unavailassert removed == []- ("attempt_id", "native_message_id"),- [- ("atm-start", "msg-start"),- ("atm-start", "atm-start"),- ("legacy-start", "legacy-start"),- ],-)-def test_restore_rebuilds_completed_exact_start_attempt(- attempt_id: str,- native_message_id: str,-) -> None:+def test_restore_rebuilds_completed_exact_start_attempt() -> None:poll = _make_poll(platform="avibe",base_session_id="ses_wb",@@ -384,7 +377,7 @@ def test_restore_rebuilds_completed_exact_start_attempt()poll.processing_indicator = {"platform": "avibe",- "delivery_start_attempt_id": attempt_id,+ "delivery_start_attempt_id": ATTEMPT_ID,"opencode_native_steering": {"target_session_id": "ses_wb","logical_turn_id": "logical-start",@@ -392,7 +385,10 @@ def test_restore_rebuilds_completed_exact_start_attempt(}agent, _, removed, _ = _build_agent({"oc-1": poll})agent._test_server.messages = [- {"info": {"id": native_message_id, "role": "user", "time": {}}},+ {+ "info": {"id": "native-start-user", "role": "user", "time": {}},+ "parts": [{"id": NATIVE_PART_ID, "type": "text", "text": "hello"}],+ },{"info": {"id": "assistant-done",@@ -445,7 +441,7 @@ def test_restore_reconciles_definitive_missing_start_attempt() -> None:)poll.processing_indicator = {"platform": "avibe",- "delivery_start_attempt_id": "atm-missing",+ "delivery_start_attempt_id": ATTEMPT_ID,"opencode_native_steering": {"target_session_id": "ses_wb","logical_turn_id": "logical-missing",@@ -463,7 +459,7 @@ def test_restore_reconciles_definitive_missing_start_attempt() -> None:agent.controller.session_turns.reconcile_start_attempt_not_written = _reconcileassert asyncio.run(agent.restore_active_polls()) == 0- assert reconciled == [("logical-missing", "atm-missing", "opencode")]+ assert reconciled == [("logical-missing", ATTEMPT_ID, "opencode")]assert removed == ["oc-1"]diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex e90df52d4..7b7fb6d12 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -11,6 +11,8 @@ from unittest.mock import AsyncMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from storage import message_deliveries as delivery_store+MODULE_PATH = Path(__file__).resolve().parents[1] / "modules" / "agents" / "opencode" / "server.py"@@ -469,7 +471,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):body = fake_session.posts[0]["json"]self.assertEqual(body["tools"], {"question": False})- async def test_prompt_async_uses_opencode_native_message_id(self):+ async def test_prompt_async_uses_opencode_native_attempt_part(self):manager = OpenCodeServerManager(binary="opencode", port=4096)fake_session = _FakeSession()@@ -482,30 +484,37 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):session_id="ses-1",directory="/tmp/work",text="hello",- message_id="msg_exact_evidence",+ attempt_id="atm_1234567890abcdef1234567890abcdef",)+ body = fake_session.posts[0]["json"]+ self.assertNotIn("messageID", body)self.assertEqual(- fake_session.posts[0]["json"]["messageID"],- "msg_exact_evidence",+ body["parts"],+ [+ {+ "type": "text",+ "text": "hello",+ "id": "prt_1234567890abcdef1234567890abcdef",+ }+ ],)- def test_durable_attempt_maps_to_opencode_message_namespace(self):- self.assertEqual(- SERVER_MODULE.native_message_id_for_attempt("atm_exact_evidence"),- "msg_exact_evidence",- )+ def test_durable_attempt_maps_to_opencode_part_evidence(self):+ attempt_id = delivery_store.new_attempt_id()- def test_attempt_evidence_accepts_current_and_legacy_native_ids(self):- self.assertEqual(- SERVER_MODULE.native_message_ids_for_attempt("atm_exact_evidence"),- ("msg_exact_evidence", "atm_exact_evidence"),- )+ self.assertRegex(attempt_id, r"^atm_[0-9a-f]{32}$")self.assertEqual(- SERVER_MODULE.native_message_ids_for_attempt("legacy-evidence"),- ("legacy-evidence",),+ 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()