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(core): bound the typing keepalive to its turn (#2259)

Call White8cf43887946d
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 862a0fb0b..b7cd59b7e 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -862,6 +862,18 @@ class MessageHandler(BaseHandler):
if not bool(getattr(request, "failure_handled", False)):
await self._emit_agent_dispatch_failure(context, request, e)
return str(e)
+ except BaseException:
+ # Cancellation is not an Exception. Whoever starts the indicator
+ # finishes it unless it was handed off to the tracked turn, which then
+ # owns the cleanup (and the ⏹️/⚠️ receipt finishing here would pre-empt).
+ if processing_indicator is not None and not processing_indicator.handed_off:
+ try:
+ await self.controller.processing_indicator.finish(
+ request if request is not None else processing_indicator
+ )
+ except Exception:
+ logger.debug("Failed to finish processing indicator on cancel", exc_info=True)
+ raise
finally:
if attachment_lease is not None:
attachment_lease.release()
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index 23e3d08a1..1ac50b9f0 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -64,6 +64,20 @@ _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"
+# Typing keepalive bounds. "<bot> is typing…" claims a turn is working on this
+# conversation right now, so the loop re-checks that claim on every tick instead
+# of trusting every exit path to cancel it (see _typing_keepalive_loop).
+TYPING_KEEPALIVE_INTERVAL_SECONDS = 5.0
+# Backstop only: the per-tick currency check already ends typing when its turn
+# ends. Agent turns have no product maximum (they may run for hours and the
+# OpenCode active-turn timeout is disabled by default), so this sits at the
+# longest default bound Avibe puts on unattended work, the 6 h command-task
+# timeout. Hitting it on a real turn only drops the typing hint; the turn, its
+# status and its result are unaffected.
+TYPING_KEEPALIVE_MAX_SECONDS = 6 * 60 * 60
+# A target that rejects this many sends in a row (deleted thread, revoked
+# access) will not recover within the turn.
+TYPING_KEEPALIVE_MAX_FAILURES = 3
@dataclass
@@ -80,6 +94,13 @@ class ProcessingIndicatorHandle:
terminal_reaction_message_id: Optional[str] = None
typing_indicator_active: bool = False
typing_indicator_task: Optional[asyncio.Task] = None
+ # Ownership of the typing keepalive: whoever starts it finishes it, unless it
+ # was handed off to the tracked turn. Before track_turn the owner is the task
+ # that started it; track_turn records the runtime turn it was handed to. Both
+ # are process-local and deliberately absent from the snapshot.
+ owner_task: Optional[asyncio.Task] = None
+ runtime_turn_key: Optional[str] = None
+ runtime_turn_token: Optional[str] = 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
@@ -89,6 +110,10 @@ class ProcessingIndicatorHandle:
# across a restore.
reaction_indicator_selected: bool = False
+ @property
+ def handed_off(self) -> bool:
+ return bool(self.runtime_turn_token)
+
def to_snapshot(self) -> dict[str, Any]:
payload = self.context.platform_specific or {}
return {
@@ -243,16 +268,69 @@ class ProcessingIndicatorService:
lang = self.controller._get_lang() if hasattr(self.controller, "_get_lang") else getattr(self.config, "language", "en")
return f"📨 {i18n_t('message.ack', lang, agent=agent_label)}"
- async def _typing_keepalive_loop(self, context: MessageContext) -> None:
+ def _typing_turn_is_current(self, handle: ProcessingIndicatorHandle) -> bool:
+ """Whether the turn that owns this typing keepalive is still running.
+
+ After hand-off the runtime turn gate is the authority: a released or
+ superseded gate means the turn is over even if no cleanup reached this
+ handle (a dropped stale emit, a backend refresh). Before hand-off there is
+ no gate token yet, so the starting task stands in for the turn.
+ """
+
+ if handle.runtime_turn_key and handle.runtime_turn_token:
+ agent_service = getattr(self.controller, "agent_service", None)
+ is_current = getattr(agent_service, "runtime_turn_is_current", None)
+ if not callable(is_current):
+ return True
+ return bool(is_current(handle.runtime_turn_key, handle.runtime_turn_token))
+ owner = handle.owner_task
+ return owner is None or not owner.done()
+
+ async def _typing_keepalive_loop(self, handle: ProcessingIndicatorHandle) -> None:
+ context = handle.context
im_client = self._get_im_client(context)
- try:
- while True:
- await asyncio.sleep(5)
- ok = await im_client.send_typing_indicator(context)
- if not ok:
- logger.debug("Typing keepalive not applied for %s", context.user_id)
- except asyncio.CancelledError:
- raise
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + TYPING_KEEPALIVE_MAX_SECONDS
+ failures = 0
+ while True:
+ await asyncio.sleep(TYPING_KEEPALIVE_INTERVAL_SECONDS)
+ if not self._typing_turn_is_current(handle):
+ logger.debug("Typing keepalive stopped: turn ended for %s", context.channel_id)
+ break
+ if loop.time() >= deadline:
+ logger.warning(
+ "Typing keepalive reached its %ss cap for %s channel=%s thread=%s; stopping",
+ TYPING_KEEPALIVE_MAX_SECONDS,
+ context.platform or "unknown",
+ context.channel_id,
+ context.thread_id,
+ )
+ break
+ try:
+ ok = bool(await im_client.send_typing_indicator(context))
+ except Exception as err:
+ logger.debug("Typing keepalive send failed: %s", err)
+ ok = False
+ if ok:
+ failures = 0
+ continue
+ failures += 1
+ if failures >= TYPING_KEEPALIVE_MAX_FAILURES:
+ logger.info(
+ "Typing keepalive stopped after %d failed sends for %s channel=%s thread=%s",
+ failures,
+ context.platform or "unknown",
+ context.channel_id,
+ context.thread_id,
+ )
+ break
+ if handle.typing_indicator_active and self._should_clear_typing_indicator(handle):
+ # Platforms whose typing state persists until cancelled would keep
+ # showing it after the loop stops on its own.
+ try:
+ await im_client.clear_typing_indicator(context)
+ except Exception as err:
+ logger.debug("Failed to clear typing indicator: %s", err)
def _admission_ack_registry(self) -> dict[str, str]:
registry = getattr(self, "_admission_acks", None)
@@ -515,7 +593,8 @@ class ProcessingIndicatorService:
return False
handle.typing_indicator_active = True
- handle.typing_indicator_task = asyncio.create_task(self._typing_keepalive_loop(context))
+ handle.owner_task = handle.owner_task or asyncio.current_task()
+ handle.typing_indicator_task = asyncio.create_task(self._typing_keepalive_loop(handle))
return True
async def _start_reaction_indicator(
@@ -724,8 +803,21 @@ class ProcessingIndicatorService:
Backends still clean up explicitly with their request object. This registry
is the outbound terminal fallback: a result emit can recover the original
handle by turn token even when a backend terminal branch lost the request.
+
+ This is also the hand-off: from here the runtime turn, not the task that
+ started the indicator, owns its cleanup, and the typing keepalive follows
+ that turn's gate.
"""
+ handle = request_or_handle
+ if not isinstance(handle, ProcessingIndicatorHandle):
+ handle = getattr(request_or_handle, "processing_indicator", None)
+ payload = context.platform_specific or {}
+ runtime_key = str(payload.get("agent_runtime_turn_key") or "").strip()
+ runtime_token = str(payload.get("agent_runtime_turn_token") or "").strip()
+ if isinstance(handle, ProcessingIndicatorHandle) and runtime_key and runtime_token:
+ handle.runtime_turn_key = runtime_key
+ handle.runtime_turn_token = runtime_token
for token in self._turn_tokens(context):
self._indicators_by_turn_token[token] = request_or_handle
@@ -853,8 +945,7 @@ class ProcessingIndicatorService:
request = request_or_handle
handle = self.handle_from_request(request)
- await self._delete_ack_message_for_handle(handle, request=request)
-
+ # Stop typing before any cleanup call that can hang on the network.
typing_task = handle.typing_indicator_task
if typing_task is not None:
typing_task.cancel()
@@ -869,6 +960,8 @@ class ProcessingIndicatorService:
if request is not None:
request.typing_indicator_task = None
+ await self._delete_ack_message_for_handle(handle, request=request)
+
if handle.typing_indicator_active and self._should_clear_typing_indicator(handle):
try:
await self._get_im_client(handle.context).clear_typing_indicator(handle.context)
diff --git a/modules/agents/service.py b/modules/agents/service.py
index ad4f8c14c..2f1ab5c55 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -288,20 +288,10 @@ class AgentService:
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)
+ # CancelledError handler never runs. The turn was never handed off, so
+ # this path still owns the indicator: let the queued-reaction task
+ # settle, then finish the 👌 and any eager typing so neither leaks.
+ await self._finish_unhanded_indicator(indicator, request, queued_reaction_task)
raise
# A restart may have started while this turn waited behind the previous
# owner of the runtime key. Keep the key lock, wait for cutover, then
@@ -311,16 +301,7 @@ class AgentService:
await self.wait_backend_ready(agent_name)
agent = self.get(agent_name)
except BaseException:
- if queued_reaction_task is not None:
- try:
- await queued_reaction_task
- except BaseException:
- pass
- if indicator is not None:
- try:
- await indicator.finish(request)
- except Exception:
- logger.debug("Failed to clean up queued reaction on restart-wait cancel", exc_info=True)
+ await self._finish_unhanded_indicator(indicator, request, queued_reaction_task)
if gate.lock.locked() and not gate.token:
gate.lock.release()
raise
@@ -1156,6 +1137,9 @@ class AgentService:
runtime_token = str(payload.get(AGENT_RUNTIME_TURN_TOKEN) or "").strip()
if not runtime_key or not runtime_token:
return True
+ return self.runtime_turn_is_current(runtime_key, runtime_token)
+
+ def runtime_turn_is_current(self, runtime_key: str, runtime_token: str) -> bool:
gate = self._turn_gates.get(runtime_key)
return gate is not None and gate.token == runtime_token
@@ -1294,6 +1278,30 @@ class AgentService:
except Exception:
logger.debug("harness prompt echo failed at turn start", exc_info=True)
+ @staticmethod
+ async def _finish_unhanded_indicator(
+ indicator: Any,
+ request: AgentRequest,
+ queued_reaction_task: Optional[asyncio.Task],
+ ) -> None:
+ """Finish an indicator whose turn exited before hand-off to its gate."""
+
+ if queued_reaction_task is not None:
+ try:
+ await queued_reaction_task
+ except BaseException:
+ pass
+ elif getattr(request, "processing_indicator", None) is None:
+ return
+ if indicator is None:
+ return
+ try:
+ # Pass the request (not the handle) so finish() clears BOTH the
+ # handle and the flat request.ack_reaction_* / typing fields.
+ await indicator.finish(request)
+ except Exception:
+ logger.debug("Failed to finish processing indicator before hand-off", exc_info=True)
+
def _track_processing_indicator_turn(self, request: AgentRequest) -> None:
handle = getattr(request, "processing_indicator", None)
if handle is None:
diff --git a/modules/im/discord.py b/modules/im/discord.py
index e83d1ec23..c6f02548a 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -462,7 +462,19 @@ class DiscordBot(BaseIMClient):
return message.channel
return None
- async def _resolve_target(self, context: MessageContext) -> Optional[discord.abc.Messageable]:
+ async def _resolve_target(
+ self,
+ context: MessageContext,
+ *,
+ thread_strict: bool = False,
+ ) -> Optional[discord.abc.Messageable]:
+ """Resolve the channel a context addresses.
+
+ ``thread_strict`` is for typing and reactions: they describe the thread's
+ turn, so an unresolvable thread (deleted, no access) yields None instead
+ of surfacing them in the parent channel.
+ """
+
direct_channel = self._get_context_channel(context)
if isinstance(direct_channel, discord.Thread):
return direct_channel
@@ -471,6 +483,8 @@ class DiscordBot(BaseIMClient):
target = await self._fetch_channel(context.thread_id)
if isinstance(target, discord.Thread):
return target
+ if thread_strict:
+ return None
if direct_channel is not None:
return direct_channel
@@ -702,9 +716,35 @@ class DiscordBot(BaseIMClient):
async def answer_callback(self, callback_id: str, text: Optional[str] = None, show_alert: bool = False) -> bool:
return True
+ async def _resolve_reaction_target(
+ self,
+ context: MessageContext,
+ message_id: str,
+ ) -> Optional[discord.abc.Messageable]:
+ # A reaction goes on the message where it was posted, which is not the
+ # turn's thread when that thread was opened from it or from the message
+ # it replies to.
+ payload = context.platform_specific or {}
+ message = payload.get("message") if isinstance(payload, dict) else None
+ if message is not None and str(getattr(message, "id", "")) == str(message_id):
+ channel = getattr(message, "channel", None)
+ if channel is not None:
+ return channel
+ target = await self._resolve_target(context, thread_strict=True)
+ if isinstance(target, discord.Thread) and str(target.id) == str(message_id):
+ # A thread started from a message shares that message's id, and the
+ # message itself lives in the parent channel. Forum posts keep their
+ # starter inside the thread, so only a text parent is used.
+ parent = target.parent
+ if parent is None and target.parent_id:
+ parent = await self._fetch_channel(str(target.parent_id))
+ if isinstance(parent, discord.TextChannel):
+ return parent
+ return target
+
async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
async def _impl() -> bool:
- target = await self._resolve_target(context)
+ target = await self._resolve_reaction_target(context, message_id)
if target is None:
return False
try:
@@ -722,7 +762,7 @@ class DiscordBot(BaseIMClient):
async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
async def _impl() -> bool:
- target = await self._resolve_target(context)
+ target = await self._resolve_reaction_target(context, message_id)
if target is None:
return False
try:
@@ -758,7 +798,7 @@ class DiscordBot(BaseIMClient):
async def send_typing_indicator(self, context: MessageContext) -> bool:
async def _impl() -> bool:
- target = await self._resolve_target(context)
+ target = await self._resolve_target(context, thread_strict=True)
if target is None:
return False
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index 832d5c8e1..b698f54d2 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -944,6 +944,163 @@ def test_real_indicator_shows_queued_reaction_on_second_message_while_first_hold
asyncio.run(_run())
+class _TypingReactionIM(_ReactionIM):
+ """Accepts every typing send, so only the turn can end the keepalive."""
+
+ async def send_typing_indicator(self, _context):
+ return True
+
+ async def clear_typing_indicator(self, _context):
+ return True
+
+
+async def _until(predicate) -> None:
+ for _ in range(200):
+ if predicate():
+ return
+ await asyncio.sleep(0)
+ raise AssertionError("condition never held")
+
+
+def _spawn_typing_turn(service, controller, message: str, message_id: str):
+ """Start a turn as MessageHandler does: eager typing, then the runtime gate,
+ both in the turn's own task, which has not run yet on return."""
+
+ request = _reaction_request(message, message_id)
+ request.context.thread_id = None
+
+ async def _turn():
+ await controller.processing_indicator._start_typing_indicator(request.processing_indicator)
+ controller.processing_indicator.apply_to_request(request, request.processing_indicator)
+ await service.handle_message("claude", request)
+
+ return request, asyncio.create_task(_turn())
+
+
+async def _start_typing_turn(service, controller, message: str, message_id: str):
+ """Spawn a typing turn and return the request, the turn and its keepalive."""
+
+ request, turn = _spawn_typing_turn(service, controller, message, message_id)
+ await _until(lambda: request.processing_indicator.typing_indicator_task is not None)
+ return request, turn, request.processing_indicator.typing_indicator_task
+
+
+async def _cancel(task) -> None:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
[email protected]("queued", [False, True], ids=["uncontended", "queued-reaction"])
+def test_cancel_while_waiting_for_backend_finishes_unhanded_typing(queued) -> None:
+ """#2164: a turn cancelled in wait_backend_ready was never handed off, so it
+ must finish its own indicator. On 74569ae0f only the queued case did."""
+
+ async def _run():
+ im = _TypingReactionIM()
+ controller = _RealIndicatorController(im)
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ release_first = asyncio.Event()
+ service.register(_RuntimeAgent(release_first))
+ first = None
+ if queued:
+ first, first_turn, _ = await _start_typing_turn(service, controller, "first", "m1")
+ await _until(lambda: service._turn_gates["session:/repo"].token)
+ service.begin_backend_drain("claude")
+
+ request, turn, typing_task = await _start_typing_turn(service, controller, "second", "m2")
+ gate = service._turn_gates["session:/repo"]
+ if queued:
+ await _until(lambda: ("add", "m2", "👌") in im.events)
+ service.release_runtime_turn(first.context)
+ await _until(lambda: gate.lock.locked() and not gate.token)
+
+ await _cancel(turn)
+
+ assert typing_task.done()
+ assert request.typing_indicator_task is None
+ if queued:
+ assert ("remove", "m2", "👌") in im.events
+ release_first.set()
+ await asyncio.wait_for(first_turn, timeout=3)
+
+ asyncio.run(_run())
+
+
+def test_cancel_while_acquiring_a_just_released_gate_finishes_typing() -> None:
+ """#2164: a released lock with a waker still pending reports unlocked, so
+ the next turn creates no queued reaction yet still blocks in acquire(). On
+ 74569ae0f that path finished only a queued reaction."""
+
+ async def _run():
+ im = _TypingReactionIM()
+ controller = _RealIndicatorController(im)
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ release_first = asyncio.Event()
+ service.register(_RuntimeAgent(release_first))
+ first, first_turn, _ = await _start_typing_turn(service, controller, "first", "m1")
+ await _until(lambda: service._turn_gates["session:/repo"].token)
+ second, second_turn, _ = await _start_typing_turn(service, controller, "second", "m2")
+ gate = service._turn_gates["session:/repo"]
+ await _until(lambda: ("add", "m2", "👌") in im.events)
+
+ # The third turn is scheduled before the first releases the gate, so it
+ # runs before the woken second turn takes the lock: it sees an unlocked
+ # gate, creates no queued reaction, and still waits behind the second.
+ third, third_turn = _spawn_typing_turn(service, controller, "third", "m3")
+ service.release_runtime_turn(first.context)
+ await _until(lambda: second.context.platform_specific.get("agent_runtime_turn_token"))
+ typing_task = third.processing_indicator.typing_indicator_task
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert not third_turn.done()
+ assert ("add", "m3", "👌") not in im.events
+
+ await _cancel(third_turn)
+
+ assert typing_task.done()
+ service.release_runtime_turn(second.context)
+ release_first.set()
+ await asyncio.wait_for(asyncio.gather(first_turn, second_turn), timeout=3)
+
+ asyncio.run(_run())
+
+
+def test_released_gate_ends_the_handed_off_typing_keepalive_within_one_tick() -> None:
+ """After hand-off the gate token decides whether the turn is current: a
+ release that never reached the indicator (a dropped stale emit, a backend
+ refresh) still stops typing while the turn's task keeps running."""
+
+ async def _run():
+ im = _TypingReactionIM()
+ controller = _RealIndicatorController(im)
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ release_first = asyncio.Event()
+ agent = _RuntimeAgent(release_first)
+ service.register(agent)
+ with patch("core.processing_indicator.TYPING_KEEPALIVE_INTERVAL_SECONDS", 0):
+ request, turn, typing_task = await _start_typing_turn(service, controller, "first", "m1")
+ await _until(lambda: agent.started == ["first"])
+ for _ in range(5):
+ await asyncio.sleep(0)
+ assert request.processing_indicator.handed_off
+ assert not typing_task.done()
+
+ service.release_runtime_turn(request.context)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ assert typing_task.done()
+ assert not turn.done()
+ release_first.set()
+ await asyncio.wait_for(turn, timeout=3)
+
+ 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
diff --git a/tests/test_discord_indicator_target.py b/tests/test_discord_indicator_target.py
new file mode 100644
index 000000000..511704a3b
--- /dev/null
+++ b/tests/test_discord_indicator_target.py
@@ -0,0 +1,164 @@
+"""Where Discord puts a turn's typing indicator and its 👌/👀 reactions.
+
+Typing and reactions describe one turn in one thread, so an unresolvable thread
+(deleted, no access) yields nothing instead of surfacing them in the parent
+channel. A reaction goes on the message where it was posted: a thread opened
+from a message shares that message's id, and the message lives in the parent.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import modules.im.discord as discord_module
+from modules.im import MessageContext
+from modules.im.discord import DiscordBot
+
+
+class _Message:
+ def __init__(self, channel, message_id):
+ self.channel = channel
+ self.id = message_id
+
+ async def add_reaction(self, emoji):
+ self.channel.calls.append(("add", self.id, emoji))
+
+ async def remove_reaction(self, emoji, _user):
+ self.channel.calls.append(("remove", self.id, emoji))
+
+
+class _Channel:
+ def __init__(self, channel_id, *, messages=()):
+ self.id = channel_id
+ self.messages = {str(message_id) for message_id in messages}
+ self.calls: list[tuple] = []
+
+ async def typing(self):
+ self.calls.append(("typing",))
+
+ async def fetch_message(self, message_id):
+ if str(message_id) not in self.messages:
+ raise LookupError(f"Unknown Message {message_id} in {self.id}")
+ return _Message(self, str(message_id))
+
+
+class _TextChannel(_Channel):
+ pass
+
+
+class _ForumChannel(_Channel):
+ pass
+
+
+class _Thread(_Channel):
+ def __init__(self, thread_id, *, parent, messages=(), cached_parent=True):
+ super().__init__(thread_id, messages=messages)
+ self.parent = parent if cached_parent else None
+ self.parent_id = parent.id
+
+
+def _bot(channels):
+ bot = object.__new__(DiscordBot)
+ bot._loop = None
+ bot.client = SimpleNamespace(user=SimpleNamespace(id=42))
+
+ async def _fetch_channel(channel_id):
+ return channels.get(str(channel_id))
+
+ bot._fetch_channel = _fetch_channel
+ return bot
+
+
+def _context(*, thread_id, message_id, message=None):
+ return MessageContext(
+ user_id="U1",
+ channel_id="100",
+ platform="discord",
+ thread_id=thread_id,
+ message_id=message_id,
+ platform_specific={"message": message} if message is not None else {},
+ )
+
+
+class DiscordIndicatorTargetTests(unittest.IsolatedAsyncioTestCase):
+ def setUp(self):
+ patcher = patch.multiple(
+ discord_module.discord,
+ Thread=_Thread,
+ TextChannel=_TextChannel,
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ async def test_unresolvable_thread_gives_no_typing_or_reaction_in_parent(self):
+ # The thread was deleted after the turn started; its id no longer
+ # resolves, but the parent channel does and holds a message of that id.
+ parent = _TextChannel("100", messages=["555", "200"])
+ bot = _bot({"100": parent})
+ for message_id in ("555", "200"):
+ with self.subTest(message_id=message_id):
+ context = _context(thread_id="555", message_id=message_id)
+
+ self.assertFalse(await bot.send_typing_indicator(context))
+ self.assertFalse(await bot.add_reaction(context, message_id, "👌"))
+ self.assertFalse(await bot.add_reaction(context, message_id, "👀"))
+ self.assertFalse(await bot.remove_reaction(context, message_id, "👀"))
+ self.assertEqual(parent.calls, [])
+
+ async def test_starter_message_reaction_is_applied_through_its_text_parent(self):
+ # A restored or re-dispatched context has no live message object; the
+ # starter is identified by sharing the thread's id.
+ for cached_parent in (True, False):
+ with self.subTest(cached_parent=cached_parent):
+ parent = _TextChannel("100", messages=["555"])
+ thread = _Thread("555", parent=parent, cached_parent=cached_parent)
+ bot = _bot({"100": parent, "555": thread})
+ context = _context(thread_id="555", message_id="555")
+
+ self.assertTrue(await bot.add_reaction(context, "555", "👌"))
+ self.assertTrue(await bot.remove_reaction(context, "555", "👌"))
+ self.assertTrue(await bot.add_reaction(context, "555", "👀"))
+ self.assertTrue(await bot.remove_reaction(context, "555", "👀"))
+
+ self.assertEqual(
+ parent.calls,
+ [("add", "555", "👌"), ("remove", "555", "👌"), ("add", "555", "👀"), ("remove", "555", "👀")],
+ )
+ self.assertEqual(thread.calls, [])
+ # Typing still belongs to the thread the turn replies in.
+ self.assertTrue(await bot.send_typing_indicator(context))
+ self.assertEqual(thread.calls, [("typing",)])
+
+ async def test_forum_starter_reaction_stays_in_its_thread(self):
+ forum = _ForumChannel("100")
+ thread = _Thread("555", parent=forum, messages=["555"])
+ bot = _bot({"100": forum, "555": thread})
+ context = _context(thread_id="555", message_id="555")
+
+ self.assertTrue(await bot.add_reaction(context, "555", "👀"))
+ self.assertEqual(thread.calls, [("add", "555", "👀")])
+ self.assertEqual(forum.calls, [])
+
+ async def test_live_message_reaction_uses_the_channel_it_was_posted_in(self):
+ # A channel reply to an anchor runs in the anchor's thread, but the
+ # user's own message stays in the channel.
+ parent = _TextChannel("100", messages=["999"])
+ thread = _Thread("555", parent=parent)
+ bot = _bot({"100": parent, "555": thread})
+ message = SimpleNamespace(id=999, channel=parent)
+ context = _context(thread_id="555", message_id="999", message=message)
+
+ self.assertTrue(await bot.add_reaction(context, "999", "👀"))
+ self.assertTrue(await bot.remove_reaction(context, "999", "👀"))
+ self.assertEqual(parent.calls, [("add", "999", "👀"), ("remove", "999", "👀")])
+ self.assertEqual(thread.calls, [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 6c72fcf6b..1b7f3c529 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -965,6 +965,80 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(captured_requests[0].typing_indicator_task)
self.assertEqual(controller.im_client.sent_messages, [("wx-chat", "Error: agent failed")])
+ def _capture_typing_tasks(self, controller):
+ tasks = []
+ start = controller.processing_indicator.start
+
+ async def _start(*args, **kwargs):
+ handle = await start(*args, **kwargs)
+ tasks.append(handle.typing_indicator_task)
+ return handle
+
+ controller.processing_indicator.start = _start
+ return tasks
+
+ async def test_cancel_before_dispatch_finishes_eager_typing(self):
+ # #2164: cancellation is a BaseException, so the turn's `except Exception`
+ # cleanup never ran and the keepalive typed until the process exited.
+ controller = _StubController(platform="slack", ack_mode="typing", typing_result=True)
+ typing_tasks = self._capture_typing_tasks(controller)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_StubSessionHandler())
+ blocked = asyncio.Event()
+
+ async def _prepare_input_metadata(*_args, **_kwargs):
+ blocked.set()
+ await asyncio.Event().wait()
+
+ handler.prepare_input_metadata = _prepare_input_metadata
+ context = MessageContext(user_id="U1", channel_id="C1", message_id="m1")
+ turn = asyncio.create_task(handler.handle_user_message(context, "hello"))
+ await asyncio.wait_for(blocked.wait(), timeout=1)
+ self.assertFalse(typing_tasks[0].done())
+
+ turn.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await turn
+
+ self.assertTrue(typing_tasks[0].done())
+ self.assertEqual(controller.agent_service.requests, [])
+
+ async def test_cancel_after_hand_off_leaves_the_indicator_to_the_turn(self):
+ # Once the runtime turn tracks the indicator it owns the cleanup, including
+ # the ⏹️/⚠️ receipt; finishing it here on cancel would pre-empt that.
+ controller = _StubController(platform="slack", ack_mode="typing", typing_result=True)
+ typing_tasks = self._capture_typing_tasks(controller)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_StubSessionHandler())
+ tracked = asyncio.Event()
+ captured = []
+
+ async def _handle_message(_agent_name, request):
+ request.context.platform_specific = {
+ **(request.context.platform_specific or {}),
+ "agent_runtime_turn_key": "session:/tmp",
+ "agent_runtime_turn_token": "turn-1",
+ }
+ controller.processing_indicator.track_turn(request.context, request)
+ captured.append(request)
+ tracked.set()
+ await asyncio.Event().wait()
+
+ controller.agent_service.handle_message = _handle_message
+ context = MessageContext(user_id="U1", channel_id="C1", message_id="m1")
+ turn = asyncio.create_task(handler.handle_user_message(context, "hello"))
+ await asyncio.wait_for(tracked.wait(), timeout=1)
+
+ turn.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await turn
+
+ try:
+ self.assertFalse(typing_tasks[0].done())
+ self.assertIs(captured[0].processing_indicator.typing_indicator_task, typing_tasks[0])
+ finally:
+ await controller.processing_indicator.finish(captured[0])
+
async def test_telegram_reaction_mode_matches_global_ack_strategy(self):
controller = _StubController(platform="telegram", ack_mode="reaction", typing_result=True)
handler = MessageHandler(controller)
diff --git a/tests/test_typing_keepalive.py b/tests/test_typing_keepalive.py
new file mode 100644
index 000000000..23f654faa
--- /dev/null
+++ b/tests/test_typing_keepalive.py
@@ -0,0 +1,151 @@
+"""The typing keepalive ends on its own when its turn does (#2164).
+
+"<bot> is typing…" claims a turn is working on this conversation now. Every exit
+path should finish the indicator, but the loop must not depend on that: each
+tick re-checks that its turn is still current, a hard cap backs that up, and a
+target that keeps rejecting sends ends the loop. The interval is patched to zero
+so a tick is one event-loop turn instead of five seconds.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import core.processing_indicator as indicator_module
+from core.processing_indicator import ProcessingIndicatorHandle, ProcessingIndicatorService
+from modules.im import MessageContext
+
+
+class _TypingIM:
+ def __init__(self, results=None):
+ # One entry per send after the first; True/False or an exception.
+ self.results = list(results or [])
+ self.typing_calls = 0
+ self.clear_calls = 0
+
+ async def send_typing_indicator(self, _context):
+ self.typing_calls += 1
+ if self.typing_calls == 1 or not self.results:
+ return True
+ result = self.results.pop(0)
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ async def clear_typing_indicator(self, _context):
+ self.clear_calls += 1
+ return True
+
+
+def _service(im):
+ controller = SimpleNamespace(
+ config=SimpleNamespace(ack_mode="typing", language="en"),
+ get_im_client_for_context=lambda _ctx: im,
+ im_client=im,
+ )
+ return ProcessingIndicatorService(controller)
+
+
+def _handle(platform="slack"):
+ context = MessageContext(user_id="U1", channel_id="C1", thread_id="T1", message_id="m1", platform=platform)
+ return ProcessingIndicatorHandle(context=context)
+
+
+class TypingKeepaliveBoundTests(unittest.IsolatedAsyncioTestCase):
+ def setUp(self):
+ patcher = patch.object(indicator_module, "TYPING_KEEPALIVE_INTERVAL_SECONDS", 0)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ async def _typing_after(self, svc, handle, owner_body):
+ """Start typing inside an owner task (as the turn does) and return both."""
+
+ started = asyncio.Event()
+
+ async def _owner():
+ await svc._start_typing_indicator(handle)
+ started.set()
+ await owner_body()
+
+ owner = asyncio.create_task(_owner())
+ await started.wait()
+ return owner, handle.typing_indicator_task
+
+ async def test_loop_ends_within_one_tick_once_its_unhanded_owner_is_gone(self):
+ # Pre-tracking window: no runtime gate token exists yet, so the task that
+ # started the indicator is the turn. It exits without finishing it.
+ for platform, clears in (("slack", 0), ("wechat", 1)):
+ with self.subTest(platform=platform):
+ im = _TypingIM()
+ svc = _service(im)
+ handle = _handle(platform)
+ release = asyncio.Event()
+ owner, typing_task = await self._typing_after(svc, handle, release.wait)
+ for _ in range(5):
+ await asyncio.sleep(0)
+ self.assertFalse(typing_task.done())
+ self.assertGreater(im.typing_calls, 1)
+
+ release.set()
+ await owner
+ sends_at_turn_end = im.typing_calls
+ await asyncio.wait_for(typing_task, timeout=1)
+
+ self.assertEqual(im.typing_calls, sends_at_turn_end)
+ # A platform whose typing persists until cancelled is cleared.
+ self.assertEqual(im.clear_calls, clears)
+
+ async def test_hard_cap_ends_a_loop_whose_turn_is_still_current(self):
+ im = _TypingIM()
+ svc = _service(im)
+ handle = _handle()
+ forever = asyncio.Event()
+ with patch.object(indicator_module, "TYPING_KEEPALIVE_MAX_SECONDS", 0):
+ with self.assertLogs("core.processing_indicator", level="WARNING") as logs:
+ owner, typing_task = await self._typing_after(svc, handle, forever.wait)
+ await asyncio.wait_for(typing_task, timeout=1)
+ try:
+ self.assertFalse(owner.done())
+ self.assertEqual(im.typing_calls, 1)
+ self.assertTrue(any("cap" in line for line in logs.output), logs.output)
+ finally:
+ owner.cancel()
+ await asyncio.gather(owner, return_exceptions=True)
+
+ async def test_consecutive_failed_sends_end_the_loop_with_one_info_log(self):
+ cases = {
+ # A success in between resets the count: calls are the start send,
+ # then F, F, T, F, F, F.
+ "rejected": ([False, False, True, False, False, False], 7),
+ "raising": ([RuntimeError("404 Unknown Channel")] * 3, 4),
+ }
+ for name, (results, expected_calls) in cases.items():
+ with self.subTest(name):
+ im = _TypingIM(results)
+ svc = _service(im)
+ handle = _handle()
+ forever = asyncio.Event()
+ with self.assertLogs("core.processing_indicator", level="INFO") as logs:
+ owner, typing_task = await self._typing_after(svc, handle, forever.wait)
+ await asyncio.wait_for(typing_task, timeout=1)
+ try:
+ self.assertFalse(owner.done())
+ self.assertEqual(im.typing_calls, expected_calls)
+ stops = [record for record in logs.records if "failed sends" in record.getMessage()]
+ self.assertEqual(len(stops), 1, logs.output)
+ self.assertEqual(stops[0].levelname, "INFO")
+ self.assertIn("channel=C1 thread=T1", stops[0].getMessage())
+ finally:
+ owner.cancel()
+ await asyncio.gather(owner, return_exceptions=True)
+
+
+if __name__ == "__main__":
+ unittest.main()