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): default-off the active-turn wall-clock cap (#1511)
Call White87888788a467
diff --git a/config/v2_config.py b/config/v2_config.pyindex 7266f37c8..c4f901367 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -287,11 +287,18 @@ DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER = 3DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800DEFAULT_OPENCODE_ERROR_RETRY_LIMIT = 1-# A provider runtime can keep an accepted OpenCode prompt in retry forever without-# surfacing a terminal message. Bound that lifecycle independently of per-request-# HTTP timeouts; 90 minutes matches the watchdog threshold reported in #1190 and-# remains adjustable for workloads that legitimately need longer turns.-DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS = 90 * 60+# OpenCode >= 1.18.x bounds its own provider retries (RETRY_MAX_RETRIES = 5) and+# writes the exhausted error onto the assistant message, which the poll loop's+# error-driven settlement already turns into a failed terminal result. The+# historical wall-clock cap from #1197 therefore default-offs here: a positive+# value is an explicit opt-in for operators who still want a hard bound.+DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS = 0+# The shipped default before the opt-in change. A settings save materializes the+# whole ``agents.opencode`` section, so a persisted value equal to this constant+# is the old default's echo rather than an operator's choice; load-time+# migration neutralizes exactly that value. Any other value is an explicit+# choice and survives the migration.+LEGACY_DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS = 90 * 60DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX = 14MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20@@ -892,9 +899,48 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[return migrated_payload, True, tuple(warnings)+def _migrate_opencode_active_turn_timeout_on_load(payload: dict) -> dict:+ """Neutralize the legacy wall-clock default echo on reload, once.++ Configs saved while the cap shipped carry+ ``agents.opencode.active_turn_timeout_seconds: 5400`` because a settings+ save materializes the whole section. That value names the old default, not+ an operator's choice, so exactly that value rewrites to the disabled+ default. ``legacy_turn_timeout_neutralized`` is the provenance marker: a+ config written under the opt-in semantics carries it, so a deliberate+ 5400-second choice saved afterwards survives every later load. Idempotent:+ once rewritten (or never eligible) the pattern never matches again.+ """++ agents = payload.get("agents")+ if not isinstance(agents, dict):+ return payload+ opencode = agents.get("opencode")+ if not isinstance(opencode, dict):+ return payload+ if "legacy_turn_timeout_neutralized" in opencode:+ return payload+ if (+ opencode.get("active_turn_timeout_seconds")+ != LEGACY_DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS+ ):+ return payload+ migrated = dict(payload)+ migrated_agents = dict(agents)+ migrated_opencode = dict(opencode)+ migrated_opencode["active_turn_timeout_seconds"] = (+ DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS+ )+ migrated_opencode["legacy_turn_timeout_neutralized"] = True+ migrated_agents["opencode"] = migrated_opencode+ migrated["agents"] = migrated_agents+ return migrated++def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:migrated, changed, warnings = _migrate_legacy_model_hub_payload(payload)migrated = _migrate_fixed_menu_routes_on_load(migrated)+ migrated = _migrate_opencode_active_turn_timeout_on_load(migrated)return migrated, changed, warnings@@ -2410,6 +2456,11 @@ class OpenCodeConfig:default_reasoning_effort: Optional[str] = Noneerror_retry_limit: int = DEFAULT_OPENCODE_ERROR_RETRY_LIMIT # Max retries on LLM stream errors (0 = no retry)active_turn_timeout_seconds: int = DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS+ # Provenance for the legacy-default neutralization: once this config has+ # been written (or migrated) under the opt-in semantics the key is present,+ # and a deliberate ``active_turn_timeout_seconds == 5400`` saved afterwards+ # is an explicit operator choice the load migration must preserve.+ legacy_turn_timeout_neutralized: bool = True# Provider the user picked in Settings → Backends → OpenCode. The provider# catalog itself lives in ~/.config/opencode/opencode.json (OpenCode's own# state file). Stays ``None`` until the user explicitly chooses so legacydiff --git a/docs/plans/opencode-turn-timeout-opt-in.md b/docs/plans/opencode-turn-timeout-opt-in.mdnew file mode 100644index 000000000..dca7d3f30--- /dev/null+++ b/docs/plans/opencode-turn-timeout-opt-in.md@@ -0,0 +1,73 @@+# OpenCode Active-Turn Timeout Becomes Opt-In++## Background++`docs/plans/opencode-active-turn-timeout.md` (#1197, fixing #1190) shipped a+90-minute wall-clock cap on accepted OpenCode turns. The incident's root cause+was OpenCode's ai-sdk runtime retrying exhausted-provider errors forever+without surfacing a terminal message, which left Avibe's error-driven+settlement nothing to observe.++Upstream has since fixed that class directly: OpenCode >= 1.18.x disables+ai-sdk internal retries (`maxRetries: 0`), runs its own bounded retry policy+(`RETRY_MAX_RETRIES = 5`, capped backoff), and writes the exhausted error onto+the assistant message, which Avibe's existing error path settles as a failed+terminal result. Verified against the locally installed 1.18.18 binary and the+dev-branch source (`packages/opencode/src/session/retry.ts`; fix commits+#40707, #41939).++The wall-clock cap therefore kills legitimate long turns while no longer+guarding a live failure mode. It also disagrees with the other backends, which+settle on surfaced errors rather than turn duration.++## Goal++- Default-disable the cap: `agents.opencode.active_turn_timeout_seconds`+ defaults to `0`, meaning no wall-clock bound.+- Keep the mechanism as an explicit operator opt-in; a positive value behaves+ exactly as before.+- Neutralize the legacy default echo at load: configs saved while the cap+ shipped carry `5400` because a settings save materializes the whole section,+ so exactly that value migrates to `0`. Any other persisted value is an+ explicit choice and survives.+- Non-positive, missing, or non-finite config values read as disabled; they+ must not silently fall back to a cap.++## Solution++- `config/v2_config.py`: `DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS = 0`,+ `LEGACY_DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS = 90 * 60`, and+ `_migrate_opencode_active_turn_timeout_on_load` wired into the load+ migration chain. The migration is a one-time neutralization guarded by the+ `legacy_turn_timeout_neutralized` provenance marker: a legacy payload (no+ marker) with the echo value loads as disabled, while any config saved under+ the opt-in semantics carries the marker, so a deliberate 5400-second choice+ saved afterwards survives every later load.+- `modules/agents/opencode/poll_loop.py`: disabled timeout yields an infinite+ deadline; `wait_for` receives `None` for the infinite budget. Error-driven+ settlement, user stop, and shutdown cancellation are unchanged.+- Poll-transport settlement: a persistent runtime outage (daemon unreachable,+ non-200 responses) can no longer retry forever once the wall-clock deadline+ is optional. Both poll loops settle the turn as a failed backend failure+ after `_POLL_FAILURE_SETTLE_LIMIT` (10) consecutive polling errors and+ best-effort abort the native session. The bound is on consecutive failures,+ never on total duration: a successful poll resets the counter, so+ intermittent blips never trip it.+- UI: the Settings → Messaging field accepts `0` (minutes) and documents the+ disabled semantics; hint copy updated in en/zh.++## Pre-1.18 runtimes++Installations that upgrade Avibe while keeping an OpenCode binary older than+the bounded-retry change re-expose themselves to the unbounded provider-retry+hang #1190 documented. Avibe cannot reliably version-gate this: OpenCode is a+user-supplied `cli_path`, and the bounded-retry policy landed mid-1.18.x line+(build-date dependent), so a `< 1.18` check would be wrong in both directions.+The cap remains fully functional as an explicit opt-in for those operators;+the product default follows the supported runtime behavior.++## Scope++HFR-432 keeps its scenario ID and semantics for the opted-in lifecycle. The+default-disabled deadline has its own unit coverage beside the poll loop+(disabled-semantics seeding test plus a no-deadline prompt-poll test).diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex 9fb417c0b..503a271be 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -6,7 +6,7 @@ import asyncioimport loggingimport mathimport time-from typing import Any, Dict, Optional+from typing import Any, Dict, Optional, Unionfrom config.v2_config import (DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS,@@ -28,6 +28,13 @@ logger = logging.getLogger(__name__)_POLL_INTERVAL_SECONDS = 2.0_TIMEOUT_ABORT_GRACE_SECONDS = 10.0+# The optional wall-clock deadline must not be the only bound on a dead runtime:+# with the cap disabled, a persistent transport outage (daemon down, non-200+# responses) would otherwise retry forever and leave the accepted turn+# unsettled with no message able to carry an error. Consecutive failures —+# 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 = 10def _opencode_error_text(error: object) -> str:@@ -136,6 +143,15 @@ class OpenCodePollLoop:await record_failure(context, diagnostic)def _active_turn_timeout_seconds(self) -> float:+ """The configured wall-clock bound, or ``0.0`` when it is disabled.++ Non-positive, missing, or non-finite values all read as disabled. The+ upstream runtime bounds its own retries and surfaces the exhausted+ error on the message, which the poll loop's error path settles, so the+ wall-clock cap is an explicit opt-in — an unset or invalid value must+ not silently re-enable one.+ """+raw_timeout = getattr(self._agent.opencode_config,"active_turn_timeout_seconds",@@ -144,13 +160,15 @@ class OpenCodePollLoop:try:timeout = float(raw_timeout)except (TypeError, ValueError):- timeout = float(DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS)+ return 0.0if not math.isfinite(timeout) or timeout <= 0:- timeout = float(DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS)+ return 0.0return timeout@staticmethoddef _deadline_from_persisted_start(timeout_seconds: float, started_at: object) -> float:+ if timeout_seconds <= 0:+ return math.inftry:wall_started_at = float(started_at)except (TypeError, ValueError):@@ -158,6 +176,12 @@ class OpenCodePollLoop:elapsed = max(0.0, time.time() - wall_started_at) if wall_started_at > 0 else 0.0return time.monotonic() + max(0.0, timeout_seconds - elapsed)+ @staticmethod+ def _wait_timeout(remaining: float) -> Union[float, None]:+ """Map an infinite remaining budget to ``wait_for``'s no-timeout form."""++ return None if math.isinf(remaining) else remaining+@staticmethodasync def _sleep_with_deadline(deadline: float) -> None:remaining = deadline - time.monotonic()@@ -208,6 +232,49 @@ class OpenCodePollLoop:request=request,)+ async def _settle_poll_transport_failure(+ self,+ *,+ request: AgentRequest,+ server: OpenCodeServerManager,+ session_id: str,+ working_path: str,+ failures: int,+ ) -> None:+ diagnostic = (+ f"OpenCode poll failed {failures} consecutive times; "+ "runtime is unreachable"+ )+ logger.warning(+ "OpenCode poll transport failures settled: session=%s failures=%s; aborting native turn",+ session_id,+ failures,+ )+ try:+ await asyncio.wait_for(+ server.abort_session(session_id, working_path),+ timeout=_TIMEOUT_ABORT_GRACE_SECONDS,+ )+ except Exception as abort_err:+ logger.error(+ "Failed to abort unreachable OpenCode session %s within %.0fs: %s",+ session_id,+ _TIMEOUT_ABORT_GRACE_SECONDS,+ abort_err,+ )+ await self._record_model_hub_failure(request.context, diagnostic)+ await emit_backend_failure(+ self._agent.controller,+ request.context,+ "opencode",+ diagnostic,+ display_text=self._t(+ "error.opencodePollTransportFailure",+ count=failures,+ ),+ request=request,+ )+def _build_restored_handle(self, poll_info):return restored_request_from_poll_info(self._agent, poll_info).processing_indicator@@ -284,7 +351,9 @@ class OpenCodePollLoop:emitted_assistant_messages: set[str] = set()final_text: Optional[str] = Nonetimeout_seconds = self._active_turn_timeout_seconds()- deadline = time.monotonic() + timeout_seconds+ deadline = (+ time.monotonic() + timeout_seconds if timeout_seconds > 0 else math.inf+ )error_retry_count = 0error_retry_limit = getattr(@@ -293,6 +362,7 @@ class OpenCodePollLoop:DEFAULT_OPENCODE_ERROR_RETRY_LIMIT,)last_error_message_id: Optional[str] = None+ poll_failures = 0def _relative_path(path: str) -> str:return self._agent._to_relative_path(path, request.working_path)@@ -316,8 +386,9 @@ class OpenCodePollLoop:session_id=session_id,directory=request.working_path,),- timeout=remaining,+ timeout=self._wait_timeout(remaining),)+ poll_failures = 0if poll_iter % 5 == 0:last_info = messages[-1].get("info", {}) if messages else {}logger.info(@@ -340,10 +411,30 @@ class OpenCodePollLoop:timeout_seconds=timeout_seconds,)return None, False+ poll_failures += 1+ if poll_failures >= _POLL_FAILURE_SETTLE_LIMIT:+ await self._settle_poll_transport_failure(+ request=request,+ server=server,+ session_id=session_id,+ working_path=request.working_path,+ failures=poll_failures,+ )+ return None, Falselogger.warning("Timed out polling OpenCode messages before the active-turn deadline")await self._sleep_with_deadline(deadline)continueexcept Exception as poll_err:+ poll_failures += 1+ if poll_failures >= _POLL_FAILURE_SETTLE_LIMIT:+ await self._settle_poll_transport_failure(+ request=request,+ server=server,+ session_id=session_id,+ working_path=request.working_path,+ failures=poll_failures,+ )+ return None, Falselogger.warning(f"Failed to poll OpenCode messages: {poll_err}")await self._sleep_with_deadline(deadline)continue@@ -559,6 +650,7 @@ class OpenCodePollLoop:try:poll_iter = 0+ poll_failures = 0while True:poll_iter += 1remaining = deadline - time.monotonic()@@ -579,8 +671,9 @@ class OpenCodePollLoop:session_id=session_id,directory=poll_info.working_path,),- timeout=remaining,+ timeout=self._wait_timeout(remaining),)+ poll_failures = 0if poll_iter % 5 == 0:last_info = messages[-1].get("info", {}) if messages else {}logger.info(@@ -605,12 +698,36 @@ class OpenCodePollLoop:self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)return+ poll_failures += 1+ if poll_failures >= _POLL_FAILURE_SETTLE_LIMIT:+ await self._settle_poll_transport_failure(+ request=restored_request,+ server=server,+ session_id=session_id,+ working_path=poll_info.working_path,+ failures=poll_failures,+ )+ self._agent.sessions.remove_active_poll(session_id)+ await self.remove_restored_ack(poll_info)+ returnlogger.warning("Timed out polling restored OpenCode messages before the active-turn deadline")await self._sleep_with_deadline(deadline)continueexcept Exception as poll_err:+ poll_failures += 1+ if poll_failures >= _POLL_FAILURE_SETTLE_LIMIT:+ await self._settle_poll_transport_failure(+ request=restored_request,+ server=server,+ session_id=session_id,+ working_path=poll_info.working_path,+ failures=poll_failures,+ )+ self._agent.sessions.remove_active_poll(session_id)+ await self.remove_restored_ack(poll_info)+ returnlogger.warning(f"Failed to poll OpenCode messages (restored): {poll_err}")await self._sleep_with_deadline(deadline)continuediff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 0bea418d0..f42bff2c9 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -3857,7 +3857,11 @@ scenarios:# accepted Turn has a bounded wall-clock owner: expiry aborts the exact native# session, emits one failed terminal result, admits the same-Session successor,# and lets a different OpenCode Agent waiting on that shared provider continue.- # The timeout never enters the empty successful-result fallback.+ # The timeout never enters the empty successful-result fallback. Since the+ # upstream runtime bounds its own retries and surfaces the exhausted error, the+ # cap is an explicit opt-in (nonzero config); this scenario exercises the+ # opted-in lifecycle only, and the default-disabled deadline has its own unit+ # coverage beside the poll loop.test: tests/test_agent_service.py::test_hfr_432_opencode_timeout_releases_fifo_and_shared_runtime- id: HFR-434name: an OpenCode steer at the native terminal boundary stays reconcilablediff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 774f2e769..3179d87e1 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -1859,6 +1859,110 @@ def test_opencode_restored_poll_keeps_empty_completion_successful():assert isinstance(results[0][1]["started_at"], float)+def test_opencode_restored_poll_settles_after_consecutive_transport_failures(+ monkeypatch,+):+ """A restored poll with a dead runtime settles by failure count too."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_FAILURE_SETTLE_LIMIT", 3+ )++ emitted = []+ removed = []+ aborted = []++ 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", (), {"platform": "slack", "ack_mode": "reaction", "language": "en"}+ )()+ self.processing_indicator = ProcessingIndicatorService(self)++ def _t(self, key, **kwargs):+ return f"{key}:{kwargs.get('count')}"++ 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)++ class _Server:+ async def list_messages(self, session_id, directory):+ raise ConnectionError("daemon down")++ async def abort_session(self, session_id, directory):+ aborted.append((session_id, directory))+ return True++ server = _Server()++ class _Agent:+ opencode_config = type(+ "OpenCodeConfig",+ (),+ {"error_retry_limit": 0, "active_turn_timeout_seconds": 0},+ )()+ controller = _Controller()+ sessions = _Sessions()++ async def _get_server(self):+ return server++ async def _remove_ack_reaction(self, request):+ return None++ async def record_model_hub_native_failure(self, context, diagnostic):+ return False++ poll = ActivePollInfo(+ opencode_session_id="oc-restored-transport-dead",+ 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 aborted == [("oc-restored-transport-dead", "/tmp/work")]+ assert removed == ["oc-restored-transport-dead"]+ assert any(+ item[0] == "notify" and item[1] == "error.opencodePollTransportFailure:3"+ for item in emitted+ )+ assert any(item[0] == "result" and item[2] is True for item in emitted)+ assert all("No response from OpenCode" not in (item[1] or "") for item in emitted)++def test_opencode_restored_poll_consumes_original_timeout_budget():emitted = []removed = []@@ -2027,6 +2131,330 @@ def test_opencode_active_turn_poll_propagates_cancellation_without_settlement():assert emitted == []+def test_opencode_active_turn_timeout_reads_disabled_semantics():+ """Every unset, non-positive, or non-finite shape reads as disabled.++ The seed set is every value shape the config can carry once the shipped+ default is disabled: the dataclass default (missing attribute), an+ explicit opt-out, a negative number, None, NaN, infinity, and an+ unparseable string. None of them may silently re-enable the historical+ wall-clock cap; only a positive opt-in survives as itself.+ """++ def _config_with(value) -> type:+ attrs = {"error_retry_limit": 0}+ if value is not Ellipsis:+ attrs["active_turn_timeout_seconds"] = value+ return type("OpenCodeConfig", (), attrs)()++ for raw_value in (Ellipsis, 0, -5, None, float("nan"), float("inf"), "garbage"):+ loop = OpenCodePollLoop(type("A", (), {"opencode_config": _config_with(raw_value)})())+ assert loop._active_turn_timeout_seconds() == 0.0, raw_value++ loop = OpenCodePollLoop(type("A", (), {"opencode_config": _config_with(90 * 60)})())+ assert loop._active_turn_timeout_seconds() == 5400.0++ assert (+ OpenCodePollLoop._deadline_from_persisted_start(0.0, time.time())+ == float("inf")+ )+ assert OpenCodePollLoop._wait_timeout(float("inf")) is None+ assert OpenCodePollLoop._wait_timeout(1.5) == 1.5+++def test_opencode_prompt_poll_has_no_wall_clock_deadline_when_disabled(monkeypatch):+ """With the cap disabled the poll loop only stops on a terminal message."""++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )++ aborted = []+ poll_count = {"n": 0}++ class _Controller:+ def _t(self, key, **kwargs):+ return f"{key}:{kwargs}"++ async def emit_agent_message(self, *args, **kwargs):+ raise AssertionError("no emission expected on a clean terminal path")++ class _Server:+ async def list_messages(self, session_id, directory):+ poll_count["n"] += 1+ if poll_count["n"] < 3:+ return []+ return [+ {+ "info": {+ "id": "msg-final",+ "role": "assistant",+ "time": {"completed": True},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "done"}],+ }+ ]++ async def abort_session(self, session_id, directory):+ aborted.append((session_id, directory))+ return True++ class _Agent:+ opencode_config = type(+ "OpenCodeConfig",+ (),+ {"error_retry_limit": 0, "active_turn_timeout_seconds": 0},+ )()+ controller = _Controller()++ @staticmethod+ def _extract_response_text(message):+ return "done"++ async def record_model_hub_native_failure(self, context, diagnostic):+ return False++ async def _run():+ request = AgentRequest(+ context=MessageContext(+ user_id="user",+ channel_id="channel",+ platform="slack",+ ),+ message="work",+ user_message="work",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="composite",+ session_key="slack::channel",+ )+ return await OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-no-deadline",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )++ final_text, should_emit = asyncio.run(_run())++ assert final_text == "done"+ assert should_emit is True+ assert poll_count["n"] == 3+ assert aborted == []+++def test_opencode_prompt_poll_settles_after_consecutive_transport_failures(+ monkeypatch,+):+ """A dead runtime settles the turn by failure count, never by duration.++ With the wall-clock cap disabled, persistent polling errors are the only+ remaining bound: after the configured number of consecutive failures the+ poll owner aborts the native session and emits one failed terminal result.+ The count is consecutive — the reset-on-recovery case is covered by its+ own test — so an intermittent blip never trips this bound.+ """++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_FAILURE_SETTLE_LIMIT", 3+ )++ emitted = []+ aborted = []+ attempts = {"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"{key}:{kwargs.get('count')}"++ 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 _Server:+ async def list_messages(self, session_id, directory):+ attempts["n"] += 1+ raise ConnectionError("daemon down")++ async def abort_session(self, session_id, directory):+ aborted.append((session_id, directory))+ return True++ class _Agent:+ opencode_config = type(+ "OpenCodeConfig",+ (),+ {"error_retry_limit": 0, "active_turn_timeout_seconds": 0},+ )()+ controller = _Controller()++ @staticmethod+ def _extract_response_text(message):+ return ""++ async def record_model_hub_native_failure(self, context, diagnostic):+ return False++ async def _run():+ request = AgentRequest(+ context=MessageContext(+ user_id="user",+ channel_id="channel",+ platform="slack",+ ),+ message="work",+ user_message="work",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="composite",+ session_key="slack::channel",+ )+ return await OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-transport-dead",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )++ final_text, should_emit = asyncio.run(_run())++ assert (final_text, should_emit) == (None, False)+ assert attempts["n"] == 3+ assert aborted == [("oc-transport-dead", "/tmp/work")]+ assert any(+ item[0] == "notify" and item[1] == "error.opencodePollTransportFailure:3"+ for item in emitted+ )+ assert any(item[0] == "result" and item[2] is True for item in emitted)+ assert all("No response from OpenCode" not in (item[1] or "") for item in emitted)+++def test_opencode_prompt_poll_transport_failure_counter_resets_on_recovery(+ monkeypatch,+):+ """Failures only count while they are consecutive.++ Two poll errors followed by a successful poll and a terminal message must+ complete normally: the counter reset on the successful poll proves the+ bound is on the outage, not on the turn's total history.+ """++ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0.01+ )+ monkeypatch.setattr(+ "modules.agents.opencode.poll_loop._POLL_FAILURE_SETTLE_LIMIT", 3+ )++ aborted = []+ emitted = []+ attempts = {"n": 0}++ class _Controller:+ def _t(self, key, **kwargs):+ return f"{key}:{kwargs}"++ async def emit_agent_message(self, *args, **kwargs):+ emitted.append((args, kwargs))++ class _Server:+ async def list_messages(self, session_id, directory):+ attempts["n"] += 1+ if attempts["n"] <= 2:+ raise ConnectionError("brief outage")+ if attempts["n"] == 3:+ return []+ return [+ {+ "info": {+ "id": "msg-final",+ "role": "assistant",+ "time": {"completed": True},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "done"}],+ }+ ]++ async def abort_session(self, session_id, directory):+ aborted.append((session_id, directory))+ return True++ class _Agent:+ opencode_config = type(+ "OpenCodeConfig",+ (),+ {"error_retry_limit": 0, "active_turn_timeout_seconds": 0},+ )()+ controller = _Controller()++ @staticmethod+ def _extract_response_text(message):+ return "done"++ async def record_model_hub_native_failure(self, context, diagnostic):+ return False++ async def _run():+ request = AgentRequest(+ context=MessageContext(+ user_id="user",+ channel_id="channel",+ platform="slack",+ ),+ message="work",+ user_message="work",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="composite",+ session_key="slack::channel",+ )+ return await OpenCodePollLoop(_Agent()).run_prompt_poll(+ request,+ _Server(),+ "oc-transport-recovered",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )++ final_text, should_emit = asyncio.run(_run())++ assert final_text == "done"+ assert should_emit is True+ assert aborted == []+ assert not any(item[0][1] == "result" and item[0][2] is True for item in emitted)++def test_mh_chan_001_opencode_restored_poll_records_source_failure():emitted = []removed = []diff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.pyindex d0c1eb870..ac58be464 100644--- a/tests/test_v2_compat_platforms.py+++ b/tests/test_v2_compat_platforms.py@@ -1,5 +1,7 @@from __future__ import annotations+import copy+import jsonimport sysfrom pathlib import Path@@ -126,6 +128,63 @@ def test_to_app_config_uses_shared_agent_defaults() -> None:compat.opencode.active_turn_timeout_seconds== DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS)+ assert DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS == 0+++def test_config_load_neutralizes_legacy_opencode_turn_timeout_default(+ monkeypatch, tmp_path+) -> None:+ """The shipped 5400-second cap is the old default's echo, not a choice.++ Seeding every persisted shape proves the property in one pass: a legacy+ payload (marker absent) with the default echo loads as disabled, while the+ same value carrying the provenance marker — the shape every post-change+ save writes — is an explicit choice that survives. An explicit custom value+ and an absent key keep their meaning.+ """++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ from core.services.settings import default_config+ from vibe import api++ base = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)+ # A genuine pre-change payload carries the echo value and no provenance+ # marker; a post-change save always carries the marker.+ cases = [+ (+ {+ "active_turn_timeout_seconds": 90 * 60,+ "legacy_turn_timeout_neutralized": True,+ },+ None,+ 90 * 60,+ ),+ ({"active_turn_timeout_seconds": 7200}, None, 7200),+ ({"active_turn_timeout_seconds": 0}, None, 0),+ ({"active_turn_timeout_seconds": 90 * 60}, "legacy", 0),+ ({"active_turn_timeout_seconds": 7200}, "legacy", 7200),+ ]+ for index, (override, legacy_shape, expected) in enumerate(cases):+ payload = copy.deepcopy(base)+ payload["agents"]["opencode"].update(override)+ if legacy_shape:+ payload["agents"]["opencode"].pop("legacy_turn_timeout_neutralized", None)+ config_path = tmp_path / f"config-{index}.json"+ config_path.write_text(json.dumps(payload), encoding="utf-8")++ loaded = V2Config.load(config_path=config_path)++ assert loaded.agents.opencode.active_turn_timeout_seconds == expected+ assert loaded.agents.opencode.legacy_turn_timeout_neutralized is True++ payload = copy.deepcopy(base)+ payload["agents"]["opencode"].pop("active_turn_timeout_seconds", None)+ config_path = tmp_path / "config-missing.json"+ config_path.write_text(json.dumps(payload), encoding="utf-8")++ loaded = V2Config.load(config_path=config_path)++ assert loaded.agents.opencode.active_turn_timeout_seconds == 0def test_to_app_config_exposes_opencode_provider_and_reasoning_fields() -> None:diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsxindex f193e6f2c..2db9b77da 100644--- a/ui/src/components/settings/SettingsMessagingPage.tsx+++ b/ui/src/components/settings/SettingsMessagingPage.tsx@@ -433,15 +433,15 @@ export const SettingsMessagingPage: React.FC = () => {control={<CompactFieldtype="number"- min={1}+ min={0}max={1440}value={Math.round(- (config.agents?.opencode?.active_turn_timeout_seconds ?? 5400) / 60+ (config.agents?.opencode?.active_turn_timeout_seconds ?? 0) / 60)}onChange={(event) => {const minutes = Math.max(- 1,- Math.min(1440, Number(event.target.value) || 1)+ 0,+ Math.min(1440, Number(event.target.value) || 0));void persist({...config,diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 212e9d6ad..91eee1e90 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2738,7 +2738,7 @@"errorRetryLimit": "Error Retry Limit","errorRetryLimitHint": "Auto-retry with 'continue' when LLM stream errors occur (0 = no retry)","opencodeActiveTurnTimeout": "OpenCode Turn Limit",- "opencodeActiveTurnTimeoutHint": "Abort and fail an accepted OpenCode turn that produces no result within this many minutes",+ "opencodeActiveTurnTimeoutHint": "Abort and fail an accepted OpenCode turn that produces no result within this many minutes. 0 disables the limit; errors still settle the turn as failed","showDuration": "Show Duration","showDurationHint": "Display task elapsed time in result messages","includeTimeInfo": "Include Current Time",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1ce7f79f0..986b75db2 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2738,7 +2738,7 @@"errorRetryLimit": "错误重试次数","errorRetryLimitHint": "当 LLM 流式响应出错时,自动发送 'continue' 重试(0 = 不重试)","opencodeActiveTurnTimeout": "OpenCode Turn 上限",- "opencodeActiveTurnTimeoutHint": "已接受的 OpenCode Turn 在指定分钟内没有结果时中止并记为失败",+ "opencodeActiveTurnTimeoutHint": "已接受的 OpenCode Turn 在指定分钟内没有结果时中止并记为失败。0 表示不限制;出错时 Turn 仍会记为失败","showDuration": "显示耗时","showDurationHint": "在结果消息中显示任务耗时","includeTimeInfo": "携带时间信息",diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 265e0515a..93f0027d1 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -361,7 +361,8 @@"opencodeEmptyResponse": "OpenCode finished without a model reply. Provider: {provider}; model: {model}; reasoning: {variant}. OpenCode did not expose a provider error for this run.","opencodeProviderRuntimeError": "OpenCode provider request failed. Provider: {provider}; model: {model}; reasoning: {variant}. Detail: {detail}","opencodeBackendError": "OpenCode error: {error}",- "opencodeActiveTurnTimeout": "OpenCode did not produce a result within the configured active-turn limit ({seconds} seconds). The native turn was aborted."+ "opencodeActiveTurnTimeout": "OpenCode did not produce a result within the configured active-turn limit ({seconds} seconds). The native turn was aborted.",+ "opencodePollTransportFailure": "OpenCode was unreachable after {count} consecutive polling failures; the native turn was aborted and recorded as failed."},"success": {"settingsUpdated": "Settings updated successfully!",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 744b4c619..868494625 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -361,7 +361,8 @@"opencodeEmptyResponse": "OpenCode 已结束,但没有产出模型回复。Provider:{provider};模型:{model};推理强度:{variant}。这次运行里 OpenCode 没有暴露服务商错误。","opencodeProviderRuntimeError": "OpenCode 服务商请求失败。Provider:{provider};模型:{model};推理强度:{variant}。详情:{detail}","opencodeBackendError": "OpenCode 错误:{error}",- "opencodeActiveTurnTimeout": "OpenCode 在配置的 active-turn 上限内没有产出结果({seconds} 秒),原生 Turn 已中止。"+ "opencodeActiveTurnTimeout": "OpenCode 在配置的 active-turn 上限内没有产出结果({seconds} 秒),原生 Turn 已中止。",+ "opencodePollTransportFailure": "OpenCode 连续 {count} 次轮询失败,运行时不可达;原生 Turn 已中止并记为失败。"},"success": {"settingsUpdated": "设置更新成功!",