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(review): put every terminal receipt on a message the platform accepts
qiqi62b60b2d137a
diff --git a/core/session_turns.py b/core/session_turns.pyindex 48be90435..a6763d824 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -5361,7 +5361,7 @@ class SessionTurnManager:return Falsedef _turn_origin_native_message_id(self, turn_id: str) -> str:- """The platform message id that opened one Turn, or ``""``.+ """The message a terminal receipt for one Turn belongs on, or ``""``.Read durably rather than from the live indicator because the caller runsAFTER a restart, where no in-memory handle survived. The Delivery's own@@ -5370,6 +5370,13 @@ class SessionTurnManager:Delivery no longer carries the native id — only the ledger row it pointsat does. The snapshot is still consulted first for a Delivery caughtbefore materialization.++ The target is not always the sender's message: a quick-reply callback is+ admitted with no ``native_message_id`` on purpose and wears its indicator+ on the bot echo instead, so ``_delivery_ack_target`` — which recovers+ that echo id from the durable admission context — decides first. Reading+ only the native id would return ``""`` for those turns and silently skip+ the ⚠️, leaving the echo claiming the turn is still running."""if not turn_id or not self._durable_schema_available():@@ -5385,10 +5392,9 @@ class SessionTurnManager:)if delivery is None:return ""- payload = delivery_store.delivery_payload(delivery)- native_id = str(payload.get("native_message_id") or "").strip()- if native_id:- return native_id+ ack_target = self._delivery_ack_target(delivery)+ if ack_target:+ return str(ack_target).strip()message_id = str(delivery.get("message_id") or "").strip()if not message_id:return ""diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 6b56ffa5e..48c54e279 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -534,6 +534,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):self._poll_loop = OpenCodePollLoop(self)self._active_requests: Dict[str, asyncio.Task] = {}+ # The AgentRequest each active task is serving, keyed exactly like+ # ``_active_requests``. ``handle_stop`` receives a *freshly built*+ # request describing the ``/stop`` message itself, so it is not a usable+ # indicator target: the 👀 sits on the message that opened the turn.+ # Only paths that end a turn from OUTSIDE its coroutine need this.+ # A restored poll registers no entry — the process that built its request+ # is gone, and a restored turn's cancellation never stamped a receipt+ # anyway; it ends with the plain removal ``remove_restored_ack`` does.+ self._active_ack_requests: Dict[str, AgentRequest] = {}# Sessions whose in-flight task is being cancelled BY THE USER. The# cancellation lands in the request coroutine, which cannot otherwise# tell a /stop from any other teardown; see ``handle_stop``.@@ -820,6 +829,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):task = asyncio.create_task(self._process_message(request))self._active_requests[request.base_session_id] = task+ self._active_ack_requests[request.base_session_id] = requestif not task:return@@ -831,6 +841,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):finally:if self._active_requests.get(request.base_session_id) is task:self._active_requests.pop(request.base_session_id, None)+ self._active_ack_requests.pop(request.base_session_id, None)self._session_manager.pop_request_session(request.base_session_id)# The poll loop ran to completion above (handle_message awaits the# task), so the turn is fully settled here. Release any web-Chat@@ -1679,7 +1690,23 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# were awaiting it, and ``task.cancel()`` hit an already-finished# task. The receipt is still owed — this stop is about to emit a# silent result, so without it the turn ends with no trace.- await self._remove_ack_reaction(request, terminal_emoji=STOPPED_REACTION_EMOJI)+ #+ # Stamped on the turn's OWN request, never on ``request``: that+ # one describes the ``/stop`` message, so finishing it would put+ # the ⏹️ on the command instead of on the message that started+ # the turn (and leave the real 👀 behind). Codex does the same+ # with the request it recovers from ``clear_pending``.+ stopped_request = self._active_ack_requests.get(request.base_session_id)+ if stopped_request is not None:+ await self._remove_ack_reaction(+ stopped_request,+ terminal_emoji=STOPPED_REACTION_EMOJI,+ )+ else:+ logger.debug(+ "OpenCode stop of %s has no retained request; skipping the receipt",+ request.base_session_id,+ )finally:# Only reached with the intent still set if something above raised# past the handlers; a claimed intent is already gone.diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex 9ad03efe5..31095822d 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -1411,6 +1411,20 @@ class TelegramBot(BaseIMClient):"writing_hand": "✍","thinking_face": "🤔","shrug": "🤷",+ # Terminal receipts. ``setMessageReaction`` accepts ONLY emoji from+ # Telegram's fixed list, and neither ⏹️ nor ⚠️ is on it — sent raw,+ # the whole call is rejected and the turn ends with no trace at all.+ # These two stand-ins are on the list and carry the same reading:+ # 🙊 for "stopped talking on your command" (the stop result is+ # deliberately silent) and 😱 for the alarm of a runtime that died+ # mid-turn. Both spellings of each source emoji are listed because+ # the constants carry U+FE0F and callers may strip it.+ "⏹️": "🙊",+ "⏹": "🙊",+ "stop_button": "🙊",+ "⚠️": "😱",+ "⚠": "😱",+ "warning": "😱",}return aliases.get(normalized, normalized)diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex bb04fc803..a3e6f4dfe 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -603,6 +603,7 @@ def _opencode_agent(primary: AgentRequest, task: asyncio.Task, server: _OpenCode)agent._client_manager = SimpleNamespace(_server_manager=server)agent._user_stopped_sessions = set()+ agent._active_ack_requests = {}agent._steering_states = {primary.base_session_id: _OpenCodeSteerState(task=task,diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex cff08c643..871acd082 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -1244,6 +1244,7 @@ def test_opencode_normal_text_matching_legacy_question_prefix_is_processed():agent.settings_manager = agent.controller.settings_manageragent._session_manager = _SessionManager()agent._active_requests = {}+ agent._active_ack_requests = {}async def _process_message(request):processed.append(request.message)diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.pyindex c0ade29c2..fc4b171fa 100644--- a/tests/test_opencode_stop_receipt.py+++ b/tests/test_opencode_stop_receipt.py@@ -27,6 +27,7 @@ from modules.agents.opencode.agent import OpenCodeAgentdef _agent():agent = object.__new__(OpenCodeAgent)agent._active_requests = {}+ agent._active_ack_requests = {}agent._user_stopped_sessions = set()agent._session_manager = SimpleNamespace(get_request_session=lambda _base: None)agent._abort_active_request = AsyncMock()@@ -95,9 +96,11 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):stop result that follows would leave the turn with no trace at all."""agent = _agent()- receipts: list[object] = []+ receipts: list[tuple[object, object]] = []agent._remove_ack_reaction = AsyncMock(- side_effect=lambda request, *, terminal_emoji=None: receipts.append(terminal_emoji)+ side_effect=lambda request, *, terminal_emoji=None: receipts.append(+ (request, terminal_emoji)+ ))async def in_flight():@@ -105,6 +108,8 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):task = asyncio.create_task(in_flight())agent._active_requests["session-1"] = task+ turn_request = _request()+ agent._active_ack_requests["session-1"] = turn_requestawait asyncio.sleep(0)async def abort(*_args, **_kwargs):@@ -118,11 +123,45 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):agent._abort_active_request = abort- self.assertTrue(await agent.handle_stop(_request()))+ stop_request = _request()+ self.assertTrue(await agent.handle_stop(stop_request))- self.assertEqual(receipts, [STOPPED_REACTION_EMOJI])+ # The receipt belongs on the TURN's request. ``stop_request`` describes+ # the /stop message, so stamping that one would put the ⏹️ on the command+ # and leave the real 👀 in place.+ self.assertEqual(receipts, [(turn_request, STOPPED_REACTION_EMOJI)])+ self.assertIsNot(receipts[0][0], stop_request)self.assertEqual(agent._user_stopped_sessions, set())+ async def test_no_receipt_when_the_turns_request_was_not_retained(self):+ # Better no receipt than one stamped on the wrong message: a turn with+ # nothing retained (restored poll already cleaned up) just ends silently.+ agent = _agent()+ receipts: list[object] = []+ agent._remove_ack_reaction = AsyncMock(+ side_effect=lambda request, *, terminal_emoji=None: receipts.append(terminal_emoji)+ )++ async def in_flight():+ await asyncio.sleep(3600)++ task = asyncio.create_task(in_flight())+ agent._active_requests["session-1"] = task+ await asyncio.sleep(0)++ async def abort(*_args, **_kwargs):+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ agent._abort_active_request = abort++ self.assertTrue(await agent.handle_stop(_request()))++ self.assertEqual(receipts, [])+async def test_the_intent_is_claimed_once(self):# Both paths call consume; the second must see nothing, or a turn whose# coroutine already stamped would get a second ⏹️ from handle_stop.diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 1e6f21cb0..ecec8dc95 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -3250,6 +3250,51 @@ def test_lost_im_turn_without_run_reports_interruption(managers) -> None:assert stamped == [("m-origin", INTERRUPTED_REACTION_EMOJI)]+def test_lost_quick_reply_turn_stamps_the_echo_it_reacted_on(managers) -> None:+ """A quick-reply turn wears its 👀 on the bot echo, not on a user message.++ The callback is admitted with ``native_message_id=None`` on purpose (it would+ collide with platform event dedup) and the echo id survives only in the+ durable admission context. Reading the native id alone yields ``""`` here, so+ the ⚠️ is skipped and the echo keeps claiming the turn is still running —+ exactly the stuck indicator the report exists to retire.+ """++ first, restarted, _engine, _engine_b, _starts = managers+ context = _context()+ admitted = asyncio.run(+ first.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p3",+ content="quick reply killed by restart",+ admission_context={"processing_indicator_message_id": "echo-9"},+ ),+ context=context,+ )+ )+ turn_id = str(admitted.turn_id)+ context.platform_specific["turn_token"] = turn_id+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"+ first._active_identity = lambda _backend, _session_id, logical_id: (+ logical_id,+ f"native-{logical_id}",+ )+ first.on_native_start(+ context,+ backend="codex",+ runtime_key=f"runtime-key-{turn_id}",+ runtime_turn_id=f"runtime-{turn_id}",+ )+ emitted, stamped = _capture_lost_turn_report(restarted)+ restarted._active_identity = lambda *_args: None++ asyncio.run(restarted.recover_durable_delivery_state("ses_fsm", service_restart=True))++ assert [kind for kind, _text in emitted] == ["notify"]+ assert stamped == [("echo-9", INTERRUPTED_REACTION_EMOJI)]++def test_lost_im_turn_report_waits_for_its_transport(managers) -> None:# Recovery runs at startup, BEFORE the IM transports finish connecting.# Emitting then would drop the notice into a client that cannot send, so thediff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.pyindex f0886af27..ad3cb8992 100644--- a/tests/test_telegram_bot.py+++ b/tests/test_telegram_bot.py@@ -14,6 +14,10 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from config import pathsfrom core import chat_discovery+from core.processing_indicator import (+ INTERRUPTED_REACTION_EMOJI,+ STOPPED_REACTION_EMOJI,+)from core.message_context import resolve_context_thread_idfrom modules.agents.native_sessions import NativeResumeSessionfrom modules.im import InlineButton, InlineKeyboard, MessageContext@@ -1115,6 +1119,51 @@ def test_add_reaction_uses_telegram_message_reactions() -> None:reaction_mock.assert_awaited_once_with("123456:test-token", "-100123", "77", "👀", proxy_url=None)+def test_terminal_receipts_are_translated_to_allowed_reactions() -> None:+ """⏹️/⚠️ are not on Telegram's fixed reaction list.++ ``setMessageReaction`` rejects the whole call for an off-list emoji, so an+ untranslated receipt is not a degraded receipt — it is no reaction at all, on+ exactly the turns (a /stop, a runtime that died) whose only trace it is. The+ ack 👀 and the admission receipts are already mapped, so terminal states must+ not be the one family that silently drops.+ """++ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ allowed = {"👀", "🤔", "🤷", "✍", "🙊", "😱"}++ for emoji in (+ STOPPED_REACTION_EMOJI,+ INTERRUPTED_REACTION_EMOJI,+ # The constants carry U+FE0F; a caller that strips it must map too.+ STOPPED_REACTION_EMOJI.rstrip("️"),+ INTERRUPTED_REACTION_EMOJI.rstrip("️"),+ ):+ normalized = bot._normalize_reaction_emoji(emoji)+ assert normalized in allowed, f"{emoji!r} -> {normalized!r} is off Telegram's list"++ # Distinct receipts stay distinguishable after translation.+ assert bot._normalize_reaction_emoji(STOPPED_REACTION_EMOJI) != bot._normalize_reaction_emoji(+ INTERRUPTED_REACTION_EMOJI+ )+++def test_add_reaction_sends_the_translated_terminal_receipt() -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")++ with patch(+ "modules.im.telegram.telegram_api.set_message_reaction",+ new=AsyncMock(return_value={"ok": True}),+ ) as reaction_mock:+ result = asyncio.run(bot.add_reaction(context, "77", STOPPED_REACTION_EMOJI))++ assert result is True+ sent = reaction_mock.await_args.args[3]+ assert sent != STOPPED_REACTION_EMOJI+ assert "️" not in sent++def test_remove_reaction_clears_telegram_message_reactions() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")