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(review): make the receipt reachable, unraceable, and retried

qiqia391530bda76
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index c4cd79873..15cef8dd8 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -564,6 +564,28 @@ class ProcessingIndicatorService:
logger.debug("Failed to stamp orphaned terminal reaction: %s", err)
return False
+ async def _stamp_terminal_reaction_without_indicator(
+ self,
+ context: MessageContext,
+ terminal_emoji: str,
+ ) -> bool:
+ """Leave the terminal receipt when the turn's indicator was not a reaction.
+
+ There is no 👀 to replace here, so nothing is removed — the receipt is
+ added to the message that started the turn. Capability-gated and
+ best-effort: a platform without reactions (WeChat) or without a target
+ message id simply ends with no receipt, same as before.
+ """
+
+ if not self._mode_supported(self._capabilities(context), "reaction", context):
+ return False
+ message_id = self._reaction_target_message_id(context)
+ try:
+ return bool(await self._get_im_client(context).add_reaction(context, message_id, terminal_emoji))
+ except Exception as err:
+ logger.debug("Failed to add terminal reaction without an indicator: %s", err)
+ return False
+
def _resolve_handle(self, request_or_handle: Any) -> tuple[ProcessingIndicatorHandle, Optional[Any]]:
if isinstance(request_or_handle, ProcessingIndicatorHandle):
return request_or_handle, None
@@ -837,6 +859,15 @@ class ProcessingIndicatorService:
if request is not None:
request.typing_indicator_active = False
+ if terminal_emoji and not handle.ack_reaction_emoji:
+ # The receipt is not a *reaction* feature, it is the only trace a
+ # silent ending leaves. ack_mode defaults to 'typing' on every
+ # platform that has it, so gating the stamp on "the indicator
+ # happened to be a reaction" would make ⏹️/⚠️ invisible for the
+ # default configuration — exactly the turns that emit no result.
+ # Stamp on the originating message instead, wherever reactions work.
+ await self._stamp_terminal_reaction_without_indicator(handle.context, terminal_emoji)
+
if handle.ack_reaction_message_id and handle.ack_reaction_emoji:
reaction_message_id = handle.ack_reaction_message_id
removed = False
diff --git a/core/session_turns.py b/core/session_turns.py
index 687641fdd..48be90435 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -515,6 +515,12 @@ class SessionTurnManager:
lives in ``internal_server``).
"""
+ # Backoff for re-sending an interruption notice the transport claimed to be
+ # ready for and then failed to deliver. Short enough to catch a blip, long
+ # enough that a hard outage does not spin; a class attribute so tests can
+ # shrink it instead of sleeping.
+ LOST_TURN_RETRY_DELAYS: tuple[float, ...] = (5.0, 30.0, 120.0)
+
def __init__(
self,
controller: Any = None,
@@ -531,6 +537,8 @@ class SessionTurnManager:
# Interruption reports owed to turns whose platform was not connected yet
# when recovery ran, keyed by platform. See ``_report_lost_im_turn``.
self._pending_lost_turn_reports: dict[str, list[tuple[str, str]]] = {}
+ # One in-flight retry task per platform for the reports above.
+ self._lost_turn_retry_tasks: dict[str, asyncio.Task[None]] = {}
# The live turn sink per TURN SINK KEY. Each is
# ``{on_chunk, done_event, turn_token}`` — the turn's stream callback +
# completion event + correlation token. Every dispatched turn registers one,
@@ -5452,6 +5460,10 @@ class SessionTurnManager:
platform,
session_id,
)
+ if self._transport_can_deliver(platform):
+ # Held despite a ready transport means the send itself failed, so no
+ # ready callback is coming to flush it — retry on our own clock.
+ self._schedule_lost_turn_retry(platform)
def _transport_can_deliver(self, platform: str) -> bool:
"""Whether ``platform`` can deliver right now.
@@ -5476,7 +5488,9 @@ class SessionTurnManager:
Held in memory only: the turn is already terminal, so a report that never
drains (transport disabled before it connects) is dropped rather than
- replayed on the next start, where it would be stale news.
+ replayed on the next start, where it would be stale news. A send that
+ fails against a connected transport is retained AND retried on a bounded
+ backoff — see ``_schedule_lost_turn_retry`` for why nothing else would.
"""
pending = self._pending_lost_turn_reports.pop(platform, [])
@@ -5507,13 +5521,64 @@ class SessionTurnManager:
if unsent:
self._pending_lost_turn_reports.setdefault(platform, []).extend(unsent)
logger.info(
- "%d lost turn report(s) on %s still undelivered; retained for the "
- "next transport-ready",
+ "%d lost turn report(s) on %s still undelivered; retrying",
len(unsent),
platform,
)
+ self._schedule_lost_turn_retry(platform)
return reported
+ def _schedule_lost_turn_retry(self, platform: str) -> None:
+ """Start the bounded retry for reports this platform failed to deliver.
+
+ ``notify_transport_ready`` has exactly one caller — ``_on_im_ready`` —
+ and ``MultiIMClient`` suppresses further ready callbacks until the
+ platform goes unready again. So a connection that merely hit one API
+ error would hold the notice forever with nothing to nudge it: the retry
+ has to come from here. One task per platform, a few attempts, then give
+ up loudly — the next genuine reconnect flushes whatever is left.
+ """
+
+ existing = self._lost_turn_retry_tasks.get(platform)
+ if existing is not None and not existing.done():
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ logger.debug("no running loop for lost turn retry on %s", platform)
+ return
+ self._lost_turn_retry_tasks[platform] = loop.create_task(
+ self._retry_lost_turn_reports(platform),
+ name=f"lost-turn-report-retry:{platform}",
+ )
+
+ async def _retry_lost_turn_reports(self, platform: str) -> None:
+ try:
+ for delay in self.LOST_TURN_RETRY_DELAYS:
+ await asyncio.sleep(delay)
+ if not self._pending_lost_turn_reports.get(platform):
+ return
+ if not self._transport_can_deliver(platform):
+ # Went unready again; the reconnect's ready callback flushes.
+ return
+ await self.notify_transport_ready(platform)
+ remaining = len(self._pending_lost_turn_reports.get(platform) or [])
+ if remaining:
+ logger.warning(
+ "%d lost turn report(s) on %s undelivered after %d retries; "
+ "held until the transport reconnects",
+ remaining,
+ platform,
+ len(self.LOST_TURN_RETRY_DELAYS),
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.debug("lost turn report retry failed for %s", platform, exc_info=True)
+ finally:
+ if self._lost_turn_retry_tasks.get(platform) is asyncio.current_task():
+ self._lost_turn_retry_tasks.pop(platform, None)
+
async def _emit_lost_turn_report(
self,
context: "MessageContext",
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index c0691c400..6b56ffa5e 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -1244,7 +1244,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
request,
terminal_emoji=(
STOPPED_REACTION_EMOJI
- if request.base_session_id in self._user_stopped_sessions
+ if self.consume_user_stop_intent(request.base_session_id)
else None
),
)
@@ -1634,6 +1634,19 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
backend=self.name,
)
+ def consume_user_stop_intent(self, base_session_id: str) -> bool:
+ """Claim the /stop intent for ``base_session_id``; True for the first claimer.
+
+ Two paths can end a stopped turn — the request coroutine's cancellation
+ handler, and ``handle_stop`` itself when the coroutine settled during the
+ abort — and exactly one of them owes the ⏹️. Claiming decides which.
+ """
+
+ if not base_session_id or base_session_id not in self._user_stopped_sessions:
+ return False
+ self._user_stopped_sessions.discard(base_session_id)
+ return True
+
async def handle_stop(self, request: AgentRequest) -> bool:
task = self._active_requests.get(request.base_session_id)
if not task or task.done():
@@ -1659,7 +1672,17 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
await task
except asyncio.CancelledError:
pass
+
+ if self.consume_user_stop_intent(request.base_session_id):
+ # Nobody claimed the intent, so the cancellation handler never
+ # ran: the abort made the poll loop settle on its own while we
+ # 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)
finally:
+ # Only reached with the intent still set if something above raised
+ # past the handlers; a claimed intent is already gone.
self._user_stopped_sessions.discard(request.base_session_id)
if opencode_session_id:
diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.py
index 0e549c8c4..c0ade29c2 100644
--- a/tests/test_opencode_stop_receipt.py
+++ b/tests/test_opencode_stop_receipt.py
@@ -87,6 +87,52 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(result)
self.assertEqual(agent._user_stopped_sessions, set())
+ async def test_task_that_settles_during_the_abort_still_gets_the_receipt(self):
+ """The abort can end the poll loop before ``task.cancel()`` is reached.
+
+ Then the cancellation handler — the only other receipt-stamping path —
+ never runs, ``cancel()`` is a no-op on a finished task, and the silent
+ stop result that follows would leave the turn with no trace at all.
+ """
+ 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):
+ # Whatever the abort does upstream, the effect here is a task that is
+ # already finished by the time control comes back.
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+ agent._abort_active_request = abort
+
+ self.assertTrue(await agent.handle_stop(_request()))
+
+ self.assertEqual(receipts, [STOPPED_REACTION_EMOJI])
+ self.assertEqual(agent._user_stopped_sessions, set())
+
+ 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.
+ agent = _agent()
+ agent._user_stopped_sessions.add("session-1")
+
+ self.assertTrue(agent.consume_user_stop_intent("session-1"))
+ self.assertFalse(agent.consume_user_stop_intent("session-1"))
+ self.assertFalse(agent.consume_user_stop_intent(""))
+
async def test_stop_of_an_idle_session_publishes_no_intent(self):
agent = _agent()
@@ -111,7 +157,7 @@ class OpenCodeStopReceiptTests(unittest.TestCase):
branch = after.partition("raise")[0]
self.assertTrue(branch, "_process_message no longer handles cancellation")
- self.assertIn("_user_stopped_sessions", branch)
+ self.assertIn("consume_user_stop_intent", branch)
self.assertIn("STOPPED_REACTION_EMOJI", branch)
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index a641b1537..1e6f21cb0 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -3353,6 +3353,68 @@ def test_lost_im_turn_report_survives_a_failed_send(managers) -> None:
assert stamped == [("m-origin", INTERRUPTED_REACTION_EMOJI)]
+def test_retained_lost_turn_report_is_retried_on_its_own_clock(managers) -> None:
+ # notify_transport_ready has exactly one caller (_on_im_ready) and the IM
+ # client suppresses repeat ready callbacks until the platform goes unready,
+ # so a connected transport that merely hit one API error would hold the
+ # notice forever. The retry has to come from the manager itself.
+ _first, restarted, _engine, _engine_b, _starts = managers
+ emitted, _stamped = _capture_lost_turn_report(restarted)
+ restarted.LOST_TURN_RETRY_DELAYS = (0.0, 0.0)
+ restarted._pending_lost_turn_reports["slack"] = [("ses_fsm", "m-origin")]
+ failures = 1
+
+ async def _emit(_context, kind, text, **_kwargs):
+ nonlocal failures
+ emitted.append((kind, text))
+ if failures:
+ failures -= 1
+ return None
+ return "msg-late"
+
+ restarted.controller.emit_agent_message = _emit
+ restarted._delivery_context = lambda _session_id: _context()
+
+ async def _flush_then_settle():
+ assert await restarted.notify_transport_ready("slack") == 0
+ assert restarted._pending_lost_turn_reports["slack"]
+ # Nothing else will call in; the scheduled retry is the only hope.
+ task = restarted._lost_turn_retry_tasks["slack"]
+ await asyncio.wait_for(task, timeout=5)
+
+ asyncio.run(_flush_then_settle())
+
+ assert len(emitted) == 2
+ assert not restarted._pending_lost_turn_reports.get("slack")
+ assert not restarted._lost_turn_retry_tasks
+
+
+def test_lost_turn_retry_gives_up_instead_of_spinning(managers) -> None:
+ # A hard outage must not turn into an unbounded resend loop; the next real
+ # reconnect flushes whatever is still owed.
+ _first, restarted, _engine, _engine_b, _starts = managers
+ emitted, _stamped = _capture_lost_turn_report(restarted)
+ restarted.LOST_TURN_RETRY_DELAYS = (0.0, 0.0)
+ restarted._pending_lost_turn_reports["slack"] = [("ses_fsm", "m-origin")]
+
+ async def _emit(_context, kind, text, **_kwargs):
+ emitted.append((kind, text))
+ return None
+
+ restarted.controller.emit_agent_message = _emit
+ restarted._delivery_context = lambda _session_id: _context()
+
+ async def _flush_and_exhaust():
+ await restarted.notify_transport_ready("slack")
+ await asyncio.wait_for(restarted._lost_turn_retry_tasks["slack"], timeout=5)
+
+ asyncio.run(_flush_and_exhaust())
+
+ # One initial attempt plus one per configured delay, then it stops.
+ assert len(emitted) == 3
+ assert restarted._pending_lost_turn_reports["slack"] == [("ses_fsm", "m-origin")]
+
+
def test_lost_turn_owning_a_run_leaves_the_notice_to_the_harness_lane(managers) -> None:
# A Harness turn already gets harness.run.interrupted.* stamped on its Run.
# Reporting again here would double-notify the same interruption.
diff --git a/tests/test_turn_terminal_reaction.py b/tests/test_turn_terminal_reaction.py
index 12e42bbb2..02fcf982c 100644
--- a/tests/test_turn_terminal_reaction.py
+++ b/tests/test_turn_terminal_reaction.py
@@ -144,6 +144,68 @@ class TerminalReactionOnFinishTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(handle.ack_reaction_emoji)
+class TerminalReceiptWithoutAReactionIndicatorTests(unittest.IsolatedAsyncioTestCase):
+ """ack_mode defaults to 'typing', so most turns own no 👀 to trade.
+
+ Gating the receipt on "the indicator happened to be a reaction" would make
+ ⏹️/⚠️ invisible for the default configuration — i.e. for exactly the silent
+ endings it exists to explain. Nothing is removed here (there is no running
+ reaction); the receipt goes on the message that started the turn.
+ """
+
+ async def test_typing_turn_still_gets_the_receipt(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), typing_indicator_active=True)
+
+ await svc.finish(handle, terminal_emoji=STOPPED_REACTION_EMOJI)
+
+ self.assertEqual(im.calls, [("add", "m1", STOPPED_REACTION_EMOJI)])
+
+ async def test_no_receipt_without_a_terminal_emoji(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), typing_indicator_active=True)
+
+ await svc.finish(handle)
+
+ self.assertEqual(im.calls, [])
+
+ async def test_no_receipt_without_a_target_message(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(message_id=""), typing_indicator_active=True)
+
+ await svc.finish(handle, terminal_emoji=STOPPED_REACTION_EMOJI)
+
+ self.assertEqual(im.calls, [])
+
+ async def test_platform_without_reactions_is_skipped(self):
+ # WeChat has no reaction API at all; asking for one would just error.
+ im = _FakeIM()
+ svc = _svc(im)
+ context = MessageContext(user_id="u1", channel_id="c1", message_id="m1", platform="wechat")
+ handle = ProcessingIndicatorHandle(context=context, typing_indicator_active=True)
+
+ await svc.finish(handle, terminal_emoji=STOPPED_REACTION_EMOJI)
+
+ self.assertEqual(im.calls, [])
+
+ async def test_a_running_reaction_is_still_replaced_not_duplicated(self):
+ # Regression guard for the two paths colliding: when the 👀 IS owned, the
+ # receipt must come from the replacement path only — one add, not two.
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = await _running(svc, im)
+
+ await svc.finish(handle, terminal_emoji=STOPPED_REACTION_EMOJI)
+
+ self.assertEqual(
+ [call for call in im.calls if call[0] == "add"],
+ [("add", "m1", STOPPED_REACTION_EMOJI)],
+ )
+
+
class OrphanedTerminalReactionTests(unittest.IsolatedAsyncioTestCase):
"""Restart recovery has no handle — only the durable Delivery's message id."""