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.

feat(im): acknowledge mid-turn delivery admission with a reaction receipt (#1211)

Qi Qi704ce1c5dabd
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 4bb401c45..e17f5a0c6 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -424,6 +424,9 @@ class MessageHandler(BaseHandler):
)
restored_route = restored_route if isinstance(restored_route, dict) else None
+ if durable_delivery_owned:
+ self._restore_reaction_target(context, delivery_context)
+
if restored_route is not None:
base_session_id = str(
restored_route.get("base_session_id") or base_session_id
@@ -598,6 +601,12 @@ class MessageHandler(BaseHandler):
delivery_intent=delivery_intent,
downloaded_attachment_paths=downloaded_attachment_paths,
admission_context={
+ # The reaction target is not always the sender's own
+ # message (a quick reply reacts on its bot echo), and it
+ # cannot be rebuilt from the Delivery snapshot.
+ "processing_indicator_message_id": self._reaction_target(
+ context
+ ),
"message_handler_route": {
"base_session_id": base_session_id,
"composite_session_id": composite_key,
@@ -947,8 +956,65 @@ class MessageHandler(BaseHandler):
from core.inbox_events import bus
bus.publish("queue.updated", {"session_id": session_id})
+ # This is the only place that knows an input's admission outcome: a
+ # Delivery that did not start its own turn returns here and the caller
+ # stops, so without a receipt the user sees nothing at all for every
+ # message sent while a turn is running.
+ await self._ack_delivery_admission(context, result)
return True
+ @staticmethod
+ def _reaction_target(context: MessageContext) -> Optional[str]:
+ """The message this input's reactions belong on, when it is not its own.
+
+ A quick-reply callback is dispatched with ``message_id=None`` (to bypass
+ platform event dedup) and reacts on its bot echo instead. The echo id
+ only exists in this process, so it has to travel with the Delivery.
+ """
+
+ target = (context.platform_specific or {}).get(
+ "processing_indicator_message_id"
+ )
+ return str(target) if target else None
+
+ @staticmethod
+ def _restore_reaction_target(
+ context: MessageContext,
+ delivery_context: Any,
+ ) -> None:
+ """Put a Delivery's reaction target back on its rehydrated context.
+
+ Durable hydration restores only the native message id, so without this a
+ promoted quick-reply Delivery computes a different receipt key: its 👌
+ would never be cleared and its own indicator would target the synthetic
+ delivery id instead of the echo.
+ """
+
+ if not isinstance(delivery_context, dict):
+ return
+ target = delivery_context.get("processing_indicator_message_id")
+ if not target:
+ return
+ spec = dict(context.platform_specific or {})
+ spec["processing_indicator_message_id"] = str(target)
+ context.platform_specific = spec
+
+ async def _ack_delivery_admission(self, context: MessageContext, result: Any) -> None:
+ """Report one admission outcome back to the sender, best effort."""
+
+ indicator = getattr(self.controller, "processing_indicator", None)
+ ack = getattr(indicator, "ack_delivery_state", None)
+ if not callable(ack):
+ return
+ try:
+ await ack(
+ context,
+ state=str(getattr(result, "state", "") or ""),
+ admission=str(getattr(result, "admission", "") or ""),
+ )
+ except Exception as err:
+ logger.debug("Failed to acknowledge delivery admission: %s", err)
+
@staticmethod
def _cleanup_unowned_attachment_paths(paths: List[str]) -> None:
from pathlib import Path
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index d0bffe7dd..362f4c31c 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -9,7 +9,9 @@ details; they should only ask this service to delete or finish an indicator.
from __future__ import annotations
import asyncio
+import copy
import logging
+from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from typing import Any, Optional
@@ -26,6 +28,39 @@ ACK_REACTION_EMOJI = "👀"
# actually starts. See AgentService.handle_message (show_queued_reaction /
# promote_reaction_to_running).
QUEUED_REACTION_EMOJI = "👌"
+# Admission receipts for an IM message that did NOT start its own turn. Without
+# them a message sent while a turn is already running gets no feedback at all:
+# the message handler hands it to its durable Delivery owner and returns before
+# any processing indicator is started, and a steered input never dispatches a
+# turn of its own. See MessageHandler._admit_human_delivery.
+STEERED_REACTION_EMOJI = "✍️"
+UNCONFIRMED_REACTION_EMOJI = "🤔"
+NOT_DELIVERED_REACTION_EMOJI = "🤷"
+# Delivery state -> admission receipt. States that own a turn (``claimed``,
+# ``steering``, ``interrupt_waiting``) are absent on purpose: their feedback is
+# the turn's own processing indicator, and an ``accepted`` Delivery is only
+# reported here when it was steered into a turn already running.
+_ADMISSION_ACK_REACTIONS: dict[str, str] = {
+ "accepted": STEERED_REACTION_EMOJI,
+ "queued": QUEUED_REACTION_EMOJI,
+ "pending_steer": QUEUED_REACTION_EMOJI,
+ "reconciling_steer": UNCONFIRMED_REACTION_EMOJI,
+ "retired": NOT_DELIVERED_REACTION_EMOJI,
+}
+# Receipts that can still be replaced or cleared later, and are therefore worth
+# remembering. The rest are final: the Delivery they describe never starts a turn
+# of its own, so nothing would ever read the entry back and keeping it would grow
+# the registry by one key per mid-turn message for the life of the process.
+_REPLACEABLE_ADMISSION_STATES = frozenset(
+ {"queued", "pending_steer", "reconciling_steer"}
+)
+# Backstop for receipts whose Delivery never reaches a turn (a queue drained by a
+# Stop, a session archived mid-wait). Bounded FIFO eviction: dropping the oldest
+# key only forfeits a later replace/clear, never the reaction itself.
+_ADMISSION_ACK_REGISTRY_LIMIT = 1024
+# Registry marker for a message whose own turn has started. Kept so a receipt
+# still in flight when the turn began cannot decorate it afterwards.
+_ADMISSION_ACK_CONSUMED = "\x00turn-started"
@dataclass
@@ -101,6 +136,8 @@ class ProcessingIndicatorService:
self.controller = controller
self.config = controller.config
self._indicators_by_turn_token: dict[str, Any] = {}
+ self._admission_acks: dict[str, str] = {}
+ self._admission_ack_locks: dict[str, asyncio.Lock] = {}
def _get_im_client(self, context: MessageContext):
getter = getattr(self.controller, "get_im_client_for_context", None)
@@ -204,8 +241,193 @@ class ProcessingIndicatorService:
except asyncio.CancelledError:
raise
+ def _admission_ack_registry(self) -> dict[str, str]:
+ registry = getattr(self, "_admission_acks", None)
+ if not isinstance(registry, dict):
+ registry = {}
+ self._admission_acks = registry
+ return registry
+
+ def _remember_admission_ack(self, key: str, value: str) -> None:
+ registry = self._admission_ack_registry()
+ registry.pop(key, None)
+ registry[key] = value
+ while len(registry) > _ADMISSION_ACK_REGISTRY_LIMIT:
+ registry.pop(next(iter(registry)), None)
+
+ def _admission_ack_locks_registry(self) -> dict[str, list]:
+ locks = getattr(self, "_admission_ack_locks", None)
+ if not isinstance(locks, dict):
+ locks = {}
+ self._admission_ack_locks = locks
+ return locks
+
+ @asynccontextmanager
+ async def _admission_ack_guard(self, key: str):
+ """Serialize every receipt operation on one message.
+
+ Both halves await a platform call, so without this an ``add_reaction``
+ still in flight would record its emoji *after* the turn's ``start()``
+ already looked for one to clear, stranding a 👌 next to the running
+ indicator.
+ """
+
+ locks = self._admission_ack_locks_registry()
+ entry = locks.get(key)
+ if entry is None:
+ entry = locks[key] = [asyncio.Lock(), 0]
+ entry[1] += 1
+ try:
+ async with entry[0]:
+ yield
+ finally:
+ entry[1] -= 1
+ if entry[1] <= 0:
+ locks.pop(key, None)
+
+ def _admission_ack_key(self, context: MessageContext) -> Optional[str]:
+ message_id = self._reaction_target_message_id(context)
+ if not message_id:
+ return None
+ return "|".join(
+ (
+ self._get_context_platform(context),
+ str(context.channel_id or ""),
+ str(message_id),
+ )
+ )
+
+ @staticmethod
+ def _admission_receipt(state: str, admission: str) -> Optional[str]:
+ """Resolve one Delivery state into the receipt it should show.
+
+ ``accepted`` is deliberately gated on explicit steer provenance: an
+ idempotent re-entry of an already accepted Delivery reports the state
+ without an ``admission``, and that observation says nothing about
+ whether the input joined a running turn or started its own.
+ """
+
+ normalized = str(state or "").strip()
+ if normalized == "accepted" and admission != "steered":
+ return None
+ return _ADMISSION_ACK_REACTIONS.get(normalized)
+
+ async def ack_delivery_state(
+ self,
+ context: MessageContext,
+ *,
+ state: str,
+ admission: str = "",
+ ) -> Optional[str]:
+ """Report the admission outcome of one IM input as a reaction receipt.
+
+ Applies only to input that did not start a turn of its own: a started
+ turn already answers with the normal processing indicator. Returns the
+ emoji that was applied, or ``None`` when nothing was reported.
+ """
+
+ if admission == "started":
+ return None
+ emoji = self._admission_receipt(state, admission)
+ if not emoji:
+ return None
+ message_id = self._reaction_target_message_id(context)
+ if not message_id:
+ return None
+ capabilities = self._capabilities(context)
+ if not self._mode_supported(capabilities, "reaction", context):
+ # Platforms without reactions (e.g. WeChat) stay silent rather than
+ # posting a bubble per queued message.
+ return None
+ key = self._admission_ack_key(context)
+ if not key:
+ return None
+ async with self._admission_ack_guard(key):
+ registry = self._admission_ack_registry()
+ previous = registry.get(key)
+ if previous == _ADMISSION_ACK_CONSUMED:
+ # This message's own turn already took the message over; a late
+ # receipt would sit next to (or replace) the running indicator.
+ return None
+ if previous == emoji:
+ return emoji
+ im_client = self._get_im_client(context)
+ if previous:
+ try:
+ await im_client.remove_reaction(context, message_id, previous)
+ except Exception as err:
+ logger.debug("Failed to remove previous admission ack: %s", err)
+ try:
+ applied = await im_client.add_reaction(context, message_id, emoji)
+ except Exception as err:
+ logger.debug("Failed to add admission ack reaction: %s", err)
+ applied = False
+ if not applied:
+ registry.pop(key, None)
+ return None
+ if str(state or "").strip() in _REPLACEABLE_ADMISSION_STATES:
+ self._remember_admission_ack(key, emoji)
+ else:
+ # Final receipt: the Delivery behind it never starts a turn, so
+ # nothing will ever replace or clear this reaction.
+ registry.pop(key, None)
+ return emoji
+
+ async def clear_admission_ack(self, context: MessageContext) -> None:
+ """Remove the admission receipt once this input's own turn takes over."""
+
+ key = self._admission_ack_key(context)
+ if not key:
+ return
+ async with self._admission_ack_guard(key):
+ registry = self._admission_ack_registry()
+ emoji = registry.get(key)
+ # Mark the message as taken over before awaiting the platform call:
+ # a receipt that arrives late must not re-decorate a running turn.
+ self._remember_admission_ack(key, _ADMISSION_ACK_CONSUMED)
+ if not emoji or emoji == _ADMISSION_ACK_CONSUMED:
+ return
+ try:
+ await self._get_im_client(context).remove_reaction(
+ context,
+ self._reaction_target_message_id(context),
+ emoji,
+ )
+ except Exception as err:
+ logger.debug("Failed to remove admission ack reaction: %s", err)
+
+ async def clear_merged_admission_acks(self, context: MessageContext) -> None:
+ """Clear the receipts of every Delivery merged into this one Turn.
+
+ Deliveries without a native message id (quick-reply callbacks) can be
+ merged into a single Turn, but only the FIRST one hydrates the dispatch
+ context. The others are accepted as part of that Turn and never
+ dispatched on their own, so their 👌 would stay up forever unless this
+ Turn clears their reaction targets too.
+ """
+
+ payload = context.platform_specific or {}
+ targets = payload.get("delivery_ack_targets") if isinstance(payload, dict) else None
+ if not isinstance(targets, (list, tuple)) or not targets:
+ return
+ own_target = self._reaction_target_message_id(context)
+ for target in targets:
+ target_id = str(target or "").strip()
+ if not target_id or target_id == own_target:
+ continue
+ merged = copy.copy(context)
+ spec = dict(payload)
+ spec["processing_indicator_message_id"] = target_id
+ merged.platform_specific = spec
+ await self.clear_admission_ack(merged)
+
async def start(self, context: MessageContext, agent_name: str, *, enabled: bool = True) -> ProcessingIndicatorHandle:
handle = ProcessingIndicatorHandle(context=context)
+ # A queued input carries an admission receipt (👌) that this turn's own
+ # indicator now replaces. Platforms that stack reactions would otherwise
+ # show both, and the receipt would outlive the wait it described.
+ await self.clear_admission_ack(context)
+ await self.clear_merged_admission_acks(context)
if not enabled:
return handle
diff --git a/core/session_turns.py b/core/session_turns.py
index 58e025671..3690bf4af 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -467,6 +467,12 @@ class DeliveryResult:
state: str
turn_id: str | None = None
reason: str | None = None
+ # How this input reached its Turn. ``accepted`` alone cannot tell a Delivery
+ # that STARTED its own Turn from one that was STEERED into a Turn already
+ # running: both settle as ``accepted``. Surfaces that report the admission
+ # back to the user need that distinction, because a started Turn already
+ # owns its own processing indicator while a steered input has none.
+ admission: Literal["", "started", "steered"] = ""
@dataclass(frozen=True)
@@ -1535,11 +1541,16 @@ class SessionTurnManager:
or attempted_turn_id
or ""
).strip()
+ state = str(delivery["state"])
return DeliveryResult(
delivery_id,
str(delivery.get("message_id") or "").strip() or None,
- str(delivery["state"]),
+ state,
turn_id or None,
+ # Every caller reaches here right after dispatching a Turn this
+ # Delivery participates in, so an owned state means this input
+ # started the work rather than joining a Turn already running.
+ admission="started" if state in {"claimed", "accepted"} else "",
)
@classmethod
@@ -1964,6 +1975,16 @@ class SessionTurnManager:
{
"delivery_id": str(deliveries[0]["id"]),
"delivery_ids": [str(row["id"]) for row in deliveries],
+ # Every reaction target this Turn absorbed. Only the first
+ # Delivery hydrates the dispatch context, so without this the
+ # admission receipts of the merged rest are never cleared.
+ "delivery_ack_targets": [
+ target
+ for target in (
+ self._delivery_ack_target(row) for row in deliveries
+ )
+ if target
+ ],
# Every display snapshot this Turn dispatches, in FIFO order.
# ``_hydrate_delivery_context`` set the singular ``display_text`` from
# the FIRST Delivery only, while ``_segment_dispatch_text`` sends the
@@ -2825,6 +2846,7 @@ class SessionTurnManager:
str((saved or {}).get("message_id") or delivery_id),
"accepted",
target_turn_id or None,
+ admission="steered",
)
if should_drain:
await self.drain_delivery_queue(session_id)
@@ -4398,6 +4420,78 @@ class SessionTurnManager:
return True
return False
+ @staticmethod
+ def _delivery_ack_target(delivery: dict[str, Any]) -> Optional[str]:
+ """Return the message an admission receipt for this Delivery sits on.
+
+ Usually the sender's own message, but a quick-reply callback is
+ dispatched with ``message_id=None`` (to bypass platform event dedup) and
+ reacts on its bot echo instead. That echo id only survives in the
+ durable admission context.
+ """
+
+ admission_context = delivery_store.delivery_admission_context(delivery)
+ if isinstance(admission_context, dict):
+ target = admission_context.get("processing_indicator_message_id")
+ if target:
+ return str(target)
+ payload = delivery_store.delivery_payload(delivery)
+ return str(payload.get("native_message_id") or "").strip() or None
+
+ def _delivery_receipt_context(
+ self,
+ session_id: str,
+ delivery: dict[str, Any],
+ ) -> Optional["MessageContext"]:
+ """Rebuild just enough routing to react on one Delivery's own message."""
+
+ payload = delivery_store.delivery_payload(delivery)
+ platform = str(payload.get("platform") or "")
+ native_message_id = str(payload.get("native_message_id") or "").strip()
+ target = self._delivery_ack_target(delivery)
+ if not platform or platform == "avibe" or not target:
+ # Nothing to decorate: only an IM input has a reaction target, and
+ # the Workbench composer is P3 (it never reaches a pending steer).
+ return None
+ context = self._delivery_context(session_id)
+ context.platform = platform
+ context.message_id = native_message_id or None
+ spec = dict(context.platform_specific or {})
+ spec["processing_indicator_message_id"] = target
+ context.platform_specific = spec
+ return context
+
+ async def _report_delivery_receipts(
+ self,
+ session_id: str,
+ deliveries: list[dict[str, Any]],
+ *,
+ state: str,
+ admission: str = "",
+ ) -> None:
+ """Report the admission outcome of Deliveries settled away from ingress.
+
+ The admission call that returned ``pending_steer`` already told the
+ sender its message was queued, but the attempt that resolves it runs
+ later (``_run_pending_steers``, recovery) and its result is consumed
+ there, not by the ingress caller — so this is the only place that can
+ report that the message joined the running turn (✍️), was definitively
+ refused (🤷), or is still unconfirmed (🤔).
+ """
+
+ indicator = getattr(self.controller, "processing_indicator", None)
+ ack = getattr(indicator, "ack_delivery_state", None)
+ if not callable(ack):
+ return
+ for delivery in deliveries or []:
+ try:
+ context = self._delivery_receipt_context(session_id, delivery)
+ if context is None:
+ continue
+ await ack(context, state=state, admission=admission)
+ except Exception as err:
+ logger.debug("Failed to report admission receipt: %s", err)
+
async def _run_pending_steers(
self,
session_id: str,
@@ -4450,7 +4544,17 @@ class SessionTurnManager:
attempt_id=attempt_id,
),
)
- await self._finish_steer(delivery_id, receipt, context=context)
+ result = await self._finish_steer(delivery_id, receipt, context=context)
+ # Every row of the attempt settles together, so the leader's outcome
+ # is the batch's outcome: accepted upgrades 👌 to ✍️, a definitive
+ # refusal after the Session went inactive retires it to 🤷, and an
+ # unconfirmed receipt reports 🤔.
+ await self._report_delivery_receipts(
+ session_id,
+ claimed_batch,
+ state=result.state,
+ admission=result.admission,
+ )
def _publish_materialized_delivery(self, delivery_id: str) -> None:
"""Publish one accepted immutable Message after its transaction commits."""
@@ -5184,6 +5288,14 @@ class SessionTurnManager:
),
context=context,
)
+ # Recovery re-enters ``deliver`` behind the ingress handler's back,
+ # so the receipt this admission earned has no other reporter.
+ await self._report_delivery_receipts(
+ observation.session_id,
+ [delivery],
+ state=result.state,
+ admission=result.admission,
+ )
return result.state != "reserved"
target_turn_id = str(delivery.get("current_target_turn_id") or "")
if delivery["state"] == "pending_steer" and target_turn_id:
@@ -5547,6 +5659,14 @@ class SessionTurnManager:
reservation["id"],
)
else:
+ # Same as the observation path: nothing else reports the
+ # admission outcome of a Delivery revived by recovery.
+ await self._report_delivery_receipts(
+ target_session,
+ [reservation],
+ state=result.state,
+ admission=result.admission,
+ )
if result.state != "reserved":
recovered.append(target_session)
with self._sqlite_engine().connect() as conn:
diff --git a/docs/plans/im-delivery-admission-ack.md b/docs/plans/im-delivery-admission-ack.md
new file mode 100644
index 000000000..d8258431a
--- /dev/null
+++ b/docs/plans/im-delivery-admission-ack.md
@@ -0,0 +1,161 @@
+# Admission Receipts for Mid-Turn IM Input
+
+Status: implemented
+Scope: IM platforms with reaction support (Slack / Discord / Telegram / Lark).
+WeChat is unaffected (no reactions).
+
+## 1. Background
+
+A user sends a message, the agent answers with 👀, and everything reads fine —
+until the user sends a *second* message while that turn is still running. That
+message gets no reaction, no typing indicator, no bubble. The user cannot tell
+whether it was folded into the running turn, queued behind it, or dropped.
+
+The 👌 "queued" receipt from [`avibe-queued-reaction-emoji.md`](avibe-queued-reaction-emoji.md)
+does not cover this. That design is owned by the in-memory runtime gate in
+`AgentService.handle_message`, which is only reached once a message is actually
+dispatched. Durable Delivery admission now runs earlier:
+
+```python
+# core/handlers/message_handler.py
+if admitted:
+ return None # ← mid-turn input stops here
+...
+if is_human:
+ processing_indicator = await ...start(context, agent_name)
+```
+
+`_admit_human_delivery` returns `True` for every input it hands to its durable
+owner, so the indicator is only ever started by the *dispatch* that follows a
+claim. That leaves two silent cases:
+
+| Input | Delivery path | Feedback before this change |
+| --- | --- | --- |
+| First message, idle session | claimed → dispatched → `start()` | 👀 |
+| Steered into a running turn | materialized as `accepted`, never dispatched | none |
+| Queued behind a running turn | `queued` until the turn ends, then dispatched | none until it starts |
+
+## 2. Goal
+
+Every IM input gets an immediate, honest receipt of what happened to it, using
+the state its durable owner actually recorded — not a guess made before
+admission.
+
+## 3. Design
+
+### 3.1 Distinguish started from steered
+
+`accepted` is the terminal state for both a Delivery that started its own Turn
+and one that was steered into a Turn already running, so the state alone cannot
+drive the receipt. `DeliveryResult` gains `admission: "" | "started" | "steered"`:
+
+- `_committed_delivery_result` reports `started` for an owned state, because
+ every caller reaches it right after dispatching a Turn this Delivery joins.
+- `_finish_steer` reports `steered` on its acceptance branch.
+
+A `started` input is left alone: its Turn already owns the 👀 indicator.
+
+### 3.2 Report the outcome as a reaction
+
+`ProcessingIndicatorService.ack_delivery_state(context, state=, admission=)`
+maps the durable state to one receipt on the sender's own message:
+
+| Delivery state | Receipt | Meaning |
+| --- | --- | --- |
+| `accepted` (steered) | ✍️ | inserted into the running turn |
+| `queued`, `pending_steer` | 👌 | queued; runs when the current turn ends |
+| `reconciling_steer` | 🤔 | sent, acknowledgement unconfirmed |
+| `retired` | 🤷 | not delivered |
+| `claimed`, `steering`, `interrupt_waiting` | — | turn-owned; the indicator answers |
+
+The service keeps a small registry keyed by platform/channel/message so a
+receipt can be replaced rather than stacked, and `start()` clears the receipt
+before the turn's own indicator takes over — a promoted Delivery is
+re-dispatched with its original native message id (`_hydrate_delivery_context`),
+so 👌 and 👀 would otherwise land on the same message.
+
+Only *replaceable* states (`queued`, `pending_steer`, `reconciling_steer`) are
+remembered. A final receipt (✍️ / 🤷) is never cleared, so keeping its key would
+leak one entry per message for the life of the process; a FIFO cap
+(`_ADMISSION_ACK_REGISTRY_LIMIT`) backstops the replaceable ones.
+
+A receipt and the turn start it races are serialized per message key by a
+refcounted `asyncio.Lock`, and `clear_admission_ack` writes an
+`_ADMISSION_ACK_CONSUMED` marker *before* awaiting the removal. Together those
+cover both orderings: a clear waits for an in-flight add and then removes it,
+and an add that lands after the turn started is suppressed instead of leaving an
+orphan 👌 next to 👀.
+
+Platforms without reaction support stay silent: one bubble per queued message is
+worse than no receipt.
+
+### 3.4 Carrying the receipt target across hydration
+
+The reaction target is not always the sender's own message — a quick reply
+reacts on the bot echo it was attached to — and it cannot be rebuilt from the
+Delivery snapshot. The ingress handler stores it in the durable
+`admission_context` (`processing_indicator_message_id`), and every consumer
+reads it back through `_delivery_ack_target`:
+
+- `MessageHandler._restore_reaction_target` when the durable owner re-dispatches
+ a hydrated context;
+- `_delivery_receipt_context` when a Delivery settles away from ingress. A
+ quick-reply callback is dispatched with `message_id=None` (to bypass platform
+ event dedup), so a persisted echo target — not a native message id — is what
+ qualifies it for a receipt;
+- `_hydrate_delivery_batch_context`, which publishes `delivery_ack_targets` for
+ the whole merged batch. Deliveries without a native message id merge into one
+ Turn and only the first hydrates the dispatch context, so `start()` clears
+ every target in the batch, not just its own.
+
+### 3.3 Platform emoji mappings
+
+Reaction emoji are not portable. Slack needs ASCII short names, Telegram accepts
+a fixed set (and lists the writing hand without U+FE0F), Lark needs `emoji_type`
+keys.
+
+- `slack.py`: `writing_hand`, `thinking_face`, `shrug` added.
+- `telegram.py`: `✍️ → ✍` normalization; 👌/🤔/🤷 pass through.
+- `discord.py`: raw unicode, no change.
+- `feishu.py`: 🤔 already maps to `THINKING`. ✍️ and 🤷 are deliberately left
+ unmapped rather than guessed — `add_reaction` logs the exact "add it to
+ `_EMOJI_MAP`" warning and returns `False`, so Lark degrades to no receipt for
+ those two until the `emoji_type` keys are verified against the Lark table.
+
+### 3.5 Reporting outcomes that settle away from ingress
+
+The ingress caller only sees the admission result. Two paths resolve a Delivery
+afterwards and are therefore the only possible reporters of its real outcome:
+
+- `_run_pending_steers` — a Delivery admitted as `pending_steer` can be accepted
+ (👌 → ✍️), definitively refused after the Session went inactive and retired
+ (👌 → 🤷), or left unconfirmed (👌 → 🤔). Every row of an attempt settles
+ together, so the leader's result is reported for the whole claimed batch.
+- recovery — `recover_durable_delivery_state` and `_resume_delivery_observation`
+ re-enter `deliver()` for a reservation committed before the service stopped.
+ The ingress handler is long gone, so recovery reports that result itself.
+
+Both go through `_report_delivery_receipts`, which is best-effort: a failure to
+react is logged and never blocks the Delivery.
+
+## 4. Known limitations
+
+- A `reconciling_steer` receipt (🤔) is upgraded only when reconciliation settles
+ through the pending-steer path; other reconciliation outcomes still show up in
+ the turn's reply instead.
+- Receipts are best-effort and in-memory: after a restart a stale 👌 is not
+ cleared by `start()`. On Telegram the reaction is replaced anyway; on Slack it
+ can linger until the next turn on that message.
+- The ✍️ receipt is intentionally permanent. It records which turn absorbed the
+ message, which stays useful after the reply arrives.
+
+## 5. Evidence
+
+- contract/unit: `tests/test_delivery_ack_reaction.py`
+ (MESSAGE-DELIVERY-301, 302, 304, 305, 309) and
+ `tests/test_session_delivery_fsm.py`
+ (MESSAGE-DELIVERY-303, 306, 307, 308, 309)
+- regression: `tests/test_processing_indicator_reaction.py`,
+ `tests/test_session_delivery_fsm.py`, `tests/scenarios/message_delivery/`
+- manual: send a second and third message on Telegram/Slack while a turn runs;
+ confirm ✍️ for a steered input, 👌 → 👀 for a queued one.
diff --git a/modules/im/slack.py b/modules/im/slack.py
index e5aaf88c0..d9dc43e86 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1354,7 +1354,8 @@ class SlackBot(BaseIMClient):
Slack's ``reactions.add`` / ``reactions.remove`` require the short name
(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.
+ indicator / handlers must be mapped here: 👀 ack, 👌 queued, 🤖 subagent,
+ ✍️ steered, 🤔 unconfirmed, 🤷 not delivered.
"""
name = (emoji or "").strip()
if name.startswith(":") and name.endswith(":") and len(name) > 2:
@@ -1366,6 +1367,10 @@ class SlackBot(BaseIMClient):
"robot": "robot_face",
"👌": "ok_hand",
"ok": "ok_hand",
+ "✍️": "writing_hand",
+ "✍": "writing_hand",
+ "🤔": "thinking_face",
+ "🤷": "shrug",
}
return aliases.get(name, name)
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index a08b95a69..7d07261ac 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -1401,6 +1401,12 @@ class TelegramBot(BaseIMClient):
"robot_face": "🤖",
"robot": "🤖",
"🤖": "🤖",
+ # Telegram's allowed reaction set lists the writing hand WITHOUT the
+ # U+FE0F variation selector; the presentation variant is rejected.
+ "✍️": "✍",
+ "writing_hand": "✍",
+ "thinking_face": "🤔",
+ "shrug": "🤷",
}
return aliases.get(normalized, normalized)
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 988c28421..fd4ae4c68 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -164,6 +164,59 @@ scenarios:
kind: lifecycle
layer: contract
test: tests/test_session_delivery_fsm.py::test_im_p1_materializes_only_after_exact_native_acceptance
+ - id: MESSAGE-DELIVERY-301
+ name: Mid-turn IM input reports its admission outcome to the sender
+ status: covered
+ kind: happy_path
+ layer: contract
+ test: tests/test_delivery_ack_reaction.py::AdmissionAckTests
+ - id: MESSAGE-DELIVERY-302
+ name: A queued admission receipt is replaced by the running turn indicator
+ status: covered
+ kind: lifecycle
+ layer: contract
+ test: tests/test_delivery_ack_reaction.py::AdmissionAckTests::test_start_clears_the_queued_receipt_before_the_turn_indicator
+ - id: MESSAGE-DELIVERY-303
+ name: Late steer acceptance upgrades the queued admission receipt
+ status: covered
+ kind: lifecycle
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_late_steer_acceptance_upgrades_the_queued_admission_receipt
+ - id: MESSAGE-DELIVERY-304
+ name: A receipt racing the turn start is cleared exactly once
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_delivery_ack_reaction.py::AdmissionAckTests::test_receipt_in_flight_when_the_turn_starts_is_still_cleared
+ - id: MESSAGE-DELIVERY-305
+ name: The receipt target survives Delivery hydration into a new process
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_delivery_ack_reaction.py::ReactionTargetSurvivalTests
+ - id: MESSAGE-DELIVERY-306
+ name: A native-less quick reply reacts on its persisted echo target
+ status: covered
+ kind: regression
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_quick_reply_receipt_uses_its_persisted_echo_target
+ - id: MESSAGE-DELIVERY-307
+ name: A steer refused after archive replaces its queued receipt
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_definitive_steer_refusal_after_archive_reports_the_retired_receipt
+ - id: MESSAGE-DELIVERY-308
+ name: A reservation revived by recovery still reports its admission
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_recovered_reservation_reports_its_admission_receipt
+ - id: MESSAGE-DELIVERY-309
+ name: One Turn clears the receipt of every Delivery merged into it
+ status: covered
+ kind: lifecycle
+ layer: contract
+ test: tests/test_delivery_ack_reaction.py::AdmissionAckTests::test_start_clears_every_receipt_merged_into_its_turn
next_priority:
- - MESSAGE-DELIVERY-301
- - MESSAGE-DELIVERY-302
+ - MESSAGE-DELIVERY-310
diff --git a/tests/test_delivery_ack_reaction.py b/tests/test_delivery_ack_reaction.py
new file mode 100644
index 000000000..992c2b053
--- /dev/null
+++ b/tests/test_delivery_ack_reaction.py
@@ -0,0 +1,464 @@
+"""Admission receipts for IM input that does not start its own turn.
+
+MESSAGE-DELIVERY-301 / 302 / 304 / 305.
+
+A message sent while a turn is already running is handed to its durable
+Delivery owner and the message handler returns before any processing indicator
+exists, so the sender used to see nothing at all. ``ack_delivery_state`` reports
+that admission outcome as a reaction on the sender's own message, and the
+receipt is cleared once that input's own turn starts.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.processing_indicator import (
+ _ADMISSION_ACK_REGISTRY_LIMIT,
+ ACK_REACTION_EMOJI,
+ NOT_DELIVERED_REACTION_EMOJI,
+ QUEUED_REACTION_EMOJI,
+ STEERED_REACTION_EMOJI,
+ UNCONFIRMED_REACTION_EMOJI,
+ ProcessingIndicatorService,
+)
+from core.session_turns import DeliveryResult
+from modules.im import MessageContext
+
+
+def _ctx(message_id="m1", platform="telegram"):
+ return MessageContext(
+ user_id="u1",
+ channel_id="c1",
+ message_id=message_id,
+ platform=platform,
+ )
+
+
+class _FakeIM:
+ def __init__(self, *, add_ok=True):
+ self.add_ok = add_ok
+ self.calls: list[tuple[str, str, str]] = []
+
+ async def add_reaction(self, context, message_id, emoji):
+ self.calls.append(("add", message_id, emoji))
+ return self.add_ok
+
+ async def remove_reaction(self, context, message_id, emoji):
+ self.calls.append(("remove", message_id, emoji))
+ return True
+
+ async def send_typing_indicator(self, context):
+ return True
+
+ async def clear_typing_indicator(self, context):
+ return True
+
+
+class _GatedIM(_FakeIM):
+ """Reaction calls that only complete when the test lets them."""
+
+ def __init__(self):
+ super().__init__()
+ self.entered = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def add_reaction(self, context, message_id, emoji):
+ self.entered.set()
+ await self.release.wait()
+ return await super().add_reaction(context, message_id, emoji)
+
+
+def _svc(im, *, reactions=True):
+ svc = ProcessingIndicatorService.__new__(ProcessingIndicatorService)
+ svc.controller = SimpleNamespace(get_im_client_for_context=lambda ctx: im, im_client=im)
+ svc.config = SimpleNamespace(ack_mode="typing")
+ svc._indicators_by_turn_token = {}
+ svc._admission_acks = {}
+ svc._admission_ack_locks = {}
+ capabilities = SimpleNamespace(
+ preferred_processing_indicator="reaction",
+ force_preferred_processing_indicator=True,
+ supports_typing_indicator=True,
+ supports_reaction_indicator=reactions,
+ supports_message_indicator=True,
+ )
+ svc._capabilities = lambda ctx: capabilities
+ svc._mode_supported = lambda caps, mode, ctx: mode == "reaction" and reactions
+ return svc
+
+
+class AdmissionAckTests(unittest.IsolatedAsyncioTestCase):
+ async def test_steered_input_reports_a_receipt(self):
+ im = _FakeIM()
+ svc = _svc(im)
+
+ applied = await svc.ack_delivery_state(_ctx(), state="accepted", admission="steered")
+
+ self.assertEqual(applied, STEERED_REACTION_EMOJI)
+ self.assertEqual(im.calls, [("add", "m1", STEERED_REACTION_EMOJI)])
+
+ async def test_queued_and_pending_steer_report_the_queued_receipt(self):
+ for state in ("queued", "pending_steer"):
+ with self.subTest(state=state):
+ im = _FakeIM()
+ svc = _svc(im)
+
+ applied = await svc.ack_delivery_state(_ctx(), state=state)
+
+ self.assertEqual(applied, QUEUED_REACTION_EMOJI)
+ self.assertEqual(im.calls, [("add", "m1", QUEUED_REACTION_EMOJI)])
+
+ async def test_unconfirmed_and_undelivered_states_are_distinguishable(self):
+ cases = {
+ "reconciling_steer": UNCONFIRMED_REACTION_EMOJI,
+ "retired": NOT_DELIVERED_REACTION_EMOJI,
+ }
+ for state, expected in cases.items():
+ with self.subTest(state=state):
+ im = _FakeIM()
+ svc = _svc(im)
+
+ self.assertEqual(await svc.ack_delivery_state(_ctx(), state=state), expected)
+
+ async def test_started_input_is_left_to_its_own_processing_indicator(self):
+ # The first message of an idle session starts a turn and already gets 👀
+ # from start(); a receipt here would overwrite it on replace-semantics
+ # platforms (Telegram) or stack on it (Slack).
+ im = _FakeIM()
+ svc = _svc(im)
+
+ applied = await svc.ack_delivery_state(_ctx(), state="accepted", admission="started")
+
+ self.assertIsNone(applied)
+ self.assertEqual(im.calls, [])
+
+ async def test_turn_owning_states_report_nothing(self):
+ for state in ("claimed", "steering", "interrupt_waiting", "reserved", ""):
+ with self.subTest(state=state):
+ im = _FakeIM()
+ svc = _svc(im)
+
+ self.assertIsNone(await svc.ack_delivery_state(_ctx(), state=state))
+ self.assertEqual(im.calls, [])
+
+ async def test_platform_without_reactions_stays_silent(self):
+ # WeChat-like: no reaction support, and a text bubble per queued message
+ # would be worse than silence.
+ im = _FakeIM()
+ svc = _svc(im, reactions=False)
+
+ self.assertIsNone(await svc.ack_delivery_state(_ctx(), state="queued"))
+ self.assertEqual(im.calls, [])
+
+ async def test_rejected_reaction_is_not_remembered(self):
+ im = _FakeIM(add_ok=False)
+ svc = _svc(im)
+ context = _ctx()
+
+ self.assertIsNone(await svc.ack_delivery_state(context, state="queued"))
+ await svc.clear_admission_ack(context)
+
+ self.assertEqual(im.calls, [("add", "m1", QUEUED_REACTION_EMOJI)])
+
+ async def test_receipt_upgrade_replaces_the_previous_one(self):
+ # A queued Delivery whose steer later settles reports the newer outcome
+ # without stacking two receipts on one message.
+ im = _FakeIM()
+ svc = _svc(im)
+ context = _ctx()
+
+ await svc.ack_delivery_state(context, state="queued")
+ await svc.ack_delivery_state(context, state="accepted", admission="steered")
+
+ self.assertEqual(
+ im.calls,
+ [
+ ("add", "m1", QUEUED_REACTION_EMOJI),
+ ("remove", "m1", QUEUED_REACTION_EMOJI),
+ ("add", "m1", STEERED_REACTION_EMOJI),
+ ],
+ )
+
+ async def test_repeated_identical_receipt_is_not_reapplied(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ context = _ctx()
+
+ await svc.ack_delivery_state(context, state="queued")
+ await svc.ack_delivery_state(context, state="pending_steer")
+
+ self.assertEqual(im.calls, [("add", "m1", QUEUED_REACTION_EMOJI)])
+
+ async def test_start_clears_the_queued_receipt_before_the_turn_indicator(self):
+ # MESSAGE-DELIVERY-302: the promoted Delivery is re-dispatched with its
+ # original native message id, so the receipt and the running indicator
+ # target the same message and must not coexist.
+ im = _FakeIM()
+ svc = _svc(im)
+ context = _ctx()
+ await svc.ack_delivery_state(context, state="queued")
+
+ handle = await svc.start(context, "claude")
+
+ self.assertEqual(
+ im.calls,
+ [
+ ("add", "m1", QUEUED_REACTION_EMOJI),
+ ("remove", "m1", QUEUED_REACTION_EMOJI),
+ ],
+ )
+ self.assertTrue(handle.reaction_indicator_selected)
+ self.assertIsNone(handle.ack_reaction_emoji)
+
+ # The turn's own indicator owns the message from here.
+ await svc.promote_reaction_to_running(handle)
+ self.assertEqual(im.calls[-1], ("add", "m1", ACK_REACTION_EMOJI))
+
+ async def test_start_clears_every_receipt_merged_into_its_turn(self):
+ # MESSAGE-DELIVERY-309: Deliveries without a native message id (quick
+ # replies) merge into one Turn, but only the first hydrates the dispatch
+ # context. The rest are accepted as part of that Turn and never
+ # dispatched, so nothing else would ever take their receipt down.
+ im = _FakeIM()
+ svc = _svc(im)
+ first = _ctx(message_id=None)
+ first.platform_specific = {"processing_indicator_message_id": "echo-1"}
+ second = _ctx(message_id=None)
+ second.platform_specific = {"processing_indicator_message_id": "echo-2"}
+ await svc.ack_delivery_state(first, state="queued")
+ await svc.ack_delivery_state(second, state="queued")
+
+ dispatch = _ctx(message_id=None)
+ dispatch.platform_specific = {
+ "processing_indicator_message_id": "echo-1",
+ "delivery_ack_targets": ["echo-1", "echo-2"],
+ }
+ await svc.start(dispatch, "claude")
+
+ self.assertEqual(
+ im.calls,
+ [
+ ("add", "echo-1", QUEUED_REACTION_EMOJI),
+ ("add", "echo-2", QUEUED_REACTION_EMOJI),
+ ("remove", "echo-1", QUEUED_REACTION_EMOJI),
+ ("remove", "echo-2", QUEUED_REACTION_EMOJI),
+ ],
+ )
+
+ async def test_receipt_is_scoped_to_one_message(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ await svc.ack_delivery_state(_ctx(message_id="m1"), state="queued")
+
+ await svc.clear_admission_ack(_ctx(message_id="m2"))
+
+ self.assertEqual(im.calls, [("add", "m1", QUEUED_REACTION_EMOJI)])
+
+ async def test_missing_message_id_reports_nothing(self):
+ im = _FakeIM()
+ svc = _svc(im)
+
+ self.assertIsNone(await svc.ack_delivery_state(_ctx(message_id=None), state="queued"))
+
+ async def test_accepted_without_steer_provenance_reports_nothing(self):
+ # An idempotent re-entry observes an already accepted Delivery and
+ # returns no admission; that observation cannot tell whether the input
+ # joined a running turn or started its own, and guessing ✍️ would stack
+ # on (or replace) a live processing indicator.
+ im = _FakeIM()
+ svc = _svc(im)
+
+ self.assertIsNone(await svc.ack_delivery_state(_ctx(), state="accepted"))
+ self.assertEqual(im.calls, [])
+
+ async def test_receipt_in_flight_when_the_turn_starts_is_still_cleared(self):
+ # Both halves await a platform call. Without serialization the add
+ # records its emoji after start() has looked for one, stranding 👌 next to
+ # the running indicator.
+ im = _GatedIM()
+ svc = _svc(im)
+ context = _ctx()
+
+ ack = asyncio.ensure_future(svc.ack_delivery_state(context, state="queued"))
+ await im.entered.wait()
+ clear = asyncio.ensure_future(svc.start(context, "claude"))
+ await asyncio.sleep(0)
+ im.release.set()
+ await ack
+ await clear
+
+ self.assertEqual(
+ im.calls,
+ [
+ ("add", "m1", QUEUED_REACTION_EMOJI),
+ ("remove", "m1", QUEUED_REACTION_EMOJI),
+ ],
+ )
+
+ async def test_receipt_arriving_after_the_turn_started_is_suppressed(self):
+ # The other ordering of the same race: the promoted turn already owns
+ # the message, so a late queued receipt must not decorate it.
+ im = _FakeIM()
+ svc = _svc(im)
+ context = _ctx()
+
+ await svc.start(context, "claude")
+ applied = await svc.ack_delivery_state(context, state="queued")
+
+ self.assertIsNone(applied)
+ self.assertEqual(im.calls, [])
+
+ async def test_final_receipts_do_not_accumulate_registry_entries(self):
+ # accepted/retired deliveries never start a turn, so nothing would ever
+ # read these entries back; keeping them grows the registry by one key
+ # per mid-turn message for the life of the process.
+ im = _FakeIM()
+ svc = _svc(im)
+
+ for index in range(5):
+ await svc.ack_delivery_state(
+ _ctx(message_id=f"steered-{index}"),
+ state="accepted",
+ admission="steered",
+ )
+ await svc.ack_delivery_state(_ctx(message_id=f"retired-{index}"), state="retired")
+
+ self.assertEqual(svc._admission_acks, {})
+ self.assertEqual(len(im.calls), 10)
+
+ async def test_replaceable_receipts_are_bounded(self):
+ im = _FakeIM()
+ svc = _svc(im)
+
+ for index in range(_ADMISSION_ACK_REGISTRY_LIMIT + 10):
+ await svc.ack_delivery_state(_ctx(message_id=f"q-{index}"), state="queued")
+
+ self.assertLessEqual(len(svc._admission_acks), _ADMISSION_ACK_REGISTRY_LIMIT)
+
+ async def test_quick_reply_echo_target_keeps_one_receipt_key(self):
+ # A quick-reply callback is dispatched with message_id=None and reacts on
+ # its bot echo. Durable hydration replaces the message id with the
+ # synthetic delivery id, so the receipt is only clearable when the echo
+ # target survives admission.
+ im = _FakeIM()
+ svc = _svc(im)
+ before = _ctx(message_id=None)
+ before.platform_specific = {"processing_indicator_message_id": "echo-7"}
+ hydrated = _ctx(message_id="delivery-abc")
+ hydrated.platform_specific = {"processing_indicator_message_id": "echo-7"}
+ stripped = _ctx(message_id="delivery-abc")
+
+ await svc.ack_delivery_state(before, state="queued")
+ await svc.clear_admission_ack(hydrated)
+
+ self.assertEqual(
+ im.calls,
+ [
+ ("add", "echo-7", QUEUED_REACTION_EMOJI),
+ ("remove", "echo-7", QUEUED_REACTION_EMOJI),
+ ],
+ )
+ self.assertNotEqual(
+ svc._admission_ack_key(before),
+ svc._admission_ack_key(stripped),
+ )
+
+
+class ReactionTargetSurvivalTests(unittest.TestCase):
+ """The reaction target must survive admission and durable hydration."""
+
+ def test_quick_reply_echo_is_captured_from_the_ingress_context(self):
+ from core.handlers.message_handler import MessageHandler
+
+ context = _ctx(message_id=None)
+ context.platform_specific = {"processing_indicator_message_id": "echo-7"}
+
+ self.assertEqual(MessageHandler._reaction_target(context), "echo-7")
+
+ def test_ordinary_message_carries_no_separate_target(self):
+ from core.handlers.message_handler import MessageHandler
+
+ self.assertIsNone(MessageHandler._reaction_target(_ctx()))
+
+ def test_hydrated_context_gets_its_reaction_target_back(self):
+ from core.handlers.message_handler import MessageHandler
+
+ hydrated = _ctx(message_id="delivery-abc")
+ hydrated.platform_specific = {"delivery_id": "delivery-abc"}
+
+ MessageHandler._restore_reaction_target(
+ hydrated,
+ {"processing_indicator_message_id": "echo-7"},
+ )
+
+ self.assertEqual(
+ (hydrated.platform_specific or {}).get("processing_indicator_message_id"),
+ "echo-7",
+ )
+
+ def test_restore_is_a_no_op_without_a_captured_target(self):
+ from core.handlers.message_handler import MessageHandler
+
+ hydrated = _ctx(message_id="delivery-abc")
+
+ MessageHandler._restore_reaction_target(hydrated, {"message_handler_route": {}})
+ MessageHandler._restore_reaction_target(hydrated, None)
+
+ self.assertIsNone(
+ (hydrated.platform_specific or {}).get("processing_indicator_message_id")
+ )
+
+
+class ReceiptEmojiMappingTests(unittest.TestCase):
+ """Every receipt emoji must resolve on the adapters that will send it."""
+
+ receipts = (
+ STEERED_REACTION_EMOJI,
+ QUEUED_REACTION_EMOJI,
+ UNCONFIRMED_REACTION_EMOJI,
+ NOT_DELIVERED_REACTION_EMOJI,
+ )
+
+ def test_slack_short_names_are_ascii(self):
+ from modules.im.slack import SlackBot
+
+ for emoji in self.receipts:
+ with self.subTest(emoji=emoji):
+ name = SlackBot._slack_reaction_name(emoji)
+ # A non-ASCII value here is an unmapped codepoint, which
+ # reactions.add rejects with ``invalid_name``.
+ self.assertTrue(name.isascii(), name)
+
+ def test_telegram_uses_allowed_reaction_variants(self):
+ from modules.im.telegram import TelegramBot
+
+ # Telegram accepts a fixed reaction set; the writing hand is listed
+ # without the U+FE0F presentation selector.
+ allowed = {"✍", "👌", "🤔", "🤷"}
+ for emoji in self.receipts:
+ with self.subTest(emoji=emoji):
+ normalized = TelegramBot._normalize_reaction_emoji(None, emoji)
+ self.assertIn(normalized, allowed)
+
+
+class DeliveryAdmissionContractTests(unittest.TestCase):
+ def test_delivery_result_defaults_to_no_admission_claim(self):
+ result = DeliveryResult("d1", None, "queued")
+ self.assertEqual(result.admission, "")
+
+ def test_started_and_steered_are_distinguishable_at_the_same_state(self):
+ started = DeliveryResult("d1", "m1", "accepted", "t1", admission="started")
+ steered = DeliveryResult("d2", "m2", "accepted", "t1", admission="steered")
+ self.assertEqual(started.state, steered.state)
+ self.assertNotEqual(started.admission, steered.admission)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index e950803dd..4bbb9e269 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -1028,6 +1028,303 @@ def test_im_p1_materializes_only_after_exact_native_acceptance(managers) -> None
assert message["author_id"] == "U42"
+def _record_admission_acks(manager: SessionTurnManager) -> list[tuple[str, str, str, str]]:
+ """Capture every admission receipt as (platform, reaction target, state, admission)."""
+
+ acks: list[tuple[str, str, str, str]] = []
+
+ async def record_ack(context, *, state, admission=""):
+ spec = context.platform_specific or {}
+ target = spec.get("processing_indicator_message_id") or context.message_id
+ acks.append((str(context.platform), str(target), state, admission))
+ return None
+
+ manager.controller.processing_indicator = SimpleNamespace(
+ ack_delivery_state=record_ack
+ )
+ return acks
+
+
+def test_late_steer_acceptance_upgrades_the_queued_admission_receipt(managers) -> None:
+ """MESSAGE-DELIVERY-303.
+
+ An input admitted as ``pending_steer`` already told its sender it was queued.
+ The attempt that actually accepts it runs in ``_run_pending_steers``, whose
+ result no ingress caller ever sees, so this loop is the only place that can
+ correct the receipt.
+ """
+
+ manager, _other, engine, _engine_b, _starts = managers
+ acks = _record_admission_acks(manager)
+
+ async def run() -> None:
+ turn_id, _ = await _activate(manager, text="active")
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ row = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="slack",
+ author="user",
+ source="user",
+ message_type="user",
+ text="late steer",
+ native_message_id="slack-msg-99",
+ ),
+ dispatch_text="late steer",
+ )
+ pending = delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=[row],
+ turn_id=turn_id,
+ attempt_id=delivery_store.new_attempt_id(),
+ )
+ assert len(pending) == 1
+ assert pending[0]["state"] == "pending_steer"
+
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ await manager._run_pending_steers("ses_fsm", turn_id, _context())
+
+ with engine.connect() as conn:
+ settled = delivery_store.get_delivery(conn, delivery_id)
+ assert settled is not None
+ assert settled["state"] == "accepted"
+
+ asyncio.run(run())
+
+ assert acks == [("slack", "slack-msg-99", "accepted", "steered")]
+
+
+def test_workbench_delivery_reports_no_reaction_receipt(managers) -> None:
+ """Only an IM input has a native message to react on."""
+
+ manager, _other, engine, _engine_b, _starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ row = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="composer input",
+ ),
+ dispatch_text="composer input",
+ )
+
+ assert manager._delivery_receipt_context("ses_fsm", row) is None
+
+
+def test_quick_reply_receipt_uses_its_persisted_echo_target(managers) -> None:
+ """MESSAGE-DELIVERY-306.
+
+ A quick-reply callback is dispatched with ``message_id=None`` on purpose, so
+ its Delivery snapshot carries no native message id and the persisted echo id
+ is the only reaction target it will ever have.
+ """
+
+ manager, _other, engine, _engine_b, _starts = managers
+ acks = _record_admission_acks(manager)
+
+ async def run() -> None:
+ turn_id, _ = await _activate(manager, text="active")
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ row = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="telegram",
+ author="user",
+ source="user",
+ message_type="user",
+ text="quick reply",
+ ),
+ dispatch_text="quick reply",
+ history_event={
+ "kind": "admission",
+ "context": {"processing_indicator_message_id": "echo-7"},
+ },
+ )
+ delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=[row],
+ turn_id=turn_id,
+ attempt_id=delivery_store.new_attempt_id(),
+ )
+
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ await manager._run_pending_steers("ses_fsm", turn_id, _context())
+
+ asyncio.run(run())
+
+ assert acks == [("telegram", "echo-7", "accepted", "steered")]
+
+
+def test_definitive_steer_refusal_after_archive_reports_the_retired_receipt(
+ managers,
+) -> None:
+ """MESSAGE-DELIVERY-307.
+
+ A Delivery refused after its Session went inactive is retired, never starts a
+ Turn of its own, and would otherwise keep the 👌 that promised it would run.
+ """
+
+ manager, _other, engine, _engine_b, _starts = managers
+ acks = _record_admission_acks(manager)
+
+ async def run() -> None:
+ turn_id, _ = await _activate(manager, text="active")
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ row = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="slack",
+ author="user",
+ source="user",
+ message_type="user",
+ text="refused steer",
+ native_message_id="slack-msg-77",
+ ),
+ dispatch_text="refused steer",
+ )
+ delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=[row],
+ turn_id=turn_id,
+ attempt_id=delivery_store.new_attempt_id(),
+ )
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(status="archived")
+ )
+
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.REFUSED))
+ await manager._run_pending_steers("ses_fsm", turn_id, _context())
+
+ with engine.connect() as conn:
+ settled = delivery_store.get_delivery(conn, delivery_id)
+ assert settled is not None
+ assert settled["state"] == "retired"
+
+ asyncio.run(run())
+
+ assert acks == [("slack", "slack-msg-77", "retired", "")]
+
+
+def test_merged_batch_exposes_every_reaction_target(managers) -> None:
+ """MESSAGE-DELIVERY-309.
+
+ Only the first Delivery of a merged Turn hydrates the dispatch context, so
+ the Turn has to carry the reaction targets of the others for the processing
+ indicator to clear their receipts.
+ """
+
+ manager, _other, engine, _engine_b, _starts = managers
+ rows = []
+ with engine.begin() as conn:
+ for index, echo in enumerate(("echo-1", "echo-2")):
+ rows.append(
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_store.new_delivery_id(),
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="telegram",
+ author="user",
+ source="user",
+ message_type="user",
+ text=f"quick reply {index}",
+ ),
+ dispatch_text=f"quick reply {index}",
+ history_event={
+ "kind": "admission",
+ "context": {"processing_indicator_message_id": echo},
+ },
+ )
+ )
+
+ context = _context()
+ manager._hydrate_delivery_batch_context(context, rows)
+
+ assert context.platform_specific["delivery_ack_targets"] == ["echo-1", "echo-2"]
+
+
+def test_recovered_reservation_reports_its_admission_receipt(managers) -> None:
+ """MESSAGE-DELIVERY-308.
+
+ A reservation committed before the service stopped is re-entered by recovery,
+ not by the ingress handler, so recovery is the only reporter of its outcome.
+ """
+
+ manager, _other, engine, _engine_b, _starts = managers
+ acks = _record_admission_acks(manager)
+
+ async def run() -> None:
+ await _activate(manager, text="active")
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="slack",
+ author="user",
+ source="user",
+ message_type="user",
+ text="recovered input",
+ native_message_id="slack-msg-55",
+ ),
+ dispatch_text="recovered input",
+ )
+
+ await manager.recover_durable_delivery_state("ses_fsm")
+
+ with engine.connect() as conn:
+ settled = delivery_store.get_delivery(conn, delivery_id)
+ assert settled is not None
+ assert settled["state"] == "queued"
+
+ asyncio.run(run())
+
+ assert acks == [("slack", "slack-msg-55", "queued", "")]
+
+
def test_duplicate_im_p1_reuses_one_delivery_and_one_native_steer(managers) -> None:
manager, _other, engine, _engine_b, _starts = managers