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): keep a completed reply superseded by a steer (#2203)

Call White0f10e0bdbb6b
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index 77801221f..ddee331e3 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -18,6 +18,7 @@ from core.handlers.model_hub.retry import RECOVERY_EXHAUSTED_CODE
from core.message_context import build_context_session_key
from core.message_output import terminal_output_for, terminal_turn_output
from core.processing_indicator import STOPPED_REACTION_EMOJI
+from core.reply_enhancer import strip_silent_blocks
from modules.agents.base import AgentRequest
from modules.agents.model_hub import bind_persisted_launch, launch_for_context
from modules.im import MessageContext
@@ -495,6 +496,85 @@ class OpenCodePollLoop:
return text
return None
+ async def _settle_final_text(
+ self,
+ context: MessageContext,
+ session_id: str,
+ messages: list[Dict[str, Any]],
+ baseline_message_ids: set[str],
+ settlement_message: Dict[str, Any],
+ emitted_message_ids: set[str],
+ ) -> str:
+ """Final text for the settlement message, keeping superseded replies.
+
+ A steer injected while the model is finishing a text reply moves the
+ settlement to the reply that answers the steer. Earlier completed
+ replies in the Turn are not the result, but they must still reach the
+ user: the last visible reply is the result, earlier visible replies
+ are emitted as intermediate assistant messages, and a silent reply
+ never displaces a visible one. Emitted IDs are persisted so a
+ restored poll does not deliver the same reply again.
+ """
+
+ settlement_id = _message_info(settlement_message).get("id")
+ replies: list[tuple[str, str]] = []
+ for message in messages:
+ info = _message_info(message)
+ message_id = info.get("id")
+ if message_id == settlement_id:
+ break
+ if (
+ not message_id
+ or message_id in baseline_message_ids
+ or message_id in emitted_message_ids
+ or info.get("role") != "assistant"
+ or not info.get("time", {}).get("completed")
+ or info.get("finish") == "tool-calls"
+ or info.get("error")
+ or info.get("summary")
+ ):
+ continue
+ text = self._agent._extract_response_text(message)
+ if text:
+ replies.append((message_id, text))
+
+ final_text = self._agent._extract_response_text(settlement_message)
+ visible = [
+ (message_id, text)
+ for message_id, text in replies
+ if strip_silent_blocks(text).strip()
+ ]
+ if not strip_silent_blocks(final_text or "").strip() and visible:
+ _, final_text = visible.pop()
+ for message_id, text in visible:
+ logger.info(
+ "Emitting superseded OpenCode reply %s before settling on %s",
+ message_id,
+ settlement_id,
+ )
+ await self._agent.controller.emit_agent_message(
+ context,
+ "assistant",
+ text,
+ parse_mode="markdown",
+ )
+ emitted_message_ids.add(message_id)
+ self._persist_emitted_assistant_messages(session_id, emitted_message_ids)
+ return final_text
+
+ def _persist_emitted_assistant_messages(
+ self, session_id: str, emitted_message_ids: set[str]
+ ) -> None:
+ """Record delivered assistant messages so a restored poll skips them."""
+
+ update_active_poll = getattr(
+ getattr(self._agent, "sessions", None), "update_active_poll_state", None
+ )
+ if callable(update_active_poll):
+ update_active_poll(
+ session_id, emitted_assistant_messages=sorted(emitted_message_ids)
+ )
+
async def run_prompt_poll(
self,
request: AgentRequest,
@@ -671,6 +751,9 @@ class OpenCodePollLoop:
parse_mode="markdown",
)
emitted_assistant_messages.add(message_id)
+ self._persist_emitted_assistant_messages(
+ session_id, emitted_assistant_messages
+ )
if messages:
remaining = deadline - time.monotonic()
@@ -783,7 +866,14 @@ class OpenCodePollLoop:
if last_info.get("finish") != "tool-calls":
if not msg_error:
error_retry_count = 0
- final_text = self._agent._extract_response_text(last_message)
+ final_text = await self._settle_final_text(
+ request.context,
+ session_id,
+ messages,
+ baseline_message_ids,
+ last_message,
+ emitted_assistant_messages,
+ )
if not final_text and not msg_error:
logger.warning(
"Last message %s has no text parts (finish=%s); "
@@ -1057,7 +1147,14 @@ class OpenCodePollLoop:
if last_info.get("finish") != "tool-calls":
if not msg_error:
error_retry_count = 0
- final_text = self._agent._extract_response_text(last_message)
+ final_text = await self._settle_final_text(
+ context,
+ session_id,
+ messages,
+ baseline_message_ids,
+ last_message,
+ emitted_assistant_messages,
+ )
if not final_text and not msg_error:
logger.warning(
"Restored poll: last message %s has no text parts (finish=%s); "
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 6feb21a65..ea1ba1f12 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -362,5 +362,11 @@ scenarios:
kind: recovery
layer: contract
test: tests/test_harness_failure_retry.py::test_harness_restart_notice_retries_through_web_and_controller
+ - id: MESSAGE-DELIVERY-321
+ name: OpenCode steer keeps a superseded completed reply and a silent reply never displaces it
+ status: covered
+ kind: regression
+ layer: contract
+ test: tests/test_opencode_steer_superseded_reply.py::test_steer_keeps_superseded_completed_reply
next_priority:
- - MESSAGE-DELIVERY-321
+ - MESSAGE-DELIVERY-322
diff --git a/tests/test_opencode_steer_superseded_reply.py b/tests/test_opencode_steer_superseded_reply.py
new file mode 100644
index 000000000..1dd099981
--- /dev/null
+++ b/tests/test_opencode_steer_superseded_reply.py
@@ -0,0 +1,201 @@
+"""A steer must not drop a completed OpenCode reply that it superseded (#2184)."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from config.v2_sessions import ActivePollInfo
+from core.processing_indicator import ProcessingIndicatorService
+from modules.agents.base import AgentRequest
+from modules.agents.opencode.poll_loop import OpenCodePollLoop
+from modules.im import MessageContext
+
+REPORT = "Weekly report: all 12 checks passed."
+SILENT = "<silent>callback acknowledged</silent>"
+
+
+def _assistant(message_id, text, *, finish="stop", completed=True):
+ return {
+ "info": {
+ "id": message_id,
+ "role": "assistant",
+ "time": {"completed": 1} if completed else {},
+ "finish": finish,
+ },
+ "parts": [{"type": "text", "text": text}] if text else [],
+ }
+
+
+def _user(message_id, text):
+ return {"info": {"id": message_id, "role": "user"}, "parts": [{"type": "text", "text": text}]}
+
+
+def _turn(reply_a, reply_b, *, finish_a="stop"):
+ """Primary prompt, reply A, two steered callbacks, then reply B."""
+
+ return [
+ _user("primary", "repeat the staged report"),
+ _assistant("reply-a", reply_a, finish=finish_a),
+ _user("steer-1", "watch callback 1"),
+ _user("steer-2", "watch callback 2"),
+ _assistant("reply-b", reply_b),
+ ]
+
+
+def _agent(results, persisted=None):
+ controller = SimpleNamespace(
+ config=SimpleNamespace(language="en"),
+ agent_auth_service=SimpleNamespace(
+ maybe_emit_auth_recovery_message=AsyncMock(return_value=False)
+ ),
+ emit_agent_message=AsyncMock(),
+ )
+ controller.processing_indicator = ProcessingIndicatorService(controller)
+
+ async def _emit_result(_context, text, **_kwargs):
+ results.append(text)
+
+ return SimpleNamespace(
+ controller=controller,
+ opencode_config=SimpleNamespace(error_retry_limit=1, active_turn_timeout_seconds=0),
+ sessions=SimpleNamespace(
+ update_active_poll_state=lambda _session_id, **state: (
+ persisted.update(state) if persisted is not None else None
+ )
+ ),
+ record_model_hub_native_failure=AsyncMock(),
+ _extract_response_text=lambda m: "".join(p.get("text", "") for p in m["parts"]),
+ emit_result_message=_emit_result,
+ _remove_ack_reaction=AsyncMock(),
+ )
+
+
+def _server(messages):
+ return SimpleNamespace(
+ list_messages=AsyncMock(return_value=messages),
+ get_session_status=AsyncMock(return_value=None),
+ prompt_async=AsyncMock(),
+ )
+
+
+async def _live_poll(messages, agent):
+ request = AgentRequest(
+ context=MessageContext(user_id="user", channel_id="channel", platform="discord"),
+ message="repeat the staged report",
+ user_message="repeat the staged report",
+ working_path="/tmp/opencode-steer-fixture",
+ base_session_id="base",
+ composite_session_id="base:fixture",
+ session_key="discord::channel",
+ )
+ final_text, should_emit = await asyncio.wait_for(
+ OpenCodePollLoop(agent).run_prompt_poll(
+ request,
+ _server(messages),
+ "native-session",
+ agent_to_use=None,
+ model_dict=None,
+ reasoning_effort=None,
+ baseline_message_ids=set(),
+ ),
+ timeout=2,
+ )
+ assert should_emit is True
+ return final_text
+
+
+async def _restored_poll(messages, agent, results, *, emitted=()):
+ server = _server(messages)
+ agent._get_server = AsyncMock(return_value=server)
+ poll = ActivePollInfo(
+ opencode_session_id="native-session",
+ base_session_id="base",
+ channel_id="channel",
+ thread_id="",
+ settings_key="channel",
+ working_path="/tmp/opencode-steer-fixture",
+ platform="discord",
+ user_id="user",
+ emitted_assistant_messages=list(emitted),
+ prompt_started_at=time.time(),
+ )
+ assert await asyncio.wait_for(OpenCodePollLoop(agent).run_restored_poll_loop(poll), timeout=2)
+ assert len(results) == 1
+ return results[0]
+
+
+def _assistant_emits(agent):
+ return [
+ call.args[2]
+ for call in agent.controller.emit_agent_message.await_args_list
+ if call.args[1] == "assistant"
+ ]
+
+
[email protected]("path", ["live", "restored"])
+ ("messages", "expected_result", "expected_emits"),
+ [
+ # A silent answer to the steer must not replace the visible reply.
+ (_turn(REPORT, SILENT), REPORT, []),
+ # A visible answer to the steer is the result; A still reaches the user.
+ (_turn(REPORT, "Callbacks noted."), "Callbacks noted.", [REPORT]),
+ # A silent reply superseded by a visible one is not re-sent.
+ (_turn(SILENT, "Callbacks noted."), "Callbacks noted.", []),
+ # When every reply is silent, the Turn stays silent.
+ (_turn(SILENT, SILENT), SILENT, []),
+ ],
+ ids=["silent-steer-reply", "visible-steer-reply", "silent-superseded", "all-silent"],
+)
+async def test_steer_keeps_superseded_completed_reply(
+ monkeypatch, path, messages, expected_result, expected_emits
+):
+ """MESSAGE-DELIVERY-321."""
+
+ monkeypatch.setattr("modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0)
+ results: list[str] = []
+ agent = _agent(results)
+
+ if path == "live":
+ final_text = await _live_poll(messages, agent)
+ else:
+ final_text = await _restored_poll(messages, agent, results)
+
+ assert final_text == expected_result
+ assert _assistant_emits(agent) == expected_emits
+
+
+async def test_tool_call_step_text_is_not_emitted_twice(monkeypatch):
+ """A tool-calls step is already streamed as it completes; settlement must not repeat it."""
+
+ monkeypatch.setattr("modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0)
+ agent = _agent([])
+ messages = _turn("Checking the report first.", SILENT, finish_a="tool-calls")
+
+ final_text = await _live_poll(messages, agent)
+
+ assert final_text == SILENT
+ assert _assistant_emits(agent) == ["Checking the report first."]
+
+
+async def test_restored_poll_does_not_resend_a_persisted_superseded_reply(monkeypatch):
+ """A restart after the superseded reply was delivered must not deliver it again."""
+
+ monkeypatch.setattr("modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0)
+ messages = _turn(REPORT, "Callbacks noted.")
+ persisted: dict = {}
+ await _live_poll(messages, _agent([], persisted))
+
+ results: list[str] = []
+ restored = _agent(results)
+ final_text = await _restored_poll(
+ messages, restored, results, emitted=persisted["emitted_assistant_messages"]
+ )
+
+ assert final_text == "Callbacks noted."
+ assert _assistant_emits(restored) == []