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(mattermost): mark the message an agent is working on with πŸ‘€ (CHOO-2317) (#277)

Louis Amaudruz6657e8d0ea24
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 122b46037..cef73499b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,15 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+- Mattermost marks the message an agent is working on with **πŸ‘€**, added when the
+ turn opens and removed when it ends. Inside a thread the mark goes on the
+ reply that asked rather than the root it hangs off, and an agent handling two
+ messages at once clears both together instead of leaving the first marked for
+ good. The reaction is added by the agent's own bot, so two agents on one
+ message read as two marks naming who is on it. Documented alongside it:
+ Mattermost has no equivalent of Slack's native progress card, and Switch does
+ not approximate one (CHOO-2317).
#### Changed
- The gateway's **Docs** button opens the published documentation at
`docs.flintai.dev` rather than the GitHub repository (CHOO-2313).
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index ae38e5ee1..8e81b529f 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -51,6 +51,9 @@ _MAX_BOT_ICON_BYTES = 5 * 1024 * 1024
# becomes a room when someone actually writes in it.
_JOINABLE_MM_CHANNEL_TYPES = frozenset({"O", "P"})
+# Emoji marking the message an agent is currently working on.
+_WORKING_REACTION = "eyes"
+
class MattermostConnectionConfig(BridgeConnectionConfig):
url: str
@@ -99,6 +102,25 @@ class MattermostAdapter(CollaborationAdapter):
self._seen_post_ids_max = 1000
self._seen_lock = threading.Lock()
+ # (channel_id, thread root post id) -> the post that actually asked.
+ # Inside a thread that is the reply, not the root the reply hangs off.
+ # Bounded like _seen_post_ids: it grows with inbound traffic and only
+ # the recent entries can still be the subject of a live turn.
+ self._thread_trigger: OrderedDict[tuple[str, str], str] = OrderedDict()
+ self._thread_trigger_max = 1000
+ self._thread_trigger_lock = threading.Lock()
+
+ # (agent_name, post_id) currently carrying the working reaction. A
+ # reaction belongs to the bot that added it, so two agents on the same
+ # post are two independent marks.
+ self._eyes: set[tuple[str, str]] = set()
+
+ # (channel_id, agent_name) -> the posts that agent has marked. An agent
+ # asked two things at once works on both, and the turn ends once β€” so
+ # the marks are cleared together rather than only on the last thread
+ # touched.
+ self._agent_eyes: dict[tuple[str, str], set[str]] = {}
+
self._main_loop: asyncio.AbstractEventLoop | None = None
# channel id -> channel name (URL slug), for building channel deeplinks.
@@ -502,7 +524,12 @@ class MattermostAdapter(CollaborationAdapter):
into a "done" marker, and resolve any pings the same way.
- ``awaiting-input`` β†’ leave the working message up; post a separate
operator ping (tracked for resolution when the turn ends).
+
+ The message that triggered the turn is marked with πŸ‘€ throughout, and
+ unmarked when it ends β€” see ``_track_eyes``.
"""
+ await self._track_eyes(channel_id, agent_name, state, thread_root_id)
+
key = (channel_id, agent_name)
if state == "working":
# Resuming work means the requested input was provided β€” remove the
@@ -555,6 +582,113 @@ class MattermostAdapter(CollaborationAdapter):
agent_name, post_id, self.translate_outbound("βœ“ Input received")
)
+ # ── The eyes on the message being worked on ──────────────────────────────
+
+ def _remember_trigger(self, channel_id: str, root_id: str, post_id: str) -> None:
+ """Record the latest post in a thread, so the eyes land on what asked.
+
+ Written from the websocket thread and read from the main loop, hence
+ the lock. Oldest entries are dropped past the cap: a thread nobody has
+ written in for a thousand messages is not the subject of a live turn,
+ and losing the entry only puts the mark on the thread root.
+ """
+ with self._thread_trigger_lock:
+ self._thread_trigger[(channel_id, root_id)] = post_id
+ self._thread_trigger.move_to_end((channel_id, root_id))
+ while len(self._thread_trigger) > self._thread_trigger_max:
+ self._thread_trigger.popitem(last=False)
+
+ async def _track_eyes(
+ self,
+ channel_id: str,
+ agent_name: str,
+ state: str,
+ thread_root_id: str | None,
+ ) -> None:
+ """Mark every message this agent is working on, and clear them together.
+
+ ``thread_root_id`` is where the answer will land: the thread the agent
+ was addressed in, or β€” since this adapter follows the anchor β€” the
+ message itself when it was addressed at the channel root. The mark
+ belongs on what was actually said, so a threaded turn is traced back
+ through ``_thread_trigger`` to the reply that asked rather than being
+ put on the root it hangs off.
+ """
+ akey = (channel_id, agent_name)
+
+ if state in ("working", "awaiting-input"):
+ if thread_root_id is None:
+ return
+ asked_on = self._thread_trigger.get(
+ (channel_id, thread_root_id), thread_root_id
+ )
+ self._agent_eyes.setdefault(akey, set()).add(asked_on)
+ await self._mark_being_read(agent_name, asked_on, working=True)
+ return
+
+ for post_id in sorted(self._agent_eyes.pop(akey, set())):
+ await self._mark_being_read(agent_name, post_id, working=False)
+
+ async def _mark_being_read(
+ self, agent_name: str, post_id: str, *, working: bool
+ ) -> None:
+ """Put πŸ‘€ on the post an agent is working on, and take it off after.
+
+ Added by the agent's own bot rather than the bridge account, so the
+ reaction says *which* agent picked the message up and two agents on one
+ message read as two. This is the progress signal that always works:
+ unlike the status post it needs no thread, and unlike the typing
+ indicator it does not expire.
+ """
+ key = (agent_name, post_id)
+ if working == (key in self._eyes):
+ return
+
+ bot_info = self._agent_bots.get(agent_name)
+ driver = self._bot_drivers.get(agent_name)
+ loop = self._main_loop
+ if not bot_info or driver is None or loop is None:
+ logger.warning(
+ "Cannot %s the working reaction for %s: no connected bot",
+ "add" if working else "remove",
+ agent_name,
+ )
+ return
+ user_id = bot_info["user_id"]
+
+ try:
+ if working:
+ await loop.run_in_executor(
+ None,
+ driver.reactions.create_reaction,
+ {
+ "user_id": user_id,
+ "post_id": post_id,
+ "emoji_name": _WORKING_REACTION,
+ },
+ )
+ self._eyes.add(key)
+ else:
+ await loop.run_in_executor(
+ None,
+ driver.reactions.delete_reaction,
+ user_id,
+ post_id,
+ _WORKING_REACTION,
+ )
+ self._eyes.discard(key)
+ except Exception as e:
+ # Cosmetic, and the post may simply be gone. Record nothing and
+ # keep the turn going.
+ logger.warning(
+ "Could not %s the working reaction on %s: %s",
+ "add" if working else "remove",
+ post_id,
+ e,
+ )
+ if not working:
+ self._eyes.discard(key)
+
async def _reposition_runtime_state(
self, channel_id: str, agent_name: str, thread_root_id: str | None
) -> None:
@@ -1186,6 +1320,7 @@ class MattermostAdapter(CollaborationAdapter):
message = post.get("message", "")
# Mattermost sets root_id to the thread root for replies, "" otherwise.
root_id = post.get("root_id", "") or None
+ self._remember_trigger(channel_id, root_id or post_id, post_id)
mm_channel_type = data.get("channel_type", "")
channel_name = str(data.get("channel_display_name", "")) or None
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_working_reaction.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_working_reaction.py
new file mode 100644
index 000000000..8112599b2
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_working_reaction.py
@@ -0,0 +1,254 @@
+"""The πŸ‘€ Mattermost puts on the message an agent is working on.
+
+Mattermost has no equivalent of Slack's native progress card, and its typing
+indicator expires after a few seconds. The reaction is therefore the one
+progress signal here that is both immediate and durable β€” and unlike the status
+post, it says *which* message was picked up.
+
+It is added by the agent's own bot rather than a shared bridge account, so two
+agents working on one message show as two marks.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ MattermostConnectionConfig,
+)
+
+
+class _FakeReactions:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, str, str, str]] = []
+ self.error: Exception | None = None
+
+ def create_reaction(self, options: dict[str, str]) -> dict[str, str]:
+ if self.error:
+ raise self.error
+ self.calls.append(
+ ("add", options["user_id"], options["post_id"], options["emoji_name"])
+ )
+ return options
+
+ def delete_reaction(
+ self, user_id: str, post_id: str, emoji_name: str
+ ) -> dict[str, str]:
+ if self.error:
+ raise self.error
+ self.calls.append(("remove", user_id, post_id, emoji_name))
+ return {"status": "OK"}
+
+
+class _FakeDriver:
+ def __init__(self) -> None:
+ self.reactions = _FakeReactions()
+
+
+def _adapter(*agents: str) -> MattermostAdapter:
+ adapter = MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mm",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+ for name in agents or ("worker",):
+ adapter._agent_bots[name] = {"user_id": f"bot-{name}"}
+ adapter._bot_drivers[name] = _FakeDriver() # type: ignore[assignment]
+
+ async def send_message(
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ return "status-post"
+
+ async def patch_post_as(agent_name: str, post_id: str, content: str) -> None:
+ return None
+
+ async def post_typing(
+ channel_id: str, sender_name: str, thread_root_id: str | None
+ ) -> None:
+ return None
+
+ adapter.send_message = send_message # type: ignore[method-assign]
+ adapter._patch_post_as = patch_post_as # type: ignore[method-assign]
+ adapter._post_typing = post_typing # type: ignore[method-assign]
+ return adapter
+
+
+def _reactions(
+ adapter: MattermostAdapter, agent: str = "worker"
+) -> list[tuple[str, ...]]:
+ driver: Any = adapter._bot_drivers[agent]
+ return driver.reactions.calls
+
+
+def _run(adapter: MattermostAdapter, *states: tuple[str, str | None]) -> None:
+ """Drive the adapter through runtime states with a live main loop set."""
+
+ async def _body() -> None:
+ adapter._main_loop = asyncio.get_running_loop()
+ for state, thread_root_id in states:
+ await adapter.apply_runtime_state(
+ "chan-1",
+ "worker",
+ state,
+ mention_handle=None,
+ thread_root_id=thread_root_id,
+ )
+
+ asyncio.run(_body())
+
+
+def test_the_message_being_worked_on_gets_the_eyes() -> None:
+ adapter = _adapter()
+
+ _run(adapter, ("working", "post-1"))
+
+ assert _reactions(adapter) == [("add", "bot-worker", "post-1", "eyes")]
+
+
+def test_the_eyes_come_off_when_the_turn_ends() -> None:
+ adapter = _adapter()
+
+ _run(adapter, ("working", "post-1"), ("idle", None))
+
+ assert _reactions(adapter) == [
+ ("add", "bot-worker", "post-1", "eyes"),
+ ("remove", "bot-worker", "post-1", "eyes"),
+ ]
+
+
+def test_the_eyes_are_added_once_for_a_turn() -> None:
+ # The activity refresh repeats `working` for as long as the agent runs.
+ adapter = _adapter()
+
+ _run(adapter, ("working", "post-1"), ("working", "post-1"), ("working", "post-1"))
+
+ assert _reactions(adapter) == [("add", "bot-worker", "post-1", "eyes")]
+
+
+def test_the_eyes_stay_on_while_the_agent_waits_for_input() -> None:
+ # awaiting-input is mid-turn, just paused β€” the message is still being
+ # worked on, so the mark stays.
+ adapter = _adapter()
+
+ _run(adapter, ("working", "post-1"), ("awaiting-input", "post-1"))
+
+ assert _reactions(adapter) == [("add", "bot-worker", "post-1", "eyes")]
+
+
+def test_the_eyes_go_on_the_message_that_asked_not_the_thread_root() -> None:
+ # Inside a thread the status is anchored to the root, but what was said is
+ # the reply β€” and the reply is what the reader is waiting on.
+ adapter = _adapter()
+ adapter._remember_trigger("chan-1", "root-1", "reply-9")
+
+ _run(adapter, ("working", "root-1"))
+
+ assert _reactions(adapter) == [("add", "bot-worker", "reply-9", "eyes")]
+
+
+def test_the_eyes_come_off_the_message_that_asked() -> None:
+ adapter = _adapter()
+ adapter._remember_trigger("chan-1", "root-1", "reply-9")
+
+ _run(adapter, ("working", "root-1"), ("idle", None))
+
+ assert ("remove", "bot-worker", "reply-9", "eyes") in _reactions(adapter)
+ assert not any(call[2] == "root-1" for call in _reactions(adapter))
+
+
+def test_a_message_at_the_channel_root_is_marked_on_itself() -> None:
+ # This adapter follows the anchor, so a root-level trigger arrives as its
+ # own post id and no trigger mapping is needed.
+ adapter = _adapter()
+
+ _run(adapter, ("working", "post-42"))
+
+ assert _reactions(adapter) == [("add", "bot-worker", "post-42", "eyes")]
+
+
+def test_every_marked_message_is_cleared_when_the_turn_ends() -> None:
+ # An agent asked two things at once works on both, but the turn ends once.
+ # Clearing only the last thread would leave the first marked for good.
+ adapter = _adapter()
+
+ _run(adapter, ("working", "post-1"), ("working", "post-2"), ("idle", None))
+
+ removed = {call[2] for call in _reactions(adapter) if call[0] == "remove"}
+ assert removed == {"post-1", "post-2"}
+
+
+def test_two_agents_on_one_message_each_leave_their_own_mark() -> None:
+ adapter = _adapter("worker", "reviewer")
+
+ async def _body() -> None:
+ adapter._main_loop = asyncio.get_running_loop()
+ for agent in ("worker", "reviewer"):
+ await adapter.apply_runtime_state(
+ "chan-1",
+ agent,
+ "working",
+ mention_handle=None,
+ thread_root_id="post-1",
+ )
+
+ asyncio.run(_body())
+
+ assert _reactions(adapter, "worker") == [("add", "bot-worker", "post-1", "eyes")]
+ assert _reactions(adapter, "reviewer") == [
+ ("add", "bot-reviewer", "post-1", "eyes")
+ ]
+
+
+def test_a_failed_reaction_does_not_break_the_turn(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # The post may have been deleted, or the bot removed from the channel. The
+ # status message is what actually carries the state.
+ adapter = _adapter()
+ driver: Any = adapter._bot_drivers["worker"]
+ driver.reactions.error = RuntimeError("403 forbidden")
+
+ with caplog.at_level(logging.WARNING):
+ _run(adapter, ("working", "post-1"))
+
+ assert ("worker", "post-1") not in adapter._eyes
+ assert any("working reaction" in r.getMessage() for r in caplog.records)
+
+
+def test_an_agent_with_no_connected_bot_is_reported_not_ignored(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _adapter()
+ adapter._bot_drivers.clear()
+ adapter._agent_bots.clear()
+
+ with caplog.at_level(logging.WARNING):
+ _run(adapter, ("working", "post-1"))
+
+ assert any("no connected bot" in r.getMessage() for r in caplog.records)
+
+
+def test_the_trigger_map_does_not_grow_without_bound() -> None:
+ adapter = _adapter()
+ adapter._thread_trigger_max = 3
+
+ for n in range(6):
+ adapter._remember_trigger("chan-1", f"root-{n}", f"post-{n}")
+
+ assert list(adapter._thread_trigger) == [
+ ("chan-1", "root-3"),
+ ("chan-1", "root-4"),
+ ("chan-1", "root-5"),
+ ]
diff --git a/docs/bridges/MATTERMOST_SETUP.md b/docs/bridges/MATTERMOST_SETUP.md
index 1d69ce2f0..86148a0d2 100644
--- a/docs/bridges/MATTERMOST_SETUP.md
+++ b/docs/bridges/MATTERMOST_SETUP.md
@@ -70,3 +70,32 @@ don't onboard Mattermost by hand β€” it's already there after setup. Log in at
starts the DM with the agent's bot and Switch picks it up.
- **Deeplinks.** Set `GATEWAY_PUBLIC_URL` on switch-core for clickable "Open in
Switch Console" links (see the [index](README.md#deployment-knobs)).
+
+## Showing that an agent is working
+
+Three signals, in order of how long they last. Nothing here needs configuring.
+
+- **πŸ‘€ on the message that asked.** Added when the agent picks the message up and
+ removed when its turn ends. Inside a thread it goes on the reply, not the root
+ the reply hangs off β€” the mark says *which* message is being handled. It is
+ added by the agent's own bot, so two agents on one message show two
+ reactions and hovering names them. This is the signal that always works: it
+ needs no thread and it does not expire.
+- **A posted status line** β€” "βš™οΈ Working on it…", edited in place as the agent
+ reports activity and retired to "βœ“ Done Β· 2m14s" when the turn finishes. It is
+ edited rather than deleted because Mattermost's client leaves a
+ "(message deleted)" placeholder behind any post removed while it is on screen.
+- **The typing indicator**, nudged once as the turn opens. Mattermost expires it
+ after about five seconds, so treat it as a first flicker rather than a
+ progress signal.
+
+**What Mattermost cannot do.** There is no equivalent of Slack's native AI
+progress card β€” the live panel that streams what an agent is doing under its own
+name. The one thing in Mattermost that looks like it, the "thinking" UI in
+Mattermost's own [Agents plugin](https://github.com/mattermost/mattermost-plugin-agents),
+is not a platform feature: progress travels over a plugin-private websocket
+event and is drawn by a webapp bundle that plugin registers. Neither half is
+reachable from a bot token or the REST API, and ephemeral posts cannot be edited
+over the API either. Matching that layer would mean Switch shipping a Mattermost
+plugin of its own, which every server admin would have to install. Switch does
+not do this, and does not approximate it.