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): gate the terminal receipt on a real removal, defer reports

qiqi5d145e50aa5e
diff --git a/core/controller.py b/core/controller.py
index b37e3dbf4..b353afd71 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1038,6 +1038,18 @@ class Controller:
# Poll registration is durable-owner evidence needed by startup recovery.
# All work admission and user-visible delivery remain behind the barrier.
await self._await_runtime_owner_recovery()
+ # Interruption reports for turns on this platform were held back during
+ # recovery precisely because it could not deliver them yet.
+ notify_turns = getattr(self.session_turns, "notify_transport_ready", None)
+ if callable(notify_turns):
+ try:
+ reported = await notify_turns(platform)
+ if reported:
+ logger.info(
+ "Reported %d interrupted turn(s) on %s", reported, platform
+ )
+ except Exception:
+ logger.exception("Failed to report interrupted turns for %s", platform)
self.scheduled_task_service.notify_transport_ready(platform)
notify_update_checker = getattr(self.update_checker, "notify_transport_ready", None)
if callable(notify_update_checker):
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index 434f23d2f..c4cd79873 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -839,16 +839,25 @@ class ProcessingIndicatorService:
if handle.ack_reaction_message_id and handle.ack_reaction_emoji:
reaction_message_id = handle.ack_reaction_message_id
+ removed = False
try:
- await self._get_im_client(handle.context).remove_reaction(
- handle.context,
- handle.ack_reaction_message_id,
- handle.ack_reaction_emoji,
+ removed = bool(
+ await self._get_im_client(handle.context).remove_reaction(
+ handle.context,
+ handle.ack_reaction_message_id,
+ handle.ack_reaction_emoji,
+ )
)
except Exception as err:
logger.debug("Failed to remove reaction ack: %s", err)
else:
- if terminal_emoji:
+ # Adapters report a failed removal by RETURNING False (Slack,
+ # Discord, Telegram, Feishu) as often as by raising, and
+ # ``promote_reaction_to_running`` already treats that value as
+ # authoritative. Stamping on an unremoved 👀 would leave the
+ # message showing running AND stopped at once, so the receipt is
+ # owed only to a removal that actually happened.
+ if terminal_emoji and removed:
try:
await self._get_im_client(handle.context).add_reaction(
handle.context,
diff --git a/core/session_turns.py b/core/session_turns.py
index c054693c5..8a16e6b8b 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -528,6 +528,9 @@ class SessionTurnManager:
self._draining_backends: set[str] = set()
self._deferred_restart_sessions: dict[str, set[str]] = {}
self._queue_recovery_locks: dict[str, asyncio.Lock] = {}
+ # 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]]] = {}
# 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,
@@ -5415,6 +5418,14 @@ class SessionTurnManager:
This is deliberately NOT the shape of a Stop, which stays silent because
the user caused it and already knows. Nobody asked for this ending, so it
has to announce itself.
+
+ Recovery runs from ``_on_runtime_ready``, which fires BEFORE an external
+ transport has necessarily connected, and the notify dispatcher turns a
+ send failure into a ``None`` this method cannot distinguish from success.
+ A turn is terminal once reported, so a lost report is lost for good —
+ hence the report is held until ``notify_transport_ready`` says that
+ platform can actually deliver. ``avibe`` is ready as soon as the runtime
+ is, so Workbench sessions still report inline.
"""
if self.controller is None:
@@ -5428,6 +5439,71 @@ class SessionTurnManager:
exc_info=True,
)
return
+ platform = str(getattr(context, "platform", "") or "")
+ if not self._transport_can_deliver(platform):
+ self._pending_lost_turn_reports.setdefault(platform, []).append(
+ (session_id, str(origin_native_message_id or ""))
+ )
+ logger.info(
+ "lost turn report deferred until %s transport is ready (session=%s)",
+ platform,
+ session_id,
+ )
+ return
+ await self._emit_lost_turn_report(context, session_id, origin_native_message_id)
+
+ def _transport_can_deliver(self, platform: str) -> bool:
+ """Whether ``platform`` can deliver right now.
+
+ Unknown readiness is treated as ready: a controller that does not expose
+ the probe (tests, embedded runners) must not silently swallow reports.
+ """
+
+ probe = getattr(self.controller, "is_im_transport_ready", None)
+ if not callable(probe) or not platform:
+ return True
+ try:
+ return bool(probe(platform))
+ except Exception:
+ logger.debug(
+ "transport readiness probe failed for %s", platform, exc_info=True
+ )
+ return True
+
+ async def notify_transport_ready(self, platform: str) -> int:
+ """Flush the interruption reports held for one platform.
+
+ 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.
+ """
+
+ pending = self._pending_lost_turn_reports.pop(platform, [])
+ if not pending or self.controller is None:
+ return 0
+ reported = 0
+ for session_id, origin_native_message_id in pending:
+ try:
+ context = self._delivery_context(session_id)
+ except Exception:
+ logger.debug(
+ "deferred lost turn report: no delivery context for session=%s",
+ session_id,
+ exc_info=True,
+ )
+ continue
+ if await self._emit_lost_turn_report(
+ context, session_id, origin_native_message_id
+ ):
+ reported += 1
+ return reported
+
+ async def _emit_lost_turn_report(
+ self,
+ context: "MessageContext",
+ session_id: str,
+ origin_native_message_id: str,
+ ) -> bool:
try:
await self.controller.emit_agent_message(
context,
@@ -5440,14 +5516,14 @@ class SessionTurnManager:
session_id,
exc_info=True,
)
- return
+ return False
# The dead process could not clear its own 👀. Retire it here so the
# triggering message stops claiming the turn is still running.
native_message_id = str(origin_native_message_id or "")
service = getattr(self.controller, "processing_indicator", None)
stamp = getattr(service, "stamp_orphaned_terminal_reaction", None)
if not native_message_id or not callable(stamp):
- return
+ return True
try:
await stamp(context, native_message_id, INTERRUPTED_REACTION_EMOJI)
except Exception:
@@ -5456,6 +5532,7 @@ class SessionTurnManager:
session_id,
exc_info=True,
)
+ return True
async def recover_durable_delivery_state(
self,
diff --git a/modules/im/slack.py b/modules/im/slack.py
index d7e147eaa..f6dd497aa 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1391,7 +1391,7 @@ class SlackBot(BaseIMClient):
(e.g. ``ok_hand``), NOT the raw unicode character — sending the codepoint
returns ``invalid_name``. Every emoji used as a reaction by the processing
indicator / handlers must be mapped here: 👀 ack, 👌 queued, 🤖 subagent,
- ✍️ steered, 🤔 unconfirmed, 🤷 not delivered.
+ ✍️ steered, 🤔 unconfirmed, 🤷 not delivered, ⏹️ stopped, ⚠️ interrupted.
"""
name = (emoji or "").strip()
if name.startswith(":") and name.endswith(":") and len(name) > 2:
@@ -1407,6 +1407,12 @@ class SlackBot(BaseIMClient):
"✍": "writing_hand",
"🤔": "thinking_face",
"🤷": "shrug",
+ # Terminal receipts. Both forms of each are listed because the
+ # constants carry U+FE0F and callers may strip it.
+ "⏹️": "stop_button",
+ "⏹": "stop_button",
+ "⚠️": "warning",
+ "⚠": "warning",
}
return aliases.get(name, name)
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 44085c347..2c62f2357 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -13,6 +13,7 @@ from core.native_dispatch_phase import (
backend_dispatch_attempted,
set_dispatch_phase,
)
+from core.processing_indicator import STOPPED_REACTION_EMOJI
from core.run_settlement import SETTLED_BY_BACKEND_REFRESH
from core.session_activities import SessionActivity, activity_completion_output
from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequest
@@ -492,7 +493,9 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(service._turn_gates[runtime_key].lock.locked())
self.assertEqual(request.context.platform_specific["turn_token"], "T1")
self.assertEqual(request.context.platform_specific["agent_runtime_turn_token"], "R1")
- controller.processing_indicator.finish.assert_awaited_once_with(pending_request)
+ controller.processing_indicator.finish.assert_awaited_once_with(
+ pending_request, terminal_emoji=STOPPED_REACTION_EMOJI
+ )
async def test_handle_stop_waits_for_in_flight_steering_write(self):
controller = _StubController()
@@ -674,7 +677,9 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
current_receiver_task=None,
activation_retired=False,
)
- controller.processing_indicator.finish.assert_awaited_once_with(pending_request)
+ controller.processing_indicator.finish.assert_awaited_once_with(
+ pending_request, terminal_emoji=STOPPED_REACTION_EMOJI
+ )
async def test_handle_stop_keeps_runtime_gate_until_cleanup_finishes(self):
controller = _StubController()
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 28ded9733..1e63bccde 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -12,6 +12,7 @@ from unittest.mock import ANY, AsyncMock, Mock, call, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from core.processing_indicator import STOPPED_REACTION_EMOJI
from core.runtime_activation import RuntimeActivationRegistry
_AGENT_PATH = Path(__file__).resolve().parents[1] / "modules/agents/codex/agent.py"
@@ -634,7 +635,9 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
agent._transports = {"/tmp": SimpleNamespace(is_alive=True, send_request=send_request)}
agent._event_handler = SimpleNamespace(clear_pending=clear_pending)
- agent._remove_ack_reaction = AsyncMock(side_effect=lambda request: events.append(("ack", None)))
+ agent._remove_ack_reaction = AsyncMock(
+ side_effect=lambda request, *, terminal_emoji=None: events.append(("ack", terminal_emoji))
+ )
agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())
request = SimpleNamespace(base_session_id="session-1", working_path="/tmp", context=object())
@@ -644,6 +647,9 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(result)
self.assertEqual(events[0][0], "send")
self.assertEqual(events[1][0], "clear")
+ # The stop is silent, so the ⏹️ receipt replacing the running 👀 is the
+ # only thing that tells the user the turn ended on their command.
+ self.assertEqual(events[2], ("ack", STOPPED_REACTION_EMOJI))
async def test_refresh_auth_state_stops_transports_and_invalidates_threads(self):
agent = object.__new__(CodexAgent)
diff --git a/tests/test_delivery_ack_reaction.py b/tests/test_delivery_ack_reaction.py
index c83f3c7ec..d459ff391 100644
--- a/tests/test_delivery_ack_reaction.py
+++ b/tests/test_delivery_ack_reaction.py
@@ -22,9 +22,11 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.processing_indicator import (
_ADMISSION_ACK_REGISTRY_LIMIT,
ACK_REACTION_EMOJI,
+ INTERRUPTED_REACTION_EMOJI,
NOT_DELIVERED_REACTION_EMOJI,
QUEUED_REACTION_EMOJI,
STEERED_REACTION_EMOJI,
+ STOPPED_REACTION_EMOJI,
UNCONFIRMED_REACTION_EMOJI,
ProcessingIndicatorService,
)
@@ -479,6 +481,39 @@ class ReceiptEmojiMappingTests(unittest.TestCase):
self.assertIn(normalized, allowed)
+class TerminalReceiptEmojiMappingTests(unittest.TestCase):
+ """⏹️/⚠️ are newer than the receipts above and are NOT mapped everywhere.
+
+ Slack is where the fix was needed and verified. Telegram publishes a fixed
+ reaction set that contains neither symbol, so the receipt degrades to no
+ reaction there — recorded rather than fixed, because the interruption
+ NOTICE is a real message and carries the meaning on its own.
+ """
+
+ receipts = (STOPPED_REACTION_EMOJI, INTERRUPTED_REACTION_EMOJI)
+
+ def test_slack_maps_both_forms_to_short_names(self):
+ from modules.im.slack import SlackBot
+
+ for emoji in self.receipts:
+ for form in (emoji, emoji.replace("️", "")):
+ with self.subTest(emoji=form):
+ name = SlackBot._slack_reaction_name(form)
+ # Unmapped codepoints fall through raw and reactions.add
+ # rejects them with ``invalid_name``.
+ self.assertTrue(name.isascii(), name)
+
+ def test_telegram_degrades_to_an_unsupported_reaction(self):
+ from modules.im.telegram import TelegramBot
+
+ allowed = {"✍", "👌", "🤔", "🤷", "👀", "🤖"}
+ for emoji in self.receipts:
+ with self.subTest(emoji=emoji):
+ self.assertNotIn(
+ TelegramBot._normalize_reaction_emoji(None, emoji), allowed
+ )
+
+
class DeliveryAdmissionContractTests(unittest.TestCase):
def test_delivery_result_defaults_to_no_admission_claim(self):
result = DeliveryResult("d1", None, "queued")
diff --git a/tests/test_feishu_reaction_emoji.py b/tests/test_feishu_reaction_emoji.py
index d3113695c..cc3f54e0d 100644
--- a/tests/test_feishu_reaction_emoji.py
+++ b/tests/test_feishu_reaction_emoji.py
@@ -17,9 +17,11 @@ sys.path.insert(0, str(ROOT))
from core.processing_indicator import ( # noqa: E402
ACK_REACTION_EMOJI,
+ INTERRUPTED_REACTION_EMOJI,
NOT_DELIVERED_REACTION_EMOJI,
QUEUED_REACTION_EMOJI,
STEERED_REACTION_EMOJI,
+ STOPPED_REACTION_EMOJI,
UNCONFIRMED_REACTION_EMOJI,
)
from core.handlers.message_handler import SUBAGENT_REACTION_EMOJI # noqa: E402
@@ -74,6 +76,22 @@ class FeishuReactionEmojiTests(unittest.TestCase):
self.assertIn(emoji, _EMOJI_MAP)
self.assertTrue(_normalize_emoji(emoji).isascii())
+ def test_terminal_receipts_are_knowingly_unmapped(self):
+ """⏹️/⚠️ degrade to no reaction on Lark, on purpose, for now.
+
+ The module docstring's rule is that every key is read off the published
+ table, never guessed, and that table was not reachable when the receipts
+ landed. An unmapped emoji is the safe failure: ``add_reaction`` warns and
+ the user loses only the receipt, whereas a guessed ``STOP`` would be
+ rejected wholesale. The interruption NOTICE is a real message and is
+ unaffected either way. Delete this test and add the two rows to
+ ``VERIFIED_EMOJI_TYPES`` once the keys are confirmed.
+ """
+
+ for emoji in (STOPPED_REACTION_EMOJI, INTERRUPTED_REACTION_EMOJI):
+ with self.subTest(emoji=emoji):
+ self.assertNotIn(emoji, _EMOJI_MAP)
+
def test_variation_selector_forms_share_one_mapping(self):
"""``_normalize_emoji`` strips colons and whitespace, not U+FE0F."""
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 3682f86d4..d06ad633a 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -3247,6 +3247,56 @@ def test_lost_im_turn_without_run_reports_interruption(managers) -> None:
assert stamped == [("m-origin", 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 the
+ # report is held and flushed from the transport-ready hook instead.
+ first, restarted, _engine, _engine_b, _starts = managers
+ context = _context()
+ admitted = asyncio.run(
+ first.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="im turn killed before the transport came up",
+ native_message_id="m-origin",
+ ),
+ 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
+ ready: set[str] = set()
+ restarted._transport_can_deliver = lambda platform: platform in ready
+
+ asyncio.run(restarted.recover_durable_delivery_state("ses_fsm", service_restart=True))
+
+ assert emitted == [] and stamped == []
+
+ ready.add("avibe")
+ reported = asyncio.run(restarted.notify_transport_ready("avibe"))
+
+ assert reported == 1
+ assert [kind for kind, _text in emitted] == ["notify"]
+ assert stamped == [("m-origin", INTERRUPTED_REACTION_EMOJI)]
+ # The queue is drained, not replayed: a second hook fires nothing.
+ assert asyncio.run(restarted.notify_transport_ready("avibe")) == 0
+ assert len(emitted) == 1
+
+
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 288cb8c9d..12e42bbb2 100644
--- a/tests/test_turn_terminal_reaction.py
+++ b/tests/test_turn_terminal_reaction.py
@@ -111,6 +111,20 @@ class TerminalReactionOnFinishTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(im.calls, [("remove", "m1", ACK_REACTION_EMOJI)])
self.assertIsNone(handle.ack_reaction_emoji)
+ async def test_receipt_is_skipped_when_removal_reports_failure(self):
+ # Slack, Discord, Telegram and Feishu all report a refused removal by
+ # RETURNING False rather than raising, and promote_reaction_to_running
+ # already treats that value as authoritative. A silent False must gate
+ # the receipt exactly like a raise does.
+ im = _FakeIM(remove_ok=False)
+ svc = _svc(im)
+ handle = await _running(svc, im)
+
+ await svc.finish(handle, terminal_emoji=STOPPED_REACTION_EMOJI)
+
+ self.assertEqual(im.calls, [("remove", "m1", ACK_REACTION_EMOJI)])
+ self.assertIsNone(handle.ack_reaction_emoji)
+
async def test_receipt_rejected_by_platform_still_clears_cleanly(self):
# WeChat-like: the terminal emoji is unsupported. The removal is what the
# bookkeeping is keyed on, so the indicator still ends cleared.