Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(bridges): make the runtime indicator follow the latest message (CHOO-1104)

Louis Amaudruz4c074e6ee0b4
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index a922f6873..68f21a66c 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+import logging
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, replace
from switch_core.bridges.collaboration.models import (
ChannelType,
@@ -13,6 +15,23 @@ from switch_core.bridges.collaboration.models import (
OutboundAttachment,
)
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class LiveRuntimeIndicator:
+ """The runtime status message currently posted for one agent in one channel.
+
+ ``body`` and ``thread_root_id`` are retained so the indicator can be
+ reposted verbatim, in the same thread, when it is moved to follow newer
+ traffic — a move has no access to the ``detail``/``deeplink_url`` the body
+ was originally rendered from.
+ """
+
+ message_ref: str
+ body: str
+ thread_root_id: str | None
+
class CollaborationAdapter(ABC):
def __init__(self) -> None:
@@ -28,6 +47,12 @@ class CollaborationAdapter(ABC):
# size against this before downloading so an oversize file is rejected
# loudly instead of being pulled down and discarded.
self._max_attachment_bytes = 20 * 1024 * 1024
+ # (channel_id, agent_name) -> the agent's live "working on it…" runtime
+ # indicator, and the operator pings posted alongside it. Adapters that
+ # render runtime state as a persistent message maintain these; the
+ # typing-indicator default leaves them empty.
+ self._working_msg: dict[tuple[str, str], LiveRuntimeIndicator] = {}
+ self._input_pings: dict[tuple[str, str], list[str]] = {}
def set_max_attachment_bytes(self, max_bytes: int) -> None:
self._max_attachment_bytes = max_bytes
@@ -193,6 +218,59 @@ class CollaborationAdapter(ABC):
else:
await self.send_typing(channel_id, agent_name, False)
+ def agents_with_live_runtime_state(self, channel_id: str) -> list[str]:
+ """Agents with a runtime indicator currently posted in this channel.
+
+ Cheap and synchronous so a caller can skip the work of deciding whether
+ a message warrants a move when there is nothing to move."""
+ return [
+ agent_name
+ for (posted_channel, agent_name) in self._working_msg
+ if posted_channel == channel_id
+ ]
+
+ async def reposition_runtime_state(self, channel_id: str, agent_name: str) -> None:
+ """Move the agent's live runtime indicator to the foot of the channel.
+
+ Called when a message the agent is party to has just crossed the bridge,
+ so the indicator no longer sits below the conversation it belongs to.
+ The replacement is posted *before* the original is removed: the
+ indicator is therefore never briefly absent, and a failed repost leaves
+ the original in place rather than clearing it.
+
+ Adapters that render runtime state as a typing indicator have nothing
+ positional to move, so the default does nothing.
+ """
+ key = (channel_id, agent_name)
+ live = self._working_msg.get(key)
+ if live is None:
+ return
+
+ ref = await self.send_message(
+ channel_id, agent_name, live.body, live.thread_root_id
+ )
+ if ref is None:
+ logger.warning(
+ "Could not repost the runtime indicator for %s in %s; leaving it "
+ "at its current position",
+ agent_name,
+ channel_id,
+ )
+ return
+
+ self._working_msg[key] = replace(live, message_ref=ref)
+ await self._remove_runtime_indicator(channel_id, live.message_ref)
+
+ async def _remove_runtime_indicator(
+ self, channel_id: str, message_ref: str
+ ) -> None:
+ """Delete a superseded runtime indicator.
+
+ Separate from ``delete_message`` so an adapter whose delete raises can
+ keep a failed cleanup from tearing down the turn — the worst case is a
+ duplicate indicator, which is visible, rather than a broken turn."""
+ await self.delete_message(channel_id, message_ref)
+
@staticmethod
def _deeplink_suffix(deeplink_url: str | None) -> str:
"""A trailing ``(Open in SwitchDash)`` link to the session, or empty.
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 9273a4e25..bf7f578a7 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -31,7 +31,11 @@ from switch_core.bridges.collaboration.models import (
)
from switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageType
from switch_core.clients.client_base import ClientBase, ClientConfig
-from switch_core.clients.mentions import mention_regex, strip_emphasis
+from switch_core.clients.mentions import (
+ mention_regex,
+ strip_emphasis,
+ unique_mention_tokens,
+)
from switch_core.db.models import BridgeMessageMap, ExternalUser
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStore
@@ -63,6 +67,11 @@ class _PendingOutboundGroup:
first_event_id: str | None = None
+# How long a queued runtime-indicator move waits before it runs, so a burst of
+# messages to the same agent costs one move rather than one per message. Short
+# enough that the indicator still reads as following the conversation.
+_INDICATOR_MOVE_DELAY_SECONDS = 1.0
+
_LOBBY_DEPRECATION_NOTICE = (
"👋 This isn't where you talk to agents — direct messages to the Switch "
"app aren't routed to anyone. Head to a channel and @-mention an agent "
@@ -136,6 +145,9 @@ class BridgeCore:
# never completes cannot leak.
self._outbound_groups: dict[str, _PendingOutboundGroup] = {}
self._outbound_group_timers: dict[str, asyncio.TimerHandle] = {}
+ # (channel_id, agent_name) whose runtime indicator is due to be moved
+ # below newly-arrived traffic. See _schedule_indicator_move.
+ self._indicator_move_timers: dict[tuple[str, str], asyncio.TimerHandle] = {}
@property
def adapter(self) -> CollaborationAdapter:
@@ -430,6 +442,13 @@ class BridgeCore:
matrix_event_id=event_id,
external_post_id=msg.message_ref,
)
+ await self._move_indicators_for_addressees(
+ channel_id=msg.channel_id,
+ room_id=room_id,
+ channel_type=msg.channel_type,
+ content=content,
+ mention_target=mention_target,
+ )
return
# Caption convention: the text rides as the caption on the first
@@ -475,6 +494,14 @@ class BridgeCore:
external_post_id=msg.message_ref,
)
+ await self._move_indicators_for_addressees(
+ channel_id=msg.channel_id,
+ room_id=room_id,
+ channel_type=msg.channel_type,
+ content=content,
+ mention_target=mention_target,
+ )
+
async def _handle_inbound_command(self, cmd: InboundCommand) -> None:
room_ids = self._channel_to_room.get(cmd.channel_id)
if room_ids is None:
@@ -988,6 +1015,9 @@ class BridgeCore:
external_post_id=message_ref,
)
+ if sender_name is not None:
+ await self._move_indicator_for_sender(channel_id, sender_name)
+
async def _outbound_thread_root_ref(
self, event_content: dict[str, object], channel_id: str
) -> str | None:
@@ -1136,6 +1166,8 @@ class BridgeCore:
external_post_id=message_ref,
)
+ await self._move_indicator_for_sender(channel_id, sender_name)
+
def _schedule_outbound_group_flush(
self,
group_id: str,
@@ -1218,6 +1250,8 @@ class BridgeCore:
external_post_id=message_ref,
)
+ await self._move_indicator_for_sender(channel_id, sender_name)
+
async def _download_matrix_media(
self, client: ClientBase[Any], mxc: str | None, filename: str
) -> bytes | None:
@@ -1318,6 +1352,117 @@ class BridgeCore:
translated = self._adapter.translate_outbound(new_content)
await self._adapter.update_message(channel_id, message_ref, translated)
+ # ── Runtime-indicator positioning ─────────────────────────────────────────
+
+ async def _move_indicator_for_sender(
+ self, channel_id: str, agent_name: str
+ ) -> None:
+ """Follow a message the agent itself just posted."""
+ if agent_name in self._adapter.agents_with_live_runtime_state(channel_id):
+ self._schedule_indicator_move(channel_id, agent_name)
+
+ async def _move_indicators_for_addressees(
+ self,
+ *,
+ channel_id: str,
+ room_id: str,
+ channel_type: ChannelType,
+ content: str,
+ mention_target: str | None,
+ ) -> None:
+ """Follow an inbound message, for each addressed agent working here.
+
+ Only agents the message actually addresses move: unrelated chatter in a
+ busy channel leaves a working agent's indicator where it is."""
+ live = self._adapter.agents_with_live_runtime_state(channel_id)
+ if not live:
+ return
+
+ # Every message in a 1:1 room addresses the agent, with no mention.
+ if channel_type == "direct":
+ for agent_name in live:
+ self._schedule_indicator_move(channel_id, agent_name)
+ return
+
+ stripped = strip_emphasis(content)
+ addressed = {
+ agent_name
+ for agent_name in live
+ if mention_regex(agent_name).search(stripped) is not None
+ }
+ if mention_target is not None and mention_target in live:
+ addressed.add(mention_target)
+
+ unmatched = [name for name in live if name not in addressed]
+ if unmatched:
+ addressed.update(
+ await self._live_agents_addressed_by_alias(room_id, content, unmatched)
+ )
+
+ for agent_name in addressed:
+ self._schedule_indicator_move(channel_id, agent_name)
+
+ async def _live_agents_addressed_by_alias(
+ self, room_id: str, content: str, candidates: list[str]
+ ) -> set[str]:
+ """Of `candidates`, those addressed by their room alias rather than name.
+
+ An alias is room-scoped, so it cannot be matched from the message text
+ alone. Only consulted when a plain-name match has already failed for the
+ agent, keeping this off the path of the common case."""
+ tokens = unique_mention_tokens(content)
+ if not tokens:
+ return set()
+
+ by_name = {name.lower(): name for name in candidates}
+ matched: set[str] = set()
+ async with self._session_factory() as session:
+ for token in tokens:
+ agent_id = await self._room_store.get_agent_id_by_alias(
+ session, room_id, token
+ )
+ if agent_id is None:
+ continue
+ agent = await self._agent_store.get(session, agent_id)
+ if agent is None:
+ continue
+ name = by_name.get(agent.name.lower())
+ if name is not None:
+ matched.add(name)
+ return matched
+
+ def _schedule_indicator_move(self, channel_id: str, agent_name: str) -> None:
+ """Queue a move of this agent's runtime indicator, coalescing bursts.
+
+ Messages arriving while a move is already queued are absorbed into it,
+ so a rapid exchange costs one delete-and-repost rather than one per
+ message. The delay is deliberately not extended by later messages —
+ a sustained conversation would otherwise starve the move indefinitely.
+ """
+ key = (channel_id, agent_name)
+ if key in self._indicator_move_timers:
+ return
+
+ loop = asyncio.get_running_loop()
+ self._indicator_move_timers[key] = loop.call_later(
+ _INDICATOR_MOVE_DELAY_SECONDS,
+ lambda: asyncio.ensure_future(self._run_indicator_move(key)),
+ )
+
+ async def _run_indicator_move(self, key: tuple[str, str]) -> None:
+ self._indicator_move_timers.pop(key, None)
+ channel_id, agent_name = key
+ try:
+ await self._adapter.reposition_runtime_state(channel_id, agent_name)
+ except Exception:
+ # The indicator is cosmetic; a platform failure here must not take
+ # down the bridge callback that happened to trigger it.
+ logger.exception(
+ "[BRIDGE-OUT] failed to move the runtime indicator for %s in %s",
+ agent_name,
+ channel_id,
+ )
+
# ── Message-map helpers ───────────────────────────────────────────────────
async def _record_message_map(
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 4189cf63e..b34316339 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -6,11 +6,15 @@ import logging
import re
from collections import OrderedDict
from collections.abc import Awaitable, Callable, Coroutine
+from dataclasses import replace
from typing import Any
import discord
-from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.adapter import (
+ CollaborationAdapter,
+ LiveRuntimeIndicator,
+)
from switch_core.bridges.collaboration.models import (
Attachment,
AttachmentFailure,
@@ -69,15 +73,9 @@ class DiscordAdapter(CollaborationAdapter):
# Discord user id ↔ username caches, for mention translation both ways.
self._user_names: dict[int, str] = {}
self._username_to_id: dict[str, int] = {}
- # (channel_id, agent_name) -> message ref of the agent's live "working
- # on it…" runtime-state message, so it can be deleted when the agent
- # stops working. Webhook messages delete cleanly on Discord, so a
- # persistent message is preferable to the one-shot typing indicator.
- self._working_msg: dict[tuple[str, str], str] = {}
- # (channel_id, agent_name) -> refs of the live "needs your input" pings,
- # kept so they can be removed when the turn ends. The working indicator
- # stays up alongside these — the agent is mid-turn, just paused.
- self._input_pings: dict[tuple[str, str], list[str]] = {}
+ # Webhook messages delete cleanly on Discord, so runtime state renders
+ # as a persistent message (see the base class's _working_msg) rather
+ # than the one-shot typing indicator.
# ── Lifecycle ────────────────────────────────────────────────────────────
@@ -455,11 +453,14 @@ class DiscordAdapter(CollaborationAdapter):
body = self._working_body(detail, deeplink_url)
existing = self._working_msg.get(key)
if existing is not None:
- await self.update_message(channel_id, existing, body)
+ await self.update_message(channel_id, existing.message_ref, body)
+ self._working_msg[key] = replace(existing, body=body)
return
ref = await self.send_message(channel_id, agent_name, body, thread_root_id)
if ref is not None:
- self._working_msg[key] = ref
+ self._working_msg[key] = LiveRuntimeIndicator(
+ message_ref=ref, body=body, thread_root_id=thread_root_id
+ )
elif state == "awaiting-input":
ref = await self._ping_operator(
channel_id, agent_name, notify_user, thread_root_id, deeplink_url
@@ -471,9 +472,9 @@ class DiscordAdapter(CollaborationAdapter):
await self._clear_input_pings(channel_id, agent_name)
async def _clear_working(self, channel_id: str, agent_name: str) -> None:
- ref = self._working_msg.pop((channel_id, agent_name), None)
- if ref is not None:
- await self.delete_message(channel_id, ref)
+ live = self._working_msg.pop((channel_id, agent_name), None)
+ if live is not None:
+ await self.delete_message(channel_id, live.message_ref)
async def _clear_input_pings(self, channel_id: str, agent_name: str) -> None:
refs = self._input_pings.pop((channel_id, agent_name), [])
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index c09ab128d..f4b38ccd7 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -10,6 +10,7 @@ import time
import uuid
from collections import OrderedDict
from collections.abc import Awaitable, Callable
+from dataclasses import replace
from typing import Any
import httpx
@@ -17,7 +18,10 @@ import requests as sync_requests
from mattermostdriver import Driver
from mattermostdriver.exceptions import NoAccessTokenProvided
-from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.adapter import (
+ CollaborationAdapter,
+ LiveRuntimeIndicator,
+)
from switch_core.bridges.collaboration.models import (
Attachment,
AttachmentFailure,
@@ -76,16 +80,13 @@ class MattermostAdapter(CollaborationAdapter):
self._seen_post_ids_max = 1000
self._seen_lock = threading.Lock()
- # (channel_id, agent_name) -> post id of the agent's live "working on
- # it…" runtime-state message. Mattermost's delete leaves a "(message
- # deleted)" tombstone, so the message is never deleted — it is edited in
- # place to a terminal marker when the turn ends (idle) or repurposed
- # into the operator ping (awaiting-input).
- self._working_msg: dict[tuple[str, str], str] = {}
- # (channel_id, agent_name) -> post ids of the live "needs your input"
- # pings, kept so they can be removed when the turn ends. The working
- # indicator stays up alongside these — the agent is mid-turn, paused.
- self._input_pings: dict[tuple[str, str], list[str]] = {}
+ # Mattermost's ordinary delete leaves a "(message deleted)" tombstone,
+ # so the runtime indicator (base class `_working_msg`) is never soft
+ # deleted — it is hard deleted where the server permits it, and
+ # otherwise edited in place to a terminal marker when the turn ends.
+ # Channels where the hard delete has been found unavailable, so the
+ # operator is warned once rather than on every message.
+ self._no_hard_delete_warned: set[str] = set()
self._main_loop: asyncio.AbstractEventLoop | None = None
@@ -472,11 +473,14 @@ class MattermostAdapter(CollaborationAdapter):
existing = self._working_msg.get(key)
if existing is not None:
# Refresh the live message in place with the latest activity.
- await self._patch_post_as(agent_name, existing, body)
+ await self._patch_post_as(agent_name, existing.message_ref, body)
+ self._working_msg[key] = replace(existing, body=body)
return
ref = await self.send_message(channel_id, agent_name, body, thread_root_id)
if ref is not None:
- self._working_msg[key] = ref
+ self._working_msg[key] = LiveRuntimeIndicator(
+ message_ref=ref, body=body, thread_root_id=thread_root_id
+ )
elif state == "awaiting-input":
ref = await self._ping_operator(
channel_id, agent_name, notify_user, thread_root_id, deeplink_url
@@ -499,6 +503,51 @@ class MattermostAdapter(CollaborationAdapter):
agent_name, post_id, self.translate_outbound("✓ input received")
)
+ async def reposition_runtime_state(self, channel_id: str, agent_name: str) -> None:
+ """Move the indicator only when Mattermost will truly delete the old one.
+
+ This inverts the base class's post-then-delete order. Mattermost can only
+ remove a post without leaving a "(message deleted)" tombstone when the
+ server permits a hard delete (v10.2+, ``EnableAPIPostDeletion``, and a
+ system-admin account). Reposting first and discovering the delete is
+ unavailable would strand a dead marker in the channel on *every*
+ message, so the delete is attempted first and the move is abandoned —
+ loudly — when it fails.
+ """
+ key = (channel_id, agent_name)
+ live = self._working_msg.get(key)
+ if live is None:
+ return
+
+ if not await self._permanent_delete(live.message_ref):
+ if channel_id not in self._no_hard_delete_warned:
+ self._no_hard_delete_warned.add(channel_id)
+ logger.warning(
+ "Cannot move the runtime indicator in Mattermost channel %s: "
+ "hard delete is unavailable, so the indicator would leave a "
+ "marker behind each time it moved. It will stay where it was "
+ "first posted. Requires Mattermost v10.2+ with "
+ "ServiceSettings.EnableAPIPostDeletion and a system-admin "
+ "account.",
+ channel_id,
+ )
+ return
+
+ ref = await self.send_message(
+ channel_id, agent_name, live.body, live.thread_root_id
+ )
+ if ref is None:
+ # The old post is already gone, so there is nothing to fall back to.
+ self._working_msg.pop(key, None)
+ logger.error(
+ "Removed the runtime indicator for %s in %s but could not repost "
+ "it; the channel now shows no indicator for this turn",
+ agent_name,
+ channel_id,
+ )
+ return
+ self._working_msg[key] = replace(live, message_ref=ref)
+
async def _dispose_working(self, channel_id: str, agent_name: str) -> None:
"""Remove the live "working on it…" message when the turn ends.
@@ -507,13 +556,13 @@ class MattermostAdapter(CollaborationAdapter):
``ServiceSettings.EnableAPIPostDeletion`` enabled and a system-admin
account, so when it is unavailable we fall back to editing the message
in place — never a soft delete, which would leave a tombstone."""
- post_id = self._working_msg.pop((channel_id, agent_name), None)
- if post_id is None:
+ live = self._working_msg.pop((channel_id, agent_name), None)
+ if live is None:
return
- if await self._permanent_delete(post_id):
+ if await self._permanent_delete(live.message_ref):
return
await self._patch_post_as(
- agent_name, post_id, self.translate_outbound("✓ done")
+ agent_name, live.message_ref, self.translate_outbound("✓ done")
)
async def _permanent_delete(self, post_id: str) -> bool:
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 4f8ee5fda..c7f5ca59c 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -5,6 +5,7 @@ import re
import uuid
from collections import OrderedDict
from collections.abc import Awaitable, Callable
+from dataclasses import replace
import httpx
from pydantic import BaseModel
@@ -14,7 +15,10 @@ from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.web.async_client import AsyncWebClient
-from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.adapter import (
+ CollaborationAdapter,
+ LiveRuntimeIndicator,
+)
from switch_core.bridges.collaboration.models import (
Attachment,
AttachmentFailure,
@@ -64,15 +68,6 @@ class SlackAdapter(CollaborationAdapter):
# Slack mentions. Populated as users are resolved.
self._username_to_id: dict[str, str] = {}
self._thinking_ts: dict[tuple[str, str], str] = {}
- # (channel_id, agent_name) -> message ref of the agent's live "working
- # on it…" runtime-state message, so it can be deleted when the agent
- # stops working. Slack can truly delete, so a persistent message is
- # preferable to the ephemeral typing indicator here.
- self._working_msg: dict[tuple[str, str], str] = {}
- # (channel_id, agent_name) -> refs of the live "needs your input" pings,
- # kept so they can be removed when the turn ends. The working indicator
- # stays up alongside these — the agent is mid-turn, just paused.
- self._input_pings: dict[tuple[str, str], list[str]] = {}
# ── Lifecycle ────────────────────────────────────────────────────────────
@@ -482,11 +477,16 @@ class SlackAdapter(CollaborationAdapter):
existing = self._working_msg.get(key)
if existing is not None:
# Refresh the live message in place with the latest activity.
- await self.update_message(channel_id, existing, body)
+ # Position is a separate concern — see reposition_runtime_state,
+ # which moves the indicator when the conversation moves on.
+ await self.update_message(channel_id, existing.message_ref, body)
+ self._working_msg[key] = replace(existing, body=body)
return
ref = await self.send_message(channel_id, agent_name, body, thread_root_id)
if ref is not None:
- self._working_msg[key] = ref
+ self._working_msg[key] = LiveRuntimeIndicator(
+ message_ref=ref, body=body, thread_root_id=thread_root_id
+ )
elif state == "awaiting-input":
# Leave the working indicator up; add a ping and track it.
ref = await self._ping_operator(
@@ -499,9 +499,9 @@ class SlackAdapter(CollaborationAdapter):
await self._clear_input_pings(channel_id, agent_name)
async def _clear_working(self, channel_id: str, agent_name: str) -> None:
- ref = self._working_msg.pop((channel_id, agent_name), None)
- if ref is not None:
- await self.delete_message(channel_id, ref)
+ live = self._working_msg.pop((channel_id, agent_name), None)
+ if live is not None:
+ await self.delete_message(channel_id, live.message_ref)
async def _clear_input_pings(self, channel_id: str, agent_name: str) -> None:
refs = self._input_pings.pop((channel_id, agent_name), [])
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
index 8c9fb3b04..19f281a6a 100644
--- a/core/switch_core/bridges/collaboration/teams/adapter.py
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -6,6 +6,7 @@ import logging
import re
from collections import OrderedDict
from collections.abc import Awaitable, Callable
+from dataclasses import replace
from datetime import UTC, datetime, timedelta
from typing import Any
from urllib.parse import quote
@@ -14,7 +15,10 @@ import httpx
from aiohttp import web
from pydantic.json_schema import SkipJsonSchema
-from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.adapter import (
+ CollaborationAdapter,
+ LiveRuntimeIndicator,
+)
from switch_core.bridges.collaboration.models import (
BridgeConnectionConfig,
ChannelType,
@@ -189,11 +193,6 @@ class TeamsAdapter(CollaborationAdapter):
self._sub_lock = asyncio.Lock()
self._renewal_task: asyncio.Task[None] | None = None
- # (channel_id, agent_name) -> live "working on it…" message ref.
- self._working_msg: dict[tuple[str, str], str] = {}
- # (channel_id, agent_name) -> live "needs your input" ping refs.
- self._input_pings: dict[tuple[str, str], list[str]] = {}
-
# ── Lifecycle ────────────────────────────────────────────────────────────
async def start(
@@ -558,11 +557,16 @@ class TeamsAdapter(CollaborationAdapter):
body = self._working_body(detail, deeplink_url)
existing = self._working_msg.get(key)
if existing is not None:
- await self._refresh_card(channel_id, existing, agent_name, body)
+ await self._refresh_card(
+ channel_id, existing.message_ref, agent_name, body
+ )
+ self._working_msg[key] = replace(existing, body=body)
return
ref = await self.send_message(channel_id, agent_name, body, thread_root_id)
if ref is not None:
- self._working_msg[key] = ref
+ self._working_msg[key] = LiveRuntimeIndicator(
+ message_ref=ref, body=body, thread_root_id=thread_root_id
+ )
elif state == "awaiting-input":
ref = await self._ping_operator(
channel_id, agent_name, notify_user, thread_root_id, deeplink_url
@@ -587,9 +591,29 @@ class TeamsAdapter(CollaborationAdapter):
)
async def _clear_working(self, channel_id: str, agent_name: str) -> None:
- ref = self._working_msg.pop((channel_id, agent_name), None)
- if ref is not None:
- await self.delete_message(channel_id, ref)
+ live = self._working_msg.pop((channel_id, agent_name), None)
+ if live is not None:
+ await self.delete_message(channel_id, live.message_ref)
+
+ async def _remove_runtime_indicator(
+ self, channel_id: str, message_ref: str
+ ) -> None:
+ """Drop a superseded indicator without letting a delete failure escape.
+
+ Unlike the other adapters, Teams' delete raises — on a missing connector
+ and on any non-2xx from the Bot Connector. When the indicator has
+ already been reposted elsewhere, a failure here means a stale duplicate
+ is left visible, which is preferable to aborting the turn."""
+ try:
+ await self.delete_message(channel_id, message_ref)
+ except (RuntimeError, httpx.HTTPError) as e:
+ logger.warning(
+ "Could not remove the superseded runtime indicator %s in %s (%s); "
+ "a stale copy may remain visible",
+ message_ref,
+ channel_id,
+ e,
+ )
async def _clear_input_pings(self, channel_id: str, agent_name: str) -> None:
refs = self._input_pings.pop((channel_id, agent_name), [])
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py
index 3bc8b9915..4fcae8061 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py
@@ -61,6 +61,9 @@ class _FakeAdapter:
def translate_inbound(self, content: str) -> str:
return content
+ def agents_with_live_runtime_state(self, channel_id: str) -> list[str]:
+ return []
+
def _fake_bridge() -> SimpleNamespace:
puppet = _FakePuppet()
@@ -75,7 +78,7 @@ def _fake_bridge() -> SimpleNamespace:
async def _record_message_map(**kwargs: str) -> None:
recorded.append(kwargs)
- return SimpleNamespace(
+ ns = SimpleNamespace(
_adapter=_FakeAdapter(),
_channel_to_room={"chan-1": ("room-1", "!room:s")},
_is_registered_agent=_is_registered_agent,
@@ -83,7 +86,13 @@ def _fake_bridge() -> SimpleNamespace:
_record_message_map=_record_message_map,
puppet=puppet,
recorded=recorded,
+ _indicator_move_timers={},
+ )
+ ns._move_indicators_for_addressees = (
+ BridgeCore._move_indicators_for_addressees.__get__(ns)
)
+ ns._schedule_indicator_move = BridgeCore._schedule_indicator_move.__get__(ns)
+ return ns
def _msg(
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py b/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py
new file mode 100644
index 000000000..fcc8dddc4
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py
@@ -0,0 +1,220 @@
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+
+
+class _FakeAdapter:
+ def __init__(self, live: list[str]) -> None:
+ self._live = live
+ self.moved: list[tuple[str, str]] = []
+
+ def agents_with_live_runtime_state(self, channel_id: str) -> list[str]:
+ return list(self._live)
+
+ async def reposition_runtime_state(self, channel_id: str, agent_name: str) -> None:
+ self.moved.append((channel_id, agent_name))
+
+
+def _bridge(live: list[str], *, aliases: dict[str, str] | None = None) -> Any:
+ """A BridgeCore stand-in wired to the real positioning methods."""
+ adapter = _FakeAdapter(live)
+ alias_map = aliases or {}
+
+ class _RoomStore:
+ async def get_agent_id_by_alias(
+ self, _session: Any, _room_id: str, alias: str
+ ) -> str | None:
+ return alias_map.get(alias.lower())
+
+ class _AgentStore:
+ async def get(self, _session: Any, agent_id: str) -> Any:
+ return SimpleNamespace(name=agent_id)
+
+ class _Session:
+ async def __aenter__(self) -> Any:
+ return self
+
+ async def __aexit__(self, *_exc: Any) -> None:
+ return None
+
+ ns = SimpleNamespace(
+ _adapter=adapter,
+ _room_store=_RoomStore(),
+ _agent_store=_AgentStore(),
+ _session_factory=lambda: _Session(),
+ _indicator_move_timers={},
+ adapter_spy=adapter,
+ )
+ for name in (
+ "_move_indicator_for_sender",
+ "_move_indicators_for_addressees",
+ "_live_agents_addressed_by_alias",
+ "_schedule_indicator_move",
+ "_run_indicator_move",
+ ):
+ setattr(ns, name, getattr(BridgeCore, name).__get__(ns))
+ return ns
+
+
+def _drain(bridge: Any, coro: Any) -> list[tuple[str, str]]:
+ """Run `coro`, then let every queued move fire, and report what moved."""
+
+ async def _go() -> None:
+ await coro
+ timers = list(bridge._indicator_move_timers.values())
+ # Fire the coalescing timers immediately rather than waiting them out.
+ for timer in timers:
+ timer.cancel()
+ for key in list(bridge._indicator_move_timers):
+ await bridge._run_indicator_move(key)
+
+ asyncio.run(_go())
+ return bridge.adapter_spy.moved
+
+
+def _addressees(bridge: Any, content: str, channel_type: str = "channel_public") -> Any:
+ return bridge._move_indicators_for_addressees(
+ channel_id="chan-1",
+ room_id="room-1",
+ channel_type=channel_type,
+ content=content,
+ mention_target=None,
+ )
+
+
+# ── Inbound: only agents the message addresses ──────────────────────────────
+
+
+def test_addressed_agent_indicator_follows_the_message() -> None:
+ bridge = _bridge(["agent-a"])
+
+ moved = _drain(bridge, _addressees(bridge, "@agent-a can you look at this?"))
+
+ assert moved == [("chan-1", "agent-a")]
+
+
+def test_unaddressed_chatter_leaves_the_indicator_alone() -> None:
+ # The whole point of scoping this per agent: a busy channel must not drag a
+ # working agent's indicator around on traffic that has nothing to do with it.
+ bridge = _bridge(["agent-a"])
+
+ moved = _drain(bridge, _addressees(bridge, "unrelated chatter between humans"))
+
+ assert moved == []
+
+
+def test_only_the_addressed_agent_of_several_moves() -> None:
+ bridge = _bridge(["agent-a", "agent-b"])
+
+ moved = _drain(bridge, _addressees(bridge, "@agent-b over to you"))
+
+ assert moved == [("chan-1", "agent-b")]
+
+
+def test_a_prefix_of_a_longer_name_is_not_treated_as_addressed() -> None:
+ bridge = _bridge(["agent-a"])
+
+ moved = _drain(bridge, _addressees(bridge, "@agent-a-2 please take this"))
+
+ assert moved == []
+
+
+def test_agent_addressed_by_its_room_alias_moves() -> None:
+ bridge = _bridge(["agent-a"], aliases={"worker": "agent-a"})
+
+ moved = _drain(bridge, _addressees(bridge, "@worker ping"))
+
+ assert moved == [("chan-1", "agent-a")]
+
+
+def test_every_message_addresses_the_agent_in_a_dm_room() -> None:
+ bridge = _bridge(["agent-a"])
+
+ moved = _drain(
+ bridge, _addressees(bridge, "no mention here", channel_type="direct")
+ )
+
+ assert moved == [("chan-1", "agent-a")]
+
+
+def test_nothing_is_scheduled_when_no_indicator_is_live() -> None:
+ bridge = _bridge([])
+
+ moved = _drain(bridge, _addressees(bridge, "@agent-a hello"))
+
+ assert moved == []
+
+
+# ── Outbound: the agent's own messages ──────────────────────────────────────
+
+
+def test_indicator_follows_a_message_the_agent_posts() -> None:
+ bridge = _bridge(["agent-a"])
+
+ moved = _drain(bridge, bridge._move_indicator_for_sender("chan-1", "agent-a"))
+
+ assert moved == [("chan-1", "agent-a")]
+
+
+def test_another_agents_message_does_not_move_this_indicator() -> None:
+ bridge = _bridge(["agent-a"])
+
+ moved = _drain(bridge, bridge._move_indicator_for_sender("chan-1", "agent-b"))
+
+ assert moved == []
+
+
+# ── Coalescing ──────────────────────────────────────────────────────────────
+
+
+def test_a_burst_of_messages_costs_a_single_move() -> None:
+ bridge = _bridge(["agent-a"])
+ scheduled: list[Any] = []
+
+ async def burst() -> None:
+ for _ in range(20):
+ await _addressees(bridge, "@agent-a another one")
+ scheduled.append(bridge._indicator_move_timers[("chan-1", "agent-a")])
+
+ moved = _drain(bridge, burst())
+
+ # One timer object throughout: later messages were absorbed into the queued
+ # move rather than each scheduling their own.
+ assert len(scheduled) == 20
+ assert all(timer is scheduled[0] for timer in scheduled)
+ assert moved == [("chan-1", "agent-a")]
+
+
+def test_a_later_message_does_not_push_the_queued_move_back() -> None:
+ # A sustained conversation must not starve the move by resetting its timer
+ # on every message, so the deadline is set once and left alone.
+ bridge = _bridge(["agent-a"])
+ deadlines: list[float] = []
+
+ async def burst() -> None:
+ for _ in range(3):
+ await _addressees(bridge, "@agent-a keep talking")
+ deadlines.append(
+ bridge._indicator_move_timers[("chan-1", "agent-a")].when()
+ )
+
+ _drain(bridge, burst())
+
+ assert len(set(deadlines)) == 1
+
+
+def test_a_platform_failure_during_a_move_does_not_escape() -> None:
+ # The indicator is cosmetic; a failed move must not propagate into the
+ # bridge callback that happened to trigger it.
+ bridge = _bridge(["agent-a"])
+
+ async def boom(_channel_id: str, _agent_name: str) -> None:
+ raise RuntimeError("platform down")
+
+ bridge._adapter.reposition_runtime_state = boom
+
+ asyncio.run(bridge._run_indicator_move(("chan-1", "agent-a")))
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py
index bfd970dba..8747c032f 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py
@@ -54,6 +54,9 @@ class _FakeAdapter:
self.batches: list[dict[str, Any]] = []
self.messages: list[dict[str, Any]] = []
+ def agents_with_live_runtime_state(self, channel_id: str) -> list[str]:
+ return []
+
async def send_attachment(
self,
channel_id,
@@ -132,6 +135,7 @@ def _fake_bridge(
recorded=recorded,
_outbound_groups={},
_outbound_group_timers={},
+ _indicator_move_timers={},
)
ns._find_channel = lambda room_id=None, matrix_room_id=None: (
"chan-1" if matrix_room_id == "!room:s" else None
@@ -145,6 +149,8 @@ def _fake_bridge(
ns
)
ns._relay_outbound_group = BridgeCore._relay_outbound_group.__get__(ns)
+ ns._move_indicator_for_sender = BridgeCore._move_indicator_for_sender.__get__(ns)
+ ns._schedule_indicator_move = BridgeCore._schedule_indicator_move.__get__(ns)
ns._flush_incomplete_outbound_group = (
BridgeCore._flush_incomplete_outbound_group.__get__(ns)
)
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
index 105f05805..526133e27 100644
--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
@@ -791,7 +791,10 @@ def test_runtime_state_working_posts_persistent_indicator() -> None:
assert len(webhook.sent) == 1
assert webhook.sent[0]["content"] == "⚙️ _Working on it…_"
assert webhook.sent[0]["username"] == "my-agent"
- assert adapter._working_msg[(str(CHANNEL_ID), "my-agent")] == f"{CHANNEL_ID}:901"
+ assert (
+ adapter._working_msg[(str(CHANNEL_ID), "my-agent")].message_ref
+ == f"{CHANNEL_ID}:901"
+ )
def test_runtime_state_detail_edits_message_in_place() -> None:
@@ -821,7 +824,10 @@ def test_runtime_state_detail_edits_message_in_place() -> None:
assert len(webhook.edits) == 1
assert webhook.edits[0]["message_id"] == 901
assert webhook.edits[0]["content"] == "⚙️ Editing adapter.py"
- assert adapter._working_msg[(str(CHANNEL_ID), "my-agent")] == f"{CHANNEL_ID}:901"
+ assert (
+ adapter._working_msg[(str(CHANNEL_ID), "my-agent")].message_ref
+ == f"{CHANNEL_ID}:901"
+ )
def test_runtime_state_idle_clears_working_message() -> None:
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py
new file mode 100644
index 000000000..ea443519c
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py
@@ -0,0 +1,161 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from switch_core.bridges.collaboration.adapter import LiveRuntimeIndicator
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ MattermostConnectionConfig,
+)
+
+
+def _adapter() -> MattermostAdapter:
+ return MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mm",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _Recorder:
+ """Records the adapter's platform calls, with a togglable hard delete."""
+
+ def __init__(self, *, hard_delete_works: bool) -> None:
+ self.hard_delete_works = hard_delete_works
+ self.hard_deletes: list[str] = []
+ self.patches: list[tuple[str, str]] = []
+ self.sends: list[tuple[str, str, str, str | None]] = []
+ self._next_id = iter(["post-2", "post-3", "post-4"])
+
+ def install(self, adapter: MattermostAdapter) -> None:
+ async def permanent_delete(post_id: str) -> bool:
+ self.hard_deletes.append(post_id)
+ return self.hard_delete_works
+
+ async def patch_post_as(agent_name: str, post_id: str, content: str) -> None:
+ self.patches.append((post_id, content))
+
+ async def send_message(
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ self.sends.append((channel_id, sender_name, content, thread_root_id))
+ return next(self._next_id)
+
+ adapter._permanent_delete = permanent_delete # type: ignore[method-assign]
+ adapter._patch_post_as = patch_post_as # type: ignore[method-assign]
+ adapter.send_message = send_message # type: ignore[method-assign]
+
+
+def _seed_indicator(
+ adapter: MattermostAdapter, *, thread_root_id: str | None = None
+) -> None:
+ adapter._working_msg[("chan-1", "worker")] = LiveRuntimeIndicator(
+ message_ref="post-1",
+ body="⚙️ _Working on it…_",
+ thread_root_id=thread_root_id,
+ )
+
+
+def test_reposition_deletes_before_reposting_when_hard_delete_works() -> None:
+ # Mattermost inverts the usual post-then-delete order: the old post must be
+ # provably gone before a replacement is posted, or a failure would strand a
+ # marker in the channel.
+ adapter = _adapter()
+ recorder = _Recorder(hard_delete_works=True)
+ recorder.install(adapter)
+ _seed_indicator(adapter, thread_root_id="root-9")
+
+ _run(adapter.reposition_runtime_state("chan-1", "worker"))
+
+ assert recorder.hard_deletes == ["post-1"]
+ assert recorder.sends == [("chan-1", "worker", "⚙️ _Working on it…_", "root-9")]
+ assert recorder.patches == []
+ assert adapter._working_msg[("chan-1", "worker")].message_ref == "post-2"
+
+
+def test_reposition_abandoned_when_hard_delete_is_unavailable() -> None:
+ # Without a hard delete, moving would leave a "✓ done" marker behind on
+ # every message. The indicator stays where it is instead.
+ adapter = _adapter()
+ recorder = _Recorder(hard_delete_works=False)
+ recorder.install(adapter)
+ _seed_indicator(adapter)
+
+ _run(adapter.reposition_runtime_state("chan-1", "worker"))
+
+ assert recorder.sends == []
+ assert recorder.patches == []
+ assert adapter._working_msg[("chan-1", "worker")].message_ref == "post-1"
+
+
+def test_unavailable_hard_delete_is_warned_once_per_channel() -> None:
+ adapter = _adapter()
+ recorder = _Recorder(hard_delete_works=False)
+ recorder.install(adapter)
+ _seed_indicator(adapter)
+
+ _run(adapter.reposition_runtime_state("chan-1", "worker"))
+ _run(adapter.reposition_runtime_state("chan-1", "worker"))
+
+ assert adapter._no_hard_delete_warned == {"chan-1"}
+
+
+def test_reposition_is_a_noop_without_a_live_indicator() -> None:
+ adapter = _adapter()
+ recorder = _Recorder(hard_delete_works=True)
+ recorder.install(adapter)
+
+ _run(adapter.reposition_runtime_state("chan-1", "worker"))
+
+ assert recorder.hard_deletes == []
+ assert recorder.sends == []
+
+
+def test_failed_repost_after_delete_drops_the_stale_ref() -> None:
+ # The old post is already gone here, so there is nothing to fall back to —
+ # the tracked ref must not keep pointing at a deleted post.
+ adapter = _adapter()
+ recorder = _Recorder(hard_delete_works=True)
+ recorder.install(adapter)
+ _seed_indicator(adapter)
+
+ async def failing_send(*_args: Any, **_kwargs: Any) -> None:
+ return None
+
+ adapter.send_message = failing_send # type: ignore[method-assign]
+ _run(adapter.reposition_runtime_state("chan-1", "worker"))
+
+ assert ("chan-1", "worker") not in adapter._working_msg
+
+
+def test_idle_still_falls_back_to_a_terminal_marker() -> None:
+ # Turn end is unchanged: without a hard delete the post is edited rather
+ # than soft deleted, so no "(message deleted)" tombstone is left.
+ adapter = _adapter()
+ recorder = _Recorder(hard_delete_works=False)
+ recorder.install(adapter)
+ _seed_indicator(adapter)
+
+ _run(
+ adapter.apply_runtime_state(
+ "chan-1", "worker", "idle", notify_user=None, thread_root_id=None
+ )
+ )
+
+ assert recorder.patches == [("post-1", "✓ done")]
+ assert ("chan-1", "worker") not in adapter._working_msg
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
index b81a67464..530e3fa67 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
@@ -616,7 +616,7 @@ def test_runtime_state_working_posts_generic_indicator() -> None:
assert len(fake.calls) == 1
assert fake.calls[0]["text"] == "⚙️ _Working on it…_"
- assert adapter._working_msg[("C123", "agent-bot")] == "C123:999.9"
+ assert adapter._working_msg[("C123", "agent-bot")].message_ref == "C123:999.9"
def test_runtime_state_detail_edits_message_in_place() -> None:
@@ -648,7 +648,7 @@ def test_runtime_state_detail_edits_message_in_place() -> None:
assert fake.updates[0]["ts"] == "999.9"
assert fake.updates[0]["text"] == "⚙️ Editing room-connection.ts"
# The tracked ref is unchanged.
- assert adapter._working_msg[("C123", "agent-bot")] == "C123:999.9"
+ assert adapter._working_msg[("C123", "agent-bot")].message_ref == "C123:999.9"
def test_runtime_state_idle_clears_working_message() -> None:
@@ -671,6 +671,87 @@ def test_runtime_state_idle_clears_working_message() -> None:
assert ("C123", "agent-bot") not in adapter._working_msg
+# ── Runtime state (following the latest message) ────────────────────────────
+
+
+def test_reposition_reposts_indicator_below_newer_traffic() -> None:
+ adapter = _adapter()
+ fake = _FakeWebClient()
+ adapter._web_client = fake # type: ignore[assignment]
+
+ _run(
+ adapter.apply_runtime_state(
+ "C123",
+ "agent-bot",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ detail="Editing adapter.py",
+ )
+ )
+ _run(adapter.reposition_runtime_state("C123", "agent-bot"))
+
+ # Reposted verbatim, then the original removed — never edited in place.
+ assert len(fake.calls) == 2
+ assert fake.calls[1]["text"] == "⚙️ Editing adapter.py"
+ assert fake.updates == []
+ assert fake.deletes == [{"channel": "C123", "ts": "999.9"}]
+ assert adapter._working_msg[("C123", "agent-bot")].message_ref == "C123:888.8"
+
+
+def test_reposition_keeps_the_indicator_in_its_thread() -> None:
+ adapter = _adapter()
+ fake = _FakeWebClient()
+ adapter._web_client = fake # type: ignore[assignment]
+
+ _run(
+ adapter.apply_runtime_state(
+ "C123",
+ "agent-bot",
+ "working",
+ notify_user=None,
+ thread_root_id="C123:111.1",
+ )
+ )
+ _run(adapter.reposition_runtime_state("C123", "agent-bot"))
+
+ assert fake.calls[1]["thread_ts"] == "111.1"
+
+
+def test_reposition_is_a_noop_without_a_live_indicator() -> None:
+ adapter = _adapter()
+ fake = _FakeWebClient()
+ adapter._web_client = fake # type: ignore[assignment]
+
+ _run(adapter.reposition_runtime_state("C123", "agent-bot"))
+
+ assert fake.calls == []
+ assert fake.deletes == []
+
+
+def test_reposition_leaves_the_original_when_the_repost_fails() -> None:
+ # A move must never end with no indicator at all: if the replacement cannot
+ # be posted, the original stays where it is rather than being deleted.
+ adapter = _adapter()
+ fake = _FakeWebClient()
+ adapter._web_client = fake # type: ignore[assignment]
+
+ _run(
+ adapter.apply_runtime_state(
+ "C123", "agent-bot", "working", notify_user=None, thread_root_id=None
+ )
+ )
+
+ async def failing_send(*_args: Any, **_kwargs: Any) -> None:
+ return None
+
+ adapter.send_message = failing_send # type: ignore[method-assign]
+ _run(adapter.reposition_runtime_state("C123", "agent-bot"))
+
+ assert fake.deletes == []
+ assert adapter._working_msg[("C123", "agent-bot")].message_ref == "C123:999.9"
+
+
# ── Self-mention (tagging the app) ───────────────────────────────────────────
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
index 8b516479b..d2048b92e 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
@@ -907,7 +907,7 @@ def test_working_posts_status_card() -> None:
)
assert len(fake.threads) == 1
- assert adapter._working_msg[("19:[email protected]", "worker")] == "M1"
+ assert adapter._working_msg[("19:[email protected]", "worker")].message_ref == "M1"
def test_working_detail_refreshes_in_place() -> None:
@@ -939,7 +939,7 @@ def test_working_detail_refreshes_in_place() -> None:
assert len(fake.threads) == 1
assert len(fake.updates) == 1
assert fake.updates[0]["activity_id"] == "M1"
- assert adapter._working_msg[("19:[email protected]", "worker")] == "M1"
+ assert adapter._working_msg[("19:[email protected]", "worker")].message_ref == "M1"
def test_idle_clears_working_message() -> None:
@@ -996,7 +996,7 @@ def test_awaiting_input_keeps_working_and_pings() -> None:
)
# Working indicator stays up; a ping is tracked separately.
- assert adapter._working_msg[key] == "M1"
+ assert adapter._working_msg[key].message_ref == "M1"
assert adapter._input_pings[key] == ["M2"]
_run(