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(im): queued reaction for messages waiting behind a running turn

Qi Qif41805e05b6e
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index ade9d959b..d0bffe7dd 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -21,6 +21,11 @@ logger = logging.getLogger(__name__)
_PROCESSING_INDICATOR_MODES = ("typing", "reaction", "message")
ACK_REACTION_EMOJI = "👀"
+# Shown while an IM message is waiting behind a running turn (blocked on the
+# runtime gate). It is promoted to ACK_REACTION_EMOJI when this message's turn
+# actually starts. See AgentService.handle_message (show_queued_reaction /
+# promote_reaction_to_running).
+QUEUED_REACTION_EMOJI = "👌"
@dataclass
@@ -34,6 +39,14 @@ class ProcessingIndicatorHandle:
ack_reaction_emoji: Optional[str] = None
typing_indicator_active: bool = False
typing_indicator_task: Optional[asyncio.Task] = None
+ # True when the reaction indicator is the selected mode for this turn. The
+ # reaction itself is added at the runtime gate (queued 👌 → running 👀), not
+ # here, so this flag tells the gate hooks whether to act. It is intentionally
+ # NOT part of to_snapshot/from_snapshot: the only snapshot/restore path
+ # (OpenCode poll loop) runs AFTER the reaction was already promoted to 👀, and
+ # finish() keys off ack_reaction_emoji directly, so the flag is not load-bearing
+ # across a restore.
+ reaction_indicator_selected: bool = False
def to_snapshot(self) -> dict[str, Any]:
payload = self.context.platform_specific or {}
@@ -198,13 +211,18 @@ class ProcessingIndicatorService:
if self._concise_status_bubble_active(context):
# The concise status bubble is the primary progress indicator, but we
- # still want the lightweight 👀 received-ack reaction AND typing
- # keepalive (both best-effort, both cleaned up on finish). We only drop
- # the ack MESSAGE mode — a separate text bubble would duplicate the
- # status bubble and can't be deleted on Slack. (B2)
+ # still want the lightweight reaction ack AND typing keepalive (both
+ # best-effort, both cleaned up on finish). We only drop the ack MESSAGE
+ # mode — a separate text bubble would duplicate the status bubble and
+ # can't be deleted on Slack. (B2)
+ #
+ # The reaction is SELECTED here but ADDED at the runtime gate so a
+ # message waiting behind a running turn shows the queued 👌 and only
+ # flips to 👀 when its turn truly starts (show_queued_reaction /
+ # promote_reaction_to_running). Typing stays eager for immediate feedback.
capabilities = self._capabilities(context)
if self._mode_supported(capabilities, "reaction", context):
- await self._start_reaction_indicator(handle)
+ handle.reaction_indicator_selected = True
if self._mode_supported(capabilities, "typing", context):
await self._start_typing_indicator(handle)
return handle
@@ -214,7 +232,12 @@ class ProcessingIndicatorService:
return handle
if mode == "typing" and await self._start_typing_indicator(handle):
return handle
- if mode == "reaction" and await self._start_reaction_indicator(handle):
+ if mode == "reaction":
+ # Reaction is the selected mode but is added at the runtime gate
+ # (queued 👌 → running 👀), not eagerly here. Selecting it preserves
+ # the single-mode "first match wins" contract: we stop trying lower
+ # modes just as if the reaction had been applied.
+ handle.reaction_indicator_selected = True
return handle
return handle
@@ -255,14 +278,19 @@ class ProcessingIndicatorService:
handle.typing_indicator_task = asyncio.create_task(self._typing_keepalive_loop(context))
return True
- async def _start_reaction_indicator(self, handle: ProcessingIndicatorHandle) -> bool:
+ async def _start_reaction_indicator(
+ self,
+ handle: ProcessingIndicatorHandle,
+ *,
+ emoji: str = ACK_REACTION_EMOJI,
+ ) -> bool:
context = handle.context
message_id = self._reaction_target_message_id(context)
if not message_id:
return False
im_client = self._get_im_client(context)
try:
- ok = await im_client.add_reaction(context, message_id, ACK_REACTION_EMOJI)
+ ok = await im_client.add_reaction(context, message_id, emoji)
except Exception as ack_err:
logger.debug("Failed to add reaction ack: %s", ack_err)
return False
@@ -272,9 +300,91 @@ class ProcessingIndicatorService:
return False
handle.ack_reaction_message_id = message_id
- handle.ack_reaction_emoji = ACK_REACTION_EMOJI
+ handle.ack_reaction_emoji = emoji
return True
+ def _resolve_handle(self, request_or_handle: Any) -> tuple[ProcessingIndicatorHandle, Optional[Any]]:
+ if isinstance(request_or_handle, ProcessingIndicatorHandle):
+ return request_or_handle, None
+ request = request_or_handle
+ return self.handle_from_request(request), request
+
+ @staticmethod
+ def _sync_reaction_to_request(handle: ProcessingIndicatorHandle, request: Optional[Any]) -> None:
+ # Keep the request's parallel reaction fields in lockstep with the handle.
+ # handle_from_request prefers the live handle object, but the OpenCode poll
+ # snapshot path reads request.ack_reaction_* directly, so they must not drift.
+ if request is not None:
+ request.ack_reaction_message_id = handle.ack_reaction_message_id
+ request.ack_reaction_emoji = handle.ack_reaction_emoji
+
+ async def show_queued_reaction(self, request_or_handle: Any) -> bool:
+ """Add the queued 👌 reaction for a message waiting behind a running turn.
+
+ Acts only when the reaction indicator is the selected mode for this turn and
+ no reaction is shown yet. Returns True only when 👌 was actually applied, so
+ the caller knows it must be cleaned up if the queued message is cancelled
+ before it ever runs.
+ """
+ handle, request = self._resolve_handle(request_or_handle)
+ if not handle.reaction_indicator_selected:
+ return False
+ if handle.ack_reaction_emoji:
+ return False
+ applied = await self._start_reaction_indicator(handle, emoji=QUEUED_REACTION_EMOJI)
+ if applied:
+ self._sync_reaction_to_request(handle, request)
+ return applied
+
+ async def promote_reaction_to_running(self, request_or_handle: Any, *, agent_name: Optional[str] = None) -> None:
+ """Switch the reaction to the running 👀 when this turn actually starts.
+
+ queued 👌 shown -> remove 👌 then add 👀; nothing shown yet (non-busy fast
+ path) -> add 👀; already 👀 -> no-op (idempotent). No-op when the reaction
+ indicator is not the selected mode. If the 👀 add fails at runtime, fall back
+ through the remaining indicator modes (``agent_name`` labels the ack message).
+ """
+ handle, request = self._resolve_handle(request_or_handle)
+ if not handle.reaction_indicator_selected:
+ return
+ if handle.ack_reaction_emoji == ACK_REACTION_EMOJI:
+ return
+ if handle.ack_reaction_emoji == QUEUED_REACTION_EMOJI and handle.ack_reaction_message_id:
+ removed = False
+ try:
+ 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 queued reaction on promote: %s", err)
+ if not removed:
+ # The queued 👌 is still on the message. Keep owning it on the handle
+ # (do NOT clear the fields and do NOT stack 👀 on top) so finish() can
+ # still remove it on the terminal result. Better a stale 👌 that gets
+ # cleaned up than a leaked one or two reactions at once.
+ return
+ handle.ack_reaction_message_id = None
+ handle.ack_reaction_emoji = None
+ applied = await self._start_reaction_indicator(handle, emoji=ACK_REACTION_EMOJI)
+ if not applied and not handle.typing_indicator_active and not handle.ack_message_id:
+ # The reaction add failed at runtime (e.g. missing reactions scope or a
+ # transient API error). Because start() deferred the reaction, the normal
+ # mode loop never tried a lower candidate — fall through the remaining
+ # modes here so the user still gets a processing ack instead of none (P2):
+ # typing first when supported, else the ack message (e.g. Lark/Feishu
+ # support reactions + message but NOT typing). Best-effort, capability-gated.
+ capabilities = self._capabilities(handle.context)
+ fell_back = False
+ if self._mode_supported(capabilities, "typing", handle.context):
+ fell_back = await self._start_typing_indicator(handle)
+ if not fell_back and self._mode_supported(capabilities, "message", handle.context):
+ await self._start_message_indicator(handle, agent_name or "")
+ self._sync_reaction_to_request(handle, request)
+
@staticmethod
def _turn_tokens(context: MessageContext) -> set[str]:
payload = context.platform_specific or {}
diff --git a/docs/plans/avibe-queued-reaction-emoji.md b/docs/plans/avibe-queued-reaction-emoji.md
new file mode 100644
index 000000000..1064a68d7
--- /dev/null
+++ b/docs/plans/avibe-queued-reaction-emoji.md
@@ -0,0 +1,306 @@
+# Queued-vs-Running Reaction Emoji for IM Turns
+
+Status: APPROVED v2 (opus review + codex review round 2 = APPROVE; implementation constraints folded in)
+Owner: qiqi
+Scope: IM platforms (Slack / Discord / Telegram / Feishu). WeChat unaffected (no reaction support).
+
+## 0. Changelog
+
+- v4 (real root cause): the queued 👌 never appeared on Slack because
+ `SlackBot.add_reaction` only mapped 👀→`eyes` / 🤖→`robot_face`; the raw 👌
+ codepoint is rejected by Slack `reactions.add` with `invalid_name`. Fixed by
+ mapping 👌→`ok_hand` (Slack, via a shared `_slack_reaction_name` helper) and
+ 👌→`OK` (Feishu emoji_type). With the platform mapping fixed, the v3 "always show
+ 👌" workaround was REVERTED back to the `gate.lock.locked()` guard: a non-queued
+ message goes straight to 👀 (no 👌→👀 flash), only a genuinely-queued message
+ shows 👌. The gate is held for the whole turn (released only on the terminal
+ result), so `locked()` reliably detects real queuing.
+- v3 (superseded by v4): dropped the `gate.lock.locked()` precondition in
+ `AgentService.handle_message`. That single-instant check missed genuinely-queued
+ messages — a queued message could show no 👌 at all (observed in testing). The
+ gate now ALWAYS calls `show_queued_reaction` before `acquire()`; a non-contended
+ turn flips 👌→👀 immediately (brief flash), a contended turn keeps 👌 for the
+ whole wait. `promote_reaction_to_running` moved to the first action after the gate
+ is acquired to minimize that flash. This supersedes goal #3 ("no 👌 flash on
+ non-queued"): reliability of the queued indicator wins over avoiding a brief flash.
+- v2: Fix P0 "👌 leaks on cancel-while-queued" (CancelledError escapes the gate try
+ block); make reaction fully **gate-owned** with explicit handling of the concise
+ status-bubble path and single-mode selection; sync `request` parallel fields on
+ promote; correct Telegram `_normalize_reaction_emoji` wording; document subagent
+ ordering and Slack reaction rate limits.
+
+## 1. Background
+
+When an IM user sends a message, the agent adds a 👀 reaction to acknowledge it is
+processing. Today that reaction is added **too early** — before the turn has actually
+started — so a message merely *waiting in line* already shows 👀, which reads as "the
+agent is thinking about THIS message" when it is not.
+
+### 1.1 Two independent concurrency mechanisms
+
+- **Web Workbench (`platform="avibe"`)** — `core/session_turns.py`
+ `SessionTurnManager` with a **persistent** queue (`messages_service` `QUEUED_TYPE`),
+ `submit()` / `flush_queue()` / `in_flight`, and `queue.updated` browser events.
+ Reactions do **not** apply (the browser has its own queue UI; the `avibe` IM client
+ does not implement reactions). Out of scope.
+- **IM (Slack/Discord/Telegram/Feishu/WeChat)** — `modules/agents/service.py`
+ `AgentService.handle_message` acquires an **in-memory** `asyncio.Lock`
+ (`_RuntimeTurnGate.lock`, keyed by `runtime_turn_key`). A second message for the
+ same runtime key **blocks on `await gate.lock.acquire()`** (serial; no persistent
+ queue, not merged, not dropped). This is the path the feature targets.
+
+### 1.2 Current reaction lifecycle (the bug)
+
+| Step | Location | Today |
+| --- | --- | --- |
+| Add reaction | `core/handlers/message_handler.py:390` `processing_indicator.start()` → `_start_reaction_indicator` | adds **👀** immediately, **before** the gate |
+| Acquire gate | `modules/agents/service.py:46` `await gate.lock.acquire()` | a 2nd message blocks HERE |
+| Turn truly starts | `modules/agents/service.py:68` `_begin_turn_status()` | status bubble posted here (correctly *after* the gate) |
+| Remove reaction | `core/processing_indicator.py:427-441` `finish()` | removes `handle.ack_reaction_emoji` on terminal result/error |
+
+The **status bubble** already waits for the gate; the **reaction** does not. The fix
+makes the reaction follow the same "real start = gate acquired" rule.
+
+### 1.3 Relevant constants / helpers (verified against code)
+
+- `core/processing_indicator.py`
+ - `ACK_REACTION_EMOJI = "👀"` (running)
+ - `ProcessingIndicatorHandle.ack_reaction_message_id` / `.ack_reaction_emoji`
+ - `start()` selects ONE mode in the normal path (`_processing_modes()` → first of
+ `message`/`typing`/`reaction` that succeeds wins and returns), EXCEPT the
+ **concise-status-bubble** branch (lines 199-210) which starts reaction **and**
+ typing together and returns early.
+ - `_start_reaction_indicator(handle)` adds the reaction; `_reaction_target_message_id`
+ picks `platform_specific["processing_indicator_message_id"]` or `context.message_id`
+ - `finish()` removes whatever emoji `handle.ack_reaction_emoji` holds (not hardcoded
+ 👀) and clears the matching `request.*` fields when a request is present.
+ - `apply_to_request()` copies `handle.ack_reaction_message_id/.ack_reaction_emoji`
+ onto the request; `handle_from_request()` prefers the live handle object's fields.
+ - terminal-token registry: `track_turn` / `finish_terminal_turn` (keyed by turn token)
+- `modules/agents/service.py`
+ - `handle_message` gate chokepoint; the `try` block starts at line 51 — **AFTER**
+ `await gate.lock.acquire()` (line 46). `except CancelledError` (line 71) therefore
+ does NOT cover a cancellation raised *by* `acquire()` while queued. `_RuntimeTurnGate`,
+ `_begin_turn_status`, `_track_processing_indicator_turn` (reads `request.processing_indicator`).
+ - `runtime_turn_key`: `BaseAgent.runtime_turn_key` → `backend_composite_session_id or
+ composite_session_id` (includes channel/session). Same channel → same gate → serial;
+ different channel → independent. So 👌 semantics ("this channel is queued") is correct.
+- `core/handlers/message_handler.py`
+ - `start()` called at line 390 (only for `is_human`); subagent 🤖
+ (`SUBAGENT_REACTION_EMOJI`) added at 392-405; error/cleanup near 484-500. The
+ outer handler is `except Exception` (line ~491) — does NOT catch `CancelledError`.
+- per-platform `add_reaction`/`remove_reaction`: `slack.py`, `discord.py`,
+ `telegram.py` (`_normalize_reaction_emoji` is a **pass-through** with a small alias
+ map `{👀, 🤖}`; it does NOT whitelist — Telegram's API server validates the emoji,
+ and 👌 is in Telegram's supported reaction set, so it is accepted; a rejected emoji
+ is swallowed and returns False), `feishu.py`, `wechat.py` (returns `False`), routed
+ via `modules/im/multi.py`, default no-op in `modules/im/base.py`.
+
+## 2. Goal
+
+For IM platforms whose reaction indicator is the active mode:
+
+1. A message **waiting behind a running turn** (blocked on the gate) shows **👌**
+ (`:ok_hand:`) — "received, queued".
+2. When that message's turn **actually starts** (gate acquired) the reaction switches
+ **👌 → 👀**.
+3. A message that runs **immediately** (gate free) shows **👀** directly — no 👌 flash.
+4. On terminal result / error / **cancellation (including while still queued)**, the
+ active reaction (👌 or 👀) is removed — no leaks.
+
+Non-goals: Web Workbench queue; persistent IM queue; typing/ack-message modes; WeChat
+reactions.
+
+## 3. Design — gate-owned reaction (refined B1)
+
+### 3.1 Principle
+
+`AgentService.handle_message` is the single chokepoint that knows "queued vs running".
+The **reaction** indicator is therefore **owned by the gate**, not by `start()`.
+`start()` keeps owning the **typing / ack-message** modes (eager, immediate feedback);
+it only *records* that the reaction indicator is the selected mode and defers the
+actual add to the gate.
+
+### 3.2 `core/processing_indicator.py`
+
+- Add `QUEUED_REACTION_EMOJI = "👌"`.
+- `ProcessingIndicatorHandle`: add `reaction_indicator_selected: bool = False`.
+ (P1.2) It is NOT load-bearing in the OpenCode snapshot/restore path — restore only
+ happens after `promote_reaction_to_running` has already set `ack_reaction_emoji=👀`,
+ and `finish()` keys off that field directly — so omitting it from
+ `to_snapshot`/`from_snapshot` is acceptable for this scope. Document the reason
+ inline so a future reader doesn't add it cargo-cult.
+- `_start_reaction_indicator(handle, *, emoji=ACK_REACTION_EMOJI)` — parametrize emoji.
+- Change `start()` so the reaction mode is **selected but not added**:
+ - Normal mode loop: when the candidate mode is `reaction` and `_mode_supported(...,
+ "reaction", context)` is true, set `handle.reaction_indicator_selected = True` and
+ `return handle` (preserves single-mode "first match wins"; does NOT call
+ `_start_reaction_indicator`). `message`/`typing` cases stay eager as today.
+ - Concise-status-bubble branch (lines 199-210): keep starting typing eagerly; for
+ reaction, set `handle.reaction_indicator_selected = True` (do NOT add now).
+- New service methods (best-effort, idempotent; both sync the request parallel fields):
+ - `async def show_queued_reaction(self, request_or_handle) -> bool`
+ - resolve handle; if `not handle.reaction_indicator_selected` → return False.
+ - if `handle.ack_reaction_emoji` already set → return False (no double-add).
+ - add `QUEUED_REACTION_EMOJI` via `_start_reaction_indicator(handle,
+ emoji=QUEUED_REACTION_EMOJI)`; on success set handle fields, mirror onto
+ `request.ack_reaction_message_id/.ack_reaction_emoji` (P1.1). Return success.
+ - `async def promote_reaction_to_running(self, request_or_handle) -> None`
+ - resolve handle; if `not handle.reaction_indicator_selected` → no-op.
+ - **idempotency guard (P2.1): if `handle.ack_reaction_emoji == ACK_REACTION_EMOJI`
+ → return** (already promoted; never double-add 👀).
+ - if `handle.ack_reaction_emoji == QUEUED_REACTION_EMOJI`: `remove_reaction(👌)`
+ then `add_reaction(👀)`; else (nothing shown yet) `add_reaction(👀)`.
+ - update handle fields to 👀 and **mirror onto the request parallel fields** (P1.1).
+- `finish()` unchanged: it already removes `handle.ack_reaction_emoji` (👌 or 👀) and
+ clears `request.*`.
+
+### 3.3 `modules/agents/service.py handle_message` (with P0.1 fix)
+
+```python
+agent = self.get(agent_name)
+runtime_key = self._runtime_turn_key(agent, request)
+gate = self._get_turn_gate(runtime_key)
+was_busy = gate.lock.locked()
+indicator = getattr(self.controller, "processing_indicator", None)
+queued_shown = False
+if was_busy and indicator is not None:
+ try:
+ queued_shown = bool(await indicator.show_queued_reaction(request))
+ except Exception:
+ logger.debug("show_queued_reaction failed", exc_info=True)
+try:
+ await gate.lock.acquire()
+except BaseException:
+ # P0.1: cancellation (e.g. SIGTERM) while still queued escapes here, OUTSIDE
+ # the main try below. Clean up the queued 👌 (+ any eager typing) so it doesn't
+ # leak permanently on the user's message.
+ if queued_shown and indicator is not None:
+ try:
+ await indicator.finish(getattr(request, "processing_indicator", None) or request)
+ except Exception:
+ logger.debug("queued reaction cleanup on cancel failed", exc_info=True)
+ raise
+gate.token = uuid.uuid4().hex
+gate.backend = agent.name
+gate.runtime_started = False
+self._stamp_runtime_turn(request, runtime_key, gate.token)
+try:
+ manager = getattr(self.controller, "session_turns", None)
+ if manager is not None:
+ manager.on_running(request.context)
+ await self._begin_turn_status(request.context)
+ if indicator is not None:
+ try:
+ await indicator.promote_reaction_to_running(request)
+ except Exception:
+ logger.debug("promote_reaction_to_running failed", exc_info=True)
+ self._track_processing_indicator_turn(request)
+ await agent.handle_message(request)
+except asyncio.CancelledError:
+ ... # existing
+```
+
+Notes:
+- `was_busy = gate.lock.locked()` is synchronous; the only await before `acquire()` is
+ the `show_queued_reaction` call. If the holder releases during it, `acquire()` returns
+ immediately and `promote_reaction_to_running` swaps 👌 → 👀 (brief 👌). Acceptable.
+- Non-busy path: no 👌; `promote_reaction_to_running` adds 👀 directly (goal #3).
+- `finish()` on the cancel path also stops the eager typing keepalive — correct full
+ cleanup for a never-run queued message; idempotent with any outer cleanup.
+
+### 3.4 Cleanup matrix (verified)
+
+| Exit path | Mechanism | 👌/👀 removed? |
+| --- | --- | --- |
+| Normal terminal result | `finish_terminal_turn`/agent `_remove_ack_reaction` → `finish()` (handle is 👀 after promote, tracked after promote) | yes |
+| Backend exception in turn | `service.py except Exception` emits silent result → outbound cleanup; handle reachable via token (stamped pre-exception) | yes |
+| Cancel **while running** | `service.py except CancelledError` → `_tidy_on_cancel` emit | yes |
+| Cancel **while queued** (P0.1) | new `except BaseException` around `acquire()` → `indicator.finish(...)` | yes (FIXED) |
+| `request` unbound before build (`message_handler` `except NameError`, ~500) | falls back to `finish(processing_indicator)`; handle object carries fields | yes |
+
+### 3.5 Subagent coexistence (P2.2)
+
+🤖 is added in `message_handler` (392-405) *before* the gate; 👌/👀 are added at the
+gate. So a queued subagent message shows 🤖 first, then 👌 once it reaches the gate,
+then 👀 on promote — both reactions coexist; `promote_reaction_to_running` only touches
+the ack reaction. The add order (🤖 then 👌) is accepted; platforms do not guarantee
+reaction display order anyway.
+
+## 4. File-by-file change list
+
+1. `core/processing_indicator.py` — `QUEUED_REACTION_EMOJI`; handle field
+ `reaction_indicator_selected`; parametrized `_start_reaction_indicator`;
+ `start()` selects-but-defers reaction (normal + concise paths);
+ `show_queued_reaction()` / `promote_reaction_to_running()` (both sync request fields).
+2. `modules/agents/service.py` — `handle_message`: `was_busy` peek +
+ `show_queued_reaction` before acquire + `except BaseException` cleanup around
+ acquire (P0.1) + `promote_reaction_to_running` after `_begin_turn_status` (all guarded).
+3. `core/handlers/message_handler.py` — no functional add/remove change at 390 (reaction
+ no longer added there because `start()` defers it); confirm nothing else relied on
+ `start()` having added the reaction synchronously.
+4. No IM adapter changes. No i18n (emojis are not localized text).
+
+## 5. Test plan
+
+- `tests/test_processing_indicator_reaction.py` (new):
+ - reaction selected + not busy → `promote` adds 👀 once; `finish` removes 👀.
+ - reaction selected + busy → `show_queued_reaction` adds 👌; `promote` removes 👌 +
+ adds 👀; `finish` removes 👀. Assert request parallel fields synced after each step.
+ - typing/message mode (reaction not selected) → `show_queued`/`promote` are no-ops
+ (no `add_reaction` calls).
+ - WeChat `add_reaction` returns False → `show_queued_reaction` returns False, handle
+ stays clean, no crash.
+- `tests/test_agent_service.py` / `tests/test_runtime_service_lock.py`:
+ - 2nd message with gate held → `show_queued_reaction(👌)` before `acquire()`;
+ `promote` after the 1st releases.
+ - **cancel while queued** → `acquire()` raises CancelledError → `finish()` called →
+ 👌 removed (P0.1 regression test).
+- `tests/test_message_handler_typing.py`: the eager-👀 assertions (around lines
+ 285-297, 592-594, 690-691, 939) must now assert `controller.im_client.reactions == []`
+ AND `request.ack_reaction_emoji is None` / `request.ack_reaction_message_id is None`
+ immediately after `handle_user_message` (reaction is selected-but-deferred, the stub
+ agent service never promotes). The promote/queued add/remove assertions move into the
+ new `tests/test_processing_indicator_reaction.py`.
+- `tests/test_status_bubble_indicator.py`: update any assertion that the concise path
+ eagerly adds the reaction (now deferred to the gate).
+- Scenario: inspect `tests/scenarios/message_delivery/`; extend or add a
+ queued→running reaction scenario if a matching shape exists; surface the scenario ID
+ in the test + PR description.
+
+## 6. Breakage risks
+
+- Tests asserting "reaction added at message arrival" must be updated
+ (`test_message_handler_typing.py`, `test_status_bubble_indicator.py`). Expected.
+- Reaction now appears at the gate rather than at 390. For a non-busy turn the gate is
+ acquired ~immediately, so the latency delta is one event-loop hop; for messages with
+ attachments the reaction already followed file processing only loosely — confirm the
+ perceived latency is acceptable (typing indicator, when active, still fires at 390).
+- Slack reaction rate limit (~1/s per conversation): the promote does remove+add (2
+ calls) only for genuinely queued messages; non-queued messages do a single add.
+ A queued **subagent** message is the worst case — 🤖 add, 👌 add, 👌 remove, 👀 add
+ = 4 sequential reaction calls (P2.3). Acceptable; note for high-frequency bursts.
+- Telegram: 👌 is accepted by the API (no code change needed); a future Telegram emoji
+ rejection is swallowed → no reaction, no crash.
+- P0.1 cancel-while-queued cleanup is the key correctness item; covered by a dedicated
+ regression test.
+
+## 7. Rollout
+
+- Worktree from `alex/master`.
+- Implement; focused pytest (processing_indicator + agent_service + runtime lock +
+ message_handler typing); `ruff check` on changed files.
+- Optional Slack Incus regression to eyeball 👌 → 👀 → cleared, and queue cancel.
+- PR; codex review + simplify loop; keep CI gates; PR body names the capability +
+ scenario IDs + evidence layers.
+
+## 8. Resolved decisions
+
+1. Reaction is **gate-owned (refined B1)**: non-busy → 👀 directly; busy → 👌 then 👀.
+2. `start()` selects-but-defers the reaction; typing/message stay eager. Concise path
+ defers the reaction too.
+3. Emoji: 👌 `:ok_hand:` (user-selected; not the hourglass used elsewhere).
+4. P0.1 fixed via `except BaseException` around `gate.lock.acquire()`.
+5. request parallel fields synced in both new methods (P1.1).
+6. Scenario catalog: to be confirmed against `tests/scenarios/message_delivery/` during
+ implementation.
diff --git a/modules/agents/service.py b/modules/agents/service.py
index c44c71d80..d7d6753d9 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -43,12 +43,75 @@ class AgentService:
agent = self.get(agent_name)
runtime_key = self._runtime_turn_key(agent, request)
gate = self._get_turn_gate(runtime_key)
- await gate.lock.acquire()
+ # Only a message that is ACTUALLY queued behind a running turn shows the
+ # queued 👌. The gate is held for the whole turn (released only on the
+ # terminal result via the outbound dispatcher), so gate.lock.locked() here
+ # means another turn for this runtime key is in flight and this message will
+ # block on acquire() below — surface that wait with 👌, then promote it to
+ # the running 👀 once the gate is acquired. A non-contended message skips 👌
+ # entirely and goes straight to 👀 at promote_reaction_to_running, so it does
+ # NOT flash 👌→👀. Reaction add/remove is owned by the processing indicator
+ # and is a no-op on platforms / modes without a reaction indicator (e.g.
+ # WeChat, typing-only, avibe Web).
+ indicator = getattr(self.controller, "processing_indicator", None)
+ queued_reaction_task: Optional[asyncio.Task] = None
+ if indicator is not None and gate.lock.locked():
+ # Contended: show the queued 👌. Fire it as a CONCURRENT task instead of
+ # awaiting it here — awaiting a network reaction call before acquire()
+ # would leave this turn OUT of the lock's FIFO waiter queue, so a later
+ # same-runtime message could reach acquire() first and reorder prompts
+ # within the session (Codex P1). Calling acquire() immediately reserves
+ # this turn's place in the queue; the task adds 👌 concurrently while we
+ # block, and we join it after acquiring (before promoting to 👀).
+ queued_reaction_task = asyncio.create_task(indicator.show_queued_reaction(request))
+ try:
+ await gate.lock.acquire()
+ except BaseException:
+ # Cancellation (e.g. SIGTERM / shutdown) while still waiting in the
+ # queue is raised by acquire() OUTSIDE the main try block below, so its
+ # CancelledError handler never runs. Let the queued-reaction task settle,
+ # then clean up the 👌 (and any eager typing) so it does not leak.
+ if queued_reaction_task is not None:
+ try:
+ await queued_reaction_task
+ except BaseException:
+ pass
+ if indicator is not None:
+ try:
+ # Pass the request (not the handle) so finish() clears BOTH
+ # the handle and the flat request.ack_reaction_* fields.
+ await indicator.finish(request)
+ except Exception:
+ logger.debug("Failed to clean up queued reaction on cancel", exc_info=True)
+ raise
gate.token = uuid.uuid4().hex
gate.backend = agent.name
gate.runtime_started = False
self._stamp_runtime_turn(request, runtime_key, gate.token)
try:
+ # Register the indicator handle for terminal/cancel cleanup BEFORE the
+ # reaction awaits below. If the turn is cancelled (shutdown / supersede)
+ # while promote is awaiting the reaction API, the scheduled terminal tidy
+ # resolves the handle by turn token from this registry — tracking it first
+ # ensures a queued 👌 or fallback typing/message indicator is still
+ # finished instead of leaking on the message (Codex P2).
+ self._track_processing_indicator_turn(request)
+ # Settle the concurrently-added queued 👌 and promote it to the running
+ # 👀 INSIDE this cancellation-managed try. A cancel (shutdown / supersede)
+ # during these awaits must reach the CancelledError handler below so the
+ # runtime turn is released; otherwise the gate token + lock would leak and
+ # later prompts for this runtime key would block forever (Codex P1). Each
+ # is individually guarded so a reaction failure can't break the turn.
+ if queued_reaction_task is not None:
+ try:
+ await queued_reaction_task
+ except Exception:
+ logger.debug("Failed to settle queued reaction", exc_info=True)
+ if indicator is not None:
+ try:
+ await indicator.promote_reaction_to_running(request, agent_name=agent_name)
+ except Exception:
+ logger.debug("Failed to promote reaction to running", exc_info=True)
# INBOUND status chokepoint (one of exactly two — the other is the outbound
# MessageDispatcher.emit_agent_message). Every turn, every source (chat /
# scheduled / Show Page), every backend funnels through here, so this is the
@@ -66,7 +129,6 @@ class AgentService:
# are optional and guarded so a missing hook or a bubble failure can
# never break the turn.
await self._begin_turn_status(request.context)
- self._track_processing_indicator_turn(request)
await agent.handle_message(request)
except asyncio.CancelledError:
# Shutdown / SIGTERM / supersede cancels the turn mid-flight. Without a
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index edf69c4bf..717b62032 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -43,6 +43,8 @@ _EMOJI_MAP: Dict[str, str] = {
"👀": "OnIt",
"robot_face": "SMART",
"🤖": "SMART",
+ "ok_hand": "OK",
+ "👌": "OK",
"thumbsup": "THUMBSUP",
"👍": "THUMBSUP",
"+1": "THUMBSUP",
@@ -823,6 +825,16 @@ class FeishuBot(BaseIMClient):
async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
self._ensure_client()
emoji_type = _normalize_emoji(emoji)
+ if not emoji_type.isascii():
+ # Feishu emoji_type values are ASCII keys (e.g. ``OK``, ``SMART``). A
+ # non-ASCII value means the raw unicode emoji has no mapping and the API
+ # will reject it — surface it instead of failing silently. Add the
+ # mapping to ``_EMOJI_MAP``.
+ logger.warning(
+ "Feishu reaction %r has no emoji_type mapping; the API will reject it. "
+ "Add it to feishu._EMOJI_MAP.",
+ emoji,
+ )
try:
from lark_oapi.api.im.v1 import (
CreateMessageReactionRequest,
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 1657d8ec4..19b6788c2 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1325,20 +1325,45 @@ class SlackBot(BaseIMClient):
logger.warning(f"Unexpected error fetching shared thread from {channel_id}/{message_ts}: {e}")
return None
- async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
- """Add a reaction emoji to a Slack message."""
- self._ensure_clients()
+ @staticmethod
+ def _slack_reaction_name(emoji: str) -> str:
+ """Translate a unicode reaction emoji to the Slack short name.
+ 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.
+ """
name = (emoji or "").strip()
if name.startswith(":") and name.endswith(":") and len(name) > 2:
name = name[1:-1]
- if name in ["👀", "eyes", "eye"]:
- name = "eyes"
- elif name in ["🤖", "robot_face", "robot"]:
- name = "robot_face"
+ aliases = {
+ "👀": "eyes",
+ "eye": "eyes",
+ "🤖": "robot_face",
+ "robot": "robot_face",
+ "👌": "ok_hand",
+ "ok": "ok_hand",
+ }
+ return aliases.get(name, name)
+
+ async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
+ """Add a reaction emoji to a Slack message."""
+ self._ensure_clients()
+ name = self._slack_reaction_name(emoji)
if not name:
return False
+ if not name.isascii():
+ # Slack reaction names are ASCII short names (e.g. ``ok_hand``). A
+ # non-ASCII value here is a raw unicode emoji with no mapping, which
+ # reactions.add rejects with ``invalid_name`` — surface it instead of
+ # failing silently. Add the mapping to ``_slack_reaction_name``.
+ logger.warning(
+ "Slack reaction %r has no short-name mapping; reactions.add will reject it. "
+ "Add it to SlackBot._slack_reaction_name.",
+ emoji,
+ )
try:
await self.web_client.reactions_add(
@@ -1377,14 +1402,7 @@ class SlackBot(BaseIMClient):
"""Remove a reaction emoji from a Slack message."""
self._ensure_clients()
- name = (emoji or "").strip()
- if name.startswith(":") and name.endswith(":") and len(name) > 2:
- name = name[1:-1]
- if name in ["👀", "eyes", "eye"]:
- name = "eyes"
- elif name in ["🤖", "robot_face", "robot"]:
- name = "robot_face"
-
+ name = self._slack_reaction_name(emoji)
if not name:
return False
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index 39546d7d4..f15843d80 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -224,6 +224,357 @@ def test_agent_service_serializes_same_runtime_until_terminal_release() -> None:
asyncio.run(_run())
+class _RecordingIndicator:
+ """Records the queued/promote/finish reaction calls the gate drives."""
+
+ def __init__(self, log: list[str]):
+ self._log = log
+
+ async def show_queued_reaction(self, _request):
+ self._log.append("show_queued")
+ return True
+
+ async def promote_reaction_to_running(self, _request, *, agent_name=None):
+ self._log.append("promote")
+
+ async def finish(self, _request_or_handle):
+ self._log.append("finish")
+
+
+class _IndicatorController(_Controller):
+ def __init__(self, log: list[str]):
+ super().__init__()
+ self.processing_indicator = _RecordingIndicator(log)
+
+
+def test_agent_service_shows_queued_reaction_then_promotes_on_start() -> None:
+ async def _run():
+ log: list[str] = []
+ controller = _IndicatorController(log)
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ release_first = asyncio.Event()
+ agent = _RuntimeAgent(release_first)
+ service.register(agent)
+
+ first_request = _request("first")
+ first = asyncio.create_task(service.handle_message("claude", first_request))
+ await asyncio.sleep(0)
+ assert agent.started == ["first"]
+
+ second = asyncio.create_task(service.handle_message("claude", _request("second")))
+ await asyncio.sleep(0.05)
+ # Only the SECOND message is queued (the first holds the gate): it shows the
+ # queued 👌 and is blocked on acquire(). The first ran uncontended, so it
+ # never showed 👌 and has already promoted to 👀.
+ assert "show_queued" in log
+ assert log.count("promote") == 1
+
+ service.release_runtime_turn(first_request.context)
+ release_first.set()
+ await asyncio.wait_for(first, timeout=3)
+ await asyncio.wait_for(second, timeout=3)
+
+ assert log.count("show_queued") == 1 # only the genuinely-queued turn shows 👌
+ assert log.count("promote") == 2 # both turns promoted when they started
+ assert "finish" not in log # no cancellation occurred
+
+ asyncio.run(_run())
+
+
+def test_agent_service_cleans_queued_reaction_when_cancelled_while_waiting() -> None:
+ async def _run():
+ log: list[str] = []
+ controller = _IndicatorController(log)
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ release_first = asyncio.Event()
+ agent = _RuntimeAgent(release_first)
+ service.register(agent)
+
+ first_request = _request("first")
+ first = asyncio.create_task(service.handle_message("claude", first_request))
+ await asyncio.sleep(0)
+ assert agent.started == ["first"]
+
+ second = asyncio.create_task(service.handle_message("claude", _request("second")))
+ await asyncio.sleep(0.05)
+ assert "show_queued" in log
+
+ # Cancel the queued message while it is still blocked on gate.acquire():
+ # its queued 👌 must be cleaned up (P0.1), and it must never promote.
+ second.cancel()
+ try:
+ await second
+ except asyncio.CancelledError:
+ pass
+
+ assert "finish" in log
+ assert log.count("promote") == 1
+
+ first.cancel()
+ await asyncio.gather(first, return_exceptions=True)
+
+ asyncio.run(_run())
+
+
+class _ReactionIM:
+ """Records the real reaction add/remove calls per message id."""
+
+ def __init__(self):
+ self.events: list[tuple[str, str, str]] = []
+
+ async def add_reaction(self, context, message_id, emoji):
+ self.events.append(("add", message_id, emoji))
+ return True
+
+ async def remove_reaction(self, context, message_id, emoji):
+ self.events.append(("remove", message_id, emoji))
+ return True
+
+
+class _RealIndicatorController(_Controller):
+ """Wires the REAL ProcessingIndicatorService so the gate exercises the actual
+ show_queued/promote path (not a recording stub)."""
+
+ def __init__(self, im: _ReactionIM):
+ super().__init__()
+ from core.processing_indicator import ProcessingIndicatorService
+
+ self.config = SimpleNamespace(ack_mode="reaction", language="en")
+ self._im = im
+ self.processing_indicator = ProcessingIndicatorService(self)
+
+ def get_im_client_for_context(self, _context):
+ return self._im
+
+
+def _reaction_request(message: str, message_id: str, runtime_key: str = "session:/repo"):
+ from core.processing_indicator import ProcessingIndicatorHandle
+
+ context = SimpleNamespace(
+ platform_specific={},
+ message_id=message_id,
+ platform="slack",
+ channel_id="C1",
+ )
+ handle = ProcessingIndicatorHandle(context=context, reaction_indicator_selected=True)
+ return SimpleNamespace(
+ context=context,
+ message=message,
+ composite_session_id=runtime_key,
+ processing_indicator=handle,
+ ack_reaction_message_id=None,
+ ack_reaction_emoji=None,
+ ack_message_id=None,
+ typing_indicator_active=False,
+ typing_indicator_task=None,
+ )
+
+
+def test_real_indicator_shows_queued_reaction_on_second_message_while_first_holds_gate() -> None:
+ """High-fidelity: the REAL ProcessingIndicatorService must put 👌 on the SECOND
+ message while the FIRST still holds the runtime gate, then promote it to 👀."""
+
+ async def _run():
+ from core.processing_indicator import ACK_REACTION_EMOJI, QUEUED_REACTION_EMOJI
+
+ im = _ReactionIM()
+ controller = _RealIndicatorController(im)
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ release_first = asyncio.Event()
+ agent = _RuntimeAgent(release_first)
+ service.register(agent)
+
+ req1 = _reaction_request("first", "m1")
+ first = asyncio.create_task(service.handle_message("claude", req1))
+ for _ in range(200):
+ if ("add", "m1", ACK_REACTION_EMOJI) in im.events:
+ break
+ await asyncio.sleep(0)
+ # First (uncontended) has started and shows the running 👀 directly — it must
+ # NOT have shown the queued 👌 (no 👌→👀 flash for a non-queued message).
+ assert ("add", "m1", ACK_REACTION_EMOJI) in im.events, im.events
+ assert ("add", "m1", QUEUED_REACTION_EMOJI) not in im.events, im.events
+
+ req2 = _reaction_request("second", "m2")
+ second = asyncio.create_task(service.handle_message("claude", req2))
+ for _ in range(200):
+ if ("add", "m2", QUEUED_REACTION_EMOJI) in im.events:
+ break
+ await asyncio.sleep(0)
+
+ # THE KEY ASSERTION: the queued 👌 is on m2 while m1's turn still holds the
+ # gate (m2 has not been promoted to 👀 yet).
+ assert ("add", "m2", QUEUED_REACTION_EMOJI) in im.events, im.events
+ assert ("add", "m2", ACK_REACTION_EMOJI) not in im.events, im.events
+
+ release_first.set()
+ service.release_runtime_turn(req1.context)
+ await asyncio.wait_for(first, timeout=3)
+ await asyncio.wait_for(second, timeout=3)
+
+ # Once m2's turn starts, 👌 is removed and 👀 added on m2.
+ assert ("remove", "m2", QUEUED_REACTION_EMOJI) in im.events, im.events
+ assert ("add", "m2", ACK_REACTION_EMOJI) in im.events, im.events
+
+ asyncio.run(_run())
+
+
+def test_processing_indicator_tracked_before_promote() -> None:
+ """Regression (Codex P2): the indicator handle must be tracked (registered for
+ terminal/cancel cleanup) BEFORE the promote await, so a cancel during promote
+ can still find and finish it instead of leaking the queued/fallback indicator."""
+
+ async def _run():
+ log: list[str] = []
+
+ class _Indicator:
+ def track_turn(self, _context, _request):
+ log.append("track")
+
+ async def show_queued_reaction(self, _request):
+ return False
+
+ async def promote_reaction_to_running(self, _request, *, agent_name=None):
+ log.append("promote")
+
+ async def finish(self, _request_or_handle):
+ log.append("finish")
+
+ controller = _Controller()
+ controller.processing_indicator = _Indicator()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ service.register(_RuntimeAgent())
+
+ request = _request("first")
+ request.processing_indicator = object() # truthy so _track_processing_indicator_turn runs
+ await service.handle_message("claude", request)
+
+ assert log[:2] == ["track", "promote"], log
+
+ asyncio.run(_run())
+
+
+def test_gate_released_when_cancelled_during_promote() -> None:
+ """Regression (Codex P1): a cancel after acquire() but during the
+ settle/promote awaits must still release the runtime gate, or the token + lock
+ leak and later prompts for the same runtime key block forever."""
+
+ async def _run():
+ promote_started = asyncio.Event()
+ block = asyncio.Event()
+
+ class _BlockingIndicator:
+ async def show_queued_reaction(self, _request):
+ return False
+
+ async def promote_reaction_to_running(self, _request, *, agent_name=None):
+ promote_started.set()
+ await block.wait() # cancel hits here, inside the managed try
+
+ async def finish(self, _request_or_handle):
+ return None
+
+ controller = _Controller()
+ controller.processing_indicator = _BlockingIndicator()
+ controller.emit_agent_message = AsyncMock() # used by the cancel tidy
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ service.register(_RuntimeAgent())
+
+ request = _request("first")
+ task = asyncio.create_task(service.handle_message("claude", request))
+ await asyncio.wait_for(promote_started.wait(), timeout=2)
+ gate = service._get_turn_gate("session:/repo")
+ assert gate.lock.locked() # acquired, currently in promote
+
+ task.cancel()
+ try:
+ await asyncio.wait_for(task, timeout=2)
+ except BaseException:
+ pass
+
+ # The CancelledError handler schedules a tidy task that releases the gate.
+ released = False
+ for _ in range(200):
+ await asyncio.sleep(0)
+ if not gate.lock.locked() and gate.token == "":
+ released = True
+ break
+ assert released # gate token + lock released despite cancel during promote
+
+ asyncio.run(_run())
+
+
+def test_queued_reaction_does_not_delay_gate_acquire_fifo() -> None:
+ """Regression (Codex P1): a contended turn must reserve its FIFO place on the
+ runtime gate WITHOUT waiting for the (network) queued-reaction call. If the 👌
+ add were awaited before acquire(), a later same-runtime message could acquire
+ first and reorder prompts."""
+
+ async def _run():
+ log: list[str] = []
+ block = asyncio.Event()
+
+ class _SlowIndicator:
+ async def show_queued_reaction(self, _request):
+ log.append("show_queued_start")
+ await block.wait() # simulate slow Slack/Feishu reaction API
+ return True
+
+ async def promote_reaction_to_running(self, _request, *, agent_name=None):
+ log.append("promote")
+
+ async def finish(self, _request_or_handle):
+ log.append("finish")
+
+ controller = _Controller()
+ controller.processing_indicator = _SlowIndicator()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ release_first = asyncio.Event()
+ agent = _RuntimeAgent(release_first)
+ service.register(agent)
+
+ first_request = _request("first")
+ first = asyncio.create_task(service.handle_message("claude", first_request))
+ await asyncio.sleep(0)
+ assert agent.started == ["first"]
+ gate = service._get_turn_gate("session:/repo")
+
+ second = asyncio.create_task(service.handle_message("claude", _request("second")))
+ # Let the second turn run far enough to fire the queued-reaction task and
+ # reach acquire(). Its show_queued is blocked forever, so if acquire() were
+ # gated behind it the gate would have NO waiter.
+ entered_queue = False
+ for _ in range(200):
+ await asyncio.sleep(0)
+ if not entered_queue and gate.lock._waiters and len(gate.lock._waiters) >= 1:
+ entered_queue = True
+ if entered_queue and "show_queued_start" in log:
+ break
+ # The turn reserved its FIFO place on the gate (it is a waiter) even though
+ # its queued reaction is still blocked — proving acquire() was NOT gated
+ # behind the reaction network call.
+ assert entered_queue
+ assert "show_queued_start" in log # the queued reaction was kicked off concurrently
+
+ # Cleanup: unblock everything and let the tasks settle.
+ block.set()
+ release_first.set()
+ service.release_runtime_turn(first_request.context)
+ for task in (first, second):
+ try:
+ await asyncio.wait_for(task, timeout=3)
+ except Exception:
+ pass
+
+ asyncio.run(_run())
+
+
def test_agent_service_allows_distinct_runtime_keys_in_parallel() -> None:
async def _run():
service = AgentService(controller=_Controller())
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 7f91df06b..fa17e57df 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -292,6 +292,12 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
_, request = controller.agent_service.requests[0]
self.assertFalse(request.typing_indicator_active)
+ # Reaction is selected but deferred to the runtime gate (not added eagerly).
+ self.assertTrue(request.processing_indicator.reaction_indicator_selected)
+ self.assertIsNone(request.ack_reaction_message_id)
+ self.assertEqual(controller.im_client.reactions, [])
+ # Turn start (gate acquired) promotes to the running 👀 on the message.
+ await controller.processing_indicator.promote_reaction_to_running(request)
self.assertEqual(request.ack_reaction_message_id, "m1")
self.assertEqual(request.ack_reaction_emoji, "👀")
self.assertEqual(controller.im_client.reactions, [("C1", "m1", "👀")])
@@ -589,6 +595,10 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
_, request = controller.agent_service.requests[0]
self.assertFalse(request.typing_indicator_active)
+ self.assertTrue(request.processing_indicator.reaction_indicator_selected)
+ self.assertIsNone(request.ack_reaction_message_id)
+ self.assertEqual(controller.im_client.reactions, [])
+ await controller.processing_indicator.promote_reaction_to_running(request)
self.assertEqual(request.ack_reaction_message_id, "m1")
self.assertEqual(request.ack_reaction_emoji, "👀")
self.assertEqual(controller.im_client.reactions, [("tg-chat", "m1", "👀")])
@@ -687,6 +697,10 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
_, request = controller.agent_service.requests[0]
self.assertFalse(request.typing_indicator_active)
self.assertEqual(controller.im_client.typing_calls, [])
+ self.assertTrue(request.processing_indicator.reaction_indicator_selected)
+ self.assertIsNone(request.ack_reaction_message_id)
+ self.assertEqual(controller.im_client.reactions, [])
+ await controller.processing_indicator.promote_reaction_to_running(request)
self.assertEqual(request.ack_reaction_message_id, "om_1")
self.assertEqual(controller.im_client.reactions, [("lark-chat", "om_1", "👀")])
@@ -839,7 +853,11 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(request.subagent_name, "reviewer")
self.assertEqual(request.subagent_key, "reviewer")
self.assertEqual(request.message, "check this")
- self.assertEqual(controller.im_client.reactions, [("C1", "m1", "👀"), ("C1", "m1", "🤖")])
+ # 🤖 is added eagerly in the handler; the ack reaction is deferred to the
+ # gate, so only 🤖 is present until the turn starts and promotes to 👀.
+ self.assertEqual(controller.im_client.reactions, [("C1", "m1", "🤖")])
+ await controller.processing_indicator.promote_reaction_to_running(request)
+ self.assertEqual(controller.im_client.reactions, [("C1", "m1", "🤖"), ("C1", "m1", "👀")])
async def test_scheduled_turn_returns_error_string_after_notifying_im(self):
controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
@@ -936,12 +954,17 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(controller.im_client.removed_keyboards, [("chat1", "slack", "prompt-msg")])
self.assertEqual(controller.im_client.sent_messages, [("chat1", "Reply: 按钮 1")])
- self.assertEqual(controller.im_client.reactions, [("chat1", "msg-1", "👀")])
+ # Reaction deferred to the gate; the echo message id is still the target.
+ self.assertEqual(controller.im_client.reactions, [])
_, request = controller.agent_service.requests[0]
self.assertIsNone(request.context.message_id)
- self.assertEqual(request.ack_reaction_message_id, "msg-1")
+ self.assertTrue(request.processing_indicator.reaction_indicator_selected)
+ self.assertIsNone(request.ack_reaction_message_id)
self.assertIsNone(request.ack_message_id)
self.assertFalse(request.typing_indicator_active)
+ await controller.processing_indicator.promote_reaction_to_running(request)
+ self.assertEqual(controller.im_client.reactions, [("chat1", "msg-1", "👀")])
+ self.assertEqual(request.ack_reaction_message_id, "msg-1")
async def test_quick_reply_callback_typing_uses_global_indicator_strategy(self):
controller = _StubController(platform="telegram", ack_mode="typing", typing_result=True)
diff --git a/tests/test_processing_indicator_reaction.py b/tests/test_processing_indicator_reaction.py
new file mode 100644
index 000000000..831d25b6e
--- /dev/null
+++ b/tests/test_processing_indicator_reaction.py
@@ -0,0 +1,243 @@
+"""Queued (👌) → running (👀) reaction lifecycle for the processing indicator.
+
+The reaction is SELECTED in start() but ADDED at the runtime gate: a message
+waiting behind a running turn shows the queued 👌, which is promoted to the
+running 👀 when its turn actually starts, and removed on finish. See
+core/processing_indicator.py and AgentService.handle_message.
+"""
+
+from __future__ import annotations
+
+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 (
+ ACK_REACTION_EMOJI,
+ QUEUED_REACTION_EMOJI,
+ ProcessingIndicatorHandle,
+ ProcessingIndicatorService,
+)
+from modules.im import MessageContext
+
+
+def _ctx(message_id="m1"):
+ return MessageContext(user_id="u1", channel_id="c1", message_id=message_id, platform="slack")
+
+
+class _FakeIM:
+ def __init__(self, *, add_ok=True, remove_ok=True, typing_ok=True):
+ self.add_ok = add_ok
+ self.remove_ok = remove_ok
+ self.typing_ok = typing_ok
+ self.calls: list[tuple[str, str, str]] = []
+ self.typing_calls: list[str] = []
+ self.clear_calls: list[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 self.remove_ok
+
+ async def send_typing_indicator(self, context):
+ self.typing_calls.append(context.channel_id)
+ return self.typing_ok
+
+ async def clear_typing_indicator(self, context):
+ self.clear_calls.append(context.channel_id)
+ return True
+
+
+def _svc(im):
+ svc = ProcessingIndicatorService.__new__(ProcessingIndicatorService)
+ svc.controller = SimpleNamespace(get_im_client_for_context=lambda ctx: im, im_client=im)
+ svc.config = SimpleNamespace()
+ svc._indicators_by_turn_token = {}
+ return svc
+
+
+def _request(handle):
+ return SimpleNamespace(
+ processing_indicator=handle,
+ ack_message_id=None,
+ ack_reaction_message_id=None,
+ ack_reaction_emoji=None,
+ typing_indicator_active=False,
+ typing_indicator_task=None,
+ )
+
+
+class QueuedReactionLifecycleTests(unittest.IsolatedAsyncioTestCase):
+ async def test_show_queued_then_promote_then_finish(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+
+ applied = await svc.show_queued_reaction(handle)
+ self.assertTrue(applied)
+ self.assertEqual(handle.ack_reaction_emoji, QUEUED_REACTION_EMOJI)
+ self.assertEqual(handle.ack_reaction_message_id, "m1")
+ self.assertEqual(im.calls, [("add", "m1", QUEUED_REACTION_EMOJI)])
+
+ await svc.promote_reaction_to_running(handle)
+ self.assertEqual(handle.ack_reaction_emoji, ACK_REACTION_EMOJI)
+ self.assertEqual(
+ im.calls,
+ [
+ ("add", "m1", QUEUED_REACTION_EMOJI),
+ ("remove", "m1", QUEUED_REACTION_EMOJI),
+ ("add", "m1", ACK_REACTION_EMOJI),
+ ],
+ )
+
+ await svc.finish(handle)
+ self.assertIsNone(handle.ack_reaction_emoji)
+ self.assertIsNone(handle.ack_reaction_message_id)
+ self.assertEqual(im.calls[-1], ("remove", "m1", ACK_REACTION_EMOJI))
+
+ async def test_promote_without_queued_adds_running_directly(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+
+ await svc.promote_reaction_to_running(handle)
+ self.assertEqual(handle.ack_reaction_emoji, ACK_REACTION_EMOJI)
+ self.assertEqual(im.calls, [("add", "m1", ACK_REACTION_EMOJI)])
+
+ async def test_promote_is_idempotent(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+
+ await svc.promote_reaction_to_running(handle)
+ await svc.promote_reaction_to_running(handle)
+ self.assertEqual(im.calls, [("add", "m1", ACK_REACTION_EMOJI)])
+
+ async def test_show_queued_noop_when_reaction_not_selected(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=False)
+
+ applied = await svc.show_queued_reaction(handle)
+ self.assertFalse(applied)
+ self.assertEqual(im.calls, [])
+ self.assertIsNone(handle.ack_reaction_emoji)
+
+ async def test_promote_noop_when_reaction_not_selected(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=False)
+
+ await svc.promote_reaction_to_running(handle)
+ self.assertEqual(im.calls, [])
+
+ async def test_show_queued_does_not_double_add(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+
+ self.assertTrue(await svc.show_queued_reaction(handle))
+ self.assertFalse(await svc.show_queued_reaction(handle))
+ self.assertEqual(im.calls, [("add", "m1", QUEUED_REACTION_EMOJI)])
+
+ async def test_show_queued_returns_false_when_platform_rejects(self):
+ # WeChat-like: add_reaction returns False — no handle state, no crash.
+ im = _FakeIM(add_ok=False)
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+
+ applied = await svc.show_queued_reaction(handle)
+ self.assertFalse(applied)
+ self.assertIsNone(handle.ack_reaction_emoji)
+ self.assertIsNone(handle.ack_reaction_message_id)
+
+ async def test_finish_removes_queued_reaction_on_cancel_while_queued(self):
+ # The cancel-while-queued path calls finish() with only 👌 shown.
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+ await svc.show_queued_reaction(handle)
+
+ await svc.finish(handle)
+ self.assertEqual(im.calls, [("add", "m1", QUEUED_REACTION_EMOJI), ("remove", "m1", QUEUED_REACTION_EMOJI)])
+ self.assertIsNone(handle.ack_reaction_emoji)
+
+ async def test_promote_keeps_queued_reaction_when_remove_fails(self):
+ # If removing 👌 fails on promote, keep owning 👌 (don't stack 👀); finish()
+ # must still be able to clear the queued reaction so it never leaks.
+ im = _FakeIM(remove_ok=False)
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+ await svc.show_queued_reaction(handle)
+
+ await svc.promote_reaction_to_running(handle)
+ # 👀 was NOT stacked on top; handle still owns 👌.
+ self.assertEqual(handle.ack_reaction_emoji, QUEUED_REACTION_EMOJI)
+ self.assertEqual([c for c in im.calls if c[0] == "add"], [("add", "m1", QUEUED_REACTION_EMOJI)])
+
+ await svc.finish(handle)
+ self.assertIsNone(handle.ack_reaction_emoji)
+ self.assertIsNone(handle.ack_reaction_message_id)
+
+ async def test_promote_falls_back_to_typing_when_reaction_add_fails(self):
+ # P2: if the reaction add fails at runtime (e.g. missing Slack scope), the
+ # deferred reaction has no lower candidate to fall through to, so promote
+ # must fall back to a typing indicator rather than leave no ack at all.
+ im = _FakeIM(add_ok=False)
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+
+ await svc.promote_reaction_to_running(handle)
+ self.assertIsNone(handle.ack_reaction_emoji) # reaction did not stick
+ self.assertTrue(handle.typing_indicator_active) # fell back to typing
+ self.assertTrue(im.typing_calls)
+
+ await svc.finish(handle) # cancels the typing keepalive task
+ self.assertFalse(handle.typing_indicator_active)
+
+ async def test_promote_falls_back_to_message_when_typing_unsupported(self):
+ # P2 follow-up: a platform with reactions + message but NO typing
+ # (Lark/Feishu). A failed reaction add must fall through to the ack message,
+ # not leave the user with no indicator.
+ im = _FakeIM(add_ok=False)
+ svc = _svc(im)
+ svc._capabilities = lambda ctx: object()
+ svc._mode_supported = lambda caps, mode, ctx: {"typing": False, "message": True}.get(mode, True)
+ started: list = []
+
+ async def _msg(handle, agent_name):
+ started.append(("message", agent_name))
+ handle.ack_message_id = "ack-1"
+ return True
+
+ svc._start_message_indicator = _msg
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+
+ await svc.promote_reaction_to_running(handle, agent_name="claude")
+ self.assertIsNone(handle.ack_reaction_emoji) # reaction did not stick
+ self.assertEqual(started, [("message", "claude")]) # fell back to ack message
+ self.assertEqual(handle.ack_message_id, "ack-1")
+
+ async def test_request_parallel_fields_synced(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = ProcessingIndicatorHandle(context=_ctx(), reaction_indicator_selected=True)
+ request = _request(handle)
+
+ await svc.show_queued_reaction(request)
+ self.assertEqual(request.ack_reaction_emoji, QUEUED_REACTION_EMOJI)
+ self.assertEqual(request.ack_reaction_message_id, "m1")
+
+ await svc.promote_reaction_to_running(request)
+ self.assertEqual(request.ack_reaction_emoji, ACK_REACTION_EMOJI)
+ self.assertEqual(request.ack_reaction_message_id, "m1")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index d0912c457..714acedd8 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -145,6 +145,57 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(ok)
self.assertEqual(calls[0]["name"], "robot_face")
+ async def test_add_reaction_maps_queued_ok_hand_to_slack_name(self):
+ # Regression: the queued 👌 reaction must map to the Slack short name
+ # "ok_hand"; sending the raw unicode returns invalid_name and the queued
+ # indicator silently never appears.
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ calls = []
+
+ class _WebClient:
+ async def reactions_add(self, **kwargs):
+ calls.append(kwargs)
+
+ async def reactions_remove(self, **kwargs):
+ calls.append(kwargs)
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ self.assertTrue(await slack.add_reaction(context, "1710000000.000010", "👌"))
+ self.assertTrue(await slack.remove_reaction(context, "1710000000.000010", "👌"))
+ self.assertEqual([c["name"] for c in calls], ["ok_hand", "ok_hand"])
+
+ async def test_add_reaction_warns_on_unmapped_unicode_emoji(self):
+ # Safeguard: an unmapped raw-unicode reaction emoji must log a WARNING so a
+ # future emoji that Slack would reject (invalid_name) is not lost silently.
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+
+ class _WebClient:
+ async def reactions_add(self, **kwargs):
+ return None
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ with self.assertLogs("modules.im.slack", level="WARNING") as captured:
+ await slack.add_reaction(context, "1710000000.000010", "🎉")
+ self.assertTrue(any("no short-name mapping" in m for m in captured.output))
+
+ async def test_add_reaction_maps_eyes_to_slack_name(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ calls = []
+
+ class _WebClient:
+ async def reactions_add(self, **kwargs):
+ calls.append(kwargs)
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ self.assertTrue(await slack.add_reaction(context, "1710000000.000010", "👀"))
+ self.assertEqual(calls[0]["name"], "eyes")
+
async def test_send_message_does_not_set_unfurl_params_by_default(self):
slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
sent_payloads = []
diff --git a/tests/test_status_bubble_indicator.py b/tests/test_status_bubble_indicator.py
index 566f39d18..9b8bd49b2 100644
--- a/tests/test_status_bubble_indicator.py
+++ b/tests/test_status_bubble_indicator.py
@@ -69,8 +69,9 @@ class ProcessingModeSuppressionTests(unittest.TestCase):
class StartConciseTests(unittest.IsolatedAsyncioTestCase):
- """In concise mode start() keeps the 👀 received-ack reaction AND typing
- keepalive (both best-effort), but never the ack message."""
+ """In concise mode start() SELECTS the reaction (added later at the runtime
+ gate as queued 👌 → running 👀) and keeps typing keepalive eager, but never
+ the ack message. The reaction is no longer added eagerly here."""
def _svc(self, *, concise, reaction_supported=True, typing_supported=True):
svc = ProcessingIndicatorService.__new__(ProcessingIndicatorService)
@@ -101,20 +102,32 @@ class StartConciseTests(unittest.IsolatedAsyncioTestCase):
svc._start_message_indicator = _message
return svc
- async def test_concise_adds_reaction_and_typing_no_message(self):
+ async def test_concise_selects_reaction_and_keeps_typing_no_message(self):
svc = self._svc(concise=True)
- await svc.start(_ctx(), "claude")
- self.assertEqual(svc.calls, ["reaction", "typing"]) # 👀 kept + typing; no ack message
+ handle = await svc.start(_ctx(), "claude")
+ # Reaction is deferred to the gate (not added here); typing stays eager.
+ self.assertEqual(svc.calls, ["typing"])
+ self.assertTrue(handle.reaction_indicator_selected)
async def test_concise_skips_reaction_when_unsupported(self):
svc = self._svc(concise=True, reaction_supported=False)
- await svc.start(_ctx(), "claude")
+ handle = await svc.start(_ctx(), "claude")
self.assertEqual(svc.calls, ["typing"])
+ self.assertFalse(handle.reaction_indicator_selected)
async def test_non_concise_uses_first_wins(self):
svc = self._svc(concise=False)
- await svc.start(_ctx(), "claude")
+ handle = await svc.start(_ctx(), "claude")
self.assertEqual(svc.calls, ["message"]) # first candidate wins, unchanged
+ self.assertFalse(handle.reaction_indicator_selected)
+
+ async def test_non_concise_reaction_mode_is_selected_but_deferred(self):
+ svc = self._svc(concise=False)
+ svc._processing_modes = lambda ctx: ["reaction"]
+ handle = await svc.start(_ctx(), "claude")
+ # Reaction selected but NOT added eagerly (added at the gate).
+ self.assertEqual(svc.calls, [])
+ self.assertTrue(handle.reaction_indicator_selected)
if __name__ == "__main__":