Skip to content

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

Mention whoever can answer a request card posted in a thread (#995)

Abel Dantas58bf5cb41027
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c97cdf3a..fb82824ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -56,6 +56,14 @@ version of their own to them without also giving them a release of their own.
from `switchCore.followTheConversation.windowSeconds` (default 300).
#### Fixed
+- **A request card posted in a thread now mentions the person who can answer
+ it.** Approval and question cards go into the thread of the turn that raised
+ them, and on Slack they used to mention nobody there, so an owner who was not
+ in the thread was never told and the agent waited. A card in a thread now
+ mentions the person who asked when the agent's addressing policy lets them
+ answer, otherwise the agent's owner if they may answer, otherwise nobody.
+ It never mentions more than one person, even when the policy lets anyone
+ answer. Cards at the top of a channel mention whoever asked, as before.
- **The template guide agents read now covers a room's `roles:`,
`references:` and `docs:`.** All three already worked in a room resource
and appear when a room is captured, but the guide stopped at `aliases:`, so
diff --git a/core/switch_core/session_activity/publisher.py b/core/switch_core/session_activity/publisher.py
index 51048dff9..4bb6228d4 100644
--- a/core/switch_core/session_activity/publisher.py
+++ b/core/switch_core/session_activity/publisher.py
@@ -68,6 +68,10 @@ from switch_core.db.models import (
TurnStatusPost,
)
from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.client_store import ClientStore
+from switch_core.db.stores.external_user_store import ExternalUserStore
+from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.session_activity_post_store import (
ApprovalRequestPostStore,
@@ -78,6 +82,7 @@ from switch_core.db.stores.session_activity_store import (
AgentSessionActivityStore,
ApprovalRequestStore,
)
+from switch_core.delivery.addressing import AddressingResolver
from switch_core.session_activity.bridge_turns import (
TurnView,
status_state,
@@ -93,6 +98,7 @@ from switch_core.sessions.contract import DecidedBy, decided
from switch_core.sessions.presentation import (
activity_error_summary,
notification_recipient,
+ request_card_recipient,
)
logger = logging.getLogger(__name__)
@@ -210,6 +216,15 @@ class AgentSessionActivityPublisher:
self._agent_online = agent_online
self._approvals = ApprovalRequestStore()
self._rooms = RoomStore()
+ self._addressing = AddressingResolver(
+ room_store=self._rooms,
+ room_role_store=RoomRoleStore(),
+ client_store=ClientStore(),
+ agent_store=AgentStore(),
+ external_user_store=ExternalUserStore(),
+ # Only role mentions consult liveness; a permission check never does.
+ live_connection_ids=set,
+ )
self._activity = AgentSessionActivityStore()
self._card_posts = ApprovalRequestPostStore()
self._turn_posts = TurnStatusPostStore()
@@ -507,23 +522,56 @@ class AgentSessionActivityPublisher:
thread_ref: str | None,
) -> str | None:
"""Who a post asking someone to act names: whoever asked, else the owner."""
- actor_id: str | None = None
- if turn_row is not None and turn_row.message_id is not None:
- actor_id = await db.scalar(
- select(Message.sender_id).where(
- Message.transport_event_id == turn_row.message_id
- )
- )
return await notification_recipient(
db,
bridge_id=self._bridge_id,
room_id=room_id,
surface=self._bridge_type,
- actor_id=actor_id,
+ actor_id=await self._asker(db, turn_row),
agent=agent,
thread_id=thread_ref,
)
+ async def _card_recipient(
+ self,
+ db: AsyncSession,
+ room_id: str,
+ agent: Agent,
+ turn_row: AgentSessionActivityItem | None,
+ thread_ref: str | None,
+ ) -> str | None:
+ """Who a new request card names: in a thread, somebody who may answer it."""
+ if thread_ref is None:
+ return await self._recipient(db, room_id, agent, turn_row, None)
+
+ async def may_answer(sender: str) -> bool:
+ decision = await self._addressing.permitted(
+ db, agent=agent, room_id=room_id, sender=sender
+ )
+ return decision.allowed
+
+ return await request_card_recipient(
+ db,
+ bridge_id=self._bridge_id,
+ room_id=room_id,
+ actor_id=await self._asker(db, turn_row),
+ agent=agent,
+ may_answer=may_answer,
+ )
+
+ async def _asker(
+ self, db: AsyncSession, turn_row: AgentSessionActivityItem | None
+ ) -> str | None:
+ """The room identity of whoever sent the message a turn answers, if known."""
+ if turn_row is None or turn_row.message_id is None:
+ return None
+ sender: str | None = await db.scalar(
+ select(Message.sender_id).where(
+ Message.transport_event_id == turn_row.message_id
+ )
+ )
+ return sender
+
async def _turn_row(
self, db: AsyncSession, agent_id: str, session_id: str, turn_id: str
) -> AgentSessionActivityItem | None:
@@ -561,7 +609,7 @@ class AgentSessionActivityPublisher:
online = self._agent_online(agent_id)
asking = post is None and row.state == "open"
recipient = (
- await self._recipient(
+ await self._card_recipient(
db, row.room_id, target.agent, turn_row, target.thread_ref
)
if asking
diff --git a/core/switch_core/sessions/presentation.py b/core/switch_core/sessions/presentation.py
index 8ccddcaf1..c6cfbb7d7 100644
--- a/core/switch_core/sessions/presentation.py
+++ b/core/switch_core/sessions/presentation.py
@@ -1,6 +1,9 @@
"""Room-safe presentation metadata for SDK collaboration messages."""
-from sqlalchemy import select
+import logging
+from collections.abc import Awaitable, Callable
+
+from sqlalchemy import Row, select
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import (
@@ -12,6 +15,8 @@ from switch_core.db.models import (
)
from switch_core.sessions.contract import TurnUpsert
+logger = logging.getLogger(__name__)
+
async def notification_recipient(
db: AsyncSession,
@@ -69,6 +74,96 @@ async def notification_recipient(
return await initiator() or await claimed_by(agent.owner_id)
+async def request_card_recipient(
+ db: AsyncSession,
+ *,
+ bridge_id: str,
+ room_id: str,
+ actor_id: str | None,
+ agent: Agent,
+ may_answer: Callable[[str], Awaitable[bool]],
+) -> str | None:
+ """The one person a request card in a thread names: someone who may answer it.
+
+ A thread is followed only by the people already in it, and the person who
+ has to answer is often not one of them, so a card there that names nobody
+ can wait unseen. `notification_recipient` names whoever asked, which suits
+ a post the asker is waiting on; a card needs whoever may answer, and on
+ the default policy only the owner may.
+
+ Whoever asked comes first, then the owner, each only when `may_answer`
+ (given their room identity) admits them, which is the check an answer is
+ put through. The asker is the one waiting on the card, so when they may
+ answer it they are named even if the owner may too. Exactly one person or
+ nobody: a policy that admits the whole room is not a reason to page the
+ whole room. A person is named by the account they hold on this bridge and
+ in this room, so somebody with no account here (an agent, for one) is not
+ named at all. An owner may hold several such accounts and a policy may
+ admit only one of them, so each is tried in turn.
+ """
+ members = (
+ select(ExternalUser.external_user_id, Client.transport_user_id)
+ .join(Client, Client.id == ExternalUser.client_id)
+ .join(ClientRoom, ClientRoom.client_id == ExternalUser.client_id)
+ .where(ExternalUser.bridge_id == bridge_id, ClientRoom.room_id == room_id)
+ )
+ refused: str | None = None
+ if actor_id is not None:
+ asker = (
+ await db.execute(
+ members.where(Client.transport_user_id == actor_id)
+ .order_by(ExternalUser.id)
+ .limit(1)
+ )
+ ).first()
+ if asker is not None:
+ if await may_answer(actor_id):
+ return str(asker.external_user_id)
+ refused = actor_id
+ if agent.owner_id is None:
+ logger.info("Agent %s has no owner to name on its request card.", agent.name)
+ else:
+ owner_accounts: list[Row[tuple[str, str]]] = list(
+ (
+ await db.execute(
+ members.join(
+ ExternalUserClaim,
+ ExternalUserClaim.external_user_id == ExternalUser.id,
+ )
+ .where(ExternalUserClaim.user_id == agent.owner_id)
+ .order_by(ExternalUser.id)
+ )
+ ).all()
+ )
+ if not owner_accounts:
+ logger.info(
+ "The owner of agent %s has no linked account in room %s on "
+ "bridge %s, so its request card cannot name them.",
+ agent.name,
+ room_id,
+ bridge_id,
+ )
+ for owner in owner_accounts:
+ if owner.transport_user_id == refused:
+ continue
+ if await may_answer(owner.transport_user_id):
+ return str(owner.external_user_id)
+ if owner_accounts:
+ logger.info(
+ "The owner of agent %s may not answer in room %s from any "
+ "account linked here, so its request card does not name them.",
+ agent.name,
+ room_id,
+ )
+ logger.info(
+ "Request card of agent %s in room %s names nobody: neither whoever "
+ "asked nor its owner has an account here that may answer it.",
+ agent.name,
+ room_id,
+ )
+ return None
+
+
def activity_error_summary(turn: TurnUpsert, *, online: bool) -> str | None:
"""Describe state without leaking provider notices or session-private output."""
if turn.status == "error":
diff --git a/core/tests/switch_core/session_activity/test_publisher.py b/core/tests/switch_core/session_activity/test_publisher.py
index b34adafa1..d02697b67 100644
--- a/core/tests/switch_core/session_activity/test_publisher.py
+++ b/core/tests/switch_core/session_activity/test_publisher.py
@@ -1,8 +1,11 @@
from __future__ import annotations
import asyncio
+import uuid
from collections.abc import AsyncIterator
from datetime import UTC, datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
import pytest
from sqlalchemy import select
@@ -11,10 +14,16 @@ from sqlalchemy.pool import NullPool
from switch_core.bridges.collaboration.adapter import RequestCard, TurnActivity
from switch_core.db.models import (
+ Agent,
ApprovalRequestPost,
BridgeMessageMap,
+ Client,
+ ClientRoom,
+ ExternalUser,
+ ExternalUserClaim,
TurnStatusPost,
)
+from switch_core.delivery.addressing import AddressingDecision
from switch_core.session_activity import publisher as publisher_module
from switch_core.session_activity.listener import AgentSessionActivityListener
from switch_core.session_activity.publisher import (
@@ -304,6 +313,90 @@ async def test_a_card_goes_into_the_thread_it_answers(
assert (await _card_post(session_factory)).thread_ref == ASKED_POST
+async def test_a_card_in_a_thread_names_the_owner_who_may_answer_it(
+ service, publisher, platform, bridged, session_factory
+):
+ """Slack's thread following reaches only the people already in the thread,
+ and the owner who has to answer is often not one of them."""
+ suffix = uuid.uuid4().hex[:8]
+ async with session_factory() as db, db.begin():
+ owner_id = await db.scalar(select(Agent.owner_id).where(Agent.id == AGENT))
+ client = Client(
+ transport_user_id=f"@owner-{suffix}:test", display_name="owner", type="user"
+ )
+ db.add(client)
+ await db.flush()
+ account = ExternalUser(
+ bridge_id=bridged.bridge_id,
+ external_user_id=f"U{suffix.upper()}",
+ external_username=f"owner-{suffix}",
+ client_id=client.id,
+ )
+ db.add_all([account, ClientRoom(client_id=client.id, room_id=bridged.room_id)])
+ await db.flush()
+ db.add(ExternalUserClaim(external_user_id=account.id, user_id=owner_id))
+
+ await _open(service, bridged.room_id, thread_id=ASKED)
+ [posted] = await platform.wait_for(1)
+ assert posted.thread_ref == ASKED_POST
+ assert posted.content.notify_external_id == f"U{suffix.upper()}"
+
+
+def _bare_publisher() -> AgentSessionActivityPublisher:
+ return AgentSessionActivityPublisher(
+ adapter=RecordingPlatform(), # type: ignore[arg-type]
+ bridge_id="bridge",
+ bridge_type="slack",
+ tenant_id="tenant",
+ listener=MagicMock(),
+ session_factory=MagicMock(),
+ agent_online=Online(),
+ )
+
+
+async def test_a_card_at_the_channel_root_names_whoever_asked_as_before(monkeypatch):
+ publisher = _bare_publisher()
+ asked = AsyncMock(return_value="UASKER")
+ answerer = AsyncMock()
+ monkeypatch.setattr(publisher_module, "notification_recipient", asked)
+ monkeypatch.setattr(publisher_module, "request_card_recipient", answerer)
+ agent = SimpleNamespace(name="agent", owner_id="owner")
+
+ assert (
+ await publisher._card_recipient(AsyncMock(), "room", agent, None, None) # type: ignore[arg-type]
+ == "UASKER"
+ )
+ assert asked.call_args.kwargs["thread_id"] is None
+ assert asked.call_args.kwargs["surface"] == "slack"
+ answerer.assert_not_called()
+
+
+async def test_a_card_in_a_thread_asks_the_addressing_policy_who_may_answer(
+ monkeypatch,
+):
+ publisher = _bare_publisher()
+ asked = AsyncMock()
+ answerer = AsyncMock(return_value="UOWNER")
+ permitted = AsyncMock(return_value=AddressingDecision(allowed=False, refusal="no"))
+ monkeypatch.setattr(publisher_module, "notification_recipient", asked)
+ monkeypatch.setattr(publisher_module, "request_card_recipient", answerer)
+ monkeypatch.setattr(publisher._addressing, "permitted", permitted)
+ agent = SimpleNamespace(name="agent", owner_id="owner")
+ db = AsyncMock()
+
+ assert (
+ await publisher._card_recipient(db, "room", agent, None, "123.456") # type: ignore[arg-type]
+ == "UOWNER"
+ )
+ asked.assert_not_called()
+ kwargs = answerer.call_args.kwargs
+ assert (kwargs["bridge_id"], kwargs["room_id"]) == ("bridge", "room")
+ assert await kwargs["may_answer"]("@someone:switch") is False
+ permitted.assert_awaited_once_with(
+ db, agent=agent, room_id="room", sender="@someone:switch"
+ )
+
+
async def test_a_refused_post_releases_its_handle(
service, publisher, platform, bridged, session_factory
):
diff --git a/core/tests/switch_core/sessions/test_session_presentation.py b/core/tests/switch_core/sessions/test_session_presentation.py
index 77f6f2f53..7e93320d4 100644
--- a/core/tests/switch_core/sessions/test_session_presentation.py
+++ b/core/tests/switch_core/sessions/test_session_presentation.py
@@ -1,5 +1,6 @@
+import logging
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -7,6 +8,7 @@ from switch_core.sessions.contract import TurnUpsert
from switch_core.sessions.presentation import (
activity_error_summary,
notification_recipient,
+ request_card_recipient,
)
@@ -158,3 +160,198 @@ async def test_an_unknown_asker_reaches_the_owner():
== "UOWNER"
)
assert db.scalar.call_count == 1
+
+
+# ── Who a request card in a thread names ─────────────────────────────────────
+
+OWNER_ACCOUNT = SimpleNamespace(
+ external_user_id="UOWNER", transport_user_id="@owner:switch"
+)
+ASKER_ACCOUNT = SimpleNamespace(
+ external_user_id="UASKER", transport_user_id="@asker:switch"
+)
+
+
+def _found(*rows):
+ """A db whose successive account lookups find these rows (None: no account,
+ a list: several accounts)."""
+ db = AsyncMock()
+ results = []
+ for row in rows:
+ result = MagicMock()
+ accounts = row if isinstance(row, list) else [] if row is None else [row]
+ result.first.return_value = accounts[0] if accounts else None
+ result.all.return_value = accounts
+ results.append(result)
+ db.execute.side_effect = results
+ return db
+
+
+def _sql(db, call: int) -> str:
+ return str(
+ db.execute.call_args_list[call]
+ .args[0]
+ .compile(compile_kwargs={"literal_binds": True})
+ )
+
+
+class MayAnswer:
+ """The answer check, admitting only the room identities it is given."""
+
+ def __init__(self, *admitted: str) -> None:
+ self.admitted = set(admitted)
+ self.asked: list[str] = []
+
+ async def __call__(self, sender: str) -> bool:
+ self.asked.append(sender)
+ return sender in self.admitted
+
+
+async def test_a_threaded_card_names_the_owner_when_the_asker_may_not_answer():
+ """On the default policy only the owner may answer, so the asker is
+ checked, refused, and the owner is named: naming the asker would ping a
+ person who cannot press anything on the card."""
+ db = _found(ASKER_ACCOUNT, OWNER_ACCOUNT)
+ may_answer = MayAnswer("@owner:switch")
+
+ assert (
+ await request_card_recipient(
+ db,
+ bridge_id="bridge",
+ room_id="room",
+ actor_id="@asker:switch",
+ agent=SimpleNamespace(name="agent", owner_id="owner"),
+ may_answer=may_answer,
+ )
+ == "UOWNER"
+ )
+ assert may_answer.asked == ["@asker:switch", "@owner:switch"]
+ query = _sql(db, 1)
+ assert "external_user_claims.user_id = 'owner'" in query
+ assert "external_users.bridge_id = 'bridge'" in query
+ assert "client_rooms.room_id = 'room'" in query
+ assert db.execute.call_count == 2
+
+
+async def test_an_asker_who_may_answer_is_named_before_the_owner():
+ """The asker is the one waiting on the card, so when the policy lets them
+ answer they are named, and the owner is not looked up at all."""
+ db = _found(ASKER_ACCOUNT, OWNER_ACCOUNT)
+ may_answer = MayAnswer("@asker:switch", "@owner:switch")
+
+ assert (
+ await request_card_recipient(
+ db,
+ bridge_id="bridge",
+ room_id="room",
+ actor_id="@asker:switch",
+ agent=SimpleNamespace(name="agent", owner_id="owner"),
+ may_answer=may_answer,
+ )
+ == "UASKER"
+ )
+ assert may_answer.asked == ["@asker:switch"]
+ query = _sql(db, 0)
+ assert "clients.matrix_user_id = '@asker:switch'" in query
+ assert "external_users.bridge_id = 'bridge'" in query
+ assert "client_rooms.room_id = 'room'" in query
+ assert db.execute.call_count == 1
+
+
+async def test_an_owner_is_named_by_the_one_linked_account_that_may_answer():
+ """A person can link several accounts on one bridge, and a policy can
+ admit just one of them, so every account is tried before giving up."""
+ other = SimpleNamespace(
+ external_user_id="UOWNER_OLD", transport_user_id="@owner-old:switch"
+ )
+ db = _found(None, [other, OWNER_ACCOUNT])
+ may_answer = MayAnswer("@owner:switch")
+
+ assert (
+ await request_card_recipient(
+ db,
+ bridge_id="bridge",
+ room_id="room",
+ actor_id="@asker:switch",
+ agent=SimpleNamespace(name="agent", owner_id="owner"),
+ may_answer=may_answer,
+ )
+ == "UOWNER"
+ )
+ assert may_answer.asked == ["@owner-old:switch", "@owner:switch"]
+ assert db.execute.call_count == 2
+
+
+async def test_an_asker_who_is_the_owner_is_not_asked_twice():
+ db = _found(OWNER_ACCOUNT, [OWNER_ACCOUNT])
+ may_answer = MayAnswer()
+
+ assert (
+ await request_card_recipient(
+ db,
+ bridge_id="bridge",
+ room_id="room",
+ actor_id="@owner:switch",
+ agent=SimpleNamespace(name="agent", owner_id="owner"),
+ may_answer=may_answer,
+ )
+ is None
+ )
+ assert may_answer.asked == ["@owner:switch"]
+ assert db.execute.call_count == 2
+
+
+async def test_an_owner_with_no_account_here_is_not_named(caplog):
+ db = _found(None, None)
+ caplog.set_level(logging.INFO, logger="switch_core.sessions.presentation")
+
+ assert (
+ await request_card_recipient(
+ db,
+ bridge_id="bridge",
+ room_id="room",
+ actor_id="@asker:switch",
+ agent=SimpleNamespace(name="agent", owner_id="owner"),
+ may_answer=MayAnswer("@owner:switch"),
+ )
+ is None
+ )
+ assert "no linked account" in caplog.text
+ assert "names nobody" in caplog.text
+
+
+async def test_an_asker_who_may_not_answer_is_not_named():
+ db = _found(ASKER_ACCOUNT, None)
+ may_answer = MayAnswer()
+
+ assert (
+ await request_card_recipient(
+ db,
+ bridge_id="bridge",
+ room_id="room",
+ actor_id="@asker:switch",
+ agent=SimpleNamespace(name="agent", owner_id="owner"),
+ may_answer=may_answer,
+ )
+ is None
+ )
+ assert may_answer.asked == ["@asker:switch"]
+
+
+async def test_an_ownerless_agent_with_no_known_asker_names_nobody(caplog):
+ db = _found()
+ caplog.set_level(logging.INFO, logger="switch_core.sessions.presentation")
+
+ assert (
+ await request_card_recipient(
+ db,
+ bridge_id="bridge",
+ room_id="room",
+ actor_id=None,
+ agent=SimpleNamespace(name="agent", owner_id=None),
+ may_answer=MayAnswer(),
+ )
+ is None
+ )
+ db.execute.assert_not_called()
+ assert "names nobody" in caplog.text