Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(opencode): bound accepted turn lifetime (#1197)

Call White1bf7a11abe68
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 6da44a570..1033d9854 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -4,6 +4,7 @@ from typing import Optional
from config.v2_config import (
DEFAULT_AGENT_BACKEND,
DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS,
+ DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS,
DEFAULT_OPENCODE_ERROR_RETRY_LIMIT,
V2Config,
SlackConfig,
@@ -54,6 +55,7 @@ class OpenCodeCompatConfig:
request_timeout_seconds: int
default_reasoning_effort: Optional[str] = None
error_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
# User's saved default provider from Settings → Backends → OpenCode.
# Used as the ``providerID`` when a routed model string has no ``provider/``
# prefix (most agents.opencode model entries are bare model IDs).
@@ -133,6 +135,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
request_timeout_seconds=60,
default_reasoning_effort=v2.agents.opencode.default_reasoning_effort,
error_retry_limit=v2.agents.opencode.error_retry_limit,
+ active_turn_timeout_seconds=v2.agents.opencode.active_turn_timeout_seconds,
# Surface the user's saved provider choice so the OpenCode agent
# adapter can prepend it as ``providerID`` for bare-model strings.
default_provider=v2.agents.opencode.default_provider,
diff --git a/config/v2_config.py b/config/v2_config.py
index 19ca5b1b9..efb824b8c 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -89,6 +89,11 @@ DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER = 3
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800
DEFAULT_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
DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX = 14
MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12
MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20
@@ -300,6 +305,7 @@ class OpenCodeConfig:
default_agent: Optional[str] = None
default_reasoning_effort: Optional[str] = None
error_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
# 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 legacy
diff --git a/docs/plans/opencode-active-turn-timeout.md b/docs/plans/opencode-active-turn-timeout.md
new file mode 100644
index 000000000..9d59134d2
--- /dev/null
+++ b/docs/plans/opencode-active-turn-timeout.md
@@ -0,0 +1,47 @@
+# OpenCode Active-Turn Timeout
+
+## Background
+
+OpenCode can accept an asynchronous prompt and keep its assistant message
+incomplete while its provider runtime retries indefinitely. Avibe currently polls
+that message without a wall-clock limit. The accepted Turn therefore retains its
+runtime ownership, and the shared OpenCode runtime can prevent unrelated Agent
+work from making progress. An operator abort eventually releases the runtime, but
+the empty completion can then be reported as a successful "No response" result.
+
+The async prompt-start confirmation behavior from #1189 and the rejected-prompt
+handling from #1186 are earlier lifecycle phases and remain unchanged.
+
+## Goal
+
+- Bound every accepted OpenCode Turn with a configurable wall-clock deadline.
+- Abort the native OpenCode session before releasing Avibe's Turn ownership.
+- Settle a timed-out Run as failed with an explicit diagnostic, never as an empty
+ successful result.
+- Apply the same remaining budget when an active poll is restored after restart.
+- Preserve user Stop, service shutdown, explicit provider errors, and normal
+ responses inside the configured limit.
+
+## Solution
+
+Add `agents.opencode.active_turn_timeout_seconds`, defaulting to 90 minutes. The
+deadline begins only after `prompt_async` is accepted. Persist that accepted time
+on the existing active-poll record so restart recovery consumes the original
+budget rather than granting a new one.
+
+At deadline expiry, the poll owner:
+
+1. aborts the exact native OpenCode session with a bounded cleanup request;
+2. records the timeout as a Model Hub native failure when applicable;
+3. emits the existing structured backend-failure terminal result; and
+4. returns without entering the empty-success fallback.
+
+The existing outbound terminal-result chokepoint remains the sole owner of Run
+failure settlement, runtime-gate release, and queued successor admission.
+
+## Scope
+
+The `create_per_run` cwd report is not part of this lifecycle failure. Current
+`master` already keeps per-run Session placement separate from a command's cwd
+and resolves new Session workdirs from explicit metadata, Scope, or runtime
+defaults. This change does not alter task routing or cwd inheritance.
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index c0b715267..37af8b396 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -1088,6 +1088,32 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
system=system_prompt_injection,
tools={"question": False},
)
+ try:
+ read_prompt_started_at = getattr(server, "get_last_prompt_started_at", None)
+ prompt_started_at = (
+ read_prompt_started_at(session_id)
+ if callable(read_prompt_started_at)
+ else None
+ ) or time.time()
+ update_active_poll = getattr(
+ self.sessions,
+ "update_active_poll_state",
+ None,
+ )
+ if callable(update_active_poll):
+ update_active_poll(
+ session_id,
+ prompt_started_at=prompt_started_at,
+ )
+ except Exception:
+ # The pre-write active-poll record remains a safe recovery fallback:
+ # its started_at is only moments older than native acceptance. Do not
+ # fail a live accepted Turn because this timestamp refinement failed.
+ logger.warning(
+ "Failed to persist OpenCode prompt start time for %s",
+ session_id,
+ exc_info=True,
+ )
current_task = asyncio.current_task()
if current_task is None:
raise RuntimeError("OpenCode runner task is unavailable")
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index b58a07ec6..3244c2804 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -4,10 +4,14 @@ from __future__ import annotations
import asyncio
import logging
+import math
import time
from typing import Any, Dict, Optional
-from config.v2_config import DEFAULT_OPENCODE_ERROR_RETRY_LIMIT
+from config.v2_config import (
+ DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS,
+ DEFAULT_OPENCODE_ERROR_RETRY_LIMIT,
+)
from core.backend_failure import emit_backend_failure
from core.message_context import build_context_session_key
from core.message_output import terminal_output_for, terminal_turn_output
@@ -21,6 +25,9 @@ from .server import OpenCodeServerManager
logger = logging.getLogger(__name__)
+_POLL_INTERVAL_SECONDS = 2.0
+_TIMEOUT_ABORT_GRACE_SECONDS = 10.0
+
def _opencode_error_text(error: object) -> str:
if not isinstance(error, dict):
@@ -95,6 +102,79 @@ class OpenCodePollLoop:
if callable(record_failure):
await record_failure(context, diagnostic)
+ def _active_turn_timeout_seconds(self) -> float:
+ raw_timeout = getattr(
+ self._agent.opencode_config,
+ "active_turn_timeout_seconds",
+ DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS,
+ )
+ try:
+ timeout = float(raw_timeout)
+ except (TypeError, ValueError):
+ timeout = float(DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS)
+ if not math.isfinite(timeout) or timeout <= 0:
+ timeout = float(DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS)
+ return timeout
+
+ @staticmethod
+ def _deadline_from_persisted_start(timeout_seconds: float, started_at: object) -> float:
+ try:
+ wall_started_at = float(started_at)
+ except (TypeError, ValueError):
+ wall_started_at = 0.0
+ elapsed = max(0.0, time.time() - wall_started_at) if wall_started_at > 0 else 0.0
+ return time.monotonic() + max(0.0, timeout_seconds - elapsed)
+
+ @staticmethod
+ async def _sleep_with_deadline(deadline: float) -> None:
+ remaining = deadline - time.monotonic()
+ if remaining > 0:
+ await asyncio.sleep(min(_POLL_INTERVAL_SECONDS, remaining))
+
+ async def _settle_active_turn_timeout(
+ self,
+ *,
+ request: AgentRequest,
+ server: OpenCodeServerManager,
+ session_id: str,
+ working_path: str,
+ timeout_seconds: float,
+ ) -> None:
+ seconds = f"{timeout_seconds:g}"
+ diagnostic = (
+ "OpenCode active turn exceeded the configured "
+ f"{seconds}-second wall-clock limit"
+ )
+ logger.warning(
+ "OpenCode active turn timed out: session=%s limit_seconds=%s; aborting native turn",
+ session_id,
+ seconds,
+ )
+ 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 timed-out 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.opencodeActiveTurnTimeout",
+ seconds=seconds,
+ ),
+ request=request,
+ )
+
def _build_restored_handle(self, poll_info):
snapshot = poll_info.processing_indicator or {
"platform": poll_info.platform,
@@ -195,8 +275,9 @@ class OpenCodePollLoop:
seen_tool_calls: set[str] = set()
emitted_assistant_messages: set[str] = set()
- poll_interval_seconds = 2.0
final_text: Optional[str] = None
+ timeout_seconds = self._active_turn_timeout_seconds()
+ deadline = time.monotonic() + timeout_seconds
error_retry_count = 0
error_retry_limit = getattr(
@@ -212,10 +293,23 @@ class OpenCodePollLoop:
poll_iter = 0
while True:
poll_iter += 1
- try:
- messages = await server.list_messages(
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ await self._settle_active_turn_timeout(
+ request=request,
+ server=server,
session_id=session_id,
- directory=request.working_path,
+ working_path=request.working_path,
+ timeout_seconds=timeout_seconds,
+ )
+ return None, False
+ try:
+ messages = await asyncio.wait_for(
+ server.list_messages(
+ session_id=session_id,
+ directory=request.working_path,
+ ),
+ timeout=remaining,
)
if poll_iter % 5 == 0:
last_info = messages[-1].get("info", {}) if messages else {}
@@ -229,9 +323,22 @@ class OpenCodePollLoop:
last_info.get("finish"),
bool(last_info.get("error")),
)
+ except asyncio.TimeoutError:
+ if time.monotonic() >= deadline:
+ await self._settle_active_turn_timeout(
+ request=request,
+ server=server,
+ session_id=session_id,
+ working_path=request.working_path,
+ timeout_seconds=timeout_seconds,
+ )
+ return None, False
+ logger.warning("Timed out polling OpenCode messages before the active-turn deadline")
+ await self._sleep_with_deadline(deadline)
+ continue
except Exception as poll_err:
logger.warning(f"Failed to poll OpenCode messages: {poll_err}")
- await asyncio.sleep(poll_interval_seconds)
+ await self._sleep_with_deadline(deadline)
continue
for message in messages:
@@ -341,7 +448,7 @@ class OpenCodePollLoop:
reasoning_effort=reasoning_effort,
tools={"question": False},
)
- await asyncio.sleep(poll_interval_seconds)
+ await self._sleep_with_deadline(deadline)
continue
except Exception as retry_err:
logger.error(
@@ -397,7 +504,7 @@ class OpenCodePollLoop:
break
break
- await asyncio.sleep(poll_interval_seconds)
+ await self._sleep_with_deadline(deadline)
return final_text, True
@@ -422,8 +529,13 @@ class OpenCodePollLoop:
baseline_message_ids = set(poll_info.baseline_message_ids)
seen_tool_calls = set(poll_info.seen_tool_calls)
emitted_assistant_messages = set(poll_info.emitted_assistant_messages)
- poll_interval_seconds = 2.0
final_text: Optional[str] = None
+ timeout_seconds = self._active_turn_timeout_seconds()
+ persisted_started_at = poll_info.prompt_started_at or poll_info.started_at
+ deadline = self._deadline_from_persisted_start(
+ timeout_seconds,
+ persisted_started_at,
+ )
error_retry_count = 0
error_retry_limit = getattr(
@@ -442,10 +554,25 @@ class OpenCodePollLoop:
poll_iter = 0
while True:
poll_iter += 1
- try:
- messages = await server.list_messages(
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ await self._settle_active_turn_timeout(
+ request=restored_request,
+ server=server,
session_id=session_id,
- directory=poll_info.working_path,
+ working_path=poll_info.working_path,
+ timeout_seconds=timeout_seconds,
+ )
+ self._agent.sessions.remove_active_poll(session_id)
+ await self.remove_restored_ack(poll_info)
+ return
+ try:
+ messages = await asyncio.wait_for(
+ server.list_messages(
+ session_id=session_id,
+ directory=poll_info.working_path,
+ ),
+ timeout=remaining,
)
if poll_iter % 5 == 0:
last_info = messages[-1].get("info", {}) if messages else {}
@@ -459,9 +586,26 @@ class OpenCodePollLoop:
last_info.get("finish"),
bool(last_info.get("error")),
)
+ except asyncio.TimeoutError:
+ if time.monotonic() >= deadline:
+ await self._settle_active_turn_timeout(
+ request=restored_request,
+ server=server,
+ session_id=session_id,
+ working_path=poll_info.working_path,
+ timeout_seconds=timeout_seconds,
+ )
+ self._agent.sessions.remove_active_poll(session_id)
+ await self.remove_restored_ack(poll_info)
+ return
+ logger.warning(
+ "Timed out polling restored OpenCode messages before the active-turn deadline"
+ )
+ await self._sleep_with_deadline(deadline)
+ continue
except Exception as poll_err:
logger.warning(f"Failed to poll OpenCode messages (restored): {poll_err}")
- await asyncio.sleep(poll_interval_seconds)
+ await self._sleep_with_deadline(deadline)
continue
for message in messages:
@@ -586,7 +730,7 @@ class OpenCodePollLoop:
break
break
- await asyncio.sleep(poll_interval_seconds)
+ await self._sleep_with_deadline(deadline)
if final_text:
await self._agent.emit_result_message(
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index 552f92b2c..81b8581ad 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -493,6 +493,7 @@ class SessionsFacade:
opencode_session_id: str,
seen_tool_calls: Optional[List[str]] = None,
emitted_assistant_messages: Optional[List[str]] = None,
+ prompt_started_at: Optional[float] = None,
) -> None:
poll_info = self.sessions_store.get_active_poll(opencode_session_id)
if poll_info:
@@ -500,6 +501,8 @@ class SessionsFacade:
poll_info.seen_tool_calls = seen_tool_calls
if emitted_assistant_messages is not None:
poll_info.emitted_assistant_messages = emitted_assistant_messages
+ if prompt_started_at is not None:
+ poll_info.prompt_started_at = prompt_started_at
self.sessions_store.update_active_poll(poll_info)
def get_all_active_polls(self) -> Dict[str, Any]:
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index b70a842fa..13c8891a3 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -3861,6 +3861,18 @@ scenarios:
# than the late receipt and must clear stale UI working state, not surface a
# false transport failure banner. A genuinely unresolved Stop remains 409.
test: tests/test_internal_server.py::test_cancel_accepts_terminal_settlement_that_races_the_stop_receipt
+ - id: HFR-432
+ name: a timed-out OpenCode Turn releases its Session FIFO and the shared provider lane
+ status: covered
+ kind: recovery
+ layer: scenario
+ backend: opencode
+ # OpenCode may accept a prompt while its provider runtime retries forever. The
+ # 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.
+ test: tests/test_agent_service.py::test_hfr_432_opencode_timeout_releases_fifo_and_shared_runtime
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yaml
index 79d2bbd77..1fe99cff5 100644
--- a/tests/scenarios/harness_failure_recovery/observations.yaml
+++ b/tests/scenarios/harness_failure_recovery/observations.yaml
@@ -260,4 +260,15 @@ observations:
with the Activity case where somebody else genuinely owns the row. Where an
identical emit is copied across backends, the guard has to be cross-backend too
-- one behavior test pins one backend and lets the other two regress.
-
+ - id: HFR-OBS-022
+ date: 2026-08-06
+ source: issue #1190 runtime evidence plus deterministic shared-runtime simulation
+ result: confirmed
+ detail: >-
+ OpenCode can accept a prompt while its provider runtime keeps the assistant
+ message incomplete and retries indefinitely. Avibe's poll owner then retains
+ the Turn without any terminal evidence. The OpenCode server is shared across
+ Vibe Agents, so native abort is the release action for provider-level blocking;
+ the failed terminal result is the existing release action for Avibe's per-Session
+ runtime gate and durable Run. Timeout must perform them in that order and must
+ not fall through to the empty successful-result path.
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index ed12915ec..74b69ee13 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -18,6 +18,9 @@ from core.session_activities import SessionActivityRegistry
from modules.agents import service as service_module
from modules.agents.service import AgentService
from modules.agents.codex.transport import CodexTransport
+from modules.agents.base import AgentRequest
+from modules.agents.opencode.poll_loop import OpenCodePollLoop
+from modules.im import MessageContext
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.session_activities import SQLiteSessionActivityStore
@@ -1482,6 +1485,176 @@ def test_agent_service_recovers_accepted_turn_when_owned_backend_dies() -> None:
asyncio.run(_run())
+def test_hfr_432_opencode_timeout_releases_fifo_and_shared_runtime() -> None:
+ """HFR-432: one stuck native Turn cannot retain either OpenCode lane forever."""
+
+ async def _run() -> None:
+ controller = _Controller()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ emitted: list[tuple[str, str, bool, str | None]] = []
+
+ class _Server:
+ def __init__(self) -> None:
+ self.poll_started = asyncio.Event()
+ self.aborted = asyncio.Event()
+ self.abort_calls: list[tuple[str, str]] = []
+
+ async def list_messages(self, session_id: str, directory: str):
+ self.poll_started.set()
+ return [
+ {
+ "info": {
+ "id": "msg-stuck",
+ "role": "assistant",
+ "time": {},
+ },
+ "parts": [],
+ }
+ ]
+
+ async def abort_session(self, session_id: str, directory: str) -> bool:
+ self.abort_calls.append((session_id, directory))
+ self.aborted.set()
+ return True
+
+ server = _Server()
+
+ class _OpenCodeTimeoutAgent(_RuntimeAgent):
+ name = "opencode"
+ opencode_config = SimpleNamespace(
+ error_retry_limit=0,
+ active_turn_timeout_seconds=0.05,
+ )
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.poll_loop = OpenCodePollLoop(self)
+ self.other_finished = asyncio.Event()
+
+ @staticmethod
+ def _extract_response_text(_message) -> str:
+ return ""
+
+ @staticmethod
+ def _to_relative_path(path: str, _working_path: str) -> str:
+ return path
+
+ async def record_model_hub_native_failure(self, _context, _diagnostic):
+ return False
+
+ async def handle_message(self, request) -> None:
+ self.started.append(request.message)
+ service.mark_runtime_turn_started(request.context)
+ if request.message == "first":
+ final_text, should_emit = await self.poll_loop.run_prompt_poll(
+ request,
+ server,
+ "oc-stuck",
+ agent_to_use=None,
+ model_dict=None,
+ reasoning_effort=None,
+ baseline_message_ids=set(),
+ )
+ assert final_text is None
+ assert should_emit is False
+ return
+ if request.message == "other-agent":
+ # Different runtime key, but the shared provider lane cannot
+ # progress until the stuck native Turn is actually aborted.
+ await server.aborted.wait()
+ self.other_finished.set()
+ await controller.emit_agent_message(
+ request.context,
+ "result",
+ f"{request.message} complete",
+ )
+
+ agent = _OpenCodeTimeoutAgent()
+ agent.controller = controller
+ service.register(agent)
+ controller._t = lambda key, **kwargs: f"{key}:{kwargs.get('seconds')}"
+
+ async def _emit(context, message_type, text, **kwargs):
+ emitted.append(
+ (
+ message_type,
+ text,
+ bool(kwargs.get("is_error")),
+ kwargs.get("terminal_error"),
+ )
+ )
+ if message_type == "result":
+ service.release_runtime_turn(context)
+
+ controller.emit_agent_message = _emit
+
+ def _opencode_request(message: str, runtime_key: str, run_id: str) -> AgentRequest:
+ return AgentRequest(
+ context=MessageContext(
+ user_id=run_id,
+ channel_id=run_id,
+ platform="avibe",
+ platform_specific={"task_execution_id": run_id},
+ ),
+ message=message,
+ user_message=message,
+ working_path="/tmp/work",
+ base_session_id=runtime_key,
+ composite_session_id=runtime_key,
+ session_key=f"avibe::{runtime_key}",
+ )
+
+ first = asyncio.create_task(
+ service.handle_message(
+ "opencode",
+ _opencode_request("first", "agent-a:/tmp/work", "run-first"),
+ )
+ )
+ await asyncio.wait_for(server.poll_started.wait(), timeout=0.5)
+ same_session_successor = asyncio.create_task(
+ service.handle_message(
+ "opencode",
+ _opencode_request(
+ "same-session-successor",
+ "agent-a:/tmp/work",
+ "run-successor",
+ ),
+ )
+ )
+ other_agent = asyncio.create_task(
+ service.handle_message(
+ "opencode",
+ _opencode_request("other-agent", "agent-b:/tmp/work", "run-other"),
+ )
+ )
+
+ await asyncio.sleep(0)
+ assert "same-session-successor" not in agent.started
+ assert "other-agent" in agent.started
+
+ await asyncio.wait_for(
+ asyncio.gather(first, same_session_successor, other_agent),
+ timeout=1,
+ )
+
+ assert server.abort_calls == [("oc-stuck", "/tmp/work")]
+ assert agent.other_finished.is_set()
+ assert agent.started.index("same-session-successor") > agent.started.index("first")
+ timeout_results = [item for item in emitted if item[2]]
+ assert timeout_results == [
+ (
+ "result",
+ "",
+ True,
+ "OpenCode active turn exceeded the configured 0.05-second wall-clock limit",
+ )
+ ]
+ assert all("No response from OpenCode" not in item[1] for item in emitted)
+
+ asyncio.run(_run())
+
+
def test_agent_service_recovery_uses_the_accepted_backend_generation() -> None:
"""HFR-002: a replacement runtime cannot hide the accepted owner's death."""
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index e8bbdee3c..4b23bcab7 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -54,6 +54,7 @@ def _full_config_payload() -> dict:
"default_model": None,
"default_reasoning_effort": None,
"error_retry_limit": 1,
+ "active_turn_timeout_seconds": 7200,
},
"claude": {
"enabled": True,
@@ -1067,6 +1068,7 @@ def test_full_config_serializers_cover_every_config_field(monkeypatch, tmp_path)
assert top_level <= set(payload), f"{label} top-level missing: {top_level - set(payload)}"
assert ui_field_names <= set(payload["ui"]), f"{label} ui missing: {ui_field_names - set(payload['ui'])}"
assert agents <= set(payload["agents"]), f"{label} agents missing: {agents - set(payload['agents'])}"
+ assert payload["agents"]["opencode"]["active_turn_timeout_seconds"] == 7200
_assert_complete("config_to_payload", api.config_to_payload(config))
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index e66ee5cc3..7e3caee9a 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -7,6 +7,8 @@ import time
from dataclasses import dataclass
from pathlib import Path
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from modules.im.base import BaseIMClient, BaseIMConfig, MessageContext
@@ -683,6 +685,7 @@ def test_opencode_restored_ack_preserves_wechat_typing_context():
def test_opencode_prompt_disables_question_tool_for_all_platforms():
calls = []
active_polls = []
+ active_poll_updates = []
recovery_order = []
class _Server:
@@ -750,6 +753,10 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
def remove_active_poll(self, session_id):
return None
+ def update_active_poll_state(self, session_id, **kwargs):
+ recovery_order.append("accepted")
+ active_poll_updates.append((session_id, kwargs))
+
class _PollLoop:
async def run_prompt_poll(self, *args, **kwargs):
return "done", True
@@ -832,7 +839,9 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
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 recovery_order[:2] == ["poll", "prompt"]
+ 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)
steering_snapshot = active_polls[0]["processing_indicator"]["opencode_native_steering"]
assert steering_snapshot["system"] == calls[0]["system"]
@@ -1809,7 +1818,7 @@ def test_opencode_restored_poll_keeps_empty_completion_successful():
platform="slack",
model_dict={"providerID": "glm", "modelID": "glm-5.2"},
reasoning_effort="high",
- prompt_started_at=42.0,
+ prompt_started_at=time.time(),
)
loop = OpenCodePollLoop(_Agent())
@@ -1831,6 +1840,174 @@ def test_opencode_restored_poll_keeps_empty_completion_successful():
assert isinstance(results[0][1]["started_at"], float)
+def test_opencode_restored_poll_consumes_original_timeout_budget():
+ emitted = []
+ removed = []
+ aborted = []
+ list_calls = []
+
+ 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('seconds')}"
+
+ 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):
+ list_calls.append((session_id, directory))
+ return []
+
+ 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.05},
+ )()
+ 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-timeout",
+ 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() - 1,
+ )
+
+ asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))
+
+ assert list_calls == []
+ assert aborted == [("oc-restored-timeout", "/tmp/work")]
+ assert removed == ["oc-restored-timeout"]
+ assert [item[0] for item in emitted] == ["notify", "notify", "result"]
+ assert emitted[1][1] == "error.opencodeActiveTurnTimeout:0.05"
+ assert emitted[2][1:] == (
+ "",
+ True,
+ "silent",
+ "OpenCode active turn exceeded the configured 0.05-second wall-clock limit",
+ )
+ assert all("No response from OpenCode" not in item[1] for item in emitted)
+
+
+def test_opencode_active_turn_poll_propagates_cancellation_without_settlement():
+ emitted = []
+ aborted = []
+ poll_started = asyncio.Event()
+
+ class _Controller:
+ async def emit_agent_message(self, *args, **kwargs):
+ emitted.append((args, kwargs))
+
+ class _Server:
+ async def list_messages(self, session_id, directory):
+ poll_started.set()
+ await asyncio.Event().wait()
+
+ 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": 60},
+ )()
+ 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="stop me",
+ user_message="stop me",
+ working_path="/tmp/work",
+ base_session_id="base",
+ composite_session_id="composite",
+ session_key="slack::channel",
+ )
+ task = asyncio.create_task(
+ OpenCodePollLoop(_Agent()).run_prompt_poll(
+ request,
+ _Server(),
+ "oc-cancelled",
+ agent_to_use=None,
+ model_dict=None,
+ reasoning_effort=None,
+ baseline_message_ids=set(),
+ )
+ )
+ await asyncio.wait_for(poll_started.wait(), timeout=0.5)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ asyncio.run(_run())
+
+ assert aborted == []
+ assert 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.py
index a3f102fa9..7ad2b2823 100644
--- a/tests/test_v2_compat_platforms.py
+++ b/tests/test_v2_compat_platforms.py
@@ -12,6 +12,7 @@ from config.v2_config import (
CodexConfig,
DEFAULT_AGENT_BACKEND,
DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS,
+ DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS,
DEFAULT_OPENCODE_ERROR_RETRY_LIMIT,
DiscordConfig,
OpenCodeConfig,
@@ -120,6 +121,10 @@ def test_to_app_config_uses_shared_agent_defaults() -> None:
assert compat.claude.idle_timeout_seconds == DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
assert compat.opencode is not None
assert compat.opencode.error_retry_limit == DEFAULT_OPENCODE_ERROR_RETRY_LIMIT
+ assert (
+ compat.opencode.active_turn_timeout_seconds
+ == DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS
+ )
def test_to_app_config_exposes_opencode_provider_and_reasoning_fields() -> None:
diff --git a/tests/test_v2_sessions.py b/tests/test_v2_sessions.py
index 61edf4604..37558c0c2 100644
--- a/tests/test_v2_sessions.py
+++ b/tests/test_v2_sessions.py
@@ -180,6 +180,33 @@ def test_active_poll_persists_typing_cleanup_context(tmp_path, monkeypatch):
assert poll.reasoning_effort == "high"
+def test_active_poll_records_native_prompt_acceptance_time(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ store = SessionsStore()
+ sessions = SessionsFacade(store)
+ sessions.add_active_poll(
+ opencode_session_id="oc-accepted",
+ base_session_id="base",
+ channel_id="channel",
+ thread_id="thread",
+ settings_key="channel",
+ working_path="/tmp/work",
+ baseline_message_ids=[],
+ prompt_started_at=None,
+ )
+
+ sessions.update_active_poll_state(
+ "oc-accepted",
+ prompt_started_at=1234.5,
+ )
+
+ reloaded = SessionsStore()
+ reloaded.load()
+ poll = reloaded.get_active_poll("oc-accepted")
+ assert poll is not None
+ assert poll.prompt_started_at == 1234.5
+
+
# --- session_mappings migration tests ---
diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsx
index df5c3c131..a95532896 100644
--- a/ui/src/components/settings/SettingsMessagingPage.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.tsx
@@ -382,6 +382,38 @@ export const SettingsMessagingPage: React.FC = () => {
}
/>
+ <SettingsRow
+ title={t('dashboard.opencodeActiveTurnTimeout')}
+ description={t('dashboard.opencodeActiveTurnTimeoutHint')}
+ control={
+ <CompactField
+ type="number"
+ min={1}
+ max={1440}
+ value={Math.round(
+ (config.agents?.opencode?.active_turn_timeout_seconds ?? 5400) / 60
+ )}
+ onChange={(event) => {
+ const minutes = Math.max(
+ 1,
+ Math.min(1440, Number(event.target.value) || 1)
+ );
+ void persist({
+ ...config,
+ agents: {
+ ...(config.agents || {}),
+ opencode: {
+ ...(config.agents?.opencode || {}),
+ active_turn_timeout_seconds: Math.round(minutes * 60),
+ },
+ },
+ });
+ }}
+ className="w-24 text-center font-mono"
+ />
+ }
+ />
+
<SettingsRow
title={t('dashboard.showDuration')}
description={t('dashboard.showDurationHint')}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a437468e8..956cfb8da 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2323,6 +2323,8 @@
"audioTranscriptEchoHint": "Send recognized text back to the chat when transcription succeeds",
"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",
"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.json
index 538f11e11..2d7d3e905 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2323,6 +2323,8 @@
"audioTranscriptEchoHint": "语音识别成功后,把转写文本也发回当前对话",
"errorRetryLimit": "错误重试次数",
"errorRetryLimitHint": "当 LLM 流式响应出错时,自动发送 'continue' 重试(0 = 不重试)",
+ "opencodeActiveTurnTimeout": "OpenCode Turn 上限",
+ "opencodeActiveTurnTimeoutHint": "已接受的 OpenCode Turn 在指定分钟内没有结果时中止并记为失败",
"showDuration": "显示耗时",
"showDurationHint": "在结果消息中显示任务耗时",
"includeTimeInfo": "携带时间信息",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 46a6c4ce3..3babc27bb 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -303,7 +303,8 @@
"opencodeQuestionToolDisabledRestored": "Restored OpenCode session asked an interactive question, but Avibe disables the OpenCode question tool. Please send a new follow-up message with your answer or direction.",
"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}"
+ "opencodeBackendError": "OpenCode error: {error}",
+ "opencodeActiveTurnTimeout": "OpenCode did not produce a result within the configured active-turn limit ({seconds} seconds). The native turn was aborted."
},
"success": {
"settingsUpdated": "Settings updated successfully!",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index d7fb760b2..3ca5a8609 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -303,7 +303,8 @@
"opencodeQuestionToolDisabledRestored": "恢复中的 OpenCode 会话发起了交互式提问,但 Avibe 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。",
"opencodeEmptyResponse": "OpenCode 已结束,但没有产出模型回复。Provider:{provider};模型:{model};推理强度:{variant}。这次运行里 OpenCode 没有暴露服务商错误。",
"opencodeProviderRuntimeError": "OpenCode 服务商请求失败。Provider:{provider};模型:{model};推理强度:{variant}。详情:{detail}",
- "opencodeBackendError": "OpenCode 错误:{error}"
+ "opencodeBackendError": "OpenCode 错误:{error}",
+ "opencodeActiveTurnTimeout": "OpenCode 在配置的 active-turn 上限内没有产出结果({seconds} 秒),原生 Turn 已中止。"
},
"success": {
"settingsUpdated": "设置更新成功!",