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.

refactor(core): centralize processing indicators

cyh563bed5e69ad
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index e0b764487..e8819b355 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -29,6 +29,7 @@ class ActivePollInfo:
# Typing indicator info for cleanup on restore
typing_indicator_active: bool = False
context_token: str = ""
+ processing_indicator: Dict[str, Any] = field(default_factory=dict)
# User identity for restoring question UI context
user_id: str = ""
platform: str = ""
@@ -49,12 +50,25 @@ class ActivePollInfo:
"ack_reaction_emoji": self.ack_reaction_emoji,
"typing_indicator_active": self.typing_indicator_active,
"context_token": self.context_token,
+ "processing_indicator": self.processing_indicator,
"user_id": self.user_id,
"platform": self.platform,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ActivePollInfo":
+ processing_indicator = data.get("processing_indicator") or {}
+ if not processing_indicator:
+ processing_indicator = {
+ "platform": data.get("platform", ""),
+ "user_id": data.get("user_id", ""),
+ "channel_id": data.get("channel_id", ""),
+ "thread_id": data.get("thread_id", ""),
+ "context_token": data.get("context_token", ""),
+ "ack_reaction_message_id": data.get("ack_reaction_message_id"),
+ "ack_reaction_emoji": data.get("ack_reaction_emoji"),
+ "typing_indicator_active": bool(data.get("typing_indicator_active", False)),
+ }
return cls(
opencode_session_id=data.get("opencode_session_id", ""),
base_session_id=data.get("base_session_id", ""),
@@ -70,6 +84,7 @@ class ActivePollInfo:
ack_reaction_emoji=data.get("ack_reaction_emoji"),
typing_indicator_active=bool(data.get("typing_indicator_active", False)),
context_token=data.get("context_token", ""),
+ processing_indicator=processing_indicator,
user_id=data.get("user_id", ""),
platform=data.get("platform", ""),
)
diff --git a/core/controller.py b/core/controller.py
index ad1f659c4..8c4c6ea28 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -24,6 +24,7 @@ from core.handlers import (
)
from core.agent_auth_service import AgentAuthService
from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.processing_indicator import ProcessingIndicatorService
from core.scheduled_tasks import ScheduledTaskService
from core.update_checker import UpdateChecker
from core.watches import ManagedWatchService
@@ -105,6 +106,7 @@ class Controller:
self.platform_settings_managers = self.settings_manager.managers
self.sessions = self.settings_manager.sessions
self.native_session_service = None
+ self.processing_indicator = ProcessingIndicatorService(self)
# Migrate legacy per-channel language into global config
self._migrate_language_from_settings()
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index d38242eab..5f87722b5 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -1,6 +1,5 @@
"""Message routing and Agent communication handlers"""
-import asyncio
import logging
from typing import List, Optional, Tuple
@@ -30,72 +29,6 @@ class MessageHandler(BaseHandler):
"""Set reference to session handler"""
self.session_handler = session_handler
- def _get_target_context(self, context: MessageContext) -> MessageContext:
- """Get target context for sending messages"""
- # For Slack, use thread for replies if enabled
- if self._get_im_client(context).should_use_thread_for_reply() and context.thread_id:
- return MessageContext(
- user_id=context.user_id,
- channel_id=context.channel_id,
- platform=context.platform,
- thread_id=context.thread_id,
- message_id=context.message_id,
- platform_specific=context.platform_specific,
- )
- return context
-
- def _get_context_platform(self, context: MessageContext) -> str:
- return (
- context.platform
- or (context.platform_specific or {}).get("platform")
- or getattr(self.config, "platform", "")
- )
-
- def _should_use_typing_ack(self, context: MessageContext) -> bool:
- platform = self._get_context_platform(context)
- if platform == "wechat":
- return True
- return getattr(self.config, "ack_mode", "typing") == "typing"
-
- async def _typing_keepalive_loop(self, context: MessageContext) -> None:
- 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
-
- async def _start_processing_indicator(
- self, context: MessageContext
- ) -> Tuple[Optional[str], Optional[str], bool, Optional[asyncio.Task]]:
- im_client = self._get_im_client(context)
- if self._should_use_typing_ack(context):
- try:
- ok = await im_client.send_typing_indicator(context)
- if ok:
- return None, None, True, asyncio.create_task(self._typing_keepalive_loop(context))
- logger.info("Typing indicator not applied (platform returned False)")
- except Exception as ack_err:
- logger.debug(f"Failed to send typing ack: {ack_err}")
- if self._get_context_platform(context) == "wechat":
- return None, None, False, None
-
- ack_reaction_message_id = None
- ack_reaction_emoji = None
- try:
- if context.message_id:
- ack_reaction_message_id = context.message_id
- ack_reaction_emoji = ":eyes:"
- ok = await im_client.add_reaction(context, ack_reaction_message_id, ack_reaction_emoji)
- if not ok:
- logger.info("Ack reaction not applied (platform returned False)")
- except Exception as ack_err:
- logger.debug(f"Failed to add reaction ack: {ack_err}")
- return ack_reaction_message_id, ack_reaction_emoji, False, None
-
async def handle_user_message(self, context: MessageContext, message: str):
"""Process regular human-originated messages and route to configured agent."""
await self._handle_turn(context, message, source=self.TURN_SOURCE_HUMAN)
@@ -120,10 +53,7 @@ class MessageHandler(BaseHandler):
async def _handle_turn(self, context: MessageContext, message: str, *, source: str) -> Optional[str]:
"""Shared turn-processing pipeline used by both human and scheduled turns."""
- ack_reaction_message_id = None
- ack_reaction_emoji = None
- typing_indicator_active = False
- typing_indicator_task = None
+ processing_indicator = None
try:
is_human = source == self.TURN_SOURCE_HUMAN
control_message = self._get_control_message(context, message) if is_human else message
@@ -292,24 +222,8 @@ class MessageHandler(BaseHandler):
base_session_id = f"{base_session_id}:{routing_agent}"
composite_key = f"{base_session_id}:{working_path}"
- ack_message_id = None
if is_human:
- ack_mode = getattr(self.config, "ack_mode", "typing")
- effective_ack_mode = "typing" if self._get_context_platform(context) == "wechat" else ack_mode
- if effective_ack_mode == "message":
- ack_context = self._get_target_context(context)
- ack_text = self._get_ack_text(agent_name)
- try:
- ack_message_id = await self._get_im_client(ack_context).send_message(ack_context, ack_text)
- except Exception as ack_err:
- logger.debug(f"Failed to send ack message: {ack_err}")
- else:
- (
- ack_reaction_message_id,
- ack_reaction_emoji,
- typing_indicator_active,
- typing_indicator_task,
- ) = await self._start_processing_indicator(context)
+ processing_indicator = await self.controller.processing_indicator.start(context, agent_name)
if is_human and subagent_name and context.message_id:
try:
@@ -349,18 +263,15 @@ class MessageHandler(BaseHandler):
base_session_id=base_session_id,
composite_session_id=composite_key,
session_key=session_key,
- ack_message_id=ack_message_id,
subagent_name=subagent_name,
subagent_key=matched_prefix,
subagent_model=subagent_model,
subagent_reasoning_effort=subagent_reasoning_effort,
- # Reaction info — agent removes :eyes: on result/error
- ack_reaction_message_id=ack_reaction_message_id,
- ack_reaction_emoji=ack_reaction_emoji,
- typing_indicator_active=typing_indicator_active,
- typing_indicator_task=typing_indicator_task,
+ processing_indicator=processing_indicator,
files=processed_files,
)
+ if processing_indicator is not None:
+ self.controller.processing_indicator.apply_to_request(request, processing_indicator)
try:
await self.controller.agent_service.handle_message(agent_name, request)
except KeyError:
@@ -382,22 +293,8 @@ class MessageHandler(BaseHandler):
# clears typing indicators, which do not have a reaction ID.
await self._remove_ack_reaction(context, request) # type: ignore[possibly-undefined]
except NameError:
- # request not defined yet, try using local variables
- if (
- ack_reaction_message_id # type: ignore[possibly-undefined]
- and ack_reaction_emoji # type: ignore[possibly-undefined]
- ):
- await self._get_im_client(context).remove_reaction(
- context, ack_reaction_message_id, ack_reaction_emoji
- )
- if typing_indicator_task: # type: ignore[possibly-undefined]
- typing_indicator_task.cancel()
- try:
- await typing_indicator_task
- except asyncio.CancelledError:
- pass
- if typing_indicator_active: # type: ignore[possibly-undefined]
- await self._get_im_client(context).clear_typing_indicator(context)
+ if processing_indicator is not None:
+ await self.controller.processing_indicator.finish(processing_indicator)
except Exception as cleanup_err:
logger.debug(f"Failed to clean up reaction on error: {cleanup_err}")
await self._get_im_client(context).send_message(
@@ -681,56 +578,11 @@ class MessageHandler(BaseHandler):
async def _delete_ack(self, channel_id: str, request: AgentRequest):
"""Delete acknowledgement message if it still exists."""
- im_client = self._get_im_client(request.context)
- if request.ack_message_id and hasattr(im_client, "delete_message"):
- try:
- await im_client.delete_message(channel_id, request.ack_message_id)
- except Exception as err:
- logger.debug(f"Failed to delete ack message: {err}")
- finally:
- request.ack_message_id = None
+ await self.controller.processing_indicator.delete_ack_message(request, channel_id=channel_id)
async def _remove_ack_reaction(self, context: MessageContext, request: AgentRequest):
"""Remove acknowledgement reaction / typing indicator if it still exists."""
- im_client = self._get_im_client(context)
- typing_task = request.typing_indicator_task
- if typing_task is not None:
- typing_task.cancel()
- try:
- await typing_task
- except asyncio.CancelledError:
- pass
- except Exception as err:
- logger.debug(f"Failed to stop typing keepalive task: {err}")
- finally:
- request.typing_indicator_task = None
-
- if request.typing_indicator_active:
- try:
- await im_client.clear_typing_indicator(context)
- except Exception as err:
- logger.debug(f"Failed to clear typing ack: {err}")
- finally:
- request.typing_indicator_active = False
-
- if request.ack_reaction_message_id and request.ack_reaction_emoji:
- try:
- await im_client.remove_reaction(
- context,
- request.ack_reaction_message_id,
- request.ack_reaction_emoji,
- )
- except Exception as err:
- logger.debug(f"Failed to remove reaction ack: {err}")
- finally:
- request.ack_reaction_message_id = None
- request.ack_reaction_emoji = None
-
- def _get_ack_text(self, agent_name: str) -> str:
- """Unified acknowledgement text before agent processing."""
- label = agent_name or self.controller.agent_service.default_agent
- agent_label = label.capitalize() if label else ""
- return f"📨 {self._t('message.ack', agent=agent_label)}"
+ await self.controller.processing_indicator.finish(request)
async def _process_file_attachments(
self, context: MessageContext, working_path: str
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
new file mode 100644
index 000000000..11615e916
--- /dev/null
+++ b/core/processing_indicator.py
@@ -0,0 +1,300 @@
+"""Processing indicator lifecycle management.
+
+This module owns the short-lived UI state shown while a user turn is being
+processed: acknowledgement messages, acknowledgement reactions, and typing
+indicators. Agent implementations should not know platform-specific cleanup
+details; they should only ask this service to delete or finish an indicator.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from dataclasses import dataclass
+from typing import Any, Optional
+
+from modules.im import MessageContext
+from vibe.i18n import t as i18n_t
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class ProcessingIndicatorHandle:
+ """Runtime handle for a processing indicator."""
+
+ context: MessageContext
+ ack_message_id: Optional[str] = None
+ ack_message_channel_id: Optional[str] = None
+ ack_reaction_message_id: Optional[str] = None
+ ack_reaction_emoji: Optional[str] = None
+ typing_indicator_active: bool = False
+ typing_indicator_task: Optional[asyncio.Task] = None
+
+ def to_snapshot(self) -> dict[str, Any]:
+ payload = self.context.platform_specific or {}
+ return {
+ "platform": self.context.platform or payload.get("platform") or "",
+ "user_id": self.context.user_id or "",
+ "channel_id": self.context.channel_id or "",
+ "thread_id": self.context.thread_id or "",
+ "message_id": self.context.message_id or "",
+ "context_token": str(payload.get("context_token") or ""),
+ "ack_message_id": self.ack_message_id,
+ "ack_message_channel_id": self.ack_message_channel_id,
+ "ack_reaction_message_id": self.ack_reaction_message_id,
+ "ack_reaction_emoji": self.ack_reaction_emoji,
+ "typing_indicator_active": self.typing_indicator_active,
+ }
+
+ @classmethod
+ def from_snapshot(cls, data: dict[str, Any]) -> "ProcessingIndicatorHandle":
+ platform = str(data.get("platform") or "")
+ context_token = str(data.get("context_token") or "")
+ platform_specific: dict[str, Any] = {}
+ if platform:
+ platform_specific["platform"] = platform
+ if context_token:
+ platform_specific["context_token"] = context_token
+ context = MessageContext(
+ user_id=str(data.get("user_id") or ""),
+ channel_id=str(data.get("channel_id") or ""),
+ platform=platform or None,
+ thread_id=data.get("thread_id") or None,
+ message_id=data.get("message_id") or None,
+ platform_specific=platform_specific or None,
+ )
+ return cls(
+ context=context,
+ ack_message_id=data.get("ack_message_id") or None,
+ ack_message_channel_id=data.get("ack_message_channel_id") or data.get("channel_id") or None,
+ ack_reaction_message_id=data.get("ack_reaction_message_id") or None,
+ ack_reaction_emoji=data.get("ack_reaction_emoji") or None,
+ typing_indicator_active=bool(data.get("typing_indicator_active", False)),
+ )
+
+
+class ProcessingIndicatorService:
+ """Start and finish processing indicators through one owner."""
+
+ def __init__(self, controller):
+ self.controller = controller
+ self.config = controller.config
+
+ def _get_im_client(self, context: MessageContext):
+ getter = getattr(self.controller, "get_im_client_for_context", None)
+ if callable(getter):
+ return getter(context)
+ return self.controller.im_client
+
+ def _get_context_platform(self, context: MessageContext) -> str:
+ return (
+ context.platform
+ or (context.platform_specific or {}).get("platform")
+ or getattr(self.config, "platform", "")
+ )
+
+ def _should_use_typing_ack(self, context: MessageContext) -> bool:
+ if self._get_context_platform(context) == "wechat":
+ return True
+ return getattr(self.config, "ack_mode", "typing") == "typing"
+
+ def _get_target_context(self, context: MessageContext) -> MessageContext:
+ im_client = self._get_im_client(context)
+ if im_client.should_use_thread_for_reply() and context.thread_id:
+ return MessageContext(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ platform=context.platform,
+ thread_id=context.thread_id,
+ message_id=context.message_id,
+ platform_specific=context.platform_specific,
+ )
+ return context
+
+ def _get_ack_text(self, agent_name: str) -> str:
+ label = agent_name or self.controller.agent_service.default_agent
+ agent_label = label.capitalize() if label else ""
+ 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:
+ 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
+
+ async def start(self, context: MessageContext, agent_name: str, *, enabled: bool = True) -> ProcessingIndicatorHandle:
+ handle = ProcessingIndicatorHandle(context=context)
+ if not enabled:
+ return handle
+
+ im_client = self._get_im_client(context)
+ ack_mode = getattr(self.config, "ack_mode", "typing")
+ effective_ack_mode = "typing" if self._get_context_platform(context) == "wechat" else ack_mode
+
+ if effective_ack_mode == "message":
+ ack_context = self._get_target_context(context)
+ try:
+ handle.ack_message_id = await self._get_im_client(ack_context).send_message(
+ ack_context,
+ self._get_ack_text(agent_name),
+ )
+ handle.ack_message_channel_id = ack_context.channel_id
+ except Exception as ack_err:
+ logger.debug("Failed to send ack message: %s", ack_err)
+ return handle
+
+ if self._should_use_typing_ack(context):
+ try:
+ ok = await im_client.send_typing_indicator(context)
+ if ok:
+ handle.typing_indicator_active = True
+ handle.typing_indicator_task = asyncio.create_task(self._typing_keepalive_loop(context))
+ return handle
+ logger.info("Typing indicator not applied (platform returned False)")
+ except Exception as ack_err:
+ logger.debug("Failed to send typing ack: %s", ack_err)
+ if self._get_context_platform(context) == "wechat":
+ return handle
+
+ try:
+ if context.message_id:
+ handle.ack_reaction_message_id = context.message_id
+ handle.ack_reaction_emoji = ":eyes:"
+ ok = await im_client.add_reaction(
+ context,
+ handle.ack_reaction_message_id,
+ handle.ack_reaction_emoji,
+ )
+ if not ok:
+ logger.info("Ack reaction not applied (platform returned False)")
+ except Exception as ack_err:
+ logger.debug("Failed to add reaction ack: %s", ack_err)
+ return handle
+
+ def apply_to_request(self, request: Any, handle: ProcessingIndicatorHandle) -> None:
+ request.processing_indicator = handle
+ request.ack_message_id = handle.ack_message_id
+ request.ack_reaction_message_id = handle.ack_reaction_message_id
+ request.ack_reaction_emoji = handle.ack_reaction_emoji
+ request.typing_indicator_active = handle.typing_indicator_active
+ request.typing_indicator_task = handle.typing_indicator_task
+
+ def handle_from_request(self, request: Any) -> ProcessingIndicatorHandle:
+ handle = getattr(request, "processing_indicator", None)
+ if isinstance(handle, ProcessingIndicatorHandle):
+ handle.ack_message_id = handle.ack_message_id or getattr(request, "ack_message_id", None)
+ handle.ack_reaction_message_id = handle.ack_reaction_message_id or getattr(
+ request,
+ "ack_reaction_message_id",
+ None,
+ )
+ handle.ack_reaction_emoji = handle.ack_reaction_emoji or getattr(request, "ack_reaction_emoji", None)
+ handle.typing_indicator_active = handle.typing_indicator_active or bool(
+ getattr(request, "typing_indicator_active", False)
+ )
+ handle.typing_indicator_task = handle.typing_indicator_task or getattr(request, "typing_indicator_task", None)
+ return handle
+ return ProcessingIndicatorHandle(
+ context=request.context,
+ ack_message_id=getattr(request, "ack_message_id", None),
+ ack_message_channel_id=getattr(request.context, "channel_id", None),
+ ack_reaction_message_id=getattr(request, "ack_reaction_message_id", None),
+ ack_reaction_emoji=getattr(request, "ack_reaction_emoji", None),
+ typing_indicator_active=bool(getattr(request, "typing_indicator_active", False)),
+ typing_indicator_task=getattr(request, "typing_indicator_task", None),
+ )
+
+ def handle_from_snapshot(self, data: dict[str, Any]) -> ProcessingIndicatorHandle:
+ return ProcessingIndicatorHandle.from_snapshot(data)
+
+ def snapshot_request(self, request: Any) -> dict[str, Any]:
+ return self.handle_from_request(request).to_snapshot()
+
+ async def delete_ack_message(self, request: Any, *, channel_id: Optional[str] = None) -> None:
+ handle = self.handle_from_request(request)
+ await self._delete_ack_message_for_handle(handle, request=request, channel_id=channel_id)
+ if getattr(request, "processing_indicator", None) is None:
+ request.processing_indicator = handle
+
+ async def _delete_ack_message_for_handle(
+ self,
+ handle: ProcessingIndicatorHandle,
+ *,
+ request: Optional[Any] = None,
+ channel_id: Optional[str] = None,
+ ) -> None:
+ ack_id = handle.ack_message_id
+ if ack_id:
+ im_client = self._get_im_client(handle.context)
+ if hasattr(im_client, "delete_message"):
+ try:
+ await im_client.delete_message(
+ channel_id or handle.ack_message_channel_id or handle.context.channel_id,
+ ack_id,
+ )
+ except Exception as err:
+ logger.debug("Could not delete ack message: %s", err)
+ finally:
+ handle.ack_message_id = None
+ if request is not None:
+ request.ack_message_id = None
+
+ async def finish(self, request_or_handle: Any) -> None:
+ if isinstance(request_or_handle, ProcessingIndicatorHandle):
+ handle = request_or_handle
+ request = None
+ else:
+ request = request_or_handle
+ handle = self.handle_from_request(request)
+
+ await self._delete_ack_message_for_handle(handle, request=request)
+
+ typing_task = handle.typing_indicator_task
+ if typing_task is not None:
+ typing_task.cancel()
+ try:
+ await typing_task
+ except asyncio.CancelledError:
+ pass
+ except Exception:
+ logger.debug("Failed to stop typing keepalive task", exc_info=True)
+ finally:
+ handle.typing_indicator_task = None
+ if request is not None:
+ request.typing_indicator_task = None
+
+ if handle.typing_indicator_active:
+ try:
+ await self._get_im_client(handle.context).clear_typing_indicator(handle.context)
+ except Exception as err:
+ logger.debug("Failed to clear typing indicator: %s", err)
+ finally:
+ handle.typing_indicator_active = False
+ if request is not None:
+ request.typing_indicator_active = False
+
+ if handle.ack_reaction_message_id and handle.ack_reaction_emoji:
+ try:
+ await self._get_im_client(handle.context).remove_reaction(
+ handle.context,
+ handle.ack_reaction_message_id,
+ handle.ack_reaction_emoji,
+ )
+ except Exception as err:
+ logger.debug("Failed to remove reaction ack: %s", err)
+ finally:
+ handle.ack_reaction_message_id = None
+ handle.ack_reaction_emoji = None
+ if request is not None:
+ request.ack_reaction_message_id = None
+ request.ack_reaction_emoji = None
+
+ if request is not None and getattr(request, "processing_indicator", None) is None:
+ request.processing_indicator = handle
diff --git a/docs/plans/processing-indicator-lifecycle.md b/docs/plans/processing-indicator-lifecycle.md
new file mode 100644
index 000000000..f7c721ac6
--- /dev/null
+++ b/docs/plans/processing-indicator-lifecycle.md
@@ -0,0 +1,31 @@
+# Processing Indicator Lifecycle
+
+## Problem
+
+Processing indicators were split across layers:
+
+- `MessageHandler` started ack messages, reactions, and typing indicators.
+- `AgentRequest` carried several loosely related mutable fields.
+- Each agent backend decided when to delete or clear those fields.
+- OpenCode persisted active poll state separately for restart recovery.
+
+That made cleanup depend on every backend remembering the same platform-specific
+details. WeChat exposed the flaw because clearing typing requires the original
+conversation context token, and restored OpenCode polls did not own that state.
+
+## Direction
+
+`core.processing_indicator.ProcessingIndicatorService` is the lifecycle owner.
+
+- Start indicators through one service.
+- Store a single handle on `AgentRequest`.
+- Keep legacy request fields in sync for compatibility while callers migrate.
+- Finish and ack-message deletion go through the same service for OpenCode,
+ Codex, Claude, and handler-level errors.
+- Persist a serializable handle snapshot for restored OpenCode polls.
+
+## Follow-Up Boundary
+
+This PR keeps the public request fields as a compatibility layer. A later cleanup
+can remove direct reads of `ack_reaction_message_id`, `typing_indicator_active`,
+and related fields once all tests and helper code use the handle directly.
diff --git a/modules/agents/base.py b/modules/agents/base.py
index af1f1d9ef..a788d766f 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import logging
import time
-import asyncio
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@@ -35,6 +34,7 @@ class AgentRequest:
last_agent_message_parse_mode: Optional[str] = None
started_at: float = field(default_factory=time.monotonic)
# Reaction ack: emoji added to user's message, to be removed when result is sent
+ processing_indicator: Optional[Any] = None
ack_reaction_message_id: Optional[str] = None
ack_reaction_emoji: Optional[str] = None
typing_indicator_active: bool = False
@@ -92,38 +92,7 @@ class BaseAgent(ABC):
should NOT override it. The guard (check-then-clear) is idempotent so
calling it more than once is harmless.
"""
- typing_task = request.typing_indicator_task
- if typing_task is not None:
- typing_task.cancel()
- try:
- await typing_task
- except asyncio.CancelledError:
- pass
- except Exception:
- logger.debug("Failed to stop typing keepalive task", exc_info=True)
- finally:
- request.typing_indicator_task = None
-
- if request.typing_indicator_active:
- try:
- await self._get_im_client(request.context).clear_typing_indicator(request.context)
- except Exception as err:
- logger.debug(f"Failed to clear typing indicator: {err}")
- finally:
- request.typing_indicator_active = False
-
- if request.ack_reaction_message_id and request.ack_reaction_emoji:
- try:
- await self._get_im_client(request.context).remove_reaction(
- request.context,
- request.ack_reaction_message_id,
- request.ack_reaction_emoji,
- )
- except Exception as err:
- logger.debug(f"Failed to remove reaction ack: {err}")
- finally:
- request.ack_reaction_message_id = None
- request.ack_reaction_emoji = None
+ await self.controller.processing_indicator.finish(request)
async def emit_result_message(
self,
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 308110758..c308a4194 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -550,12 +550,16 @@ class ClaudeAgent(BaseAgent):
# inside the loop.
async def _delete_ack(self, context: MessageContext, request: AgentRequest):
+ service = getattr(self.controller, "processing_indicator", None)
+ if service is not None:
+ await service.delete_ack_message(request, channel_id=context.channel_id)
+ return
ack_id = request.ack_message_id
if ack_id and hasattr(self.im_client, "delete_message"):
try:
await self.im_client.delete_message(context.channel_id, ack_id)
except Exception as err:
- logger.debug(f"Could not delete ack message: {err}")
+ logger.debug("Could not delete ack message: %s", err)
finally:
request.ack_message_id = None
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 5e17c0c24..7a0709497 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -725,6 +725,10 @@ class CodexAgent(BaseAgent):
return turn_id
async def _delete_ack(self, request: AgentRequest) -> None:
+ service = getattr(self.controller, "processing_indicator", None)
+ if service is not None:
+ await service.delete_ack_message(request)
+ return
ack_id = request.ack_message_id
if ack_id and hasattr(self.im_client, "delete_message"):
try:
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 34b41c7ff..8864bf718 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -289,6 +289,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
ack_reaction_emoji=request.ack_reaction_emoji,
typing_indicator_active=request.typing_indicator_active,
context_token=str(platform_payload.get("context_token") or ""),
+ processing_indicator=self.controller.processing_indicator.snapshot_request(request),
user_id=request.context.user_id or "",
platform=request.context.platform or platform_payload.get("platform") or "",
)
@@ -421,12 +422,16 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
return terminated
async def _delete_ack(self, request: AgentRequest) -> None:
+ service = getattr(self.controller, "processing_indicator", None)
+ if service is not None:
+ await service.delete_ack_message(request)
+ return
ack_id = request.ack_message_id
if ack_id and hasattr(self.im_client, "delete_message"):
try:
await self.im_client.delete_message(request.context.channel_id, ack_id)
except Exception as err:
- logger.debug(f"Could not delete ack message: {err}")
+ logger.debug("Could not delete ack message: %s", err)
finally:
request.ack_message_id = None
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index 9bc735614..3517b58ba 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -21,25 +21,25 @@ class OpenCodePollLoop:
self._agent = agent
self._question_handler = question_handler
+ def _build_restored_handle(self, poll_info):
+ snapshot = poll_info.processing_indicator or {
+ "platform": poll_info.platform,
+ "user_id": poll_info.user_id,
+ "channel_id": poll_info.channel_id,
+ "thread_id": poll_info.thread_id,
+ "context_token": getattr(poll_info, "context_token", ""),
+ "ack_reaction_message_id": poll_info.ack_reaction_message_id,
+ "ack_reaction_emoji": poll_info.ack_reaction_emoji,
+ "typing_indicator_active": bool(getattr(poll_info, "typing_indicator_active", False)),
+ }
+ return self._agent.controller.processing_indicator.handle_from_snapshot(snapshot)
+
def _build_restored_context(self, poll_info):
- from modules.im import MessageContext
-
- platform_specific: dict[str, Any] = {}
- if poll_info.platform:
- platform_specific["platform"] = poll_info.platform
- if getattr(poll_info, "context_token", ""):
- platform_specific["context_token"] = poll_info.context_token
-
- return MessageContext(
- user_id=poll_info.user_id or "",
- channel_id=poll_info.channel_id,
- platform=poll_info.platform or None,
- thread_id=poll_info.thread_id,
- platform_specific=platform_specific or None,
- )
+ return self._build_restored_handle(poll_info).context
def _build_restored_ack_request(self, poll_info) -> AgentRequest:
- context = self._build_restored_context(poll_info)
+ handle = self._build_restored_handle(poll_info)
+ context = handle.context
session_key = f"{poll_info.platform}::{poll_info.settings_key}" if poll_info.platform else poll_info.settings_key
return AgentRequest(
context=context,
@@ -48,9 +48,11 @@ class OpenCodePollLoop:
base_session_id=poll_info.base_session_id,
composite_session_id=f"{poll_info.base_session_id}:{poll_info.working_path}",
session_key=session_key,
- ack_reaction_message_id=poll_info.ack_reaction_message_id,
- ack_reaction_emoji=poll_info.ack_reaction_emoji,
- typing_indicator_active=bool(getattr(poll_info, "typing_indicator_active", False)),
+ processing_indicator=handle,
+ ack_message_id=handle.ack_message_id,
+ ack_reaction_message_id=handle.ack_reaction_message_id,
+ ack_reaction_emoji=handle.ack_reaction_emoji,
+ typing_indicator_active=handle.typing_indicator_active,
)
async def remove_restored_ack(self, poll_info) -> None:
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index b39f3096c..d0707c1f6 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -334,6 +334,7 @@ class SessionsFacade:
ack_reaction_emoji: Optional[str] = None,
typing_indicator_active: bool = False,
context_token: str = "",
+ processing_indicator: Optional[Dict[str, Any]] = None,
user_id: str = "",
platform: str = "",
) -> None:
@@ -352,6 +353,7 @@ class SessionsFacade:
ack_reaction_emoji=ack_reaction_emoji,
typing_indicator_active=typing_indicator_active,
context_token=context_token,
+ processing_indicator=processing_indicator or {},
user_id=user_id,
platform=platform,
)
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index d3293448c..a701126a6 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -11,6 +11,7 @@ ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from modules.im import MessageContext
+from core.processing_indicator import ProcessingIndicatorService
def _load_message_handler_class():
@@ -31,6 +32,7 @@ def _load_message_handler_class():
subagent_key: str | None = None
subagent_model: str | None = None
subagent_reasoning_effort: str | None = None
+ processing_indicator: object | None = None
ack_reaction_message_id: str | None = None
ack_reaction_emoji: str | None = None
typing_indicator_active: bool = False
@@ -172,6 +174,7 @@ class _StubController:
self.settings_handler = type("Settings", (), {})()
self.command_handler = type("Cmd", (), {"handle_start": staticmethod(lambda context, args: None)})()
self.agent_auth_service = type("Auth", (), {})()
+ self.processing_indicator = ProcessingIndicatorService(self)
def update_thread_message_id(self, context):
return None
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 5d20deb94..cea570721 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -11,6 +11,7 @@ from modules.im.base import BaseIMClient, BaseIMConfig, MessageContext
from modules.im.multi import MultiIMClient
from modules.settings_manager import MultiSettingsManager
from config.v2_sessions import ActivePollInfo
+from core.processing_indicator import ProcessingIndicatorService
from modules.agents.opencode.poll_loop import OpenCodePollLoop
@@ -78,6 +79,10 @@ class _StubClient(BaseIMClient):
return FileDownloadResult(True, target_path)
+ async def clear_typing_indicator(self, context):
+ self.sent.append(("clear_typing", context.platform, context.user_id, (context.platform_specific or {}).get("context_token")))
+ return True
+
def format_markdown(self, text: str) -> str:
return text
@@ -160,6 +165,14 @@ def test_active_poll_info_round_trips_restored_typing_context():
platform="wechat",
typing_indicator_active=True,
context_token="ctx-1",
+ processing_indicator={
+ "platform": "wechat",
+ "user_id": "user-1",
+ "channel_id": "chan-1",
+ "thread_id": "thread-1",
+ "context_token": "ctx-1",
+ "typing_indicator_active": True,
+ },
)
restored = ActivePollInfo.from_dict(poll.to_dict())
@@ -167,14 +180,29 @@ def test_active_poll_info_round_trips_restored_typing_context():
assert restored.platform == "wechat"
assert restored.typing_indicator_active is True
assert restored.context_token == "ctx-1"
+ assert restored.processing_indicator["context_token"] == "ctx-1"
def test_opencode_restored_ack_preserves_wechat_typing_context():
captured = []
+ wechat = _StubClient("wechat")
class _StubAgent:
+ def __init__(self):
+ self.controller = type(
+ "Controller",
+ (),
+ {
+ "config": type("Config", (), {"platform": "wechat", "ack_mode": "typing", "language": "en"})(),
+ "im_client": wechat,
+ "get_im_client_for_context": lambda self, context: wechat,
+ },
+ )()
+ self.controller.processing_indicator = ProcessingIndicatorService(self.controller)
+
async def _remove_ack_reaction(self, request):
captured.append(request)
+ await self.controller.processing_indicator.finish(request)
poll = ActivePollInfo(
opencode_session_id="ses-1",
@@ -187,15 +215,68 @@ def test_opencode_restored_ack_preserves_wechat_typing_context():
platform="wechat",
typing_indicator_active=True,
context_token="ctx-1",
+ processing_indicator={
+ "platform": "wechat",
+ "user_id": "user-1",
+ "channel_id": "chan-1",
+ "thread_id": "thread-1",
+ "context_token": "ctx-1",
+ "typing_indicator_active": True,
+ },
)
loop = OpenCodePollLoop(_StubAgent(), question_handler=None)
asyncio.run(loop.remove_restored_ack(poll))
request = captured[0]
- assert request.typing_indicator_active is True
+ assert request.typing_indicator_active is False
assert request.context.platform == "wechat"
assert request.context.platform_specific == {"platform": "wechat", "context_token": "ctx-1"}
+ assert wechat.sent == [("clear_typing", "wechat", "user-1", "ctx-1")]
+
+
+def test_processing_indicator_handle_is_source_of_truth_for_backend_cleanup():
+ wechat = _StubClient("wechat")
+
+ class _Controller:
+ def __init__(self):
+ self.config = type("Config", (), {"platform": "wechat", "ack_mode": "typing", "language": "en"})()
+ self.im_client = wechat
+ self.settings_manager = type("Settings", (), {})()
+ self.processing_indicator = ProcessingIndicatorService(self)
+
+ def get_im_client_for_context(self, context):
+ return wechat
+
+ controller = _Controller()
+ handle = controller.processing_indicator.handle_from_snapshot(
+ {
+ "platform": "wechat",
+ "user_id": "user-1",
+ "channel_id": "chan-1",
+ "context_token": "ctx-1",
+ "typing_indicator_active": True,
+ }
+ )
+ request = type(
+ "Request",
+ (),
+ {
+ "context": handle.context,
+ "ack_message_id": None,
+ "ack_reaction_message_id": None,
+ "ack_reaction_emoji": None,
+ "typing_indicator_active": False,
+ "typing_indicator_task": None,
+ "processing_indicator": handle,
+ },
+ )()
+
+ asyncio.run(controller.processing_indicator.finish(request))
+
+ assert request.typing_indicator_active is False
+ assert handle.typing_indicator_active is False
+ assert wechat.sent == [("clear_typing", "wechat", "user-1", "ctx-1")]
def test_multi_im_client_routes_download_by_file_info_platform():
diff --git a/tests/test_v2_sessions.py b/tests/test_v2_sessions.py
index f90f2064d..659ae352a 100644
--- a/tests/test_v2_sessions.py
+++ b/tests/test_v2_sessions.py
@@ -151,6 +151,13 @@ def test_active_poll_persists_typing_cleanup_context(tmp_path, monkeypatch):
baseline_message_ids=[],
typing_indicator_active=True,
context_token="ctx-4",
+ processing_indicator={
+ "platform": "wechat",
+ "user_id": "wx-user",
+ "channel_id": "wx-chat",
+ "context_token": "ctx-4",
+ "typing_indicator_active": True,
+ },
user_id="wx-user",
platform="wechat",
)
@@ -162,6 +169,7 @@ def test_active_poll_persists_typing_cleanup_context(tmp_path, monkeypatch):
assert poll is not None
assert poll.typing_indicator_active is True
assert poll.context_token == "ctx-4"
+ assert poll.processing_indicator["context_token"] == "ctx-4"
# --- session_mappings migration tests ---