Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(teams): stop adding users to the whole team when a private channel is mistaken for public (#591)
Christian McDermotta15012852f02
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 977d19549..275e37dbb 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -494,6 +494,11 @@ class CollaborationAdapter(ABC):# Set by set_channel_migration_handler. Called with (old_id, new_id)# when the platform reissues a channel's id.self._on_channel_migrated: Callable[[str, str], Awaitable[None]] | None = None+ # Set by set_channel_type_handler. Called with (channel_id, type) when+ # the adapter learns a channel's type from the platform.+ self._on_channel_type_learned: (+ Callable[[str, ChannelType], Awaitable[None]] | None+ ) = None# Set by set_agent_presentation_resolver. Returns the agent's stored# presentation, or None for a name that is not an agent. Left unset an# adapter still works — every agent renders under its identifier with@@ -1253,6 +1258,12 @@ class CollaborationAdapter(ABC):bot having to be re-added to each channel."""return None+ async def refresh_channel_types(self, channel_ids: list[str]) -> None:+ """Re-read each channel's type from the platform and report it through+ the channel-type handler. Called at bridge startup. Default is a no-op;+ only Teams saves types it could not verify."""+ return None+def set_service_url_persister(self, persist: Callable[[str], Awaitable[None]]) -> None:@@ -1303,6 +1314,13 @@ class CollaborationAdapter(ABC):the platform forwards them, while nothing inbound matches a room again."""self._on_channel_migrated = handler+ def set_channel_type_handler(+ self, handler: Callable[[str, ChannelType], Awaitable[None]]+ ) -> None:+ """Install the callback an adapter calls when it learns a channel's+ type from the platform, so rooms saved with a different one follow."""+ self._on_channel_type_learned = handler+def set_interaction_handler(self, handler: Callable[[InboundInteraction], Awaitable[None]]) -> None:diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 4b093742d..99333e18b 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -241,6 +241,7 @@ class BridgeCore:self._pending_message_maps: dict[str, str] = {}# Identity provisioning runs in the background — see _create_agent_identities.self._identity_task: asyncio.Task[None] | None = None+ self._channel_type_refresh_task: asyncio.Task[None] | None = None# Turns and request cards from the tables the host reports to, pushed# as they change. Only where the platform draws session activity.self._connections = connections@@ -386,6 +387,7 @@ class BridgeCore:await self._load_channel_map()await self._load_existing_puppets()self._adapter.set_channel_migration_handler(self._handle_channel_migrated)+ self._adapter.set_channel_type_handler(self._record_channel_type)self._adapter.set_agent_presentation_resolver(self._agent_presentation)# A bridge on a shared connection that started before the connection# was up is attached later (when it comes up, or on its first event).@@ -422,6 +424,10 @@ class BridgeCore:# restarts one. Messages do not depend on it: an agent is addressable# by name whether or not its platform identity exists yet.self._identity_task = asyncio.create_task(self._run_agent_identities())+ # Not awaited either: one platform read per channel, and nothing waits on it.+ self._channel_type_refresh_task = asyncio.create_task(+ self._run_channel_type_refresh()+ )async def stop(self) -> None:if self._activity_publisher is not None:@@ -429,6 +435,12 @@ class BridgeCore:if self._identity_task and not self._identity_task.done():self._identity_task.cancel()self._identity_task = None+ if (+ self._channel_type_refresh_task+ and not self._channel_type_refresh_task.done()+ ):+ self._channel_type_refresh_task.cancel()+ self._channel_type_refresh_task = Noneawait self._adapter.stop()# ── Startup loading ──────────────────────────────────────────────────────@@ -607,6 +619,71 @@ class BridgeCore:if channels:await self._adapter.ensure_channel_subscriptions(channels)+ async def _run_channel_type_refresh(self) -> None:+ """Wrapper for the background channel-type refresh; see+ `_run_agent_identities` for why it exists and unbinds the tenant."""+ with no_tenant():+ try:+ await self._refresh_channel_types()+ except asyncio.CancelledError:+ logger.info(+ "%s channel type refresh cancelled before finishing",+ self._bridge_type,+ )+ raise+ except Exception:+ logger.exception(+ "%s channel type refresh stopped unexpectedly", self._bridge_type+ )++ async def _refresh_channel_types(self) -> None:+ """Have the adapter re-read the type of every channel this bridge's+ live rooms are bound to, so quiet channels are corrected too."""+ async with tenant_session(+ self._session_factory, self._bridge_tenant_id+ ) as session:+ rooms = await self._room_store.get_by_bridge(session, self._bridge_id)+ channel_ids = sorted(+ {+ room.external_channel_id+ for room in rooms+ if room.external_channel_id+ and room.archived_at is None+ and room.channel_type in ("channel_public", "channel_private")+ }+ )+ if channel_ids:+ await self._adapter.refresh_channel_types(channel_ids)++ async def _record_channel_type(+ self, channel_id: str, channel_type: ChannelType+ ) -> None:+ """Correct rooms bound to a channel whose saved privacy the platform+ contradicts. It matters beyond the label: moving a room to another+ bridge keeps its saved type, so a private room saved as public would+ get a public channel there."""+ if channel_type not in ("channel_public", "channel_private"):+ return+ async with tenant_session(+ self._session_factory, self._bridge_tenant_id+ ) as session:+ corrected = await self._room_store.correct_channel_type(+ session,+ bridge_id=self._bridge_id,+ external_channel_id=channel_id,+ channel_type=channel_type,+ )+ await session.commit()+ for room_id in corrected:+ logger.warning(+ "Room %s was saved with the wrong privacy; %s reports its "+ "channel %s as %s, and the room now says so",+ room_id,+ self._bridge_type,+ channel_id,+ channel_type,+ )+# ── Inbound (platform → room) ───────────────────────────────────────────async def _agent_presentation(self, agent_name: str) -> AgentPresentation | None:diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex 4273d9183..f5f48af18 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -328,6 +328,17 @@ _COMMAND_PREFIXES = ("!", "/")_CHANNEL_READ_RETRY_AFTER = 300.0+def _channel_type_of(channel: dict[str, Any]) -> ChannelType:+ """Only a ``standard`` channel shares the team's membership. Anything else,+ including values Graph adds later, is private: wrongly private fails+ loudly, wrongly public adds people to the whole team."""+ return (+ "channel_public"+ if channel.get("membershipType") == "standard"+ else "channel_private"+ )++def _handle_for(user: dict[str, Any]) -> str:"""The handle Switch knows a Teams person by.@@ -690,7 +701,8 @@ class TeamsAdapter(CollaborationAdapter):# Installed by the bridge to persist a newly-learned serviceUrl so it# survives a restart. No-op until set.self._persist_service_url: Callable[[str], Awaitable[None]] | None = None- # channel/chat id -> ChannelType, learned from inbound activities.+ # channel/chat id -> ChannelType. A channel's privacy comes only from+ # Graph or from creating it; an activity cannot say whether it is private.self._channel_type: dict[str, ChannelType] = {}# casefolded username -> AAD object id, for rendering real @mentions.self._mention_targets: dict[str, str] = {}@@ -962,7 +974,8 @@ class TeamsAdapter(CollaborationAdapter):# team and is not to be trusted — most often it was not read at all,# because the wrong team is exactly what Graph refuses. Without this the# subscription heals on the new team while the name and layout stay- # stuck at whatever the failed read left behind.+ # stuck at whatever the failed read left behind. Privacy is kept: it+ # belongs to the channel, whichever team it was read through.self._team_of_channel[channel_id] = team_idself._channel_names.pop(channel_id, None)self._channel_layouts.pop(channel_id, None)@@ -2002,25 +2015,20 @@ class TeamsAdapter(CollaborationAdapter):known = self._channel_type.get(channel_id)if known is not None:return known- if self._graph is None:- raise RuntimeError("Teams adapter not started")- team_id = self._team_of_channel.get(channel_id, self._config.team_id)- channel = await self._graph.get_channel(team_id=team_id, channel_id=channel_id)- resolved: ChannelType = (- "channel_private"- if channel.get("membershipType") == "private"- else "channel_public"- )- self._channel_type[channel_id] = resolved- # The same response carries the name and layout, so record them rather- # than reading the channel a second time on the first message.- self._channel_names.setdefault(- channel_id, str(channel.get("displayName") or "")- )- self._channel_layouts.setdefault(- channel_id, str(channel.get("layoutType") or "")- )- return resolved+ channel = await self._fetch_channel(channel_id)+ return _channel_type_of(channel)++ async def refresh_channel_types(self, channel_ids: list[str]) -> None:+ for channel_id in channel_ids:+ try:+ await self._fetch_channel(channel_id)+ except Exception:+ logger.warning(+ "Could not read whether Teams channel %s is private; its "+ "room keeps the type it was saved with until a read succeeds",+ channel_id,+ exc_info=True,+ )async def search_directory_users(self, query: str) -> list[DirectoryUser]:"""Search the AAD directory for people to claim as an identity.@@ -2091,8 +2099,28 @@ class TeamsAdapter(CollaborationAdapter):raise RuntimeError("Teams adapter not started")team_id = self._team_of_channel.get(channel_id, self._config.team_id)# Private channels have their own membership; standard channels inherit- # the team's, so a user is added to the team instead.- is_private = self._channel_type.get(channel_id) == "channel_private"+ # the team's, so a user is added to the team instead — only ever when+ # the channel is known to be standard, never as a fallback.+ try:+ channel_type = await self.get_channel_type(channel_id)+ except Exception:+ logger.exception(+ "Could not tell whether Teams channel %s is private; added none "+ "of %d user(s) rather than risk adding them to the whole team",+ channel_id,+ len(user_external_ids),+ )+ return list(user_external_ids)+ if channel_type not in ("channel_public", "channel_private"):+ logger.error(+ "Teams conversation %s is a %s, not a channel; added none of "+ "%d user(s)",+ channel_id,+ channel_type,+ len(user_external_ids),+ )+ return list(user_external_ids)+ is_private = channel_type == "channel_private"failed: list[str] = []for user_id in user_external_ids:try:@@ -2350,11 +2378,12 @@ class TeamsAdapter(CollaborationAdapter):service_url = str(activity.get("serviceUrl", "")).strip()activity_type = activity.get("type")- channel_id, channel_type = self._channel_from_activity(activity)+ channel_id, chat_type = self._channel_from_activity(activity)if service_url and channel_id:self._service_url[channel_id] = service_urlawait self._learn_service_url(service_url)- self._channel_type[channel_id] = channel_type+ if chat_type is not None:+ self._channel_type[channel_id] = chat_typeteam = (activity.get("channelData") or {}).get("team") or {}# Graph channel subscriptions key on the team's AAD group GUID, which@@ -2366,9 +2395,10 @@ class TeamsAdapter(CollaborationAdapter):await self._learn_channel_team(channel_id, str(group_id))if activity_type == "message":+ channel_type = await self._inbound_channel_type(channel_id, chat_type)await self._dispatch_message(activity, channel_id, channel_type)elif activity_type == "conversationUpdate":- await self._dispatch_conversation_update(activity, channel_id, channel_type)+ await self._dispatch_conversation_update(activity, channel_id, chat_type)elif activity_type == "invoke" and activity.get("name") == _INVOKE_CARD_ACTION:return await self._dispatch_card_action(activity, channel_id)return None@@ -2376,7 +2406,9 @@ class TeamsAdapter(CollaborationAdapter):@staticmethoddef _channel_from_activity(activity: dict[str, Any],- ) -> tuple[str, ChannelType]:+ ) -> tuple[str, ChannelType | None]:+ """The conversation id and, for a chat, its type. A channel's type is+ None: Teams sends the same shape for standard, private and shared."""conversation = activity.get("conversation") or {}conv_id = str(conversation.get("id", ""))conv_type = conversation.get("conversationType", "")@@ -2385,12 +2417,28 @@ class TeamsAdapter(CollaborationAdapter):if conv_type == "channel" or "@thread.tacv2" in conv_id:channel_id = str(channel.get("id") or conv_id.split(";", 1)[0])- return channel_id, "channel_public"+ return channel_id, Noneif conv_type == "personal":return conv_id, "direct"if conv_type == "groupChat":return conv_id, "group"- return conv_id.split(";", 1)[0], "channel_public"+ return conv_id.split(";", 1)[0], None++ async def _inbound_channel_type(+ self, channel_id: str, chat_type: ChannelType | None+ ) -> ChannelType:+ """The type to report for an inbound conversation. A channel Graph+ cannot describe is reported private but not cached, so it is re-read+ once the retry window passes."""+ if chat_type is not None:+ return chat_type+ known = self._channel_type.get(channel_id)+ if known is not None:+ return known+ if self._read_recently_failed(channel_id):+ return "channel_private"+ channel = await self._read_channel(channel_id)+ return "channel_private" if channel is None else _channel_type_of(channel)def _seen_activity(self, activity_id: str) -> bool:if not activity_id:@@ -2706,9 +2754,13 @@ class TeamsAdapter(CollaborationAdapter):)async def _dispatch_conversation_update(- self, activity: dict[str, Any], channel_id: str, channel_type: ChannelType+ self, activity: dict[str, Any], channel_id: str, chat_type: ChannelType | None) -> None:members_added = activity.get("membersAdded") or []+ if not members_added:+ # Deletions, renames and departures don't need the type; skip the read.+ return+ channel_type = await self._inbound_channel_type(channel_id, chat_type)recipient = activity.get("recipient") or {}bot_id = str(recipient.get("id", ""))channel_name = await self._resolve_channel_name(activity, channel_id)@@ -2782,11 +2834,12 @@ class TeamsAdapter(CollaborationAdapter):async def _read_channel(self, channel_id: str) -> dict[str, Any] | None:"""Read a channel from Graph once and cache what the adapter needs.- Two things come off this call — the display name, without which a room- is titled after a `19:…` id, and the conversation layout, which decides- whether an untied reply is steered into a post. They are cached- together because they arrive together: asking twice would double the- traffic for nothing.+ Three things come off this call — the display name, without which a room+ is titled after a `19:…` id; the conversation layout, which decides+ whether an untied reply is steered into a post; and whether the channel+ is private, which an activity never says. They are cached together+ because they arrive together: asking twice would double the traffic for+ nothing.Returns None when the read could not be made or failed. A failure isremembered so the read is not retried on every message, but only for@@ -2796,30 +2849,56 @@ class TeamsAdapter(CollaborationAdapter):capture die at a restart, and it is not worth repeating for a cheapersymptom."""- if self._graph is None or not self._is_channel(channel_id):- return None- team_id = self._team_of_channel.get(channel_id) or self._config.team_id- if not team_id:+ if not self._is_channel(channel_id):return Nonetry:- channel = await self._graph.get_channel(- team_id=team_id, channel_id=channel_id- )+ return await self._fetch_channel(channel_id)except Exception:logger.warning("Could not read Teams channel %s; until this succeeds a room "- "created for it is named after its id, and replies there are "- "threaded as if it used the posts layout",+ "created for it is named after its id and saved as private, and "+ "replies there are threaded as if it used the posts layout",channel_id,exc_info=True,)self._channel_read_failed_at[channel_id] = time.monotonic()return None++ async def _fetch_channel(self, channel_id: str) -> dict[str, Any]:+ """Read a channel from Graph and cache its privacy, name and layout;+ raises on failure."""+ if self._graph is None:+ raise RuntimeError("Teams adapter not started")+ team_id = self._team_of_channel.get(channel_id) or self._config.team_id+ if not team_id:+ raise RuntimeError(f"No team is known for Teams channel {channel_id}")+ channel = await self._graph.get_channel(team_id=team_id, channel_id=channel_id)+ channel_type = _channel_type_of(channel)self._channel_read_failed_at.pop(channel_id, None)+ self._channel_type[channel_id] = channel_typeself._channel_names[channel_id] = str(channel.get("displayName") or "")self._channel_layouts[channel_id] = str(channel.get("layoutType") or "")+ await self._report_channel_type(channel_id, channel_type)return channel+ async def _report_channel_type(+ self, channel_id: str, channel_type: ChannelType+ ) -> None:+ """Pass a channel's type to the bridge to correct its saved rooms. A+ failure is logged, not raised: the adapter still acts on the type, and+ the room is corrected at the next startup refresh."""+ if self._on_channel_type_learned is None:+ return+ try:+ await self._on_channel_type_learned(channel_id, channel_type)+ except Exception:+ logger.warning(+ "Could not record Teams channel %s as %s on its room",+ channel_id,+ channel_type,+ exc_info=True,+ )+def _read_recently_failed(self, channel_id: str) -> bool:failed_at = self._channel_read_failed_at.get(channel_id)if failed_at is None:@@ -3166,7 +3245,7 @@ class TeamsAdapter(CollaborationAdapter):await self._deliver(channel_id=channel_id,- channel_type=self._channel_type.get(channel_id, "channel_public"),+ channel_type=await self._inbound_channel_type(channel_id, None),sender_id=sender_id,sender_name=sender_name,text=content,diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.pyindex f742cb772..1e154f199 100644--- a/core/switch_core/db/stores/room_store.py+++ b/core/switch_core/db/stores/room_store.py@@ -195,6 +195,29 @@ class RoomStore:room.external_channel_id = external_channel_idawait session.flush()+ async def correct_channel_type(+ self,+ session: AsyncSession,+ *,+ bridge_id: str,+ external_channel_id: str,+ channel_type: str,+ ) -> list[str]:+ """Set `channel_type` on this bridge's rooms bound to the channel and+ saved as a channel of the other privacy; returns the ids that changed."""+ result = await session.execute(+ update(Room)+ .where(+ Room.bridge_id == bridge_id,+ Room.external_channel_id == external_channel_id,+ Room.channel_type.in_(("channel_public", "channel_private")),+ Room.channel_type != channel_type,+ )+ .values(channel_type=channel_type)+ .returning(Room.id)+ )+ return list(result.scalars().all())+async def clear_bridge(self, session: AsyncSession, room_id: str) -> None:room = await session.get(Room, room_id)if room is None:diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.pyindex 5b5bb4d48..7d6c065f0 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py@@ -261,6 +261,9 @@ def test_the_resolver_is_installed_before_the_adapter_starts() -> None:def set_channel_migration_handler(self, handler: Any) -> None:return None+ def set_channel_type_handler(self, handler: Any) -> None:+ return None+def set_agent_presentation_resolver(self, resolver: Any) -> None:installed.append(resolver)@@ -278,6 +281,7 @@ def test_the_resolver_is_installed_before_the_adapter_starts() -> None:bridge._load_channel_map = _noop # type: ignore[assignment,method-assign]bridge._load_existing_puppets = _noop # type: ignore[assignment,method-assign]bridge._ensure_channel_captures = _noop # type: ignore[assignment,method-assign]+ bridge._refresh_channel_types = _noop # type: ignore[assignment,method-assign]bridge._create_agent_identities = _noop # type: ignore[assignment,method-assign]asyncio.run(BridgeCore.start(bridge))diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.pyindex 2634a4dfc..30d7504fa 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py@@ -88,6 +88,9 @@ def test_the_handler_is_installed_before_the_adapter_starts() -> None:def set_channel_migration_handler(self, handler: Any) -> None:installed.append(handler)+ def set_channel_type_handler(self, handler: Any) -> None:+ return None+def set_agent_presentation_resolver(self, resolver: Any) -> None:# Not what this test is about; present so the stub satisfies what# `start` installs on its adapter.@@ -106,6 +109,7 @@ def test_the_handler_is_installed_before_the_adapter_starts() -> None:bridge._load_channel_map = _noop # type: ignore[assignment,method-assign]bridge._load_existing_puppets = _noop # type: ignore[assignment,method-assign]bridge._ensure_channel_captures = _noop # type: ignore[assignment,method-assign]+ bridge._refresh_channel_types = _noop # type: ignore[assignment,method-assign]bridge._create_agent_identities = _noop # type: ignore[assignment,method-assign]asyncio.run(BridgeCore.start(bridge))diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.pynew file mode 100644index 000000000..aea208c07--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py@@ -0,0 +1,266 @@+"""The bridge corrects rooms whose saved channel type the platform contradicts,+whenever the adapter learns one and, on startup, for every live channel room."""++from __future__ import annotations++import asyncio+import logging+from types import SimpleNamespace+from typing import Any++import pytest++from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.tenant_context import current_tenant_id, tenant_scope+++class _FakeSession:+ def __init__(self) -> None:+ self.commits = 0++ async def __aenter__(self) -> _FakeSession:+ return self++ async def __aexit__(self, *exc: Any) -> None:+ return None++ async def commit(self) -> None:+ self.commits += 1+++class _RoomStore:+ def __init__(self, rooms: list[SimpleNamespace], corrected: list[str]) -> None:+ self._rooms = rooms+ self._corrected = corrected+ self.corrections: list[tuple[str, str, str]] = []+ self.tenants: list[str | None] = []++ async def get_by_bridge(self, session: Any, bridge_id: str) -> list[Any]:+ assert bridge_id == "bridge-1"+ self.tenants.append(current_tenant_id())+ return self._rooms++ async def correct_channel_type(+ self,+ session: Any,+ *,+ bridge_id: str,+ external_channel_id: str,+ channel_type: str,+ ) -> list[str]:+ self.corrections.append((bridge_id, external_channel_id, channel_type))+ self.tenants.append(current_tenant_id())+ return self._corrected+++def _room(+ external_channel_id: str | None, channel_type: str | None, archived: bool+) -> SimpleNamespace:+ return SimpleNamespace(+ external_channel_id=external_channel_id,+ channel_type=channel_type,+ archived_at="2026-01-01T00:00:00Z" if archived else None,+ )+++class _Adapter:+ def __init__(self) -> None:+ self.refreshed: list[list[str]] = []++ async def refresh_channel_types(self, channel_ids: list[str]) -> None:+ self.refreshed.append(channel_ids)+++def _bridge(store: _RoomStore, adapter: _Adapter) -> SimpleNamespace:+ session = _FakeSession()+ return SimpleNamespace(+ session=session,+ _session_factory=lambda: session,+ _room_store=store,+ _adapter=adapter,+ _bridge_id="bridge-1",+ _bridge_tenant_id="tenant-1",+ _bridge_type="teams",+ )+++# ── Recording what the adapter learned ───────────────────────────────────────+++ ("channel_type", "corrected", "asked"),+ [+ ("channel_private", ["room-1"], True),+ ("channel_private", [], True),+ ("direct", ["room-1"], False),+ ],+ ids=["corrected", "already-right", "chat-type-ignored"],+)+async def test_a_learned_type_corrects_this_bridges_rooms(+ channel_type: str,+ corrected: list[str],+ asked: bool,+ caplog: pytest.LogCaptureFixture,+) -> None:+ store = _RoomStore([], corrected)+ bridge = _bridge(store, _Adapter())++ with caplog.at_level(logging.WARNING):+ await BridgeCore._record_channel_type(+ bridge, # type: ignore[arg-type]+ "19:[email protected]",+ channel_type, # type: ignore[arg-type]+ )++ expected = [("bridge-1", "19:[email protected]", channel_type)]+ assert store.corrections == (expected if asked else [])+ # Written and committed under the bridge's tenant.+ assert store.tenants == (["tenant-1"] if asked else [])+ assert bridge.session.commits == (1 if asked else 0)+ # One warning per room actually changed, naming it.+ assert len(caplog.records) == (len(corrected) if asked else 0)+ assert all("room-1" in r.getMessage() for r in caplog.records)+++# ── The startup pass ─────────────────────────────────────────────────────────+++ ("rooms", "refreshed"),+ [+ (+ [+ _room("19:[email protected]", "channel_private", False),+ _room("19:[email protected]", "channel_public", False),+ _room("19:[email protected]", "channel_public", False),+ _room("19:[email protected]", "channel_public", True),+ _room("a:dm", "direct", False),+ _room("19:[email protected]", "group", False),+ _room(None, "channel_public", False),+ _room("19:[email protected]", None, False),+ ],+ [["19:[email protected]", "19:[email protected]"]],+ ),+ ([_room("a:dm", "direct", False)], []),+ ],+ ids=["live-channel-rooms-once-each", "no-channel-rooms"],+)+async def test_startup_rereads_every_live_channel_room(+ rooms: list[SimpleNamespace], refreshed: list[list[str]]+) -> None:+ adapter = _Adapter()+ store = _RoomStore(rooms, [])++ await BridgeCore._refresh_channel_types(_bridge(store, adapter)) # type: ignore[arg-type]++ assert adapter.refreshed == refreshed+ assert store.tenants == ["tenant-1"]+++async def test_adapters_have_nothing_to_refresh_by_default() -> None:+ adapter: Any = SimpleNamespace()+ await CollaborationAdapter.refresh_channel_types(adapter, ["C1"])+++# ── Wiring in start() and stop() ─────────────────────────────────────────────+++class _StartableAdapter:+ def __init__(self) -> None:+ self.channel_type_handler: Any = None+ self.handler_set_before_start = False++ def set_channel_type_handler(self, handler: Any) -> None:+ self.channel_type_handler = handler++ def set_channel_migration_handler(self, handler: Any) -> None:+ return None++ def set_agent_presentation_resolver(self, resolver: Any) -> None:+ return None++ async def start(self, **kwargs: Any) -> None:+ self.handler_set_before_start = self.channel_type_handler is not None++ async def stop(self) -> None:+ return None+++def _startable_core(refresh: Any) -> tuple[BridgeCore, _StartableAdapter]:+ core = object.__new__(BridgeCore)+ adapter = _StartableAdapter()++ async def _noop() -> None:+ return None++ for name, value in {+ "_bridge_type": "teams",+ "_adapter": adapter,+ "_identity_task": None,+ "_channel_type_refresh_task": None,+ "_load_channel_map": _noop,+ "_load_existing_puppets": _noop,+ "_ensure_channel_captures": _noop,+ "_create_agent_identities": _noop,+ "_refresh_channel_types": refresh,+ }.items():+ setattr(core, name, value)+ for name in (+ "_handle_channel_migrated",+ "_agent_presentation",+ "_handle_inbound_message",+ "_handle_inbound_command",+ "_handle_agent_joined_channel",+ "_handle_user_joined_channel",+ "_handle_app_joined_channel",+ ):+ setattr(core, name, None)+ return core, adapter+++async def test_start_installs_the_correction_and_stop_cancels_the_refresh(+ caplog: pytest.LogCaptureFixture,+) -> None:+ # Without the handler, a type learned at runtime corrects nothing until the+ # next start. The refresh must not inherit the tenant of whoever started it.+ running = asyncio.Event()+ tenants: list[str | None] = []++ async def _slow() -> None:+ tenants.append(current_tenant_id())+ running.set()+ await asyncio.sleep(30)++ core, adapter = _startable_core(_slow)++ with caplog.at_level(logging.INFO), tenant_scope("request-tenant"):+ await core.start()+ task = core._channel_type_refresh_task+ await asyncio.wait_for(running.wait(), timeout=1)+ await core.stop()+ await asyncio.sleep(0)++ assert adapter.channel_type_handler == core._record_channel_type+ assert adapter.handler_set_before_start+ assert task is not None and task.cancelled()+ assert core._channel_type_refresh_task is None+ assert "channel type refresh cancelled before finishing" in caplog.text+ assert tenants == [None]+++async def test_a_failed_refresh_is_logged_rather_than_swallowed(+ caplog: pytest.LogCaptureFixture,+) -> None:+ async def _explode() -> None:+ raise RuntimeError("refresh blew up")++ core, _ = _startable_core(_explode)++ with caplog.at_level(logging.ERROR):+ await core.start()+ assert core._channel_type_refresh_task is not None+ await core._channel_type_refresh_task+ await core.stop()++ assert "channel type refresh stopped unexpectedly" in caplog.textdiff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.pyindex fb6e2b32a..5bc526f46 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py@@ -23,6 +23,9 @@ class _FakeAdapter:def set_channel_migration_handler(self, handler: Any) -> None:pass+ def set_channel_type_handler(self, handler: Any) -> None:+ pass+def set_agent_presentation_resolver(self, resolver: Any) -> None:pass@@ -43,6 +46,7 @@ def _core(provision: Any) -> tuple[BridgeCore, _FakeAdapter]:core._bridge_type = "slack" # type: ignore[attr-defined]core._adapter = adapter # type: ignore[attr-defined]core._identity_task = None # type: ignore[attr-defined]+ core._channel_type_refresh_task = None # type: ignore[attr-defined]async def _noop() -> None:return None@@ -50,6 +54,7 @@ def _core(provision: Any) -> tuple[BridgeCore, _FakeAdapter]:core._load_channel_map = _noop # type: ignore[assignment]core._load_existing_puppets = _noop # type: ignore[assignment]core._ensure_channel_captures = _noop # type: ignore[assignment]+ core._refresh_channel_types = _noop # type: ignore[assignment]core._handle_channel_migrated = None # type: ignore[attr-defined]core._agent_presentation = None # type: ignore[attr-defined]core._handle_inbound_message = None # type: ignore[attr-defined]@@ -132,7 +137,10 @@ async def test_a_failure_is_logged_rather_than_swallowed(assert task is not Noneawait task- assert any("stopped unexpectedly" in r.getMessage() for r in caplog.records)+ assert any(+ "identity provisioning stopped unexpectedly" in r.getMessage()+ for r in caplog.records+ )await core.stop()diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.pyindex b0fd05378..2871487d3 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py@@ -117,14 +117,15 @@ def _capture_commands(adapter: TeamsAdapter) -> list[InboundCommand]:def test_channel_from_channel_activity_uses_channel_data_id() -> None:activity = {"conversation": {- "id": "19:[email protected];messageid=100",+ "id": "19:[email protected];messageid=100","conversationType": "channel",},"channelData": {"channel": {"id": "19:[email protected]"}},}channel_id, channel_type = TeamsAdapter._channel_from_activity(activity)assert channel_id == "19:[email protected]"- assert channel_type == "channel_public"+ # The activity cannot say whether the channel is private.+ assert channel_type is Nonedef test_channel_from_personal_activity_is_direct() -> None:@@ -327,6 +328,7 @@ def test_http_messages_dispatches_authenticated_activity() -> None:def test_inbound_channel_message_top_level_has_no_root() -> None:adapter = _adapter()+ adapter._channel_type["19:[email protected]"] = "channel_public"captured = _capture_messages(adapter)activity = {@@ -457,6 +459,7 @@ def test_inbound_channel_command_after_bot_mention_routes_to_on_command() -> Non# the bot, so a channel command always arrives as "@Bot !cmd". The leading# bot mention must not hide the "!" command marker.adapter = _adapter()+ adapter._channel_type["19:[email protected]"] = "channel_public"commands = _capture_commands(adapter)messages = _capture_messages(adapter)diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_channel_privacy.py b/core/tests/switch_core/bridges/collaboration/test_teams_channel_privacy.pynew file mode 100644index 000000000..150cc0204--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_channel_privacy.py@@ -0,0 +1,362 @@+"""Whether a Teams channel is private decides who a user is added to. A standard+channel shares its team's membership, so adding someone to it adds them to the+team; calling a private channel standard silently adds them to the whole team.+"""++from __future__ import annotations++import logging+from collections.abc import Awaitable, Callable+from typing import Any++import pytest++from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++CHANNEL = "19:[email protected]"+CHAT = "19:[email protected]"+++class _FakeGraph:+ """Graph as far as channel privacy and membership go. A membership type of+ None makes the read fail, as it does without permission or in an outage."""++ def __init__(self, membership_type: str | None) -> None:+ self.membership_type = membership_type+ self.by_channel: dict[str, str | None] = {}+ self.channel_reads = 0+ self.channel_members: list[str] = []+ self.team_members: list[str] = []++ async def create_channel(self, *, display_name: str, **_: Any) -> dict[str, Any]:+ return {"id": CHANNEL, "displayName": display_name}++ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:+ self.channel_reads += 1+ membership = self.by_channel.get(channel_id, self.membership_type)+ if membership is None:+ raise RuntimeError("Graph refused the read")+ return {+ "id": channel_id,+ "displayName": "Room",+ "membershipType": membership,+ "layoutType": "chat",+ }++ async def add_channel_member(self, *, user_aad_id: str, **_: Any) -> None:+ self.channel_members.append(user_aad_id)++ async def add_team_member(self, *, user_aad_id: str, **_: Any) -> None:+ self.team_members.append(user_aad_id)++ async def create_subscription(self, **_: Any) -> dict[str, Any]:+ return {"id": "SUB-X"}+++def _adapter(membership_type: str | None) -> tuple[TeamsAdapter, _FakeGraph]:+ config = TeamsConnectionConfig(+ app_id="app-123",+ app_password="secret",+ tenant_id="tenant-9",+ team_id="team-7",+ public_base_url="https://switch.example",+ client_state="s3cr3t",+ )+ graph = _FakeGraph(membership_type)+ adapter = TeamsAdapter(config=config)+ adapter._graph = graph # type: ignore[assignment]+ return adapter, graph+++def _capture(adapter: TeamsAdapter, handler: str) -> list[Any]:+ captured: list[Any] = []++ async def record(item: Any) -> None:+ captured.append(item)++ setattr(adapter, handler, record)+ return captured+++def _capture_learned(adapter: TeamsAdapter, *, fail: bool) -> list[tuple[str, str]]:+ learned: list[tuple[str, str]] = []++ async def on_learned(channel_id: str, channel_type: Any) -> None:+ learned.append((channel_id, channel_type))+ if fail:+ raise RuntimeError("database unavailable")++ adapter.set_channel_type_handler(on_learned)+ return learned+++def _message(activity_id: str) -> dict[str, Any]:+ return {+ "type": "message",+ "id": activity_id,+ "serviceUrl": "https://smba.example/amer/",+ "text": "<at>Switch</at> hello",+ "from": {"aadObjectId": "aad-1", "name": "alice"},+ "recipient": {"id": "28:app-123"},+ "conversation": {+ "id": f"{CHANNEL};messageid={activity_id}",+ "conversationType": "channel",+ },+ "channelData": {"channel": {"id": CHANNEL}},+ }+++def _bot_added() -> dict[str, Any]:+ return {+ "type": "conversationUpdate",+ "serviceUrl": "https://smba.example/amer/",+ "recipient": {"id": "28:app-123"},+ "membersAdded": [{"id": "28:app-123"}],+ "conversation": {"id": CHANNEL, "conversationType": "channel"},+ "channelData": {"channel": {"id": CHANNEL, "name": "Room"}},+ }+++async def _add_bob(adapter: TeamsAdapter) -> list[str]:+ return await adapter.add_users_to_channel(CHANNEL, ["bob"], ["aad-bob"])+++# ── Adding users ─────────────────────────────────────────────────────────────+++async def test_activity_from_a_private_channel_does_not_open_it_to_the_team() -> None:+ # The create-with-people sequence: the bot's join and a message arrive from+ # the new private channel before anyone is added.+ adapter, graph = _adapter("private")+ await adapter.create_channel("Room", "topic", channel_type="channel_private")+ await adapter._dispatch_activity(_bot_added())+ await adapter._dispatch_activity(_message("m1"))++ assert await _add_bob(adapter) == []+ assert (graph.channel_members, graph.team_members) == (["aad-bob"], [])+++ ("membership_type", "to_channel", "to_team"),+ [+ ("standard", [], ["aad-bob"]),+ ("private", ["aad-bob"], []),+ ("shared", ["aad-bob"], []),+ ],+)+async def test_after_a_restart_teams_is_asked_before_adding(+ membership_type: str, to_channel: list[str], to_team: list[str]+) -> None:+ adapter, graph = _adapter(membership_type)++ assert await _add_bob(adapter) == []+ assert graph.channel_reads == 1+ assert (graph.channel_members, graph.team_members) == (to_channel, to_team)+++ ("membership_type", "team_id", "channel_id", "known"),+ [+ (None, "team-7", CHANNEL, None),+ ("standard", "", CHANNEL, None),+ ("standard", "team-7", CHAT, "group"),+ ],+ ids=["teams-cannot-say", "no-team-known", "group-chat"],+)+async def test_nobody_is_added_unless_the_channel_is_known(+ membership_type: str | None,+ team_id: str,+ channel_id: str,+ known: str | None,+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter, graph = _adapter(membership_type)+ adapter._config.team_id = team_id+ if known:+ adapter._channel_type[channel_id] = known++ with caplog.at_level(logging.ERROR):+ failed = await adapter.add_users_to_channel(+ channel_id, ["bob", "eve"], ["aad-bob", "aad-eve"]+ )++ assert failed == ["aad-bob", "aad-eve"]+ assert (graph.channel_members, graph.team_members) == ([], [])+ errors = [r for r in caplog.records if channel_id in r.getMessage()]+ assert [r.levelno for r in errors] == [logging.ERROR]+++async def test_reading_a_channel_needs_a_started_adapter() -> None:+ adapter, _ = _adapter("private")+ adapter._graph = None++ with pytest.raises(RuntimeError, match="not started"):+ await adapter.get_channel_type(CHANNEL)+++# ── What inbound reports ─────────────────────────────────────────────────────+++async def _via_message(adapter: TeamsAdapter) -> list[Any]:+ captured = _capture(adapter, "_on_message")+ await adapter._dispatch_activity(_message("m1"))+ return [m.channel_type for m in captured]+++async def _via_bot_added(adapter: TeamsAdapter) -> list[Any]:+ captured = _capture(adapter, "_on_app_joined")+ await adapter._dispatch_activity(_bot_added())+ return [j.channel_type for j in captured]+++async def _via_captured_message(adapter: TeamsAdapter) -> list[Any]:+ captured = _capture(adapter, "_on_message")+ await adapter._deliver_graph_message(+ {+ "id": "g1",+ "messageType": "message",+ "from": {"user": {"id": "aad-1", "displayName": "alice"}},+ "channelIdentity": {"teamId": "team-7", "channelId": CHANNEL},+ "body": {"contentType": "text", "content": "hello"},+ }+ )+ return [m.channel_type for m in captured]+++ "deliver", [_via_message, _via_bot_added, _via_captured_message]+)+ ("membership_type", "reported"),+ [+ ("standard", "channel_public"),+ ("private", "channel_private"),+ (None, "channel_private"),+ ],+)+async def test_inbound_reports_what_teams_says_the_channel_is(+ deliver: Callable[[TeamsAdapter], Awaitable[list[Any]]],+ membership_type: str | None,+ reported: str,+) -> None:+ # A room auto-created for the channel is saved with this type. When Teams+ # cannot say it is reported private, but not cached, so adding still asks.+ adapter, _ = _adapter(membership_type)++ assert await deliver(adapter) == [reported]+ assert adapter._channel_type.get(CHANNEL) == (reported if membership_type else None)++[email protected]("membership_type", ["private", None])+async def test_a_channel_is_read_and_warned_about_at_most_once(+ membership_type: str | None, caplog: pytest.LogCaptureFixture+) -> None:+ # A failed read is not retried, nor warned about again, in the retry window.+ adapter, graph = _adapter(membership_type)+ _capture(adapter, "_on_message")++ with caplog.at_level(logging.WARNING):+ await adapter._dispatch_activity(_message("m1"))+ await adapter._dispatch_activity(_message("m2"))++ assert graph.channel_reads == 1+ warnings = [r for r in caplog.records if CHANNEL in r.getMessage()]+ assert len(warnings) == (0 if membership_type else 1)+++ ("conversation_type", "service_url", "known"),+ [+ ("groupChat", "https://smba.example/amer/", None),+ ("groupChat", "", None),+ ("", "https://smba.example/amer/", "group"),+ ],+ ids=["said-by-activity", "said-without-service-url", "already-known"],+)+async def test_a_chat_is_not_mistaken_for_a_channel(+ conversation_type: str, service_url: str, known: str | None+) -> None:+ # An activity with no conversation type is channel-shaped by default, so a+ # chat's type is remembered once there is a way to reply to it. Graph has no+ # channel by a chat's id.+ adapter, graph = _adapter("standard")+ graph.by_channel[CHAT] = None+ if known:+ adapter._channel_type[CHAT] = known+ captured = _capture(adapter, "_on_message")+ activity = _message("m1")+ activity["serviceUrl"] = service_url+ activity["conversation"] = {"id": CHAT, "conversationType": conversation_type}+ activity["channelData"] = {}++ await adapter._dispatch_activity(activity)++ assert [m.channel_type for m in captured] == ["group"]+ assert adapter._channel_type.get(CHAT) == ("group" if service_url else None)+++async def test_a_conversation_update_adding_nobody_does_not_read_the_channel() -> None:+ adapter, graph = _adapter(None)+ activity = _bot_added()+ activity["membersAdded"] = []+ activity["channelData"]["eventType"] = "channelDeleted"++ await adapter._dispatch_activity(activity)++ assert graph.channel_reads == 0+++# ── Reporting learned types, so saved rooms are corrected ────────────────────+++async def test_refresh_reports_what_teams_says_and_warns_on_failures(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter, graph = _adapter("standard")+ graph.by_channel = {"19:[email protected]": "private", "19:[email protected]": None}+ learned = _capture_learned(adapter, fail=False)++ with caplog.at_level(logging.WARNING):+ await adapter.refresh_channel_types(+ )++ assert learned == [+ ("19:[email protected]", "channel_public"),+ ("19:[email protected]", "channel_private"),+ ]+ assert [r.getMessage() for r in caplog.records if "19:bad" in r.getMessage()]++[email protected]("recording_fails", [False, True])+async def test_a_type_learned_at_runtime_is_reported(+ recording_fails: bool, caplog: pytest.LogCaptureFixture+) -> None:+ # The first successful read after startup corrects the saved room too, and+ # failing to record it is logged but must not stop the adapter acting on it.+ adapter, graph = _adapter("private")+ learned = _capture_learned(adapter, fail=recording_fails)++ with caplog.at_level(logging.WARNING):+ assert await _add_bob(adapter) == []++ assert learned == [(CHANNEL, "channel_private")]+ assert (graph.channel_members, graph.team_members) == (["aad-bob"], [])+ assert ("Could not record" in caplog.text) == recording_fails+++async def test_a_successful_read_lifts_the_retry_wait_for_every_path() -> None:+ # A failed read delays re-reading the name and layout; a later successful+ # privacy read must lift that wait.+ adapter, graph = _adapter(None)+ await adapter._read_channel(CHANNEL)+ assert adapter._read_recently_failed(CHANNEL)++ graph.membership_type = "private"+ assert await adapter.get_channel_type(CHANNEL) == "channel_private"++ assert not adapter._read_recently_failed(CHANNEL)+ assert adapter._channel_names[CHANNEL] == "Room"diff --git a/core/tests/switch_core/db/stores/test_room_channel_type.py b/core/tests/switch_core/db/stores/test_room_channel_type.pynew file mode 100644index 000000000..ccf142991--- /dev/null+++ b/core/tests/switch_core/db/stores/test_room_channel_type.py@@ -0,0 +1,95 @@+"""Correcting a channel's saved type touches only the room bound to that channel+on that bridge and saved as a channel; anything else is not about it."""++from __future__ import annotations++import uuid++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Client, CollaborationBridge, Room+from switch_core.db.stores.room_store import RoomStore++CHANNEL = "19:[email protected]"+CHAT = "19:[email protected]"+++async def _make_bridge(session: AsyncSession) -> str:+ client = Client(+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ display_name="teams client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type="teams",+ display_name="teams",+ connection_config={},+ client_id=client.id,+ status="active",+ )+ session.add(bridge)+ await session.flush()+ return bridge.id+++async def _make_room(+ session: AsyncSession,+ bridge_id: str | None,+ external_channel_id: str | None,+ channel_type: str | None,+) -> str:+ room = await RoomStore().create(+ session,+ Room(+ matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",+ name="room",+ description="room desc",+ bridge_id=bridge_id,+ channel_type=channel_type,+ external_channel_id=external_channel_id,+ ),+ )+ return room.id+++async def test_only_the_room_saved_with_the_other_privacy_is_corrected(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = RoomStore()+ async with session_factory() as session:+ bridge = await _make_bridge(session)+ other_bridge = await _make_bridge(session)+ target = await _make_room(session, bridge, CHANNEL, "channel_public")+ untouched = {+ await _make_room(+ session, other_bridge, CHANNEL, "channel_public"+ ): "channel_public",+ await _make_room(+ session, bridge, "19:x", "channel_public"+ ): "channel_public",+ await _make_room(session, bridge, CHAT, "group"): "group",+ await _make_room(session, None, None, None): None,+ }+ await session.commit()++ async def correct(channel_id: str) -> list[str]:+ return await store.correct_channel_type(+ session,+ bridge_id=bridge,+ external_channel_id=channel_id,+ channel_type="channel_private",+ )++ assert await correct(CHANNEL) == [target]+ assert await correct(CHANNEL) == [] # already right+ assert await correct(CHAT) == [] # a chat, not a channel+ await session.commit()++ async with session_factory() as session:+ saved = {+ room_id: (await store.get(session, room_id)).channel_type # type: ignore[union-attr]+ for room_id in [target, *untouched]+ }+ assert saved == {target: "channel_private", **untouched}diff --git a/docs/old/bridges/TEAMS_SETUP.md b/docs/old/bridges/TEAMS_SETUP.mdindex 2c0c96a74..ab081265e 100644--- a/docs/old/bridges/TEAMS_SETUP.md+++ b/docs/old/bridges/TEAMS_SETUP.md@@ -189,14 +189,15 @@ when one is missing, not so you can pick and choose:| --- | --- || `ChannelMessage.Read.All`<br>(or `ChannelMessage.Read.Group`, see below) | No channel capture. The bridge sees only messages that @mention the bot, so plain channel conversation, and bare `!commands`, never reach Switch. || `Channel.Create` | Adding a room to the bridge fails: Switch cannot provision the room's channel. |-| `Channel.ReadBasic.All` | Three things, all from the same read. Binding a room to a channel that **already exists** fails (see [Bringing Switch into a channel that already exists](#bringing-switch-into-a-channel-that-already-exists)) — Switch reads the channel to learn whether it is standard or private, and provisions membership differently for each. A room auto-created for a channel is titled after the channel's raw `19:…` id, because Teams often omits the name from the activity. And agents fall back to posts-layout threading in every channel (see [How agents use threads](#how-agents-use-threads)). |+| `Channel.ReadBasic.All` | Several things, all from the same read. Switch reads a channel to learn whether it is standard or private, and adds people differently to each: to the team for a standard channel, to the channel itself for a private or shared one. It will not guess, so after a restart **nobody can be added to any channel** (each person is reported as not added), and binding a room to a channel that **already exists** fails (see [Bringing Switch into a channel that already exists](#bringing-switch-into-a-channel-that-already-exists)). A room auto-created for a channel is saved as private, and titled after the channel's raw `19:…` id because Teams often omits the name from the activity. And agents fall back to posts-layout threading in every channel (see [How agents use threads](#how-agents-use-threads)). || `TeamMember.ReadWrite.All` | People named on a room are not added to a **standard** channel. A standard channel inherits the team's membership, so they are added to the team. || `ChannelMember.ReadWrite.All` | The same, for a **private** channel, which carries its own membership. || `User.ReadBasic.All` | Nobody can link their Switch account to their Teams account, so no agent can @mention its owner. Switch also cannot resolve a sender's name when Teams omits it — 1:1 chats especially — and falls back to their raw id, which then becomes their name in room titles and in every reply that addresses them. |Two of these are easy to skip and expensive to omit. **`Channel.ReadBasic.All`**-looks redundant next to `Channel.Create` and is not: creating a channel and-adopting an existing one are different paths, and only the second reads.+looks redundant next to `Channel.Create` and is not: Switch knows a channel's+privacy when it creates it, but not after a restart or for a channel it did not+create, and it reads the channel to find out.**`User.ReadBasic.All`** looks like it only matters once someone links anaccount, and does not — without it, everyone in Teams is an opaque id toSwitch from the first message.