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): settle the owning assistant, not messages[-1] (#1531)
Call White842c55be8ef5
diff --git a/docs/plans/opencode-poll-settlement-owner.md b/docs/plans/opencode-poll-settlement-owner.mdnew file mode 100644index 000000000..3b5969693--- /dev/null+++ b/docs/plans/opencode-poll-settlement-owner.md@@ -0,0 +1,31 @@+# OpenCode poll settles the owning assistant, not messages[-1]++## Background++Two live OpenCode sessions hung with Avibe still polling: a completed+assistant already carried `UnknownError: unknown certificate verification+error`, then a user inject ("继续" / a watch callback) and an empty leftover+generation sat after it. The poll loop only inspected `messages[-1]`, so the+error never became a terminal result.++## Goal++Settle from the assistant that owns the current turn, using both the message+snapshot and native session status. A trailing user while OpenCode is+busy/retry is a live steer or auto-retry. The same snapshot while idle is a+hang (watch callback / typed "继续" after a completed error) and can settle.+An unreadable status is treated as live so an accepted steer is not closed.++## Solution++`_settlement_assistant_message` walks the snapshot backward. Native liveness+comes from the same status sample that produced the snapshot when the+steering wrapper already read it; otherwise from ``/session/status``. A+successful omission (``None``) is idle. An unread or failed status is live. After posting auto-retry+``continue``, the inject stays pending for a short confirmation window+even if status already reports idle. Restored polls do not take the+empty-success finish path until the error retry budget is exhausted.+The status probe is bounded by the remaining turn budget. Auto-retry+``continue`` now arms the same awaiting-after boundary steer already uses,+so settlement will not close the previous error until a post-boundary+assistant exists.diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 8d26fee20..506c44611 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -141,6 +141,7 @@ class _SteeringAwareOpenCodeServer:) -> None:self._server = serverself._state = state+ self.last_list_native_live: bool | None = Nonedef __getattr__(self, name: str) -> Any:return getattr(self._server, name)@@ -247,6 +248,32 @@ class _SteeringAwareOpenCodeServer:for index, message in enumerate(messages))+ @classmethod+ def _has_completed_error_after(+ cls,+ messages: list[Dict[str, Any]],+ excluded_message_ids: set[str],+ *,+ inserted_user_text: str | None = None,+ ) -> bool:+ inserted_user_index = -1+ if inserted_user_text is not None:+ inserted_user_index = cls._inserted_user_index(+ messages,+ excluded_message_ids,+ inserted_user_text,+ )+ if inserted_user_index < 0:+ return False+ return any(+ index > inserted_user_index+ and message.get("info", {}).get("role") == "assistant"+ and message.get("info", {}).get("id") not in excluded_message_ids+ and message.get("info", {}).get("time", {}).get("completed")+ and message.get("info", {}).get("error")+ for index, message in enumerate(messages)+ )+def _has_pending_question_tool(self, messages: list[Dict[str, Any]]) -> bool:return any(message.get("info", {}).get("id") not in self._state.baseline_message_ids@@ -326,6 +353,7 @@ class _SteeringAwareOpenCodeServer:while True:wait_for_insert = Falseasync with self._state.lock:+ self.last_list_native_live = Noneif self._state.terminal_status_failure_messages is not None:return self._state.terminal_status_failure_messagesmessages = await self._server.list_messages(session_id, directory)@@ -340,6 +368,9 @@ class _SteeringAwareOpenCodeServer:if reconcile_insert or final_snapshot or reconcile_initial_status:try:status = await self._server.get_session_status(session_id, directory)+ from modules.agents.opencode.poll_loop import _native_session_is_live++ self.last_list_native_live = _native_session_is_live(status)except Exception as exc:self._state.status_reconciliation_failures += 1if (@@ -477,9 +508,15 @@ class _SteeringAwareOpenCodeServer:inserted_user_text=inserted_user_text,))- if has_final_insert_result:+ has_post_boundary_error = self._has_completed_error_after(+ messages,+ awaiting,+ inserted_user_text=inserted_user_text,+ )+ if has_final_insert_result or has_post_boundary_error:self._clear_awaiting_reconciliation()- self._state.closing = True+ if has_final_insert_result:+ self._state.closing = Truereturn messagesstart_deadline = (self._state.awaiting_start_confirmation_deadline@@ -562,7 +599,27 @@ class _SteeringAwareOpenCodeServer:{**failure, "info": info},]return- await self._server.prompt_async(*args, **kwargs)+ kwargs_map = dict(kwargs)+ prompt_text = str(kwargs_map.get("text") or "")+ snapshot_ids = kwargs_map.pop("awaiting_after_ids", None)+ if snapshot_ids is None:+ session_id = str(kwargs_map.get("session_id") or "")+ directory = str(kwargs_map.get("directory") or "")+ if session_id and directory:+ try:+ current = await self._server.list_messages(session_id, directory)+ except Exception:+ current = []+ snapshot_ids = self._message_ids(current)+ if snapshot_ids is not None:+ self._state.awaiting_after_message_ids = set(snapshot_ids)+ self._state.awaiting_user_text = prompt_text or None+ self._state.awaiting_start_confirmation_deadline = (+ time.monotonic() + _ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS+ )+ self._state.awaiting_active_status_observed = False+ self._state.awaiting_result_confirmation_deadline = None+ await self._server.prompt_async(*args, **{k: v for k, v in kwargs.items() if k != "awaiting_after_ids"})async def abort_session(self, *args, **kwargs) -> bool:async with self._state.lock:diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex 503a271be..149323794 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -35,6 +35,9 @@ _TIMEOUT_ABORT_GRACE_SECONDS = 10.0# never total duration — drive this settlement, so an intermittent blip that# recovers between polls resets the count and never trips it._POLL_FAILURE_SETTLE_LIMIT = 10+# OpenCode can report idle after accepting ``continue`` / a steer, before the+# replacement assistant is visible. Keep that inject pending for this window.+_POST_INJECT_CONFIRMATION_SECONDS = 5.0def _opencode_error_text(error: object) -> str:@@ -46,6 +49,109 @@ def _opencode_error_text(error: object) -> str:return f"{error_name} - {error_message[:500]}".strip(" -")+def _message_info(message: Dict[str, Any]) -> Dict[str, Any]:+ info = message.get("info")+ return info if isinstance(info, dict) else {}+++def _native_session_is_live(+ status: Optional[Dict[str, Any]],+ *,+ status_known: bool = True,+) -> bool:+ """True when OpenCode still owns the turn (busy/retry).++ A successful ``/session/status`` that omits this session is idle+ (``get_session_status`` returns ``None``). An unread or failed status+ (``status_known=False``) is treated as live so an accepted steer is not+ closed during the window where the user message exists and the assistant+ does not.+ """++ if not status_known:+ return True+ if not isinstance(status, dict):+ return False+ return status.get("type") in {"busy", "retry"}+++def _has_post_boundary_assistant(+ messages: list[Dict[str, Any]],+ boundary_ids: set[str],+) -> bool:+ return any(+ (info := _message_info(message)).get("id")+ and info.get("id") not in boundary_ids+ and info.get("role") == "assistant"+ for message in messages+ )+++def _snapshot_needs_native_liveness(+ messages: list[Dict[str, Any]],+ baseline_message_ids: set[str],+ awaiting_after_ids: Optional[set[str]] = None,+) -> bool:+ """True only when idle vs busy can change which completed assistant settles."""++ if awaiting_after_ids and not _has_post_boundary_assistant(+ messages, awaiting_after_ids+ ):+ return False+ latest_new: Optional[Dict[str, Any]] = None+ for message in reversed(messages):+ info = _message_info(message)+ message_id = info.get("id")+ if not message_id or message_id in baseline_message_ids:+ continue+ latest_new = message+ break+ if latest_new is None:+ return False+ info = _message_info(latest_new)+ if info.get("role") == "assistant" and not info.get("time", {}).get("completed"):+ return False+ return info.get("role") == "user"+++def _settlement_assistant_message(+ messages: list[Dict[str, Any]],+ baseline_message_ids: set[str],+ *,+ native_live: bool,+ awaiting_after_ids: Optional[set[str]] = None,+) -> Optional[Dict[str, Any]]:+ """The assistant message that owns this poll's settlement.++ Trailing user injects are not the turn. While the native session is live,+ or an awaiting inject boundary has no post-boundary assistant yet, keep+ the previous completed assistant pending. When idle and the inject has+ produced no new assistant, settle the completed owner behind it.+ """++ if awaiting_after_ids and not _has_post_boundary_assistant(+ messages, awaiting_after_ids+ ):+ return None++ skipped_user = False+ for message in reversed(messages):+ info = _message_info(message)+ message_id = info.get("id")+ if not message_id or message_id in baseline_message_ids:+ continue+ if info.get("role") != "assistant":+ if info.get("role") == "user":+ skipped_user = True+ continue+ if not info.get("time", {}).get("completed"):+ return None+ if skipped_user and native_live:+ return None+ return message+ return None++def restored_platform_from_poll_info(poll_info) -> str:snapshot = poll_info.processing_indicator if isinstance(poll_info.processing_indicator, dict) else {}platform = str(snapshot.get("platform") or poll_info.platform or "")@@ -182,6 +288,37 @@ class OpenCodePollLoop:return None if math.isinf(remaining) else remaining+ async def _native_session_is_live(+ self,+ server: OpenCodeServerManager,+ session_id: str,+ directory: str,+ *,+ remaining: float,+ pending_inject_until: float = 0.0,+ ) -> bool:+ if pending_inject_until and time.monotonic() < pending_inject_until:+ return True+ snapshot_live = getattr(server, "last_list_native_live", None)+ if isinstance(snapshot_live, bool):+ return snapshot_live+ reader = getattr(server, "get_session_status", None)+ if not callable(reader):+ return True+ try:+ status = await asyncio.wait_for(+ reader(session_id, directory),+ timeout=self._wait_timeout(remaining),+ )+ except Exception as err:+ logger.debug(+ "OpenCode session status unavailable for %s: %s",+ session_id,+ err,+ )+ return True+ return _native_session_is_live(status)+@staticmethodasync def _sleep_with_deadline(deadline: float) -> None:remaining = deadline - time.monotonic()@@ -363,6 +500,7 @@ class OpenCodePollLoop:)last_error_message_id: Optional[str] = Nonepoll_failures = 0+ pending_inject_until = 0.0def _relative_path(path: str) -> str:return self._agent._to_relative_path(path, request.working_path)@@ -504,14 +642,35 @@ class OpenCodePollLoop:emitted_assistant_messages.add(message_id)if messages:- last_message = messages[-1]- last_info = last_message.get("info", {})+ remaining = deadline - time.monotonic()+ awaiting_after_ids = getattr(+ getattr(server, "_state", None),+ "awaiting_after_message_ids",+ None,+ )+ native_live = False+ if _snapshot_needs_native_liveness(+ messages, baseline_message_ids, awaiting_after_ids+ ):+ native_live = await self._native_session_is_live(+ server,+ session_id,+ request.working_path,+ remaining=remaining,+ pending_inject_until=pending_inject_until,+ )+ last_message = _settlement_assistant_message(+ messages,+ baseline_message_ids,+ native_live=native_live,+ awaiting_after_ids=awaiting_after_ids,+ )+ last_info = _message_info(last_message) if last_message else {}last_id = last_info.get("id")if (- last_id- and last_id not in baseline_message_ids- and last_info.get("role") == "assistant"+ last_message is not None+ and last_idand last_info.get("time", {}).get("completed")):msg_error = last_info.get("error")@@ -545,6 +704,14 @@ class OpenCodePollLoop:model=model_dict,reasoning_effort=reasoning_effort,tools={"question": False},+ awaiting_after_ids={+ str(_message_info(item).get("id"))+ for item in messages+ if _message_info(item).get("id")+ },+ )+ pending_inject_until = (+ time.monotonic() + _POST_INJECT_CONFIRMATION_SECONDS)await self._sleep_with_deadline(deadline)continue@@ -642,6 +809,7 @@ class OpenCodePollLoop:DEFAULT_OPENCODE_ERROR_RETRY_LIMIT,)last_error_message_id: Optional[str] = None+ pending_inject_until = 0.0started_at = time.monotonic()@@ -801,9 +969,31 @@ class OpenCodePollLoop:await self._agent.controller.emit_agent_message(context, "tool_call", tool_summary)if messages:- last_message = messages[-1]- last_info = last_message.get("info", {})- if last_info.get("role") == "assistant":+ remaining = deadline - time.monotonic()+ awaiting_after_ids = getattr(+ getattr(server, "_state", None),+ "awaiting_after_message_ids",+ None,+ )+ native_live = False+ if _snapshot_needs_native_liveness(+ messages, baseline_message_ids, awaiting_after_ids+ ):+ native_live = await self._native_session_is_live(+ server,+ session_id,+ poll_info.working_path,+ remaining=remaining,+ pending_inject_until=pending_inject_until,+ )+ last_message = _settlement_assistant_message(+ messages,+ baseline_message_ids,+ native_live=native_live,+ awaiting_after_ids=awaiting_after_ids,+ )+ last_info = _message_info(last_message) if last_message else {}+ if last_info.get("id"):time_info = last_info.get("time") or {}if time_info.get("completed"):msg_error = last_info.get("error")@@ -828,6 +1018,8 @@ class OpenCodePollLoop:self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)return+ await self._sleep_with_deadline(deadline)+ continueif last_info.get("finish") != "tool-calls":if not msg_error:diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex 591ba07af..5cc9ae4fc 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -1711,6 +1711,49 @@ async def test_opencode_retry_keeps_completed_error_snapshots_gated() -> None:await _cancel_tasks(*(task for task in (poll_task, gate_task) if task is not None))+async def test_opencode_idle_post_boundary_error_clears_awaiting_boundary() -> None:+ """A completed retry error must reach the poll owner, not a synthetic idle failure."""++ primary = _primary_request(backend="opencode")+ gate_task = await _held_task()+ server = _OpenCodeServer(+ messages=[+ {+ "info": {"id": "primary-user", "role": "user"},+ "parts": [{"type": "text", "text": "continue"}],+ },+ {+ "info": {+ "id": "retry-error",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError", "data": {"message": "tls"}},+ },+ "parts": [],+ },+ ],+ status={"type": "idle"},+ )+ agent = _opencode_agent(primary, gate_task, server)+ state = agent._steering_states[primary.base_session_id]+ state.awaiting_after_message_ids = {"older-error"}+ state.awaiting_user_text = "continue"+ state.awaiting_active_status_observed = True+ poll_server = _SteeringAwareOpenCodeServer(server, state)+ try:+ snapshot = await asyncio.wait_for(+ poll_server.list_messages("opencode-session", primary.working_path),+ timeout=1,+ )+ assert snapshot[-1]["info"]["id"] == "retry-error"+ assert snapshot[-1]["info"]["error"]["name"] == "UnknownError"+ assert state.awaiting_after_message_ids is None+ assert state.closing is False+ finally:+ await _cancel_tasks(gate_task)++@pytest.mark.anyioasync def test_opencode_refuses_after_poll_owner_claims_terminal_result() -> None:primary = _primary_request(backend="opencode")diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 3179d87e1..5edfbb239 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -26,7 +26,10 @@ from modules.agents.base import AgentRequestfrom modules.agents.model_hub import launch_for_contextfrom modules.agents.service import AgentServicefrom modules.agents.opencode.agent import OpenCodeAgent-from modules.agents.opencode.poll_loop import OpenCodePollLoop+from modules.agents.opencode.poll_loop import (+ OpenCodePollLoop,+ _settlement_assistant_message,+)from modules.agents.opencode.utils import resolve_opencode_reasoning_effort@@ -1498,6 +1501,91 @@ def test_opencode_poll_aborts_disabled_question_toolcall():assert emitted[0][1] == "translated:error.opencodeQuestionToolDisabled"+def test_settlement_assistant_message_walks_back_to_the_owning_turn():+ """Every live snapshot shape settles the same owning assistant.++ Seed the shapes already seen in production: last-is-assistant, a trailing+ user inject, an empty leftover generation after a completed error, and a+ follow-up that already has parts. The owner is a property of the snapshot,+ not of which id happens to sit at messages[-1].+ """++ error_assistant = {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError"},+ },+ "parts": [],+ }+ trailing_user = {+ "info": {"id": "msg-user", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "继续"}],+ }+ empty_inflight = {+ "info": {"id": "msg-empty", "role": "assistant", "time": {}},+ "parts": [],+ }+ live_followup = {+ "info": {"id": "msg-live", "role": "assistant", "time": {}},+ "parts": [{"type": "text", "text": "working"}],+ }+ completed_ok = {+ "info": {+ "id": "msg-ok",+ "role": "assistant",+ "time": {"completed": 1},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "done"}],+ }++ cases = (+ ([error_assistant], False, "msg-err"),+ ([error_assistant], True, "msg-err"),+ ([error_assistant, trailing_user], False, "msg-err"),+ ([error_assistant, trailing_user], True, None),+ ([error_assistant, trailing_user, empty_inflight], False, None),+ ([error_assistant, trailing_user, empty_inflight], True, None),+ ([error_assistant, live_followup], True, None),+ ([error_assistant, live_followup], False, None),+ ([completed_ok, trailing_user], False, "msg-ok"),+ ([completed_ok, trailing_user], True, None),+ ([trailing_user], False, None),+ ([trailing_user], True, None),+ ([error_assistant, trailing_user, empty_inflight, completed_ok], False, "msg-ok"),+ )+ for messages, native_live, expected_id in cases:+ owner = _settlement_assistant_message(+ messages, set(), native_live=native_live+ )+ actual_id = None if owner is None else owner["info"]["id"]+ assert actual_id == expected_id, (native_live, expected_id, actual_id)++ owner = _settlement_assistant_message(+ [error_assistant],+ set(),+ native_live=False,+ awaiting_after_ids={"msg-err"},+ )+ assert owner is None+ owner = _settlement_assistant_message(+ [error_assistant, trailing_user],+ set(),+ native_live=False,+ awaiting_after_ids={"msg-err"},+ )+ assert owner is None+ owner = _settlement_assistant_message(+ [error_assistant, trailing_user, completed_ok],+ set(),+ native_live=False,+ awaiting_after_ids={"msg-err"},+ )+ assert owner is not None and owner["info"]["id"] == "msg-ok"++def test_opencode_poll_notifies_and_settles_on_retry_exhaustion():# A completed assistant message carrying an error, with retries exhausted# (error_retry_limit=0) and the auth-recovery path declining (non-auth error),@@ -1604,32 +1692,29 @@ def test_opencode_poll_notifies_and_settles_on_retry_exhaustion():assert model_hub_failures == [(request.context, "ProviderError - rate limited")]-def test_opencode_poll_keeps_explicit_empty_completion_on_success_path():+def test_opencode_poll_settles_error_when_trailing_user_is_last():+ """A watch/steer inject after a completed error is not the turn.++ The live hang was: assistant completed with error, then a user message+ ("继续" / a watch callback) became messages[-1], so the last-only+ settlement never ran.+ """+emitted = []+ model_hub_failures = []class _AuthSvc:- async def maybe_emit_auth_recovery_message(self, context, backend, message):+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):return False- class _Formatter:- def format_toolcall(self, *args, **kwargs):- return "tool"-class _Controller:agent_auth_service = _AuthSvc()- def __init__(self):- self.config = type("Config", (), {"platform": "slack", "ack_mode": "reaction", "language": "en"})()- self.im_client = type("IM", (), {"formatter": _Formatter()})()- self.processing_indicator = ProcessingIndicatorService(self)-def _t(self, key, **kwargs):- if key == "common.default":- return "(Default)"- if key == "error.opencodeEmptyResponse":- return "empty:{provider}/{model}/{variant}".format(**kwargs)- if key == "error.opencodeProviderRuntimeError":- return "provider:{provider}/{model}/{variant}:{detail}".format(**kwargs)+ if key == "error.opencodeBackendError":+ return f"OpenCode error: {kwargs['error']}"return f"translated:{key}"async def emit_agent_message(@@ -1642,54 +1727,249 @@ def test_opencode_poll_keeps_explicit_empty_completion_on_success_path():is_error=False,level="normal",output=None,+ terminal_error=None,):- emitted.append((message_type, text, is_error, level))+ emitted.append((message_type, text, is_error, level, terminal_error))class _Agent:opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()controller = _Controller()- im_client = type("IM", (), {"formatter": _Formatter()})()-- def _get_formatter(self, context):- return _Formatter()-- def _to_relative_path(self, path, working_path):- return pathdef _extract_response_text(self, message):return ""+ async def record_model_hub_native_failure(self, context, diagnostic):+ model_hub_failures.append(diagnostic)+ return True+class _Server:- async def get_recent_session_error(self, session_id, since=None):- return "AI_APICallError (ECONNRESET) while calling https://relay.example/messages"+ async def list_messages(self, session_id, directory):+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {+ "name": "UnknownError",+ "data": {"message": "unknown certificate verification error"},+ },+ },+ "parts": [],+ },+ {+ "info": {"id": "msg-user", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "继续"}],+ },+ ]- async def get_provider_api_diagnostic(self, provider_id, model_id):+ async def get_session_status(self, session_id, directory):return None- def get_last_prompt_started_at(self, session_id):- return 42.0+ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ final_text, should_emit = asyncio.run(+ OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert (final_text, should_emit) == (None, False)+ assert [item[0] for item in emitted] == ["notify", "result"]+ assert "certificate verification" in emitted[0][1]+ assert model_hub_failures == [+ "UnknownError - unknown certificate verification error"+ ]+++def test_opencode_poll_keeps_accepted_steer_pending_while_native_busy(monkeypatch):+ """A trailing user while OpenCode is busy is a live steer, not a hang."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ emitted = []+ polls = {"n": 0}++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):+ return False++ class _Controller:+ agent_auth_service = _AuthSvc()++ def _t(self, key, **kwargs):+ return f"translated:{key}"++ async def emit_agent_message(self, *args, **kwargs):+ emitted.append((args, kwargs))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ controller = _Controller()++ def _extract_response_text(self, message):+ return "steered"++ async def record_model_hub_native_failure(self, context, diagnostic):+ raise AssertionError("must not settle the prior turn while steer is live")+ class _Server:async def list_messages(self, session_id, directory):- return [+ polls["n"] += 1+ followup_ready = polls["n"] >= 3+ rows = [{"info": {- "id": "msg-empty",+ "id": "msg-ok","role": "assistant","time": {"completed": 1},- "finish": "unknown",- "tokens": {- "input": 8,- "output": 4,- "reasoning": 2,- "cache": {"read": 1, "write": 0},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "old"}],+ },+ {+ "info": {"id": "msg-steer", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "steer"}],+ },+ ]+ if followup_ready:+ rows.append(+ {+ "info": {+ "id": "msg-new",+ "role": "assistant",+ "time": {"completed": 1},+ "finish": "stop",},+ "parts": [{"type": "text", "text": "steered"}],+ }+ )+ return rows++ async def get_session_status(self, session_id, directory):+ if polls["n"] >= 3:+ return {"type": "idle"}+ return {"type": "busy"}++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ final_text, should_emit = asyncio.run(+ OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert (final_text, should_emit) == ("steered", True)+ assert polls["n"] == 3+ assert not any(item[0][1] == "result" for item in emitted)+++def test_opencode_poll_uses_snapshot_live_flag_instead_of_rereading_status(monkeypatch):+ """The wrapper's busy decision wins over a later idle status read."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ emitted = []+ polls = {"n": 0}+ status_reads = {"n": 0}++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):+ return False++ class _Controller:+ agent_auth_service = _AuthSvc()++ def _t(self, key, **kwargs):+ return f"translated:{key}"++ async def emit_agent_message(self, *args, **kwargs):+ emitted.append((args, kwargs))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ controller = _Controller()++ def _extract_response_text(self, message):+ return "steered"++ async def record_model_hub_native_failure(self, context, diagnostic):+ raise AssertionError("stale idle status must not settle the pre-steer turn")++ class _Server:+ last_list_native_live = True++ async def list_messages(self, session_id, directory):+ polls["n"] += 1+ followup_ready = polls["n"] >= 3+ if followup_ready:+ self.last_list_native_live = False+ rows = [+ {+ "info": {+ "id": "msg-ok",+ "role": "assistant",+ "time": {"completed": 1},+ "finish": "stop",},- "parts": [- {"type": "step-start", "id": "step-start"},- {"type": "step-finish", "id": "step-finish"},- ],- }+ "parts": [{"type": "text", "text": "old"}],+ },+ {+ "info": {"id": "msg-steer", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "steer"}],+ },]+ if followup_ready:+ rows.append(+ {+ "info": {+ "id": "msg-new",+ "role": "assistant",+ "time": {"completed": 1},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "steered"}],+ }+ )+ return rows++ async def get_session_status(self, session_id, directory):+ status_reads["n"] += 1+ return Nonerequest = AgentRequest(context=MessageContext(user_id="u", channel_id="c", platform="slack"),@@ -1701,22 +1981,686 @@ def test_opencode_poll_keeps_explicit_empty_completion_on_success_path():session_key="slack::c",)- loop = OpenCodePollLoop(_Agent())final_text, should_emit = asyncio.run(- loop.run_prompt_poll(+ OpenCodePollLoop(_Agent()).run_prompt_poll(request,_Server(),"oc-session",agent_to_use=None,- model_dict={"providerID": "glm", "modelID": "glm-5.2"},+ model_dict=None,reasoning_effort=None,baseline_message_ids=set(),))- assert final_text is None- assert should_emit is True- assert emitted == []+ assert (final_text, should_emit) == ("steered", True)+ assert polls["n"] == 3+ assert status_reads["n"] == 0+ assert not any(item[0][1] == "result" for item in emitted)+++def test_opencode_poll_keeps_retry_pending_on_empty_inflight_assistant(monkeypatch):+ """Auto-retry ``continue`` must stay live until the new assistant completes."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ emitted = []+ polls = {"n": 0}++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):+ return False++ class _Controller:+ agent_auth_service = _AuthSvc()++ def _t(self, key, **kwargs):+ if key == "error.opencodeBackendError":+ return f"OpenCode error: {kwargs['error']}"+ return f"translated:{key}"++ async def emit_agent_message(+ self,+ context,+ message_type,+ text,+ parse_mode=None,+ *,+ is_error=False,+ level="normal",+ output=None,+ terminal_error=None,+ ):+ emitted.append((message_type, text, is_error, level, terminal_error))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ controller = _Controller()++ def _extract_response_text(self, message):+ return "recovered"++ async def record_model_hub_native_failure(self, context, diagnostic):+ raise AssertionError("must not settle while retry is in flight")++ class _Server:+ async def list_messages(self, session_id, directory):+ polls["n"] += 1+ followup_completed = polls["n"] >= 3+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError", "data": {"message": "tls failed"}},+ },+ "parts": [],+ },+ {+ "info": {"id": "msg-user", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "continue"}],+ },+ {+ "info": {+ "id": "msg-empty",+ "role": "assistant",+ "time": {"completed": 1} if followup_completed else {},+ "finish": "stop" if followup_completed else None,+ },+ "parts": (+ [{"type": "text", "text": "recovered"}] if followup_completed else []+ ),+ },+ ]++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ final_text, should_emit = asyncio.run(+ OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert (final_text, should_emit) == ("recovered", True)+ assert polls["n"] == 3+ assert not any(item[0] == "result" for item in emitted)+++def test_opencode_poll_keeps_continue_pending_through_idle_visibility_gap(monkeypatch):+ """After posting continue, an idle trailing-user snapshot is still live."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POST_INJECT_CONFIRMATION_SECONDS", 1.0+ )+ emitted = []+ polls = {"n": 0}++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):+ return False++ class _Controller:+ agent_auth_service = _AuthSvc()++ def _t(self, key, **kwargs):+ if key == "error.opencodeBackendError":+ return f"OpenCode error: {kwargs['error']}"+ return f"translated:{key}"++ async def emit_agent_message(+ self,+ context,+ message_type,+ text,+ parse_mode=None,+ *,+ is_error=False,+ level="normal",+ output=None,+ terminal_error=None,+ ):+ emitted.append((message_type, text, is_error, level, terminal_error))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 1})()+ controller = _Controller()++ def _extract_response_text(self, message):+ return "recovered"++ async def record_model_hub_native_failure(self, context, diagnostic):+ raise AssertionError("must not settle during the continue visibility gap")++ class _Server:+ async def list_messages(self, session_id, directory):+ polls["n"] += 1+ if polls["n"] == 1:+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError", "data": {"message": "tls"}},+ },+ "parts": [],+ }+ ]+ if polls["n"] == 2:+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError", "data": {"message": "tls"}},+ },+ "parts": [],+ },+ {+ "info": {"id": "msg-continue", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "continue"}],+ },+ ]+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError", "data": {"message": "tls"}},+ },+ "parts": [],+ },+ {+ "info": {"id": "msg-continue", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "continue"}],+ },+ {+ "info": {+ "id": "msg-new",+ "role": "assistant",+ "time": {"completed": 1},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "recovered"}],+ },+ ]++ async def prompt_async(self, **kwargs):+ return None++ async def get_session_status(self, session_id, directory):+ return None++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ final_text, should_emit = asyncio.run(+ OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert (final_text, should_emit) == ("recovered", True)+ assert polls["n"] >= 3+ assert not any(item[0] == "result" for item in emitted)+++def test_opencode_poll_keeps_retry_pending_before_continue_user_appears(monkeypatch):+ """Awaiting boundary holds the old error until post-inject evidence exists."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ emitted = []+ polls = {"n": 0}++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):+ return False++ class _Controller:+ agent_auth_service = _AuthSvc()++ def _t(self, key, **kwargs):+ if key == "error.opencodeBackendError":+ return f"OpenCode error: {kwargs['error']}"+ return f"translated:{key}"++ async def emit_agent_message(self, *args, **kwargs):+ emitted.append((args, kwargs))++ class _State:+ awaiting_after_message_ids = {"msg-err"}+ awaiting_user_text = "continue"++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 1})()+ controller = _Controller()++ def _extract_response_text(self, message):+ return "recovered"++ async def record_model_hub_native_failure(self, context, diagnostic):+ raise AssertionError("must not settle the prior error before continue appears")++ class _Server:+ def __init__(self):+ self._state = _State()++ async def list_messages(self, session_id, directory):+ polls["n"] += 1+ error = {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError", "data": {"message": "tls"}},+ },+ "parts": [],+ }+ if polls["n"] == 1:+ return [error]+ if polls["n"] == 2:+ return [+ error,+ {+ "info": {"id": "msg-continue", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "continue"}],+ },+ ]+ return [+ error,+ {+ "info": {"id": "msg-continue", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "continue"}],+ },+ {+ "info": {+ "id": "msg-new",+ "role": "assistant",+ "time": {"completed": 1},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "recovered"}],+ },+ ]++ async def get_session_status(self, session_id, directory):+ return None++ async def prompt_async(self, **kwargs):+ return None++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ final_text, should_emit = asyncio.run(+ OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert (final_text, should_emit) == ("recovered", True)+ assert polls["n"] >= 3+ assert not any(item[0][1] == "result" for item in emitted)+++def test_opencode_poll_does_not_settle_error_while_followup_has_parts():+ """A follow-up assistant that already has parts is still the live turn."""++ emitted = []+ polls = {"n": 0}++ class _Controller:+ def _t(self, key, **kwargs):+ return f"translated:{key}"++ async def emit_agent_message(self, *args, **kwargs):+ emitted.append((args, kwargs))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ controller = _Controller()++ def _extract_response_text(self, message):+ return "recovered"++ async def record_model_hub_native_failure(self, context, diagnostic):+ raise AssertionError("must not settle the earlier error")++ class _Server:+ async def list_messages(self, session_id, directory):+ polls["n"] += 1+ followup_completed = polls["n"] >= 2+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "UnknownError", "data": {"message": "old"}},+ },+ "parts": [],+ },+ {+ "info": {+ "id": "msg-live",+ "role": "assistant",+ "time": {"completed": 1} if followup_completed else {},+ "finish": "stop" if followup_completed else None,+ },+ "parts": [{"type": "text", "text": "recovered"}],+ },+ ]++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ final_text, should_emit = asyncio.run(+ OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert (final_text, should_emit) == ("recovered", True)+ assert polls["n"] == 2+ assert not any(item[0][1] == "result" for item in emitted)+++def test_opencode_poll_keeps_explicit_empty_completion_on_success_path():+ emitted = []++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(self, context, backend, message):+ return False++ class _Formatter:+ def format_toolcall(self, *args, **kwargs):+ return "tool"++ class _Controller:+ agent_auth_service = _AuthSvc()++ def __init__(self):+ self.config = type("Config", (), {"platform": "slack", "ack_mode": "reaction", "language": "en"})()+ self.im_client = type("IM", (), {"formatter": _Formatter()})()+ self.processing_indicator = ProcessingIndicatorService(self)++ def _t(self, key, **kwargs):+ if key == "common.default":+ return "(Default)"+ if key == "error.opencodeEmptyResponse":+ return "empty:{provider}/{model}/{variant}".format(**kwargs)+ if key == "error.opencodeProviderRuntimeError":+ return "provider:{provider}/{model}/{variant}:{detail}".format(**kwargs)+ return f"translated:{key}"++ async def emit_agent_message(+ self,+ context,+ message_type,+ text,+ parse_mode=None,+ *,+ is_error=False,+ level="normal",+ output=None,+ ):+ emitted.append((message_type, text, is_error, level))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ controller = _Controller()+ im_client = type("IM", (), {"formatter": _Formatter()})()++ def _get_formatter(self, context):+ return _Formatter()++ def _to_relative_path(self, path, working_path):+ return path++ def _extract_response_text(self, message):+ return ""++ class _Server:+ async def get_recent_session_error(self, session_id, since=None):+ return "AI_APICallError (ECONNRESET) while calling https://relay.example/messages"++ async def get_provider_api_diagnostic(self, provider_id, model_id):+ return None++ def get_last_prompt_started_at(self, session_id):+ return 42.0++ async def list_messages(self, session_id, directory):+ return [+ {+ "info": {+ "id": "msg-empty",+ "role": "assistant",+ "time": {"completed": 1},+ "finish": "unknown",+ "tokens": {+ "input": 8,+ "output": 4,+ "reasoning": 2,+ "cache": {"read": 1, "write": 0},+ },+ },+ "parts": [+ {"type": "step-start", "id": "step-start"},+ {"type": "step-finish", "id": "step-finish"},+ ],+ }+ ]++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ loop = OpenCodePollLoop(_Agent())+ final_text, should_emit = asyncio.run(+ loop.run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict={"providerID": "glm", "modelID": "glm-5.2"},+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert final_text is None+ assert should_emit is True+ assert emitted == []+++def test_opencode_restored_poll_settles_error_after_retry_budget(monkeypatch):+ """A restored poll must emit the backend error, not (No response)."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ emitted = []+ removed = []+ results = []++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):+ return False++ class _Controller:+ agent_auth_service = _AuthSvc()++ def __init__(self):+ self.config = type("Config", (), {"language": "en"})()+ self.processing_indicator = ProcessingIndicatorService(self)++ def _t(self, key, **kwargs):+ if key == "error.opencodeBackendError":+ return f"OpenCode error: {kwargs['error']}"+ return f"translated:{key}"++ async def emit_agent_message(+ self,+ context,+ message_type,+ text,+ parse_mode=None,+ *,+ is_error=False,+ level="normal",+ output=None,+ terminal_error=None,+ ):+ emitted.append((message_type, text, is_error, level, terminal_error))++ class _Sessions:+ def remove_active_poll(self, session_id):+ removed.append(session_id)++ def update_active_poll_state(self, session_id, **kwargs):+ return None++ class _Server:+ async def list_messages(self, session_id, directory):+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {+ "name": "UnknownError",+ "data": {"message": "certificate failed"},+ },+ },+ "parts": [],+ },+ {+ "info": {"id": "msg-user", "role": "user", "time": {}},+ "parts": [{"type": "text", "text": "继续"}],+ },+ ]++ async def get_session_status(self, session_id, directory):+ return None++ server = _Server()++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 1})()+ controller = _Controller()+ sessions = _Sessions()++ async def _get_server(self):+ return server++ def _extract_response_text(self, message):+ return ""++ async def emit_result_message(self, context, text, **kwargs):+ results.append(text)++ async def _remove_ack_reaction(self, request):+ return None++ async def record_model_hub_native_failure(self, context, diagnostic):+ return True++ poll = ActivePollInfo(+ opencode_session_id="oc-session",+ base_session_id="base",+ channel_id="c",+ thread_id="t",+ settings_key="c",+ working_path="/tmp/work",+ baseline_message_ids=[],+ platform="slack",+ prompt_started_at=time.time(),+ )++ asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))++ assert removed == ["oc-session"]+ assert any(item[0] == "result" and item[2] is True for item in emitted)+ assert all("No response from OpenCode" not in str(item) for item in results)+ assert any("certificate failed" in (item[1] or "") for item in emitted)def test_opencode_restored_poll_keeps_empty_completion_successful():