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): finish processing indicators on terminal results (#600)

Call Whiteab6118af936f
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index f64d63f98..a685c1763 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -127,6 +127,16 @@ class ConsolidatedMessageDispatcher:
if callable(release):
release(context)
+ async def _finish_processing_indicator_turn(self, context: MessageContext) -> None:
+ service = getattr(self.controller, "processing_indicator", None)
+ finish_terminal = getattr(service, "finish_terminal_turn", None)
+ if not callable(finish_terminal):
+ return
+ try:
+ await finish_terminal(context)
+ except Exception:
+ logger.debug("terminal processing-indicator cleanup failed", exc_info=True)
+
def _is_current_runtime_turn(self, context: MessageContext) -> bool:
service = getattr(self.controller, "agent_service", None)
matches = getattr(service, "emit_matches_runtime_turn", None)
@@ -529,6 +539,7 @@ class ConsolidatedMessageDispatcher:
return None
finally:
if canonical_type == "result":
+ await self._finish_processing_indicator_turn(context)
self._release_runtime_turn(context)
# Resolve the delivery target once. Routed / post_to / thread replies
@@ -583,6 +594,7 @@ class ConsolidatedMessageDispatcher:
return message_id
finally:
if canonical_type == "result":
+ await self._finish_processing_indicator_turn(context)
self._release_runtime_turn(context)
if canonical_type == "notify":
@@ -792,6 +804,7 @@ class ConsolidatedMessageDispatcher:
return primary_message_id
finally:
+ await self._finish_processing_indicator_turn(context)
self._release_runtime_turn(context)
if canonical_type not in {"system", "assistant", "toolcall"}:
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index 0bb483c79..1c82cb67a 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -84,6 +84,7 @@ class ProcessingIndicatorService:
def __init__(self, controller):
self.controller = controller
self.config = controller.config
+ self._indicators_by_turn_token: dict[str, Any] = {}
def _get_im_client(self, context: MessageContext):
getter = getattr(self.controller, "get_im_client_for_context", None)
@@ -248,6 +249,42 @@ class ProcessingIndicatorService:
handle.ack_reaction_emoji = ACK_REACTION_EMOJI
return True
+ @staticmethod
+ def _turn_tokens(context: MessageContext) -> set[str]:
+ payload = context.platform_specific or {}
+ tokens = set()
+ for key in ("turn_token", "agent_runtime_turn_token"):
+ token = str(payload.get(key) or "").strip()
+ if token:
+ tokens.add(token)
+ return tokens
+
+ def track_turn(self, context: MessageContext, request_or_handle: Any) -> None:
+ """Remember this turn's indicator for terminal-result cleanup.
+
+ 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.
+ """
+
+ for token in self._turn_tokens(context):
+ self._indicators_by_turn_token[token] = request_or_handle
+
+ def _forget_turn(self, context: MessageContext, handle: ProcessingIndicatorHandle) -> None:
+ for token in self._turn_tokens(context):
+ tracked = self._indicators_by_turn_token.get(token)
+ if tracked is handle or getattr(tracked, "processing_indicator", None) is handle:
+ self._indicators_by_turn_token.pop(token, None)
+
+ async def finish_terminal_turn(self, context: MessageContext) -> None:
+ """Finish the processing indicator for a terminal result emit."""
+
+ for token in self._turn_tokens(context):
+ tracked = self._indicators_by_turn_token.pop(token, None)
+ if tracked is not None:
+ await self.finish(tracked)
+ return
+
def _delete_context(self, handle: ProcessingIndicatorHandle, channel_id: Optional[str]) -> MessageContext:
target_channel_id = channel_id or handle.ack_message_channel_id
if target_channel_id and target_channel_id != handle.context.channel_id:
@@ -379,3 +416,5 @@ class ProcessingIndicatorService:
if request is not None and getattr(request, "processing_indicator", None) is None:
request.processing_indicator = handle
+
+ self._forget_turn(handle.context, handle)
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 3bb9e988e..72dbd3861 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -55,6 +55,7 @@ class AgentService:
manager = getattr(self.controller, "session_turns", None)
if manager is not None:
manager.on_running(request.context)
+ self._track_processing_indicator_turn(request)
await agent.handle_message(request)
except asyncio.CancelledError:
self.release_runtime_turn(request.context)
@@ -210,6 +211,15 @@ class AgentService:
return
request.context.platform_specific[AGENT_TURN_TOKEN] = runtime_token
+ def _track_processing_indicator_turn(self, request: AgentRequest) -> None:
+ handle = getattr(request, "processing_indicator", None)
+ if handle is None:
+ return
+ service = getattr(self.controller, "processing_indicator", None)
+ track = getattr(service, "track_turn", None)
+ if callable(track):
+ track(request.context, request)
+
async def refresh_runtime_config(self, agent_name: str, runtime_config: Any) -> bool:
"""Refresh a backend's live runtime state from the latest config.
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 6cdee1a42..963476ade 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -13,8 +13,10 @@ from modules.im.base import BaseIMClient, BaseIMConfig, MessageContext
from modules.im.multi import IMClientRemovalError, MultiIMClient
from modules.settings_manager import MultiSettingsManager
from config.v2_sessions import ActivePollInfo
+from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.processing_indicator import ProcessingIndicatorService
from modules.agents.base import AgentRequest
+from modules.agents.service import AgentService
from modules.agents.opencode.agent import OpenCodeAgent
from modules.agents.opencode.poll_loop import OpenCodePollLoop
@@ -103,6 +105,10 @@ class _StubClient(BaseIMClient):
self.sent.append(("clear_typing", context.platform, context.user_id, (context.platform_specific or {}).get("context_token")))
return True
+ async def send_typing_indicator(self, context):
+ self.sent.append(("typing", context.platform, context.user_id))
+ return True
+
async def delete_message(self, context, message_id):
self.sent.append(("delete", context.platform, context.channel_id, message_id))
return True
@@ -1240,6 +1246,86 @@ def test_processing_indicator_message_delete_policy_comes_from_platform_registry
assert telegram.sent == [("delete", "telegram", "chat-1", "ack-1")]
+class _TerminalCleanupSettings:
+ def _canonicalize_message_type(self, message_type):
+ return message_type
+
+ def is_message_type_hidden(self, settings_key, canonical_type):
+ return False
+
+
+class _TerminalCleanupController:
+ def __init__(self, platform: str, client: _StubClient):
+ self.config = type(
+ "Config",
+ (),
+ {"platform": platform, "ack_mode": "typing", "language": "en", "reply_enhancements": False},
+ )()
+ self.im_client = client
+ self.session_handler = type("SessionHandler", (), {"finalize_scheduled_delivery": lambda *args: None})()
+ self.processing_indicator = ProcessingIndicatorService(self)
+ self.agent_service = AgentService(self)
+
+ def get_im_client_for_context(self, context):
+ return self.im_client
+
+ def get_settings_manager_for_context(self, context):
+ return _TerminalCleanupSettings()
+
+ def _get_settings_key(self, context):
+ return context.channel_id
+
+ def _get_session_key(self, context):
+ return f"{context.platform}::{context.channel_id}"
+
+
+async def _run_terminal_result_cleanup(platform: str, *, platform_specific=None):
+ client = _StubClient(platform)
+ controller = _TerminalCleanupController(platform, client)
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="user-1",
+ channel_id="chan-1",
+ platform=platform,
+ platform_specific=platform_specific,
+ )
+ handle = await controller.processing_indicator.start(context, "claude")
+ request = AgentRequest(
+ context=context,
+ message="hello",
+ working_path="/tmp",
+ base_session_id="base",
+ composite_session_id="base:/tmp",
+ session_key=f"{platform}::chan-1",
+ processing_indicator=handle,
+ )
+ controller.processing_indicator.apply_to_request(request, handle)
+ controller.agent_service._stamp_runtime_turn(request, "base:/tmp", "turn-1")
+ gate = controller.agent_service._get_turn_gate("base:/tmp")
+ gate.token = "turn-1"
+ gate.backend = "claude"
+ controller.processing_indicator.track_turn(context, request)
+
+ await dispatcher.emit_agent_message(context, "result", "done")
+
+ assert request.typing_indicator_active is False
+ assert request.typing_indicator_task is None
+ assert handle.typing_indicator_active is False
+ return client
+
+
+def test_terminal_result_finishes_registered_telegram_typing_turn():
+ client = asyncio.run(_run_terminal_result_cleanup("telegram"))
+
+ assert client.sent == [("typing", "telegram", "user-1"), ("telegram", "chan-1", "done")]
+
+
+def test_terminal_result_finishes_registered_wechat_typing_turn():
+ client = asyncio.run(_run_terminal_result_cleanup("wechat", platform_specific={"context_token": "ctx-1"}))
+
+ assert ("clear_typing", "wechat", "user-1", "ctx-1") in client.sent
+
+
def test_multi_im_client_routes_download_by_file_info_platform():
slack = _StubClient("slack")
wechat = _StubClient("wechat")