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): let the runtime indicator follow the agent between threads (CHOO-1104)

Louis Amaudruz5e17ac1482a3
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 68f21a66c..121c8cec3 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -229,8 +229,10 @@ class CollaborationAdapter(ABC):
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.
+ async def reposition_runtime_state(
+ self, channel_id: str, agent_name: str, thread_root_id: str | None
+ ) -> None:
+ """Move the agent's live runtime indicator to follow the latest message.
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.
@@ -238,6 +240,11 @@ class CollaborationAdapter(ABC):
indicator is therefore never briefly absent, and a failed repost leaves
the original in place rather than clearing it.
+ ``thread_root_id`` is the thread that message belonged to, and is where
+ the indicator lands — so it follows the agent between threads (and back
+ out to the channel root) rather than being stranded in whichever thread
+ the turn happened to start in.
+
Adapters that render runtime state as a typing indicator have nothing
positional to move, so the default does nothing.
"""
@@ -246,9 +253,7 @@ class CollaborationAdapter(ABC):
if live is None:
return
- ref = await self.send_message(
- channel_id, agent_name, live.body, live.thread_root_id
- )
+ ref = await self.send_message(channel_id, agent_name, live.body, thread_root_id)
if ref is None:
logger.warning(
"Could not repost the runtime indicator for %s in %s; leaving it "
@@ -258,7 +263,9 @@ class CollaborationAdapter(ABC):
)
return
- self._working_msg[key] = replace(live, message_ref=ref)
+ self._working_msg[key] = replace(
+ live, message_ref=ref, thread_root_id=thread_root_id
+ )
await self._remove_runtime_indicator(channel_id, live.message_ref)
async def _remove_runtime_indicator(
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index bf7f578a7..f684b56a2 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -146,8 +146,10 @@ class BridgeCore:
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.
+ # below newly-arrived traffic, and the thread each should land in.
+ # See _schedule_indicator_move.
self._indicator_move_timers: dict[tuple[str, str], asyncio.TimerHandle] = {}
+ self._indicator_move_targets: dict[tuple[str, str], str | None] = {}
@property
def adapter(self) -> CollaborationAdapter:
@@ -448,6 +450,7 @@ class BridgeCore:
channel_type=msg.channel_type,
content=content,
mention_target=mention_target,
+ thread_root_id=msg.root_id,
)
return
@@ -500,6 +503,7 @@ class BridgeCore:
channel_type=msg.channel_type,
content=content,
mention_target=mention_target,
+ thread_root_id=msg.root_id,
)
async def _handle_inbound_command(self, cmd: InboundCommand) -> None:
@@ -1016,7 +1020,9 @@ class BridgeCore:
)
if sender_name is not None:
- await self._move_indicator_for_sender(channel_id, sender_name)
+ await self._move_indicator_for_sender(
+ channel_id, sender_name, thread_root_ref
+ )
async def _outbound_thread_root_ref(
self, event_content: dict[str, object], channel_id: str
@@ -1166,7 +1172,7 @@ class BridgeCore:
external_post_id=message_ref,
)
- await self._move_indicator_for_sender(channel_id, sender_name)
+ await self._move_indicator_for_sender(channel_id, sender_name, thread_root_ref)
def _schedule_outbound_group_flush(
self,
@@ -1250,7 +1256,7 @@ class BridgeCore:
external_post_id=message_ref,
)
- await self._move_indicator_for_sender(channel_id, sender_name)
+ await self._move_indicator_for_sender(channel_id, sender_name, thread_root_ref)
async def _download_matrix_media(
self, client: ClientBase[Any], mxc: str | None, filename: str
@@ -1355,11 +1361,11 @@ class BridgeCore:
# ── Runtime-indicator positioning ─────────────────────────────────────────
async def _move_indicator_for_sender(
- self, channel_id: str, agent_name: str
+ self, channel_id: str, agent_name: str, thread_root_id: str | None
) -> 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)
+ self._schedule_indicator_move(channel_id, agent_name, thread_root_id)
async def _move_indicators_for_addressees(
self,
@@ -1369,6 +1375,7 @@ class BridgeCore:
channel_type: ChannelType,
content: str,
mention_target: str | None,
+ thread_root_id: str | None,
) -> None:
"""Follow an inbound message, for each addressed agent working here.
@@ -1381,7 +1388,7 @@ class BridgeCore:
# 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)
+ self._schedule_indicator_move(channel_id, agent_name, thread_root_id)
return
stripped = strip_emphasis(content)
@@ -1400,7 +1407,7 @@ class BridgeCore:
)
for agent_name in addressed:
- self._schedule_indicator_move(channel_id, agent_name)
+ self._schedule_indicator_move(channel_id, agent_name, thread_root_id)
async def _live_agents_addressed_by_alias(
self, room_id: str, content: str, candidates: list[str]
@@ -1431,15 +1438,23 @@ class BridgeCore:
matched.add(name)
return matched
- def _schedule_indicator_move(self, channel_id: str, agent_name: str) -> None:
+ def _schedule_indicator_move(
+ self, channel_id: str, agent_name: str, thread_root_id: str | None
+ ) -> 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.
+
+ ``thread_root_id`` is the thread the triggering message belongs to, and
+ the one the indicator will land in. A coalesced burst keeps the most
+ recent one, so the indicator follows the conversation's latest thread
+ rather than the one that opened the window.
"""
key = (channel_id, agent_name)
+ self._indicator_move_targets[key] = thread_root_id
if key in self._indicator_move_timers:
return
@@ -1451,9 +1466,12 @@ class BridgeCore:
async def _run_indicator_move(self, key: tuple[str, str]) -> None:
self._indicator_move_timers.pop(key, None)
+ thread_root_id = self._indicator_move_targets.pop(key, None)
channel_id, agent_name = key
try:
- await self._adapter.reposition_runtime_state(channel_id, agent_name)
+ await self._adapter.reposition_runtime_state(
+ channel_id, agent_name, thread_root_id
+ )
except Exception:
# The indicator is cosmetic; a platform failure here must not take
# down the bridge callback that happened to trigger it.
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index f4b38ccd7..cd4dc8467 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -503,7 +503,9 @@ 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:
+ async def reposition_runtime_state(
+ self, channel_id: str, agent_name: str, thread_root_id: str | None
+ ) -> 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
@@ -533,9 +535,7 @@ class MattermostAdapter(CollaborationAdapter):
)
return
- ref = await self.send_message(
- channel_id, agent_name, live.body, live.thread_root_id
- )
+ ref = await self.send_message(channel_id, agent_name, live.body, 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)
@@ -546,7 +546,9 @@ class MattermostAdapter(CollaborationAdapter):
channel_id,
)
return
- self._working_msg[key] = replace(live, message_ref=ref)
+ self._working_msg[key] = replace(
+ live, message_ref=ref, thread_root_id=thread_root_id
+ )
async def _dispose_working(self, channel_id: str, agent_name: str) -> None:
"""Remove the live "working on it…" message when the turn ends.
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
index fcc8dddc4..69a69eca2 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py
@@ -11,12 +11,16 @@ class _FakeAdapter:
def __init__(self, live: list[str]) -> None:
self._live = live
self.moved: list[tuple[str, str]] = []
+ self.targets: list[str | None] = []
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:
+ async def reposition_runtime_state(
+ self, channel_id: str, agent_name: str, thread_root_id: str | None
+ ) -> None:
self.moved.append((channel_id, agent_name))
+ self.targets.append(thread_root_id)
def _bridge(live: list[str], *, aliases: dict[str, str] | None = None) -> Any:
@@ -47,6 +51,7 @@ def _bridge(live: list[str], *, aliases: dict[str, str] | None = None) -> Any:
_agent_store=_AgentStore(),
_session_factory=lambda: _Session(),
_indicator_move_timers={},
+ _indicator_move_targets={},
adapter_spy=adapter,
)
for name in (
@@ -76,13 +81,19 @@ def _drain(bridge: Any, coro: Any) -> list[tuple[str, str]]:
return bridge.adapter_spy.moved
-def _addressees(bridge: Any, content: str, channel_type: str = "channel_public") -> Any:
+def _addressees(
+ bridge: Any,
+ content: str,
+ channel_type: str = "channel_public",
+ thread_root_id: str | None = None,
+) -> Any:
return bridge._move_indicators_for_addressees(
channel_id="chan-1",
room_id="room-1",
channel_type=channel_type,
content=content,
mention_target=None,
+ thread_root_id=thread_root_id,
)
@@ -155,7 +166,7 @@ def test_nothing_is_scheduled_when_no_indicator_is_live() -> None:
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"))
+ moved = _drain(bridge, bridge._move_indicator_for_sender("chan-1", "agent-a", None))
assert moved == [("chan-1", "agent-a")]
@@ -163,11 +174,45 @@ def test_indicator_follows_a_message_the_agent_posts() -> None:
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"))
+ moved = _drain(bridge, bridge._move_indicator_for_sender("chan-1", "agent-b", None))
assert moved == []
+# ── Threads ─────────────────────────────────────────────────────────────────
+
+
+def test_the_move_targets_the_thread_the_message_arrived_in() -> None:
+ bridge = _bridge(["agent-a"])
+
+ _drain(bridge, _addressees(bridge, "@agent-a in here", thread_root_id="root-7"))
+
+ assert bridge.adapter_spy.targets == ["root-7"]
+
+
+def test_a_coalesced_burst_lands_in_the_most_recent_thread() -> None:
+ # The indicator should follow where the conversation ended up, not where it
+ # was when the coalescing window opened.
+ bridge = _bridge(["agent-a"])
+
+ async def burst() -> None:
+ await _addressees(bridge, "@agent-a first", thread_root_id="root-1")
+ await _addressees(bridge, "@agent-a second", thread_root_id="root-2")
+ await _addressees(bridge, "@agent-a third", thread_root_id="root-3")
+
+ _drain(bridge, burst())
+
+ assert bridge.adapter_spy.targets == ["root-3"]
+
+
+def test_a_message_at_the_channel_root_brings_the_indicator_back_out() -> None:
+ bridge = _bridge(["agent-a"])
+
+ _drain(bridge, _addressees(bridge, "@agent-a out here", thread_root_id=None))
+
+ assert bridge.adapter_spy.targets == [None]
+
+
# ── Coalescing ──────────────────────────────────────────────────────────────
@@ -212,7 +257,9 @@ def test_a_platform_failure_during_a_move_does_not_escape() -> None:
# bridge callback that happened to trigger it.
bridge = _bridge(["agent-a"])
- async def boom(_channel_id: str, _agent_name: str) -> None:
+ async def boom(
+ _channel_id: str, _agent_name: str, _thread_root_id: str | None
+ ) -> None:
raise RuntimeError("platform down")
bridge._adapter.reposition_runtime_state = boom
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
index ea443519c..014bfd3dc 100644
--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py
@@ -80,7 +80,7 @@ def test_reposition_deletes_before_reposting_when_hard_delete_works() -> None:
recorder.install(adapter)
_seed_indicator(adapter, thread_root_id="root-9")
- _run(adapter.reposition_runtime_state("chan-1", "worker"))
+ _run(adapter.reposition_runtime_state("chan-1", "worker", "root-9"))
assert recorder.hard_deletes == ["post-1"]
assert recorder.sends == [("chan-1", "worker", "⚙️ _Working on it…_", "root-9")]
@@ -88,6 +88,18 @@ def test_reposition_deletes_before_reposting_when_hard_delete_works() -> None:
assert adapter._working_msg[("chan-1", "worker")].message_ref == "post-2"
+def test_reposition_rehomes_into_the_thread_of_the_latest_message() -> None:
+ 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", "root-42"))
+
+ assert recorder.sends == [("chan-1", "worker", "⚙️ _Working on it…_", "root-42")]
+ assert adapter._working_msg[("chan-1", "worker")].thread_root_id == "root-42"
+
+
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.
@@ -96,7 +108,7 @@ def test_reposition_abandoned_when_hard_delete_is_unavailable() -> None:
recorder.install(adapter)
_seed_indicator(adapter)
- _run(adapter.reposition_runtime_state("chan-1", "worker"))
+ _run(adapter.reposition_runtime_state("chan-1", "worker", None))
assert recorder.sends == []
assert recorder.patches == []
@@ -109,8 +121,8 @@ def test_unavailable_hard_delete_is_warned_once_per_channel() -> None:
recorder.install(adapter)
_seed_indicator(adapter)
- _run(adapter.reposition_runtime_state("chan-1", "worker"))
- _run(adapter.reposition_runtime_state("chan-1", "worker"))
+ _run(adapter.reposition_runtime_state("chan-1", "worker", None))
+ _run(adapter.reposition_runtime_state("chan-1", "worker", None))
assert adapter._no_hard_delete_warned == {"chan-1"}
@@ -120,7 +132,7 @@ def test_reposition_is_a_noop_without_a_live_indicator() -> None:
recorder = _Recorder(hard_delete_works=True)
recorder.install(adapter)
- _run(adapter.reposition_runtime_state("chan-1", "worker"))
+ _run(adapter.reposition_runtime_state("chan-1", "worker", None))
assert recorder.hard_deletes == []
assert recorder.sends == []
@@ -138,7 +150,7 @@ def test_failed_repost_after_delete_drops_the_stale_ref() -> None:
return None
adapter.send_message = failing_send # type: ignore[method-assign]
- _run(adapter.reposition_runtime_state("chan-1", "worker"))
+ _run(adapter.reposition_runtime_state("chan-1", "worker", None))
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 530e3fa67..78ff7782e 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
@@ -689,7 +689,7 @@ def test_reposition_reposts_indicator_below_newer_traffic() -> None:
detail="Editing adapter.py",
)
)
- _run(adapter.reposition_runtime_state("C123", "agent-bot"))
+ _run(adapter.reposition_runtime_state("C123", "agent-bot", None))
# Reposted verbatim, then the original removed — never edited in place.
assert len(fake.calls) == 2
@@ -699,7 +699,7 @@ def test_reposition_reposts_indicator_below_newer_traffic() -> None:
assert adapter._working_msg[("C123", "agent-bot")].message_ref == "C123:888.8"
-def test_reposition_keeps_the_indicator_in_its_thread() -> None:
+def test_reposition_stays_in_the_thread_when_the_message_is_in_it() -> None:
adapter = _adapter()
fake = _FakeWebClient()
adapter._web_client = fake # type: ignore[assignment]
@@ -713,17 +713,59 @@ def test_reposition_keeps_the_indicator_in_its_thread() -> None:
thread_root_id="C123:111.1",
)
)
- _run(adapter.reposition_runtime_state("C123", "agent-bot"))
+ _run(adapter.reposition_runtime_state("C123", "agent-bot", "C123:111.1"))
assert fake.calls[1]["thread_ts"] == "111.1"
+def test_reposition_follows_the_agent_into_a_different_thread() -> None:
+ # The indicator re-homes rather than being stranded in whichever thread the
+ # turn happened to open in.
+ 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", "C123:222.2"))
+
+ assert fake.calls[1]["thread_ts"] == "222.2"
+ assert adapter._working_msg[("C123", "agent-bot")].thread_root_id == "C123:222.2"
+
+
+def test_reposition_follows_the_agent_back_out_to_the_channel_root() -> 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", None))
+
+ assert fake.calls[1]["thread_ts"] is None
+ assert adapter._working_msg[("C123", "agent-bot")].thread_root_id is None
+
+
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"))
+ _run(adapter.reposition_runtime_state("C123", "agent-bot", None))
assert fake.calls == []
assert fake.deletes == []
@@ -746,7 +788,7 @@ def test_reposition_leaves_the_original_when_the_repost_fails() -> None:
return None
adapter.send_message = failing_send # type: ignore[method-assign]
- _run(adapter.reposition_runtime_state("C123", "agent-bot"))
+ _run(adapter.reposition_runtime_state("C123", "agent-bot", None))
assert fake.deletes == []
assert adapter._working_msg[("C123", "agent-bot")].message_ref == "C123:999.9"