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(indicator): make terminal cleanup ownership explicit

cyhc5c7a77e6147
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index 15cef8dd8..23e3d08a1 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -75,6 +75,9 @@ class ProcessingIndicatorHandle:
ack_message_channel_id: Optional[str] = None
ack_reaction_message_id: Optional[str] = None
ack_reaction_emoji: Optional[str] = None
+ # Captured only by start(), which runs for human turns. Backend-initiated
+ # turns may reuse a context with an old message_id and must not stamp it.
+ terminal_reaction_message_id: 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
@@ -100,6 +103,7 @@ class ProcessingIndicatorHandle:
"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,
+ "terminal_reaction_message_id": self.terminal_reaction_message_id,
"typing_indicator_active": self.typing_indicator_active,
}
@@ -128,6 +132,12 @@ class ProcessingIndicatorHandle:
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,
+ terminal_reaction_message_id=(
+ data.get("terminal_reaction_message_id")
+ or data.get("ack_reaction_message_id")
+ or data.get("message_id")
+ or None
+ ),
typing_indicator_active=bool(data.get("typing_indicator_active", False)),
)
@@ -427,7 +437,10 @@ class ProcessingIndicatorService:
await self.clear_admission_ack(merged)
async def start(self, context: MessageContext, agent_name: str, *, enabled: bool = True) -> ProcessingIndicatorHandle:
- handle = ProcessingIndicatorHandle(context=context)
+ handle = ProcessingIndicatorHandle(
+ context=context,
+ terminal_reaction_message_id=self._reaction_target_message_id(context),
+ )
# A queued input carries an admission receipt (👌) that this turn's own
# indicator now replaces. Platforms that stack reactions would otherwise
# show both, and the receipt would outlive the wait it described.
@@ -566,7 +579,7 @@ class ProcessingIndicatorService:
async def _stamp_terminal_reaction_without_indicator(
self,
- context: MessageContext,
+ handle: ProcessingIndicatorHandle,
terminal_emoji: str,
) -> bool:
"""Leave the terminal receipt when the turn's indicator was not a reaction.
@@ -577,9 +590,10 @@ class ProcessingIndicatorService:
message id simply ends with no receipt, same as before.
"""
- if not self._mode_supported(self._capabilities(context), "reaction", context):
+ context = handle.context
+ message_id = handle.terminal_reaction_message_id
+ if not message_id or not self._capabilities(context).supports_reaction_indicator:
return False
- message_id = self._reaction_target_message_id(context)
try:
return bool(await self._get_im_client(context).add_reaction(context, message_id, terminal_emoji))
except Exception as err:
@@ -768,6 +782,7 @@ class ProcessingIndicatorService:
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.terminal_reaction_message_id = handle.terminal_reaction_message_id
request.typing_indicator_active = handle.typing_indicator_active
request.typing_indicator_task = handle.typing_indicator_task
@@ -781,6 +796,11 @@ class ProcessingIndicatorService:
None,
)
handle.ack_reaction_emoji = handle.ack_reaction_emoji or getattr(request, "ack_reaction_emoji", None)
+ handle.terminal_reaction_message_id = handle.terminal_reaction_message_id or getattr(
+ request,
+ "terminal_reaction_message_id",
+ None,
+ )
handle.typing_indicator_active = handle.typing_indicator_active or bool(
getattr(request, "typing_indicator_active", False)
)
@@ -792,6 +812,7 @@ class ProcessingIndicatorService:
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),
+ terminal_reaction_message_id=getattr(request, "terminal_reaction_message_id", None),
typing_indicator_active=bool(getattr(request, "typing_indicator_active", False)),
typing_indicator_task=getattr(request, "typing_indicator_task", None),
)
@@ -866,7 +887,7 @@ class ProcessingIndicatorService:
# happened to be a reaction" would make ⏹️/⚠️ invisible for the
# default configuration — exactly the turns that emit no result.
# Stamp on the originating message instead, wherever reactions work.
- await self._stamp_terminal_reaction_without_indicator(handle.context, terminal_emoji)
+ await self._stamp_terminal_reaction_without_indicator(handle, terminal_emoji)
if handle.ack_reaction_message_id and handle.ack_reaction_emoji:
reaction_message_id = handle.ack_reaction_message_id
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 66cf47d69..14a2dd551 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -53,6 +53,7 @@ class AgentRequest:
processing_indicator: Optional[Any] = None
ack_reaction_message_id: Optional[str] = None
ack_reaction_emoji: Optional[str] = None
+ terminal_reaction_message_id: Optional[str] = None
typing_indicator_active: bool = False
typing_indicator_task: Optional[Any] = None
# File attachments (downloaded or with URLs for download)
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index f3209ab5e..5ebab1108 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -142,6 +142,7 @@ class CodexEventHandler:
logger.debug("Ignoring interrupted completion for unknown turn %s", turn_id)
return
self._clear_generated_image_snapshot(params)
+ cleanup_request = self._agent._turn_registry.claim_indicator_cleanup(turn_id)
self._agent._turn_registry.pop_turn(turn_id)
# A turn is interrupted for two very different reasons: the user
# stopped it, or a newer turn superseded it. Only the first is owed a
@@ -149,10 +150,11 @@ class CodexEventHandler:
# be running concurrently with the ``turn/interrupt`` RPC that caused
# the completion.
stopped_by_user = self._agent.consume_user_stop_intent(turn_id)
- await self._agent._remove_ack_reaction(
- tracked_request,
- terminal_emoji=STOPPED_REACTION_EMOJI if stopped_by_user else None,
- )
+ if cleanup_request is not None:
+ await self._agent._remove_ack_reaction(
+ cleanup_request,
+ terminal_emoji=STOPPED_REACTION_EMOJI if stopped_by_user else None,
+ )
# Turn ended without a result — release any web-Chat stream waiter
# (token-guarded, so a superseded turn won't close a newer stream).
self._release_stream_turn(tracked_request.context)
@@ -549,9 +551,11 @@ class CodexEventHandler:
# ------------------------------------------------------------------
def clear_pending(self, turn_id: str) -> AgentRequest | None:
- """Hide a turn from user-facing output after interruption/replacement."""
+ """Hide a turn and claim its one allowed indicator cleanup."""
turn_state = self._agent._turn_registry.hide_turn(turn_id)
- return turn_state.request if turn_state else None
+ if turn_state is None:
+ return None
+ return self._agent._turn_registry.claim_indicator_cleanup(turn_id)
# ------------------------------------------------------------------
# Dispatch table
diff --git a/modules/agents/codex/turn_state.py b/modules/agents/codex/turn_state.py
index 6b0d580ff..a2ae7de5e 100644
--- a/modules/agents/codex/turn_state.py
+++ b/modules/agents/codex/turn_state.py
@@ -17,6 +17,7 @@ class CodexTurnState:
terminal_error: Optional[str] = None
terminal_error_notified: bool = False
visible_to_user: bool = True
+ indicator_cleanup_claimed: bool = False
@dataclass
@@ -136,6 +137,15 @@ class CodexTurnRegistry:
pending.completed = True
return state
+ def claim_indicator_cleanup(self, turn_id: str) -> Optional[AgentRequest]:
+ """Return the turn request to the first indicator-cleanup owner only."""
+
+ state = self.get_turn(turn_id)
+ if state is None or state.indicator_cleanup_claimed:
+ return None
+ state.indicator_cleanup_claimed = True
+ return state.request
+
def hide_turn(self, turn_id: str) -> Optional[CodexTurnState]:
state = self.get_turn(turn_id)
if not state:
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index a59058e42..3837e4cd0 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -57,7 +57,12 @@ from vibe.i18n import t as i18n_t
from .caller_context import bind_session as bind_caller_context_session
from .client_manager import OpenCodeClientManager
from .message_processor import OpenCodeMessageProcessorMixin
-from .poll_loop import OpenCodePollLoop, restored_platform_from_poll_info, restored_session_key_from_poll_info
+from .poll_loop import (
+ OpenCodePollLoop,
+ restored_platform_from_poll_info,
+ restored_request_from_poll_info,
+ restored_session_key_from_poll_info,
+)
from .server import (
OpenCodePromptRejectedError,
OpenCodeServerManager,
@@ -539,9 +544,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# request describing the ``/stop`` message itself, so it is not a usable
# indicator target: the 👀 sits on the message that opened the turn.
# Only paths that end a turn from OUTSIDE its coroutine need this.
- # A restored poll registers no entry — the process that built its request
- # is gone, and a restored turn's cancellation never stamped a receipt
- # anyway; it ends with the plain removal ``remove_restored_ack`` does.
+ # Restored polls reconstruct and register the same request shape before
+ # becoming stoppable, so their cancellation can stamp the original turn's
+ # message instead of the fresh /stop request.
self._active_ack_requests: Dict[str, AgentRequest] = {}
# Sessions whose in-flight task is being cancelled BY THE USER. The
# cancellation lands in the request coroutine, which cannot otherwise
@@ -1976,6 +1981,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
restoration_ready = asyncio.get_running_loop().create_future()
restoration_published = asyncio.Event()
+ restored_request = restored_request_from_poll_info(self, poll_info)
task = asyncio.create_task(
self._run_restored_poll_loop_with_tracking(
poll_info,
@@ -1989,6 +1995,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
(restoration_ready, restoration_published, poll_info)
)
self._active_requests[poll_info.base_session_id] = task
+ self._active_ack_requests[poll_info.base_session_id] = restored_request
self._session_manager.set_request_session(
poll_info.base_session_id,
poll_info.opencode_session_id,
@@ -2191,6 +2198,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
if self._active_requests.get(poll_info.base_session_id) is current_task:
self._active_requests.pop(poll_info.base_session_id, None)
+ self._active_ack_requests.pop(poll_info.base_session_id, None)
self._session_manager.pop_request_session(poll_info.base_session_id)
if restoration_ready is not None and not restoration_ready.done():
restoration_ready.set_result(False)
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index 3244c2804..e7eef7185 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -15,6 +15,7 @@ from config.v2_config import (
from core.backend_failure import emit_backend_failure
from core.message_context import build_context_session_key
from core.message_output import terminal_output_for, terminal_turn_output
+from core.processing_indicator import STOPPED_REACTION_EMOJI
from modules.agents.base import AgentRequest
from modules.agents.model_hub import bind_persisted_launch
from modules.im import MessageContext
@@ -84,6 +85,38 @@ def restored_session_key_from_poll_info(poll_info, *, context: Optional[MessageC
)
+def restored_request_from_poll_info(agent, poll_info) -> AgentRequest:
+ """Rebuild the request that owns a restored poll's indicator lifecycle."""
+
+ 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)),
+ }
+ handle = agent.controller.processing_indicator.handle_from_snapshot(snapshot)
+ context = handle.context
+ return AgentRequest(
+ context=context,
+ message="",
+ user_message="",
+ working_path=poll_info.working_path,
+ base_session_id=poll_info.base_session_id,
+ composite_session_id=f"{poll_info.base_session_id}:{poll_info.working_path}",
+ session_key=restored_session_key_from_poll_info(poll_info, context=context),
+ 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,
+ terminal_reaction_message_id=handle.terminal_reaction_message_id,
+ typing_indicator_active=handle.typing_indicator_active,
+ )
+
+
class OpenCodePollLoop:
def __init__(self, agent):
self._agent = agent
@@ -176,39 +209,13 @@ class OpenCodePollLoop:
)
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)
+ return restored_request_from_poll_info(self._agent, poll_info).processing_indicator
def _build_restored_context(self, poll_info):
return self._build_restored_handle(poll_info).context
def _build_restored_ack_request(self, poll_info) -> AgentRequest:
- handle = self._build_restored_handle(poll_info)
- context = handle.context
- session_key = restored_session_key_from_poll_info(poll_info, context=context)
- return AgentRequest(
- context=context,
- message="",
- user_message="",
- working_path=poll_info.working_path,
- 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,
- 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,
- )
+ return restored_request_from_poll_info(self._agent, poll_info)
async def remove_restored_ack(self, poll_info) -> None:
await self._agent._remove_ack_reaction(self._build_restored_ack_request(poll_info))
@@ -512,7 +519,10 @@ class OpenCodePollLoop:
"""Continue a poll loop that was interrupted by restart."""
session_id = poll_info.opencode_session_id
- restored_request = self._build_restored_ack_request(poll_info)
+ active_ack_requests = getattr(self._agent, "_active_ack_requests", {})
+ restored_request = active_ack_requests.get(
+ poll_info.base_session_id
+ ) or self._build_restored_ack_request(poll_info)
context = restored_request.context
processing_snapshot = (
poll_info.processing_indicator if isinstance(poll_info.processing_indicator, dict) else {}
@@ -754,7 +764,11 @@ class OpenCodePollLoop:
except asyncio.CancelledError:
logger.info(f"Restored OpenCode poll cancelled for {poll_info.base_session_id}")
- await self.remove_restored_ack(poll_info)
+ stopped_by_user = self._agent.consume_user_stop_intent(poll_info.base_session_id)
+ await self._agent._remove_ack_reaction(
+ restored_request,
+ terminal_emoji=STOPPED_REACTION_EMOJI if stopped_by_user else None,
+ )
self._agent.sessions.remove_active_poll(session_id)
raise
except Exception as e:
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index cc0a79fee..02dde1f4a 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -1005,26 +1005,57 @@ class FeishuBot(BaseIMClient):
logger.debug("Failed to add Feishu reaction: %s", exc)
return False
+ def _reaction_is_owned_by_bot(self, item: object) -> bool:
+ """Whether a listed reaction was created by this application."""
+
+ if not isinstance(item, dict):
+ return False
+ operator = item.get("operator")
+ if not isinstance(operator, dict) or operator.get("operator_type") != "app":
+ return False
+ operator_id = str(operator.get("operator_id") or "").strip()
+ bot_ids = {
+ str(value).strip()
+ for value in (self._bot_open_id, getattr(self.config, "app_id", None))
+ if value
+ }
+ return bool(operator_id and operator_id in bot_ids)
+
async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
self._ensure_client()
- # Feishu remove reaction requires reaction_id; we'd need to list reactions first.
- # For simplicity, attempt to delete by listing and finding matching reaction.
+ # Feishu deletes by reaction_id, so resolve only this app's matching
+ # reaction. Multiple people may use the same emoji.
try:
token = await self._get_tenant_token()
if not token:
return False
emoji_type = _normalize_emoji(emoji)
- # List reactions
url = f"{self.config.api_base_url}/open-apis/im/v1/messages/{message_id}/reactions"
+ params = {
+ "reaction_type": emoji_type,
+ "user_id_type": "open_id",
+ "page_size": 50,
+ }
async with aiohttp.ClientSession() as session:
- async with session.get(url, headers={"Authorization": f"Bearer {token}"}) as resp:
- if resp.status != 200:
+ while True:
+ async with session.get(
+ url,
+ headers={"Authorization": f"Bearer {token}"},
+ params=params,
+ ) as resp:
+ if resp.status != 200:
+ return False
+ data = await resp.json()
+ if data.get("code") not in (None, 0):
return False
- data = await resp.json()
- items = data.get("data", {}).get("items", [])
+ page = data.get("data", {})
+ items = page.get("items", []) if isinstance(page, dict) else []
for item in items:
- rt = item.get("reaction_type", {})
- if rt.get("emoji_type") == emoji_type:
+ rt = item.get("reaction_type", {}) if isinstance(item, dict) else {}
+ if (
+ rt.get("emoji_type") == emoji_type
+ and self._reaction_is_owned_by_bot(item)
+ ):
reaction_id = item.get("reaction_id")
if reaction_id:
del_url = f"{url}/{reaction_id}"
@@ -1033,7 +1064,10 @@ class FeishuBot(BaseIMClient):
headers={"Authorization": f"Bearer {token}"},
) as del_resp:
return del_resp.status == 200
- return False
+ page_token = page.get("page_token") if isinstance(page, dict) else None
+ if not (isinstance(page, dict) and page.get("has_more") and page_token):
+ return False
+ params["page_token"] = page_token
except Exception as exc:
logger.debug("Failed to remove Feishu reaction: %s", exc)
return False
diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.py
index 839798298..8061672f5 100644
--- a/tests/test_codex_event_handler.py
+++ b/tests/test_codex_event_handler.py
@@ -26,6 +26,7 @@ class _TurnState:
self.terminal_error = None
self.terminal_error_notified = False
self.visible_to_user = True
+ self.indicator_cleanup_claimed = False
class _StubTurnRegistry:
@@ -52,6 +53,13 @@ class _StubTurnRegistry:
self._active_turns.pop(state.request.base_session_id, None)
return state
+ def claim_indicator_cleanup(self, turn_id: str):
+ state = self._turns.get(turn_id)
+ if state is None or state.indicator_cleanup_claimed:
+ return None
+ state.indicator_cleanup_claimed = True
+ return state.request
+
def hide_turn(self, turn_id: str):
state = self._turns.get(turn_id)
if not state:
@@ -389,6 +397,22 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
# Consumed: handle_stop must not stamp a second one behind it.
self.assertEqual(agent._user_stopped_turn_ids, set())
+ async def test_hidden_turn_completion_cannot_compete_with_claimed_cleanup(self):
+ agent = _StubAgent()
+ agent.controller.agent_service = SimpleNamespace(release_runtime_turn=Mock())
+ handler = CodexEventHandler(agent)
+ context = SimpleNamespace(platform_specific={})
+ request = SimpleNamespace(base_session_id="session-1", context=context, started_at=0)
+ agent._turn_registry.register_turn("turn-1", request)
+
+ claimed_request = handler.clear_pending("turn-1")
+ await handler._on_turn_completed(
+ {"turn": {"id": "turn-1", "status": "interrupted"}}, request
+ )
+
+ self.assertIs(claimed_request, request)
+ agent._remove_ack_reaction.assert_not_awaited()
+
async def test_auth_recovery_message_suppresses_plain_notify(self):
agent = _StubAgent()
agent.controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)
diff --git a/tests/test_codex_turn_state.py b/tests/test_codex_turn_state.py
index 30731be83..db2eee1d6 100644
--- a/tests/test_codex_turn_state.py
+++ b/tests/test_codex_turn_state.py
@@ -71,3 +71,12 @@ def test_finalize_turn_start_response_removes_old_bootstrapped_active_turn():
assert registry.get_turn("turn-old") is None
assert registry.get_request_for_turn("turn-old") is None
assert registry.get_active_turn("session-1") == "turn-new"
+
+
+def test_indicator_cleanup_has_exactly_one_owner():
+ registry = CodexTurnRegistry()
+ request = SimpleNamespace(base_session_id="session-1")
+ registry.register_turn("turn-1", request)
+
+ assert registry.claim_indicator_cleanup("turn-1") is request
+ assert registry.claim_indicator_cleanup("turn-1") is None
diff --git a/tests/test_feishu_reaction_emoji.py b/tests/test_feishu_reaction_emoji.py
index 20221e462..c119a4d97 100644
--- a/tests/test_feishu_reaction_emoji.py
+++ b/tests/test_feishu_reaction_emoji.py
@@ -17,6 +17,8 @@ ever used as evidence *for* a key.
import sys
import unittest
from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
@@ -31,7 +33,7 @@ from core.processing_indicator import ( # noqa: E402
UNCONFIRMED_REACTION_EMOJI,
)
from core.handlers.message_handler import SUBAGENT_REACTION_EMOJI # noqa: E402
-from modules.im.feishu import _EMOJI_MAP, _normalize_emoji # noqa: E402
+from modules.im.feishu import FeishuBot, _EMOJI_MAP, _normalize_emoji # noqa: E402
# unicode emoji -> the exact emoji_type Lark publishes for it.
VERIFIED_EMOJI_TYPES = {
@@ -110,6 +112,98 @@ class FeishuReactionEmojiTests(unittest.TestCase):
self.assertEqual(_normalize_emoji(":writing_hand:"), "Typing")
self.assertEqual(_normalize_emoji(":shrug:"), "Shrug")
+ def test_reaction_cleanup_accepts_only_this_app_operator(self):
+ bot = FeishuBot.__new__(FeishuBot)
+ bot.config = SimpleNamespace(app_id="cli_app")
+ bot._bot_open_id = "ou_bot"
+
+ self.assertTrue(bot._reaction_is_owned_by_bot({"operator": {"operator_type": "app", "operator_id": "ou_bot"}}))
+ self.assertTrue(bot._reaction_is_owned_by_bot({"operator": {"operator_type": "app", "operator_id": "cli_app"}}))
+ self.assertFalse(
+ bot._reaction_is_owned_by_bot({"operator": {"operator_type": "user", "operator_id": "ou_user"}})
+ )
+ self.assertFalse(
+ bot._reaction_is_owned_by_bot({"operator": {"operator_type": "app", "operator_id": "cli_other"}})
+ )
+
+
+class FeishuReactionCleanupTests(unittest.IsolatedAsyncioTestCase):
+ async def test_remove_skips_human_match_and_finds_bot_on_next_page(self):
+ pages = [
+ {
+ "code": 0,
+ "data": {
+ "items": [
+ {
+ "reaction_id": "human-reaction",
+ "operator": {"operator_type": "user", "operator_id": "ou_user"},
+ "reaction_type": {"emoji_type": "OnIt"},
+ }
+ ],
+ "has_more": True,
+ "page_token": "next-page",
+ },
+ },
+ {
+ "code": 0,
+ "data": {
+ "items": [
+ {
+ "reaction_id": "bot-reaction",
+ "operator": {"operator_type": "app", "operator_id": "ou_bot"},
+ "reaction_type": {"emoji_type": "OnIt"},
+ }
+ ],
+ "has_more": False,
+ },
+ },
+ ]
+ get_params = []
+ deleted = []
+
+ class _Response:
+ def __init__(self, *, payload=None, status=200):
+ self.payload = payload
+ self.status = status
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def json(self):
+ return self.payload
+
+ class _Session:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ def get(self, _url, *, headers, params):
+ get_params.append(dict(params))
+ return _Response(payload=pages.pop(0))
+
+ def delete(self, url, *, headers):
+ deleted.append(url)
+ return _Response(status=200)
+
+ bot = FeishuBot.__new__(FeishuBot)
+ bot.config = SimpleNamespace(app_id="cli_app", api_base_url="https://open.feishu.cn")
+ bot._bot_open_id = "ou_bot"
+ bot._lark_client = object()
+ bot._get_tenant_token = AsyncMock(return_value="token")
+
+ with patch("modules.im.feishu.aiohttp.ClientSession", return_value=_Session()):
+ removed = await bot.remove_reaction(SimpleNamespace(), "m1", "👀")
+
+ self.assertTrue(removed)
+ self.assertNotIn("human-reaction", "".join(deleted))
+ self.assertIn("bot-reaction", deleted[0])
+ self.assertEqual(get_params[1]["page_token"], "next-page")
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.py
index 75c08ce87..f2091be2f 100644
--- a/tests/test_opencode_restore_polls.py
+++ b/tests/test_opencode_restore_polls.py
@@ -113,9 +113,11 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
class _Controller:
def __init__(self):
+ from core.processing_indicator import ProcessingIndicatorService
from core.session_turns import SessionTurnManager
self.config = SimpleNamespace(language=language)
+ self.processing_indicator = ProcessingIndicatorService(self)
# The restore path re-marks running via the turn owner, which delegates
# to set_agent_status — wire a real manager so the full path is exercised.
self.session_turns = SessionTurnManager(self)
@@ -129,6 +131,8 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
agent._poll_loop = _PollLoop()
agent._session_manager = _SessionManager()
agent._active_requests = {}
+ agent._active_ack_requests = {}
+ agent._user_stopped_sessions = set()
agent._steering_states = {}
agent._restored_poll_servers = {}
@@ -224,8 +228,11 @@ def test_restore_im_registration_failure_retries_before_releasing_poll() -> None
await asyncio.wait_for(poll_started.wait(), timeout=1)
task = agent._active_requests[poll.base_session_id]
assert not task.done()
+ restored_request = agent._active_ack_requests[poll.base_session_id]
+ assert restored_request.base_session_id == poll.base_session_id
release_poll.set()
await task
+ assert agent._active_ack_requests == {}
return restored
assert asyncio.run(_run()) == 1
diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.py
index 3c91bc5fe..3b0c42992 100644
--- a/tests/test_opencode_stop_receipt.py
+++ b/tests/test_opencode_stop_receipt.py
@@ -18,10 +18,14 @@ from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from core.processing_indicator import STOPPED_REACTION_EMOJI
+from config.v2_sessions import ActivePollInfo
+from core.processing_indicator import STOPPED_REACTION_EMOJI, ProcessingIndicatorService
from modules.agents.opencode.agent import OpenCodeAgent
+from modules.agents.opencode.poll_loop import OpenCodePollLoop, restored_request_from_poll_info
def _agent():
@@ -223,6 +227,73 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(result)
self.assertEqual(agent._user_stopped_sessions, set())
+ async def test_restored_poll_cancellation_stamps_its_retained_request(self):
+ entered = asyncio.Event()
+ cleanups: list[tuple[object, object]] = []
+
+ class _Controller:
+ def __init__(self):
+ self.config = SimpleNamespace(
+ platform="slack",
+ ack_mode="reaction",
+ language="en",
+ )
+ self.processing_indicator = ProcessingIndicatorService(self)
+
+ async def emit_agent_message(self, *_args, **_kwargs):
+ return None
+
+ class _Server:
+ async def list_messages(self, **_kwargs):
+ entered.set()
+ await asyncio.Event().wait()
+
+ agent = SimpleNamespace(
+ controller=_Controller(),
+ opencode_config=SimpleNamespace(active_turn_timeout_seconds=60),
+ sessions=SimpleNamespace(remove_active_poll=Mock()),
+ _active_ack_requests={},
+ _user_stopped_sessions={"session-1"},
+ )
+
+ async def _get_server():
+ return _Server()
+
+ async def _remove_ack_reaction(request, *, terminal_emoji=None):
+ cleanups.append((request, terminal_emoji))
+
+ def _consume(session_id):
+ return OpenCodeAgent.consume_user_stop_intent(agent, session_id)
+
+ agent._get_server = _get_server
+ agent._remove_ack_reaction = _remove_ack_reaction
+ agent.consume_user_stop_intent = _consume
+ poll = ActivePollInfo(
+ opencode_session_id="oc-1",
+ base_session_id="session-1",
+ channel_id="c1",
+ thread_id="t1",
+ settings_key="c1",
+ working_path="/tmp/work",
+ processing_indicator={
+ "platform": "slack",
+ "user_id": "u1",
+ "channel_id": "c1",
+ "message_id": "m1",
+ },
+ )
+ restored_request = restored_request_from_poll_info(agent, poll)
+ agent._active_ack_requests[poll.base_session_id] = restored_request
+
+ task = asyncio.create_task(OpenCodePollLoop(agent).run_restored_poll_loop(poll))
+ await entered.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ self.assertEqual(cleanups, [(restored_request, STOPPED_REACTION_EMOJI)])
+ self.assertEqual(agent._user_stopped_sessions, set())
+
class OpenCodeStopReceiptTests(unittest.TestCase):
"""The intent is only useful if the cancellation branch actually spends it.
@@ -242,6 +313,16 @@ class OpenCodeStopReceiptTests(unittest.TestCase):
self.assertIn("consume_user_stop_intent", branch)
self.assertIn("STOPPED_REACTION_EMOJI", branch)
+ def test_restored_cancellation_branch_reads_the_intent(self):
+ source = inspect.getsource(OpenCodePollLoop.run_restored_poll_loop)
+ _, _, after = source.partition("except asyncio.CancelledError:")
+ branch = after.partition("raise")[0]
+
+ self.assertTrue(branch, "run_restored_poll_loop no longer handles cancellation")
+ self.assertIn("consume_user_stop_intent", branch)
+ self.assertIn("STOPPED_REACTION_EMOJI", branch)
+ self.assertIn("restored_request", branch)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_turn_terminal_reaction.py b/tests/test_turn_terminal_reaction.py
index 02fcf982c..08e1380ba 100644
--- a/tests/test_turn_terminal_reaction.py
+++ b/tests/test_turn_terminal_reaction.py
@@ -156,16 +156,35 @@ class TerminalReceiptWithoutAReactionIndicatorTests(unittest.IsolatedAsyncioTest
async def test_typing_turn_still_gets_the_receipt(self):
im = _FakeIM()
svc = _svc(im)
- handle = ProcessingIndicatorHandle(context=_ctx(), typing_indicator_active=True)
+ handle = ProcessingIndicatorHandle(
+ context=_ctx(),
+ terminal_reaction_message_id="m1",
+ typing_indicator_active=True,
+ )
await svc.finish(handle, terminal_emoji=STOPPED_REACTION_EMOJI)
self.assertEqual(im.calls, [("add", "m1", STOPPED_REACTION_EMOJI)])
+ async def test_human_turn_target_survives_the_restored_snapshot(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ handle = await svc.start(_ctx(), "claude", enabled=False)
+
+ restored = svc.handle_from_snapshot(handle.to_snapshot())
+ await svc.finish(restored, terminal_emoji=STOPPED_REACTION_EMOJI)
+
+ self.assertEqual(restored.terminal_reaction_message_id, "m1")
+ self.assertEqual(im.calls, [("add", "m1", STOPPED_REACTION_EMOJI)])
+
async def test_no_receipt_without_a_terminal_emoji(self):
im = _FakeIM()
svc = _svc(im)
- handle = ProcessingIndicatorHandle(context=_ctx(), typing_indicator_active=True)
+ handle = ProcessingIndicatorHandle(
+ context=_ctx(),
+ terminal_reaction_message_id="m1",
+ typing_indicator_active=True,
+ )
await svc.finish(handle)
@@ -185,7 +204,11 @@ class TerminalReceiptWithoutAReactionIndicatorTests(unittest.IsolatedAsyncioTest
im = _FakeIM()
svc = _svc(im)
context = MessageContext(user_id="u1", channel_id="c1", message_id="m1", platform="wechat")
- handle = ProcessingIndicatorHandle(context=context, typing_indicator_active=True)
+ handle = ProcessingIndicatorHandle(
+ context=context,
+ terminal_reaction_message_id="m1",
+ typing_indicator_active=True,
+ )
await svc.finish(handle, terminal_emoji=STOPPED_REACTION_EMOJI)
@@ -205,6 +228,24 @@ class TerminalReceiptWithoutAReactionIndicatorTests(unittest.IsolatedAsyncioTest
[("add", "m1", STOPPED_REACTION_EMOJI)],
)
+ async def test_agent_initiated_turn_does_not_reuse_an_old_context_message(self):
+ im = _FakeIM()
+ svc = _svc(im)
+ request = SimpleNamespace(
+ context=_ctx(message_id="old-human-message"),
+ processing_indicator=None,
+ ack_message_id=None,
+ ack_reaction_message_id=None,
+ ack_reaction_emoji=None,
+ terminal_reaction_message_id=None,
+ typing_indicator_active=False,
+ typing_indicator_task=None,
+ )
+
+ await svc.finish(request, terminal_emoji=STOPPED_REACTION_EMOJI)
+
+ self.assertEqual(im.calls, [])
+
class OrphanedTerminalReactionTests(unittest.IsolatedAsyncioTestCase):
"""Restart recovery has no handle — only the durable Delivery's message id."""