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
Make the Teams bridge deployable, connectable, and honest when it fails (#208)
Christian McDermottfda7f07d8989
diff --git a/.gitignore b/.gitignoreindex 4fb674e18..be828358b 100644--- a/.gitignore+++ b/.gitignore@@ -238,3 +238,8 @@ related-projects.switchdash-icon-drop/download.txtdownload.xml++# Teams app packages built from docs/bridges/teams-app/. The manifest there+# ships with a placeholder app id on purpose; a built package carries a real+# tenant's, and this directory is where people naturally build one.+docs/bridges/teams-app/*.zipdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 08fcd1094..49d0c9121 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,293 @@ version of their own to them without also giving them a release of their own.### [Unreleased]+#### Added+- Switch's commands appear in Teams' `/` autocomplete picker. The shipped+ manifest moves to schema v1.29 and declares `supportsTargetedMessages` plus a+ second command list with `triggers: ["slash"]`. The two surfaces disagree+ about the slash — the picker prints it and inserts the bare name, while the+ mention menu inserts a title verbatim — so the lists carry the same commands+ spelled for their own surface. A command picked from the picker is sent+ privately to Switch and needs no `@`-mention.++#### Fixed+- A Teams message that merely began with a slash is no longer swallowed as a+ command. Pasting `/Users/ada/notes.md` came back "unknown command" instead of+ reaching an agent. `/` is not Switch's prefix — it opens paths, dates and+ fractions — so an unknown `/name` is now read as text. `!` is Switch's own,+ so `!list-agent` still answers that it is a typo.+- An agent no longer answers Switch's own notices. A system message — a+ command's result, "Added X to this room", the guidance shown when someone+ tags the app itself — is output, not a request for a reply, and the marker+ saying so was honoured by the admin client but not by agents. Two ways in: a+ direct room addresses its agent with every message, so running+ `/list-agents` in a 1:1 chat had the agent start a session to respond to its+ own roster; and any notice that lists the agents present writes each `@name`,+ which tagged all of them. Such a message now arrives as ordinary unaddressed+ context on every platform.++#### Added+- `just teams-app-package` builds the Teams app package an operator uploads.+ Every route into a tenant wants a `.zip` — the Developer Portal's Import app,+ Upload a custom app, the admin centre — and none of them takes a bare+ `manifest.json`, so the guide's "now zip these three files" was a step people+ had to get right by hand. It also writes the app id into the three places it+ has to match, checks the limits Teams enforces without explaining them, and+ exits non-zero naming any placeholder left in, so a null app id cannot ship+ quietly.++#### Changed+- The shipped Teams app manifest declares `supportsChannelFeatures: tier1`.+ Teams requires it of any manifest at schema v1.25 or later whose bot takes+ the `team` scope and refuses the upload without it — a validator rule, not a+ schema one, so the package validated cleanly against the published schema and+ was still rejected. The package builder now checks the same rule.+- The shipped Teams app manifest moves to schema v1.27. It was written at v1.19+ on the reasoning that older schemas upload most reliably; the tenant we+ actually run on is on v1.27, which settles that better than the reasoning+ did. Nothing is removed between the two and the required fields are+ identical, so it is a version bump rather than a rewrite — and v1.25 raised a+ command list's cap from ten entries to twelve, so the menu gains+ `/list-switch-agents` and `/room-url`.++#### Fixed+- A Teams posts channel no longer fills with *"This message has been deleted."*+ Teams substitutes that for any deleted message and keeps it in the post, so+ an agent's status line — posted, moved as the conversation went on, and+ removed at the end — left one behind per move and per turn. Talking to an+ agent produced a column of them. The status is now posted once, stays where+ it is, and is edited to `✓ Done · <elapsed>` when the turn ends, as it+ already was on Mattermost for the same reason. Threads-layout channels delete+ cleanly and are unchanged.+- An agent addressing a Teams user by name produces a real mention again,+ rather than flat text that notifies nobody. Teams offers a *display* name on+ an inbound activity, and that was taken as the person's handle — so someone+ was filed under `Louis Amaudruz`, space and all, while the matcher that turns+ `@name` back into a mention stops at the first space. It looked for `Louis`,+ the directory held `louis amaudruz`, and the two could never meet: anyone+ whose handle contained a space was permanently unmentionable. A display name+ is now traded for the one-word principal name the directory holds, and the+ matcher recognises the names it knows however many words they run to, so+ people already stored the old way work without being renamed.+- Concurrent writes to a bridge's learned `connection_config` no longer lose+ each other. The Teams bridge records a channel's team the first time it sees+ that channel, each from its own session, so a burst of new channels was a+ burst of read-modify-writes on one JSONB value: measured, eight concurrent+ writes landed two. A dropped entry is exactly the state that makes Graph+ refuse that channel's subscription after the next restart. The row is now+ locked for the update, which also stops the serviceUrl writer clobbering it.+- The Graph notification endpoint compares its `clientState` in constant time.+ It is the only control that authenticates a notification's origin, and a+ plain `!=` on a secret leaks its prefix through timing.+- Repairing a placeholder username costs one lookup per person rather than one+ per message. It runs on every inbound message on every bridge, and the common+ case — a stored name that is already fine — was still opening a session and+ querying.+- A Graph read of a Teams channel that fails is retried later instead of being+ believed forever. The name and layout of a channel are read together and+ cached, and a failure was cached with them — so one blip, or a permission+ granted a minute after the bridge started, left that channel nameless and+ threaded as a posts channel for the life of the process. Learning a channel's+ team now also discards anything read against the previous one, since a read+ made against the wrong team is exactly the read Graph refuses.+- The rejection an inbound Teams activity gets when it is addressed to the+ wrong app id names the audience the token carries — and now reads that back+ out of a signature-verified decode rather than an unverified one. The+ signature had in fact already been checked by the time this ran, so nothing+ was exploitable, but quoting an unverified claim in the message explaining+ why a caller was rejected is a habit worth not having.+- Teams channel capture no longer dies at a restart for any channel outside the+ connection's configured team. A Graph subscription names the team as well as+ the channel, and the team is only ever carried on an inbound activity — held+ in memory it was lost on restart, and those channels fell back to the+ configured team, where Graph answers "Channel is not present in the team".+ Nothing recovered it: refilling the map needs an activity from the channel,+ and without capture Teams delivers only messages mentioning the bot, so+ addressing an agent — the normal way to use the room — never arrived. The+ mapping is now persisted the way the Bot Connector endpoint already was.++#### Added+- Teams accepts `/command` as well as `!command`, and the setup guide carries+ the app-manifest snippet that puts the commands above the compose box. Teams+ has no server-registered slash commands: a manifest command list types the+ text and the bot parses it, so the two prefixes are the same thing by the+ time Switch sees them — but people arriving from Slack try `/` first, and+ until now got nothing.++- The Helm chart can publish and route the Microsoft Teams bridge listener. The+ Teams adapter serves Bot Framework activities and Graph change notifications+ from its own HTTP server on port 3978, separate from the API on 8000, and+ nothing in the chart exposed it — so a Teams bridge could create channels and+ post while receiving nothing back, looking healthy throughout. Set+ `switchCore.teamsBridge.enabled=true` to publish the container and Service+ port, and `switchCore.teamsBridge.ingress.mode` to say how the two callback+ paths are routed: `dedicated` renders a second Ingress carrying only those+ paths on their own host and certificate, so Microsoft can reach them while the+ gateway stays internal; `shared` adds them to the chart's managed Ingress;+ `external` leaves the routing to you (see `samples/ingress.example.yaml`).+ Off by default, because bridges are created at runtime and the chart cannot+ detect one.+- The Teams Ingress supports sitting behind a CDN or reverse proxy: leave its+ `host` empty and TLS off, and it renders a host-less rule that answers+ whatever `Host` arrives. That is the shape needed when the public name belongs+ to something upstream, and it is the only option that needs no domain of your+ own — the setup doc carries the CloudFront recipe, including the two settings+ (forward query strings, do not cache) without which Graph's subscription+ handshake fails. Empty `host` with TLS enabled is still rejected, since a+ host-less rule cannot carry a certificate.+- The chart now refuses to render a Teams bridge that nothing can reach —+ enabled with no routing mode, `shared` without a managed Ingress, or either+ managed mode without a hostname. Publishing the port without a route is the+ silent half-failure the rest of this work exists to prevent, so it is a+ render-time error rather than something found days later.+- `helm test` checks the Teams listener, running Graph's own validation+ handshake against the Service. It proves the listener is bound and the port+ published; it runs in-cluster, so it deliberately does not claim anything+ about public reachability, and says so.+- Post-install notes print the exact `public_base_url` to paste into the bridge,+ and warn when its Ingress has TLS disabled — Graph only calls HTTPS it trusts.+- The Helm chart has a `README.md`, covering which of Switch's three network+ surfaces have to be reachable from where. Only the Teams listener needs the+ public internet; every other bridge connects outbound.+- Registering a bridge that would contend with an existing one for a host+ resource is refused, naming what clashed. Teams is the case that has one: its+ inbound listener needs a TCP port, and a second bridge on the same port failed+ to bind inside a background task, was dropped from the running set, and never+ retried — surfacing much later as `Bridge not running: <id>` with no stated+ cause. Adapters declare this by implementing `exclusive_resource`; those that+ only dial out declare nothing and are unaffected. The same check runs at+ startup, so rows predating it get a clear error instead of a bind failure.+- Bridge credentials are verified before a bridge is saved. Adapters start in a+ background task whose exceptions are logged and swallowed, so credentials that+ the platform rejects used to be stored, reported as success, and surface hours+ later as an unrelated-looking failure. Registering a Teams bridge now asks+ Azure for both tokens it will need first, and a refusal comes back as a 400+ carrying Microsoft's own explanation — which names the mistake outright,+ including the client secret **value** vs secret **ID** mix-up. Adapters opt in+ by implementing `verify_credentials`; the default still accepts anything,+ because an adapter that cannot check cheaply should not pretend to.++#### Changed+- A Teams bridge is five fields instead of nine. The `clientState` shared secret+ and the Graph encryption certificate, public key and private key are generated+ when the bridge is created rather than asked for: they are values the operator+ invents rather than gets from Microsoft, and asking meant an invented secret,+ an `openssl` invocation, and three PEM fields whose only symptom when pasted+ wrong is channel capture that silently never decrypts. Supplying your own+ through the API still wins, all three or none. Existing bridges are untouched,+ including any left without encryption material.+- The Teams Graph private key is no longer typed into a plaintext form field.+ The gateway decides which inputs to mask by matching the field name against+ `token|password|secret|api_key`, which `encryption_private_key` does not match;+ generating it removes the field from the form entirely.+- `docs/bridges/TEAMS_SETUP.md` rewritten. It now walks through Azure setup+ value by value and says where each one comes from, documents the deployment+ and public-ingress requirements (previously absent), and adds verification and+ troubleshooting sections keyed to the errors these failures actually produce —+ starting with the client secret **value** vs secret **ID** mix-up, which+ surfaces only as an opaque `AADSTS7000215` at the first Graph call.++#### Fixed+- Following an "Open in Switch Console" link no longer strands the browser tab.+ The gateway answered the click with a bare `302` to the `switchdash://`+ deeplink; the browser hands that to the desktop app without loading a page,+ so the tab kept whatever it last rendered — on Teams, Defender's Safe Links+ interstitial, still saying "Verifying link . . ." after Switch Console had+ opened, which reads as a link that hung. It now serves a page that opens the+ app, tries to close itself, and — since browsers only let a script close a+ window a script opened — otherwise says the handover worked and the tab can+ be closed.+- A Graph permission granted while the bridge is running takes effect on the+ next call instead of within the hour. An app's roles are stamped into its+ access token when it is issued, so consent granted afterwards is invisible+ for the token's lifetime — Graph keeps answering `Authorization_RequestDenied`+ on a permission the operator can see plainly granted in Azure, which sends+ them back to look at it again. A `401` or `403` from Graph now discards the+ cached token and retries once with a fresh one. Once, and only when the token+ was old enough to have missed the grant, so a genuine denial costs one extra+ round trip rather than looping.+- A person recorded under a Teams id gets their name back on their next+ message. Switch files someone under the name it is first given, and Teams+ often gives none — a 1:1 activity carries no sender name — so its own id went+ in and then read as that person's name in room titles, on their Matrix+ account and in every agent reply addressing them. Resolving names properly+ helped only people met afterwards; this repairs the records already written,+ without a migration. One-way by design: an id becomes a name, never the+ reverse, and one name never replaces another.+- A Teams channel with no name in its activity is looked up in Graph rather+ than falling back to its id, so an auto-created room is called something a+ person recognises instead of `19:7641f9de326b4…`. Cached, including the+ "asked and could not say" case.+- An agent's first message in a Teams channel opens a post and everything it+ says next joins that post. It used to open a fresh one each time, so an agent+ introducing itself produced a column of one-line posts rather than a+ conversation.+- An agent answering in a Teams channel replies inside the post it was asked+ in. A channel is a list of posts rather than a stream, so posting at the root+ opens a new conversation — the question sat in one post and the answer+ appeared as a fresh one below it. A reply that names no thread now goes to+ the post the bridge last saw that channel speak in. Per channel, so two+ conversations at once in the same channel can still cross; Teams offers no+ better signal on an untied reply, and the wrong post beats a new one every+ time. Chats and group chats are unaffected.+- Teams messages are rendered for Teams. Shared bridge code emitted Slack's+ `<@id>` mention form on every platform, so a Teams user was told they had+ tagged `<@28:11111111-…>`; an `@name` was inert text, because Teams needs+ `<at>` markup *and* a matching entity and the adapter emitted neither, so an+ agent could never notify its owner; and single line breaks vanished, because+ an Adaptive Card text block follows Markdown in treating one newline as+ whitespace. Outbound bodies were also being rendered twice — callers of+ `send_message` render first by contract, and Slack and Teams rendered again,+ which Slack's real conversion has been quietly suffering.+- A Teams sender with no name attached is looked up rather than filed under+ their id. Teams omits the sender's name from some activities — 1:1 chats+ especially — and the raw `29:…` id became that person's name in the room+ title, on their Matrix account and in every reply addressing them. The+ directory and the message paths now also agree on one handle (the local part+ of the principal name) instead of storing a principal name from one and a+ display name from the other. Existing records keep the name they were+ created with.+- Directory search matches on user principal name, so confirming a claim finds+ the person who was just picked from the list. It searched display name and+ mail only, then re-searched by principal name to confirm — a 404 for anyone+ whose mail differs from their UPN or who has none. `User.ReadBasic.All` is+ also now documented; without it the search fails and nobody can link an+ account at all.+- The "Open in Switch Console" link no longer renders as empty brackets on+ Teams. Teams strips a link whose scheme is not http(s) — label included —+ and the console deeplink is `switchdash://`. Teams now declares that, so the+ URL is rewritten to the gateway redirect as it already was for Discord and+ Telegram, and a deployment missing `GATEWAY_PUBLIC_URL` is told at startup.+- Adding a room to a bridge no longer answers `500` when the platform refuses+ to create the channel. Graph says exactly what is wrong — which permission is+ missing, which value it will not take — and that sentence went to the log+ while the operator got an unhandled exception. Platform refusals are now+ `BridgeOperationError`, the counterpart to `BridgeCredentialError` for+ everything after the credentials are accepted, and room creation returns a+ `502` quoting the platform. Registering a bridge only proves it will issue a+ token, so this class of failure always surfaces after setup has reported+ success. Only the Teams adapter raises it so far.+- A Teams channel subscription that fails is retried instead of leaving capture+ dead until someone restarts the process. Graph validates a notification URL+ by calling it, and the bridge asks for its subscriptions seconds after+ binding its port — behind a load balancer that is precisely when nothing+ answers yet, so the first attempt after *every* restart was refused and the+ restart that broke capture was also the only thing that could fix it. The+ retry backs off to a few minutes and says so when capture recovers; repeats+ of an unchanged failure are quiet, but a change of reason is not.+- Binding a room to a collaboration channel that already exists now establishes+ message capture for it. Capture was only ever set up as a side effect of+ *creating* a channel, so a room pointed at an existing one — on creation, on+ linking a bridge to an internal room, or on moving a room between bridges —+ heard nothing but the messages that @mentioned it. Invisible on bridges whose+ capture is one bridge-wide stream, and on Teams it survived only until the+ next restart happened to reconcile it.+- A Teams activity rejected for the wrong audience says which audience it+ carried and which one the bridge expects. The rejection is almost always the+ Azure Bot resource and the registered app registration having different app+ ids, and the message it replaced — `Audience doesn't match` — named neither,+ so the one fact needed to fix it was the one fact not logged.+### [0.20.0] - 2026-08-24#### Addeddiff --git a/README.md b/README.mdindex 7e752d9f4..3a0438cf6 100644--- a/README.md+++ b/README.md@@ -194,6 +194,127 @@ dashboard covers the rest.one up for you, on this machine or on a host you own, without you writing anyCompose or Helm configuration.+1. In the gateway, create a room (and note its id).+2. Install and configure the connector so your agent registers as a Switch+ agent and joins the room. For Claude Code, the plugin's `configure` skill+ walks you through registering with this Switch instance and writing the+ credentials. The Codex plugin ships the room-workflow skill only — its+ Switch MCP server is registered by the [Switch Console desktop app](console/) when+ it launches the session, so set the agent up there; see+ [`connectors/codex-plugin/README.md`](connectors/codex-plugin/README.md).+3. Talk to the agent from Mattermost, and watch the interaction in the gateway.++Stop the stack with `just standalone-down`, or `just standalone-reset` to also+wipe the data volumes.++> ⚠️ **`just standalone-reset` is destructive.** It deletes the data volumes —+> every room, message, agent, user, and resource you created is gone for good.+> Use `just standalone-down` for an ordinary stop that keeps your data.++## Getting started (local development)++**Prerequisites:** [Docker](https://docs.docker.com/get-docker/),+[uv](https://docs.astral.sh/uv/), and [just](https://github.com/casey/just)+(`brew install just`).++```bash+just init-env # first-time setup — generate .env with random secrets+uv sync # install Python dependencies+just gateway-install # install gateway frontend deps (first time only)+just up # start the supporting stack (Docker Compose)+just run # run switch-core locally (:8000)+just gateway-dev # run the gateway frontend (separate terminal)+```++`just up` starts the **supporting services** in Docker — Tuwunel, PostgreSQL,+and Mattermost. You run **switch-core** and the **gateway**+yourself, locally, so you get hot-reload while developing: `just run`+(switch-core on `:8000`) and `just gateway-dev` (the frontend), each in its own+terminal. Stop the stack with `just down` (or `just reset` to also wipe+volumes).++## Common commands++Run `just` with no arguments to list every recipe. The most-used ones:++| Command | What it does |+|---|---|+| `just init-env` | Generate `.env` with freshly generated secrets (no default login) |+| `just up` / `just down` | Start / stop the local dev stack |+| `just reset` | Stop the stack and wipe volumes (incl. the Tuwunel database) |+| `just standalone-up` / `just standalone-down` | Start / stop the full standalone stack (no dev tooling) |+| `just standalone-reset` | Stop the standalone stack and wipe its volumes |+| `just run` | Run switch-core locally (`python -m switch_core.main`) |+| `just migrate` | Apply migrations (`alembic upgrade head`) |+| `just migration "msg"` | Autogenerate a new Alembic migration |+| `just format` | Format + autofix with ruff |+| `just check` | Lint/format check (CI mode, no changes) |+| `just typecheck` | Type-check with mypy |+| `just test` | Run the test suite (`pytest core/tests/`); `just test -k name` for one test |+| `just gateway-dev` / `just gateway-build` | Run / build the gateway frontend |++## Architecture++The platform service lives in [`core/switch_core/`](core/switch_core/)+(import root `switch_core`, distribution name `switch-core`). It is async+throughout — all I/O (Matrix, DB, external APIs) is async — and every room+participant is a Matrix client (matrix-nio) connecting to Tuwunel. Persistence+is PostgreSQL, managed with Alembic.++Module layout under `core/switch_core/`:++| Module | Responsibility |+|---|---|+| `config.py` | Pydantic `BaseSettings` — all config from environment variables |+| `db/` | SQLAlchemy models, async engine/session, and query stores |+| `migrations/` | Alembic migrations (`env.py`, `versions/`) |+| `rooms/` | Room lifecycle, configuration, provisioning |+| `clients/` | Matrix clients (agent, user, resource manager, observe) |+| `bridges/` | External integrations — `agent/`, `collaboration/`, `observe/`, `resource/` |+| `protect/` | Protection pipeline (checks, protect bridge, API) |+| `gateway/` | Management API for the frontend |++The operator dashboard frontend lives in [`gateway/`](gateway/)+(Node/Vite, served via nginx).++## Documentation++User-facing documentation is published at+**[docs.flintai.dev](https://docs.flintai.dev/flintai/switch/getting-started)** —+installing Switch Console, adding a server, onboarding agents, creating rooms,+[connecting a messaging app](https://docs.flintai.dev/flintai/switch/deploy/messaging-apps)+and [hosting remotely](https://docs.flintai.dev/flintai/switch/deploy/host-remotely).++Design and protocol references for contributors live in [`docs/`](docs/):+[`ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the system overview and+[`api/AGENT_PROTOCOL.md`](docs/api/AGENT_PROTOCOL.md) for the agent protocol.++## Repository layout++| Path | Contents |+|---|---|+| `core/` | Backend tree — a self-contained Python project (`pyproject.toml`, `uv.lock`, `alembic.ini`) holding the service package and tests |+| `core/switch_core/` | The main Python service package (import root `switch_core`, dist `switch-core`) |+| `core/tests/` | Test suite, mirroring the `switch_core/` module structure |+| `gateway/` | Operator dashboard frontend (Node/Vite) |+| `console/` | The Switch Console desktop app |+| `connectors/` | Agent connectors (`claude-code-plugin`, `codex-plugin`) |+| `deploy/` | Deployment assets — Docker Compose stacks (`local/`), the Kubernetes Helm chart (`remote/helm/switch/`, see its [README](deploy/remote/helm/switch/README.md)) and shared resources |+| `justfile` | Repo-root task runner (drives all three code trees) |++## Testing++Tests live in `core/tests/switch_core/` and mirror the module structure. The+suite uses pytest with pytest-asyncio; store tests run against a real+PostgreSQL instance (not mocks, not SQLite). Run them with `just test`.++## License++Agent Switch is licensed under the **Apache License 2.0 with the Commons Clause**+condition (Copyright (c) 2026 SB Technology, Inc. dba SandboxAQ) — see+[`LICENSE`](LICENSE) for the full text. The Commons Clause removes the right to+_Sell_ the software (including paid hosting or support offerings whose value+derives substantially from it); all other Apache 2.0 grants are unchanged.## Contributingdiff --git a/core/switch_core/bridges/agent/deeplink.py b/core/switch_core/bridges/agent/deeplink.pyindex 48c982c7f..f837c456a 100644--- a/core/switch_core/bridges/agent/deeplink.py+++ b/core/switch_core/bridges/agent/deeplink.py@@ -1,24 +1,77 @@from __future__ import annotations+from html import escape+from fastapi import APIRouter, Request-from fastapi.responses import RedirectResponse+from fastapi.responses import HTMLResponsefrom switch_core.deeplinks import gateway_query_to_switchdashrouter = APIRouter()+# Handing a browser off to a desktop app leaves a tab behind, and what that tab+# shows is whatever it last rendered. A 302 renders nothing, so the tab kept the+# page it came from — on Teams, Defender's Safe Links interstitial, still saying+# "Verifying link . . ." long after Switch Console had opened. It reads as a+# link that hung.+#+# So render something. Closing the tab is attempted but cannot be relied on:+# browsers only let a script close a window that a script opened, and this one+# was opened by a click in Teams. When the close is refused the page says the+# handover worked and the tab can go — which is the true statement the blank+# redirect never made.+#+# The target is interpolated into an href and read back out of the DOM rather+# than written into a script. This endpoint is public and its query string comes+# from whoever clicked, so the escaping is load-bearing; the scheme and host are+# fixed constants, leaving no way to point the anchor at another scheme.+_HANDOFF_PAGE = """<!doctype html>+<html lang="en">+<meta charset="utf-8">+<title>Opening Switch Console</title>+<meta name="viewport" content="width=device-width, initial-scale=1">+<style>+ body {{ font: 16px/1.5 system-ui, sans-serif; margin: 0; display: grid;+ place-items: center; min-height: 100vh; text-align: center;+ color: #1a1a1a; background: #fafafa; }}+ @media (prefers-color-scheme: dark) {{+ body {{ color: #f0f0f0; background: #141414; }}+ }}+ main {{ padding: 2rem; max-width: 28rem; }}+ p {{ margin: 0.5rem 0; }}+ .muted {{ opacity: 0.7; font-size: 0.9em; }}+</style>+<main>+ <p id="status">Opening Switch Console…</p>+ <p class="muted">+ <a id="target" href="{target}">Open it manually</a> if nothing happens.+ </p>+</main>+<script>+ var target = document.getElementById("target");+ var status = document.getElementById("status");+ window.location.href = target.href;+ window.setTimeout(function () {{+ window.close();+ status.textContent = "Switch Console is open. You can close this tab.";+ }}, 500);+</script>+</html>+"""++@router.get("/deeplink/session")-async def redirect_session_deeplink(request: Request) -> RedirectResponse:- """302-redirect to the `switchdash://session?…` deeplink.+async def redirect_session_deeplink(request: Request) -> HTMLResponse:+ """Hand the browser off to the `switchdash://session?…` deeplink.- Platforms that only linkify http(s) (Discord, …) can't render the raw+ Platforms that only linkify http(s) (Teams, Discord, …) can't render the rawcustom-scheme deeplink, so the bridge posts this https URL instead and theclick lands here. The incoming query string is carried across verbatim; thescheme and host of the target are fixed constants, so this cannot be coercedinto an open redirect. Public by design — the link is followed by whoever- clicks it in the external channel, and it serves no data beyond the redirect+ clicks it in the external channel, and it serves no data beyond the handoff(its `/deeplink` prefix is in the Bearer middleware's public allowlist)."""target = gateway_query_to_switchdash(request.url.query)- return RedirectResponse(url=target, status_code=302)+ return HTMLResponse(_HANDOFF_PAGE.format(target=escape(target, quote=True)))diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 27e1524ca..f5c5e24e8 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -24,6 +24,27 @@ from switch_core.bridges.collaboration.models import (logger = logging.getLogger(__name__)+def format_elapsed(seconds: float) -> str:+ """How long a turn took, for the marker its status line becomes.++ Rounded to whole seconds and written the way a reader skims it — "8s",+ "2m14s", "1h03m" — rather than as a precise duration nobody reads. Sub-+ second turns report "0s" instead of an empty string.++ Lives here rather than beside one adapter because every platform that+ retires a status line by editing it rather than deleting it wants the same+ words on it.+ """+ total = max(0, int(seconds))+ if total < 60:+ return f"{total}s"+ minutes, secs = divmod(total, 60)+ if minutes < 60:+ return f"{minutes}m{secs:02d}s"+ hours, minutes = divmod(minutes, 60)+ return f"{hours}h{minutes:02d}m"++@dataclass(frozen=True)class LiveRuntimeIndicator:"""The runtime status message currently posted for one agent in one channel.@@ -128,6 +149,57 @@ class CollaborationAdapter(ABC):def set_max_attachment_bytes(self, max_bytes: int) -> None:self._max_attachment_bytes = max_bytes+ @classmethod+ async def prepare_config(+ cls, connection_config: dict[str, object]+ ) -> dict[str, object]:+ """Fill in values the operator should not have to supply, at create time.++ Called once, when a bridge is registered — never on start, so a value+ minted here is persisted and stable for the life of the bridge. An+ adapter that generates key material must do it here rather than in a+ model default, or every restart would mint a fresh one and quietly+ invalidate whatever the last one signed or encrypted.++ Async because generating key material is CPU-bound and this runs on+ the event loop that carries every live Matrix session.+ """+ return connection_config++ @classmethod+ def exclusive_resource(cls, connection_config: dict[str, object]) -> str | None:+ """Name a host resource this bridge needs to itself, if any.++ Two bridges returning the same string cannot coexist in one process.+ Returning None — the default — means a bridge of this type can be run+ alongside any number of its own kind, which is true of every adapter+ that only dials out.++ The returned string is quoted verbatim in the refusal shown to whoever+ registers the second bridge, so it must not embed credential material.++ The point is to refuse the second one at registration, with a sentence+ saying what clashed. Without it the collision surfaces as whatever the+ underlying resource does when contended, which for a TCP port is a bind+ error inside a background task, minutes later and nowhere near the+ operator who caused it.+ """+ return None++ @classmethod+ async def verify_credentials(cls, connection_config: dict[str, object]) -> None:+ """Prove the credentials work, before the bridge is persisted.++ Raise :class:`BridgeCredentialError` with a message fit for an operator+ to read. Adapters start in a background task whose exceptions are logged+ and swallowed, so without this a wrong password looks like success and+ surfaces hours later as an unrelated-looking failure.++ The default accepts anything: an adapter that cannot check cheaply+ should not pretend to.+ """+ return None+@abstractmethodasync def start(self,@@ -194,13 +266,45 @@ class CollaborationAdapter(ABC):def _bridge_display_name(self) -> str:return "Switch"+ def is_placeholder_username(self, username: str) -> bool:+ """Whether a stored name for a person is really one of this platform's+ opaque ids, recorded because nothing better was available at the time.++ Switch files a person under the name it first sees, and some platforms+ do not always supply one — Teams omits it from a 1:1 chat activity. The+ id then becomes that person's name everywhere: their Matrix account,+ the title of any room auto-created for them, and every agent reply that+ addresses them. Fixing the resolution stops it happening to the next+ person and does nothing for the ones already recorded, so an adapter+ that can recognise its own ids says so here and the name is repaired+ the next time they speak.++ Default False: on a platform whose handles are handles, there is+ nothing to recognise and nothing to repair.+ """+ return False++ def render_app_mention(self, token: str) -> str:+ """Render a mention of the Switch app itself, given the platform's own+ handle for it.++ Mention syntax is per-platform and the caller is not: this is used by a+ notice in shared bridge code, which for a long time emitted Slack's+ ``<@id>`` form everywhere. Slack renders that as the app's name; Teams+ prints it verbatim, so a user was told they had tagged+ ``<@28:11111111-…>``. Override wherever that form is not what the+ platform reads.+ """+ return f"<@{token}>"+def slash_invite_hint(self) -> str | None:"""How to run `invite-agent` as a native slash command here, if at all.- Native slash commands are per-platform: Slack declares them in its app- manifest, Discord registers them per guild and Telegram publishes a bot- command menu, while Mattermost and Teams have none — so the no-agents- notice must not advertise a `/` form on a bridge that has none to offer.+ The `/` form is per-platform: Slack declares its commands in the app+ manifest, Discord registers them per guild, and Telegram and Teams+ accept `/` as an ordinary message prefix, while Mattermost has nothing —+ so the no-agents notice must not advertise a `/` form on a bridge that+ has none to offer.The invocation differs too, since Slack and Telegram take a free-texttail where Discord names each argument as its own field, so each adapterspells out its own.@@ -506,7 +610,18 @@ class CollaborationAdapter(ABC):topic: str,*,channel_type: ChannelType = "channel_public",- ) -> str: ...+ ) -> str:+ """Provision a channel on the platform and return its external id.++ When the platform *refuses* — a permission not consented, a name it+ will not take — raise :class:`BridgeOperationError` carrying what the+ platform said. Room creation turns that into a 502 quoting it, so the+ operator who asked for the room learns why it failed; anything else+ becomes an opaque 500 and the explanation stays in the log. Raise+ :class:`ChannelCreationUnsupported` instead when declining without+ asking the platform at all.+ """+ ...async def create_dm_channel(self,@@ -604,7 +719,20 @@ class CollaborationAdapter(ABC):channel_id: str,user_names: list[str],user_external_ids: list[str],- ) -> None: ...+ ) -> list[str]:+ """Add the given people to a channel; return the ids that could not be.++ ``user_names`` and ``user_external_ids`` are positionally paired.++ A person who cannot be added is a poor reason to fail the whole+ operation — the caller is usually creating a room, and abandoning it+ over one guest account or one missing platform permission leaves a+ half-provisioned room behind and tells the operator nothing. Nor should+ it pass silently, which reports a room that quietly lacks the people+ asked for. So: continue, and hand back who was left out for the caller+ to disclose.+ """+ ...@abstractmethodasync def create_agent_identity(@@ -658,6 +786,19 @@ class CollaborationAdapter(ABC):carried on inbound activities) override this to persist it."""return None+ def set_channel_team_persister(+ self, persist: Callable[[str, str], Awaitable[None]]+ ) -> None:+ """Install a callback the adapter uses to persist which container a+ channel belongs to, when that is learned from inbound traffic rather+ than configured.++ Default is a no-op; Teams overrides it because a Graph message+ subscription is created against `teams/{team}/channels/{channel}`, and+ the team arrives only on an inbound activity. Losing it on restart+ silently kills capture in every channel outside the configured team."""+ return None+def set_channel_migration_handler(self, handler: Callable[[str, str], Awaitable[None]]) -> None:diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 1453fcc6f..2c1f417e8 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -139,6 +139,11 @@ class BridgeCore:self._channel_to_room: dict[str, tuple[str, str]] = {}self._room_to_channel: dict[tuple[str, str], str] = {}self._user_puppets: dict[str, str] = {}+ # External user ids whose stored name is known not to be a platform id,+ # so the placeholder repair does not re-ask the database once per+ # message. One-way, so a cached answer cannot go stale — see+ # _repair_placeholder_username.+ self._names_known_good: set[str] = set()self._puppet_matrix_ids: set[str] = set()self._channel_locks: dict[str, asyncio.Lock] = {}self._puppet_locks: dict[str, asyncio.Lock] = {}@@ -344,7 +349,7 @@ class BridgeCore:if agent is not None:agents.append((agent.name, agent.description))- app_mention = f"<@{token}>"+ app_mention = self._adapter.render_app_mention(token)if agents:agent_list = "\n".join(f"• @{name} — {description}" for name, description in agents@@ -464,6 +469,7 @@ class BridgeCore:if mention_target is None:await self._maybe_guide_self_mention(msg, room_id)+ await self._repair_placeholder_username(msg.sender_id, msg.sender_name)puppet = await self._ensure_user_in_matrix_room(external_user_id=msg.sender_id,external_username=msg.sender_name,@@ -1038,6 +1044,74 @@ class BridgeCore:# ── Puppet lifecycle ─────────────────────────────────────────────────────+ async def _repair_placeholder_username(+ self, external_user_id: str, resolved_username: str+ ) -> None:+ """Replace a stored name that is really a platform id, now we have one.++ Switch files someone under the name it first saw, and a platform that+ supplied none left its own id there — which then reads as that person's+ name in the room title, on their Matrix account and in every agent+ reply that addresses them. Repairing on the way past needs no migration+ for the rows already written.++ Runs on every inbound message on every bridge, so the common path — a+ stored name that is fine — must not cost a query. Once someone's stored+ name is known not to be a placeholder it cannot become one again (the+ repair below is one-way), so that answer is remembered and the lookup+ happens once per person rather than once per message.++ Deliberately one-way: an id is replaced by a name, never the reverse,+ and a name is never replaced by another name. Renaming someone people+ have been addressing for weeks because a platform changed its mind about+ their display name would be worse than the problem.+ """+ if not resolved_username or not external_user_id:+ return+ if external_user_id in self._names_known_good:+ return+ if self._adapter.is_placeholder_username(resolved_username):+ return+ async with self._session_factory() as session:+ existing = await self._external_user_store.get_by_external_id(+ session, self._bridge_id, external_user_id+ )+ if existing is None:+ # Not filed yet; the caller creates them a moment later under+ # the name we already have, so there is nothing to repair and+ # nothing worth remembering.+ return+ if existing.external_username == resolved_username or not (+ self._adapter.is_placeholder_username(existing.external_username)+ ):+ self._names_known_good.add(external_user_id)+ return+ logger.info(+ "Renaming external user %s from its %s id to '%s'",+ external_user_id,+ self._bridge_type,+ resolved_username,+ )+ await self._external_user_store.rename(+ session, existing.id, resolved_username+ )+ await session.commit()+ client_id = existing.client_id+ # The Matrix account keeps its localpart — that is an address, and+ # changing it would orphan the history — but its display name is what+ # people read.+ puppet = self._client_lifecycle.get(client_id)+ if puppet is not None:+ try:+ await puppet.set_display_name(resolved_username)+ except Exception:+ logger.warning(+ "Renamed external user %s but could not update the display "+ "name of its Matrix account",+ external_user_id,+ exc_info=True,+ )+async def ensure_external_user(self, *, external_user_id: str, external_username: str) -> ExternalUser:diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 95ef948cc..f794c625c 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -896,13 +896,14 @@ class DiscordAdapter(CollaborationAdapter):channel_id: str,user_names: list[str],user_external_ids: list[str],- ) -> None:+ ) -> list[str]:channel = await self._get_channel(int(channel_id))if self._channel_type_of(channel) != "channel_private":# Public guild channels are visible to every member — there is no# per-channel membership to grant.- return+ return []guild = channel.guild+ failed: list[str] = []for user_name, user_id in zip(user_names, user_external_ids):try:member = await self._get_member(guild, user_id)@@ -915,6 +916,8 @@ class DiscordAdapter(CollaborationAdapter):channel_id,e,)+ failed.append(user_id)+ return failed# ── Agent identity ───────────────────────────────────────────────────────diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 3d0b5c7c2..83c9871ad 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -80,6 +80,22 @@ class CollaborationBridgeLifecycleService:self._config_registry: dict[str, type[BridgeConnectionConfig]] = {}self._bridges: dict[str, BridgeCore] = {}self._tasks: dict[str, asyncio.Task[None]] = {}+ # bridge_id -> the host resource it holds exclusively while running+ # (see CollaborationAdapter.exclusive_resource). Lets a second+ # claimant be refused by name instead of failing on the resource.+ self._held_resources: dict[str, str] = {}+ # Serialises registration. The exclusivity check reads the stored+ # bridges and the winner is not written until several awaits later,+ # so two concurrent registrations would both see a free resource and+ # both take it — the very collision the check exists to refuse.+ #+ # A process-wide lock is sufficient *because* switch-core is a+ # singleton: the chart fails the render for replicaCount != 1, since+ # it holds live Matrix sessions in memory. If that ever changes, this+ # has to become a database constraint — the way the single-default+ # bridge invariant already is — because a lock in one process would+ # then be guarding nothing.+ self._register_lock = asyncio.Lock()def register_adapter(self,@@ -179,6 +195,61 @@ class CollaborationBridgeLifecycleService:except Exception:logger.exception("Failed to start bridge %s", bridge.id)+ async def _reject_resource_conflict(+ self,+ bridge_type: str,+ connection_config: dict[str, object],+ *,+ exclude_bridge_id: str | None = None,+ ) -> None:+ """Refuse a bridge that would contend for a resource another one holds.++ Checked against every stored bridge rather than the running set, so the+ answer does not depend on whether the incumbent happens to be up.+ """+ adapter_cls = self._adapter_registry.get(bridge_type)+ if adapter_cls is None:+ return+ wanted = adapter_cls.exclusive_resource(connection_config)+ if wanted is None:+ return++ async with self._session_factory() as session:+ existing = await self._bridge_store.get_all(session)+ for other in existing:+ # Guard the None case explicitly: an unflushed row has no id yet, and+ # `other.id == exclude_bridge_id` would then be None == None and skip+ # a bridge that genuinely holds the resource.+ if exclude_bridge_id is not None and other.id == exclude_bridge_id:+ continue+ if other.type != bridge_type:+ continue+ other_cls = self._adapter_registry.get(other.type)+ if other_cls is None:+ continue+ try:+ held = other_cls.exclusive_resource(other.connection_config or {})+ except Exception:+ # A stored config we can no longer parse should not block a new+ # bridge — it is its own problem, and it is already logged when+ # that bridge tries to start.+ logger.warning(+ "Could not read the exclusive resource of bridge %s (%s)",+ other.id,+ other.type,+ exc_info=True,+ )+ continue+ if held == wanted:+ raise ValueError(+ f"'{other.display_name}' already uses {wanted} on this "+ f"instance, and two {bridge_type} bridges cannot share it. "+ "Delete that bridge first, or give this one a different "+ "listen_port in its connection_config — noting the Helm "+ "chart publishes only one Teams port, so a second one needs "+ "its own Service port and route."+ )+async def register(self,*,@@ -186,6 +257,22 @@ class CollaborationBridgeLifecycleService:display_name: str,connection_config: dict[str, object],channel_creation_enabled: bool,+ ) -> CollaborationBridge:+ async with self._register_lock:+ return await self._register_locked(+ bridge_type=bridge_type,+ display_name=display_name,+ connection_config=connection_config,+ channel_creation_enabled=channel_creation_enabled,+ )++ async def _register_locked(+ self,+ *,+ bridge_type: str,+ display_name: str,+ connection_config: dict[str, object],+ channel_creation_enabled: bool,) -> CollaborationBridge:adapter_cls = self._adapter_registry.get(bridge_type)config_cls = self._config_registry.get(bridge_type)@@ -199,7 +286,21 @@ class CollaborationBridgeLifecycleService:"platform and add the bot to it; Switch adopts it as a room.")- config_cls.model_validate(connection_config)+ # Fill in what the adapter generates, validate the result, and persist+ # the validated form — not the raw request — so a value minted here is+ # stored once and never re-derived.+ connection_config = await adapter_cls.prepare_config(connection_config)+ validated = config_cls.model_validate(connection_config)+ connection_config = validated.model_dump(mode="json")++ await self._reject_resource_conflict(bridge_type, connection_config)++ # Before anything is written. The adapter runs in a background task+ # whose failures are logged and swallowed, so credentials that are wrong+ # would otherwise be stored, reported as success, and only surface later+ # as an unrelated-looking error. Failing here also avoids leaving an+ # orphan Matrix identity behind for a bridge that was never viable.+ await adapter_cls.verify_credentials(connection_config)bridge_client_record = await self._client_lifecycle.create_client(client_type="bridge",@@ -240,11 +341,30 @@ class CollaborationBridgeLifecycleService:if adapter_cls is None or config_cls is None:raise ValueError(f"Unknown bridge type: {bridge.type}")+ # Registration refuses a conflicting bridge, but rows predating that+ # check still exist, and start_all would otherwise walk into the bind+ # error one of them causes. Say which bridge holds it instead.+ wanted = adapter_cls.exclusive_resource(bridge.connection_config or {})+ if wanted is not None:+ for other_id, held in self._held_resources.items():+ if held == wanted and other_id != bridge_id:+ raise ValueError(+ f"Cannot start bridge {bridge_id} ({bridge.type}): "+ f"{wanted} is already held by bridge {other_id}. Only "+ "one of them can run; delete one, or give it a "+ "different listen_port."+ )+typed_config = config_cls.model_validate(bridge.connection_config or {})adapter = adapter_cls(config=typed_config) # type: ignore[call-arg]adapter.set_service_url_persister(lambda service_url: self._persist_service_url(bridge_id, service_url))+ adapter.set_channel_team_persister(+ lambda channel_id, team_id: self._persist_channel_team(+ bridge_id, channel_id, team_id+ )+ )adapter.set_max_attachment_bytes(self._config.agent_media_max_bytes)if (@@ -307,6 +427,8 @@ class CollaborationBridgeLifecycleService:)self._bridges[bridge_id] = bridge_coreself._tasks[bridge_id] = task+ if wanted is not None:+ self._held_resources[bridge_id] = wantedlogger.info("Started collaboration bridge %s (%s)", bridge_id, bridge.type)@@ -317,6 +439,17 @@ class CollaborationBridgeLifecycleService:await self._bridge_store.set_service_url(session, bridge_id, service_url)await session.commit()+ async def _persist_channel_team(+ self, bridge_id: str, channel_id: str, team_id: str+ ) -> None:+ """Persist the team an adapter learned a channel belongs to, so channel+ capture survives a restart (used by the Teams adapter)."""+ async with self._session_factory() as session:+ await self._bridge_store.set_channel_team(+ session, bridge_id, channel_id, team_id+ )+ await session.commit()+async def _run_bridge(self,bridge_id: str,@@ -330,6 +463,7 @@ class CollaborationBridgeLifecycleService:logger.exception("Bridge %s crashed", bridge_id)self._bridges.pop(bridge_id, None)self._tasks.pop(bridge_id, None)+ self._held_resources.pop(bridge_id, None)async def stop(self, bridge_id: str) -> None:bridge_core = self._bridges.get(bridge_id)@@ -341,6 +475,7 @@ class CollaborationBridgeLifecycleService:task.cancel()self._bridges.pop(bridge_id, None)+ self._held_resources.pop(bridge_id, None)logger.info("Stopped collaboration bridge %s", bridge_id)async def restart(self, bridge_id: str) -> None:diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex 2039354ce..cf9875071 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -22,6 +22,7 @@ from switch_core.agent_icon import default_icon_urlfrom switch_core.bridges.collaboration.adapter import (CollaborationAdapter,LiveRuntimeIndicator,+ format_elapsed,)from switch_core.bridges.collaboration.models import (Attachment,@@ -715,7 +716,7 @@ class MattermostAdapter(CollaborationAdapter):live = self._working_msg.pop((channel_id, agent_name), None)if live is None:return- elapsed = _format_elapsed(time.monotonic() - live.started_at)+ elapsed = format_elapsed(time.monotonic() - live.started_at)await self._patch_post_as(agent_name,live.message_ref,@@ -907,14 +908,21 @@ class MattermostAdapter(CollaborationAdapter):channel_id: str,user_names: list[str],user_external_ids: list[str],- ) -> None:+ ) -> list[str]:if not self._admin_driver or not self._main_loop:raise RuntimeError("Cannot add users to channel: Mattermost client not connected")loop = self._main_loop- for username in user_names:+ failed: list[str] = []+ # Mattermost resolves people by username and ignores the ids, and one+ # internal caller (the default-member add) has only a name to give — so+ # walk the names and reach for a paired id only if one was supplied.+ for index, username in enumerate(user_names):+ external_id = (+ user_external_ids[index] if index < len(user_external_ids) else username+ )try:user = await loop.run_in_executor(None, self._admin_driver.users.get_user_by_username, username@@ -931,6 +939,8 @@ class MattermostAdapter(CollaborationAdapter):username,channel_id,)+ failed.append(external_id)+ return failedasync def get_external_user_id(self, username: str) -> str | None:"""Resolve a platform username to its current user id, or None if the@@ -1651,20 +1661,3 @@ class MattermostAdapter(CollaborationAdapter):except Exception:passreturn None---def _format_elapsed(seconds: float) -> str:- """How long a turn took, for the marker its status line becomes.-- Rounded to whole seconds and written the way a reader skims it — "8s",- "2m14s", "1h03m" — rather than as a precise duration nobody reads. Sub-- second turns report "0s" instead of an empty string.- """- total = max(0, int(seconds))- if total < 60:- return f"{total}s"- minutes, secs = divmod(total, 60)- if minutes < 60:- return f"{minutes}m{secs:02d}s"- hours, minutes = divmod(minutes, 60)- return f"{hours}h{minutes:02d}m"diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.pyindex 3245d1fad..054369cde 100644--- a/core/switch_core/bridges/collaboration/models.py+++ b/core/switch_core/bridges/collaboration/models.py@@ -152,3 +152,32 @@ class BridgeInstallLink(BaseModel):class BridgeConnectionConfig(BaseModel):pass+++class BridgeCredentialError(Exception):+ """A bridge's credentials were rejected by the platform.++ Carries a message intended for the operator who typed them, so it is+ surfaced verbatim rather than being reduced to "invalid configuration" —+ the platform's own explanation is almost always the actionable part.+ """+++class BridgeOperationError(RuntimeError):+ """A platform refused an operation the bridge asked it to perform.++ The counterpart to :class:`BridgeCredentialError` for everything after the+ credentials are accepted: a permission not granted, a name not allowed, a+ resource that is gone. A token proves only that the platform will talk to+ us, so these arrive long after registration reported success, and the+ platform's wording is again the actionable part — it names the permission+ to consent to, or the value to change.++ Distinct from :class:`ChannelCreationUnsupported`, which is Switch+ declining before it calls out at all. This one has been out to the platform+ and come back with an answer, which is why it is carried to the caller+ rather than logged behind an opaque 500.++ A ``RuntimeError`` so that callers already distinguishing "the request was+ wrong" (``ValueError``) from "the attempt failed" keep working unchanged.+ """diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex ef9a5c93c..3f558700a 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -404,7 +404,7 @@ class SlackAdapter(CollaborationAdapter):try:result = await self._web_client.chat_postMessage(channel=channel_id,- text=self.translate_outbound(content),+ text=content,username=sender_name,icon_url=await self.agent_icon_url(sender_name),thread_ts=thread_ts,@@ -1436,12 +1436,13 @@ class SlackAdapter(CollaborationAdapter):channel_id: str,user_names: list[str],user_external_ids: list[str],- ) -> None:+ ) -> list[str]:if not self._web_client:raise RuntimeError("Cannot add users to channel: Slack client not connected")+ failed: list[str] = []for user_id in user_external_ids:try:await self._web_client.conversations_invite(@@ -1455,6 +1456,8 @@ class SlackAdapter(CollaborationAdapter):channel_id,e,)+ failed.append(user_id)+ return failed# ── Agent identity ───────────────────────────────────────────────────────diff --git a/core/switch_core/bridges/collaboration/teams/README.md b/core/switch_core/bridges/collaboration/teams/README.mdindex e1cbba191..be4dda0e4 100644--- a/core/switch_core/bridges/collaboration/teams/README.md+++ b/core/switch_core/bridges/collaboration/teams/README.md@@ -35,6 +35,33 @@ and avatar. Human users map to Matrix puppets keyed on their AAD object id. Bothinbound paths funnel through one delivery + de-duplication path (keyed on theTeams message id); the bot's own posts are dropped to prevent loops.+**Threading** depends on the channel's Graph `layoutType`, read once per channel+by the same call that resolves its display name. A `chat`-layout channel is a+stream and gets the ordinary policy every other adapter uses: no thread named+means the channel root. A `post`-layout channel is a list of conversations, so+an untied outbound message is steered into the post the channel was last seen+speaking in — otherwise an answer starts a new conversation instead of landing+under the question. The Bot Framework activity carries nothing about layout,+and listing a team's channels reports `layoutType` as null for all of them, so+the per-channel read is the only route; an unreadable layout is treated as+`post`, Graph's own default.++**Runtime status** is retired differently per layout, for the same reason.+Teams substitutes *"This message has been deleted."* for a deleted message in a+`post`-layout channel and keeps it in the post, so there the status card is+never deleted: it is edited into a `✓ Done · <elapsed>` marker, and it is not+repositioned either (a move is a repost plus a delete). A `chat`-layout channel+deletes cleanly and keeps the ordinary behaviour. Mattermost does the same+thing for the same reason — see `_apply_runtime_state` there.++**Commands** arrive three ways and all land on the same dispatcher: `!name`,+`/name`, and a bare `name` on a *targeted* message (`recipient.isTargeted`),+which is what Teams' `/` picker sends — it prints the slash and inserts the+name without it. A bare name is only read as a command when it is both+targeted and known, and an unknown `/name` is left as text, since `/` opens+paths and dates as often as commands. `!` is Switch's own prefix, so an+unknown `!name` still answers "unknown command".+## Security noteGraph resource-data encryption proves message **integrity, not origin** (the@@ -46,6 +73,11 @@ authenticated by verifying the Bot Connector JWT.## Ops prerequisites (must exist before onboarding)+**This is a checklist of what must exist, not instructions for producing it.**+For the steps — which portal blade, which button, in what order — follow+[`docs/bridges/TEAMS_SETUP.md`](../../../../../docs/bridges/TEAMS_SETUP.md),+whose Part 1 covers these one for one.+Environment/tenant setup owned by an administrator — track as a separate ops task.1. **Azure AD app registration** providing the bot's `app_id` (client id), a@@ -53,16 +85,19 @@ Environment/tenant setup owned by an administrator — track as a separate ops t2. **Azure Bot resource** against that app, with the **messaging endpoint** setto `https://<public-host>/api/messages` and the **Microsoft Teams channel**enabled.-3. **Teams app package** (manifest) including the bot, installed into the target- team so it can be added to channels and post proactively.+3. **Teams app package** (manifest plus its two icons) including the bot,+ installed into the target team so it can be added to channels and post+ proactively. A ready-made one ships at+ [`docs/bridges/teams-app/`](../../../../../docs/bridges/teams-app/).4. **Graph API permissions** with admin consent, for channel capture +provisioning: `ChannelMessage.Read.Group` (RSC, preferred) *or* tenant-wide- `ChannelMessage.Read.All`; plus `Channel.Create` and- `TeamMember.ReadWrite.All` / `ChannelMember.ReadWrite.All`. Resource-data- subscriptions count against a shared per-tenant Teams subscription quota.-5. **Encryption certificate** for Graph resource data: an X.509 cert whose public- certificate is handed to Graph and whose private key the bridge holds to- decrypt message bodies. Give it a stable id.+ `ChannelMessage.Read.All`; plus `Channel.Create`, `Channel.ReadBasic.All`,+ `User.ReadBasic.All`, and `TeamMember.ReadWrite.All` /+ `ChannelMember.ReadWrite.All`. Resource-data subscriptions count against a+ shared per-tenant Teams subscription quota.+5. *(nothing to do)* The X.509 keypair Graph resource data is encrypted to is+ generated on bridge creation. Listed only so its absence is not mistaken for+ an omission; a supplied set still wins if all three fields are given.6. **Public HTTPS ingress** routing `https://<public-host>/api/messages` and`/api/teams/notifications` to the bridge's listener. Graph requires valid TLSand a response to its validation handshake within 10 seconds.@@ -75,19 +110,22 @@ Onboard through the gateway (collaboration bridge create). Admin-supplied fields- **`team_id`** — the AAD team (group) id outbound-created channels go into.- **`public_base_url`** — the public HTTPS base the listener is reachable at (usedto build the `/api/teams/notifications` URL given to Graph).-- **`client_state`** — required shared secret (see Security note).-- **`encryption_certificate_id`**, **`encryption_public_certificate`** (PEM),- **`encryption_private_key`** (PEM) — required for channel-message capture.--Switch-internal fields are **not** admin inputs and are hidden from the gateway-form: the listener bind (`listen_host`/`listen_port`, default `0.0.0.0:3978`) is a-deployment detail Switch owns, and `service_url` is learned at runtime and-persisted automatically. An operator can still override the bind via the stored++Generated on creation, and hidden from the form: **`client_state`** (the shared+secret validated on every notification — see Security note) and the encryption+trio **`encryption_certificate_id`**, **`encryption_public_certificate`**,+**`encryption_private_key`**. A supplied set still wins, but all three or none;+a partial set is rejected.++Switch-internal fields are **not** admin inputs and are hidden too: the listener+bind (`listen_host`/`listen_port`, default `0.0.0.0:3978`) is a deployment+detail Switch owns, and `service_url` is learned at runtime and persisted+automatically. An operator can still override the bind via the stored`connection_config` when running more than one Teams bridge on a host.-Without the encryption fields the bridge still runs (outbound, chats, and-@mention capture work), but per-channel Graph subscriptions are skipped and an-error is logged — full channel capture is disabled until they are supplied.+A bridge created before Switch generated this material may hold no encryption+material at all. It still runs — outbound, chats and @mention capture work —+but per-channel Graph subscriptions are skipped and an error is logged.## Known limitations / follow-ups@@ -96,7 +134,17 @@ error is logged — full channel capture is disabled until they are supplied.- **Attachments** (inbound media and outbound files) are currently **disclosed,not relayed**: the message text bridges and a note names the un-relayed media.Native relay is a tenant-validated follow-up.-- **Real outbound @mentions** are not yet emitted (needs a display-name → AAD id- directory); mention text bridges as plain `@name`.+- **An outbound @mention is real only for someone Switch can address** — a+ person who has linked their Teams account, whose AAD object id Switch+ therefore holds. Everyone else, and every agent, bridges as plain `@name`+ text.+- **In a posts-layout channel, an untied reply lands in the post the channel+ last spoke in** (see Threading above) — wrong when two conversations run in+ one channel at once. Teams offers nothing better to key on.+- **Private and shared channels** are declared supported+ (`supportsChannelFeatures: tier1`, which Teams requires of any v1.25++ manifest taking the `team` scope) but are not exercised: they must be added+ to per channel, and Graph refuses message subscriptions on them for+ RSC-consented apps.- **One Teams bridge per listener port** — run multiple Teams bridges on distinctports (and ingress routes) if needed.diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex b5e198487..e832ed35f 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -1,27 +1,34 @@from __future__ import annotationsimport asyncio+import hmacimport html+import jsonimport loggingimport re+import secretsimport timefrom collections import OrderedDictfrom collections.abc import Awaitable, Callablefrom dataclasses import replacefrom datetime import UTC, datetime, timedelta-from typing import Any+from typing import Any, ClassVarfrom urllib.parse import quoteimport httpxfrom aiohttp import web+from pydantic import Field, model_validatorfrom pydantic.json_schema import SkipJsonSchema+from switch_core.bridges.agent.commands import COMMANDS_BY_NAMEfrom switch_core.bridges.collaboration.adapter import (CollaborationAdapter,LiveRuntimeIndicator,+ format_elapsed,)from switch_core.bridges.collaboration.models import (BridgeConnectionConfig,+ BridgeCredentialError,ChannelType,DirectoryUser,InboundAgentJoin,@@ -41,6 +48,7 @@ from switch_core.bridges.collaboration.teams.cards import (from switch_core.bridges.collaboration.teams.connector import BotConnectorClientfrom switch_core.bridges.collaboration.teams.crypto import (decrypt_resource_data,+ generate_encryption_keypair,load_certificate_der_b64,)from switch_core.bridges.collaboration.teams.graph import GraphClient@@ -50,6 +58,77 @@ logger = logging.getLogger(__name__)_MENTION_TAG = re.compile(r"<at\b[^>]*>(.*?)</at>", re.IGNORECASE | re.DOTALL)_HTML_TAG = re.compile(r"<[^>]+>")_BR_TAG = re.compile(r"<br\s*/?>", re.IGNORECASE)+# The whole of a name, if every character of it can be part of an `@mention`.+_HANDLE_SHAPE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")+# What may follow a name for it to have ended there, rather than the name+# being a prefix of a longer one: `@ada` must not match inside `@adaline`.+_MENTION_END = r"(?![A-Za-z0-9._-])"+_AT_TAG = re.compile(r"<at>(.*?)</at>", re.DOTALL)+# A Teams identifier standing where a person's name should be: a channel+# account (`29:…`, `8:orgid:…`) or a bare Entra object id.+_TEAMS_ID = re.compile(+ r"^(?:\d+:\S+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$",+ re.IGNORECASE,+)+# A newline with no newline either side of it.+_LONE_NEWLINE = re.compile(r"(?<!\n)\n(?!\n)")+# Both prefixes reach the same dispatcher. `!` is Switch's own; `/` is what a+# Teams command list types into the compose box when someone picks a command,+# and what anyone who has used Slack will try first.+_COMMAND_PREFIXES = ("!", "/")++# How long a failed Graph read of a channel is taken at its word before being+# tried again. Long enough that a channel Graph will not describe is not read+# on every message; short enough that a blip, or a permission granted after the+# bridge started, heals on its own.+_CHANNEL_READ_RETRY_AFTER = 300.0+++def _handle_for(user: dict[str, Any]) -> str:+ """The handle Switch knows a Teams person by.++ The local part of their user principal name — `ada.lovelace` from+ `[email protected]`. Unique within a tenant, and unlike a display+ name it survives being written as `@handle`, which is how someone is+ addressed in a room and how an outbound mention is matched back to them.++ Every path that meets a person must agree on this, or the same human gets+ two records: the directory used to yield the whole principal name while+ inbound messages yielded the display name, and whichever arrived first won.+ """+ principal = str(user.get("userPrincipalName") or "")+ if principal:+ return principal.split("@", 1)[0]+ display = str(user.get("displayName") or "")+ return display or str(user.get("id") or "")+++def _is_usable_handle(name: str) -> bool:+ """Whether `name` survives being written as `@name`.++ A handle is read back out of message text, where a mention ends at the+ first character that cannot be part of one. A name containing anything+ else — a space, above all, since most display names have one — is+ therefore unaddressable, and an id was never a name to begin with.+ """+ return (+ bool(name)+ and not _TEAMS_ID.match(name)+ and _HANDLE_SHAPE.match(name) is not None+ )+++def _hard_wrap(text: str) -> str:+ """Make single line breaks survive into Teams.++ An Adaptive Card TextBlock follows Markdown's rule that one newline is+ whitespace, so a heading and the line under it arrive as one run-on+ sentence. Doubling a lone newline gives the break back. Existing blank+ lines are left alone — doubling those too would stretch every paragraph+ gap — and list items keep their own lines, which is why this is done here+ rather than by splitting the body into separate blocks.+ """+ return _LONE_NEWLINE.sub("\n\n", text)def _render_mentions(text: str) -> str:@@ -84,10 +163,40 @@ def _strip_leading_mention(text: str) -> str:return _LEADING_MENTION_TAG.sub("", text, count=1)+def _aad_failure_message(exc: Exception) -> str:+ """Reduce an AAD token failure to the sentence an operator can act on.++ The raw failure carries the whole OAuth error body — trace ids, correlation+ ids, timestamps — wrapped around one useful sentence. Microsoft writes that+ sentence well (it names the client-secret value-vs-ID mix-up outright), so+ surface it and drop the rest. Falls back to the full text if the body is not+ the shape we expect, rather than losing the detail.+ """+ text = str(exc)+ start = text.find("{")+ if start != -1:+ try:+ body = json.loads(text[start:])+ except json.JSONDecodeError:+ body = None+ if isinstance(body, dict):+ description = body.get("error_description")+ if isinstance(description, str) and description:+ sentence = description.split("Trace ID:")[0].strip().rstrip(".")+ return f"Microsoft rejected these credentials — {sentence}."+ return f"Microsoft rejected these credentials — {text}"++# Channel-message subscriptions with resource data live at most 60 minutes; we# request 55 and proactively renew well before expiry._SUBSCRIPTION_TTL = timedelta(minutes=55)_RENEWAL_INTERVAL_SECONDS = 40 * 60+# How soon, and how rarely, to re-attempt a channel that has no live+# subscription. The floor is short because the common failure clears in about a+# minute (a load balancer registering a newly-started pod); the ceiling keeps a+# permanently broken channel from hammering Graph for the life of the process.+_REPAIR_MIN_INTERVAL_SECONDS = 30+_REPAIR_MAX_INTERVAL_SECONDS = 5 * 60class TeamsConnectionConfig(BridgeConnectionConfig):@@ -124,17 +233,29 @@ class TeamsConnectionConfig(BridgeConnectionConfig):# Graph change-notification resource-data encryption. Graph encrypts message# bodies with the public certificate; the private key decrypts them on- # delivery. Required once channel-message subscriptions are enabled.- encryption_certificate_id: str | None = None- encryption_public_certificate: str | None = None- encryption_private_key: str | None = None+ # delivery. Required once channel-message subscriptions are enabled, so the+ # trio is generated on creation rather than asked for — an operator pasting+ # PEMs into a form is three chances to disable channel capture silently, and+ # the certificate is key transport that Graph never validates against a trust+ # store, so there is nothing an operator-supplied one would buy. Hidden from+ # the gateway form; supplying your own through the API still wins.+ encryption_certificate_id: SkipJsonSchema[str | None] = None+ encryption_public_certificate: SkipJsonSchema[str | None] = None+ encryption_private_key: SkipJsonSchema[str | None] = None# Shared secret echoed back in every change notification and validated on- # receipt. Required, and the ONLY control that authenticates a notification's- # origin: Graph resource-data encryption proves integrity but NOT origin (the- # wrapping key is the public certificate, which anyone can encrypt to), so- # without clientState the notification endpoint is spoofable.- client_state: str+ # receipt. The ONLY control that authenticates a notification's origin: Graph+ # resource-data encryption proves integrity but NOT origin (the wrapping key+ # is the public certificate, which anyone can encrypt to), so without+ # clientState the notification endpoint is spoofable.+ #+ # Generated, not asked for: it is a secret with no external meaning, so+ # prompting an operator to invent one only invites a weak or reused value.+ # Required rather than defaulted, and minted in prepare_config at+ # registration — a default here would mint a fresh secret every time a stored+ # config was validated, and every live subscription would start failing its+ # origin check with nothing to point at.+ client_state: SkipJsonSchema[str]# Bot Connector serviceUrl (the per-tenant outbound endpoint). It is learned# from inbound Bot Framework activities and persisted here so outbound@@ -147,6 +268,37 @@ class TeamsConnectionConfig(BridgeConnectionConfig):# hidden from the gateway config form (SkipJsonSchema).service_url: SkipJsonSchema[str | None] = None+ # Channel id -> the AAD group id of the team holding it, learned from the+ # `channelData` of inbound activities and persisted here. A Graph message+ # subscription names the team as well as the channel, and `team_id` above+ # is only the team Switch *provisions into* — a channel the bot was added+ # to in some other team belongs to none of it. Held in memory alone this+ # was lost on every restart, and capture in those channels stayed dead+ # until someone thought to mention the bot; see `_learn_channel_team`.+ # Learned at runtime, never an admin input, so it is hidden from the form.+ channel_teams: SkipJsonSchema[dict[str, str]] = Field(default_factory=dict)++ @model_validator(mode="after")+ def _encryption_material_is_all_or_nothing(self) -> TeamsConnectionConfig:+ """A half-supplied encryption trio is a mistake, not a partial request.++ Completing it for them would pair someone's certificate with a private+ key they do not hold, and the only symptom would be channel capture that+ never decrypts.+ """+ supplied = [+ self.encryption_certificate_id,+ self.encryption_public_certificate,+ self.encryption_private_key,+ ]+ if any(supplied) and not all(supplied):+ raise ValueError(+ "encryption_certificate_id, encryption_public_certificate and "+ "encryption_private_key must be supplied together, or all left "+ "unset to have them generated"+ )+ return self+class TeamsAdapter(CollaborationAdapter):"""Microsoft Teams collaboration adapter.@@ -155,10 +307,88 @@ class TeamsAdapter(CollaborationAdapter):agent, and per-agent presentation is done with Adaptive Card sender labelsrather than a bot account per agent. Outbound messages are delivered throughthe Bot Framework connector; inbound activities arrive at a self-hosted- aiohttp listener. Full (non-@mention) channel-message capture via Microsoft- Graph subscriptions is layered on in a later phase.+ aiohttp listener. Full (non-@mention) channel-message capture goes through+ Microsoft Graph change-notification subscriptions."""+ # Teams keeps only http(s) anchors: a link on any other scheme is stripped+ # whole, label and all, so a `switchdash://` deeplink left the literal+ # brackets around it and rendered as "()". It needs the https redirect,+ # which means `GATEWAY_PUBLIC_URL` must be set — and declaring this is what+ # makes the lifecycle say so at startup when it is not.+ renders_custom_url_schemes: ClassVar[bool] = False++ @classmethod+ async def prepare_config(+ cls, connection_config: dict[str, object]+ ) -> dict[str, object]:+ """Mint the clientState secret and the Graph encryption trio.++ Here rather than as model defaults because this runs only at+ registration, so what it produces is persisted once and never re-derived.+ A default on the model would mint fresh values every time a stored config+ was validated — a new certificate and a new shared secret on every+ restart, while Graph carried on encrypting to the old certificate and+ echoing the old secret. Capture would fail its origin check and its+ decryption, with nothing in the logs pointing at why.+ """+ prepared = dict(connection_config)+ if not prepared.get("client_state"):+ prepared["client_state"] = secrets.token_urlsafe(32)+ keys = (+ "encryption_certificate_id",+ "encryption_public_certificate",+ "encryption_private_key",+ )+ if any(prepared.get(k) for k in keys):+ return prepared+ # RSA keygen is CPU-bound and switch-core runs every live Matrix+ # session on this loop, so it does not run on it.+ cert_pem, key_pem = await asyncio.to_thread(generate_encryption_keypair)+ prepared["encryption_certificate_id"] = f"switch-teams-{secrets.token_hex(8)}"+ prepared["encryption_public_certificate"] = cert_pem+ prepared["encryption_private_key"] = key_pem+ return prepared++ @classmethod+ def exclusive_resource(cls, connection_config: dict[str, object]) -> str | None:+ """The inbound listener's TCP port, which one process can hold once.++ Teams is push-based, so each bridge runs an HTTP server; two on the same+ port means the second never binds. Declaring it here turns that into a+ refusal at registration naming the port, rather than a bind error in a+ background task that leaves the bridge silently dropped.+ """+ config = TeamsConnectionConfig.model_validate(connection_config)+ return f"tcp/{config.listen_port}"++ @classmethod+ async def verify_credentials(cls, connection_config: dict[str, object]) -> None:+ """Ask Azure AD for both tokens the bridge will need.++ This is the call that fails on a wrong client secret, and Microsoft's+ error names the mistake precisely — including the classic case of the+ secret's ID being pasted instead of its value. Getting that to the+ operator at save time is the whole point.+ """+ config = TeamsConnectionConfig.model_validate(connection_config)+ async with httpx.AsyncClient(timeout=30) as http:+ tokens = TeamsTokenProvider(+ tenant_id=config.tenant_id,+ app_id=config.app_id,+ app_password=config.app_password,+ http=http,+ )+ try:+ await tokens.graph_token()+ await tokens.bot_token()+ except RuntimeError as exc:+ raise BridgeCredentialError(_aad_failure_message(exc)) from exc+ except httpx.HTTPError as exc:+ raise BridgeCredentialError(+ f"Could not reach Microsoft to verify these credentials: {exc}"+ ) from exc+def __init__(self, *, config: TeamsConnectionConfig) -> None:super().__init__()self._config = config@@ -180,6 +410,27 @@ class TeamsAdapter(CollaborationAdapter):self._persist_service_url: Callable[[str], Awaitable[None]] | None = None# channel/chat id -> ChannelType, learned from inbound activities.self._channel_type: dict[str, ChannelType] = {}+ # casefolded username -> AAD object id, for rendering real @mentions.+ self._mention_targets: dict[str, str] = {}+ # `_mention_targets` compiled into an `@name` matcher; None until built,+ # and discarded whenever the targets change.+ self._mention_pattern: re.Pattern[str] | None = None+ # AAD object id -> the handle we know that person by, so a directory+ # read happens once per sender rather than once per message.+ self._sender_handles: dict[str, str] = {}+ # channel id -> the post the bridge last saw a message in there, so a+ # reply that names no thread lands under what it is answering.+ self._last_post: dict[str, str] = {}+ # channel id -> its display name; "" records that Graph was asked and+ # could not say, so it is not asked again on every message.+ self._channel_names: dict[str, str] = {}+ # channel id -> when a Graph read of it last failed (monotonic), so the+ # retry is throttled without being abandoned. See `_read_channel`.+ self._channel_read_failed_at: dict[str, float] = {}+ # channel id -> "post" | "chat", the conversation layout Graph reports.+ # "" records that Graph was asked and could not say. See+ # `_uses_post_layout` for what an unknown layout is treated as.+ self._channel_layouts: dict[str, str] = {}# message id -> (service_url, conversation_id) for later edit/delete.self._sent: dict[str, tuple[str, str]] = {}# Inbound de-duplication — the Bot Framework and Graph capture paths can@@ -189,11 +440,23 @@ class TeamsAdapter(CollaborationAdapter):# channel id -> Graph subscription id, for channels we capture.self._subscriptions: dict[str, str] = {}- # channel id -> AAD team id, learned from bot-join activities so a- # channel-message subscription can be created for it.- self._team_of_channel: dict[str, str] = {}+ # Channels that should be captured, whether or not they currently are.+ # Kept apart from `_subscriptions` so a failed attempt is remembered as+ # work still owed rather than forgotten the moment it fails.+ self._capture_wanted: set[str] = set()+ # channel id -> last failure, so the repair loop can retry quietly and+ # still speak up when the reason changes.+ self._capture_failures: dict[str, str] = {}+ # channel id -> AAD team id, learned from inbound activities so a+ # channel-message subscription can be created for it. Seeded from the+ # persisted config, so a channel outside the configured team keeps its+ # capture across a restart instead of waiting to be re-taught.+ self._team_of_channel: dict[str, str] = dict(config.channel_teams)+ # Installed by the bridge to persist a newly-learned channel/team pair.+ self._persist_channel_team: Callable[[str, str], Awaitable[None]] | None = Noneself._sub_lock = asyncio.Lock()self._renewal_task: asyncio.Task[None] | None = None+ self._repair_task: asyncio.Task[None] | None = None# ── Lifecycle ────────────────────────────────────────────────────────────@@ -240,6 +503,7 @@ class TeamsAdapter(CollaborationAdapter):)await self._adopt_existing_subscriptions()self._renewal_task = asyncio.create_task(self._renewal_loop())+ self._repair_task = asyncio.create_task(self._repair_loop())@propertydef _notification_url(self) -> str:@@ -331,14 +595,21 @@ class TeamsAdapter(CollaborationAdapter):channel_id,)+ @staticmethod+ async def _cancel(task: asyncio.Task[None] | None) -> None:+ if task is None:+ return+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+async def stop(self) -> None:- if self._renewal_task is not None:- self._renewal_task.cancel()- try:- await self._renewal_task- except asyncio.CancelledError:- pass- self._renewal_task = None+ await self._cancel(self._renewal_task)+ self._renewal_task = None+ await self._cancel(self._repair_task)+ self._repair_task = Noneif self._runner is not None:await self._runner.cleanup()self._runner = None@@ -379,6 +650,51 @@ class TeamsAdapter(CollaborationAdapter):except Exception:logger.warning("Failed to persist Teams serviceUrl", exc_info=True)+ def set_channel_team_persister(+ self, persist: Callable[[str, str], Awaitable[None]]+ ) -> None:+ self._persist_channel_team = persist++ async def _learn_channel_team(self, channel_id: str, team_id: str) -> None:+ """Record which team a channel belongs to, and persist it.++ A Graph message subscription is created against+ ``teams/{team}/channels/{channel}/messages``, so the team is not+ optional — and the only place it arrives is the ``channelData`` of an+ inbound activity. Held in memory alone it is lost on every restart,+ and a channel in any team other than the configured one then falls+ back to that one, where Graph answers "Channel is not present in the+ team" and capture never starts.++ That failure cannot heal on its own: refilling the map needs an+ activity from the channel, and without capture Teams delivers only+ messages that mention the bot — so tagging an *agent*, which is the+ normal way to use the room, never arrives. Silence, until someone+ happens to tag the bot itself.+ """+ if self._team_of_channel.get(channel_id) == team_id:+ return+ # Anything already read for this channel was read against a different+ # 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.+ self._team_of_channel[channel_id] = team_id+ self._channel_names.pop(channel_id, None)+ self._channel_layouts.pop(channel_id, None)+ self._channel_read_failed_at.pop(channel_id, None)+ if self._persist_channel_team is None:+ return+ try:+ await self._persist_channel_team(channel_id, team_id)+ except Exception:+ logger.warning(+ "Failed to persist the team of Teams channel %s; capture there "+ "will need the bot mentioned again after the next restart",+ channel_id,+ exc_info=True,+ )+def _is_channel(self, channel_id: str) -> bool:"""Whether ``channel_id`` is a Teams channel (threaded) vs a flat chat.@@ -393,15 +709,115 @@ class TeamsAdapter(CollaborationAdapter):def _thread_conversation(channel_id: str, root_id: str) -> str:return f"{channel_id};messageid={root_id}"+ async def _channel_layout(self, channel_id: str) -> str | None:+ """The channel's conversation layout as Graph reports it, or None.++ Graph is the only thing that knows: a Bot Framework activity says+ nothing about layout, and listing a team's channels returns the+ property as null for every one of them. So it is a per-channel read,+ cached — and the same read the channel's name comes from, so learning+ both costs one call.+ """+ cached = self._channel_layouts.get(channel_id)+ if cached is not None:+ return cached or None+ if self._read_recently_failed(channel_id):+ return None+ await self._read_channel(channel_id)+ return self._channel_layouts.get(channel_id) or None++ async def _uses_post_layout(+ self, channel_id: str, *, is_channel: bool | None = None+ ) -> bool:+ """Whether replies in this channel have to be steered into a post.++ Teams has two channel layouts and they want opposite things.++ A **posts** channel is a list of conversations: a message at the root+ opens a new one. An agent answering a question there must land under+ the question, or the answer appears as a fresh post below and reads as+ a non-sequitur.++ A **chat** channel is a stream, like every other platform Switch+ bridges. "No thread" means the root, and steering is exactly wrong: it+ buries an agent's first message, the room-linked notice and the runtime+ status inside whatever thread the channel last used. So a chat channel+ gets the ordinary policy — the agent decides whether to thread, and+ nothing is rewritten on the way out.++ An unreadable layout is treated as posts. That is Graph's own default,+ and it is what every Teams channel was before the chat layout existed,+ so it is the answer least likely to surprise. Chats and group chats+ have no posts to be wrong about and are never steered.+ """+ threaded = self._is_channel(channel_id) if is_channel is None else is_channel+ if not threaded:+ return False+ return await self._channel_layout(channel_id) != "chat"++ async def _remember_post(+ self,+ channel_id: str,+ post_id: str,+ *,+ is_channel: bool | None = None,+ only_if_unset: bool = False,+ ) -> None:+ """Note the post a posts-channel conversation is currently in.++ Inbound, unconditionally: the message someone just sent is what an+ untied reply should answer under.++ Outbound, only when nothing is recorded yet (`only_if_unset`). The+ first thing an agent says in a channel has no question to answer — it+ opens a post — and what it says next belongs in that post rather than+ in a fresh one each time, or an agent greeting itself into a channel+ produces a column of one-line posts. But an agent's own message must+ never *displace* a real one: an agent deliberately replying into an+ older thread would otherwise drag every later answer back into it.+ """+ if not post_id:+ return+ if only_if_unset and channel_id in self._last_post:+ return+ if await self._uses_post_layout(channel_id, is_channel=is_channel):+ self._last_post[channel_id] = post_id++ async def _post_to_answer_in(+ self, channel_id: str, thread_root_id: str | None+ ) -> str | None:+ """Which post a channel reply belongs under, in a posts channel.++ A caller that named a thread knows better than we do and wins. What+ this covers is the caller that named none, which is any agent whose+ reply was not itself threaded in Matrix: answer in the post the bridge+ last saw this channel speak in, rather than opening a new one.++ The limitation, stated because it is real: "last" is per channel, so+ two conversations running in the same posts channel at the same moment+ can cross. Teams gives no better signal on an untied reply, and landing+ in the wrong post beats starting a fresh one every time.++ Chat-layout channels are left entirely alone — see `_uses_post_layout`.+ """+ if thread_root_id is not None:+ return thread_root_id+ if not await self._uses_post_layout(channel_id):+ return None+ return self._last_post.get(channel_id)+async def _message_activity(self, sender_name: str, body: str) -> dict[str, Any]:icon_url = await self.agent_icon_url(sender_name)+ mentions = self._mention_entities(body)return {"type": "message",# Notification/preview text; without it Teams renders a# "cards.unsupported" placeholder in toasts, mobile, and link previews."summary": f"{sender_name}: {body}","attachments": [- card_attachment(agent_message_card(sender_name, body, icon_url))+ card_attachment(+ agent_message_card(sender_name, body, icon_url, mentions=mentions)+ )],}@@ -418,9 +834,11 @@ class TeamsAdapter(CollaborationAdapter):raise RuntimeError("Cannot send message: Teams adapter not started")service_url = self._service_url_for(channel_id)- activity = await self._message_activity(- sender_name, self.translate_outbound(content)- )+ # `content` arrives rendered: every caller of `send_message` runs+ # `translate_outbound` first, and rendering again here put the body+ # through the conversion twice.+ activity = await self._message_activity(sender_name, content)+ thread_root_id = await self._post_to_answer_in(channel_id, thread_root_id)if self._is_channel(channel_id) and thread_root_id is None:conversation_id, msg_id = await self._connector.create_channel_thread(@@ -440,6 +858,9 @@ class TeamsAdapter(CollaborationAdapter):if msg_id:self._sent[msg_id] = (service_url, conversation_id)+ await self._remember_post(+ channel_id, thread_root_id or msg_id, only_if_unset=True+ )return msg_idreturn None@@ -458,7 +879,14 @@ class TeamsAdapter(CollaborationAdapter):raise RuntimeError("Cannot post admin message: Teams adapter not started")service_url = self._service_url_for(channel_id)- activity = {"type": "message", "text": self.translate_outbound(content)}+ body = self.translate_outbound(content)+ thread_root_id = await self._post_to_answer_in(channel_id, thread_root_id)+ activity: dict[str, Any] = {"type": "message", "text": body}+ mentions = self._mention_entities(body)+ if mentions:+ # A plain-text activity carries its mention entities directly; only+ # a card puts them under `msteams`.+ activity["entities"] = mentionsif self._is_channel(channel_id) and thread_root_id is None:conversation_id, msg_id = await self._connector.create_channel_thread(@@ -478,6 +906,9 @@ class TeamsAdapter(CollaborationAdapter):if msg_id:self._sent[msg_id] = (service_url, conversation_id)+ await self._remember_post(+ channel_id, thread_root_id or msg_id, only_if_unset=True+ )return msg_idreturn None@@ -506,7 +937,7 @@ class TeamsAdapter(CollaborationAdapter):service_url=service_url,conversation_id=conversation_id,activity_id=message_ref,- activity={"type": "message", "text": self.translate_outbound(new_content)},+ activity={"type": "message", "text": new_content},)async def delete_message(self, channel_id: str, message_ref: str) -> None:@@ -556,9 +987,18 @@ class TeamsAdapter(CollaborationAdapter):A "working on it…" card is posted (as the agent) while the agent worksand edited in place as the activity detail changes; it stays up through``awaiting-input`` — where a "needs your input" ping is added — and both- are removed when the turn goes ``idle`` (or resumes to ``working``,- since the requested input was provided). Teams messages are truly- deletable, so no tombstone is left behind.+ are retired when the turn goes ``idle`` (or resumes to ``working``,+ since the requested input was provided).++ **How they are retired depends on the channel's layout**, because Teams+ does not delete the same way in both. In a chat-layout channel a deleted+ message is gone, so the status is removed and leaves nothing behind. In+ a **posts** channel Teams substitutes *"This message has been deleted."*+ and keeps it in the post — so a status that appears and vanishes each+ turn litters the conversation with tombstones, one per turn per agent.+ There is no way to delete without one. So there, as on Mattermost, the+ status is never deleted: it is edited into a small terminal marker and+ left as the record of a turn that is over."""key = (channel_id, agent_name)if state == "working":@@ -586,9 +1026,19 @@ class TeamsAdapter(CollaborationAdapter):if ref is not None:self._input_pings.setdefault(key, []).append(ref)else:- await self._clear_working(channel_id, agent_name)+ await self._retire_working(channel_id, agent_name)await self._clear_input_pings(channel_id, agent_name)+ async def _leaves_a_tombstone(self, channel_id: str) -> bool:+ """Whether deleting a message here would leave wreckage behind.++ Only in a posts channel, where Teams replaces a deleted message with+ *"This message has been deleted."* and keeps it in the post. A+ chat-layout channel drops it cleanly, and a chat or group chat has no+ post to litter.+ """+ return await self._uses_post_layout(channel_id)+async def _refresh_card(self, channel_id: str, message_ref: str, agent_name: str, body: str) -> None:@@ -602,10 +1052,44 @@ class TeamsAdapter(CollaborationAdapter):activity=await self._message_activity(agent_name, body),)- async def _clear_working(self, channel_id: str, agent_name: str) -> None:+ async def _retire_working(self, channel_id: str, agent_name: str) -> None:+ """End the turn's live status: edited where a delete would scar, else+ removed.++ The marker is kept to the bare fact that the turn finished and how long+ it took, because in a posts channel this line stays there for good and+ has to earn its place. The session link is deliberately dropped: it+ belongs on a live indicator, where it is still worth following, not on+ the record of a turn that is over.+ """live = self._working_msg.pop((channel_id, agent_name), None)- if live is not None:+ if live is None:+ return+ if not await self._leaves_a_tombstone(channel_id):await self.delete_message(channel_id, live.message_ref)+ return+ elapsed = format_elapsed(time.monotonic() - live.started_at)+ await self._refresh_card(+ channel_id,+ live.message_ref,+ agent_name,+ self.translate_outbound(f"✓ Done · {elapsed}"),+ )++ async def _reposition_runtime_state(+ self, channel_id: str, agent_name: str, thread_root_id: str | None+ ) -> None:+ """Follow the conversation, except where moving would leave a scar.++ Repositioning is a repost plus a delete, and in a posts channel that+ delete leaves *"This message has been deleted."* behind — once per move,+ so the busier the conversation the more of them. Pinned to where the+ turn began there instead: less precise about where the agent is up to,+ and it costs the reader nothing.+ """+ if await self._leaves_a_tombstone(channel_id):+ return+ await super()._reposition_runtime_state(channel_id, agent_name, thread_root_id)async def _remove_runtime_indicator(self, channel_id: str, message_ref: str@@ -628,9 +1112,25 @@ class TeamsAdapter(CollaborationAdapter):)async def _clear_input_pings(self, channel_id: str, agent_name: str) -> None:+ """Resolve the operator pings raised during the turn.++ Edited rather than removed wherever a delete would leave a tombstone —+ and for a ping that matters more than for the status line, since the+ people looking at it are exactly the ones it was aimed at."""refs = self._input_pings.pop((channel_id, agent_name), [])+ if not refs:+ return+ scars = await self._leaves_a_tombstone(channel_id)for ref in refs:- await self.delete_message(channel_id, ref)+ if scars:+ await self._refresh_card(+ channel_id,+ ref,+ agent_name,+ self.translate_outbound("✓ Input received"),+ )+ else:+ await self.delete_message(channel_id, ref)# ── Channels ─────────────────────────────────────────────────────────────@@ -668,7 +1168,9 @@ class TeamsAdapter(CollaborationAdapter):raise RuntimeError(f"Teams channel creation returned no id for '{name}'")self._channel_type[channel_id] = channel_type- self._team_of_channel[channel_id] = self._config.team_id+ await self._learn_channel_team(channel_id, self._config.team_id)+ self._channel_names[channel_id] = str(channel.get("displayName") or "")+ self._channel_layouts[channel_id] = str(channel.get("layoutType") or "")# Capture the new channel's messages right away.await self._ensure_channel_subscription(channel_id)return channel_id@@ -687,6 +1189,14 @@ class TeamsAdapter(CollaborationAdapter):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 resolvedasync def search_directory_users(self, query: str) -> list[DirectoryUser]:@@ -705,7 +1215,7 @@ class TeamsAdapter(CollaborationAdapter):results = [DirectoryUser(external_user_id=str(user.get("id")),- username=str(user.get("userPrincipalName") or user.get("id") or ""),+ username=_handle_for(user),display_name=str(user.get("displayName") or user.get("userPrincipalName") or ""),@@ -753,7 +1263,7 @@ class TeamsAdapter(CollaborationAdapter):channel_id: str,user_names: list[str],user_external_ids: list[str],- ) -> None:+ ) -> list[str]:if self._graph is None:raise RuntimeError("Teams adapter not started")team_id = self._team_of_channel.get(channel_id, self._config.team_id)@@ -776,11 +1286,7 @@ class TeamsAdapter(CollaborationAdapter):"Failed to add user %s to Teams channel %s", user_id, channel_id)failed.append(user_id)- if failed:- raise RuntimeError(- f"Failed to add {len(failed)} user(s) to Teams channel "- f"{channel_id}: {', '.join(failed)}"- )+ return failed# ── Agent identity ───────────────────────────────────────────────────────@@ -799,8 +1305,170 @@ class TeamsAdapter(CollaborationAdapter):# ── Translation ──────────────────────────────────────────────────────────+ def prime_mention_targets(self, targets: dict[str, str]) -> None:+ """Learn ``username -> AAD object id`` so an ``@name`` can become a real+ Teams mention. Without it every ``@name`` goes out as inert text and the+ person it names is never notified."""+ self._mention_targets.update(+ {name.casefold(): external_id for name, external_id in targets.items()}+ )+ self._mention_pattern = None++ def _known_name_pattern(self) -> re.Pattern[str] | None:+ """An ``@name`` matcher covering the names we can actually address.++ Built from the targets rather than from a general name shape, because+ a Teams handle is often a display name and so often contains a space:+ no fixed pattern can tell where `@Louis Amaudruz` ends without knowing+ the name. Longest first, so the full name wins over its first word.++ Rebuilt when the targets change, which is on startup and once per+ person met.+ """+ if self._mention_pattern is None and self._mention_targets:+ names = sorted(self._mention_targets, key=len, reverse=True)+ alternatives = "|".join(re.escape(name) for name in names)+ self._mention_pattern = re.compile(+ f"@({alternatives}){_MENTION_END}", re.IGNORECASE+ )+ return self._mention_pattern+def translate_outbound(self, content: str) -> str:- return content+ return _hard_wrap(self._mark_mentions(content))++ def _mark_mentions(self, content: str) -> str:+ """Wrap ``@name`` in Teams' ``<at>`` markup for people we can address.++ Only names we hold an AAD id for: the markup is half of a mention and+ the entity built from it in ``_mention_entities`` is the other, so+ marking a name we cannot pair would render a mention that highlights+ nobody. Agent names are deliberately among those left alone — an agent+ is not a Teams user, and ``@agent`` is Switch's own addressing, which+ wants the plain text.+ """+ pattern = self._known_name_pattern()+ if pattern is None:+ return content++ def _replace(match: re.Match[str]) -> str:+ name = match.group(1)+ # The pattern matches case-insensitively while the entity is looked+ # up by casefold, and for a few scripts those disagree. Emitting+ # markup the entity pass would not pair leaves a mention that+ # highlights nobody, so leave the text alone instead.+ if name.casefold() not in self._mention_targets:+ return match.group(0)+ return f"<at>{html.escape(name)}</at>"++ return pattern.sub(_replace, content)++ def _mention_entities(self, text: str) -> list[dict[str, Any]]:+ """Bot Framework mention entities for the ``<at>`` markup in ``text``.++ Teams needs both halves and rejects neither: markup with no entity is+ plain text, an entity with no markup does nothing. Built from the+ rendered body so the two cannot drift.+ """+ entities: list[dict[str, Any]] = []+ seen: set[str] = set()+ for escaped_name in _AT_TAG.findall(text):+ if escaped_name in seen:+ continue+ name = html.unescape(escaped_name)+ external_id = self._mention_targets.get(name.casefold())+ if external_id is None:+ continue+ seen.add(escaped_name)+ entities.append(+ {+ "type": "mention",+ "text": f"<at>{escaped_name}</at>",+ "mentioned": {"id": external_id, "name": name},+ }+ )+ return entities++ async def _sender_handle(self, sender_id: str, offered_name: str) -> str:+ """The handle to file an inbound sender under.++ Teams omits the sender's name from some activities — 1:1 chats above+ all — and the fallback was the raw id, so `29:1AbCdEf…` became a+ person's name: in the room title, on their Matrix account, and in the+ text of every agent reply that addressed them. An id is never a name,+ so look one up instead, and only give up when Graph cannot say either.++ What Teams offers on an activity is the *display* name, which is+ usually two words. A handle is also what an agent writes to address+ someone, and `@Louis Amaudruz` cannot be read back — a mention ends at+ the first space — so taking the offered name at face value files+ people under something that can never be tagged. Ask the directory for+ the principal name instead, which is one word by construction, and+ keep the offered name only if the directory cannot say.++ Cached per sender: it is one directory read per person, on a value that+ does not change between messages.+ """+ cached = self._sender_handles.get(sender_id)+ if cached is not None:+ return cached+ handle = ""+ # A one-word name Teams offered is already a usable handle and costs+ # nothing. An id masquerading as a name, or a name with a space in it,+ # sends us to the directory for something better.+ if (+ offered_name+ and offered_name != sender_id+ and _is_usable_handle(offered_name)+ ):+ handle = offered_name+ elif self._graph is not None and sender_id:+ try:+ handle = _handle_for(await self._graph.get_user(user_id=sender_id))+ except Exception:+ logger.warning(+ "Could not resolve a handle for Teams sender %s; falling "+ "back to %s",+ sender_id,+ "the display name Teams offered" if offered_name else "their id",+ exc_info=True,+ )+ # A display name with a space is a poor handle but a good deal better+ # than an id, so it stands when the directory yields nothing.+ handle = handle or offered_name or sender_id+ self._sender_handles[sender_id] = handle+ return handle++ @staticmethod+ def _command_name(token: str) -> str:+ """The command a leading `!name` or `/name` token names.++ Teams has no server-registered slash commands — a bot's command list+ is declared in its app manifest and, when picked, simply types the text+ into the compose box. So `/help` reaches us as an ordinary message and+ the two prefixes are the same thing by the time we see them.+ """+ return token.lstrip("!/")++ def slash_invite_hint(self) -> str | None:+ # Teams has no server-registered slash commands: a manifest command+ # list only types the text into the compose box, and the bot parses it+ # like any other message. So the slash form always works, whether or+ # not the operator has declared it, and reaches the same dispatcher.+ return (+ "`/invite-agent @agent-name` — the same thing, if you prefer the slash form"+ )++ def is_placeholder_username(self, username: str) -> bool:+ # Every id Teams hands out for a person is one of two shapes: a+ # channel-account id, prefixed with digits and a colon (`29:1AbC…`,+ # `8:orgid:…`), or a bare Entra object id. Neither is anybody's name.+ return bool(_TEAMS_ID.match(username.strip()))++ def render_app_mention(self, token: str) -> str:+ # Teams' handle for the app is an id, not a name, and it has no inline+ # syntax that turns one into a mention — so name nobody and read+ # naturally instead of printing `<@28:…>` at someone.+ return "me"def translate_inbound(self, raw_message: str) -> str:return raw_message@@ -847,7 +1515,7 @@ class TeamsAdapter(CollaborationAdapter):# GUID"). Fall back to the configured team_id, which is also that GUID.group_id = team.get("aadGroupId") or self._config.team_idif group_id and channel_id:- self._team_of_channel[channel_id] = str(group_id)+ await self._learn_channel_team(channel_id, str(group_id))if activity_type == "message":await self._dispatch_message(activity, channel_id, channel_type)@@ -892,7 +1560,9 @@ class TeamsAdapter(CollaborationAdapter):sender = activity.get("from") or {}sender_id = str(sender.get("aadObjectId") or sender.get("id") or "")- sender_name = str(sender.get("name") or sender_id)+ sender_name = await self._sender_handle(+ sender_id, str(sender.get("name") or "")+ )raw_text = str(activity.get("text", ""))text = self._clean_text(raw_text)@@ -914,7 +1584,7 @@ class TeamsAdapter(CollaborationAdapter):if thread_root and thread_root != activity_id:root_id = thread_root- channel_name = self._channel_name(activity)+ channel_name = await self._resolve_channel_name(activity, channel_id)await self._deliver(channel_id=channel_id,@@ -927,8 +1597,47 @@ class TeamsAdapter(CollaborationAdapter):channel_name=channel_name,self_mention_token=self_mention_token,command_text=command_text,+ is_targeted=bool((activity.get("recipient") or {}).get("isTargeted")),)+ def _command_in(self, probe: str, *, is_targeted: bool) -> str | None:+ """The command this message runs, or None if it is ordinary text.++ Two ways a command arrives, and both need a name Switch knows.++ **Prefixed** — `!help`, or `/help`. The prefix alone used to be enough,+ which meant any message opening with a slash was swallowed: paste a+ path and you got "unknown command" instead of your message. Telegram+ already guards against that; this is the same guard.++ **Bare, on a targeted message** — Teams' `/` picker prepends the slash+ itself and inserts the command's bare name, so `activity.text` is+ `help`, not `/help`. That is why the slash-triggered list in the shipped+ manifest declares titles without one, matching Microsoft's own samples.+ A bare name is only read as a command when the message was targeted at+ this bot: outside that, "help" in a channel is somebody talking.+ """+ if not probe:+ return None+ first = probe.split(None, 1)[0]+ name = self._command_name(first)+ if name in COMMANDS_BY_NAME:+ # Known, however it was written: `!help`, `/help`, or the bare+ # `help` the picker inserts.+ return name if first[:1] in _COMMAND_PREFIXES or is_targeted else None+ # Unknown. Whether that is worth answering depends on which prefix was+ # used, because the two mean different things to a person.+ #+ # `!` is Switch's own and means nothing else, so `!list-agent` is a+ # misspelt command and deserves to be told so.+ #+ # `/` is not Switch's — it opens paths, dates and fractions, and Teams+ # delivers those as ordinary text. Reading every one as a command is+ # how `/Users/ada/notes.md` came back "unknown command" instead of+ # reaching an agent. So an unknown `/name` is left as what it looks+ # like: a message.+ return name if first.startswith("!") else None+async def _deliver(self,*,@@ -942,6 +1651,7 @@ class TeamsAdapter(CollaborationAdapter):channel_name: str | None,self_mention_token: str | None = None,command_text: str | None = None,+ is_targeted: bool = False,) -> None:"""Route a parsed inbound message to the command or message callback.@@ -952,8 +1662,18 @@ class TeamsAdapter(CollaborationAdapter):used only to detect and parse ``!``-commands (a channel command arrives as``@Bot !cmd``), while ``text`` — mention intact — is what a plain messageis bridged as. Defaults to ``text`` when the caller has nothing to strip."""+ # The post this message sits in — itself, when it opened the post.+ # Remembered so an untied reply lands under the question rather than+ # starting a conversation of its own; see _post_to_answer_in.+ await self._remember_post(+ channel_id,+ root_id or message_ref,+ # The caller was told the type; do not re-derive it from the id.+ is_channel=channel_type in ("channel_public", "channel_private"),+ )command_probe = (command_text if command_text is not None else text).strip()- if command_probe.startswith("!") and self._on_command is not None:+ command = self._command_in(command_probe, is_targeted=is_targeted)+ if command is not None and self._on_command is not None:parts = command_probe.split(None, 1)await self._on_command(InboundCommand(@@ -961,7 +1681,7 @@ class TeamsAdapter(CollaborationAdapter):channel_type=channel_type,sender_id=sender_id,sender_name=sender_name,- command=parts[0].lstrip("!"),+ command=command,args=parts[1].strip() if len(parts) > 1 else "",message_ref=message_ref,root_id=root_id,@@ -991,7 +1711,7 @@ class TeamsAdapter(CollaborationAdapter):members_added = activity.get("membersAdded") or []recipient = activity.get("recipient") or {}bot_id = str(recipient.get("id", ""))- channel_name = self._channel_name(activity)+ channel_name = await self._resolve_channel_name(activity, channel_id)for member in members_added:member_id = str(member.get("id", ""))@@ -1010,23 +1730,105 @@ class TeamsAdapter(CollaborationAdapter):))elif self._on_user_joined is not None:+ joiner_id = str(member.get("aadObjectId") or member_id)await self._on_user_joined(InboundUserJoin(channel_id=channel_id,channel_type=channel_type,- external_user_id=str(member.get("aadObjectId") or member_id),- external_username=str(member.get("name") or member_id),+ external_user_id=joiner_id,+ external_username=await self._sender_handle(+ joiner_id, str(member.get("name") or "")+ ),channel_name=channel_name,))@staticmethoddef _channel_name(activity: dict[str, Any]) -> str | None:+ """The channel's name as the activity gives it, if it gives it.++ Prefer the channel's own name over the team's: the team's is the same+ for every channel in it, which makes a poor room title. Teams omits+ both more often than not — see `_resolve_channel_name`.+ """channel_data = activity.get("channelData") or {}+ channel = channel_data.get("channel") or {}team = channel_data.get("team") or {}- name = team.get("name")+ name = channel.get("name") or team.get("name")return str(name) if name else None+ async def _resolve_channel_name(+ self, activity: dict[str, Any], channel_id: str+ ) -> str | None:+ """The channel's name, asking Graph when the activity does not say.++ Without this the caller has nothing to name an auto-created room after+ and falls back to the channel id, so a room ends up titled+ `19:7641f9de326b4…` — in the room list, in the sidebar, and in every+ session opened against it. Graph knows the name; one read per channel,+ cached, is a cheap price for a room somebody can recognise.+ """+ name = self._channel_name(activity)+ if name:+ return name+ cached = self._channel_names.get(channel_id)+ if cached is not None:+ return cached or None+ if self._read_recently_failed(channel_id):+ return None+ await self._read_channel(channel_id)+ return self._channel_names.get(channel_id) or None++ 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.++ Returns None when the read could not be made or failed. A failure is+ remembered so the read is not retried on every message, but only for+ `_CHANNEL_READ_RETRY_AFTER` — a Graph blip, or a permission granted+ minutes later, must not pin a channel to "nameless, posts layout" for+ the life of the process. That is the same shape as the bug that made+ capture die at a restart, and it is not worth repeating for a cheaper+ symptom.+ """+ 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:+ return None+ try:+ channel = await self._graph.get_channel(+ team_id=team_id, channel_id=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",+ channel_id,+ exc_info=True,+ )+ self._channel_read_failed_at[channel_id] = time.monotonic()+ return None+ self._channel_read_failed_at.pop(channel_id, None)+ self._channel_names[channel_id] = str(channel.get("displayName") or "")+ self._channel_layouts[channel_id] = str(channel.get("layoutType") or "")+ return channel++ def _read_recently_failed(self, channel_id: str) -> bool:+ failed_at = self._channel_read_failed_at.get(channel_id)+ if failed_at is None:+ return False+ if time.monotonic() - failed_at < _CHANNEL_READ_RETRY_AFTER:+ return True+ del self._channel_read_failed_at[channel_id]+ return False+def _self_mention_token(self, activity: dict[str, Any]) -> str | None:recipient = activity.get("recipient") or {}bot_id = str(recipient.get("id", ""))@@ -1109,21 +1911,19 @@ class TeamsAdapter(CollaborationAdapter):"""if channel_id in self._subscriptions or self._graph is None:return+ self._capture_wanted.add(channel_id)if not (self._config.encryption_public_certificateand self._config.encryption_certificate_id):- logger.error(- "Cannot subscribe to channel %s messages: encryption certificate "- "not configured on the Teams bridge",+ self._note_capture_failure(channel_id,+ "encryption certificate not configured on the Teams bridge",)returnteam_id = self._team_of_channel.get(channel_id) or self._config.team_idif not team_id:- logger.warning(- "Cannot subscribe to channel %s: team id unknown", channel_id- )+ self._note_capture_failure(channel_id, "team id unknown")returnasync with self._sub_lock:@@ -1142,18 +1942,80 @@ class TeamsAdapter(CollaborationAdapter):encryption_certificate=cert_der,encryption_certificate_id=self._config.encryption_certificate_id,)- except Exception:- logger.exception(- "Failed to create Graph subscription for channel %s", channel_id- )+ except Exception as exc:+ self._note_capture_failure(channel_id, f"{type(exc).__name__}: {exc}")returnself._subscriptions[channel_id] = str(sub.get("id", ""))+ recovered = self._capture_failures.pop(channel_id, None) is not Nonelogger.info(- "Subscribed to Teams channel %s messages (subscription %s)",+ "%s Teams channel %s messages (subscription %s)",+ "Capture recovered for" if recovered else "Subscribed to",channel_id,self._subscriptions[channel_id],)+ def _note_capture_failure(self, channel_id: str, summary: str) -> None:+ """Record that a channel still has no capture, logging without repeating.++ ``_repair_loop`` retries for as long as the bridge runs, so a channel+ that can never be subscribed would otherwise write the same error+ forever. The first failure is logged in full; after that only a *change*+ in what Graph says is worth a line, and it is worth a lot — a 403+ turning into a 400 is a permission problem turning into an unreachable+ endpoint, which is the one thing a reader needs to know.+ """+ previous = self._capture_failures.get(channel_id)+ self._capture_failures[channel_id] = summary+ if previous is None:+ logger.error(+ "Failed to create Graph subscription for channel %s (%s); "+ "capture is degraded and will be retried",+ channel_id,+ summary,+ )+ elif previous != summary:+ logger.warning(+ "Graph subscription for channel %s is still failing, now with: %s",+ channel_id,+ summary,+ )+ else:+ logger.debug(+ "Graph subscription for channel %s still failing: %s",+ channel_id,+ summary,+ )++ async def _repair_loop(self) -> None:+ """Keep retrying channels that should be captured and are not.++ A subscription can fail for reasons that pass on their own, and the two+ that bite are both startup: Graph validates the notification URL by+ calling it, which a load balancer will refuse for the first minute or so+ after a new pod starts, and an app's Graph roles are fixed when its token+ is issued, so consent granted while the bridge is running is invisible+ until the token is replaced. Both used to leave capture dead until+ someone restarted the process — and a restart is what caused the first+ one, so it could just as easily fail again.++ Backs off while a channel keeps failing so a genuinely broken one does+ not hammer Graph, and returns to the short interval as soon as something+ succeeds.+ """+ delay = _REPAIR_MIN_INTERVAL_SECONDS+ while True:+ await asyncio.sleep(delay)+ missing = [c for c in self._capture_wanted if c not in self._subscriptions]+ if not missing:+ delay = _REPAIR_MIN_INTERVAL_SECONDS+ continue+ for channel_id in missing:+ await self._ensure_channel_subscription(channel_id)+ if any(c not in self._subscriptions for c in missing):+ delay = min(delay * 2, _REPAIR_MAX_INTERVAL_SECONDS)+ else:+ delay = _REPAIR_MIN_INTERVAL_SECONDS+async def _handle_http_notifications(self, request: web.Request) -> web.Response:# Subscription-creation handshake: Graph calls the endpoint with a# ``validationToken`` that must be echoed back verbatim as text/plain.@@ -1181,7 +2043,13 @@ class TeamsAdapter(CollaborationAdapter):# lifecycle events alike. clientState is the only origin control (the# encryption proves integrity, not origin), so an unverified lifecycle# event (e.g. a forged reauthorizationRequired) must not be honoured.- if item.get("clientState") != self._config.client_state:+ # Compared in constant time: this is an authentication check, and a+ # `!=` on a secret leaks its prefix through timing. 256 bits makes that+ # impractical to exploit rather than impossible to attempt, and the+ # cheap version is the same one line.+ if not hmac.compare_digest(+ str(item.get("clientState") or ""), self._config.client_state+ ):logger.warning("Rejected Graph notification: clientState mismatch")return@@ -1269,7 +2137,9 @@ class TeamsAdapter(CollaborationAdapter):else:user = sender.get("user") or {}sender_id = str(user.get("id", ""))- sender_name = str(user.get("displayName") or sender_id)+ sender_name = await self._sender_handle(+ sender_id, str(user.get("displayName") or "")+ )identity = chat_message.get("channelIdentity") or {}channel_id = str(identity.get("channelId", ""))diff --git a/core/switch_core/bridges/collaboration/teams/auth.py b/core/switch_core/bridges/collaboration/teams/auth.pyindex d5b9b8bc5..5f94e323a 100644--- a/core/switch_core/bridges/collaboration/teams/auth.py+++ b/core/switch_core/bridges/collaboration/teams/auth.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport loggingimport time+from typing import Anyimport httpximport jwt@@ -45,8 +46,28 @@ class TeamsTokenProvider:self._app_id = app_idself._app_password = app_passwordself._http = http- # scope -> (access_token, expires_at_epoch)- self._cache: dict[str, tuple[str, float]] = {}+ # scope -> (access_token, expires_at_epoch, issued_at_epoch)+ self._cache: dict[str, tuple[str, float, float]] = {}++ def invalidate(self, scope: str, *, min_age_seconds: float = 0.0) -> bool:+ """Drop a cached token so the next call mints a fresh one.++ An app's Graph roles are fixed when its token is issued, so a permission+ consented while the bridge is running is invisible for as long as the+ token lasts — about an hour of Graph insisting a permission is missing+ while the operator looks at it plainly granted in Azure. Throwing the+ token away on that refusal is what turns an hour into a second.++ ``min_age_seconds`` guards the pathological case: a token minted moments+ ago cannot have missed a grant, so re-minting it would only add a round+ trip to every genuine denial. Returns whether anything was dropped, so a+ caller can skip a retry that has nothing new to offer.+ """+ cached = self._cache.get(scope)+ if cached is None or time.time() - cached[2] < min_age_seconds:+ return False+ del self._cache[scope]+ return Trueasync def token(self, scope: str) -> str:cached = self._cache.get(scope)@@ -68,10 +89,21 @@ class TeamsTokenProvider:f"AAD token request for scope {scope} failed "f"({resp.status_code}): {resp.text}")- payload = resp.json()- access_token = str(payload["access_token"])+ # A 200 whose body is not the token response we expect — an HTML error+ # page from a proxy in front of AAD, or a shape change — must fail the+ # same way a 401 does. Left to raise on its own it surfaces as KeyError+ # or a JSON decode error, which callers looking for a credential problem+ # do not catch, and the save-time check turns into a 500.+ try:+ payload = resp.json()+ access_token = str(payload["access_token"])+ except (ValueError, KeyError, TypeError) as exc:+ raise RuntimeError(+ f"AAD token request for scope {scope} returned "+ f"{resp.status_code} with an unusable body: {resp.text[:500]}"+ ) from excexpires_in = float(payload.get("expires_in", 3600))- self._cache[scope] = (access_token, now + expires_in)+ self._cache[scope] = (access_token, now + expires_in, now)return access_tokenasync def bot_token(self) -> str:@@ -111,14 +143,49 @@ class InboundActivityValidator:raise PermissionError("missing bearer token on inbound Teams activity")token = auth_header.split(" ", 1)[1].strip()signing_key = self._ensure_jwks().get_signing_key_from_jwt(token)- jwt.decode(- token,- signing_key.key,- algorithms=["RS256"],- audience=self._app_id,- issuer=_BOTFRAMEWORK_ISSUER,- options={"require": ["exp", "iss", "aud"]},- )+ try:+ jwt.decode(+ token,+ signing_key.key,+ algorithms=["RS256"],+ audience=self._app_id,+ issuer=_BOTFRAMEWORK_ISSUER,+ options={"require": ["exp", "iss", "aud"]},+ )+ except jwt.InvalidAudienceError as exc:+ audience = self._describe_audience(token, signing_key.key)+ raise PermissionError(+ f"inbound Teams activity is addressed to {audience}, "+ f"but this bridge is configured with app id {self._app_id!r}. "+ "The Azure Bot resource's Microsoft App ID must be the app id "+ "registered on the bridge."+ ) from exc++ @staticmethod+ def _describe_audience(token: str, signing_key: Any) -> str:+ """The audience the token actually carries, for a mismatch message.++ Decoded with the same signing key, relaxing only the audience check —+ the one claim already known not to match. Reading it from an unverified+ parse would mean quoting an attacker's own words back in the message+ explaining why they were rejected, and the habit is worth not having+ even where, as here, the signature has just been checked.++ The audience of a Bot Connector token is an application id, not a+ secret; the token itself is never logged.+ """+ try:+ claims = jwt.decode(+ token,+ signing_key,+ algorithms=["RS256"],+ issuer=_BOTFRAMEWORK_ISSUER,+ options={"verify_aud": False},+ )+ except jwt.PyJWTError:+ return "an unreadable audience"+ aud = claims.get("aud")+ return f"app id {aud!r}" if aud else "no audience"def close(self) -> None:self._http.close()diff --git a/core/switch_core/bridges/collaboration/teams/cards.py b/core/switch_core/bridges/collaboration/teams/cards.pyindex de8f5e0d4..6731e8956 100644--- a/core/switch_core/bridges/collaboration/teams/cards.py+++ b/core/switch_core/bridges/collaboration/teams/cards.py@@ -5,7 +5,12 @@ from typing import AnyADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive"-def agent_message_card(agent_name: str, body: str, icon_url: str) -> dict[str, Any]:+def agent_message_card(+ agent_name: str,+ body: str,+ icon_url: str,+ mentions: list[dict[str, Any]] | None = None,+) -> dict[str, Any]:"""An Adaptive Card that labels a message with the sending agent's identity.Teams has a single bot identity and no per-message username override (unlike@@ -15,8 +20,13 @@ def agent_message_card(agent_name: str, body: str, icon_url: str) -> dict[str, Amarkdown subset: bold, italic, links, lists).``icon_url`` is resolved by the caller — the agent's own icon or the shared- default — because looking it up is async and this builder is not."""- return {+ default — because looking it up is async and this builder is not.++ ``mentions`` are Bot Framework mention entities matching ``<at>`` markup in+ ``body``. A card carries them under ``msteams`` rather than on the activity,+ and without them the markup renders as inert text and the person is never+ notified."""+ card: dict[str, Any] = {"$schema": "http://adaptivecards.io/schemas/adaptive-card.json","type": "AdaptiveCard","version": "1.4",@@ -64,6 +74,9 @@ def agent_message_card(agent_name: str, body: str, icon_url: str) -> dict[str, A},],}+ if mentions:+ card["msteams"] = {"entities": mentions}+ return carddef card_attachment(card: dict[str, Any]) -> dict[str, Any]:diff --git a/core/switch_core/bridges/collaboration/teams/crypto.py b/core/switch_core/bridges/collaboration/teams/crypto.pyindex 30f765668..943d5bded 100644--- a/core/switch_core/bridges/collaboration/teams/crypto.py+++ b/core/switch_core/bridges/collaboration/teams/crypto.py@@ -4,15 +4,18 @@ import base64import hashlibimport hmacimport json+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom cryptography import x509from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import padding as asym_padding+from cryptography.hazmat.primitives.asymmetric import rsafrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes-from cryptography.hazmat.primitives.hashes import SHA1+from cryptography.hazmat.primitives.hashes import SHA1, SHA256from cryptography.hazmat.primitives.padding import PKCS7from cryptography.hazmat.primitives.serialization import load_pem_private_key+from cryptography.x509.oid import NameOIDclass ResourceDataError(RuntimeError):@@ -83,6 +86,48 @@ def decrypt_resource_data(return result+def generate_encryption_keypair() -> tuple[str, str]:+ """Mint a self-signed X.509 keypair for Graph resource-data encryption.++ Graph uses the certificate purely as key transport for the per-notification+ symmetric key: it encrypts to the public key and never validates a chain, an+ issuer or an expiry against any trust store. So a self-signed certificate is+ not a compromise here — there is no party for a CA to vouch to.++ Returns ``(certificate_pem, private_key_pem)``.+ """+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ subject = x509.Name(+ [x509.NameAttribute(NameOID.COMMON_NAME, "switch-teams-bridge")]+ )+ # Anchored in the past rather than at `now` so a clock skewed backwards on+ # the node that mints it cannot produce a not-yet-valid certificate, and run+ # long because Graph rejects a subscription whose certificate is outside its+ # validity window and nothing renews this one. Rotation is replacement:+ # generate a new pair, which today means re-creating the bridge. That means+ # there is no expiry prompting anyone to do it — worth revisiting if these+ # keys ever need a lifecycle of their own.+ not_before = datetime(2000, 1, 1, tzinfo=UTC)+ not_after = not_before + timedelta(days=365 * 100)+ cert = (+ x509.CertificateBuilder()+ .subject_name(subject)+ .issuer_name(subject)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(not_before)+ .not_valid_after(not_after)+ .sign(key, SHA256())+ )+ cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")+ key_pem = key.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ ).decode("utf-8")+ return cert_pem, key_pem++def load_certificate_der_b64(cert_pem: str) -> str:"""Validate the PEM certificate and return its base64 DER body.diff --git a/core/switch_core/bridges/collaboration/teams/graph.py b/core/switch_core/bridges/collaboration/teams/graph.pyindex fd572407c..698828c2c 100644--- a/core/switch_core/bridges/collaboration/teams/graph.py+++ b/core/switch_core/bridges/collaboration/teams/graph.py@@ -2,32 +2,102 @@ from __future__ import annotationsimport loggingfrom typing import Any+from urllib.parse import quoteimport httpx-from switch_core.bridges.collaboration.teams.auth import TeamsTokenProvider+from switch_core.bridges.collaboration.models import BridgeOperationError+from switch_core.bridges.collaboration.teams.auth import GRAPH_SCOPE, TeamsTokenProviderlogger = logging.getLogger(__name__)GRAPH_BASE = "https://graph.microsoft.com/v1.0"+# How old our token must be before an authorization refusal is worth re-minting+# it for. A token issued seconds ago cannot have missed a grant.+_TOKEN_RETRY_AGE = 30.0-class GraphError(RuntimeError):+class GraphError(BridgeOperationError):"""A Microsoft Graph REST call returned a non-success status."""+def _graph_error(operation: str, resp: httpx.Response) -> GraphError:+ """A ``GraphError`` for a failed call, leading with Graph's own explanation.++ Graph answers a refusal with ``{"error": {"code", "message"}}``, and that+ message is the only part anyone can act on — it names the permission that+ was not consented, the host it could not resolve, the value it would not+ take. Passing the raw body on instead buries it in JSON, and the raw body is+ what reaches the operator once this becomes an API response.++ A body that is not that shape is passed through verbatim: better an+ unfriendly error that is true than a tidy one that guesses.+ """+ detail = resp.text+ try:+ error = resp.json()["error"]+ message = str(error["message"])+ code = str(error.get("code") or "").strip()+ detail = f"{code}: {message}" if code else message+ except (ValueError, KeyError, TypeError):+ pass+ return GraphError(f"{operation} failed ({resp.status_code}): {detail}")++class GraphClient:"""Async client for the Microsoft Graph endpoints the Teams bridge needs:- change-notification subscriptions (this phase) and, later, channel/user- provisioning. Every call carries an app-only Graph token."""+ change-notification subscriptions, channel and membership provisioning, and+ directory lookups. Every call carries an app-only Graph token."""def __init__(self, *, tokens: TeamsTokenProvider, http: httpx.AsyncClient) -> None:self._tokens = tokensself._http = http- async def _headers(self) -> dict[str, str]:+ async def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:token = await self._tokens.graph_token()- return {"Authorization": f"Bearer {token}"}+ headers = {"Authorization": f"Bearer {token}"}+ if extra:+ headers.update(extra)+ return headers++ async def _send(+ self,+ method: str,+ url: str,+ *,+ extra_headers: dict[str, str] | None = None,+ **kwargs: Any,+ ) -> httpx.Response:+ """Make a Graph call, retrying once if the token predates a new grant.++ Graph roles are carried in the token, not looked up per call, so a+ permission consented after ours was issued does nothing until the token+ is replaced — the refusal names a permission the operator can see is+ granted, and says it for as long as the token lives. When Graph refuses+ on authorization we therefore drop the token and ask once more with a+ newly minted one.++ Exactly once, and only if the token was old enough to have missed the+ grant, so a genuine denial costs one extra round trip rather than+ looping.+ """+ resp = await self._http.request(+ method, url, headers=await self._headers(extra_headers), **kwargs+ )+ if resp.status_code not in (401, 403):+ return resp+ if not self._tokens.invalidate(GRAPH_SCOPE, min_age_seconds=_TOKEN_RETRY_AGE):+ return resp+ logger.info(+ "Graph refused %s %s with %d; retrying once with a freshly issued "+ "token, in case a permission was granted since the last one",+ method,+ url,+ resp.status_code,+ )+ return await self._http.request(+ method, url, headers=await self._headers(extra_headers), **kwargs+ )async def create_subscription(self,@@ -57,50 +127,34 @@ class GraphClient:"clientState": client_state,"expirationDateTime": expiration_iso,}- resp = await self._http.post(- f"{GRAPH_BASE}/subscriptions", json=body, headers=await self._headers()- )+ resp = await self._send("POST", f"{GRAPH_BASE}/subscriptions", json=body)if resp.status_code >= 300:- raise GraphError(- f"create subscription for {resource} failed "- f"({resp.status_code}): {resp.text}"- )+ raise _graph_error(f"create subscription for {resource}", resp)result: dict[str, Any] = resp.json()return resultasync def renew_subscription(self, *, subscription_id: str, expiration_iso: str) -> None:- resp = await self._http.patch(+ resp = await self._send(+ "PATCH",f"{GRAPH_BASE}/subscriptions/{subscription_id}",json={"expirationDateTime": expiration_iso},- headers=await self._headers(),)if resp.status_code >= 300:- raise GraphError(- f"renew subscription {subscription_id} failed "- f"({resp.status_code}): {resp.text}"- )+ raise _graph_error(f"renew subscription {subscription_id}", resp)async def delete_subscription(self, *, subscription_id: str) -> None:- resp = await self._http.delete(- f"{GRAPH_BASE}/subscriptions/{subscription_id}",- headers=await self._headers(),+ resp = await self._send(+ "DELETE", f"{GRAPH_BASE}/subscriptions/{subscription_id}")if resp.status_code >= 300 and resp.status_code != 404:- raise GraphError(- f"delete subscription {subscription_id} failed "- f"({resp.status_code}): {resp.text}"- )+ raise _graph_error(f"delete subscription {subscription_id}", resp)async def list_subscriptions(self) -> list[dict[str, Any]]:- resp = await self._http.get(- f"{GRAPH_BASE}/subscriptions", headers=await self._headers()- )+ resp = await self._send("GET", f"{GRAPH_BASE}/subscriptions")if resp.status_code >= 300:- raise GraphError(- f"list subscriptions failed ({resp.status_code}): {resp.text}"- )+ raise _graph_error("list subscriptions", resp)value: list[dict[str, Any]] = resp.json().get("value", [])return value@@ -121,28 +175,32 @@ class GraphClient:"description": description,"membershipType": membership_type,}- resp = await self._http.post(- f"{GRAPH_BASE}/teams/{team_id}/channels",- json=body,- headers=await self._headers(),+ resp = await self._send(+ "POST", f"{GRAPH_BASE}/teams/{team_id}/channels", json=body)if resp.status_code >= 300:- raise GraphError(- f"create channel '{display_name}' in team {team_id} failed "- f"({resp.status_code}): {resp.text}"+ raise _graph_error(+ f"create channel '{display_name}' in team {team_id}", resp)result: dict[str, Any] = resp.json()return resultasync def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:- resp = await self._http.get(+ """One channel's properties.++ `$select` is not an optimisation here so much as a correctness one:+ Graph documents populating `email` and `summary` as expensive, and+ `layoutType` — which tells a posts channel from a chat one — is only+ returned by this per-channel read. Listing a team's channels reports it+ as null for every channel, so there is no bulk route to it.+ """+ resp = await self._send(+ "GET",f"{GRAPH_BASE}/teams/{team_id}/channels/{channel_id}",- headers=await self._headers(),+ params={"$select": "id,displayName,description,membershipType,layoutType"},)if resp.status_code >= 300:- raise GraphError(- f"get channel {channel_id} failed ({resp.status_code}): {resp.text}"- )+ raise _graph_error(f"get channel {channel_id}", resp)result: dict[str, Any] = resp.json()return result@@ -153,25 +211,47 @@ class GraphClient:ConsistencyLevel header. Returns the raw Graph user objects."""escaped = query.replace('"', '\\"')- headers = await self._headers()- headers["ConsistencyLevel"] = "eventual"- resp = await self._http.get(+ resp = await self._send(+ "GET",f"{GRAPH_BASE}/users",+ extra_headers={"ConsistencyLevel": "eventual"},params={- "$search": f'"displayName:{escaped}" OR "mail:{escaped}"',+ # userPrincipalName is searched as well as name and mail+ # because it is the handle Switch stores and later searches+ # back for when a claim is confirmed. Without it, a tenant+ # whose mail differs from its UPN — or has none — 404s on+ # someone the user just picked out of this very list.+ "$search": (+ f'"displayName:{escaped}" OR "mail:{escaped}" '+ f'OR "userPrincipalName:{escaped}"'+ ),"$select": "id,displayName,userPrincipalName,mail","$top": str(top),},- headers=headers,)if resp.status_code >= 300:- raise GraphError(- f"user search for {query!r} failed ({resp.status_code}): {resp.text}"- )+ raise _graph_error(f"user search for {query!r}", resp)payload: dict[str, Any] = resp.json()users: list[dict[str, Any]] = payload.get("value", []) or []return users+ async def get_user(self, *, user_id: str) -> dict[str, Any]:+ """One directory user by AAD object id.++ Teams leaves the sender's name off some activities — 1:1 chats in+ particular — and an id is not a name, however much the shape of the+ code lets it stand in for one.+ """+ resp = await self._send(+ "GET",+ f"{GRAPH_BASE}/users/{quote(user_id, safe='')}",+ params={"$select": "id,displayName,userPrincipalName,mail"},+ )+ if resp.status_code >= 300:+ raise _graph_error(f"get user {user_id}", resp)+ result: dict[str, Any] = resp.json()+ return result+async def add_channel_member(self, *, team_id: str, channel_id: str, user_aad_id: str) -> None:@@ -181,15 +261,14 @@ class GraphClient:"roles": [],"[email protected]": (f"{GRAPH_BASE}/users('{user_aad_id}')"),}- resp = await self._http.post(+ resp = await self._send(+ "POST",f"{GRAPH_BASE}/teams/{team_id}/channels/{channel_id}/members",json=body,- headers=await self._headers(),)if resp.status_code >= 300 and resp.status_code != 409:- raise GraphError(- f"add member {user_aad_id} to channel {channel_id} failed "- f"({resp.status_code}): {resp.text}"+ raise _graph_error(+ f"add member {user_aad_id} to channel {channel_id}", resp)async def add_team_member(self, *, team_id: str, user_aad_id: str) -> None:@@ -199,13 +278,8 @@ class GraphClient:"roles": [],"[email protected]": (f"{GRAPH_BASE}/users('{user_aad_id}')"),}- resp = await self._http.post(- f"{GRAPH_BASE}/teams/{team_id}/members",- json=body,- headers=await self._headers(),+ resp = await self._send(+ "POST", f"{GRAPH_BASE}/teams/{team_id}/members", json=body)if resp.status_code >= 300 and resp.status_code != 409:- raise GraphError(- f"add member {user_aad_id} to team {team_id} failed "- f"({resp.status_code}): {resp.text}"- )+ raise _graph_error(f"add member {user_aad_id} to team {team_id}", resp)diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex b70d18688..4bbe2ed96 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -1142,18 +1142,19 @@ class TelegramAdapter(CollaborationAdapter):channel_id: str,user_names: list[str],user_external_ids: list[str],- ) -> None:+ ) -> list[str]:# The Bot API has no call that adds a member to a chat — a person joins# from a Telegram client or an invite link. Say so rather than reporting# a membership change that never happened.if not user_names:- return+ return []logger.warning("Cannot add %s to Telegram chat %s — the Bot API cannot add members; ""they must join from a Telegram client or an invite link",", ".join(user_names),channel_id,)+ return list(user_external_ids)# ── Agent identity ───────────────────────────────────────────────────────diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.pyindex 224b19ad6..5cc0e7430 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_client.py@@ -46,6 +46,7 @@ from switch_core.bridges.resource.events import (RoomDocumentUpdateResponse,)from switch_core.bridges.resource.tracker import ResourceRequestTracker+from switch_core.clients.admin_messages import ADMIN_MARKERfrom switch_core.clients.client_base import ClientBase, ClientConfigfrom switch_core.clients.mentions import (NAME_CHAR as _NAME_CHAR,@@ -1206,7 +1207,19 @@ class AgentClient(ClientBase[ClientConfig]):Direct rooms always address. Otherwise the agent is addressed by an`@name` mention OR by an `@<role>` tag for a room-role it currentlyholds (see `_is_mentioned_via_role`).++ **A system message never addresses anyone**, whatever the room type.+ Switch's own notices — a command's answer, "Added X to this room", the+ guidance shown when someone tags the app itself — are output, not a+ request for a reply. Two ways they were read as one: in a direct room+ every message addresses the agent, so running `/list-agents` in a 1:1+ chat had the agent start a session to respond to its own roster; and in+ any room, a notice that lists the agents present writes each `@name`,+ which tagged every one of them. The marker exists to say "generated by+ Switch"; this is it being honoured."""+ if ADMIN_MARKER in (event.source.get("content") or {}):+ return Falseif meta.channel_type == "direct":return Trueif self._is_mentioned(event):diff --git a/core/switch_core/clients/client_base.py b/core/switch_core/clients/client_base.pyindex 8a3dcdcbb..fbb5a7032 100644--- a/core/switch_core/clients/client_base.py+++ b/core/switch_core/clients/client_base.py@@ -13,6 +13,7 @@ from nio import (JoinedRoomsError,LoginError,MatrixRoom,+ ProfileSetDisplayNameError,ReactionEvent,RoomMemberEvent,RoomMessageMedia,@@ -119,6 +120,20 @@ class ClientBase[ConfigT: ClientConfig]:async def wait_ready(self) -> None:await self._ready.wait()+ async def set_display_name(self, display_name: str) -> None:+ """Change the name this client shows under in Matrix.++ The user id is an address and stays put; this is the label rooms+ render. Used to correct a puppet filed under a platform id before the+ platform would say who the person was.+ """+ resp = await self.client.set_displayname(display_name)+ if isinstance(resp, ProfileSetDisplayNameError):+ raise RuntimeError(+ f"Could not set the display name of {self.matrix_user_id}: {resp}"+ )+ self.display_name = display_name+def _joined_event(self, room_id: str) -> asyncio.Event:event = self._room_joined_events.get(room_id)if event is None:diff --git a/core/switch_core/db/stores/collaboration_bridge_store.py b/core/switch_core/db/stores/collaboration_bridge_store.pyindex cc4d8eb3a..812e5e919 100644--- a/core/switch_core/db/stores/collaboration_bridge_store.py+++ b/core/switch_core/db/stores/collaboration_bridge_store.py@@ -101,20 +101,61 @@ class CollaborationBridgeStore:await session.flush()return bridge+ async def _locked_for_config_update(+ self, session: AsyncSession, bridge_id: str+ ) -> CollaborationBridge:+ """The bridge row, locked for the rest of this transaction.++ ``connection_config`` is one JSONB value, and the learned parts of it+ are written by read-modify-write from independent sessions — a Teams+ bridge persists a channel's team the first time it sees that channel,+ so a burst of new channels is a burst of concurrent writers. Unlocked,+ each one reads the blob before the others commit and the last write+ wins, silently discarding the rest. Measured: eight concurrent writes+ landed two.++ A dropped `channel_teams` entry is not cosmetic — it is exactly the+ state that makes Graph refuse that channel's subscription after the+ next restart, which is the failure the entry exists to prevent.+ """+ row = await session.execute(+ select(CollaborationBridge)+ .where(CollaborationBridge.id == bridge_id)+ .with_for_update()+ )+ bridge = row.scalar_one_or_none()+ if bridge is None:+ raise ValueError(f"Bridge not found: {bridge_id}")+ return bridge+async def set_service_url(self, session: AsyncSession, bridge_id: str, service_url: str) -> None:"""Persist a learned outbound serviceUrl into ``connection_config`` so itsurvives a restart. Reassigns the dict so SQLAlchemy tracks the change."""- bridge = await session.get(CollaborationBridge, bridge_id)- if bridge is None:- raise ValueError(f"Bridge not found: {bridge_id}")+ bridge = await self._locked_for_config_update(session, bridge_id)bridge.connection_config = {**(bridge.connection_config or {}),"service_url": service_url,}await session.flush()+ async def set_channel_team(+ self, session: AsyncSession, bridge_id: str, channel_id: str, team_id: str+ ) -> None:+ """Persist which team a channel belongs to into ``connection_config``.++ Merged into the existing map rather than replacing it, so learning one+ channel does not forget the rest. Reassigns the dicts so SQLAlchemy+ tracks the change (a mutated JSONB value is not detected)."""+ bridge = await self._locked_for_config_update(session, bridge_id)+ config = dict(bridge.connection_config or {})+ known = dict(config.get("channel_teams") or {})+ known[channel_id] = team_id+ config["channel_teams"] = known+ bridge.connection_config = config+ await session.flush()+async def delete(self, session: AsyncSession, bridge_id: str) -> None:bridge = await session.get(CollaborationBridge, bridge_id)if bridge:diff --git a/core/switch_core/db/stores/external_user_store.py b/core/switch_core/db/stores/external_user_store.pyindex 321cffcbd..92046cc04 100644--- a/core/switch_core/db/stores/external_user_store.py+++ b/core/switch_core/db/stores/external_user_store.py@@ -16,6 +16,19 @@ class ExternalUserStore:async def get(self, session: AsyncSession, user_id: str) -> ExternalUser | None:return await session.get(ExternalUser, user_id)+ async def rename(+ self, session: AsyncSession, user_id: str, external_username: str+ ) -> None:+ """Correct the name a person is filed under on their bridge.++ Their `external_user_id` is what identifies them and does not change,+ so claims and room membership are untouched; this is only the label —+ which matters because it is what agents address them by.+ """+ user = await session.get(ExternalUser, user_id)+ if user is not None:+ user.external_username = external_username+async def get_by_external_id(self, session: AsyncSession, bridge_id: str, external_user_id: str) -> ExternalUser | None:diff --git a/core/switch_core/deeplinks.py b/core/switch_core/deeplinks.pyindex 98259a76b..ff2034eb0 100644--- a/core/switch_core/deeplinks.py+++ b/core/switch_core/deeplinks.py@@ -9,7 +9,8 @@ from urllib.parse import urlsplit_DEEPLINK_SCHEME = "switchdash"_DEEPLINK_HOST = "session"-# Gateway path that 302-redirects to the reconstructed `switchdash://` deeplink.+# Gateway path that hands the browser off to the reconstructed `switchdash://`+# deeplink.# Kept here so the route and the rewrite agree on a single source of truth.DEEPLINK_REDIRECT_PATH = "/deeplink/session"@@ -19,7 +20,7 @@ def switchdash_to_gateway(deeplink_url: str, gateway_public_url: str) -> str | NPlatforms like Discord only linkify http(s), so the raw custom-schemedeeplink renders as plain text. The gateway serves an HTTP endpoint- (`DEEPLINK_REDIRECT_PATH`) that 302-redirects to the deeplink; posting that+ (`DEEPLINK_REDIRECT_PATH`) that hands off to the deeplink; posting thathttps URL makes the "Open in Switch Console" link clickable everywhere.The query string is carried across verbatim (server/agent/room/session and@@ -62,10 +63,10 @@ def deeplink_for_platform(def gateway_query_to_switchdash(query: str) -> str:"""Reconstruct the `switchdash://session?…` deeplink the redirect targets.- The inverse of `switchdash_to_gateway`: the redirect endpoint hands the- incoming query string here to build the Location it 302s to. Scheme and host- are fixed constants, so the endpoint can never be coerced into redirecting to- an arbitrary target.+ The inverse of `switchdash_to_gateway`: the handoff endpoint hands the+ incoming query string here to build the link it sends the browser to. Scheme+ and host are fixed constants, so the endpoint can never be coerced into+ pointing at an arbitrary target."""suffix = f"?{query}" if query else ""return f"{_DEEPLINK_SCHEME}://{_DEEPLINK_HOST}{suffix}"diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex c05685a69..243d5066c 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -11,7 +11,11 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)-from switch_core.bridges.collaboration.models import BridgeInstallLink, DirectoryUser+from switch_core.bridges.collaboration.models import (+ BridgeCredentialError,+ BridgeInstallLink,+ DirectoryUser,+)from switch_core.db.models import CollaborationBridge, ExternalUser, Userfrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStore@@ -169,6 +173,10 @@ async def create_bridge(connection_config=dict(req.connection_config),channel_creation_enabled=req.channel_creation_enabled,)+ except BridgeCredentialError as exc:+ # The platform's own words, verbatim — it knows what is wrong with the+ # credentials and we do not.+ raise HTTPException(status_code=400, detail=str(exc)) from excexcept ValidationError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excexcept ValueError as exc:diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex 094d711cf..9b59c1d93 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -8,7 +8,10 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.authz import Action, Principal, can, requirefrom switch_core.bridges.agent.protocol.service import ProtocolService-from switch_core.bridges.collaboration.models import ChannelType+from switch_core.bridges.collaboration.models import (+ BridgeOperationError,+ ChannelType,+)from switch_core.db.models import Room, RoomGroup, Userfrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStore@@ -347,6 +350,12 @@ async def create_room(result = await room_service.create_room(config)except ValueError as e:raise HTTPException(status_code=400, detail=str(e))+ except BridgeOperationError as e:+ # The platform refused to provision the channel and said why. Its+ # wording names the permission to grant or the value to change, and+ # the operator who clicked the button is the only one who can act on+ # it — so it goes back to them rather than into the log alone.+ raise HTTPException(status_code=502, detail=str(e)) from efresh = await room_store.get(session, result.room.id)if fresh is None:raise HTTPException(status_code=500, detail="Room missing after create")@@ -375,6 +384,8 @@ async def create_room_from_yaml(raise HTTPException(status_code=400, detail=str(e)) from eexcept PermissionError as e:raise HTTPException(status_code=403, detail=str(e)) from e+ except BridgeOperationError as e:+ raise HTTPException(status_code=502, detail=str(e)) from e@router.get("/{room_id}/yaml")diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex b72edbf1d..a53e8dd99 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -21,6 +21,7 @@ from switch_core.db.stores.room_store import RoomStorefrom switch_core.matrix_admin import MatrixAdminif TYPE_CHECKING:+ from switch_core.bridges.collaboration.bridge_core import BridgeCorefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -344,6 +345,69 @@ class RoomService:"allow channel creation for this connection.")+ @staticmethod+ async def _add_users_to_channel(+ bridge_core: BridgeCore,+ external_channel_id: str,+ user_names: list[str],+ ) -> list[dict[str, Any]]:+ """Add the room's people to its channel; report who did not make it.++ Returns ``failed_attachments``-shaped entries, because that is what this+ is: a post-creation step that can partly fail without the room being+ wrong. Two ways to miss — Switch not knowing the person on this bridge,+ and the platform refusing to add them — and both used to disappear into+ a log line, leaving a room that silently lacked the people it was asked+ for.+ """+ resolved = await bridge_core.resolve_external_user_id_map(user_names)+ failures: list[dict[str, Any]] = [+ {+ "kind": "user",+ "id": name,+ "error": "no account with this name is known on the bridge",+ }+ for name in user_names+ if name not in resolved+ ]+ # Paired positionally by contract, so build both from the same mapping+ # rather than passing the caller's full name list beside a shorter list+ # of ids — an adapter that zips them would otherwise mis-attribute.+ names = list(resolved)+ failed_ids = await bridge_core.adapter.add_users_to_channel(+ external_channel_id, names, [resolved[name] for name in names]+ )+ by_id = {resolved[name]: name for name in names}+ failures.extend(+ {+ "kind": "user",+ "id": by_id.get(external_id, external_id),+ "error": "the platform would not add them to the channel",+ }+ for external_id in failed_ids+ )+ return failures++ @staticmethod+ async def _ensure_channel_capture(+ bridge_core: BridgeCore,+ external_channel_id: str,+ channel_type: ChannelType,+ ) -> None:+ """Establish server-side message capture for a channel bound to a room.++ Provisioning a channel subscribes to it on the way past, but binding one+ that already exists does not — and on a bridge whose capture is a+ per-channel subscription (Teams, via Graph) that leaves the room+ receiving only what @mentions the bot, until the bridge next restarts+ and its startup reconciliation notices. A no-op for adapters whose+ capture is a single bridge-wide stream, and idempotent for those where+ it is not.+ """+ await bridge_core.adapter.ensure_channel_subscriptions(+ [(external_channel_id, channel_type)]+ )+async def create_room(self, config: RoomCreateConfig) -> RoomCreateResult:await self._validate_attachments(config)# Validate the group up front so a bad id fails before we provision a@@ -465,6 +529,11 @@ class RoomService:if bridge_core and external_channel_id:bridge_core.end_provisioning(external_channel_id)+ if bridge_core and external_channel_id:+ await self._ensure_channel_capture(+ bridge_core, external_channel_id, channel_type+ )+# Invite the bridge client before the agent clients so it is joined (and# thus replicating) before any agent can post — otherwise messages sent# in the gap predate the bridge's join and are dropped by _should_ignore,@@ -474,6 +543,7 @@ class RoomService:matrix_room_id, bridge_core._bridge_client_matrix_user_id)+ unreachable_users: list[dict[str, Any]] = []if (bridge_coreand external_channel_id@@ -484,9 +554,8 @@ class RoomService:external_channel_id, agent_names)if config.user_names:- ext_ids = await bridge_core.resolve_external_user_ids(config.user_names)- await bridge_core.adapter.add_users_to_channel(- external_channel_id, config.user_names, ext_ids+ unreachable_users = await self._add_users_to_channel(+ bridge_core, external_channel_id, config.user_names)await bridge_core.ensure_users_in_room(room.id, matrix_room_id, config.user_names@@ -516,7 +585,9 @@ class RoomService:len(system_clients),)- failed_attachments = await self._attach_after_creation(room.id, config)+ failed_attachments = unreachable_users + await self._attach_after_creation(+ room.id, config+ )if failed_attachments:logger.warning("Room %s created with %d attachment failure(s): %s",@@ -752,10 +823,13 @@ class RoomService:await session.commit()async def add_users_to_room(self, room_id: str, user_names: list[str]) -> list[str]:- """Add users to a bridged room; returns the names that could not be- resolved on the room's bridge (added users are omitted from the- result). A name is unresolvable when the bridge has no external user- for it — e.g. the person has not yet signed into that workspace."""+ """Add users to a bridged room; returns the names that did not make it+ (added users are omitted from the result).++ Two ways to miss. The bridge may have no external user for the name —+ the person has not yet signed into that workspace — or the platform may+ refuse to add someone it does know. Both come back here, because to the+ caller they are the same fact: that person is not in the room."""async with self._session_factory() as session:room = await self._room_store.get(session, room_id)if room is None:@@ -768,9 +842,11 @@ class RoomService:resolved = await bridge_core.resolve_external_user_id_map(user_names)unresolved = [name for name in user_names if name not in resolved]resolved_names = list(resolved.keys())- await bridge_core.adapter.add_users_to_channel(+ failed_ids = await bridge_core.adapter.add_users_to_channel(room.external_channel_id, resolved_names, list(resolved.values()))+ by_id = {resolved[name]: name for name in resolved_names}+ unresolved.extend(by_id.get(fid, fid) for fid in failed_ids)await bridge_core.ensure_users_in_room(room.id, room.matrix_room_id, resolved_names)@@ -819,6 +895,9 @@ class RoomService:bridge_core.add_room_mapping(room.id, room.matrix_room_id, external_channel_id)+ await self._ensure_channel_capture(+ bridge_core, external_channel_id, channel_type+ )logger.info("Linked bridge %s to room %s", bridge_id, room_id)@@ -924,6 +1003,10 @@ class RoomService:new_bridge.add_room_mapping(room_id, matrix_room_id, external_channel_id)finally:new_bridge.end_provisioning(external_channel_id)++ await self._ensure_channel_capture(+ new_bridge, external_channel_id, resolved_channel_type+ )await self._matrix_admin.invite_to_room(matrix_room_id, new_bridge._bridge_client_matrix_user_id)diff --git a/core/tests/switch_core/bridges/agent/test_deeplink_route.py b/core/tests/switch_core/bridges/agent/test_deeplink_route.pyindex 4b2d87c7d..274cf3b27 100644--- a/core/tests/switch_core/bridges/agent/test_deeplink_route.py+++ b/core/tests/switch_core/bridges/agent/test_deeplink_route.py@@ -27,26 +27,67 @@ def _client_with_auth() -> TestClient:return TestClient(app, follow_redirects=False)-class TestDeeplinkRedirect:- def test_302_redirects_to_switchdash_deeplink(self) -> None:+class TestDeeplinkHandoff:+ """The click lands here and has to reach the desktop app.++ It used to be a bare 302. A browser handing off to a desktop app leaves the+ tab on whatever it last rendered, and a 302 renders nothing — so on Teams+ the tab sat on Defender's "Verifying link . . ." interstitial long after+ Switch Console had opened, reading as a link that hung.+ """++ def test_the_page_points_at_the_switchdash_deeplink(self) -> None:resp = _client().get("/deeplink/session",params={"server": "https://s", "agent": "a", "room": "r", "session": "x"},)- assert resp.status_code == 302- location = resp.headers["location"]- assert location.startswith("switchdash://session?")- assert "room=r" in location- assert "agent=a" in location- def test_no_query_redirects_to_bare_deeplink(self) -> None:+ assert resp.status_code == 200+ assert "switchdash://session?" in resp.text+ assert "room=r" in resp.text+ assert "agent=a" in resp.text++ def test_no_query_still_reaches_the_bare_deeplink(self) -> None:resp = _client().get("/deeplink/session")- assert resp.status_code == 302- assert resp.headers["location"] == "switchdash://session"++ assert resp.status_code == 200+ assert 'href="switchdash://session"' in resp.text++ def test_it_tries_to_close_the_tab_and_says_so_when_it_cannot(self) -> None:+ # Browsers only let a script close a window a script opened, and this+ # one was opened by a click in Teams — so the close usually fails and+ # the page has to end on a true statement rather than a spinner.+ resp = _client().get("/deeplink/session", params={"room": "r"})++ assert "window.close()" in resp.text+ assert "You can close this tab" in resp.text++ def test_a_manual_link_survives_without_javascript(self) -> None:+ resp = _client().get("/deeplink/session", params={"room": "r"})++ assert 'id="target" href="switchdash://session?room=r"' in resp.text+++class TestDeeplinkQueryIsEscaped:+ """The endpoint is public and its query comes from whoever clicked it, so+ the target now lands in HTML rather than a Location header."""++ def test_a_quote_in_the_query_cannot_break_out_of_the_attribute(self) -> None:+ resp = _client().get('/deeplink/session?room="><script>alert(1)</script>')++ assert "<script>alert(1)</script>" not in resp.text+ assert "<script>" in resp.text or "%3Cscript%3E" in resp.text++ def test_the_scheme_cannot_be_changed_by_the_caller(self) -> None:+ resp = _client().get("/deeplink/session?room=javascript:alert(1)")++ # The anchor is anchored: scheme and host are constants prepended here.+ assert 'href="switchdash://session?' in resp.text+ assert 'href="javascript:' not in resp.textclass TestDeeplinkIsPublic:- """The redirect must bypass the agent-bridge Bearer auth — it is clicked+ """The handoff must bypass the agent-bridge Bearer auth — it is clickedfrom an external channel with no token (the 401 CHOO-1588 originally hit)."""def test_deeplink_session_path_is_public(self) -> None:@@ -58,11 +99,12 @@ class TestDeeplinkIsPublic:def test_unrelated_path_is_not_public(self) -> None:assert _is_public_path("/agents/x") is False- def test_redirect_works_through_bearer_middleware_without_token(self) -> None:+ def test_handoff_works_through_bearer_middleware_without_token(self) -> None:# The exact CHOO-1588 regression: a no-token click returned 401# "Missing or invalid Authorization header" before /deeplink was public.resp = _client_with_auth().get("/deeplink/session", params={"server": "https://s", "room": "r"})- assert resp.status_code == 302- assert resp.headers["location"].startswith("switchdash://session?")++ assert resp.status_code == 200+ assert "switchdash://session?" in resp.textdiff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.pyindex 7f9f7111d..1cc21a722 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.py@@ -16,6 +16,11 @@ from switch_core.bridges.collaboration.models import (# away from the external-user path.+async def _noop_repair(*_args: object, **_kwargs: object) -> None:+ """Correcting a name recorded as a platform id — not what these tests turn on."""+ return None++def _msg(sender_name: str) -> InboundMessage:return InboundMessage(channel_id="chan-1",@@ -55,6 +60,7 @@ def _fake_bridge(*, agents: set[str]) -> SimpleNamespace:return Nonereturn SimpleNamespace(+ _repair_placeholder_username=_noop_repair,_is_registered_agent=_is_registered_agent,_ensure_user_in_matrix_room=_ensure_user_in_matrix_room,_handle_agent_joined_channel=_handle_agent_joined_channel,diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.pyindex 9e74b4384..cc8c8d94a 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py@@ -75,7 +75,12 @@ def _fake_bridge() -> SimpleNamespace:async def _record_message_map(**kwargs: str) -> None:recorded.append(kwargs)+ async def _repair_placeholder_username(*_args: Any, **_kwargs: Any) -> None:+ # Correcting a name recorded as a platform id; nothing these tests turn on.+ return None+ns = SimpleNamespace(+ _repair_placeholder_username=_repair_placeholder_username,_adapter=_FakeAdapter(),_channel_to_room={"chan-1": ("room-1", "!room:s")},_is_registered_agent=_is_registered_agent,diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py b/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.pyindex 1acaf053e..2bc78267e 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py@@ -52,6 +52,12 @@ def _fake_bridge(*, alias_agent: str | None, agents: dict[str, SimpleNamespace])return agents.get(aid)class _Adapter:+ def render_app_mention(self, token: str) -> str:+ # Slack's form, which is what the base class renders and what these+ # assertions are written against. A platform that reads it+ # differently overrides it — that is the point of the hook.+ return f"<@{token}>"+async def admin_message(self,channel_id: str,diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.pyindex c2955da6d..c5db36072 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py@@ -158,34 +158,33 @@ def test_teams_adapter_registers_with_expected_required_fields() -> None:assert "teams" in service.get_registered_types()schema = service.get_config_schema("teams")- # The credentials + endpoint fields with no default are required; the- # subscription/encryption fields are optional. client_state is required —- # it is the only control that authenticates a notification's origin.+ # Every field on the form is a value the operator has to fetch from Azure,+ # and all of them are required — there is no such thing as a half-configured+ # Teams bridge.assert set(schema["required"]) == {"app_id","app_password","tenant_id","team_id","public_base_url",- "client_state",}- # Switch-internal fields (the listener bind, the runtime-learned serviceUrl)- # are hidden from the admin config form — the admin only supplies genuine- # Teams/Azure credentials + endpoint.- assert set(schema["properties"]) == {- "app_id",- "app_password",- "tenant_id",- "team_id",- "public_base_url",+ assert set(schema["properties"]) == set(schema["required"])+ # Switch-internal fields are hidden: the listener bind and the+ # runtime-learned serviceUrl, plus everything Switch generates for itself —+ # the clientState shared secret and the Graph encryption trio. Asking an+ # operator to invent a secret or paste PEMs is three ways to get a silently+ # broken bridge.+ for hidden in (+ "listen_host",+ "listen_port",+ "service_url","client_state","encryption_certificate_id","encryption_public_certificate","encryption_private_key",- }- assert "listen_host" not in schema["properties"]- assert "listen_port" not in schema["properties"]- assert "service_url" not in schema["properties"]+ "channel_teams",+ ):+ assert hidden not in schema["properties"]# ── Connection config validation ─────────────────────────────────────────────diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.pyindex 0f02719df..d45e148cb 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py@@ -30,6 +30,11 @@ MATRIX_ROOM_ID = "!matrix:switch.local"APP_SENDER_ID = "BDATADOG"+async def _noop_repair(*_args: object, **_kwargs: object) -> None:+ """Correcting a name recorded as a platform id — not what these tests turn on."""+ return None++class _FakePuppet:"""Stands in for a ClientBase puppet whose join lands after the invite."""@@ -74,6 +79,7 @@ def _bridge(return "client-new"bridge = SimpleNamespace(+ _repair_placeholder_username=_noop_repair,_user_puppets={"ext-alice": "client-1"}if known_puppets is Noneelse known_puppets,@@ -180,6 +186,7 @@ async def test_first_message_from_app_sender_is_relayed() -> None:return await BridgeCore._ensure_user_in_matrix_room(inner, **kwargs) # type: ignore[arg-type]bridge = SimpleNamespace(+ _repair_placeholder_username=_noop_repair,_is_registered_agent=_is_registered_agent,_ensure_user_in_matrix_room=_ensure_user_in_matrix_room,_record_message_map=_record_message_map,@@ -221,6 +228,7 @@ async def test_first_message_from_unknown_member_is_relayed() -> None:relayed.append((kwargs["matrix_event_id"], kwargs["external_post_id"]))bridge = SimpleNamespace(+ _repair_placeholder_username=_noop_repair,_is_registered_agent=_is_registered_agent,_ensure_user_in_matrix_room=_ensure_user_in_matrix_room,_record_message_map=_record_message_map,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.pyindex 1472db4e6..62a57fa17 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@@ -16,11 +16,13 @@ import asyncioimport timefrom typing import Any-from switch_core.bridges.collaboration.adapter import LiveRuntimeIndicator+from switch_core.bridges.collaboration.adapter import (+ LiveRuntimeIndicator,+ format_elapsed,+)from switch_core.bridges.collaboration.mattermost.adapter import (MattermostAdapter,MattermostConnectionConfig,- _format_elapsed,)@@ -308,12 +310,12 @@ def test_a_retired_turn_does_not_nudge() -> None:def test_elapsed_is_written_the_way_it_is_read() -> None:- assert _format_elapsed(0.4) == "0s"- assert _format_elapsed(8.9) == "8s"- assert _format_elapsed(59) == "59s"- assert _format_elapsed(60) == "1m00s"- assert _format_elapsed(134) == "2m14s"- assert _format_elapsed(3600) == "1h00m"- assert _format_elapsed(3780) == "1h03m"+ assert format_elapsed(0.4) == "0s"+ assert format_elapsed(8.9) == "8s"+ assert format_elapsed(59) == "59s"+ assert format_elapsed(60) == "1m00s"+ assert format_elapsed(134) == "2m14s"+ assert format_elapsed(3600) == "1h00m"+ assert format_elapsed(3780) == "1h03m"# A clock that ran backwards is not a negative duration.- assert _format_elapsed(-5) == "0s"+ assert format_elapsed(-5) == "0s"diff --git a/core/tests/switch_core/bridges/collaboration/test_placeholder_username_repair.py b/core/tests/switch_core/bridges/collaboration/test_placeholder_username_repair.pynew file mode 100644index 000000000..fec17e8be--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_placeholder_username_repair.py@@ -0,0 +1,223 @@+"""CHOO-2067 — a person filed under a platform id gets their name back.++Switch records someone under the name it first sees. Teams does not always+supply one — a 1:1 chat activity often carries no `from.name` — so its own id+went in instead, and then read as that person's name everywhere: the title of+the room auto-created for them, their Matrix account, and the text of every+agent reply that addressed them.++Resolving the name properly stopped it happening to the next person and did+nothing for anyone already recorded, which is most of the people in a+deployment that has been running. This repairs them on their next message.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_TEAMS_ID = "29:1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"+++class _FakeSession:+ async def __aenter__(self) -> _FakeSession:+ return self++ async def __aexit__(self, *exc: object) -> bool:+ return False++ async def commit(self) -> None:+ return None+++class _Store:+ def __init__(self, user: Any) -> None:+ self._user = user+ self.renames: list[tuple[str, str]] = []+ self.reads = 0++ async def get_by_external_id(+ self, session: Any, bridge_id: str, external_user_id: str+ ) -> Any:+ self.reads += 1+ return self._user++ async def rename(self, session: Any, user_id: str, external_username: str) -> None:+ self.renames.append((user_id, external_username))+ self._user.external_username = external_username+++class _Puppet:+ def __init__(self) -> None:+ self.names: list[str] = []++ async def set_display_name(self, name: str) -> None:+ self.names.append(name)+++class _Lifecycle:+ def __init__(self, puppet: Any) -> None:+ self._puppet = puppet++ def get(self, client_id: str) -> Any:+ return self._puppet+++def _teams_adapter() -> TeamsAdapter:+ return TeamsAdapter(+ 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",+ )+ )+++def _core(stored_name: str, *, adapter: Any = None, puppet: Any = None) -> Any:+ user = SimpleNamespace(+ id="eu-1", external_username=stored_name, client_id="client-1"+ )+ core = object.__new__(BridgeCore)+ core._session_factory = lambda: _FakeSession() # type: ignore[attr-defined]+ core._bridge_id = "bridge-1" # type: ignore[attr-defined]+ core._bridge_type = "teams" # type: ignore[attr-defined]+ core._adapter = adapter or _teams_adapter() # type: ignore[attr-defined]+ core._external_user_store = _Store(user) # type: ignore[attr-defined]+ core._client_lifecycle = _Lifecycle(puppet or _Puppet()) # type: ignore[attr-defined]+ core._names_known_good = set() # type: ignore[attr-defined]+ return core+++# ── recognising an id ────────────────────────────────────────────────────────+++def test_teams_recognises_its_own_ids() -> None:+ adapter = _teams_adapter()++ assert adapter.is_placeholder_username(_TEAMS_ID)+ assert adapter.is_placeholder_username("8:orgid:abc-def")+ assert adapter.is_placeholder_username("50758b1a-9d9a-4430-8160-1a2b3c4d5e6f")+++def test_teams_does_not_mistake_a_name_for_an_id() -> None:+ adapter = _teams_adapter()++ for name in ("ada.lovelace", "Ada Lovelace", "alice", "a1b2c3"):+ assert not adapter.is_placeholder_username(name), name+++def test_a_platform_whose_handles_are_handles_recognises_nothing() -> None:+ # The default: nothing to recognise, so nothing is ever renamed.+ from switch_core.bridges.collaboration.adapter import CollaborationAdapter++ assert CollaborationAdapter.is_placeholder_username(None, _TEAMS_ID) is False # type: ignore[arg-type]+++# ── the repair ───────────────────────────────────────────────────────────────+++async def test_an_id_is_replaced_by_the_name_and_the_account_renamed() -> None:+ puppet = _Puppet()+ core = _core(_TEAMS_ID, puppet=puppet)++ await core._repair_placeholder_username("aad-1", "ada.lovelace")++ assert core._external_user_store.renames == [("eu-1", "ada.lovelace")]+ assert puppet.names == ["ada.lovelace"]+++async def test_a_real_name_already_stored_is_left_alone() -> None:+ # Renaming someone people have been addressing for weeks, because the+ # platform changed its mind about their display name, is worse than the+ # problem being fixed.+ core = _core("ada.lovelace")++ await core._repair_placeholder_username("aad-1", "Ada L")++ assert core._external_user_store.renames == []+++async def test_an_id_is_never_written_over_a_name() -> None:+ # The resolution can still fail and fall back to the id. That must not+ # undo a good name.+ core = _core("ada.lovelace")++ await core._repair_placeholder_username("aad-1", _TEAMS_ID)++ assert core._external_user_store.renames == []+++async def test_one_id_is_not_swapped_for_another() -> None:+ core = _core(_TEAMS_ID)++ await core._repair_placeholder_username("aad-1", "8:orgid:something")++ assert core._external_user_store.renames == []+++async def test_nothing_happens_when_the_name_is_unchanged() -> None:+ core = _core(_TEAMS_ID)++ await core._repair_placeholder_username("aad-1", _TEAMS_ID)++ assert core._external_user_store.renames == []+++async def test_an_empty_resolution_is_ignored() -> None:+ core = _core(_TEAMS_ID)++ await core._repair_placeholder_username("aad-1", "")++ assert core._external_user_store.renames == []+++async def test_the_rename_stands_even_if_the_account_cannot_be_relabelled() -> None:+ # The stored name is what agents address; the Matrix label is cosmetic.+ # Losing the second is no reason to abandon the first.+ class _Failing(_Puppet):+ async def set_display_name(self, name: str) -> None:+ raise RuntimeError("homeserver said no")++ core = _core(_TEAMS_ID, puppet=_Failing())++ await core._repair_placeholder_username("aad-1", "ada.lovelace")++ assert core._external_user_store.renames == [("eu-1", "ada.lovelace")]+++# ── cost on the common path ──────────────────────────────────────────────────+++async def test_a_name_already_known_good_is_not_looked_up_again() -> None:+ """This runs on every inbound message on every bridge, so the case where+ there is nothing to repair — almost every message — must not cost a query.+ A stored name that is not a placeholder cannot become one, since the repair+ is one-way, so the answer is safe to keep."""+ core = _core("Ada Lovelace")++ for _ in range(5):+ await core._repair_placeholder_username(_TEAMS_ID, "Ada Lovelace")++ assert core._external_user_store.reads == 1+++async def test_a_repaired_name_is_not_looked_up_again_either() -> None:+ core = _core(_TEAMS_ID)++ await core._repair_placeholder_username(_TEAMS_ID, "Ada Lovelace")+ assert core._external_user_store.renames == [("eu-1", "Ada Lovelace")]++ reads_after_repair = core._external_user_store.reads+ await core._repair_placeholder_username(_TEAMS_ID, "Ada Lovelace")++ assert core._external_user_store.reads == reads_after_repair + 1+ assert core._external_user_store.renames == [("eu-1", "Ada Lovelace")]diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.pyindex 779a936aa..f2471ffe4 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py@@ -918,6 +918,12 @@ class _CountingConnector:self.deletes.append(activity_id)+def _card_text(activity: dict[str, Any]) -> str:+ """The body an agent card carries, whatever its shape."""+ card = activity["attachments"][0]["content"]+ return "\n".join(str(block.get("text", "")) for block in card["body"])++def _wire_counting(adapter: TeamsAdapter, connector: _CountingConnector) -> None:adapter._connector = connector # type: ignore[assignment]adapter._default_service_url = "https://smba.example/amer/"@@ -975,7 +981,7 @@ def test_working_detail_refreshes_in_place() -> None:assert adapter._working_msg[("19:[email protected]", "worker")].message_ref == "M1"-def test_idle_clears_working_message() -> None:+def test_idle_retires_the_working_message_by_editing_it() -> None:adapter = _adapter()fake = _CountingConnector()_wire_counting(adapter, fake)@@ -999,7 +1005,12 @@ def test_idle_clears_working_message() -> None:))- assert fake.deletes == ["M1"]+ # A posts channel: Teams substitutes "This message has been deleted." for+ # anything removed and keeps it in the post, so the status is edited into a+ # terminal marker instead of being deleted.+ assert fake.deletes == []+ assert [u["activity_id"] for u in fake.updates] == ["M1"]+ assert "Done" in _card_text(fake.updates[-1]["activity"])assert ("19:[email protected]", "worker") not in adapter._working_msg@@ -1041,7 +1052,8 @@ def test_awaiting_input_keeps_working_and_pings() -> None:thread_root_id=None,))- # Both the working message and the ping are removed on idle.- assert set(fake.deletes) == {"M1", "M2"}+ # Both are retired on idle — edited, not deleted, in a posts channel.+ assert fake.deletes == []+ assert {u["activity_id"] for u in fake.updates} == {"M1", "M2"}assert key not in adapter._working_msgassert key not in adapter._input_pingsdiff --git a/core/tests/switch_core/bridges/collaboration/test_teams_app_package.py b/core/tests/switch_core/bridges/collaboration/test_teams_app_package.pynew file mode 100644index 000000000..0488a107f--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_app_package.py@@ -0,0 +1,391 @@+"""The Teams app package we ship has to be uploadable as it stands.++`docs/bridges/teams-app/` is a paste-and-upload package, not an illustration:+an operator zips those three files and Teams accepts or rejects them. Teams+gives no useful error for most of these mistakes — an icon of the wrong size or+an eleventh command comes back as a generic validation failure — so the limits+are asserted here instead.+"""++from __future__ import annotations++import json+import re+import struct+import sys+import zipfile+from pathlib import Path++import pytest++PACKAGE = Path(__file__).resolve().parents[5] / "docs" / "bridges" / "teams-app"+MANIFEST = PACKAGE / "manifest.json"++# The placeholder an operator must replace with their Azure Bot app id. It is+# the null GUID precisely so an unreplaced one is obvious rather than plausible.+PLACEHOLDER_ID = "00000000-0000-0000-0000-000000000000"++[email protected](scope="module")+def manifest() -> dict:+ return json.loads(MANIFEST.read_text())+++def _png_size(path: Path) -> tuple[int, int]:+ """(width, height) from a PNG's IHDR, without an image library."""+ header = path.read_bytes()[:24]+ assert header[:8] == b"\x89PNG\r\n\x1a\n", f"{path.name} is not a PNG"+ width, height = struct.unpack(">II", header[16:24])+ return width, height+++def test_the_manifest_is_valid_json_at_the_version_it_claims(manifest: dict) -> None:+ # The two must agree: Teams pins `manifestVersion` to a `const` per schema,+ # so a mismatched pair fails validation with nothing useful said about why.+ version = manifest["manifestVersion"]+ assert manifest["$schema"].endswith(f"/v{version}/MicrosoftTeams.schema.json")+++def test_every_field_teams_requires_is_present(manifest: dict) -> None:+ for field in (+ "manifestVersion",+ "version",+ "id",+ "developer",+ "name",+ "description",+ "icons",+ "accentColor",+ ):+ assert field in manifest, f"the manifest has no {field}"+ for field in ("name", "websiteUrl", "privacyUrl", "termsOfUseUrl"):+ assert manifest["developer"][field]+++def test_the_app_is_called_agent_switch(manifest: dict) -> None:+ assert manifest["name"]["short"] == "Agent Switch"+ assert manifest["developer"]["name"] == "Agent Switch"+++def test_the_strings_are_inside_the_lengths_teams_enforces(manifest: dict) -> None:+ # A manifest over any of these is rejected on upload with no useful reason.+ assert len(manifest["name"]["short"]) <= 30+ assert len(manifest["name"]["full"]) <= 100+ assert manifest["name"]["short"] != manifest["name"]["full"]+ assert len(manifest["description"]["short"]) <= 80+ assert len(manifest["description"]["full"]) <= 4000+ assert len(manifest["developer"]["name"]) <= 32+++def test_the_developer_urls_are_https(manifest: dict) -> None:+ # The schema types all three as httpsUrl; http fails validation.+ for field in ("websiteUrl", "privacyUrl", "termsOfUseUrl"):+ assert manifest["developer"][field].startswith("https://")+++def test_the_accent_colour_is_a_six_digit_hex(manifest: dict) -> None:+ accent = manifest["accentColor"]+ assert len(accent) == 7 and accent[0] == "#"+ int(accent[1:], 16)+++def test_the_app_id_placeholder_is_the_same_in_all_three_places(+ manifest: dict,+) -> None:+ # An operator replaces one value; the guide says so because Teams ties the+ # app, the bot and the Entra registration together through it.+ assert manifest["id"] == PLACEHOLDER_ID+ assert manifest["bots"][0]["botId"] == PLACEHOLDER_ID+ assert manifest["webApplicationInfo"]["id"] == PLACEHOLDER_ID+++def test_there_is_exactly_one_bot_covering_all_three_scopes(manifest: dict) -> None:+ assert len(manifest["bots"]) == 1, "Teams allows one bot per app"+ assert set(manifest["bots"][0]["scopes"]) == {"team", "personal", "groupChat"}+++def test_the_command_menu_is_within_the_platform_limits(manifest: dict) -> None:+ command_lists = manifest["bots"][0]["commandLists"]+ assert len(command_lists) <= 3+ for entry in command_lists:+ # Twelve from schema v1.25; ten before that.+ assert len(entry["commands"]) <= 12, "Teams caps a command list at twelve"+ for command in entry["commands"]:+ assert len(command["title"]) <= 32+ assert len(command["description"]) <= 128+++def test_a_mention_menu_title_carries_the_prefix_it_will_insert(+ manifest: dict,+) -> None:+ # The @mention menu inserts a title verbatim and prepends nothing, so the+ # title has to be the text Switch dispatches on.+ from switch_core.bridges.collaboration.teams.adapter import _COMMAND_PREFIXES++ for entry in manifest["bots"][0]["commandLists"]:+ if "slash" in entry.get("triggers", ["mention"]):+ continue+ for command in entry["commands"]:+ assert command["title"][:1] in _COMMAND_PREFIXES, command["title"]+++def test_a_slash_picker_title_is_bare_because_teams_adds_the_slash(+ manifest: dict,+) -> None:+ # The `/` picker prepends the slash for display and inserts the bare name,+ # which is why every Microsoft sample declares these without one. A title+ # of "/help" would render as "//help" and arrive with a prefix the picker+ # did not intend.+ for entry in manifest["bots"][0]["commandLists"]:+ if "slash" not in entry.get("triggers", ["mention"]):+ continue+ for command in entry["commands"]:+ assert not command["title"].startswith("/"), command["title"]+++def test_the_slash_picker_needs_the_bot_to_accept_targeted_messages(+ manifest: dict,+) -> None:+ # Declaring triggers: ["slash"] surfaces nothing on its own — the schema is+ # explicit that supportsTargetedMessages is what puts the agent in the+ # picker. Getting one without the other is a silent no-op.+ bot = manifest["bots"][0]+ declares_slash = any(+ "slash" in entry.get("triggers", ["mention"])+ for entry in bot.get("commandLists", [])+ )+ if declares_slash:+ assert bot.get("supportsTargetedMessages") is True+++def test_both_surfaces_offer_the_same_commands(manifest: dict) -> None:+ # Two lists exist only because the two surfaces spell a title differently.+ # They should not drift into offering different things.+ lists = {+ tuple(sorted(entry.get("triggers", ["mention"]))): {+ c["title"].lstrip("/") for c in entry["commands"]+ }+ for entry in manifest["bots"][0]["commandLists"]+ }+ assert lists[("mention",)] == lists[("slash",)]+++def test_the_menu_only_offers_commands_switch_answers(manifest: dict) -> None:+ # `/status` shipped in the old snippet and is not a command — picking it+ # from the menu returned "unknown command".+ from switch_core.bridges.agent.commands import COMMANDS_BY_NAME++ offered = {+ command["title"].lstrip("/!")+ for entry in manifest["bots"][0]["commandLists"]+ for command in entry["commands"]+ }+ unknown = sorted(offered - set(COMMANDS_BY_NAME))+ assert not unknown, f"the menu offers commands Switch cannot answer: {unknown}"+++def test_the_guide_ships_the_same_manifest_it_tells_you_to_paste() -> None:+ """The setup guide embeds the manifest so it can be copied without a+ download. Two copies drift, and the one people paste is the one in the+ guide — so they are compared rather than trusted."""+ guide = (PACKAGE.parent / "TEAMS_SETUP.md").read_text()+ fenced = re.search(r"```json\n(\{.*?\n\})\n```", guide, re.S)+ assert fenced, "no JSON block in TEAMS_SETUP.md — did the manifest section move?"+ assert json.loads(fenced.group(1)) == json.loads(MANIFEST.read_text())+++def test_both_icons_exist_at_the_sizes_teams_requires(manifest: dict) -> None:+ colour = PACKAGE / manifest["icons"]["color"]+ outline = PACKAGE / manifest["icons"]["outline"]+ assert _png_size(colour) == (192, 192)+ assert _png_size(outline) == (32, 32)+++def test_the_icons_are_named_relatively_so_they_zip_flat(manifest: dict) -> None:+ # Teams rejects a package whose files sit inside a folder, so the manifest+ # must not reference a path either.+ for path in manifest["icons"].values():+ assert "/" not in path and not path.startswith(".")+++# ── the builder that turns the three files into an uploadable zip ─────────────+++def _build(tmp_path: Path, *args: str) -> tuple[int, Path]:+ """Run the packager as an operator would, and return (exit code, zip)."""+ import subprocess++ out = tmp_path / "pkg.zip"+ script = PACKAGE.parents[2] / "scripts" / "build_teams_app_package.py"+ result = subprocess.run(+ [sys.executable, str(script), "-o", str(out), *args],+ capture_output=True,+ text=True,+ )+ return result.returncode, out+++def test_the_package_is_flat_because_teams_rejects_a_nested_one(+ tmp_path: Path,+) -> None:+ code, out = _build(tmp_path, "--app-id", "3fa85f64-5717-4562-b3fc-2c963f66afa6")++ names = zipfile.ZipFile(out).namelist()+ assert sorted(names) == ["color.png", "manifest.json", "outline.png"]+ assert all("/" not in name for name in names)+ assert code == 1 # host and URLs left as placeholders, and it says so+++def test_the_app_id_is_written_to_all_three_places(tmp_path: Path) -> None:+ # One value, three fields, and Teams does not explain a mismatch — which is+ # the whole reason this is not a hand edit.+ app_id = "3fa85f64-5717-4562-b3fc-2c963f66afa6"+ _, out = _build(tmp_path, "--app-id", app_id)++ built = json.loads(zipfile.ZipFile(out).read("manifest.json"))+ assert built["id"] == app_id+ assert built["bots"][0]["botId"] == app_id+ assert built["webApplicationInfo"]["id"] == app_id+++def test_a_fully_supplied_package_reports_success(tmp_path: Path) -> None:+ code, out = _build(+ tmp_path,+ "--app-id",+ "3fa85f64-5717-4562-b3fc-2c963f66afa6",+ "--public-host",+ "teams.example.org",+ "--privacy-url",+ "https://example.org/privacy",+ "--terms-url",+ "https://example.org/terms",+ )++ assert code == 0+ built = json.loads(zipfile.ZipFile(out).read("manifest.json"))+ assert built["validDomains"] == ["teams.example.org"]+ assert built["developer"]["privacyUrl"] == "https://example.org/privacy"+++def test_an_unreplaced_placeholder_is_a_non_zero_exit(tmp_path: Path) -> None:+ # So a CI step or a careless operator cannot ship the null GUID quietly.+ code, _ = _build(tmp_path)++ assert code == 1+++def test_a_bad_app_id_is_refused_rather_than_written(tmp_path: Path) -> None:+ code, out = _build(tmp_path, "--app-id", "not-a-guid")++ assert code != 0+ assert not out.exists()+++def test_the_built_package_declares_channel_feature_support(tmp_path: Path) -> None:+ _, out = _build(tmp_path, "--app-id", "3fa85f64-5717-4562-b3fc-2c963f66afa6")++ built = json.loads(zipfile.ZipFile(out).read("manifest.json"))+ assert built["supportsChannelFeatures"] == "tier1"+++def test_a_team_scoped_app_on_a_modern_schema_declares_channel_features(+ manifest: dict,+) -> None:+ """Teams rejects the upload without it, in its own words: "Applications with+ manifest version 1.25 or higher that support the 'team' scope must include+ the 'supportsChannelFeatures' property."++ It is a validator rule rather than a schema one, so nothing catches it+ before the upload does — which is how a package that validated cleanly+ against the published schema still came back refused.+ """+ version = tuple(int(n) for n in manifest["manifestVersion"].split("."))+ team_scoped = any("team" in bot.get("scopes", []) for bot in manifest["bots"])+ if version >= (1, 25) and team_scoped:+ assert manifest.get("supportsChannelFeatures") == "tier1"+++def test_the_builder_refuses_a_package_teams_would_reject_for_it(+ tmp_path: Path,+) -> None:+ # Pins the check itself, not just today's manifest: the rule has to survive+ # someone editing the shipped file.+ import subprocess++ stripped = json.loads(MANIFEST.read_text())+ stripped.pop("supportsChannelFeatures", None)+ scratch = tmp_path / "manifest.json"+ scratch.write_text(json.dumps(stripped))+ for icon in stripped["icons"].values():+ (tmp_path / icon).write_bytes((PACKAGE / icon).read_bytes())++ script = PACKAGE.parents[2] / "scripts" / "build_teams_app_package.py"+ source = script.read_text().replace(+ 'PACKAGE_DIR = REPO_ROOT / "docs" / "bridges" / "teams-app"',+ f"PACKAGE_DIR = Path({str(tmp_path)!r})",+ )+ patched = tmp_path / "build.py"+ patched.write_text(source)++ result = subprocess.run(+ [+ sys.executable,+ str(patched),+ "-o",+ str(tmp_path / "x.zip"),+ "--app-id",+ "3fa85f64-5717-4562-b3fc-2c963f66afa6",+ ],+ capture_output=True,+ text=True,+ )++ assert result.returncode != 0+ assert "supportsChannelFeatures" in (result.stdout + result.stderr)+++def test_bump_raises_the_patch_version(tmp_path: Path) -> None:+ # Teams matches on `id` and ignores an upload whose version has not risen,+ # without saying so — which is the usual reason an edit "did nothing".+ _, out = _build(+ tmp_path, "--app-id", "3fa85f64-5717-4562-b3fc-2c963f66afa6", "--bump"+ )++ shipped = json.loads(MANIFEST.read_text())["version"]+ built = json.loads(zipfile.ZipFile(out).read("manifest.json"))["version"]+ assert built != shipped+ major, minor, patch = (int(n) for n in built.split("."))+ was = [int(n) for n in shipped.split(".")]+ assert [major, minor, patch] == [was[0], was[1], was[2] + 1]+++def test_an_unbumped_build_says_teams_will_ignore_it(tmp_path: Path) -> None:+ import subprocess++ script = PACKAGE.parents[2] / "scripts" / "build_teams_app_package.py"+ result = subprocess.run(+ [+ sys.executable,+ str(script),+ "-o",+ str(tmp_path / "p.zip"),+ "--app-id",+ "3fa85f64-5717-4562-b3fc-2c963f66afa6",+ ],+ capture_output=True,+ text=True,+ )++ assert "--bump" in result.stdout+++def test_the_slash_list_is_offered_in_every_scope_the_bot_has(+ manifest: dict,+) -> None:+ # Narrowing this hid the commands in 1:1 chats. Microsoft's own example on+ # the slash-commands page scopes its slash list to personal as well, even+ # though the prose enumerates only channels and group chats — an inert+ # scope costs nothing, a missing one costs the feature.+ bot = manifest["bots"][0]+ for entry in bot["commandLists"]:+ assert set(entry["scopes"]) == set(bot["scopes"]), entry["triggers"]diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_auth.py b/core/tests/switch_core/bridges/collaboration/test_teams_auth.pyindex 6c0bf794c..6411f4b23 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_auth.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_auth.py@@ -178,9 +178,71 @@ def test_validator_rejects_wrong_audience() -> None:priv, pub = _keypair()validator = _validator(pub, app_id="app-1")- with pytest.raises(jwt.InvalidAudienceError):+ with pytest.raises(PermissionError) as excinfo:validator.validate(f"Bearer {_token(priv, aud='someone-else')}")+ # A mismatch is a misconfiguration, and the operator cannot fix it without+ # both halves: the app id Azure addressed the activity to, and the one this+ # bridge was registered with.+ message = str(excinfo.value)+ assert "someone-else" in message+ assert "app-1" in message+++def test_audience_mismatch_message_survives_an_unreadable_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The mismatch message reads the audience back out of the token. A token+ that decodes for verification but not for inspection must still produce the+ rejection, not a second error on top of it."""+ priv, pub = _keypair()+ validator = _validator(pub, app_id="app-1")+ token = _token(priv, aud="someone-else")++ original = jwt.decode++ def _decode(*args: Any, **kwargs: Any) -> Any:+ if kwargs.get("options", {}).get("verify_aud") is False:+ raise jwt.DecodeError("unreadable")+ return original(*args, **kwargs)++ monkeypatch.setattr(jwt, "decode", _decode)++ with pytest.raises(PermissionError) as excinfo:+ validator.validate(f"Bearer {token}")++ assert "app-1" in str(excinfo.value)+++def test_the_audience_quoted_back_is_a_signature_verified_one(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The rejection message names the audience the token carries, so that+ value must not come from an unverified parse — otherwise the text+ explaining why an attacker was rejected is written by the attacker.++ Every decode in the validator carries a key and checks the signature; only+ the audience claim, the one already known to mismatch, is relaxed.+ """+ priv, pub = _keypair()+ validator = _validator(pub, app_id="app-1")+ seen: list[dict[str, Any]] = []++ original = jwt.decode++ def _decode(*args: Any, **kwargs: Any) -> Any:+ seen.append(dict(kwargs.get("options") or {}))+ assert len(args) > 1 and args[1], "decoded with no key"+ return original(*args, **kwargs)++ monkeypatch.setattr(jwt, "decode", _decode)++ with pytest.raises(PermissionError):+ validator.validate(f"Bearer {_token(priv, aud='someone-else')}")++ assert seen, "the validator did not decode at all"+ assert not any(o.get("verify_signature") is False for o in seen)+def test_validator_rejects_expired_token() -> None:priv, pub = _keypair()diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_capture_repair.py b/core/tests/switch_core/bridges/collaboration/test_teams_capture_repair.pynew file mode 100644index 000000000..e85affe44--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_capture_repair.py@@ -0,0 +1,239 @@+"""CHOO-2067 — channel capture must survive a subscription that fails once.++Graph validates a notification URL by calling it, and a bridge asks for its+subscriptions within seconds of binding its port. Behind a load balancer that+is exactly when nothing answers yet, so the first attempt after every restart+is refused. Capture then stayed dead for the life of the process — and it was a+restart that broke it, so restarting to fix it is a coin toss. Observed four+times in one afternoon on switch-dev.++The same loop covers a slower case: an app's Graph roles are fixed when its+token is issued, so consent granted while the bridge runs does nothing until+the token is replaced.+"""++from __future__ import annotations++import asyncio+import datetime+import functools+from collections.abc import Callable+from typing import Any++import pytest+from cryptography import x509+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric import rsa+from cryptography.x509.oid import NameOID++from switch_core.bridges.collaboration.teams import adapter as adapter_module+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_CHANNEL = "19:[email protected]"++[email protected]_cache(maxsize=1)+def _cert_pem() -> str:+ """A real self-signed certificate — the subscription path loads it before+ it calls Graph, so a placeholder would fail these tests for the wrong+ reason. Generated once for the module."""+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "switch-teams-test")])+ now = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)+ cert = (+ x509.CertificateBuilder()+ .subject_name(name)+ .issuer_name(name)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now)+ .not_valid_after(now + datetime.timedelta(days=365))+ .sign(key, hashes.SHA256())+ )+ return cert.public_bytes(serialization.Encoding.PEM).decode()+++def _config() -> TeamsConnectionConfig:+ return TeamsConnectionConfig(+ app_id="app-123",+ app_password="secret",+ tenant_id="tenant-1",+ team_id="team-1",+ public_base_url="https://switch.example",+ encryption_certificate_id="cert-1",+ encryption_public_certificate=_cert_pem(),+ encryption_private_key="unused — nothing here decrypts a notification",+ client_state="s3cr3t",+ )+++class _Graph:+ """A Graph stub whose subscription call fails a set number of times."""++ def __init__(self, *, failures: int, error: Exception | None = None) -> None:+ self._remaining = failures+ self._error = error or RuntimeError(+ "ServiceUnavailable from the notification endpoint"+ )+ self.attempts = 0++ async def create_subscription(self, **kwargs: Any) -> dict[str, Any]:+ self.attempts += 1+ if self._remaining > 0:+ self._remaining -= 1+ raise self._error+ return {"id": "sub-1"}+++def _adapter(graph: _Graph) -> TeamsAdapter:+ adapter = TeamsAdapter(config=_config())+ adapter._graph = graph # type: ignore[assignment]+ return adapter+++async def test_a_failed_subscription_is_remembered_as_work_still_owed() -> None:+ adapter = _adapter(_Graph(failures=1))++ await adapter._ensure_channel_subscription(_CHANNEL)++ # Nothing captured yet — but the channel is not forgotten, which is what+ # let the old code drop it silently until the next restart.+ assert _CHANNEL not in adapter._subscriptions+ assert _CHANNEL in adapter._capture_wanted+ assert _CHANNEL in adapter._capture_failures+++async def test_the_second_attempt_succeeds_once_the_endpoint_answers() -> None:+ graph = _Graph(failures=1)+ adapter = _adapter(graph)++ await adapter._ensure_channel_subscription(_CHANNEL)+ await adapter._ensure_channel_subscription(_CHANNEL)++ assert graph.attempts == 2+ assert adapter._subscriptions[_CHANNEL] == "sub-1"+ # The failure is cleared, so a later failure logs as new rather than as a+ # repeat of one that has since been fixed.+ assert _CHANNEL not in adapter._capture_failures+++async def test_a_subscribed_channel_is_not_re_attempted() -> None:+ graph = _Graph(failures=0)+ adapter = _adapter(graph)++ await adapter._ensure_channel_subscription(_CHANNEL)+ await adapter._ensure_channel_subscription(_CHANNEL)++ assert graph.attempts == 1+++async def test_a_missing_certificate_is_recorded_without_calling_graph() -> None:+ config = _config()+ config.encryption_public_certificate = None+ config.encryption_certificate_id = None+ graph = _Graph(failures=0)+ adapter = TeamsAdapter(config=config)+ adapter._graph = graph # type: ignore[assignment]++ await adapter._ensure_channel_subscription(_CHANNEL)++ assert graph.attempts == 0+ assert "encryption certificate" in adapter._capture_failures[_CHANNEL]+++async def test_repeat_failures_are_quiet_but_a_changed_reason_is_not(+ caplog: pytest.LogCaptureFixture,+) -> None:+ # The loop retries for the life of the process, so an unfixable channel must+ # not write the same error forever — while a 403 becoming a 400 is the+ # difference between a permission problem and an unreachable endpoint.+ adapter = _adapter(_Graph(failures=0))+ caplog.set_level("WARNING")++ adapter._note_capture_failure(_CHANNEL, "403 Forbidden")+ adapter._note_capture_failure(_CHANNEL, "403 Forbidden")+ first_pass = [r for r in caplog.records if r.levelname in ("ERROR", "WARNING")]+ assert len(first_pass) == 1+ assert first_pass[0].levelname == "ERROR"++ adapter._note_capture_failure(_CHANNEL, "400 ValidationError")+ second_pass = [r for r in caplog.records if r.levelname in ("ERROR", "WARNING")]+ assert len(second_pass) == 2+ assert second_pass[1].levelname == "WARNING"+ assert "400 ValidationError" in second_pass[1].getMessage()+++async def test_recovery_is_announced(caplog: pytest.LogCaptureFixture) -> None:+ # A quiet recovery is nearly as bad as a quiet failure: the log said capture+ # was degraded and must say when it stopped being so.+ adapter = _adapter(_Graph(failures=1))+ await adapter._ensure_channel_subscription(_CHANNEL)+ caplog.set_level("INFO")++ await adapter._ensure_channel_subscription(_CHANNEL)++ assert any("Capture recovered" in r.getMessage() for r in caplog.records)+++async def test_a_first_time_subscription_does_not_claim_to_have_recovered(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter = _adapter(_Graph(failures=0))+ caplog.set_level("INFO")++ await adapter._ensure_channel_subscription(_CHANNEL)++ messages = [r.getMessage() for r in caplog.records]+ assert any("Subscribed to" in m for m in messages)+ assert not any("Capture recovered" in m for m in messages)+++async def _drive(adapter: TeamsAdapter, *, until: Callable[[], bool]) -> None:+ """Run the repair loop until a condition holds, then stop it."""+ task = asyncio.create_task(adapter._repair_loop())+ try:+ for _ in range(200):+ await asyncio.sleep(0.005)+ if until():+ return+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+++async def test_the_loop_restores_capture_with_no_restart_and_no_operator(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # The whole point: the first attempt after a restart is refused because the+ # load balancer is not serving the new pod yet, and a minute later it is.+ monkeypatch.setattr(adapter_module, "_REPAIR_MIN_INTERVAL_SECONDS", 0.01)+ monkeypatch.setattr(adapter_module, "_REPAIR_MAX_INTERVAL_SECONDS", 0.02)+ adapter = _adapter(_Graph(failures=1))++ await adapter._ensure_channel_subscription(_CHANNEL)+ assert _CHANNEL not in adapter._subscriptions++ await _drive(adapter, until=lambda: _CHANNEL in adapter._subscriptions)++ assert adapter._subscriptions[_CHANNEL] == "sub-1"+++async def test_a_channel_that_never_recovers_is_still_being_tried(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Backing off must not become giving up: the permission case can take an+ # hour to clear, long after any bounded number of attempts would have run+ # out.+ monkeypatch.setattr(adapter_module, "_REPAIR_MIN_INTERVAL_SECONDS", 0.01)+ monkeypatch.setattr(adapter_module, "_REPAIR_MAX_INTERVAL_SECONDS", 0.02)+ graph = _Graph(failures=10_000)+ adapter = _adapter(graph)++ await adapter._ensure_channel_subscription(_CHANNEL)+ await _drive(adapter, until=lambda: graph.attempts >= 4)++ assert graph.attempts >= 4+ assert _CHANNEL in adapter._capture_wanteddiff --git a/core/tests/switch_core/bridges/collaboration/test_teams_channel_layout.py b/core/tests/switch_core/bridges/collaboration/test_teams_channel_layout.pynew file mode 100644index 000000000..20684dd22--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_channel_layout.py@@ -0,0 +1,325 @@+"""Teams has two channel layouts, and they want opposite things.++A **posts** channel is a list of conversations: a message at the root opens a+new one, so an agent's answer has to be steered under the question or it reads+as a non-sequitur. A **chat** channel is a stream like every other platform+Switch bridges, and steering there is exactly wrong — it buries the agent's+first message, the room-linked notice and the runtime status inside whatever+thread the channel last used.++Graph is the only thing that knows which is which.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_CHANNEL = "19:[email protected]"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class _Connector:+ def __init__(self) -> None:+ self.new_posts: list[str] = []+ self.replies: list[str] = []++ async def create_channel_thread(+ self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ ) -> tuple[str, str]:+ self.new_posts.append(channel_id)+ return f"{channel_id};messageid=new", "msg-new"++ async def send_to_conversation(+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]+ ) -> str:+ self.replies.append(conversation_id)+ return "msg-reply"+++class _Graph:+ """Graph, answering only what the adapter reads off a channel."""++ def __init__(self, layout: str | None) -> None:+ self._layout = layout+ self.reads = 0++ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:+ self.reads += 1+ channel: dict[str, Any] = {"id": channel_id, "displayName": "general"}+ if self._layout is not None:+ channel["layoutType"] = self._layout+ return channel+++class _RefusingGraph:+ def __init__(self) -> None:+ self.reads = 0++ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:+ self.reads += 1+ raise RuntimeError("Authorization_RequestDenied")+++def _adapter(graph: Any) -> tuple[TeamsAdapter, _Connector]:+ adapter = TeamsAdapter(+ 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",+ )+ )+ connector = _Connector()+ adapter._connector = connector # type: ignore[assignment]+ adapter._graph = graph+ adapter._default_service_url = "https://smba.example"+ adapter._channel_type[_CHANNEL] = "channel_public"+ return adapter, connector+++async def _seen(adapter: TeamsAdapter, *, root_id: str | None, ref: str) -> None:+ adapter._on_message = None # type: ignore[assignment]+ adapter._on_command = None # type: ignore[assignment]+ await adapter._deliver(+ channel_id=_CHANNEL,+ channel_type="channel_public",+ sender_id="aad-1",+ sender_name="alice",+ text="a question",+ message_ref=ref,+ root_id=root_id,+ channel_name="general",+ )+++# ── Chat layout: the ordinary policy, same as every other bridge ──────────────+++def test_a_chat_channel_answers_at_the_root_when_no_thread_was_named() -> None:+ adapter, connector = _adapter(_Graph("chat"))+ _run(_seen(adapter, root_id=None, ref="msg-1"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer"))++ # A new root message in the stream, not a reply buried under msg-1.+ assert connector.new_posts == [_CHANNEL]+ assert connector.replies == []+++def test_a_chat_channel_still_honours_a_thread_the_agent_chose() -> None:+ # The agent decides: a Matrix-threaded reply is threaded in Teams too.+ adapter, connector = _adapter(_Graph("chat"))+ _run(_seen(adapter, root_id=None, ref="msg-1"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer", "msg-1"))++ assert connector.replies == [f"{_CHANNEL};messageid=msg-1"]+++def test_a_chat_channel_puts_the_room_linked_notice_at_the_root() -> None:+ # The notice answers nothing, and lands after the message that triggered+ # the room's creation — so it is the case most likely to be swallowed.+ adapter, connector = _adapter(_Graph("chat"))+ _run(_seen(adapter, root_id=None, ref="msg-1"))++ _run(adapter.admin_message(_CHANNEL, "I've linked this channel to a room."))++ assert connector.new_posts == [_CHANNEL]+ assert connector.replies == []+++def test_a_chat_channel_keeps_the_runtime_status_where_the_message_was() -> None:+ adapter, connector = _adapter(_Graph("chat"))++ # Triggered by a message at the root → the status belongs at the root.+ _run(+ adapter.apply_runtime_state(+ _CHANNEL, "james", "working", mention_handle=None, thread_root_id=None+ )+ )+ assert connector.new_posts == [_CHANNEL]+ assert connector.replies == []++ # Triggered from inside a thread → the status belongs in that thread.+ _run(+ adapter.apply_runtime_state(+ _CHANNEL, "rita", "working", mention_handle=None, thread_root_id="msg-4"+ )+ )+ assert connector.replies == [f"{_CHANNEL};messageid=msg-4"]+++def test_a_chat_channel_does_not_glue_an_agents_messages_together() -> None:+ # The bug Louis saw: everything an agent said after its first message was+ # rewritten into the thread that first message opened.+ adapter, connector = _adapter(_Graph("chat"))++ _run(adapter.send_message(_CHANNEL, "james", "Hi! I'm here and connected."))+ _run(adapter.send_message(_CHANNEL, "james", "What can I help with?"))++ assert connector.new_posts == [_CHANNEL, _CHANNEL]+ assert connector.replies == []+++# ── Posts layout: unchanged, an answer goes under the question ────────────────+++def test_a_posts_channel_still_answers_under_the_question() -> None:+ adapter, connector = _adapter(_Graph("post"))+ _run(_seen(adapter, root_id=None, ref="post-1"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer"))++ assert connector.new_posts == []+ assert connector.replies == [f"{_CHANNEL};messageid=post-1"]+++def test_an_agents_own_post_never_displaces_a_real_message() -> None:+ # An agent deliberately replying into an older thread must not drag every+ # later answer back into it.+ adapter, connector = _adapter(_Graph("post"))+ _run(_seen(adapter, root_id=None, ref="post-2"))++ _run(adapter.send_message(_CHANNEL, "james", "a note on the old one", "post-1"))+ _run(adapter.send_message(_CHANNEL, "james", "answering you"))++ assert connector.replies == [+ f"{_CHANNEL};messageid=post-1",+ f"{_CHANNEL};messageid=post-2",+ ]+++# ── When Graph cannot say ─────────────────────────────────────────────────────+++def test_an_unreadable_layout_is_treated_as_posts() -> None:+ # Graph's own default, and what every Teams channel was before the chat+ # layout existed — so it is the answer least likely to surprise.+ adapter, connector = _adapter(_RefusingGraph())+ _run(_seen(adapter, root_id=None, ref="post-1"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer"))++ assert connector.replies == [f"{_CHANNEL};messageid=post-1"]+++def test_a_layout_graph_omits_is_treated_as_posts() -> None:+ adapter, connector = _adapter(_Graph(None))+ _run(_seen(adapter, root_id=None, ref="post-1"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer"))++ assert connector.replies == [f"{_CHANNEL};messageid=post-1"]+++def test_the_layout_is_read_once_per_channel() -> None:+ graph = _Graph("chat")+ adapter, _ = _adapter(graph)++ _run(_seen(adapter, root_id=None, ref="msg-1"))+ _run(adapter.send_message(_CHANNEL, "james", "one"))+ _run(adapter.send_message(_CHANNEL, "james", "two"))+ _run(_seen(adapter, root_id=None, ref="msg-2"))++ assert graph.reads == 1+++def test_a_refusal_is_not_retried_on_every_message() -> None:+ graph = _RefusingGraph()+ adapter, _ = _adapter(graph)++ _run(_seen(adapter, root_id=None, ref="post-1"))+ _run(adapter.send_message(_CHANNEL, "james", "one"))+ _run(adapter.send_message(_CHANNEL, "james", "two"))++ assert graph.reads == 1+++# ── A failed read must not be permanent ───────────────────────────────────────+++class _FlakyGraph:+ """Refuses the first read, answers the second."""++ def __init__(self, layout: str) -> None:+ self._layout = layout+ self.reads = 0++ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:+ self.reads += 1+ if self.reads == 1:+ raise RuntimeError("ServiceUnavailable")+ return {"id": channel_id, "displayName": "general", "layoutType": self._layout}+++def test_a_failed_read_is_retried_once_its_backoff_has_passed() -> None:+ # A blip, or a permission granted a minute after the bridge started, must+ # not pin a channel to "nameless, posts layout" for the life of the+ # process — that is the shape of the bug that killed capture at a restart.+ import switch_core.bridges.collaboration.teams.adapter as adapter_module++ graph = _FlakyGraph("chat")+ adapter, connector = _adapter(graph)++ _run(adapter._channel_layout(_CHANNEL))+ assert graph.reads == 1+ # Still inside the backoff: no second call, and no layout yet.+ _run(adapter._channel_layout(_CHANNEL))+ assert graph.reads == 1++ adapter._channel_read_failed_at[_CHANNEL] -= (+ adapter_module._CHANNEL_READ_RETRY_AFTER + 1+ )++ assert _run(adapter._channel_layout(_CHANNEL)) == "chat"+ assert graph.reads == 2+ # And once it has answered, it is not asked again.+ _run(adapter._channel_layout(_CHANNEL))+ assert graph.reads == 2+++def test_learning_a_new_team_reopens_a_read_made_against_the_old_one() -> None:+ """The gap this closes: a channel in another team fails its read, then the+ team is learned and the subscription heals — but the name and layout would+ stay stuck at whatever the failed read left behind, because the wrong team+ is exactly what Graph refuses."""+ graph = _Graph("chat")+ adapter, _ = _adapter(graph)+ # A read made while the team was wrong, cached as "could not say".+ adapter._channel_layouts[_CHANNEL] = ""+ adapter._channel_names[_CHANNEL] = ""+ adapter._channel_read_failed_at[_CHANNEL] = 0.0++ _run(adapter._learn_channel_team(_CHANNEL, "team-elsewhere"))++ assert _CHANNEL not in adapter._channel_layouts+ assert _CHANNEL not in adapter._channel_read_failed_at+ assert _run(adapter._channel_layout(_CHANNEL)) == "chat"+++def test_relearning_the_same_team_does_not_discard_a_good_read() -> None:+ graph = _Graph("chat")+ adapter, _ = _adapter(graph)+ _run(adapter._learn_channel_team(_CHANNEL, "team-7"))+ _run(adapter._channel_layout(_CHANNEL))+ assert graph.reads == 1++ _run(adapter._learn_channel_team(_CHANNEL, "team-7"))++ assert _run(adapter._channel_layout(_CHANNEL)) == "chat"+ assert graph.reads == 1diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_channel_team_memory.py b/core/tests/switch_core/bridges/collaboration/test_teams_channel_team_memory.pynew file mode 100644index 000000000..cf6c26f0b--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_channel_team_memory.py@@ -0,0 +1,149 @@+"""A Teams channel's team has to outlive the process that learned it.++A Graph message subscription is created against+``teams/{team}/channels/{channel}/messages``. The team arrives only in the+``channelData`` of an inbound activity, and the bridge's configured ``team_id``+is merely the team it *provisions into* — a channel the bot was added to in+some other team belongs to none of it.++Held in memory alone, the mapping was lost on every restart and those channels+fell back to the configured team, where Graph answers "Channel is not present+in the team". Nothing recovered it either: refilling the map needs an activity+from that channel, and without capture Teams delivers only messages that+mention the bot — so addressing an *agent*, the normal way to use the room,+never arrived.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_CONFIGURED_TEAM = "team-configured"+_OTHER_TEAM = "team-elsewhere"+_CHANNEL = "19:[email protected]"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++def _config(**overrides: Any) -> TeamsConnectionConfig:+ return TeamsConnectionConfig(+ app_id="app-123",+ app_password="secret",+ tenant_id="tenant-9",+ team_id=_CONFIGURED_TEAM,+ public_base_url="https://switch.example",+ client_state="s3cr3t",+ **overrides,+ )+++def _activity_from(team_id: str) -> dict[str, Any]:+ """A conversationUpdate naming the team the channel actually lives in."""+ return {+ "type": "conversationUpdate",+ "id": "act-1",+ "serviceUrl": "https://smba.example",+ "conversation": {"id": _CHANNEL, "conversationType": "channel"},+ "channelData": {+ "channel": {"id": _CHANNEL, "name": "Agent Switch Test"},+ "team": {"id": "19:[email protected]", "aadGroupId": team_id},+ },+ "membersAdded": [],+ "recipient": {"id": "28:bot"},+ }+++def test_the_team_of_a_channel_is_persisted_when_it_is_learned() -> None:+ adapter = TeamsAdapter(config=_config())+ saved: list[tuple[str, str]] = []++ async def persist(channel_id: str, team_id: str) -> None:+ saved.append((channel_id, team_id))++ adapter.set_channel_team_persister(persist)+ _run(adapter._dispatch_activity(_activity_from(_OTHER_TEAM)))++ assert saved == [(_CHANNEL, _OTHER_TEAM)]+++def test_a_persisted_team_is_known_before_any_activity_arrives() -> None:+ # The restart case: the adapter comes up knowing what the last one learned,+ # so capture is re-established without the bot having to be mentioned.+ adapter = TeamsAdapter(config=_config(channel_teams={_CHANNEL: _OTHER_TEAM}))++ assert adapter._team_of_channel[_CHANNEL] == _OTHER_TEAM+++def test_without_it_the_channel_falls_back_to_the_wrong_team() -> None:+ # The bug, pinned: this is what Graph refuses with "Channel is not present+ # in the team".+ adapter = TeamsAdapter(config=_config())++ assert adapter._team_of_channel.get(_CHANNEL) is None+ assert adapter._config.team_id == _CONFIGURED_TEAM+++def test_the_same_team_is_not_written_twice() -> None:+ # Every inbound activity carries the team; persisting on each one would be+ # a database write per message.+ adapter = TeamsAdapter(config=_config())+ writes: list[tuple[str, str]] = []++ async def persist(channel_id: str, team_id: str) -> None:+ writes.append((channel_id, team_id))++ adapter.set_channel_team_persister(persist)+ _run(adapter._dispatch_activity(_activity_from(_OTHER_TEAM)))+ _run(adapter._dispatch_activity(_activity_from(_OTHER_TEAM)))++ assert len(writes) == 1+++def test_a_channel_that_moves_team_is_written_again() -> None:+ adapter = TeamsAdapter(config=_config(channel_teams={_CHANNEL: _CONFIGURED_TEAM}))+ writes: list[tuple[str, str]] = []++ async def persist(channel_id: str, team_id: str) -> None:+ writes.append((channel_id, team_id))++ adapter.set_channel_team_persister(persist)+ _run(adapter._dispatch_activity(_activity_from(_OTHER_TEAM)))++ assert writes == [(_CHANNEL, _OTHER_TEAM)]+ assert adapter._team_of_channel[_CHANNEL] == _OTHER_TEAM+++def test_a_failing_persister_does_not_break_the_activity() -> None:+ # The write is bookkeeping. Losing it costs capture after the next restart,+ # which is worth a warning — not dropping the message being handled.+ adapter = TeamsAdapter(config=_config())++ async def persist(channel_id: str, team_id: str) -> None:+ raise RuntimeError("database is down")++ adapter.set_channel_team_persister(persist)+ _run(adapter._dispatch_activity(_activity_from(_OTHER_TEAM)))++ assert adapter._team_of_channel[_CHANNEL] == _OTHER_TEAM+++def test_an_adapter_with_no_persister_still_works() -> None:+ # Adapters are constructed directly in tests and tools, without a bridge+ # behind them to persist anything.+ adapter = TeamsAdapter(config=_config())++ _run(adapter._dispatch_activity(_activity_from(_OTHER_TEAM)))++ assert adapter._team_of_channel[_CHANNEL] == _OTHER_TEAMdiff --git a/core/tests/switch_core/bridges/collaboration/test_teams_clients.py b/core/tests/switch_core/bridges/collaboration/test_teams_clients.pyindex ccb448917..710cf5173 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_clients.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_clients.py@@ -32,12 +32,37 @@ def _run(coro: Any) -> Any:class _FakeTokens:+ """A token provider with nothing cached, so an authorization refusal has no+ stale token to blame and is not retried. The retry itself is exercised by+ `_StaleTokens` below."""++ def __init__(self) -> None:+ self.tokens = ["graph-tok"]+async def graph_token(self) -> str:- return "graph-tok"+ return self.tokens[-1]async def bot_token(self) -> str:return "bot-tok"+ def invalidate(self, scope: str, *, min_age_seconds: float = 0.0) -> bool:+ return False+++class _StaleTokens(_FakeTokens):+ """A provider holding one token old enough to predate a recent grant."""++ def __init__(self) -> None:+ super().__init__()+ self.invalidations = 0++ def invalidate(self, scope: str, *, min_age_seconds: float = 0.0) -> bool:+ self.invalidations += 1+ if self.invalidations > 1:+ return False+ self.tokens.append("graph-tok-fresh")+ return True+class _Recorder:"""Captures each request and replies with a scripted status/body."""@@ -63,8 +88,8 @@ def _client(recorder: _Recorder) -> httpx.AsyncClient:return httpx.AsyncClient(transport=httpx.MockTransport(recorder.handler))-def _graph(recorder: _Recorder) -> GraphClient:- return GraphClient(tokens=_FakeTokens(), http=_client(recorder)) # type: ignore[arg-type]+def _graph(recorder: _Recorder, tokens: _FakeTokens | None = None) -> GraphClient:+ return GraphClient(tokens=tokens or _FakeTokens(), http=_client(recorder)) # type: ignore[arg-type]def _connector(recorder: _Recorder) -> BotConnectorClient:@@ -313,3 +338,96 @@ def test_delete_activity_success_is_silent() -> None:))assert rec.last.method == "DELETE"+++# ── a permission granted while we hold a token ───────────────────────────────+++class _RelentingRecorder(_Recorder):+ """Refuses the first call and accepts the second, the way Graph behaves+ once the caller presents a token minted after the grant."""++ def __init__(self, body: Any) -> None:+ super().__init__(403, body)++ def handler(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ if len(self.requests) == 1:+ return httpx.Response(403, json=self.body)+ return httpx.Response(200, json={"value": []})+++def _denied() -> dict[str, Any]:+ return {+ "error": {+ "code": "Authorization_RequestDenied",+ "message": "Insufficient privileges to complete the operation.",+ }+ }+++def test_a_403_is_retried_once_with_a_freshly_minted_token() -> None:+ # An app's Graph roles are fixed when its token is issued, so a permission+ # consented while the bridge runs does nothing until the token is replaced.+ # Left alone, that is an hour of Graph reporting a permission the operator+ # can see is granted.+ recorder = _RelentingRecorder(_denied())+ tokens = _StaleTokens()++ result = _run(_graph(recorder, tokens).list_subscriptions())++ assert result == []+ assert len(recorder.requests) == 2+ assert recorder.requests[0].headers["Authorization"] == "Bearer graph-tok"+ assert recorder.requests[1].headers["Authorization"] == "Bearer graph-tok-fresh"+++def test_a_403_that_survives_the_retry_still_raises() -> None:+ recorder = _Recorder(403, _denied())++ with pytest.raises(GraphError, match="Authorization_RequestDenied"):+ _run(_graph(recorder, _StaleTokens()).list_subscriptions())++ # Exactly twice: retrying a genuine denial in a loop helps nobody.+ assert len(recorder.requests) == 2+++def test_a_401_is_retried_too() -> None:+ # An expired or revoked token looks like this rather than a 403.+ recorder = _RelentingRecorder({"error": {"code": "InvalidAuthenticationToken"}})+ recorder.status = 401++ def handler(request: httpx.Request) -> httpx.Response:+ recorder.requests.append(request)+ if len(recorder.requests) == 1:+ return httpx.Response(401, json=recorder.body)+ return httpx.Response(200, json={"value": []})++ recorder.handler = handler # type: ignore[method-assign]++ _run(_graph(recorder, _StaleTokens()).list_subscriptions())++ assert len(recorder.requests) == 2+++def test_a_freshly_minted_token_is_not_re_minted() -> None:+ # `_FakeTokens.invalidate` reports nothing droppable, standing in for a+ # token issued moments ago — which cannot have missed a grant, so retrying+ # would only add a round trip to every genuine denial.+ recorder = _Recorder(403, _denied())++ with pytest.raises(GraphError):+ _run(_graph(recorder).list_subscriptions())++ assert len(recorder.requests) == 1+++def test_a_non_authorization_failure_is_not_retried() -> None:+ # A 400 says the request was wrong, and asking again with a new token+ # cannot make it right.+ recorder = _Recorder(400, {"error": {"code": "ValidationError"}})++ with pytest.raises(GraphError):+ _run(_graph(recorder, _StaleTokens()).list_subscriptions())++ assert len(recorder.requests) == 1diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_graph_errors.py b/core/tests/switch_core/bridges/collaboration/test_teams_graph_errors.pynew file mode 100644index 000000000..f61eb1979--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_graph_errors.py@@ -0,0 +1,84 @@+"""CHOO-2067 — what a Graph refusal says by the time it reaches a person.++These errors are the only account anyone gets of why provisioning failed, and+they now travel out of the API rather than stopping at the log, so their+wording is load-bearing.+"""++from __future__ import annotations++import httpx++from switch_core.bridges.collaboration.models import BridgeOperationError+from switch_core.bridges.collaboration.teams.graph import GraphError, _graph_error++_FORBIDDEN = {+ "error": {+ "code": "Forbidden",+ "message": (+ "Missing role permissions on the request. API requires one of "+ "'Channel.Create, Teamwork.Migrate.All'. Roles on the request ''."+ ),+ }+}+++def _resp(+ status: int, *, json: dict[str, object] | None = None, text: str = ""+) -> httpx.Response:+ if json is not None:+ return httpx.Response(status, json=json)+ return httpx.Response(status, text=text)+++def test_graph_error_leads_with_graphs_own_message() -> None:+ err = _graph_error("create channel 'Work' in team t1", _resp(403, json=_FORBIDDEN))++ message = str(err)+ assert "create channel 'Work' in team t1 failed (403)" in message+ assert "Forbidden: Missing role permissions" in message+ assert "'Channel.Create, Teamwork.Migrate.All'" in message+ # The JSON scaffolding is gone; only the sentence survives.+ assert "innerError" not in message+ assert '{"error"' not in message+++def test_a_body_that_is_not_graphs_shape_is_passed_through_verbatim() -> None:+ # A proxy or WAF answering in place of Graph. Guessing at what an unknown+ # body meant would be worse than showing it.+ err = _graph_error(+ "list subscriptions", _resp(502, text="<html>Bad Gateway</html>")+ )++ assert "list subscriptions failed (502)" in str(err)+ assert "<html>Bad Gateway</html>" in str(err)+++def test_an_error_object_without_a_message_falls_back_rather_than_half_reporting() -> (+ None+):+ err = _graph_error("get channel c1", _resp(400, json={"error": {"code": "Bad"}}))++ # No `message` key: the raw body is more honest than the bare code.+ assert '"code":"Bad"' in str(err).replace(" ", "")+++def test_a_code_less_error_uses_the_message_alone() -> None:+ err = _graph_error(+ "get channel c1", _resp(404, json={"error": {"message": "no such channel"}})+ )++ assert str(err).endswith("failed (404): no such channel")+++def test_graph_errors_are_bridge_operation_errors() -> None:+ # What lets the room-creation door answer 502 with Graph's words instead of+ # dropping an unhandled exception into a 500.+ err = _graph_error("create channel 'Work' in team t1", _resp(403, json=_FORBIDDEN))++ assert isinstance(err, GraphError)+ assert isinstance(err, BridgeOperationError)+ # Still a RuntimeError, so callers that already sorted "the attempt failed"+ # from "the request was wrong" are unaffected.+ assert isinstance(err, RuntimeError)+ assert not isinstance(err, ValueError)diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py b/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.pynew file mode 100644index 000000000..a3963582e--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py@@ -0,0 +1,237 @@+"""CHOO-2067 — what an agent's message looks like once it reaches Teams.++Three faults, all seen in one screenshot from switch-dev: a Slack-shaped+`<@28:11111111-…>` printed at the reader, an `@name` that highlighted nobody,+and a heading running into the line beneath it.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)+from switch_core.bridges.collaboration.teams.cards import agent_message_card+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++def _adapter(**targets: str) -> TeamsAdapter:+ adapter = TeamsAdapter(+ 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",+ )+ )+ if targets:+ adapter.prime_mention_targets(dict(targets))+ return adapter+++# ── @mentions ────────────────────────────────────────────────────────────────+++def test_a_known_person_becomes_real_mention_markup() -> None:+ adapter = _adapter(alice="aad-alice")++ assert adapter.translate_outbound("hi @alice") == "hi <at>alice</at>"+++def test_the_markup_is_matched_by_an_entity_or_it_highlights_nobody() -> None:+ adapter = _adapter(alice="aad-alice")+ body = adapter.translate_outbound("hi @alice")++ assert adapter._mention_entities(body) == [+ {+ "type": "mention",+ "text": "<at>alice</at>",+ "mentioned": {"id": "aad-alice", "name": "alice"},+ }+ ]+++def test_mention_matching_ignores_case() -> None:+ adapter = _adapter(Alice="aad-alice")++ assert adapter.translate_outbound("hi @alice") == "hi <at>alice</at>"+++def test_an_unknown_name_is_left_alone() -> None:+ # Agent names land here: an agent is not a Teams user, and Switch's own+ # addressing wants the plain `@name`. Marking it would render a mention+ # that highlights nobody.+ adapter = _adapter(alice="aad-alice")++ assert adapter.translate_outbound("ask @james about it") == ("ask @james about it")+ assert adapter._mention_entities("ask @james about it") == []+++def test_a_name_repeated_gets_one_entity() -> None:+ adapter = _adapter(alice="aad-alice")+ body = adapter.translate_outbound("@alice ping @alice again")++ assert body.count("<at>alice</at>") == 2+ assert len(adapter._mention_entities(body)) == 1+++def test_a_handle_with_a_space_in_it_is_still_a_mention() -> None:+ # The reported bug. Teams offers a display name for people whose principal+ # name we cannot read, so the handle we file them under is two words. A+ # matcher that stops at the space sees `@Louis` and finds nobody, and the+ # person gets flat text and no notification.+ adapter = _adapter(**{"Louis Amaudruz": "aad-louis"})+ body = adapter.translate_outbound("@Louis Amaudruz starting a session")++ assert body == "<at>Louis Amaudruz</at> starting a session"+ assert adapter._mention_entities(body) == [+ {+ "type": "mention",+ "text": "<at>Louis Amaudruz</at>",+ "mentioned": {"id": "aad-louis", "name": "Louis Amaudruz"},+ }+ ]+++def test_the_longest_known_name_wins() -> None:+ # Both are addressable, so matching the shorter one first would tag the+ # wrong person and leave "Amaudruz" dangling as text.+ adapter = _adapter(**{"Louis": "aad-other", "Louis Amaudruz": "aad-louis"})++ assert adapter.translate_outbound("@Louis Amaudruz") == "<at>Louis Amaudruz</at>"+ assert adapter.translate_outbound("@Louis alone") == "<at>Louis</at> alone"+++def test_a_known_name_is_not_matched_inside_a_longer_one() -> None:+ adapter = _adapter(ada="aad-ada")++ assert adapter.translate_outbound("@adaline wrote it") == "@adaline wrote it"+++def test_a_name_learned_later_is_matched_from_then_on() -> None:+ # The matcher is built from the targets, so it has to be rebuilt when a+ # person is met for the first time mid-session.+ adapter = _adapter(alice="aad-alice")+ assert adapter.translate_outbound("hi @bob") == "hi @bob"++ adapter.prime_mention_targets({"bob": "aad-bob"})++ assert adapter.translate_outbound("hi @bob") == "hi <at>bob</at>"+++def test_the_card_carries_mentions_where_teams_looks_for_them() -> None:+ # On a card the entities live under `msteams`, not on the activity.+ adapter = _adapter(alice="aad-alice")+ body = adapter.translate_outbound("hi @alice")++ activity = _run(adapter._message_activity("james", body))+ card = activity["attachments"][0]["content"]++ assert card["msteams"]["entities"][0]["mentioned"]["id"] == "aad-alice"+++def test_a_card_with_no_mentions_carries_no_msteams_block() -> None:+ assert "msteams" not in agent_message_card("james", "hello", "http://icon")+++# ── the app's own handle ─────────────────────────────────────────────────────+++def test_the_app_is_named_in_words_not_in_slack_syntax() -> None:+ # This is the `<@28:11111111-…>` from the screenshot. Teams has no inline+ # syntax that turns its app id into a mention, so printing one at the+ # reader is strictly worse than saying "me".+ adapter = _adapter()++ rendered = adapter.render_app_mention("28:11111111-2222-3333-4444-555555555555")++ assert rendered == "me"+ assert "<@" not in rendered+++# ── line breaks ──────────────────────────────────────────────────────────────+++def test_a_single_newline_survives() -> None:+ # Adaptive Cards follow Markdown: one newline is whitespace. This is the+ # heading that ran into the sentence under it.+ adapter = _adapter()++ assert adapter.translate_outbound("**Heading:**\nbody") == ("**Heading:**\n\nbody")+++def test_an_existing_paragraph_gap_is_not_widened() -> None:+ adapter = _adapter()++ assert adapter.translate_outbound("one\n\ntwo") == "one\n\ntwo"+++def test_list_items_keep_their_own_lines() -> None:+ adapter = _adapter()++ rendered = adapter.translate_outbound("- one\n- two")++ assert rendered == "- one\n\n- two"+ assert rendered.count("- ") == 2+++def test_a_body_with_no_newlines_is_unchanged() -> None:+ adapter = _adapter()++ assert adapter.translate_outbound("just a sentence") == "just a sentence"+++# ── translated once, not twice ───────────────────────────────────────────────+++def test_send_message_does_not_translate_again() -> None:+ # Callers of send_message translate first, by documented contract. The+ # adapter used to translate a second time, which is invisible while+ # translation is a no-op and corrupting the moment it is not — doubling+ # every newline again, and re-marking text that was already marked.+ adapter = _adapter(alice="aad-alice")+ already = adapter.translate_outbound("hi @alice\nthere")++ activity = _run(adapter._message_activity("james", already))++ assert activity["attachments"][0]["content"]["body"][-1]["text"] == already+ assert "<at><at>" not in already+ assert "\n\n\n" not in already+++# ── commands ─────────────────────────────────────────────────────────────────+++def test_both_command_prefixes_name_the_same_command() -> None:+ # Teams has no server-registered slash commands: a manifest command list+ # types the text into the compose box, so `/help` arrives as an ordinary+ # message. By the time we see it the two prefixes are the same thing.+ assert TeamsAdapter._command_name("!list-agents") == "list-agents"+ assert TeamsAdapter._command_name("/list-agents") == "list-agents"+++def test_a_bare_word_is_not_mistaken_for_a_command_name() -> None:+ assert TeamsAdapter._command_name("list-agents") == "list-agents"+++def test_the_invite_hint_offers_the_slash_form_unconditionally() -> None:+ hint = _adapter().slash_invite_hint()++ assert hint is not None+ assert "/invite-agent" in hint+ # Teams has no server-registered slash commands, so `/` is just a message+ # prefix the bot parses. It works whether or not the operator has declared+ # a command list, and the hint must not imply otherwise.+ assert "manifest" not in hintdiff --git a/core/tests/switch_core/bridges/collaboration/test_teams_post_replies.py b/core/tests/switch_core/bridges/collaboration/test_teams_post_replies.pynew file mode 100644index 000000000..6e5b196e6--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_post_replies.py@@ -0,0 +1,194 @@+"""CHOO-2067 — an answer belongs under the question.++A Teams posts channel is a list of posts, not a stream of messages, so posting+at the channel root starts a new conversation. An agent whose reply named no+thread did exactly that: the question sat in one post and its answer appeared+as a fresh one below, reading as a non-sequitur.++These cases run with no Graph client, so they also pin the fallback: a channel+whose layout cannot be read is treated as a posts channel. The two layouts are+separated in `test_teams_channel_layout.py`.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_CHANNEL = "19:[email protected]"+_CHAT = "19:[email protected]"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class _Connector:+ def __init__(self) -> None:+ self.new_posts: list[str] = []+ self.replies: list[str] = []++ async def create_channel_thread(+ self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ ) -> tuple[str, str]:+ self.new_posts.append(channel_id)+ return f"{channel_id};messageid=new", "msg-new"++ async def send_to_conversation(+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]+ ) -> str:+ self.replies.append(conversation_id)+ return "msg-reply"+++def _adapter() -> tuple[TeamsAdapter, _Connector]:+ adapter = TeamsAdapter(+ 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",+ )+ )+ connector = _Connector()+ adapter._connector = connector # type: ignore[assignment]+ adapter._default_service_url = "https://smba.example"+ adapter._channel_type[_CHANNEL] = "channel_public"+ adapter._channel_type[_CHAT] = "group"+ return adapter, connector+++async def _seen(adapter: TeamsAdapter, *, root_id: str | None, ref: str) -> None:+ """Put an inbound channel message through the shared delivery path."""+ adapter._on_message = None # type: ignore[assignment]+ adapter._on_command = None # type: ignore[assignment]+ await adapter._deliver(+ channel_id=_CHANNEL,+ channel_type="channel_public",+ sender_id="aad-1",+ sender_name="alice",+ text="a question",+ message_ref=ref,+ root_id=root_id,+ channel_name="general",+ )+++def test_a_reply_lands_in_the_post_the_question_was_asked_in() -> None:+ adapter, connector = _adapter()+ _run(_seen(adapter, root_id=None, ref="post-1"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer"))++ assert connector.new_posts == []+ assert connector.replies == [f"{_CHANNEL};messageid=post-1"]+++def test_a_reply_inside_an_existing_post_uses_that_post_not_the_message() -> None:+ adapter, connector = _adapter()+ _run(_seen(adapter, root_id="post-1", ref="msg-7"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer"))++ assert connector.replies == [f"{_CHANNEL};messageid=post-1"]+++def test_an_explicit_thread_still_wins() -> None:+ # A caller that named a thread knows better than the last thing we saw.+ adapter, connector = _adapter()+ _run(_seen(adapter, root_id=None, ref="post-1"))++ _run(adapter.send_message(_CHANNEL, "james", "an answer", "post-9"))++ assert connector.replies == [f"{_CHANNEL};messageid=post-9"]+++def test_with_nothing_seen_yet_a_new_post_is_still_opened() -> None:+ # An agent speaking first in a channel has nothing to answer under, and+ # must not be silenced for it.+ adapter, connector = _adapter()++ _run(adapter.send_message(_CHANNEL, "james", "good morning"))++ assert connector.new_posts == [_CHANNEL]+ assert connector.replies == []+++def test_group_chats_are_left_alone() -> None:+ # A group chat is a stream, not a list of posts — there is nothing to be+ # wrong about, and forcing a thread would be the wrong shape.+ adapter, connector = _adapter()++ _run(adapter.send_message(_CHAT, "james", "hello"))++ assert connector.new_posts == []+ assert connector.replies == [_CHAT]+++def test_the_post_follows_the_conversation_as_it_moves() -> None:+ adapter, connector = _adapter()+ _run(_seen(adapter, root_id=None, ref="post-1"))+ _run(adapter.send_message(_CHANNEL, "james", "first answer"))+ _run(_seen(adapter, root_id=None, ref="post-2"))+ _run(adapter.send_message(_CHANNEL, "james", "second answer"))++ assert connector.replies == [+ f"{_CHANNEL};messageid=post-1",+ f"{_CHANNEL};messageid=post-2",+ ]+++def test_an_agent_speaking_first_keeps_its_own_post() -> None:+ # Nothing to answer under, so the first message opens a post — but the+ # second must join it. Otherwise an agent greeting itself into a channel+ # produces a column of one-line posts, which is what it did.+ adapter, connector = _adapter()++ _run(adapter.send_message(_CHANNEL, "james", "Hi! I'm here and connected."))+ _run(adapter.send_message(_CHANNEL, "james", "What can I help with?"))++ assert connector.new_posts == [_CHANNEL]+ assert connector.replies == [f"{_CHANNEL};messageid=msg-new"]+++def test_an_admin_notice_joins_the_conversation_too() -> None:+ adapter, connector = _adapter()+ _run(_seen(adapter, root_id=None, ref="post-1"))++ _run(adapter.admin_message(_CHANNEL, "Added james to this room."))++ assert connector.new_posts == []+ assert connector.replies == [f"{_CHANNEL};messageid=post-1"]+++def test_an_inbound_message_still_wins_over_the_agents_own_post() -> None:+ # Someone asking a new question moves the conversation; the agent should+ # follow them rather than keep talking in the post it opened earlier.+ adapter, connector = _adapter()+ _run(adapter.send_message(_CHANNEL, "james", "good morning"))+ _run(_seen(adapter, root_id=None, ref="post-2"))++ _run(adapter.send_message(_CHANNEL, "james", "answering you"))++ assert connector.replies == [f"{_CHANNEL};messageid=post-2"]+++def test_a_group_chat_records_no_post() -> None:+ adapter, connector = _adapter()++ _run(adapter.send_message(_CHAT, "james", "hello"))+ _run(adapter.send_message(_CHAT, "james", "again"))++ assert connector.new_posts == []+ assert connector.replies == [_CHAT, _CHAT]diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_provisioning.py b/core/tests/switch_core/bridges/collaboration/test_teams_provisioning.pyindex 2ec80df0f..c697944b4 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_provisioning.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_provisioning.py@@ -3,8 +3,6 @@ from __future__ import annotationsimport asynciofrom typing import Any-import pytest-from switch_core.bridges.collaboration.teams.adapter import (TeamsAdapter,TeamsConnectionConfig,@@ -199,23 +197,38 @@ class _FailingGraph(_FakeGraph):await super().add_team_member(team_id=team_id, user_aad_id=user_aad_id)-def test_add_users_raises_on_partial_failure() -> None:- # A user that fails to add must surface as an error — the caller cannot be- # told the add succeeded when it did not (fail-loud). The good user is still- # added; the failure is reported afterwards.+def test_add_users_reports_partial_failure_without_raising() -> None:+ # This used to raise, and raising is what made adding a room answer 500:+ # the call runs inside room creation, so one guest account or one missing+ # Teams permission destroyed the whole request and left a half-provisioned+ # room behind. Every other adapter carries on. Still not silent — who was+ # left out comes back, and room creation reports them.adapter = _adapter()fake = _FailingGraph()adapter._graph = fake # type: ignore[assignment]adapter._channel_type["19:[email protected]"] = "channel_public"- with pytest.raises(RuntimeError, match="aad-bad"):- _run(- adapter.add_users_to_channel(- "19:[email protected]",- ["good", "bad"],- ["aad-good", "aad-bad"],- )+ failed = _run(+ adapter.add_users_to_channel(+ "19:[email protected]",+ ["good", "bad"],+ ["aad-good", "aad-bad"],)+ )- # The user that could be added was still added before the error surfaced.+ assert failed == ["aad-bad"]+ # The user that could be added was added rather than abandoned partway.assert fake.team_members == [{"team_id": "team-7", "user": "aad-good"}]+++def test_add_users_reports_nothing_when_all_succeed() -> None:+ adapter = _adapter()+ fake = _FakeGraph()+ adapter._graph = fake # type: ignore[assignment]+ adapter._channel_type["19:[email protected]"] = "channel_public"++ failed = _run(+ adapter.add_users_to_channel("19:[email protected]", ["good"], ["aad-good"])+ )++ assert failed == []diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_runtime_state_layout.py b/core/tests/switch_core/bridges/collaboration/test_teams_runtime_state_layout.pynew file mode 100644index 000000000..521e6b278--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_runtime_state_layout.py@@ -0,0 +1,235 @@+"""Teams deletes differently in its two channel layouts, so the status retires+differently too.++In a **posts** channel Teams substitutes *"This message has been deleted."* and+keeps it in the post. A status line that appears and vanishes every turn+therefore leaves one tombstone per turn per agent, and repositioning it leaves+another per move — which is what a channel talking to agents actually looked+like. Nothing turns that off, so the answer is not to delete: the status is+edited into a terminal marker and left as the record of a finished turn, the+way Mattermost already does it for the same reason.++A **chat**-layout channel drops a deleted message cleanly, so it keeps the+original behaviour: the status disappears when the turn ends.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_CHANNEL = "19:[email protected]"+_AGENT = "worker"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class _Connector:+ def __init__(self) -> None:+ self.updates: list[dict[str, Any]] = []+ self.deletes: list[str] = []+ self.posted: list[str] = []+ self._n = 0++ def _next(self) -> str:+ self._n += 1+ return f"M{self._n}"++ async def create_channel_thread(+ self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ ) -> tuple[str, str]:+ mid = self._next()+ self.posted.append(mid)+ return f"{channel_id};messageid={mid}", mid++ async def send_to_conversation(+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]+ ) -> str:+ mid = self._next()+ self.posted.append(mid)+ return mid++ async def update_activity(+ self,+ *,+ service_url: str,+ conversation_id: str,+ activity_id: str,+ activity: dict[str, Any],+ ) -> None:+ self.updates.append({"activity_id": activity_id, "activity": activity})++ async def delete_activity(+ self, *, service_url: str, conversation_id: str, activity_id: str+ ) -> None:+ self.deletes.append(activity_id)+++class _Graph:+ def __init__(self, layout: str) -> None:+ self._layout = layout++ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:+ return {"id": channel_id, "displayName": "general", "layoutType": self._layout}+++def _adapter(layout: str) -> tuple[TeamsAdapter, _Connector]:+ adapter = TeamsAdapter(+ 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",+ )+ )+ connector = _Connector()+ adapter._connector = connector # type: ignore[assignment]+ adapter._graph = _Graph(layout) # type: ignore[assignment]+ adapter._default_service_url = "https://smba.example"+ adapter._channel_type[_CHANNEL] = "channel_public"+ return adapter, connector+++def _text(activity: dict[str, Any]) -> str:+ card = activity["attachments"][0]["content"]+ return "\n".join(str(block.get("text", "")) for block in card["body"])+++def _work(adapter: TeamsAdapter, **kw: Any) -> None:+ _run(+ adapter.apply_runtime_state(+ _CHANNEL, _AGENT, "working", mention_handle=None, thread_root_id=None, **kw+ )+ )+++def _idle(adapter: TeamsAdapter) -> None:+ _run(+ adapter.apply_runtime_state(+ _CHANNEL, _AGENT, "idle", mention_handle=None, thread_root_id=None+ )+ )+++# ── posts layout: nothing is ever deleted ─────────────────────────────────────+++def test_a_finished_turn_edits_the_status_rather_than_deleting_it() -> None:+ adapter, connector = _adapter("post")++ _work(adapter)+ _idle(adapter)++ assert connector.deletes == []+ assert [u["activity_id"] for u in connector.updates] == ["M1"]+ assert "Done" in _text(connector.updates[-1]["activity"])+++def test_the_marker_says_how_long_the_turn_took() -> None:+ adapter, connector = _adapter("post")++ _work(adapter)+ _idle(adapter)++ # Format is "✓ Done · 0s" — the duration matters more than the exact word.+ assert "·" in _text(connector.updates[-1]["activity"])+++def test_the_marker_drops_the_session_link() -> None:+ # The link is worth following while an agent is working. On the record of a+ # turn that is over it is clutter, and this line stays for good.+ adapter, connector = _adapter("post")++ _work(adapter, deeplink_url="https://switch.example/deeplink/session?x=1")+ _idle(adapter)++ assert "deeplink" not in _text(connector.updates[-1]["activity"])+++def test_an_operator_ping_is_resolved_by_editing_too() -> None:+ adapter, connector = _adapter("post")++ _work(adapter)+ _run(+ adapter.apply_runtime_state(+ _CHANNEL,+ _AGENT,+ "awaiting-input",+ mention_handle="ada",+ thread_root_id=None,+ )+ )+ _idle(adapter)++ assert connector.deletes == []+ assert {u["activity_id"] for u in connector.updates} == {"M1", "M2"}+++def test_the_status_does_not_move_to_follow_the_conversation() -> None:+ # A move is a repost plus a delete, and that delete scars once per move —+ # so the busier the channel, the more of them.+ adapter, connector = _adapter("post")++ _work(adapter)+ posted_before = list(connector.posted)++ _run(adapter.reposition_runtime_state(_CHANNEL, _AGENT, "post-9"))++ assert connector.posted == posted_before+ assert connector.deletes == []+ assert adapter._working_msg[(_CHANNEL, _AGENT)].message_ref == "M1"+++# ── chat layout: unchanged, the status disappears ─────────────────────────────+++def test_a_chat_channel_still_removes_the_status_when_the_turn_ends() -> None:+ adapter, connector = _adapter("chat")++ _work(adapter)+ _idle(adapter)++ assert connector.deletes == ["M1"]+ assert (_CHANNEL, _AGENT) not in adapter._working_msg+++def test_a_chat_channel_still_moves_the_status_to_follow_the_conversation() -> None:+ adapter, connector = _adapter("chat")++ _work(adapter)+ _run(adapter.reposition_runtime_state(_CHANNEL, _AGENT, "msg-9"))++ # Reposted first, then the original removed — never briefly absent.+ assert connector.deletes == ["M1"]+ assert adapter._working_msg[(_CHANNEL, _AGENT)].message_ref == "M2"+++def test_a_chat_channel_still_removes_an_operator_ping() -> None:+ adapter, connector = _adapter("chat")++ _work(adapter)+ _run(+ adapter.apply_runtime_state(+ _CHANNEL,+ _AGENT,+ "awaiting-input",+ mention_handle="ada",+ thread_root_id=None,+ )+ )+ _idle(adapter)++ assert set(connector.deletes) == {"M1", "M2"}diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_sender_names.py b/core/tests/switch_core/bridges/collaboration/test_teams_sender_names.pynew file mode 100644index 000000000..c07873fc8--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_sender_names.py@@ -0,0 +1,171 @@+"""CHOO-2067 — a Teams id is not a person's name.++Teams leaves the sender's name off some activities, 1:1 chats above all, and+the fallback was the raw id. `29:1AbCdEf…` then became a+person's name everywhere it was used: the auto-created room's title, their+Matrix account, and the text of every agent reply that addressed them. All+three were visible in one screenshot from switch-dev.++The second half is agreement. The directory used to hand back a whole user+principal name while inbound messages handed back a display name, so the same+human was filed under two names and whichever arrived first won.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+ _handle_for,+)++_AAD_ID = "29:1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class _Graph:+ def __init__(self, user: dict[str, Any] | None, *, fail: bool = False) -> None:+ self._user = user+ self._fail = fail+ self.lookups: list[str] = []++ async def get_user(self, *, user_id: str) -> dict[str, Any]:+ self.lookups.append(user_id)+ if self._fail:+ raise RuntimeError("Graph said no")+ return self._user or {}+++def _adapter(graph: _Graph | None = None) -> TeamsAdapter:+ adapter = TeamsAdapter(+ 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",+ )+ )+ if graph is not None:+ adapter._graph = graph # type: ignore[assignment]+ return adapter+++# ── the handle both paths agree on ───────────────────────────────────────────+++def test_the_handle_is_the_local_part_of_the_principal_name() -> None:+ # Not the whole UPN: `@[email protected]` does not survive being+ # written as a mention, and being addressable is the point of a handle.+ assert (+ _handle_for(+ {+ "id": "aad-1",+ "userPrincipalName": "[email protected]",+ "displayName": "Ada Lovelace",+ }+ )+ == "ada.lovelace"+ )+++def test_the_display_name_is_used_when_there_is_no_principal_name() -> None:+ assert _handle_for({"id": "aad-1", "displayName": "Ada Lovelace"}) == (+ "Ada Lovelace"+ )+++def test_the_id_is_the_last_resort_only() -> None:+ assert _handle_for({"id": "aad-1"}) == "aad-1"+++# ── resolving an inbound sender ──────────────────────────────────────────────+++def test_a_missing_name_is_looked_up_rather_than_replaced_by_the_id() -> None:+ graph = _Graph({"userPrincipalName": "[email protected]"})+ adapter = _adapter(graph)++ handle = _run(adapter._sender_handle(_AAD_ID, ""))++ assert handle == "ada.lovelace"+ assert graph.lookups == [_AAD_ID]+++def test_a_one_word_name_teams_offered_is_taken_without_asking_graph() -> None:+ graph = _Graph({"userPrincipalName": "[email protected]"})+ adapter = _adapter(graph)++ handle = _run(adapter._sender_handle(_AAD_ID, "ada"))++ assert handle == "ada"+ assert graph.lookups == []+++def test_a_display_name_with_a_space_is_traded_for_the_principal_name() -> None:+ # The offered name is what Teams puts on an activity, and it is nearly+ # always two words. `@Ada Lovelace` cannot be read back out of a message —+ # a mention ends at the space — so filing someone under it makes them+ # permanently untaggable. The directory has a one-word answer; ask for it.+ graph = _Graph({"userPrincipalName": "[email protected]"})+ adapter = _adapter(graph)++ handle = _run(adapter._sender_handle(_AAD_ID, "Ada Lovelace"))++ assert handle == "ada.lovelace"+ assert graph.lookups == [_AAD_ID]+++def test_a_display_name_stands_when_the_directory_cannot_improve_on_it() -> None:+ # Worse than a handle, better than an id: the room still shows a person's+ # name, and `_mark_mentions` can still tag them by matching the whole of it.+ graph = _Graph(None, fail=True)+ adapter = _adapter(graph)++ assert _run(adapter._sender_handle(_AAD_ID, "Ada Lovelace")) == "Ada Lovelace"+++def test_a_name_that_is_really_the_id_is_not_believed() -> None:+ # The shape of the old bug: Teams "offers" a name that is the id.+ graph = _Graph({"userPrincipalName": "[email protected]"})+ adapter = _adapter(graph)++ assert _run(adapter._sender_handle(_AAD_ID, _AAD_ID)) == "ada.lovelace"+++def test_the_lookup_happens_once_per_person() -> None:+ graph = _Graph({"userPrincipalName": "[email protected]"})+ adapter = _adapter(graph)++ _run(adapter._sender_handle(_AAD_ID, ""))+ _run(adapter._sender_handle(_AAD_ID, ""))++ assert graph.lookups == [_AAD_ID]+++def test_a_failed_lookup_falls_back_to_the_id_rather_than_dropping_the_message() -> (+ None+):+ # Degraded, and visibly so in the log — but a message from someone whose+ # name we cannot resolve still has to reach the room.+ graph = _Graph(None, fail=True)+ adapter = _adapter(graph)++ assert _run(adapter._sender_handle(_AAD_ID, "")) == _AAD_ID+++def test_no_graph_client_still_yields_something_usable() -> None:+ adapter = _adapter()++ assert _run(adapter._sender_handle(_AAD_ID, "")) == _AAD_IDdiff --git a/core/tests/switch_core/bridges/collaboration/test_teams_slash_commands.py b/core/tests/switch_core/bridges/collaboration/test_teams_slash_commands.pynew file mode 100644index 000000000..45c916fdd--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_slash_commands.py@@ -0,0 +1,180 @@+"""Teams' `/` picker sends a command without the slash it shows.++Picking `/help` from the picker switches the compose box to targeted-message+mode and inserts the *bare* name — Microsoft's own samples declare titles like+`my-reminders` and match them with `lower == "my-reminders"`. So a dispatcher+that keys on a prefix sees an ordinary message and does nothing.++`recipient.isTargeted` is what marks the message as aimed at this bot, and it+is the only thing that makes a bare word safe to read as a command.++The same change closes an older hole in the other direction: any message that+merely *began* with a slash was swallowed as a command, so pasting a path got+you "unknown command" instead of your message.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.models import InboundCommand, InboundMessage+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_CHANNEL = "19:[email protected]"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++def _adapter() -> tuple[TeamsAdapter, list[InboundCommand], list[InboundMessage]]:+ adapter = TeamsAdapter(+ 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",+ )+ )+ adapter._channel_type[_CHANNEL] = "channel_public"+ commands: list[InboundCommand] = []+ messages: list[InboundMessage] = []++ async def on_command(cmd: InboundCommand) -> None:+ commands.append(cmd)++ async def on_message(msg: InboundMessage) -> None:+ messages.append(msg)++ adapter._on_command = on_command # type: ignore[assignment]+ adapter._on_message = on_message # type: ignore[assignment]+ return adapter, commands, messages+++def _deliver(adapter: TeamsAdapter, text: str, *, targeted: bool = False) -> None:+ _run(+ adapter._deliver(+ channel_id=_CHANNEL,+ channel_type="channel_public",+ sender_id="aad-1",+ sender_name="ada",+ text=text,+ message_ref="m-1",+ root_id=None,+ channel_name="general",+ is_targeted=targeted,+ )+ )+++# ── the picker: a bare name on a targeted message ─────────────────────────────+++def test_a_bare_command_from_the_picker_is_dispatched() -> None:+ adapter, commands, messages = _adapter()++ _deliver(adapter, "list-agents", targeted=True)++ assert [c.command for c in commands] == ["list-agents"]+ assert messages == []+++def test_a_bare_command_keeps_its_arguments() -> None:+ adapter, commands, _ = _adapter()++ _deliver(adapter, "invite-agent @james", targeted=True)++ assert commands[0].command == "invite-agent"+ assert commands[0].args == "@james"+++def test_an_ordinary_targeted_message_is_not_a_command() -> None:+ # A user can put the compose box in targeted mode and just talk. Only a+ # name Switch knows is read as a command.+ adapter, commands, messages = _adapter()++ _deliver(adapter, "can you summarise the thread", targeted=True)++ assert commands == []+ assert [m.content for m in messages] == ["can you summarise the thread"]+++def test_a_bare_command_word_in_ordinary_chat_is_left_alone() -> None:+ # "help" said in a channel is somebody talking, not a command.+ adapter, commands, messages = _adapter()++ _deliver(adapter, "help", targeted=False)++ assert commands == []+ assert [m.content for m in messages] == ["help"]+++# ── prefixes still work, and no longer swallow everything ─────────────────────+++def test_a_slash_prefixed_command_still_works() -> None:+ adapter, commands, _ = _adapter()++ _deliver(adapter, "/list-agents")++ assert [c.command for c in commands] == ["list-agents"]+++def test_a_bang_prefixed_command_still_works() -> None:+ adapter, commands, _ = _adapter()++ _deliver(adapter, "!list-agents")++ assert [c.command for c in commands] == ["list-agents"]+++def test_a_pasted_path_is_a_message_not_an_unknown_command() -> None:+ # The reported hole: anything opening with a slash was taken as a command,+ # so this came back "unknown command" instead of reaching the agent.+ adapter, commands, messages = _adapter()++ _deliver(adapter, "/Users/ada/notes.md is the file")++ assert commands == []+ assert [m.content for m in messages] == ["/Users/ada/notes.md is the file"]+++def test_a_misspelled_bang_command_still_gets_the_unknown_command_reply() -> None:+ # `!` is Switch's own prefix and means nothing else, so a name it does not+ # know is a typo worth answering.+ adapter, commands, messages = _adapter()++ _deliver(adapter, "!list-agent")++ assert [c.command for c in commands] == ["list-agent"]+ assert messages == []+++def test_an_unknown_slash_word_is_a_message_not_a_command() -> None:+ # `/` is not Switch's prefix — it opens paths, dates and fractions — so an+ # unknown one is read as what it looks like.+ adapter, commands, messages = _adapter()++ _deliver(adapter, "/deploy the thing")++ assert commands == []+ assert [m.content for m in messages] == ["/deploy the thing"]+++def test_a_fraction_beginning_with_a_slash_is_left_alone() -> None:+ adapter, commands, messages = _adapter()++ _deliver(adapter, "/2 of the rows are wrong")++ assert commands == []+ assert len(messages) == 1diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.pynew file mode 100644index 000000000..130918879--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py@@ -0,0 +1,629 @@+"""Values Switch generates for a Teams bridge, and the save-time credential check."""++from __future__ import annotations++import asyncio+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import httpx+import pytest+from cryptography import x509+from cryptography.hazmat.primitives.serialization import load_pem_private_key+from pydantic import ValidationError++from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)+from switch_core.bridges.collaboration.models import (+ BridgeConnectionConfig,+ BridgeCredentialError,+)+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)+from switch_core.bridges.collaboration.teams.crypto import (+ generate_encryption_keypair,+ load_certificate_der_b64,+)+++def _raw_config(**overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "app_id": "app-id",+ "app_password": "app-password",+ "tenant_id": "tenant-id",+ "team_id": "team-id",+ "public_base_url": "https://teams.example.com",+ }+ base.update(overrides)+ return base+++# ── Generated values ─────────────────────────────────────────────────────────+++async def test_client_state_is_generated_and_unguessable() -> None:+ first = await TeamsAdapter.prepare_config(_raw_config())+ second = await TeamsAdapter.prepare_config(_raw_config())++ assert len(str(first["client_state"])) >= 32+ assert first["client_state"] != second["client_state"]+++async def test_client_state_supplied_by_caller_wins() -> None:+ prepared = await TeamsAdapter.prepare_config(_raw_config(client_state="mine"))++ assert prepared["client_state"] == "mine"+++def test_a_config_with_no_client_state_is_rejected_not_filled_in() -> None:+ """Silently minting one would break every live subscription's origin check."""+ with pytest.raises(ValidationError, match="client_state"):+ TeamsConnectionConfig.model_validate(_raw_config())+++async def test_prepare_config_generates_a_usable_encryption_trio() -> None:+ prepared = await TeamsAdapter.prepare_config(_raw_config())++ assert prepared["encryption_certificate_id"]+ # The certificate has to survive the exact round trip the subscription path+ # puts it through, and the private key has to parse.+ assert load_certificate_der_b64(str(prepared["encryption_public_certificate"]))+ assert load_pem_private_key(+ str(prepared["encryption_private_key"]).encode(), password=None+ )+++def test_generated_certificate_matches_its_private_key() -> None:+ cert_pem, key_pem = generate_encryption_keypair()++ cert = x509.load_pem_x509_certificate(cert_pem.encode())+ key = load_pem_private_key(key_pem.encode(), password=None)++ assert cert.public_key().public_numbers() == key.public_key().public_numbers()+++async def test_prepare_config_leaves_a_supplied_trio_alone() -> None:+ cert_pem, key_pem = generate_encryption_keypair()+ prepared = await TeamsAdapter.prepare_config(+ _raw_config(+ encryption_certificate_id="mine",+ encryption_public_certificate=cert_pem,+ encryption_private_key=key_pem,+ )+ )++ assert prepared["encryption_certificate_id"] == "mine"+ assert prepared["encryption_public_certificate"] == cert_pem+++async def test_prepare_config_does_not_mutate_its_argument() -> None:+ raw = _raw_config()+ await TeamsAdapter.prepare_config(raw)++ assert "encryption_private_key" not in raw+++async def test_validating_a_stored_config_never_regenerates_key_material() -> None:+ """The pair is minted once, at registration.++ Regenerating on every validate would mean a fresh certificate each restart+ while Graph kept encrypting to the previous one, and capture would fail to+ decrypt with nothing to point at.+ """+ stored = await TeamsAdapter.prepare_config(_raw_config())++ first = TeamsConnectionConfig.model_validate(stored)+ second = TeamsConnectionConfig.model_validate(stored)++ assert first.encryption_private_key == second.encryption_private_key+ assert first.client_state == second.client_state+++def test_a_config_with_no_encryption_material_stays_empty() -> None:+ """A bridge registered before generation existed keeps its degraded state.++ Filling it in here would silently pair it with a certificate Graph was never+ told about.+ """+ config = TeamsConnectionConfig.model_validate(_raw_config(client_state="s"))++ assert config.encryption_private_key is None+ assert config.encryption_public_certificate is None+++def test_half_an_encryption_trio_is_rejected() -> None:+ cert_pem, _ = generate_encryption_keypair()++ with pytest.raises(ValidationError, match="must be supplied together"):+ TeamsConnectionConfig.model_validate(+ _raw_config(client_state="s", encryption_public_certificate=cert_pem)+ )+++# ── Save-time credential verification ────────────────────────────────────────+++class _FakeHttp:+ """Stands in for httpx.AsyncClient as an async context manager."""++ def __init__(self, status: int, body: Any) -> None:+ self.status = status+ self.body = body+ self.calls: list[str] = []++ async def __aenter__(self) -> _FakeHttp:+ return self++ async def __aexit__(self, *exc: object) -> None:+ return None++ async def post(self, url: str, data: dict[str, str]) -> httpx.Response:+ self.calls.append(data["scope"])+ return httpx.Response(+ status_code=self.status,+ json=self.body,+ request=httpx.Request("POST", url),+ )+++def fake_http(monkeypatch: pytest.MonkeyPatch) -> Any:+ def _install(status: int, body: Any) -> _FakeHttp:+ client = _FakeHttp(status, body)+ monkeypatch.setattr(+ "switch_core.bridges.collaboration.teams.adapter.httpx.AsyncClient",+ lambda **_: client,+ )+ return client++ return _install+++async def test_verify_credentials_requests_both_scopes(fake_http: Any) -> None:+ client = fake_http(200, {"access_token": "tok", "expires_in": 3600})++ await TeamsAdapter.verify_credentials(+ await TeamsAdapter.prepare_config(_raw_config())+ )++ assert client.calls == [+ "https://graph.microsoft.com/.default",+ "https://api.botframework.com/.default",+ ]+++async def test_verify_credentials_surfaces_the_secret_id_mistake(+ fake_http: Any,+) -> None:+ """The failure that cost this the most time must reach the operator intact."""+ fake_http(+ 401,+ {+ "error": "invalid_client",+ "error_description": (+ "AADSTS7000215: Invalid client secret provided. Ensure the secret "+ "being sent in the request is the client secret value, not the "+ "client secret ID, for a secret added to app 'abc'. "+ "Trace ID: 1234 Correlation ID: 5678"+ ),+ },+ )++ with pytest.raises(BridgeCredentialError) as excinfo:+ await TeamsAdapter.verify_credentials(_raw_config(client_state="s"))++ message = str(excinfo.value)+ assert "not the client secret ID" in message+ # The trace and correlation ids are noise to the person reading a form error.+ assert "Trace ID" not in message+++async def test_verify_credentials_keeps_an_unparseable_body(fake_http: Any) -> None:+ fake_http(500, "upstream exploded")++ with pytest.raises(BridgeCredentialError, match="upstream exploded"):+ await TeamsAdapter.verify_credentials(_raw_config(client_state="s"))+++async def test_verify_credentials_reports_an_unreachable_microsoft(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _Unreachable(_FakeHttp):+ async def post(self, url: str, data: dict[str, str]) -> httpx.Response:+ raise httpx.ConnectError("no route to host")++ monkeypatch.setattr(+ "switch_core.bridges.collaboration.teams.adapter.httpx.AsyncClient",+ lambda **_: _Unreachable(200, {}),+ )++ with pytest.raises(BridgeCredentialError, match="Could not reach Microsoft"):+ await TeamsAdapter.verify_credentials(_raw_config(client_state="s"))+++# ── register() wiring ────────────────────────────────────────────────────────+++class _RecordingAdapter(CollaborationAdapter):+ """Records the order register() drives the two hooks in."""++ events: list[str] = []+ seen_config: dict[str, object] = {}+ fail_verification = False++ @classmethod+ async def prepare_config(+ cls, connection_config: dict[str, object]+ ) -> dict[str, object]:+ cls.events.append("prepare")+ return {**connection_config, "generated": "yes"}++ @classmethod+ async def verify_credentials(cls, connection_config: dict[str, object]) -> None:+ cls.events.append("verify")+ cls.seen_config = dict(connection_config)+ if cls.fail_verification:+ raise BridgeCredentialError("platform said no")++ async def start(self, *args: Any, **kwargs: Any) -> None: # pragma: no cover+ raise AssertionError("start must not run when verification fails")++ async def stop(self) -> None: # pragma: no cover+ return None++ async def send_message(self, *args: Any, **kwargs: Any) -> str | None:+ return None++ async def create_channel(self, *args: Any, **kwargs: Any) -> str:+ return "c"++ async def get_channel_type(self, *args: Any, **kwargs: Any) -> Any:+ return None++ async def add_agents_to_channel(self, *args: Any, **kwargs: Any) -> None:+ return None++ async def add_users_to_channel(self, *args: Any, **kwargs: Any) -> None:+ return None++ async def create_agent_identity(self, *args: Any, **kwargs: Any) -> None:+ return None++ async def remove_agent_identity(self, *args: Any, **kwargs: Any) -> None:+ return None++ async def get_channel_agent_names(self, *args: Any, **kwargs: Any) -> list[str]:+ return []+++class _RecordingConfig(BridgeConnectionConfig):+ app_id: str+ generated: str+++def _lifecycle() -> CollaborationBridgeLifecycleService:+ service = CollaborationBridgeLifecycleService(+ bridge_store=MagicMock(),+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=MagicMock(),+ agent_store=MagicMock(),+ client_store=MagicMock(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ matrix_admin=MagicMock(),+ session_factory=MagicMock(),+ config=MagicMock(),+ )+ service.register_adapter("recording", _RecordingAdapter, _RecordingConfig)+ return service+++async def test_register_prepares_then_verifies_before_touching_anything() -> None:+ """Verification has to precede the Matrix identity and the DB write.++ Otherwise a bridge that was never viable still leaves an orphan client+ behind, and the row has to be cleaned up by hand.+ """+ _RecordingAdapter.events = []+ _RecordingAdapter.fail_verification = True+ service = _lifecycle()++ with pytest.raises(BridgeCredentialError, match="platform said no"):+ await service.register(+ bridge_type="recording",+ display_name="Recording",+ connection_config={"app_id": "a"},+ channel_creation_enabled=True,+ )++ assert _RecordingAdapter.events == ["prepare", "verify"]+ # No Matrix identity was minted for a bridge that cannot work.+ service._client_lifecycle.create_client.assert_not_called() # type: ignore[attr-defined]+++async def test_register_verifies_the_prepared_config_not_the_raw_request() -> None:+ """A generated credential must be the one that gets checked."""+ _RecordingAdapter.events = []+ _RecordingAdapter.fail_verification = True+ service = _lifecycle()++ with pytest.raises(BridgeCredentialError):+ await service.register(+ bridge_type="recording",+ display_name="Recording",+ connection_config={"app_id": "a"},+ channel_creation_enabled=True,+ )++ assert _RecordingAdapter.seen_config["generated"] == "yes"+++# ── Refusing a second Teams bridge ───────────────────────────────────────────+++async def test_exclusive_resource_is_the_listener_port() -> None:+ assert TeamsAdapter.exclusive_resource(_raw_config(client_state="s")) == "tcp/3978"+ assert (+ TeamsAdapter.exclusive_resource(_raw_config(client_state="s", listen_port=3979))+ == "tcp/3979"+ )+++def test_outbound_only_adapters_claim_nothing() -> None:+ """Slack, Discord and Mattermost dial out; any number can coexist."""+ assert CollaborationAdapter.exclusive_resource({}) is None+++def _service_with_existing(existing: list[Any]) -> CollaborationBridgeLifecycleService:+ session = MagicMock()+ session.__aenter__ = AsyncMock(return_value=session)+ session.__aexit__ = AsyncMock(return_value=None)+ store = MagicMock()+ store.get_all = AsyncMock(return_value=existing)+ service = CollaborationBridgeLifecycleService(+ bridge_store=store,+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=MagicMock(),+ agent_store=MagicMock(),+ client_store=MagicMock(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ matrix_admin=MagicMock(),+ session_factory=MagicMock(return_value=session),+ config=MagicMock(),+ )+ service.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)+ return service+++async def _stored_bridge(**overrides: Any) -> Any:+ bridge = MagicMock()+ bridge.id = overrides.pop("id", "existing-id")+ bridge.type = overrides.pop("type", "teams")+ bridge.display_name = overrides.pop("display_name", "Contoso Teams")+ bridge.connection_config = await TeamsAdapter.prepare_config(+ _raw_config(**overrides)+ )+ return bridge+++async def test_second_teams_bridge_on_the_same_port_is_refused() -> None:+ """The failure this replaces was a bind error in a background task."""+ service = _service_with_existing([await _stored_bridge()])++ with pytest.raises(ValueError) as excinfo:+ await service.register(+ bridge_type="teams",+ display_name="Second Teams",+ connection_config=_raw_config(),+ channel_creation_enabled=True,+ )++ message = str(excinfo.value)+ assert "Contoso Teams" in message+ assert "tcp/3978" in message+++async def test_a_second_bridge_on_its_own_port_is_allowed_through(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Refuse the collision, not the configuration.++ Getting past this check is not the same as working — the chart publishes one+ Teams port — but that is the operator's deliberate choice to make.+ """+ service = _service_with_existing([await _stored_bridge()])+ monkeypatch.setattr(+ TeamsAdapter, "verify_credentials", AsyncMock(return_value=None)+ )+ service._client_lifecycle.create_client = AsyncMock( # type: ignore[attr-defined]+ side_effect=RuntimeError("stop here — past the conflict check")+ )++ with pytest.raises(RuntimeError, match="stop here"):+ await service.register(+ bridge_type="teams",+ display_name="Second Teams",+ connection_config=_raw_config(listen_port=3979),+ channel_creation_enabled=True,+ )+++async def test_a_non_teams_bridge_is_not_blocked_by_a_teams_one(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ slack = await _stored_bridge(id="slack-id", type="slack")+ slack.connection_config = {"bot_token": "x"}+ service = _service_with_existing([slack])+ monkeypatch.setattr(+ TeamsAdapter, "verify_credentials", AsyncMock(return_value=None)+ )+ service._client_lifecycle.create_client = AsyncMock( # type: ignore[attr-defined]+ side_effect=RuntimeError("stop here — past the conflict check")+ )++ with pytest.raises(RuntimeError, match="stop here"):+ await service.register(+ bridge_type="teams",+ display_name="Teams",+ connection_config=_raw_config(),+ channel_creation_enabled=True,+ )+++# ── Regressions found in review ──────────────────────────────────────────────+++async def test_a_200_with_no_access_token_is_a_credential_error(+ fake_http: Any,+) -> None:+ """A proxy in front of AAD answering 200 with the wrong body.++ Left to raise on its own this is a KeyError, which no caller catches, so a+ save-time check designed to produce a clean 400 produced a 500 instead.+ """+ fake_http(200, {"expires_in": 3600})++ with pytest.raises(BridgeCredentialError, match="unusable body"):+ await TeamsAdapter.verify_credentials(_raw_config(client_state="s"))+++async def test_a_200_that_is_not_json_is_a_credential_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _Html(_FakeHttp):+ async def post(self, url: str, data: dict[str, str]) -> httpx.Response:+ return httpx.Response(+ status_code=200,+ text="<html>blocked by policy</html>",+ request=httpx.Request("POST", url),+ )++ monkeypatch.setattr(+ "switch_core.bridges.collaboration.teams.adapter.httpx.AsyncClient",+ lambda **_: _Html(200, {}),+ )++ with pytest.raises(BridgeCredentialError, match="unusable body"):+ await TeamsAdapter.verify_credentials(_raw_config(client_state="s"))+++async def test_concurrent_registration_cannot_take_the_same_port_twice(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Two bridges registered at once must not both pass the exclusivity check.++ The check reads the stored bridges and the winner is not written until+ several awaits later, so without serialisation both callers saw a free port+ and both took it — reproducing the collision the check exists to refuse.+ """+ stored: list[Any] = []++ session = MagicMock()+ session.__aenter__ = AsyncMock(return_value=session)+ session.__aexit__ = AsyncMock(return_value=None)+ session.commit = AsyncMock(return_value=None)+ store = MagicMock()+ store.get_all = AsyncMock(side_effect=lambda _s: list(stored))++ async def _create(_s: Any, bridge: Any) -> Any:+ # The real store commits well after the conflict check has run.+ await asyncio.sleep(0)+ stored.append(bridge)+ return bridge++ store.create = AsyncMock(side_effect=_create)++ service = CollaborationBridgeLifecycleService(+ bridge_store=store,+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=MagicMock(),+ agent_store=MagicMock(),+ client_store=MagicMock(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ matrix_admin=MagicMock(),+ session_factory=MagicMock(return_value=session),+ config=MagicMock(),+ )+ service.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)+ monkeypatch.setattr(+ TeamsAdapter, "verify_credentials", AsyncMock(return_value=None)+ )++ client = MagicMock()+ client.id = "client-id"++ async def _create_client(**_: Any) -> Any:+ await asyncio.sleep(0)+ return client++ service._client_lifecycle.create_client = AsyncMock(side_effect=_create_client) # type: ignore[attr-defined]+ service.start = AsyncMock(return_value=None) # type: ignore[method-assign]++ results = await asyncio.gather(+ service.register(+ bridge_type="teams",+ display_name="Teams A",+ connection_config=_raw_config(),+ channel_creation_enabled=True,+ ),+ service.register(+ bridge_type="teams",+ display_name="Teams B",+ connection_config=_raw_config(),+ channel_creation_enabled=True,+ ),+ return_exceptions=True,+ )++ refused = [r for r in results if isinstance(r, ValueError)]+ assert len(refused) == 1, f"expected exactly one refusal, got {results}"+ assert "tcp/3978" in str(refused[0])+ assert len(stored) == 1+++async def test_start_refuses_a_second_bridge_already_holding_the_port() -> None:+ """The startup guard, which covers rows that predate the registration check.++ Registration cannot create a colliding pair any more, but two already exist+ on some instances, and `start_all` walks straight into them.+ """+ session = MagicMock()+ session.__aenter__ = AsyncMock(return_value=session)+ session.__aexit__ = AsyncMock(return_value=None)++ stored = await _stored_bridge(id="second-id")+ store = MagicMock()+ store.get = AsyncMock(return_value=stored)++ service = CollaborationBridgeLifecycleService(+ bridge_store=store,+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=MagicMock(),+ agent_store=MagicMock(),+ client_store=MagicMock(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ matrix_admin=MagicMock(),+ session_factory=MagicMock(return_value=session),+ config=MagicMock(),+ )+ service.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)+ # A bridge already running and holding the port.+ service._held_resources["first-id"] = "tcp/3978"++ with pytest.raises(ValueError) as excinfo:+ await service.start("second-id")++ message = str(excinfo.value)+ assert "tcp/3978" in message+ assert "first-id" in messagediff --git a/core/tests/switch_core/clients/test_system_message_never_addresses.py b/core/tests/switch_core/clients/test_system_message_never_addresses.pynew file mode 100644index 000000000..ec6a4e3ac--- /dev/null+++ b/core/tests/switch_core/clients/test_system_message_never_addresses.py@@ -0,0 +1,106 @@+"""Switch's own notices are output, not a request for a reply.++Seen on a Teams 1:1 chat: someone ran `/list-agents`, the bridge answered with+the room roster, and the agent then started a session to respond to that+roster — "Nothing to action there…". It reads as the slash command waking the+agent, and it is not. A direct room addresses its agent with *every* message,+and nothing exempted the admin client's own output.++The second way in is not specific to direct rooms: a notice that lists the+agents present writes each one as `@name`, which tags every one of them.++`ADMIN_MARKER` already means "generated by Switch, do not react to it" — the+admin client honours it. These pin that the agent client does too, while the+message still arrives as ordinary unaddressed context.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from switch_core.clients.admin_messages import ADMIN_MARKER, admin_extra_content+from switch_core.clients.agent_client import AgentClient+from switch_core.clients.room_meta import RoomMeta+++def _event(body: str, *, admin: bool = False) -> SimpleNamespace:+ content: dict = {"body": body}+ if admin:+ content.update(admin_extra_content(None))+ return SimpleNamespace(+ body=body,+ formatted_body=None,+ sender="@switch-admin:switch.local",+ source={"content": content},+ )+++def _meta(channel_type: str) -> RoomMeta:+ return RoomMeta(room_id="room-1", name="a room", channel_type=channel_type)+++def _client(name: str = "flintai-sdk.ts") -> SimpleNamespace:+ client = SimpleNamespace(+ agent=SimpleNamespace(name=name),+ matrix_user_id=f"@switch-agent-{name}:switch.local",+ )++ async def _no(*_a: object, **_k: object) -> bool:+ return False++ client._is_mentioned = lambda event: AgentClient._is_mentioned(client, event)+ client._is_mentioned_via_alias = _no+ client._is_mentioned_via_role = _no+ return client+++async def _addressed(client: SimpleNamespace, event: object, meta: RoomMeta) -> bool:+ return await AgentClient._compute_addressed(client, event, meta)+++async def test_a_command_result_in_a_direct_room_does_not_address_the_agent() -> None:+ # The reported case: /list-agents in a 1:1 chat, answered by the bridge,+ # and the agent spinning up a session to reply to the answer.+ roster = _event("**Agents in this room:**\n- flintai-sdk.ts", admin=True)++ assert await _addressed(_client(), roster, _meta("direct")) is False+++async def test_a_person_in_a_direct_room_still_addresses_the_agent() -> None:+ # The rule that makes a DM feel like a DM has to survive the fix.+ assert await _addressed(_client(), _event("hello?"), _meta("direct")) is True+++async def test_a_notice_naming_the_agents_present_does_not_tag_them() -> None:+ # In a channel, the self-mention guidance lists "• @name — description" for+ # every agent in the room. Unmarked, that woke all of them.+ notice = _event(+ "👋 You tagged me directly…\n• @flintai-sdk.ts — Claude Code",+ admin=True,+ )++ assert await _addressed(_client(), notice, _meta("channel_public")) is False+++async def test_a_person_tagging_the_agent_in_a_channel_still_addresses_it() -> None:+ tagged = _event("@flintai-sdk.ts can you look at this")++ assert await _addressed(_client(), tagged, _meta("channel_public")) is True+++async def test_the_marker_alone_is_enough_whatever_type_it_carries() -> None:+ # The type is for per-platform rendering; presence is what means "system".+ from switch_core.clients.admin_messages import AdminMessageType++ event = _event("Added flintai-sdk.ts to this room.")+ event.source["content"].update(admin_extra_content(AdminMessageType.COMMAND_RESULT))+ assert ADMIN_MARKER in event.source["content"]++ assert await _addressed(_client(), event, _meta("direct")) is Falsediff --git a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.pyindex b54b8fa65..3804ddfdf 100644--- a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py+++ b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport uuidimport pytest@@ -150,3 +151,147 @@ async def test_set_default_unknown_bridge_raises(async with session_factory() as session:with pytest.raises(ValueError):await store.set_default(session, "does-not-exist")+++async def test_set_channel_team_merges_rather_than_replaces(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Learning one channel's team must not forget the others.++ The map is a single JSONB value, so a write that assigned instead of+ merging would drop every channel learned before it — and each loss costs+ Teams channel capture until the bot is mentioned in that channel again.+ """+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)++ await store.set_channel_team(session, bridge_id, "19:[email protected]", "team-1")+ await store.set_channel_team(session, bridge_id, "19:[email protected]", "team-2")+ await session.commit()++ async with session_factory() as session:+ bridge = await store.get(session, bridge_id)+ assert bridge is not None+ assert bridge.connection_config["channel_teams"] == {+ "19:[email protected]": "team-1",+ "19:[email protected]": "team-2",+ }+++async def test_set_channel_team_updates_a_channel_that_moved(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)++ await store.set_channel_team(session, bridge_id, "19:[email protected]", "team-1")+ await store.set_channel_team(session, bridge_id, "19:[email protected]", "team-2")+ await session.commit()++ async with session_factory() as session:+ bridge = await store.get(session, bridge_id)+ assert bridge is not None+ assert bridge.connection_config["channel_teams"] == {+ "19:[email protected]": "team-2"+ }+++async def test_set_channel_team_leaves_the_rest_of_the_config_alone(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)+ await store.set_service_url(session, bridge_id, "https://smba.example")++ await store.set_channel_team(session, bridge_id, "19:[email protected]", "team-1")+ await session.commit()++ async with session_factory() as session:+ bridge = await store.get(session, bridge_id)+ assert bridge is not None+ assert bridge.connection_config["service_url"] == "https://smba.example"+ assert bridge.connection_config["channel_teams"]+++async def test_set_channel_team_unknown_bridge_raises(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ with pytest.raises(ValueError):+ await store.set_channel_team(session, "does-not-exist", "19:a", "team-1")+++async def test_concurrent_channel_team_writes_do_not_lose_each_other(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The Teams bridge persists a channel's team the first time it sees that+ channel, each from its own session — so a burst of new channels is a burst+ of concurrent read-modify-writes on one JSONB value. Unlocked, the last+ write won and the rest vanished; measured at eight concurrent writes+ landing two. A dropped entry is the exact state that makes Graph refuse+ that channel's subscription after the next restart.+ """+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)+ await session.commit()++ async def write(index: int) -> None:+ # Mirrors lifecycle_service._persist_channel_team: its own session.+ async with session_factory() as session:+ await store.set_channel_team(+ session, bridge_id, f"19:c{index}@thread.tacv2", f"team-{index}"+ )+ await session.commit()++ await asyncio.gather(*(write(i) for i in range(8)))++ async with session_factory() as session:+ bridge = await store.get(session, bridge_id)+ assert bridge is not None+ assert bridge.connection_config["channel_teams"] == {+ f"19:c{i}@thread.tacv2": f"team-{i}" for i in range(8)+ }+++async def test_a_service_url_write_does_not_clobber_learned_channel_teams(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ # The two writers share one JSONB column, so they race each other as well+ # as themselves.+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)+ await session.commit()++ async def set_team() -> None:+ async with session_factory() as session:+ await store.set_channel_team(+ session, bridge_id, "19:[email protected]", "team-1"+ )+ await session.commit()++ async def set_url() -> None:+ async with session_factory() as session:+ await store.set_service_url(session, bridge_id, "https://smba.example")+ await session.commit()++ await asyncio.gather(set_team(), set_url())++ async with session_factory() as session:+ bridge = await store.get(session, bridge_id)+ assert bridge is not None+ assert bridge.connection_config["service_url"] == "https://smba.example"+ assert bridge.connection_config["channel_teams"] == {+ "19:[email protected]": "team-1"+ }diff --git a/core/tests/switch_core/gateway/test_room_create_platform_error.py b/core/tests/switch_core/gateway/test_room_create_platform_error.pynew file mode 100644index 000000000..2f12c9064--- /dev/null+++ b/core/tests/switch_core/gateway/test_room_create_platform_error.py@@ -0,0 +1,101 @@+"""CHOO-2067 — a platform's refusal to provision a channel must reach the+operator who asked for the room.++Adding a room to a Microsoft Teams bridge whose app registration had no+consented Graph permissions returned a bare `500`. Graph had answered with the+exact permission it wanted, and that sentence went to the log while the person+clicking the button got nothing to act on. The route coroutine is exercised+directly; the failure happens before any store is touched, so no database is+needed.+"""++from __future__ import annotations++from typing import Any++import pytest+from fastapi import HTTPException++from switch_core.bridges.collaboration.models import (+ BridgeOperationError,+ ChannelCreationUnsupported,+)+from switch_core.gateway.rooms import create_room+from switch_core.gateway.schemas import RoomCreateRequest++_GRAPH_REFUSAL = (+ "create channel 'Switch Test Room' in team team-1 failed (403): "+ "Forbidden: Missing role permissions on the request. API requires one of "+ "'Channel.Create, Teamwork.Migrate.All'."+)+++class _RaisingRoomService:+ def __init__(self, exc: Exception) -> None:+ self._exc = exc++ async def create_room(self, config: Any) -> Any:+ raise self._exc+++def _request() -> RoomCreateRequest:+ return RoomCreateRequest(+ name="Switch Test Room",+ description="d",+ channel_type="channel_public",+ bridge_id="bridge-1",+ agent_names=["agent.one"],+ )+++async def _call(exc: Exception) -> HTTPException:+ """Invoke the route with a room service that fails, and return the raised+ HTTPException. Every dependency after the failure point is unused."""+ with pytest.raises(HTTPException) as excinfo:+ await create_room(+ req=_request(),+ session=None, # type: ignore[arg-type]+ room_service=_RaisingRoomService(exc), # type: ignore[arg-type]+ room_store=None, # type: ignore[arg-type]+ bridge_store=None, # type: ignore[arg-type]+ external_user_store=None, # type: ignore[arg-type]+ protocol=None, # type: ignore[arg-type]+ user=type("U", (), {"id": "u1"})(), # type: ignore[arg-type]+ )+ return excinfo.value+++async def test_platform_refusal_is_502_carrying_the_platforms_words() -> None:+ exc = await _call(BridgeOperationError(_GRAPH_REFUSAL))++ assert exc.status_code == 502+ # The actionable half — which permission is missing — survives to the caller.+ assert "Channel.Create" in exc.detail+ assert exc.detail == _GRAPH_REFUSAL+++async def test_switch_declining_is_still_a_400() -> None:+ # ChannelCreationUnsupported is Switch refusing before it calls out, which+ # is a fault in the request rather than upstream. It must not be swept into+ # the new 502 branch.+ exc = await _call(ChannelCreationUnsupported("channel creation is turned off"))++ assert exc.status_code == 400+ assert "turned off" in exc.detail+++async def test_an_ordinary_bug_is_not_dressed_up_as_a_platform_refusal() -> None:+ # The 502 claims the platform answered. A KeyError in our own code did not,+ # so it must keep propagating as an unhandled error rather than being+ # reported to the operator as something for them to fix in Azure.+ with pytest.raises(KeyError):+ await create_room(+ req=_request(),+ session=None, # type: ignore[arg-type]+ room_service=_RaisingRoomService(KeyError("boom")), # type: ignore[arg-type]+ room_store=None, # type: ignore[arg-type]+ bridge_store=None, # type: ignore[arg-type]+ external_user_store=None, # type: ignore[arg-type]+ protocol=None, # type: ignore[arg-type]+ user=type("U", (), {"id": "u1"})(), # type: ignore[arg-type]+ )diff --git a/core/tests/switch_core/test_room_service_add_users.py b/core/tests/switch_core/test_room_service_add_users.pynew file mode 100644index 000000000..7c7fc4790--- /dev/null+++ b/core/tests/switch_core/test_room_service_add_users.py@@ -0,0 +1,139 @@+"""CHOO-2067 — a person who cannot be added must not take the room with them.++Adding a room to a Teams bridge answered `500` when any one member could not+be added to the channel: the Teams adapter raised where Slack, Mattermost and+Discord log and continue, and it runs inside room creation, so the request died+with a half-provisioned room behind it. The opposite failure is just as bad —+dropping people quietly leaves a room that lacks the people it was asked for+and says nothing.+"""++from __future__ import annotations++from typing import Any++from switch_core.room_service import RoomService+++class _FakeAdapter:+ def __init__(self, *, failing_ids: list[str]) -> None:+ self._failing_ids = failing_ids+ self.calls: list[tuple[list[str], list[str]]] = []++ async def add_users_to_channel(+ self,+ channel_id: str,+ user_names: list[str],+ user_external_ids: list[str],+ ) -> list[str]:+ self.calls.append((list(user_names), list(user_external_ids)))+ return [i for i in user_external_ids if i in self._failing_ids]+++class _FakeBridgeCore:+ def __init__(self, *, known: dict[str, str], failing_ids: list[str]) -> None:+ self._known = known+ self.adapter = _FakeAdapter(failing_ids=failing_ids)++ async def resolve_external_user_id_map(+ self, user_names: list[str]+ ) -> dict[str, str]:+ return {n: self._known[n] for n in user_names if n in self._known}+++async def _add(+ *, known: dict[str, str], failing_ids: list[str], asked_for: list[str]+) -> tuple[list[dict[str, Any]], _FakeBridgeCore]:+ bridge = _FakeBridgeCore(known=known, failing_ids=failing_ids)+ failures = await RoomService._add_users_to_channel(+ bridge, # type: ignore[arg-type]+ "chan-1",+ asked_for,+ )+ return failures, bridge+++async def test_everyone_added_reports_nothing() -> None:+ failures, bridge = await _add(+ known={"alice": "ext-a", "bob": "ext-b"},+ failing_ids=[],+ asked_for=["alice", "bob"],+ )++ assert failures == []+ assert bridge.adapter.calls == [(["alice", "bob"], ["ext-a", "ext-b"])]+++async def test_a_name_the_bridge_does_not_know_is_reported_by_name() -> None:+ failures, bridge = await _add(+ known={"alice": "ext-a"},+ failing_ids=[],+ asked_for=["alice", "ghost"],+ )++ assert failures == [+ {+ "kind": "user",+ "id": "ghost",+ "error": "no account with this name is known on the bridge",+ }+ ]+ # Only the resolvable person is offered to the adapter — and the two lists+ # stay aligned, which is the bug that used to lurk here: the caller's full+ # name list went out beside a shorter list of ids, so an adapter that zipped+ # them attributed a failure to the wrong person.+ assert bridge.adapter.calls == [(["alice"], ["ext-a"])]+++async def test_a_platform_refusal_is_reported_by_name_not_by_id() -> None:+ # The operator typed a name; an opaque platform id means nothing to them.+ failures, _ = await _add(+ known={"alice": "ext-a", "bob": "ext-b"},+ failing_ids=["ext-b"],+ asked_for=["alice", "bob"],+ )++ assert failures == [+ {+ "kind": "user",+ "id": "bob",+ "error": "the platform would not add them to the channel",+ }+ ]+++async def test_both_kinds_of_miss_are_reported_together() -> None:+ failures, _ = await _add(+ known={"alice": "ext-a", "bob": "ext-b"},+ failing_ids=["ext-b"],+ asked_for=["alice", "bob", "ghost"],+ )++ assert [f["id"] for f in failures] == ["ghost", "bob"]+++async def test_an_unmappable_failure_id_still_gets_reported() -> None:+ # An adapter returning something we did not hand it is a bug, but losing+ # the failure entirely would be worse than reporting it raw.+ bridge = _FakeBridgeCore(known={"alice": "ext-a"}, failing_ids=[])++ async def _add_users(+ channel_id: str, user_names: list[str], user_external_ids: list[str]+ ) -> list[str]:+ return ["ext-surprise"]++ bridge.adapter.add_users_to_channel = _add_users # type: ignore[assignment]++ failures = await RoomService._add_users_to_channel(+ bridge, # type: ignore[arg-type]+ "chan-1",+ ["alice"],+ )++ assert failures == [+ {+ "kind": "user",+ "id": "ext-surprise",+ "error": "the platform would not add them to the channel",+ }+ ]diff --git a/core/tests/switch_core/test_room_service_change_bridge.py b/core/tests/switch_core/test_room_service_change_bridge.pyindex 86e1eb79e..8424d9178 100644--- a/core/tests/switch_core/test_room_service_change_bridge.py+++ b/core/tests/switch_core/test_room_service_change_bridge.py@@ -81,6 +81,11 @@ class _FakeAdapter:) -> None:self._events.append(("add_agents", channel_id, list(agent_names)))+ async def ensure_channel_subscriptions(+ self, channels: list[tuple[str, str]]+ ) -> None:+ self._events.append(("ensure_capture", list(channels)))+class _FakeBridgeCore:def __init__(@@ -316,6 +321,39 @@ class TestChangeBridge:assert room_store.update_bridge_calls[0]["external_channel_id"] == "chan-reused"assert ("add_room_mapping", "room-1", "chan-reused") in eventsassert ("add_agents", "chan-reused", ["agent.one"]) in events+ # Provisioning a channel subscribes to it on the way past; binding one+ # that already exists has nothing to piggy-back on, so capture must be+ # established explicitly or the room only ever hears @mentions.+ assert ("ensure_capture", [("chan-reused", "channel_public")]) in events++ async def test_capture_is_established_for_a_freshly_created_channel(self) -> None:+ # Idempotent by design: the adapter skips a channel it is already+ # subscribed to, so asking again after provisioning costs nothing and+ # removes the need for either path to know what the other did.+ events: list[Any] = []+ room = SimpleNamespace(+ id="room-1",+ name="Work",+ description="d",+ matrix_room_id="!mx:switch.local",+ bridge_id=None,+ channel_type=None,+ external_channel_id=None,+ )+ new_bridge = _FakeBridgeCore(+ events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ )+ svc, _ = _build_service(+ room=room,+ agent_ids=[],+ agent_names={},+ bridges={"bridge-new": new_bridge},+ events=events,+ )++ await svc.change_bridge("room-1", bridge_id="bridge-new")++ assert ("ensure_capture", [("chan-new", "channel_public")]) in eventsasync def test_raises_when_target_bridge_not_running(self) -> None:events: list[Any] = []@@ -395,3 +433,68 @@ class TestChangeBridge:assert room_store.update_bridge_calls == []assert events == []+++class TestLinkBridgeToRoom:+ """Binding a bridge to an existing internal room.++ The other way a room ends up pointing at a channel nobody subscribed to.+ """++ def _room(self) -> Any:+ return SimpleNamespace(+ id="room-1",+ name="Work",+ description="d",+ matrix_room_id="!mx:switch.local",+ bridge_id=None,+ channel_type=None,+ external_channel_id=None,+ )++ async def test_binding_an_existing_channel_establishes_capture(self) -> None:+ events: list[Any] = []+ bridge = _FakeBridgeCore(events, matrix_user_id="@bot:switch.local")+ svc, room_store = _build_service(+ room=self._room(),+ agent_ids=[],+ agent_names={},+ bridges={"bridge-1": bridge},+ events=events,+ )++ await svc.link_bridge_to_room(+ "room-1",+ "bridge-1",+ "channel_private",+ external_channel_id="chan-existing",+ )++ assert not any(e[0] == "create_channel" for e in events)+ assert room_store.update_bridge_calls[0]["external_channel_id"] == (+ "chan-existing"+ )+ assert ("ensure_capture", [("chan-existing", "channel_private")]) in events++ async def test_capture_follows_the_mapping(self) -> None:+ # Capture must not be established before the room↔channel mapping is+ # registered: a notification arriving in the gap has nowhere to land.+ events: list[Any] = []+ bridge = _FakeBridgeCore(events, matrix_user_id="@bot:switch.local")+ svc, _ = _build_service(+ room=self._room(),+ agent_ids=[],+ agent_names={},+ bridges={"bridge-1": bridge},+ events=events,+ )++ await svc.link_bridge_to_room(+ "room-1", "bridge-1", "channel_public", external_channel_id="chan-existing"+ )++ map_idx = events.index(("add_room_mapping", "room-1", "chan-existing"))+ capture_idx = events.index(+ ("ensure_capture", [("chan-existing", "channel_public")])+ )+ assert map_idx < capture_idxdiff --git a/deploy/remote/helm/switch/README.md b/deploy/remote/helm/switch/README.mdnew file mode 100644index 000000000..985933425--- /dev/null+++ b/deploy/remote/helm/switch/README.md@@ -0,0 +1,169 @@+# Switch Helm chart++Deploys Switch into a Kubernetes cluster: switch-core (the API and all bridge+adapters), the gateway dashboard, a Tuwunel Matrix homeserver, Postgres, and+optionally Mattermost.++```bash+helm install switch oci://ghcr.io/<owner>/charts/switch --version <version> -f my-values.yaml+```++Everything is configured through `values.yaml`, which is commented per value —+read it as the reference. This page covers the two things that are not obvious+from a values file: **what has to be reachable from where**, and the operational+constraints you cannot configure away.++For backup and restore, see [`BACKUP.md`](BACKUP.md).++---++## What has to be reachable, and from where++Switch has three network surfaces, and they have genuinely different exposure+requirements. Getting this wrong is the most common deployment problem, because+two of the three fail *silently* — the pods are healthy and the dashboard works.++| Surface | Port | Who must reach it | Consequence if unreachable |+| --- | --- | --- | --- |+| Gateway dashboard | 3000 | Your operators | You cannot administer Switch |+| Agent API + MCP | 8000 | Agents, wherever they run | Remote agents cannot connect; local ones are fine |+| Teams bridge listener | 3978 | **Microsoft, from the public internet** | The Teams bridge half-works, silently |++**Only the Teams listener requires public internet exposure**, and only if you+run a Microsoft Teams bridge. Every other collaboration bridge — Slack,+Mattermost, Discord, Telegram — connects *outbound* over a WebSocket and needs+no ingress at all.++If your agents all run inside the cluster or on operator machines that can reach+it privately, nothing here needs to be on the public internet.++### The agent API++Port 8000 serves the agent bridge, MCP, and OAuth/MCP discovery. Expose it as+widely as your agents live and no wider — a VPN or private load balancer is+fine, and is the better default. `ingress.agentApiPaths` lists the prefixes+routed there.++Note it is Bearer-token authenticated, not unauthenticated, but it is still the+control plane: agents post messages and read room context through it.++### The Teams bridge listener++Unlike every other bridge, Teams pushes to you. Microsoft calls two paths —+`/api/messages` (Bot Framework activities) and `/api/teams/notifications` (Graph+change notifications) — and the adapter serves them from its own HTTP server on+port 3978, separate from the API on 8000.++That means:++- The address must resolve in **public DNS**. Tailscale, a VPN or an+ internal-only load balancer will not do; Microsoft's servers are on the+ internet.+- It must be **HTTPS with a certificate Microsoft trusts**. Graph answers a new+ subscription by calling your notification URL and expecting the validation+ token echoed back within 10 seconds, so a self-signed cert, a redirect or an+ auth proxy in front all fail the handshake.+- Those two paths are unauthenticated *at the network layer* by necessity — the+ adapter authenticates each request itself (Bot Connector JWT, and the+ `clientState` shared secret respectively). Do not put an auth proxy in front.++Because it is only two paths, you do not have to expose anything else. Set+`switchCore.teamsBridge.ingress.mode=dedicated` and the chart renders a second+Ingress carrying just those paths on their own hostname, leaving the gateway and+agent API wherever you put them:++```yaml+switchCore:+ teamsBridge:+ enabled: true+ ingress:+ mode: dedicated+ className: nginx+ host: teams.switch.example.com+ annotations:+ cert-manager.io/cluster-issuer: letsencrypt-prod+ tls:+ enabled: true+ secretName: switch-teams-tls+```++The other modes are `shared` (add the paths to the chart's managed Ingress, so+Teams shares the gateway's hostname) and `external` (you route them yourself —+see [`samples/ingress.example.yaml`](samples/ingress.example.yaml)).++**Enabling the bridge without choosing a mode is a render-time error.**+Publishing the port with nothing routing to it produces a bridge that creates+channels and posts messages while receiving nothing back, which is a failure you+would otherwise discover days later. The chart refuses instead.++Note the dedicated Ingress takes its annotations only from+`teamsBridge.ingress.annotations`; the top-level `ingress.annotations` are not+merged in, so anything org-wide has to be repeated there.++After install, `helm test` runs Graph's validation handshake against the Service+to prove the listener is bound and published. **It fails until a Teams bridge is+registered** — the chart opens the port, but only a configured bridge puts a+listener behind it — so keep it out of any automated gate that reads a failure+as broken. And it runs *inside* the cluster, so it cannot tell you whether+Microsoft can reach you. Check that from outside:++```bash+curl -i "https://teams.switch.example.com/api/teams/notifications?validationToken=ping"+```++Expect `200` with `ping` echoed back as `text/plain`. A timeout means it is not+public; a 404 means the path is missing or aimed at port 8000.++Full walkthrough, including the Azure side:+[`docs/bridges/TEAMS_SETUP.md`](../../../../docs/bridges/TEAMS_SETUP.md).++---++## Ingress modes++`ingress.mode` controls the main web Ingress:++- **`existing`** (default) — the chart renders no Ingress. Wire the Services up+ with your own manifest; [`samples/ingress.example.yaml`](samples/ingress.example.yaml)+ is copy-pasteable.+- **`managed`** — the chart renders one path-routed Ingress on `ingress.host`:+ `agentApiPaths` to switch-core, everything else to the gateway SPA.++`switchCore.teamsBridge.ingress.mode` is independent of this — `dedicated` works+under either.++TLS is yours to arrange. `ingress.tls.enabled` renders a `spec.tls` stanza;+supply `secretName`, or add a cert-manager annotation and let it create the+Secret. If your controller configures TLS by annotation instead (AWS ALB, for+example), leave `tls.enabled` false and annotate.++---++## Constraints you cannot configure away++**switch-core runs exactly one replica.** It holds live Matrix sync sessions and+bridge connections in memory; a second replica would duplicate every client and+split session state. `switchCore.replicaCount` other than 1 fails the render,+and the deployment strategy is `Recreate`, so upgrades have a brief outage+rather than two pods fighting.++**Bridges are created at runtime, not in values.** You register a collaboration+bridge in the gateway dashboard, with its credentials, after the chart is+installed. That is why `switchCore.teamsBridge.enabled` exists at all: the chart+cannot see your bridges, so it cannot infer that you need port 3978 published.++**A bridge that fails to start is dropped, not retried.** It is restarted when+switch-core restarts. If a bridge is missing after a configuration change,+restart the deployment.++---++## Secrets++Either let the chart manage them — set the values under `secrets:` and it+renders `<release>-secrets` — or set `secrets.existingSecret` to the name of a+Secret you produced yourself (External Secrets Operator, sealed-secrets, …). The+required keys are listed above the `secrets:` block in `values.yaml`.++Bridge credentials are **not** among them. Those are entered in the gateway and+stored in the database.diff --git a/deploy/remote/helm/switch/samples/ingress.example.yaml b/deploy/remote/helm/switch/samples/ingress.example.yamlindex da0652d45..5fb7effd1 100644--- a/deploy/remote/helm/switch/samples/ingress.example.yaml+++ b/deploy/remote/helm/switch/samples/ingress.example.yaml@@ -49,6 +49,25 @@ spec:- path: /healthpathType: Prefixbackend: { service: { name: RELEASE-switch-core, port: { number: 8000 } } }+ # Microsoft Teams bridge only, and only with+ # switchCore.teamsBridge.ingress.mode=external — the mode that says+ # "I route these myself". Delete both if you run no Teams bridge.+ #+ # The Teams adapter listens on its own port inside switch-core (3978+ # by default), NOT on 8000, so these two paths need the teams port;+ # aiming them at 8000 reaches the API, which does not speak Bot+ # Framework. The chart publishes that port only when+ # switchCore.teamsBridge.enabled=true.+ #+ # Prefer mode=dedicated to putting these here: it gives the callback+ # its own host and certificate, so Microsoft reaches those two paths+ # and nothing else while the gateway stays internal.+ - path: /api/messages+ pathType: Prefix+ backend: { service: { name: RELEASE-switch-core, port: { number: 3978 } } }+ - path: /api/teams/notifications+ pathType: Prefix+ backend: { service: { name: RELEASE-switch-core, port: { number: 3978 } } }- path: /pathType: Prefixbackend: { service: { name: RELEASE-gateway, port: { number: 3000 } } }diff --git a/deploy/remote/helm/switch/templates/NOTES.txt b/deploy/remote/helm/switch/templates/NOTES.txtindex 745ba6879..64cd6aef7 100644--- a/deploy/remote/helm/switch/templates/NOTES.txt+++ b/deploy/remote/helm/switch/templates/NOTES.txt@@ -26,6 +26,71 @@ Ingress is in "existing" mode: no Ingress was rendered. Expose the gateway andagent API with your own controller (see the chart's samples/ingress.example.yaml)or set ingress.mode=managed.{{- end }}+{{- if .Values.switchCore.teamsBridge.enabled }}++── Microsoft Teams bridge ──────────────────────────────────────────────────────+{{- $teams := .Values.switchCore.teamsBridge }}+{{- $origin := include "switch.teamsPublicOrigin" . }}+{{- if and (eq $teams.ingress.mode "dedicated") $teams.ingress.host }}+A dedicated Ingress ({{ include "switch.fullname" . }}-teams) carries the two+callback paths on host {{ $teams.ingress.host }}. Point its DNS at your ingress+controller.+{{- else if eq $teams.ingress.mode "dedicated" }}+A dedicated Ingress ({{ include "switch.fullname" . }}-teams) carries the two+callback paths, with no host rule — so it answers whatever Host header reaches+it. That is the shape to use behind a CDN or reverse proxy that terminates TLS+and owns the public name.++Put that proxy in front of this Ingress's load balancer, and make sure it+forwards query strings, allows POST and does NOT cache: Graph validates a new+subscription with a POST carrying ?validationToken=, and a stripped or cached+answer fails the handshake.+{{- else if eq $teams.ingress.mode "shared" }}+The two callback paths were added to the managed Ingress on host+{{ .Values.ingress.host }}.+{{- else }}+Routing is set to "external": the chart rendered no route for the Teams paths.+Add them to your own Ingress, both to {{ include "switch.switchCoreHost" . }}:{{ $teams.port }}+and NOT to the API port:+{{- range $path := .Values.ingress.teamsPaths }}+ {{ $path }}+{{- end }}+{{- end }}+{{ if $origin }}+Set the bridge's public_base_url to exactly:++ {{ $origin }}+{{- $tlsHere := ternary $teams.ingress.tls.enabled .Values.ingress.tls.enabled (eq $teams.ingress.mode "dedicated") }}+{{- if not $tlsHere }}++⚠ https, even though TLS is disabled on this Ingress — Graph refuses a+ plaintext URL, so that host has to be served over HTTPS by something in+ front (a CDN, or a load balancer configured by annotation). If nothing is,+ the bridge will create channels and then silently receive nothing.+{{- end }}+{{- else }}+Set the bridge's public_base_url to the public HTTPS origin Microsoft will call+— scheme and host only, no path.+{{- if eq $teams.ingress.mode "external" }}++The chart renders no Ingress in this mode, so it cannot tell you the origin:+you route the two paths yourself, and the public name is whatever you route+them from.+{{- else }}++This Ingress has no host of its own, so the chart cannot tell you: the public+name belongs to whatever sits in front of it.+{{- end }}+{{- end }}++Then verify from OUTSIDE the cluster, which is the part that usually fails:++ curl -i "{{ if $origin }}{{ $origin }}{{ else }}https://<your-public-host>{{ end }}/api/teams/notifications?validationToken=ping"++Expect 200 with `ping` echoed back. A timeout means it is not public; a 404+means the path is missing or aimed at the API port. `helm test` checks the+in-cluster half. See docs/bridges/TEAMS_SETUP.md.+{{- end }}⚠ BACK UP YOUR DATA — this chart ships no backup jobs.The Tuwunel volume ({{ include "switch.fullname" . }}-tuwunel-data) holds thediff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex 4d0a80f62..889025039 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -118,6 +118,66 @@ Other service hostnames (used in env vars and init containers).{{- include "switch.fullname" . }}-mattermost{{- end }}+{{/*+Public origin of the Teams bridge listener: the value the bridge's+public_base_url must be set to.++Always https, whatever `tls.enabled` says. That flag governs whether *this*+Ingress carries a certificate, not what Microsoft dials — and Graph refuses a+plaintext URL, so http is never the answer. Deriving the scheme from the flag+printed `http://<host>` as the value to use whenever TLS terminated upstream,+which is the documented ALB pattern.++Empty only when the host is genuinely unknown to the chart: a host-less rule+behind a CDN that owns the public name. The caller must then ask the operator+rather than print a guess.+*/}}+{{- define "switch.teamsPublicOrigin" -}}+{{- $teams := .Values.switchCore.teamsBridge -}}+{{- if and (eq $teams.ingress.mode "dedicated") $teams.ingress.host -}}+{{- printf "https://%s" $teams.ingress.host -}}+{{- else if and (eq $teams.ingress.mode "shared") .Values.ingress.host -}}+{{- printf "https://%s" .Values.ingress.host -}}+{{- end -}}+{{- end }}++{{/*+Reject Teams bridge configurations that would deploy a listener nothing can+reach. Publishing the port without routing it produces a bridge that creates+channels and posts fine while silently receiving nothing, which is the exact+failure this block exists to prevent — so these are render-time errors rather+than something you discover hours later at Graph subscription time.+*/}}+{{- define "switch.validateTeamsBridge" -}}+{{- $teams := .Values.switchCore.teamsBridge -}}+{{- $mode := $teams.ingress.mode -}}+{{- $modes := list "dedicated" "shared" "external" -}}+{{- if not $teams.enabled -}}+{{- if $mode -}}+{{- fail (printf "switchCore.teamsBridge.ingress.mode is %q but switchCore.teamsBridge.enabled is false: nothing publishes port %v for it to route to. Set enabled=true, or clear the mode." $mode $teams.port) -}}+{{- end -}}+{{- else -}}+{{- if not $mode -}}+{{- fail "switchCore.teamsBridge.enabled is true but switchCore.teamsBridge.ingress.mode is unset. Microsoft calls the Teams listener from the public internet, so publishing the port is only half the job — choose how the two callback paths are routed: \"dedicated\" (the chart renders an Ingress for them on their own host), \"shared\" (add them to the chart's managed Ingress), or \"external\" (you route them yourself; see samples/ingress.example.yaml)." -}}+{{- end -}}+{{- if not (has $mode $modes) -}}+{{- fail (printf "switchCore.teamsBridge.ingress.mode must be one of dedicated, shared or external — got %q." $mode) -}}+{{- end -}}+{{- if and (eq $mode "shared") (ne .Values.ingress.mode "managed") -}}+{{- fail (printf "switchCore.teamsBridge.ingress.mode is \"shared\" but ingress.mode is %q: there is no chart-managed Ingress to add the Teams paths to. Set ingress.mode=managed, or use teamsBridge.ingress.mode=dedicated to give Teams its own Ingress, or \"external\" to route it yourself." .Values.ingress.mode) -}}+{{- end -}}+{{- if and (eq $mode "shared") (not .Values.ingress.host) -}}+{{- fail "switchCore.teamsBridge.ingress.mode is \"shared\" but ingress.host is empty. Microsoft resolves the notification URL from public DNS, so the Ingress needs a real hostname rather than a catch-all rule." -}}+{{- end -}}+{{- if and (ne $mode "external") (not .Values.ingress.teamsPaths) -}}+{{- fail "ingress.teamsPaths is empty, so the Teams Ingress would render a rule with no paths — which Helm accepts and the Kubernetes API rejects at apply time. Restore the two callback paths, or set switchCore.teamsBridge.ingress.mode=external if you route them yourself." -}}+{{- end -}}+{{- if and (eq $mode "dedicated") (not $teams.ingress.host) $teams.ingress.tls.enabled -}}+{{- fail "switchCore.teamsBridge.ingress.mode is \"dedicated\" with TLS enabled but switchCore.teamsBridge.ingress.host is empty: a host-less rule cannot carry a TLS certificate. Either set the host, or set tls.enabled=false if something upstream terminates TLS and owns the public name (a CDN or reverse proxy — then public_base_url is that name, not this Ingress's)." -}}+{{- end -}}+{{- end -}}+{{- end }}+{{/*Prepend the global image registry if set.Usage: {{ include "switch.image" (dict "global" .Values.global "image" .Values.switchCore.image) }}diff --git a/deploy/remote/helm/switch/templates/common/generic-ingress.yaml b/deploy/remote/helm/switch/templates/common/generic-ingress.yamlindex fdbf23d43..e4a53aeda 100644--- a/deploy/remote/helm/switch/templates/common/generic-ingress.yaml+++ b/deploy/remote/helm/switch/templates/common/generic-ingress.yaml@@ -54,6 +54,17 @@ spec:port:number: {{ $.Values.switchCore.service.port }}{{- end }}+ {{- if eq .Values.switchCore.teamsBridge.ingress.mode "shared" }}+ {{- range $path := .Values.ingress.teamsPaths }}+ - path: {{ $path | quote }}+ pathType: Prefix+ backend:+ service:+ name: {{ $svcCore }}+ port:+ number: {{ $.Values.switchCore.teamsBridge.port }}+ {{- end }}+ {{- end }}- path: /pathType: Prefixbackend:diff --git a/deploy/remote/helm/switch/templates/common/teams-ingress.yaml b/deploy/remote/helm/switch/templates/common/teams-ingress.yamlnew file mode 100644index 000000000..1b660c46f--- /dev/null+++ b/deploy/remote/helm/switch/templates/common/teams-ingress.yaml@@ -0,0 +1,59 @@+{{- if eq .Values.switchCore.teamsBridge.ingress.mode "dedicated" }}+{{- $teams := .Values.switchCore.teamsBridge }}+{{- $svcCore := include "switch.switchCoreHost" . }}+# Dedicated Ingress for the Microsoft Teams bridge listener+# (switchCore.teamsBridge.ingress.mode=dedicated).+#+# Separate from the main web Ingress on purpose. Microsoft needs exactly two+# paths and nothing else, so this lets the Teams callback have a public+# hostname and certificate while the gateway and agent API stay wherever you+# put them — including entirely internal. It renders independently of+# ingress.mode, so installs that bring their own Ingress for everything else+# still get this one for free.+#+# Both paths are unauthenticated at the network layer by necessity: Microsoft+# cannot satisfy an auth proxy, and Graph's validation handshake fails in front+# of one. The adapter authenticates every request itself — Bot Connector JWT on+# /api/messages, the clientState shared secret on /api/teams/notifications.+apiVersion: networking.k8s.io/v1+kind: Ingress+metadata:+ name: {{ include "switch.fullname" . }}-teams+ labels:+ {{- include "switch.labels" . | nindent 4 }}+ {{- with $teams.ingress.annotations }}+ annotations:+ {{- toYaml . | nindent 4 }}+ {{- end }}+spec:+ {{- if $teams.ingress.className }}+ ingressClassName: {{ $teams.ingress.className }}+ {{- end }}+ {{- if $teams.ingress.tls.enabled }}+ tls:+ - hosts:+ - {{ $teams.ingress.host | quote }}+ {{- if $teams.ingress.tls.secretName }}+ secretName: {{ $teams.ingress.tls.secretName }}+ {{- end }}+ {{- end }}+ rules:+ # Host-less when no host is set: with a CDN or reverse proxy in front, the+ # Host header arriving here is that proxy's name, which is not known when+ # the chart renders. Matching on it would 404 every callback.+ - {{ if $teams.ingress.host }}host: {{ $teams.ingress.host | quote }}+ {{ end }}http:+ paths:+ {{- /* This shared list is this Ingress's entire public surface — the+ point of `dedicated` is that it carries these two paths and+ nothing else, so widening it widens what is exposed. */}}+ {{- range $path := $.Values.ingress.teamsPaths }}+ - path: {{ $path | quote }}+ pathType: Prefix+ backend:+ service:+ name: {{ $svcCore }}+ port:+ number: {{ $teams.port }}+ {{- end }}+{{- end }}diff --git a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml b/deploy/remote/helm/switch/templates/switch-core/deployment.yamlindex d95e1559c..e83682727 100644--- a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/deployment.yaml@@ -38,6 +38,11 @@ spec:ports:- containerPort: 8000protocol: TCP+ {{- if .Values.switchCore.teamsBridge.enabled }}+ - containerPort: {{ .Values.switchCore.teamsBridge.port }}+ name: teams+ protocol: TCP+ {{- end }}env:{{- include "switch.coreEnv" . | nindent 12 }}readinessProbe:diff --git a/deploy/remote/helm/switch/templates/switch-core/service.yaml b/deploy/remote/helm/switch/templates/switch-core/service.yamlindex 37024a323..21a5c2e0d 100644--- a/deploy/remote/helm/switch/templates/switch-core/service.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/service.yaml@@ -1,3 +1,4 @@+{{- include "switch.validateTeamsBridge" . }}apiVersion: v1kind: Servicemetadata:@@ -12,5 +13,11 @@ spec:targetPort: 8000protocol: TCPname: http+ {{- if .Values.switchCore.teamsBridge.enabled }}+ - port: {{ .Values.switchCore.teamsBridge.port }}+ targetPort: {{ .Values.switchCore.teamsBridge.port }}+ protocol: TCP+ name: teams+ {{- end }}selector:{{- include "switch.selectorLabels" (dict "Release" .Release "component" "switch-core") | nindent 4 }}diff --git a/deploy/remote/helm/switch/templates/tests/teams-listener.yaml b/deploy/remote/helm/switch/templates/tests/teams-listener.yamlnew file mode 100644index 000000000..04cae2aaa--- /dev/null+++ b/deploy/remote/helm/switch/templates/tests/teams-listener.yaml@@ -0,0 +1,74 @@+{{- if .Values.switchCore.teamsBridge.enabled }}+{{- $teams := .Values.switchCore.teamsBridge }}+# `helm test` check for the Teams bridge listener.+#+# Probes the notification path through the Service: GET it with a+# validationToken and require it echoed back verbatim. That proves the listener+# is bound inside the pod AND that the Service publishes its port — the two+# halves the chart is responsible for.+#+# Graph's real handshake is a POST carrying the same query parameter. The same+# handler answers both, and a GET is what a probe can express, so this+# exercises the handshake's shape rather than reproducing it.+#+# It deliberately does NOT prove Microsoft can reach you. This runs inside the+# cluster, so it says nothing about public DNS, ingress routing or certificate+# trust, which is exactly where this usually fails. Verify that from outside:+#+# curl -i "https://<your-public-host>/api/teams/notifications?validationToken=ping"+#+# Expect 200 with `ping` echoed as text/plain.+apiVersion: v1+kind: Pod+metadata:+ name: {{ include "switch.fullname" . }}-teams-listener-test+ labels:+ {{- include "switch.labels" . | nindent 4 }}+ annotations:+ helm.sh/hook: test+ helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded+spec:+ restartPolicy: Never+ {{- if .Values.global.imagePullSecrets }}+ {{- include "switch.imagePullSecrets" . | nindent 2 }}+ {{- end }}+ containers:+ - name: probe+ image: busybox:1.36+ command:+ - sh+ - -c+ - |+ set -eu+ url="http://{{ include "switch.switchCoreHost" . }}:{{ $teams.port }}/api/teams/notifications"+ token="switch-helm-test"+ echo "GET $url?validationToken=$token"+ body=$(wget -T 10 -qO- "$url?validationToken=$token") || {+ echo "FAIL: nothing answered on port {{ $teams.port }}."+ echo+ echo "Most likely no Teams bridge is registered yet. The chart publishes"+ echo "the port, but only a configured bridge starts a listener behind it —"+ echo "and you normally enable the chart flag FIRST, because the bridge"+ echo "needs the public URL that produces. If that is where you are,"+ echo "register the bridge and run this again."+ echo+ echo "Otherwise the listener failed to start. Look for 'Teams adapter"+ echo "listening on' in the switch-core logs; if it is absent, look for"+ echo "'crashed' — a second Teams bridge cannot bind the same port."+ exit 1+ }+ if [ "$body" != "$token" ]; then+ echo "FAIL: expected the validation token echoed back, got: $body"+ exit 1+ fi+ echo "OK: listener answered Graph's validation handshake."+ echo+ echo "This proves the pod and Service only. Confirm Microsoft can reach you"+ echo "from OUTSIDE the cluster:"+ {{- $origin := include "switch.teamsPublicOrigin" . }}+ {{- if $origin }}+ echo ' curl -i "{{ $origin }}/api/teams/notifications?validationToken=ping"'+ {{- else }}+ echo ' curl -i "https://<your-public-host>/api/teams/notifications?validationToken=ping"'+ {{- end }}+{{- end }}diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex 8082cfb9f..c5a1cccc1 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -46,6 +46,15 @@ ingress:- /oauth- /.well-known- /health+ # Path prefixes served by the Teams bridge listener rather than the FastAPI+ # app, because that listener is a separate HTTP server on its own port. Used+ # by both switchCore.teamsBridge.ingress modes "shared" and "dedicated".+ # Graph rejects a subscription whose notification URL does not answer its+ # validation handshake over valid TLS within 10 seconds, so wherever these are+ # served must be publicly reachable — not Tailscale- or VPN-only.+ teamsPaths:+ - /api/messages+ - /api/teams/notifications# ── Secrets ───────────────────────────────────────────────────────────────────# Two ways to supply secrets:@@ -114,6 +123,71 @@ switchCore:service:type: ClusterIPport: 8000+ # Microsoft Teams bridge listener. The Teams adapter runs its own HTTP server+ # inside switch-core, separate from the FastAPI app on service.port: Bot+ # Framework activities arrive at /api/messages and Graph change notifications+ # at /api/teams/notifications. Microsoft calls both from the public internet,+ # so both must be reachable over HTTPS. Without that the bridge is+ # outbound-only — it can create channels and post, but receives nothing back+ # and captures no messages.+ #+ # Off by default, and deliberately: Teams bridges are created at runtime in the+ # gateway, not in Helm values, so the chart cannot tell whether you have one.+ # Enable this when you configure a Teams bridge, and set that bridge's+ # public_base_url to the host this is served on.+ teamsBridge:+ enabled: false+ # Listener bind port inside the container; must match the bridge's+ # listen_port (default 3978). One Teams bridge per port.+ port: 3978+ # How Microsoft reaches the two callback paths (ingress.teamsPaths).+ # Required when enabled — publishing the port without routing it is the+ # failure this whole block exists to prevent, so the chart refuses to render+ # rather than let you deploy a bridge that can never receive anything.+ #+ # dedicated -> the chart renders a second Ingress carrying only those two+ # paths, with its own host, class, annotations and TLS. Use+ # this to give Teams a public hostname while the gateway+ # stays internal: Microsoft needs those two paths and nothing+ # else, and both authenticate per-request inside the adapter.+ # shared -> add the paths to the chart's main Ingress. Requires+ # ingress.mode=managed, and puts Teams on the same public+ # host as the gateway.+ # external -> the chart renders no route; you add the two paths to your+ # own Ingress. See samples/ingress.example.yaml.+ ingress:+ mode: ""+ # Used by mode=dedicated only.+ className: ""+ # Public hostname Microsoft resolves, e.g. "teams.switch.example.com".+ # Must match the host in the bridge's public_base_url.+ #+ # Leave empty ONLY when something upstream terminates TLS and owns the+ # public name — a CDN or reverse proxy in front of this Ingress. The rule+ # then carries no host and answers whatever Host header arrives, which is+ # required there: the incoming Host is the proxy's name, and the chart+ # cannot know it. Empty with tls.enabled=true is rejected, because a+ # host-less rule cannot carry a certificate.+ host: ""+ # Annotations for the dedicated Ingress. This is the ONLY source of them:+ # the top-level ingress.annotations are not merged in, so an org-wide+ # annotation set there (a WAF association, cost tags, a policy webhook)+ # does not reach this Ingress and must be repeated here. That separation+ # is deliberate — the main Ingress's streaming annotations suit long-lived+ # MCP/SSE connections and Teams callbacks are short request/response —+ # but it does mean this list is not additive.+ # For cert-manager, add e.g.:+ # cert-manager.io/cluster-issuer: letsencrypt-prod+ annotations: {}+ tls:+ # Graph only calls an HTTPS URL whose certificate it trusts, so this is+ # on by default. Set false only when TLS terminates upstream and is not+ # expressed in spec.tls — e.g. an AWS ALB configured by annotation. The+ # chart cannot verify that, so it warns instead of failing.+ enabled: true+ # Secret holding the cert; cert-manager creates it from the annotation+ # above, or reference a pre-created TLS Secret.+ secretName: ""# switch-core keeps live Matrix sync sessions in memory, so it MUST run as a# single replica — a second replica would double every client and split# session state. This is enforced at render time; do not raise it.diff --git a/docs/bridges/DISCORD_SETUP.md b/docs/bridges/DISCORD_SETUP.mdindex fdef24056..0f0542e7d 100644--- a/docs/bridges/DISCORD_SETUP.md+++ b/docs/bridges/DISCORD_SETUP.md@@ -179,8 +179,8 @@ GATEWAY_PUBLIC_URL=https://switch-api.acme.com```When set, Switch rewrites the deeplink to a clickable-`https://<switch-api-host>/deeplink/session?…` redirect (a `302` back to the-`switchdash://` scheme) at runtime-state ingestion — so both the bridged+`https://<switch-api-host>/deeplink/session?…` link (a page that hands off to+the `switchdash://` scheme) at runtime-state ingestion — so both the bridgedworking/awaiting-input status message **and** the `!agents-status` command surface aclickable link, on every platform at once. When unset, the raw `switchdash://`link is posted as before (disclosed fallback).diff --git a/docs/bridges/README.md b/docs/bridges/README.mdindex c000c9670..6d4dde73b 100644--- a/docs/bridges/README.md+++ b/docs/bridges/README.md@@ -53,23 +53,32 @@ form lists the live set and the fields each one requires.- **Rooms.** Depending on the platform, a Switch room is created for a channeleither when the bot is added to it (Slack, Mattermost, Teams, Telegram) orlazily on the first bridged message (Discord — it has no "app added to channel"- signal). Existing Switch rooms can also be bound to a channel at room-creation+ signal). Teams is a partial case: an app is installed into a *team* rather+ than a channel, so the signal fires for the channel it is added to and the+ team's other standard channels are bound explicitly — see+ [`TEAMS_SETUP.md`](TEAMS_SETUP.md#bringing-switch-into-a-channel-that-already-exists).+ Existing Switch rooms can also be bound to a channel at room-creationtime. See **Channel creation** below for the other direction — Switch makingthe channel — which not every connection can or may do.- **Addressing agents.** Users `@mention` an agent by name in the channel toaddress it; unaddressed chatter is bridged as context. In-room commands (e.g.- `!invite-agent`) work on every platform. Slack, Discord and Telegram- additionally expose them as **native slash commands** (`/invite-agent`) routed- into the same handler — declared in the app manifest on Slack, registered- automatically per guild on Discord, and accepted alongside `!` on Telegram,- where `/` is the platform's own convention.+ `!invite-agent`) work on every platform. Every platform except Mattermost also+ takes the `/invite-agent` form, routed into the same handler — though what+ makes it work differs. Slack declares its commands in the app manifest and+ Discord registers them per guild, so `/` is a real platform command there.+ Telegram and Teams simply accept `/` alongside `!` as an ordinary message:+ on Telegram because `/` is the platform's own convention, and on Teams+ because a manifest command list only *types* the command into the compose box+ for the bot to parse.- **"Open in Switch Console" links.** Agents surface a `switchdash://…` deeplink with- their runtime status. Platforms that only render `http(s)` links (Discord and- Telegram) need `GATEWAY_PUBLIC_URL` set so Switch can rewrite it to a clickable- `https://<switch-api-host>/deeplink/session?…` redirect; the bridge logs a- warning at startup when one of those platforms is running without it. Unset,- the address is posted as tap-to-copy text rather than as a link the platform- would silently discard. See the Discord or Telegram guide.+ their runtime status. Platforms that only render `http(s)` links (Discord,+ Telegram and Teams) need `GATEWAY_PUBLIC_URL` set so Switch can rewrite it to+ a clickable `https://<switch-api-host>/deeplink/session?…` redirect; the+ bridge logs a warning at startup when one of those platforms is running+ without it. Unset, the raw address is posted instead of a link — readable on+ Discord, tap-to-copy on Telegram, and **discarded entirely on Teams**, which+ strips a non-http link along with its label. See the Discord, Telegram or+ Teams guide.### Channel creation@@ -106,6 +115,12 @@ are deployment-level environment config on switch-core:at `/deeplink/session` on the API root (the agent-bridge app), **not** under the`/gateway` mount — so front it with a proxy that routes the API root, not only`/gateway/*`. Leave unset to post the raw `switchdash://` deeplink (the- disclosed fallback). Applies to every platform but matters most for Discord.-- **Teams** additionally needs public HTTPS ingress to the bridge's listener —- see [`TEAMS_SETUP.md`](TEAMS_SETUP.md).+ disclosed fallback). Applies to every platform, and is **required** on+ Discord, Telegram and Teams, which render only http(s) links — Teams goes+ further and strips a link on any other scheme entirely, label included, so+ without this the deeplink renders as empty brackets.+- **Teams** additionally needs public HTTPS ingress to the bridge's listener, on+ its own port — it is the only bridge Switch does not reach outbound. See+ [`TEAMS_SETUP.md`](TEAMS_SETUP.md) for the bridge side, and the Helm chart's+ [README](../../deploy/remote/helm/switch/README.md) for which Switch surfaces+ have to be reachable from where.diff --git a/docs/bridges/TEAMS_SETUP.md b/docs/bridges/TEAMS_SETUP.mdindex 235dec415..2f3829fe5 100644--- a/docs/bridges/TEAMS_SETUP.md+++ b/docs/bridges/TEAMS_SETUP.md@@ -4,14 +4,93 @@ Connects a Microsoft Teams tenant to Switch. A **single Azure bot app** backsevery Switch agent (like Slack); each agent's messages render as an **AdaptiveCard** headed with the agent's name and avatar.-Teams is the only bridge that **requires public HTTPS ingress**: it has no-persistent bot socket, so the adapter hosts its own HTTP listener and Microsoft-pushes events to it.+Teams is the most involved bridge to set up. Unlike Slack or Mattermost it has+no persistent socket, so it is **push-based**: Microsoft calls Switch, not the+other way round. That single fact drives most of this guide — the adapter hosts+its own HTTP listener, and that listener must be reachable from the public+internet or the bridge only half-works.-> This guide is the operator-facing setup walkthrough. The in-package note at+> This is the operator-facing walkthrough. The in-package note at> [`core/switch_core/bridges/collaboration/teams/README.md`](../../core/switch_core/bridges/collaboration/teams/README.md)-> covers the adapter's internal architecture (Bot Framework + Graph capture,-> encryption, de-duplication) in more depth.+> covers the adapter's internals (Bot Framework + Graph capture, encryption,+> de-duplication).++---++## Prerequisites++Have these before you start. Two of them involve someone who may not be you,+and both are on the critical path.++**In Microsoft Entra ID / Azure**++- Rights to create an **app registration** and a client secret on it.+- Someone who can **grant admin consent** for Graph application permissions+ (see [1.4](#14-graph-api-permissions)). Tenant-wide consent is usually a+ Global Administrator or Privileged Role Administrator. If that is not you,+ line them up now: nothing in Part 4 works until consent is granted.+- Rights to **install a Teams app into a team** — either sideloading enabled+ for you, or an admin who can upload to the organisation's app catalog.++**In your deployment**++- A **public DNS name** resolvable from the internet, and **HTTPS** on it that+ Microsoft will trust. Teams is push-based: Microsoft calls you. A VPN-only or+ tailnet name cannot work, and neither can plain HTTP.+- Administrator access to the Switch dashboard, and a running switch-core you+ can deploy chart changes to.++**Decide one thing up front: the public hostname of the Teams listener.** It+goes into the Azure Bot's messaging endpoint in [1.3](#13-azure-bot-resource),+into `public_base_url` in [Part 3](#part-3-onboard-the-bridge-in-switch), and+into your ingress in [Part 2](#part-2-deployment) — and changing it later means+editing all three. It need not be the name that serves the dashboard, and+usually should not be.++**Time.** An hour if you have all of the above and the consent is quick;+longer if you are waiting on an administrator.++---++## Read this first: the two mistakes that cost the most time++Both produce confusing failures. Neither is obvious from the error you see.++### 1. The client secret is the **value**, not the secret ID++When you create a client secret, the Azure portal shows two columns: **Value**+and **Secret ID**. Both look like opaque strings. You want the **Value**.++Pasting the Secret ID is rejected when you save the bridge, with Microsoft's+own words:++```+AADSTS7000215: Invalid client secret provided. Ensure the secret being sent+in the request is the client secret value, not the client secret ID.+```++**The Value is shown exactly once**, when the secret is created. Navigate away+and it is gone forever — the portal will still show the Secret ID, which is what+makes this so easy to get wrong later. If you did not record it, do not try to+recover it: create a new secret and use that.++### 2. The listener needs **public** HTTPS ingress++The adapter runs its own HTTP server on port **3978**, *separate* from Switch's+main API on 8000. Microsoft pushes to it:++- `POST /api/messages` — Bot Framework activities (inbound messages)+- `POST /api/teams/notifications` — Graph change notifications++If these are not publicly reachable, the bridge is **outbound-only**: it creates+channels and posts messages fine, so it looks healthy, but nothing from Teams+ever arrives. Tailscale, a VPN or an internal-only load balancer are **not+enough** — the caller is Microsoft, out on the internet.++See [Part 2: Deployment](#part-2-deployment) — this is a separate step from+filling in the bridge form, and it is the one most often skipped.++---## Architecture in brief@@ -28,78 +107,1213 @@ Two Microsoft APIs feed the bridge, both landing on the adapter's own listener:validates the `clientState` secret, decrypts with its private key, and renewssubscriptions before their ~60-minute expiry.-## Ops prerequisites (must exist before onboarding)--These are tenant/environment setup owned by an administrator — treat as a-separate ops task before you can onboard the bridge.--1. **Azure AD app registration** — provides the bot's `app_id` (client id), a- client secret (`app_password`), and the `tenant_id`.-2. **Azure Bot resource** on that app, with the **messaging endpoint** set to- `https://<public-host>/api/messages` and the **Microsoft Teams channel**- enabled.-3. **Teams app package** (manifest) including the bot, installed into the target- team so it can be added to channels and post proactively.-4. **Graph API permissions** (admin-consented) for channel capture +- provisioning: `ChannelMessage.Read.Group` (RSC, preferred) *or* tenant-wide- `ChannelMessage.Read.All`; plus `Channel.Create` and- `TeamMember.ReadWrite.All` / `ChannelMember.ReadWrite.All`. Resource-data- subscriptions count against a shared per-tenant Teams subscription quota.-5. **Encryption certificate** — an X.509 cert whose public certificate is handed- to Graph and whose private key the bridge holds to decrypt message bodies.- Give it a stable id.-6. **Public HTTPS ingress** routing `https://<public-host>/api/messages` and- `/api/teams/notifications` to the bridge's listener. Graph requires valid TLS- and a response to its validation handshake within 10 seconds.--## Onboard the bridge in Switch--As a gateway admin, onboard the bridge from the **operator dashboard**:-**Messaging Apps → Register messaging app → Teams**, give it a display name (e.g. "Acme-Teams"), and fill in the fields below.--Fields (`TeamsConnectionConfig`):--| Field | Required | Description |+Capture therefore has two tiers. `@mention` capture needs only the Bot Framework+path; full channel capture additionally needs Graph subscriptions, which need+the Graph permissions in [1.4](#14-graph-api-permissions). The keypair those+notifications are encrypted to is Switch's own — generated per bridge, with+nothing to obtain or install.++---++## Part 1: Azure setup++Tenant/environment setup owned by an administrator. Treat it as a separate ops+task, done before you touch the Switch dashboard. Keep a scratch note as you go —+Part 3 asks for each value by name.++### 1.1 App registration++**Azure portal → Microsoft Entra ID → App registrations → New registration.**++Record:++| You need | Where it is | Portal label |+| --- | --- | --- |+| `app_id` | App registration → Overview | **Application (client) ID** |+| `tenant_id` | App registration → Overview | **Directory (tenant) ID** |++Both are GUIDs. Do not confuse the Application (client) ID with the **Object+ID** directly beneath it — the Object ID is not used here.++### 1.2 Client secret++**App registration → Certificates & secrets → Client secrets → New client+secret.**++Record the **Value** column — see [the warning above](#1-the-client-secret-is-the-value-not-the-secret-id).+This becomes `app_password`.++Note the expiry you choose. When it lapses the bridge stops authenticating and+fails the way a wrong secret does, though Azure reports it with its own error+code — so record the date somewhere you will see it.++### 1.3 Azure Bot resource++**Create an Azure Bot** resource backed by the app registration above.++- **Messaging endpoint:** `https://<your-public-host>/api/messages`+- **Channels** (the Azure Bot blade of that name — not Teams channels):+ enable **Microsoft Teams**++**Back it by the app registration from 1.1 — not a new one.** The create form+will happily make you a fresh app registration, and everything then looks+correct: Graph runs on 1.1's id and creates channels, while Microsoft signs+inbound activities with the bot's id and Switch rejects every one of them. Check+**Configuration → Microsoft App ID** on the finished resource and confirm it is+the id from 1.1.++The messaging endpoint is the hostname you settled on in+[Prerequisites](#prerequisites), with `/api/messages` on the end. It must be+the same origin you give as `public_base_url` in+[Part 3](#part-3-onboard-the-bridge-in-switch) — the listener's host, which is+not necessarily the one serving the dashboard. Under+[Part 2](#part-2-deployment)'s recommended `mode: dedicated`, both are the+Teams host.++### 1.4 Graph API permissions++**App registration → API permissions → Add a permission → Microsoft Graph →+Application permissions.**++Application permissions, not delegated: the bridge acts as itself, with no+signed-in user. Every one of them needs **Grant admin consent** afterwards — a+permission added but not consented behaves exactly as if it were absent, and+Graph reports it as `Authorization_RequestDenied` rather than as anything to do+with consent.++Grant all six. The table says what each one buys so you can tell what is broken+when one is missing, not so you can pick and choose:++| Permission | Without it |+| --- | --- |+| `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)). |+| `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.+**`User.ReadBasic.All`** looks like it only matters once someone links an+account, and does not — without it, everyone in Teams is an opaque id to+Switch from the first message.++**About the RSC variant.** `ChannelMessage.Read.Group` is resource-specific+consent: scoped to the teams your app is installed in rather than tenant-wide,+and preferable where your organisation will accept it. Three consequences. It+is declared in the Teams app manifest ([1.5](#15-teams-app-package)) as well as+granted in the portal, so it is not a drop-in substitution for a checkbox. It+applies only to teams the app is installed in — so if capture works in one team+and not another, that is the first thing to check. And Microsoft blocks message+subscriptions on **private and shared** channels for apps consented this way,+answering `403`; those need the tenant-wide permission.++The shipped manifest pairs it with `ChannelSettings.Read.Group`, the RSC+equivalent of `Channel.ReadBasic.All`. Take both or neither: on the RSC route,+`ChannelSettings.Read.Group` is what lets Switch read a channel's name and+layout.++> **Teams protected APIs.** Microsoft gates change notifications carrying Teams+> message content behind a separate access request, and may attach billing to+> them. If subscriptions are refused on a tenant where the permissions above are+> plainly granted and consented, this is the likely reason — check the current+> Microsoft Graph documentation for "protected APIs for Microsoft Teams", since+> the terms have changed more than once.++> **Subscription quota.** Graph resource-data subscriptions count against a+> shared per-tenant Teams quota. A tenant already using Graph subscriptions+> heavily can hit that ceiling.++Nothing in this section is needed for the Bot Framework side. Messages that+@mention the bot arrive over the Bot Connector, authenticated by the app+registration itself, and need no Graph permission at all — which is why a+bridge with none of the above still looks half-alive.++### 1.5 Teams app package++An Azure Bot is reachable but not yet *present* in Teams. A Teams app package+puts it in a team, and without one the bot cannot be added to channels or post+proactively — so this step is a hard prerequisite for Part 4, not a formality.++Switch ships a complete one. Copy the manifest below into a `manifest.json`,+put the two icons beside it, change three values, zip the three files and+upload. The whole package is in the repository at+[`docs/bridges/teams-app/`](teams-app/) if you would rather download it than+copy it — including+[`color.png`](teams-app/color.png) and [`outline.png`](teams-app/outline.png),+which you need either way.++<details>+<summary><strong>Agent Switch app manifest</strong> (paste this)</summary>++```json+{+ "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.29/MicrosoftTeams.schema.json",+ "manifestVersion": "1.29",+ "version": "1.0.0",+ "id": "00000000-0000-0000-0000-000000000000",+ "developer": {+ "name": "Agent Switch",+ "websiteUrl": "https://github.com/sandbox-quantum/switch",+ "privacyUrl": "https://example.com/privacy",+ "termsOfUseUrl": "https://example.com/terms"+ },+ "name": {+ "short": "Agent Switch",+ "full": "Agent Switch \u2014 your AI agents, in your channels"+ },+ "description": {+ "short": "Work with your AI agents in Teams channels and chats.",+ "full": "Agent Switch puts your AI agents into Microsoft Teams. Mention an agent by name in a channel and it answers there, in the same conversation, with its progress shown on the message while it works. Each Switch room is a Teams channel, so the people and the agents share one thread of context rather than one per tool.\n\nThis app is the Teams end of a Switch deployment you run yourself. It talks only to your own Switch server: no conversation data reaches the app's authors, and there is no hosted service behind it.\n\nIn a chat, type /help. In a channel, mention the app first: @Agent Switch /help."+ },+ "icons": {+ "color": "color.png",+ "outline": "outline.png"+ },+ "accentColor": "#3F3C3B",+ "supportsChannelFeatures": "tier1",+ "bots": [+ {+ "botId": "00000000-0000-0000-0000-000000000000",+ "scopes": [+ "team",+ "personal",+ "groupChat"+ ],+ "supportsTargetedMessages": true,+ "isNotificationOnly": false,+ "supportsFiles": false,+ "commandLists": [+ {+ "scopes": [+ "team",+ "groupChat",+ "personal"+ ],+ "triggers": [+ "mention"+ ],+ "commands": [+ {+ "title": "/help",+ "description": "Show every in-room command"+ },+ {+ "title": "/list-agents",+ "description": "List the agents in this room"+ },+ {+ "title": "/agents-status",+ "description": "Show each agent's presence and capabilities"+ },+ {+ "title": "/invite-agent",+ "description": "Add an existing agent: /invite-agent @agent-name"+ },+ {+ "title": "/agents-greet",+ "description": "Have the agents here introduce themselves"+ },+ {+ "title": "/roles",+ "description": "List this room's roles and who holds each"+ },+ {+ "title": "/list-aliases",+ "description": "List this room's agent aliases"+ },+ {+ "title": "/set-alias",+ "description": "Give an agent a room alias: /set-alias @agent-name @alias"+ },+ {+ "title": "/reset",+ "description": "Reset an agent's session: /reset @agent-name"+ },+ {+ "title": "/interrupt",+ "description": "Interrupt an agent's current turn: /interrupt @agent-name"+ },+ {+ "title": "/list-switch-agents",+ "description": "List every agent on this Switch, to find one to invite"+ },+ {+ "title": "/room-url",+ "description": "Show this room's address in Switch"+ }+ ]+ },+ {+ "scopes": [+ "team",+ "groupChat",+ "personal"+ ],+ "triggers": [+ "slash"+ ],+ "commands": [+ {+ "title": "help",+ "description": "Show every in-room command"+ },+ {+ "title": "list-agents",+ "description": "List the agents in this room"+ },+ {+ "title": "agents-status",+ "description": "Show each agent's presence and capabilities"+ },+ {+ "title": "invite-agent",+ "description": "Add an existing agent: /invite-agent @agent-name"+ },+ {+ "title": "agents-greet",+ "description": "Have the agents here introduce themselves"+ },+ {+ "title": "roles",+ "description": "List this room's roles and who holds each"+ },+ {+ "title": "list-aliases",+ "description": "List this room's agent aliases"+ },+ {+ "title": "set-alias",+ "description": "Give an agent a room alias: /set-alias @agent-name @alias"+ },+ {+ "title": "reset",+ "description": "Reset an agent's session: /reset @agent-name"+ },+ {+ "title": "interrupt",+ "description": "Interrupt an agent's current turn: /interrupt @agent-name"+ },+ {+ "title": "list-switch-agents",+ "description": "List every agent on this Switch, to find one to invite"+ },+ {+ "title": "room-url",+ "description": "Show this room's address in Switch"+ }+ ]+ }+ ]+ }+ ],+ "permissions": [+ "identity",+ "messageTeamMembers"+ ],+ "validDomains": [+ "switch.example.com"+ ],+ "webApplicationInfo": {+ "id": "00000000-0000-0000-0000-000000000000",+ "resource": "https://graph.microsoft.com"+ },+ "authorization": {+ "permissions": {+ "resourceSpecific": [+ {+ "name": "ChannelMessage.Read.Group",+ "type": "Application"+ },+ {+ "name": "ChannelSettings.Read.Group",+ "type": "Application"+ }+ ]+ }+ }+}+```++</details>++**Change these before you upload:**++| In the manifest | Replace with |+| --- | --- |+| `00000000-0000-0000-0000-000000000000` — in `id`, `bots[0].botId` **and** `webApplicationInfo.id` | The `app_id` from [1.1](#11-app-registration). The same value in all three: it is what ties the Teams app, the bot and the Entra registration together. |+| `switch.example.com` in `validDomains` | The host of your `public_base_url` |+| `https://example.com/privacy` and `https://example.com/terms` | Your organisation's own privacy policy and terms. Teams requires all three `developer` URLs and does not check them on upload, so an unchanged placeholder installs fine and then tells your users the app has no privacy policy. |++**Delete the `authorization` block** unless you are taking the resource-specific+consent route for channel capture ([1.4](#14-graph-api-permissions)). RSC is+declared here as well as granted in the portal, so it is not a drop-in+substitute for the tenant-wide permission; if you granted+`ChannelMessage.Read.All` instead, this block asks the team owner to consent to+something you are not using.++**Then build the package.** Every upload route wants a `.zip` — the Developer+Portal's **Import app** included — and none of them takes a bare+`manifest.json`. From a clone of the repository:++```bash+just teams-app-package \+ --app-id 00000000-0000-0000-0000-000000000000 \+ --public-host teams.example.com \+ --privacy-url https://example.com/privacy \+ --terms-url https://example.com/terms+```++That writes `agent-switch-teams.zip`, filling the app id into all three places+for you and checking the limits Teams enforces without explaining — icon sizes,+name and description lengths, the command cap. **Pass the id rather than+editing `manifest.json`**: that file is tracked in a public repository and+ships with a placeholder deliberately, so an id typed into it is one+`git add` from being published.++**Updating an app that is already installed? Add `--bump`.** Teams matches on+`id` and ignores an upload whose `version` has not increased, without saying+so — it is the usual reason an edit appears to have done nothing. It exits non-zero and names+anything you left as a placeholder, so a null app id cannot ship quietly. Add+`--version` when you are updating an app that is already installed.++Without a clone, do it by hand — the three files must be at the **root** of the+zip, because Teams rejects a package whose contents sit inside a folder:++```bash+zip -j agent-switch-teams.zip manifest.json color.png outline.png+```++**Then get it into Teams**, whichever of these your tenant allows:++- **Sideload it** — Teams → **Apps → Manage your apps → Upload an app → Upload+ a custom app**, pick the zip, choose the team. This needs *Upload custom+ apps* on in your app setup policy (Teams admin center → **Teams apps → Setup+ policies**), and a policy change can take up to 24 hours to take effect. If+ the **Upload a custom app** option is not there, that setting is off.+- **Have an admin publish it** — Teams admin center → **Teams apps → Manage+ apps → Upload new app**. No sideloading permission needed, and it becomes+ available to the whole organisation.+- **Register it in the Developer Portal first** — `dev.teams.microsoft.com` →+ **Apps → Import app**, upload the zip. Useful if you want to edit the+ manifest in a UI afterwards, or hand the app to someone else to publish.++This is the step most likely to need someone else, which is why it is in+[Prerequisites](#prerequisites).++#### The icons++A Teams package will not install without two PNGs, and **a manifest cannot+point at an image URL** — Teams reads them from inside the zip. Both are in+[`docs/bridges/teams-app/`](teams-app/):++| File | Size | What it is || --- | --- | --- |-| `app_id` | yes | Azure AD app (bot) client id. |-| `app_password` | yes | Azure AD app client secret. |-| `tenant_id` | yes | Azure AD tenant id. |-| `team_id` | yes | AAD team (group) id that outbound-created channels go into. |-| `public_base_url` | yes | Public HTTPS base the listener is reachable at (used to build the `/api/teams/notifications` URL given to Graph). |-| `client_state` | yes | Shared secret echoed in every Graph notification and validated on receipt — the only control that authenticates a notification's origin. |-| `encryption_certificate_id` | for channel capture | Stable id for the Graph resource-data encryption cert. |-| `encryption_public_certificate` | for channel capture | PEM public certificate handed to Graph. |-| `encryption_private_key` | for channel capture | PEM private key used to decrypt message bodies. |--Switch-internal fields are **not** admin inputs and are hidden from the gateway-form:--- `listen_host` / `listen_port` (default `0.0.0.0:3978`) — the listener bind, a- deployment detail. Override via the stored `connection_config` only when- running more than one Teams bridge on a host (one bridge per listener port).+| `color.png` | 192×192 | The full-colour app icon. Square with no rounded corners: Teams masks the corners itself, so an icon that rounds its own is rounded twice. |+| `outline.png` | 32×32 | A white silhouette on transparency, for the Teams app bar. Not a shrunk logo — no colour, no padding around the symbol. |++Replace them with your own if you would rather the app carried your branding;+keep the sizes and the outline's white-on-transparent rule.++The **Azure Bot resource carries its own icon**, separately from this package.+Set it there too ([1.3](#13-azure-bot-resource) → the bot's **Settings**), or+the bot shows a default avatar in some surfaces even though the package is+branded.++#### Changing the app later++A manifest edit only reaches an installed app if you **raise `version`** and+upload again. Teams matches on `id`, so the same `id` with a higher `version`+replaces the app rather than adding a second one. Leave `version` alone and the+upload does nothing, silently — which is the usual reason a newly added command+never appears in the compose box.++Most changes then propagate on their own. Ones that alter what the app can do —+adding a bot, changing `botId`, adding RSC permissions — need each team to+consent again, and until someone does, that team keeps the old version.++Never change `id` after the app is installed. Teams would treat the upload as a+different app and you would have two.++#### Record the team id++The **team id** is the Entra group id of the team new channels are created in.+This becomes `team_id`. The simplest way to read it: open the team in Teams on+the web and copy the `groupId` query parameter from the URL.++---++## Part 2: Deployment++**This part is easy to miss, and skipping it produces a bridge that looks+healthy and silently receives nothing.** The Teams listener is the only bridge+component in Switch that needs its own network path.++### What has to be true++1. Port **3978** on the switch-core pod/container is published by a Service.+2. Something routes `/api/messages` and `/api/teams/notifications` to that+ port — **not** to port 8000, which is a different HTTP server.+3. The host is reachable **from the public internet** over HTTPS with a valid+ certificate.+4. `public_base_url` in Part 3 exactly matches that public origin.++Graph is strict about (3): when you create a subscription it immediately sends+`POST <your notification URL>?validationToken=…` and expects the decoded token+echoed back as `text/plain` **within 10 seconds**, over TLS it trusts. A+self-signed ingress certificate, a redirect, or an auth proxy in front will all+fail that handshake.++### Helm++The chart publishes the listener only when you ask it to, because bridges are+created at runtime in the gateway — the chart cannot tell whether you have a+Teams bridge. Enabling it takes two decisions, not one: the port, and how+Microsoft reaches it.++```yaml+switchCore:+ teamsBridge:+ enabled: true # publishes containerPort + Service port+ port: 3978 # must match the bridge's listen_port (see Part 3)+ ingress:+ mode: dedicated # dedicated | shared | external — required when enabled+```++`mode` has no default, because none of the three is a safe guess. Leaving it+unset **fails the render** rather than deploying a listener nothing can reach:++```+switchCore.teamsBridge.enabled is true but switchCore.teamsBridge.ingress.mode+is unset. Microsoft calls the Teams listener from the public internet, so+publishing the port is only half the job — choose how the two callback paths+are routed: ...+```++A mode set while `enabled: false` fails the same way — nothing publishes the+port for it to route to — as does any value outside the three below.++**`mode: dedicated` — the chart renders a second Ingress.** Recommended.+`<release>-teams` carries only the two callback paths, on its own host, class,+annotations and TLS:++```yaml+switchCore:+ teamsBridge:+ enabled: true+ ingress:+ mode: dedicated+ className: nginx+ host: teams.example.com # must match the host in public_base_url+ annotations:+ cert-manager.io/cluster-issuer: letsencrypt-prod+ tls:+ enabled: true+ secretName: teams-tls+```++It renders **regardless of the chart's top-level `ingress.mode`**, including+`existing`, where the+chart renders no other Ingress at all — and that is the point. Microsoft needs+those two paths and nothing else, and the adapter authenticates every request+itself, so the gateway and agent API can stay internal while only these are+public. The main Ingress's nginx streaming annotations are deliberately **not**+applied here: Teams callbacks are short request/response, not long-lived+streams.++**Behind a CDN or reverse proxy, leave `host` empty and TLS off.** This is the+option to reach for when you have no domain to hand — a CDN in front of the load+balancer gives you a public HTTPS name and a trusted certificate with no DNS+work at all:++```yaml+switchCore:+ teamsBridge:+ enabled: true+ ingress:+ mode: dedicated+ className: alb+ annotations:+ alb.ingress.kubernetes.io/scheme: internet-facing+ alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}]'+ alb.ingress.kubernetes.io/target-type: ip+ tls:+ enabled: false # the CDN terminates TLS, not this Ingress+```++The rule then carries no host and answers whatever `Host` header arrives, which+is required: the incoming Host is the CDN's name, and the chart cannot know it.+`public_base_url` is the CDN's name, not this Ingress's.++**Three things the CDN must do**, or the bridge fails in ways that look+unrelated: allow `POST`, forward query strings, and **not cache**. All three are+the same requirement seen from different angles — Graph validates every new+subscription with `POST …?validationToken=…`, so the token rides on the query+string of a POST, and a cached or stripped answer fails the handshake. On+CloudFront that is the `Managed-AllViewer` origin-request policy and the+`Managed-CachingDisabled` cache policy, with all HTTP methods allowed.++Note the trade: with an HTTP origin, anyone who learns the load balancer's own+hostname can reach these paths directly, bypassing the CDN. That is tolerable+here only because the adapter authenticates every request itself.++Empty `host` with `tls.enabled: true` is rejected — a host-less rule cannot+carry a certificate.++**`mode: shared` — the paths go on the chart's main Ingress,** putting Teams on+the same public host as the gateway. That Ingress has to exist and to have a+real hostname, so `ingress.mode: managed` and a non-empty `ingress.host` are+both required:++```yaml+ingress:+ mode: managed+ host: switch.example.com+switchCore:+ teamsBridge:+ enabled: true+ ingress:+ mode: shared+```++Otherwise:++```+switchCore.teamsBridge.ingress.mode is "shared" but ingress.mode is "existing":+there is no chart-managed Ingress to add the Teams paths to.+```++**`mode: external` — the chart renders no route.** Enabling the bridge still+publishes the Service port, but you add the two paths to your own manifest:++```yaml+- path: /api/messages+ pathType: Prefix+ backend: { service: { name: RELEASE-switch-core, port: { number: 3978 } } }+- path: /api/teams/notifications+ pathType: Prefix+ backend: { service: { name: RELEASE-switch-core, port: { number: 3978 } } }+```++See [`samples/ingress.example.yaml`](../../deploy/remote/helm/switch/samples/ingress.example.yaml)+for the full manifest.++**TLS is on by default, and warns rather than fails.**+`switchCore.teamsBridge.ingress.tls.enabled` defaults to `true`, because Graph+calls only an HTTPS URL whose certificate it trusts. Setting it `false` is *not*+an error: TLS may terminate upstream where the chart cannot see it — an AWS ALB+configured by annotation, say — so the install output warns instead:++```text+Set the bridge's public_base_url to exactly:++ https://teams.example.com++⚠ https, even though TLS is disabled on this Ingress — Graph refuses a+ plaintext URL, so that host has to be served over HTTPS by something in+ front (a CDN, or a load balancer configured by annotation). If nothing is,+ the bridge will create channels and then silently receive nothing.+```++**Both of those only happen when the chart knows the public origin** — that is,+`dedicated` with a `host`, or `shared`. Then the install output prints the exact+value to paste into `public_base_url` in Part 3, always as `https`: `tls.enabled`+governs whether *this Ingress* carries the certificate, not what Microsoft+dials, and Graph refuses plaintext either way.++Under `external`, or the CDN shape above (`dedicated` with an empty `host`), the+public name belongs to something in front, so the chart neither prints an origin+nor warns about its TLS. **Nothing will tell you that origin is unreachable or+plaintext** — verifying it is on you, and [Part 4](#part-4-verify) step 4 is how.++### Checking it with `helm test`++`helm test <release>` runs `<release>-teams-listener-test`, a pod that probes+the notification path through the Service and requires a `validationToken` to+come back echoed verbatim.++It sends a GET, where Graph sends a POST, because the same handler answers both+and a GET is what a probe can express. So it exercises the handshake's shape+rather than reproducing it: enough to prove the listener is bound inside the pod+and the Service publishes its port, and no more.++**It cannot prove Microsoft can reach you.** It runs inside the cluster, so it+says nothing about public DNS, ingress routing or certificate trust, which is+exactly where this usually fails; the external `curl` in+[Part 4](#part-4-verify) step 4 remains the real check.++**Run it after registering the bridge, not before.** The chart publishes the+port; only a configured Teams bridge starts a listener behind it. Enabling+`teamsBridge` necessarily comes first — the bridge's `public_base_url` is the+address that enabling it produces — so between the two there is a window where+this test fails and nothing is wrong. Its output says so.++A failure *after* the bridge exists means the listener never started: look for+`Teams adapter listening on` in the switch-core logs, and note that a second+Teams bridge on the same port will keep it from binding.++### Running more than one Teams bridge++**One Teams bridge per listener port, and Switch enforces it.** Registering a+second bridge on a port another one already uses is refused, naming the bridge+that holds it:++```+'Contoso Teams' already uses tcp/3978 on this instance, and two teams+bridges cannot share it. Delete that bridge first, or give this one a+different listen_port in its connection_config …+```++That refusal exists because the alternative is worse: two adapters racing for+one port means the loser fails to bind inside a background task, gets dropped+from the running set, and is never retried. The only symptom is+`Bridge not running: <id>` the next time you use it — nowhere near the cause.++A genuinely separate second bridge needs a distinct `listen_port`, **plus its+own Service port and ingress route**. The chart publishes only one Teams port,+so the second is yours to wire by hand.++`listen_port` is not on the registration form, and **a bridge's+`connection_config` cannot be edited after it is created** — the dashboard's+update endpoint carries only the greeting and channel-creation toggles. So it+has to go in at creation time, through the API rather than the form:++```bash+curl -X POST "https://<gateway-host>/gateway/collaboration-bridges" \+ -H "Authorization: Bearer <admin token>" \+ -H "Content-Type: application/json" \+ -d '{"bridge_type": "teams", "display_name": "Second Teams",+ "connection_config": {"app_id": "…", "app_password": "…",+ "tenant_id": "…", "team_id": "…",+ "public_base_url": "https://teams2.example.com",+ "listen_port": 3979}}'+```++Getting it wrong means deleting the bridge and creating it again. Consider+whether you need a second at all: one Azure app can serve one tenant's team, and+most deployments want exactly one.++---++## Part 3: Onboard the bridge in Switch++As a Switch administrator: **Messaging Apps → Register messaging app → Teams**,+give it+a display name (e.g. "Acme Teams"), and fill in the fields.++There are five. Four are values Azure gave you in Part 1; the fifth is the+listener's public origin you settled on in Part 2.++| Field | Value | From |+| --- | --- | --- |+| `app_id` | Application (client) ID | 1.1 |+| `app_password` | Client secret **Value** — not the Secret ID | 1.2 |+| `tenant_id` | Directory (tenant) ID | 1.1 |+| `team_id` | Entra group id of the team new channels go into | 1.5 |+| `public_base_url` | Public HTTPS origin **of the listener** — scheme + host, no path. Under `mode: dedicated` that is the Teams host (`https://teams.example.com`), not the dashboard's; a Helm install prints the exact value to use | Part 2 |++Alongside them the dialog carries a display name and an **Allow creating+channels from Switch** toggle, on by default. Leave it on unless you want rooms+to be bound only to channels that already exist — with it off, adding a room+that would provision a channel is refused, and the refusal says so.++**Switch checks these before saving.** It requests both Azure tokens the bridge+needs, and if Microsoft refuses, the form fails with Microsoft's own+explanation instead of accepting the values and going quiet. So a wrong secret+is a red message in front of you, not a mystery hours later.++Note what that check can and cannot tell you: a token proves the credentials+are good, not that the app may *do* anything. Permissions are only tested when+Graph is first called, which is why a bridge can save cleanly and then fail on+its first room — see [1.4](#14-graph-api-permissions).++That also means creating a bridge requires Switch to reach+`login.microsoftonline.com`. On a restricted network, allow that egress first.++Everything else is generated or learned, and hidden from the form:++- `client_state` — the shared secret echoed in every Graph notification and+ validated on receipt. Minted per bridge; there is nothing to invent.+- The **encryption trio** Graph resource-data notifications are encrypted to —+ generated per bridge, so channel capture works out of the box rather than+ only once someone pastes three PEMs correctly. Supplying your own through the+ API still wins, all three or none; rotating means re-creating the bridge.+- `listen_host` / `listen_port` (default `0.0.0.0:3978`) — the listener bind.+ A deployment detail, and only worth changing to run more than one Teams bridge+ on a host. Because it cannot be edited later, it has to be passed at creation+ through the API — see+ [Running more than one Teams bridge](#running-more-than-one-teams-bridge).- `service_url` — the Bot Connector outbound endpoint, learned at runtime frominbound activities and persisted automatically.-Without the three encryption fields the bridge still runs (outbound, chats, and-`@mention` capture work), but per-channel Graph subscriptions are skipped and an-error is logged — **full channel capture is disabled until they are supplied**.+**A bridge registered before Switch started generating this material keeps+whatever it was given** — which for an older one is no encryption material at+all, in which case channel capture stays off and an error is logged. You can+tell from its detail page: an empty `encryption_certificate_id` is the sign.+Credentials cannot be edited, so adopting the generated ones means deleting the+bridge and creating it again.++### Bringing Switch into a channel that already exists++A room does not have to bring a new channel with it. Adding a room to the+bridge normally provisions one, but you can instead point the room at a channel+where a conversation is already happening.++**There is no per-channel install step.** Installing the app into a team+([1.5](#15-teams-app-package)) makes the bot available in every **standard**+channel of that team at once — you do not add it channel by channel, and there+is no "add app to this channel" button to look for. Private and shared channels+are the exception: each one needs the app added to it explicitly.++#### 1. Get the channel's id++The channel's Switch-side id is its Teams thread id, of the form+`19:…@thread.tacv2`. To read it: **right-click the channel in Teams → Get link+to channel**, and take the first path segment of the URL.++```+https://teams.microsoft.com/l/channel/19%3Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa%40thread.tacv2/My%20channel?groupId=…&tenantId=…+ └──────────────── the channel id, URL-encoded ─────────────────┘+```++**URL-decode it before you paste it in**: `%3A` is `:` and `%40` is `@`, so the+example above is `19:[email protected]`. The+`groupId` in the same URL is the team id from [1.5](#15-teams-app-package) —+useful confirmation that the channel is in the team the bridge points at.++#### 2. Bind a room to it++In the dashboard: **Rooms → Create room**, pick this Teams connection as the+room's messaging app, choose **Use existing channel** rather than *Create new+channel*, and paste the id into **External channel ID**. Switch detects whether+the channel is standard or private itself.++Two things differ from the provisioning path, and both have bitten people:++- **Switch reads the channel** to learn whether it is standard or private,+ because membership is granted differently for each. That read needs+ `Channel.ReadBasic.All` ([1.4](#14-graph-api-permissions)), which the+ provisioning path never uses — so a bridge that has been creating channels+ happily for weeks can fail the first time you adopt one.+- **Capture is set up when the room is bound**, the same as for a channel+ Switch created. If the notification endpoint is unreachable at that moment+ the subscription fails, and the bridge retries in the background rather than+ giving up — see [Troubleshooting](#troubleshooting).++Switch posts a short notice in the channel once the room is linked, which is+also your confirmation that outbound works.++#### 3. Say something to an agent++Add an agent to the room and `@`-mention it by name in the channel.++Whether the bot needs mentioning depends on capture. Without Graph channel+capture, Teams only delivers a channel message to a bot that was+`@mentioned` — that is the platform's rule, not Switch's — so both messages and+bare commands need it. With capture live ([1.4](#14-graph-api-permissions)) the+bridge sees every message in the channel, and a bare `!help` works. Mentioning+an *agent* by name is separate, and is always how you address one.++#### Private and shared channels++These work differently enough to plan around. Three things, in the order they+bite:++- **The app can be added to them, but has not been proven in them.** The+ manifest declares `"supportsChannelFeatures": "tier1"`, which is what makes+ Teams offer it in a private or shared channel's **Add an app** list. That is+ not a choice: Teams **requires** the property of any manifest at schema v1.25+ or later whose bot takes the `team` scope, and refuses the upload without it.+ Read the declaration as "allowed here", not as "tested here" — the next two+ points still hold.+- **Each one needs the app added to it.** Installing into the team covers every+ standard channel and no private or shared one. If Graph returns+ `403 app not enabled in this channel`, that is the missing step.+- **Graph channel capture does not work there over RSC.** Microsoft blocks+ message subscriptions on private and shared channels for apps consented that+ way, and answers `403`. If you need full capture in one, grant tenant-wide+ `ChannelMessage.Read.All` ([1.4](#14-graph-api-permissions)) instead of the+ RSC variant. Otherwise the channel falls back to `@mention`-only capture,+ which still works.++A channel shared *into* your team from elsewhere cannot have apps added from+where you see it — go to the team that hosts it.++---++## Part 4: Verify++Do these in order. Each one isolates a different failure.++**1. The listener started.** In the switch-core logs:++```+Teams adapter listening on 0.0.0.0:3978 (app <your app id>)+```++**2. Credentials work.** Still at startup, you should *not* see:++```+Could not list existing Graph subscriptions on start+```++That warning means the very first Graph call failed — almost always the client+secret, occasionally missing admin consent. Fix it before going further; every+later step depends on this call working.++**3. The listener is reachable in-cluster.** On a Helm install, `helm test+<release>` answers this without leaving the cluster — see+[above](#checking-it-with-helm-test). Skip to step 4 if it passes; if it fails,+the problem is the pod or the Service, not your ingress.++**4. The listener is publicly reachable.** From outside your network — a phone+on mobile data is a good check, since it cannot be on your VPN:++```bash+curl -i "https://<your-public-host>/api/teams/notifications?validationToken=ping"+```++Use the host from `public_base_url`, which under `mode: dedicated` is the Teams+host rather than the dashboard's. Expect `200` with `ping` echoed back as+`text/plain`. A 404 means the path is missing or pointed at port 8000; a timeout+or DNS error means it is not public. **This is the step `helm test` cannot do+for you, and the one that most often fails.**++**5. Provisioning works.** In the dashboard, **Rooms → Create room**, pick this+Teams connection and leave **Create new channel** selected. A matching+channel should appear in the target team within a second or two.++**6. Capture works.** Post in that channel from Teams and confirm it reaches the+Switch room. If `@mentions` arrive but ordinary messages do not, Graph+subscriptions are failing while Bot Framework is fine — check step 4 and the+encryption fields.++Note that steps 5 and 6 fail independently: provisioning is outbound and needs+only working credentials, while capture needs the public route. A bridge that+passes 5 and fails 6 is the signature of unreachable ingress.++**7. An agent posts back.** Add an agent to the room and address it from the+channel. Its reply should arrive as a card headed with the agent's name and+avatar, under the post you asked in. This is the one step that exercises the+outbound path end to end, and the first thing that fails if the bridge has+never accepted an inbound activity — see the `serviceUrl` entry in+[Troubleshooting](#troubleshooting).++---++## How agents use threads++Teams offers a channel two conversation layouts, and Switch behaves differently+in each. Nothing here is configurable: the bridge asks Graph which layout a+channel uses and follows it. Channel owners choose the layout in Teams: hover the channel, then+**More options (…) → Edit channel → Conversation layout**. If the option is+not there, a tenant administrator has turned the threads layout off org-wide+(**Teams admin center → Settings & policies → Teams and channels**).++**Threads layout** (Graph calls it `chat`) is a stream of messages, like every+other platform Switch bridges. Agents behave as they do on Slack:++- An agent decides whether to reply in a thread. A reply to something said in a+ thread stays in that thread; anything else goes to the channel.+- The notice Switch posts when it links a channel to a room goes to the+ channel, not into a thread.+- A working agent's status card sits wherever the message that triggered it+ was — in the thread if it was asked there, at the channel level if it was+ asked there.++**Posts layout** (Graph calls it `post`) is a list of conversations, where a+message at the channel level starts a new one rather than continuing the last.+Answering there needs steering, or a reply appears as a fresh post below the+question and reads as a non-sequitur. So:++- An agent's reply lands in the post containing the message it is answering,+ whether or not the agent chose to thread it.+- With nothing to answer — an agent introducing itself, say — it lands in the+ post the channel last spoke in, or opens one if the bridge has not yet seen+ this channel speak. What it says after that joins the same post rather than+ starting another.+- A post an *agent* opened never displaces a real message as the one later+ answers land in.+- **A working agent's status is posted once, stays where it is, and is edited+ to `✓ Done` when the turn ends.** It is never deleted, because Teams replaces+ a deleted message with *"This message has been deleted."* and keeps it in the+ post — so a status that vanished each turn would leave one of those behind+ every time, and another every time it moved. In a threads-layout channel a+ delete is clean, so there the status disappears and follows the conversation+ as it does on every other platform.++If Switch cannot read a channel's layout — Graph refusing the read is the usual+reason — it assumes posts. That is Graph's own default for a channel it+creates, and what every channel was before the threads layout existed. Note it+is no longer what the Teams client picks for a new one.++---++## Commands++Both `!list-agents` and `/list-agents` work, and reach the same place. `!help`+lists every command Switch understands.++**Whether a channel command needs the bot mentioned depends on capture**, and+this is the one thing people get wrong:++- **With Graph channel capture live** ([1.4](#14-graph-api-permissions)), the+ bridge sees every message in the channel, so a bare `!list-agents` works.+- **Without it**, Teams only delivers a channel message to a bot that was+ `@mentioned` — the platform's rule, not Switch's — so the command must carry+ the mention:++ ```text+ @Agent Switch /list-agents+ ```++ The mention is stripped before the command is parsed, so+ `@Agent Switch /help`, `@Agent Switch !invite-agent @agent-name` and the rest+ behave as they do elsewhere.++In a 1:1 chat no mention is ever needed.++### Putting the commands in the Teams UI++Teams has no server-registered slash commands the way Slack does. What it has+is a **command list**, declared in the app manifest, which shows the commands+in the bot's own menu; picking one types it into the compose box. The manifest+in [1.5](#15-teams-app-package) already carries one, so if you used it there is+nothing to do here.++Three things to know if you are editing it.++**A title is inserted verbatim** in the mention menu — Teams prepends nothing+there, which is why those titles carry their `/`. The `/` picker is the+opposite: it prepends the slash and inserts the bare name. Keep each list+spelled for its own surface.++**The list is presentation only.** Teams types the text and Switch parses it,+so a command missing from the manifest still works if someone types it, and a+command in the manifest that Switch does not know returns the usual "unknown+command".++**Teams caps a command list at twelve commands** per scope (ten before schema+v1.25), which is why the shipped one is a selection rather than all of them.+Swap in whichever twelve your teams actually use; `!help` lists the rest.++**The commands appear twice, spelled differently, and that is deliberate.**+Teams has two surfaces and they disagree about the slash:++- The **`/` autocomplete picker**, the one you get by typing `/` in the compose+ box. It prints the slash itself and inserts the *bare* name, so those titles+ are declared without one. `supportsTargetedMessages` on the bot is what puts+ Switch in that picker at all; `triggers: ["slash"]` is what puts individual+ commands there.+- The **bot's own command menu**, reached by mentioning it. That inserts a+ title verbatim, so those titles keep their `/`.++A title with a slash in the picker would read `//help`, and a title without one+in the mention menu would insert `help`, which is a word rather than a command.+Hence two lists with the same commands.++Picking from the `/` picker also sends the message **privately to Switch** —+other people in the channel do not see it, and no `@`-mention is needed. It+works in channels, group chats and meeting chats, but not in a 1:1 chat, where+you can simply type the command.++If the menu does not appear after you edit it, the manifest almost certainly+reached nobody: an edit only lands if you raise `version` and upload again —+see [Changing the app later](#changing-the-app-later).++`!` remains available everywhere and needs no manifest at all.++---++## Clickable "Open in Switch Console" links (`GATEWAY_PUBLIC_URL`)++Teams renders only `http(s)` links, and it does not merely leave others as+plain text: it **strips the whole link, label included**, so a raw+`switchdash://session?…` deeplink arrives as empty brackets. Set+**`GATEWAY_PUBLIC_URL`** on switch-core to the Switch API's public origin —+scheme + host only, **no path**:++```dotenv+# .env / deployment env+GATEWAY_PUBLIC_URL=https://switch-api.example.com+```++Switch then posts `https://<switch-api-host>/deeplink/session?…` instead, a+page that opens Switch Console and then tries to close itself. The bridge logs+a warning at startup when Teams is running without this set.++Two Teams-specific notes:++- This is the **Switch API** host, not the Teams listener host and not the+ dashboard. It has to be reachable from wherever people click the link.+- Microsoft Defender for Office 365 may rewrite the link through **Safe Links**,+ which adds an interstitial before your page. That is expected. If the tab is+ left on "Verifying link…" after Switch Console has opened, it is a stale+ deployment — the handoff page replaced a bare redirect precisely because a+ redirect left that interstitial on screen.++---++## Troubleshooting++Symptoms as they actually appear, and what each one means.++#### `AADSTS7000215: Invalid client secret provided`, when saving the bridge++The `app_password` is the secret **ID** instead of the secret **value**, or the+secret has expired. Create a new secret and use the Value column. See 1.2.++#### `Could not list existing Graph subscriptions on start` (at startup)++The first Graph call failed — missing admin consent on the Graph permissions, or+a secret that expired after the bridge was created. The bridge starts anyway and+fails at the first real operation. Credentials are verified when the bridge is+saved, so a typo would have been caught then: this is consent or expiry.++#### Adding a room to the bridge returns an error++Channel provisioning called Graph and Graph refused. The switch-core logs carry+the reason; look for `create channel '<name>' in team <id> failed (<status>)`.+Common causes: bad or expired secret; `Channel.Create` missing or unconsented;+wrong `team_id`; the Teams app not installed in that team.++#### `Failed to create Graph subscription for channel <id> (…); capture is degraded and will be retried`++Channel provisioning succeeded but capture setup did not, so the channel exists+and only `@mentions` arrive. Usually the notification URL is not publicly+reachable ([Part 2](#part-2-deployment)), or its TLS is not trusted. Read the+reason on the same line — Graph says which it was.++The bridge keeps retrying, backing off to every few minutes, so a cause that+clears on its own needs no intervention: the two common ones are a load+balancer that has not yet started serving a newly-started pod, and a Graph+permission consented after the bridge was running (see below). Recovery is+logged as `Capture recovered for Teams channel <id> messages (subscription+<sub-id>)`. Repeats of an unchanged+failure are logged at debug to keep the log readable, but a **change** in the+reason is logged — that is the interesting event.++#### Still failing on a permission you have already granted++An app's Graph roles are fixed when its access token is issued, and tokens last+about an hour, so consent granted while the bridge is running does nothing+until the token is replaced. Switch handles this: a Graph call refused with+`401` or `403` throws the cached token away and tries once more with a freshly+minted one, so a grant takes effect on the next attempt rather than at the next+restart. If a refusal persists past that, the permission really is missing or+unconsented — check 1.4.++#### `Failed to resolve domain <host>: No such host is known` (inside that error)++`public_base_url` points at a name Microsoft cannot resolve. A Tailscale or+other VPN-internal hostname does this: it resolves for you and not for them, so+Graph rejects the subscription before ever sending traffic. It must be public+DNS.++#### `Failed to create Graph subscription for channel <id> (encryption certificate not configured on the Teams bridge)`++The same log line as above, with a different reason in the brackets: the bridge+has no encryption material — an older bridge registered before Switch generated+it, or one deliberately registered without it. There is no way to add it to an+existing bridge; delete and re-create. Retrying will not help this one, and the+retry cannot tell.++#### `no Bot Connector serviceUrl known for channel <id> — the bot has not yet received an activity from this tenant`++An agent tried to post into Teams and could not. This looks like an outbound+fault and is not: the address Switch posts to is per-tenant and Microsoft only+ever hands it over inside an *inbound* activity, which is then persisted. If+nothing has ever reached the listener, there is nothing to send to. **Fix+inbound and outbound starts working too** — no separate action.++#### `Rejected inbound Teams activity: … addressed to app id '<x>', but this bridge is configured with app id '<y>'` (with a `401` on `POST /api/messages`)++Microsoft is reaching the listener — the public route is fine — and the activity+is signed by a genuine Bot Connector token, but for a different bot. The Azure+Bot resource's **Microsoft App ID** is not the app registration the bridge was+registered with. See 1.3. Nothing in the outbound direction notices, because+Graph runs on the registered id, so channel creation keeps working throughout.++Worth knowing when you fix it: the bridge learns its outbound address from the+first *accepted* inbound activity, so until one gets past this, agents cannot+reply either — see the `serviceUrl` entry above.++#### Bot creates channels, but nothing from Teams ever arrives, and agents cannot reply either++The classic symptom of no public route to 3978, and the reason it is confusing+is above: channel creation is Graph (outbound, works) while both message+directions depend on the listener. Work through [Part 2](#part-2-deployment),+then Part 4 step 4. On a Helm install with `teamsBridge.ingress.mode` set to+`dedicated` or `shared` the route exists by construction, so look instead at DNS,+TLS trust, or an auth proxy in front.++#### `Bridge not running: <bridge id>`, when adding a room++The bridge crashed during startup and was dropped; it is not retried until+switch-core restarts. Look for `Bridge <id> crashed` in the logs.++On Teams the classic cause was `address already in use` on 3978 — a second Teams+bridge cannot bind the same port. That is now caught before it happens, both at+registration and again at startup, so instead of a bind error you get a message+naming the bridge that holds the port. Delete the duplicate and restart+switch-core to bring the survivor up.++#### `Authorization_RequestDenied` from Graph++A permission is present but not admin-consented, or you granted a delegated+permission where an application permission is required. See 1.4.++#### Nobody can link their account: the people search errors, or says the person does not exist right after you picked them from the list++Directory search reads `User.ReadBasic.All` — see [1.4](#14-graph-api-permissions).+Without it the search fails outright, and the message names neither the+permission nor Graph. Until someone is linked, an agent has no way to @-mention+its owner, so this reads as "the agent ignores me" rather than as a setup step+left undone.++---## Security noteGraph resource-data encryption proves message **integrity, not origin** (thewrapping key is the public certificate, which anyone can encrypt to). The`clientState` shared secret is therefore **required** and validated on every-notification. Inbound Bot Framework activities are separately authenticated by+notification.++That is also why Switch generating its own keypair costs nothing: the+certificate is pure key transport, and Microsoft never validates it against a+trust store, checks an issuer or cares who signed it. There is no party for a CA+to vouch to. Inbound Bot Framework activities are separately authenticated byverifying the Bot Connector JWT.-## Known limitations / follow-ups+Because `/api/messages` and `/api/teams/notifications` are exposed publicly,+both are unauthenticated at the network layer by necessity — authentication+happens inside the adapter, per request. Do not put an auth proxy in front of+them; Microsoft cannot satisfy it, and Graph's validation handshake will fail.++---++## Known limitations-- **Switch-initiated DM rooms** are user-initiated (as on Mattermost);- bootstrapping one bot-side needs proactive app installation via Graph.-- **Attachments** (inbound media and outbound files) are currently **disclosed,- not relayed** — the text bridges and a note names the un-relayed media.-- **Real outbound `@mentions`** are not yet emitted (needs a display-name → AAD- id directory); mention text bridges as plain `@name`.+- **A DM has to be started from Teams** (as on Mattermost). Switch cannot open+ one; doing it bot-side would need proactive app installation via Graph.+- **Attachments are disclosed, not relayed.** The message text is bridged, and+ a note names the media that did not come with it.+- **An `@mention` only becomes a real mention for someone Switch can address.**+ That means a person who has linked their Teams account+ ([Part 3](#part-3-onboard-the-bridge-in-switch)) and whose directory id+ Switch therefore holds. Everyone else — and every agent, which is not a Teams+ user at all — renders as plain `@name` text, which is what Switch's own+ addressing matches on.+- **In a posts channel, a reply with no thread of its own lands in the post the+ channel last spoke in.** See [How agents use threads](#how-agents-use-threads)+ — right almost always, and wrong when two conversations run in one posts+ channel at the same moment. Teams offers nothing better to key on for a reply+ that is not explicitly threaded.+- **Private and shared channels need a newer manifest** than the one shipped,+ and cannot use resource-specific consent for channel capture. See+ [Private and shared channels](#private-and-shared-channels).- **One Teams bridge per listener port** — run multiple on distinct ports (andingress routes) if needed.diff --git a/docs/bridges/TELEGRAM_SETUP.md b/docs/bridges/TELEGRAM_SETUP.mdindex c8b384838..6a707fb73 100644--- a/docs/bridges/TELEGRAM_SETUP.md+++ b/docs/bridges/TELEGRAM_SETUP.md@@ -217,8 +217,8 @@ GATEWAY_PUBLIC_URL=https://switch-api.acme.com```When set, Switch rewrites the deeplink to a clickable-`https://<switch-api-host>/deeplink/session?…` redirect (a `302` back to the-`switchdash://` scheme) at runtime-state ingestion — so both the bridged+`https://<switch-api-host>/deeplink/session?…` link (a page that hands off to+the `switchdash://` scheme) at runtime-state ingestion — so both the bridgedworking/awaiting-input status message **and** the `!status` command surface aclickable link. When unset, the address is posted as a code span — visible andtap-to-copy, and disclosed as the fallback it is.diff --git a/docs/bridges/teams-app/README.md b/docs/bridges/teams-app/README.mdnew file mode 100644index 000000000..b3466adc1--- /dev/null+++ b/docs/bridges/teams-app/README.md@@ -0,0 +1,91 @@+# Agent Switch — Teams app package++The three files beside this one are a complete Microsoft Teams app package.+Zip them, upload the zip, and the Switch bot exists in your tenant with the+Switch name, icons and command menu already set.++- `manifest.json` — the app definition+- `color.png` — 192×192 full-colour icon+- `outline.png` — 32×32 white-on-transparent icon for the Teams app bar++Teams reads icons from inside the package; a manifest cannot point at an image+URL. That is why they are committed here rather than described.++## Use it++**Do not edit this file to put your app id in it.** It is tracked in a public+repository; pass `--app-id` to the builder below and it fills all three places+without touching the file. The table is here for the by-hand path.++**1. Replace the placeholders.**++| Placeholder | Replace with |+| --- | --- |+| `00000000-0000-0000-0000-000000000000` (3 places: `id`, `bots[0].botId`, `webApplicationInfo.id`) | Your Azure Bot's app id — the `app_id` from [TEAMS_SETUP.md §1.1](../TEAMS_SETUP.md#11-app-registration). The same value in all three. |+| `switch.example.com` in `validDomains` | The host of your `public_base_url` |+| `https://example.com/privacy` and `https://example.com/terms` | Your organisation's privacy policy and terms. Teams does not check them on upload, so leaving these installs fine and then tells your users the app has no privacy policy. |++**2. Decide about the `authorization` block.** It asks for resource-specific+consent to read channel messages and settings, scoped to the team the app is+installed in. **Delete it** unless you are taking that route — if you granted+tenant-wide Graph permissions in Entra instead, it asks every team owner to+consent to something the deployment does not use. See+[§1.4](../TEAMS_SETUP.md#14-graph-api-permissions) for the two routes.++**3. Build the zip.** From the repository root:++```bash+just teams-app-package --app-id <your-app-id> --public-host <your-host>+```++That does steps 1 and 2 for you as well — the app id goes into all three+places, and it refuses to pretend a placeholder is a real value. Or by hand,+from this directory:++```bash+zip -j agent-switch-teams.zip manifest.json color.png outline.png+```++`-j` matters. The three files must sit at the root of the zip — Teams rejects a+package whose contents are inside a folder.++**4. Upload it**, as described in+[TEAMS_SETUP.md §1.5](../TEAMS_SETUP.md#15-teams-app-package).++## Changing it later++A manifest edit only reaches an installed app if you **raise `version`** and+upload again. Teams matches on `id`, so the same `id` with a higher `version`+replaces the app rather than adding a second one. Leave `version` alone and+nothing happens, silently.++Never change `id` after the app is installed: Teams would treat the upload as a+different app.++## What the manifest asks for++- **Scopes** `team`, `personal` and `groupChat` — Switch bridges channels, 1:1+ chats and group chats.+- **`commandLists`** — the ten commands Teams offers in the bot's menu. Each+ title carries its `/` because Teams types the title verbatim and prepends+ nothing; without it the command arrives as an ordinary message. The menu is+ presentation only, so a command missing here still works if someone types it.+ Ten is the platform's limit per scope, not ours; `!help` lists them all.+- **`authorization.permissions.resourceSpecific`** — the resource-specific+ consent route for reading channel messages and channel settings, scoped to+ the team the app is installed in. Delete it if you granted tenant-wide Graph+ permissions in Entra instead; see+ [§1.4](../TEAMS_SETUP.md#14-graph-api-permissions) for the two routes.+- **`supportsFiles: false`** — Switch does not yet relay files inbound from+ Teams, and says so on the message rather than dropping them quietly.++## Where the icons came from++`color.png` is the Switch Console app icon's mark and palette, redrawn as a+flat 192×192 square: Teams masks the corners itself, so a package icon must not+round its own. `outline.png` is the same mark in white on transparency, which+is what the Teams app bar expects. Both derive from+`gateway/public/switch_logo_light.svg`.++The Azure Bot resource carries its **own** icon, separately from this package.+Set it there too, or the bot shows a default avatar in some surfaces.diff --git a/docs/bridges/teams-app/color.png b/docs/bridges/teams-app/color.pngnew file mode 100644index 000000000..6495f519dBinary files /dev/null and b/docs/bridges/teams-app/color.png differdiff --git a/docs/bridges/teams-app/manifest.json b/docs/bridges/teams-app/manifest.jsonnew file mode 100644index 000000000..d821660c3--- /dev/null+++ b/docs/bridges/teams-app/manifest.json@@ -0,0 +1,186 @@+{+ "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.29/MicrosoftTeams.schema.json",+ "manifestVersion": "1.29",+ "version": "1.0.0",+ "id": "00000000-0000-0000-0000-000000000000",+ "developer": {+ "name": "Agent Switch",+ "websiteUrl": "https://github.com/sandbox-quantum/switch",+ "privacyUrl": "https://example.com/privacy",+ "termsOfUseUrl": "https://example.com/terms"+ },+ "name": {+ "short": "Agent Switch",+ "full": "Agent Switch \u2014 your AI agents, in your channels"+ },+ "description": {+ "short": "Work with your AI agents in Teams channels and chats.",+ "full": "Agent Switch puts your AI agents into Microsoft Teams. Mention an agent by name in a channel and it answers there, in the same conversation, with its progress shown on the message while it works. Each Switch room is a Teams channel, so the people and the agents share one thread of context rather than one per tool.\n\nThis app is the Teams end of a Switch deployment you run yourself. It talks only to your own Switch server: no conversation data reaches the app's authors, and there is no hosted service behind it.\n\nIn a chat, type /help. In a channel, mention the app first: @Agent Switch /help."+ },+ "icons": {+ "color": "color.png",+ "outline": "outline.png"+ },+ "accentColor": "#3F3C3B",+ "supportsChannelFeatures": "tier1",+ "bots": [+ {+ "botId": "00000000-0000-0000-0000-000000000000",+ "scopes": [+ "team",+ "personal",+ "groupChat"+ ],+ "supportsTargetedMessages": true,+ "isNotificationOnly": false,+ "supportsFiles": false,+ "commandLists": [+ {+ "scopes": [+ "team",+ "groupChat",+ "personal"+ ],+ "triggers": [+ "mention"+ ],+ "commands": [+ {+ "title": "/help",+ "description": "Show every in-room command"+ },+ {+ "title": "/list-agents",+ "description": "List the agents in this room"+ },+ {+ "title": "/agents-status",+ "description": "Show each agent's presence and capabilities"+ },+ {+ "title": "/invite-agent",+ "description": "Add an existing agent: /invite-agent @agent-name"+ },+ {+ "title": "/agents-greet",+ "description": "Have the agents here introduce themselves"+ },+ {+ "title": "/roles",+ "description": "List this room's roles and who holds each"+ },+ {+ "title": "/list-aliases",+ "description": "List this room's agent aliases"+ },+ {+ "title": "/set-alias",+ "description": "Give an agent a room alias: /set-alias @agent-name @alias"+ },+ {+ "title": "/reset",+ "description": "Reset an agent's session: /reset @agent-name"+ },+ {+ "title": "/interrupt",+ "description": "Interrupt an agent's current turn: /interrupt @agent-name"+ },+ {+ "title": "/list-switch-agents",+ "description": "List every agent on this Switch, to find one to invite"+ },+ {+ "title": "/room-url",+ "description": "Show this room's address in Switch"+ }+ ]+ },+ {+ "scopes": [+ "team",+ "groupChat",+ "personal"+ ],+ "triggers": [+ "slash"+ ],+ "commands": [+ {+ "title": "help",+ "description": "Show every in-room command"+ },+ {+ "title": "list-agents",+ "description": "List the agents in this room"+ },+ {+ "title": "agents-status",+ "description": "Show each agent's presence and capabilities"+ },+ {+ "title": "invite-agent",+ "description": "Add an existing agent: /invite-agent @agent-name"+ },+ {+ "title": "agents-greet",+ "description": "Have the agents here introduce themselves"+ },+ {+ "title": "roles",+ "description": "List this room's roles and who holds each"+ },+ {+ "title": "list-aliases",+ "description": "List this room's agent aliases"+ },+ {+ "title": "set-alias",+ "description": "Give an agent a room alias: /set-alias @agent-name @alias"+ },+ {+ "title": "reset",+ "description": "Reset an agent's session: /reset @agent-name"+ },+ {+ "title": "interrupt",+ "description": "Interrupt an agent's current turn: /interrupt @agent-name"+ },+ {+ "title": "list-switch-agents",+ "description": "List every agent on this Switch, to find one to invite"+ },+ {+ "title": "room-url",+ "description": "Show this room's address in Switch"+ }+ ]+ }+ ]+ }+ ],+ "permissions": [+ "identity",+ "messageTeamMembers"+ ],+ "validDomains": [+ "switch.example.com"+ ],+ "webApplicationInfo": {+ "id": "00000000-0000-0000-0000-000000000000",+ "resource": "https://graph.microsoft.com"+ },+ "authorization": {+ "permissions": {+ "resourceSpecific": [+ {+ "name": "ChannelMessage.Read.Group",+ "type": "Application"+ },+ {+ "name": "ChannelSettings.Read.Group",+ "type": "Application"+ }+ ]+ }+ }+}diff --git a/docs/bridges/teams-app/outline.png b/docs/bridges/teams-app/outline.pngnew file mode 100644index 000000000..bf01bddcdBinary files /dev/null and b/docs/bridges/teams-app/outline.png differdiff --git a/justfile b/justfileindex 7c83c0eb8..b0084b395 100644--- a/justfile+++ b/justfile@@ -88,6 +88,14 @@ artifacts:artifacts-check:uv run --project core python scripts/gen_artifacts.py --check+# ── Build the Teams app package an operator uploads ───────────────────────────+# Every route into a tenant wants a .zip — Developer Portal Import app, Upload a+# custom app, the admin centre — and none takes a bare manifest.json. Pass the+# Azure Bot app id and it fills the three places it has to match.+# just teams-app-package --app-id <guid> --public-host teams.example.com+teams-app-package *args:+ uv run --project core python scripts/build_teams_app_package.py {{ args }}+# ── Run alembic migrations ─────────────────────────────────────────────────────migrate:uv run --project core alembic -c core/alembic.ini upgrade headdiff --git a/scripts/build_teams_app_package.py b/scripts/build_teams_app_package.pynew file mode 100644index 000000000..a4d00668b--- /dev/null+++ b/scripts/build_teams_app_package.py@@ -0,0 +1,228 @@+#!/usr/bin/env python3+"""Build the uploadable Teams app package: manifest + the two icons, zipped.++Every route into a tenant wants a `.zip` — the Developer Portal's **Import+app**, the client's **Upload a custom app**, and the admin centre's **Upload+new app** alike. None of them takes a bare `manifest.json`. So the repository+ships the three files and this makes the archive, rather than committing a+binary that would drift from the files beside it.++It also fills in the values that would otherwise be edited by hand in three+places, because the app id has to match in all of them and a mismatch is not+something Teams explains.++The zip is written flat, with the three files at its root: Teams rejects a+package whose contents sit inside a folder, and that is the single most common+way a hand-made one fails.++Usage:+ python scripts/build_teams_app_package.py --app-id <guid>+ python scripts/build_teams_app_package.py --app-id <guid> \\+ --public-host teams.example.com \\+ --privacy-url https://example.com/privacy \\+ --terms-url https://example.com/terms \\+ --app-name "Acme Agents"++With no --app-id it still builds, leaving the placeholder in place and saying+so — useful for checking the package shape without a tenant to hand.+"""++from __future__ import annotations++import argparse+import json+import re+import struct+import sys+import zipfile+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+PACKAGE_DIR = REPO_ROOT / "docs" / "bridges" / "teams-app"+MANIFEST = PACKAGE_DIR / "manifest.json"++# The three files Teams expects at the root of the archive.+ICON_KEYS = ("color", "outline")+EXPECTED_ICON_SIZE = {"color": (192, 192), "outline": (32, 32)}++PLACEHOLDER_APP_ID = "00000000-0000-0000-0000-000000000000"+PLACEHOLDER_HOST = "switch.example.com"+PLACEHOLDER_URLS = ("https://example.com/privacy", "https://example.com/terms")++_GUID = re.compile(r"^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$")+++def _png_size(path: Path) -> tuple[int, int]:+ """(width, height) from a PNG's IHDR, without an image library."""+ header = path.read_bytes()[:24]+ if header[:8] != b"\x89PNG\r\n\x1a\n":+ raise SystemExit(f"{path.name} is not a PNG")+ width, height = struct.unpack(">II", header[16:24])+ return width, height+++def _apply(manifest: dict, args: argparse.Namespace) -> list[str]:+ """Substitute what the operator supplied. Returns what is still a placeholder."""+ if args.app_id:+ if not _GUID.match(args.app_id):+ raise SystemExit(+ f"--app-id must be a GUID, got {args.app_id!r}. It is the Azure "+ "Bot's Application (client) ID, not its Object ID or its name."+ )+ manifest["id"] = args.app_id+ manifest["bots"][0]["botId"] = args.app_id+ manifest["webApplicationInfo"]["id"] = args.app_id+ if args.public_host:+ manifest["validDomains"] = [args.public_host]+ if args.privacy_url:+ manifest["developer"]["privacyUrl"] = args.privacy_url+ if args.terms_url:+ manifest["developer"]["termsOfUseUrl"] = args.terms_url+ if args.website_url:+ manifest["developer"]["websiteUrl"] = args.website_url+ if args.app_name:+ manifest["name"]["short"] = args.app_name+ manifest["name"]["full"] = args.app_name_full or args.app_name+ if args.bump:+ parts = manifest["version"].split(".")+ parts[-1] = str(int(parts[-1]) + 1)+ manifest["version"] = ".".join(parts)+ if args.version:+ manifest["version"] = args.version+ blob = json.dumps(manifest)+ left: list[str] = []+ if PLACEHOLDER_APP_ID in blob:+ left.append(f"the app id is still {PLACEHOLDER_APP_ID} — pass --app-id")+ if PLACEHOLDER_HOST in blob:+ left.append(f"validDomains is still {PLACEHOLDER_HOST} — pass --public-host")+ for url in PLACEHOLDER_URLS:+ if url in blob:+ left.append(f"{url} is a placeholder — pass --privacy-url / --terms-url")+ return left+++def _check(manifest: dict) -> None:+ """The constraints Teams enforces silently, checked before upload."""+ name, desc = manifest["name"], manifest["description"]+ problems = []+ if len(name["short"]) > 30:+ problems.append("name.short is over 30 characters")+ if name.get("full") and len(name["full"]) > 100:+ problems.append("name.full is over 100 characters")+ if name.get("full") and name["full"] == name["short"]:+ problems.append("name.short and name.full must differ")+ if len(desc["short"]) > 80:+ problems.append("description.short is over 80 characters")+ if len(desc["full"]) > 4000:+ problems.append("description.full is over 4000 characters")+ if not re.match(r"^#[0-9a-fA-F]{6}$", manifest["accentColor"]):+ problems.append("accentColor must be #RRGGBB")+ for field in ("websiteUrl", "privacyUrl", "termsOfUseUrl"):+ if not manifest["developer"][field].startswith("https://"):+ problems.append(f"developer.{field} must be https")+ for entry in manifest["bots"][0].get("commandLists", []):+ if len(entry["commands"]) > 12:+ problems.append("a command list may hold at most 12 commands")+ # Teams' own words on rejecting the upload: "Applications with manifest+ # version 1.25 or higher that support the 'team' scope must include the+ # 'supportsChannelFeatures' property." It is a validator rule, not a schema+ # one, so nothing catches it before the upload does — hence catching it+ # here.+ schema_version = tuple(int(n) for n in manifest["manifestVersion"].split("."))+ has_team_scope = any(+ "team" in bot.get("scopes", []) for bot in manifest.get("bots", [])+ )+ if schema_version >= (1, 25) and has_team_scope:+ if not manifest.get("supportsChannelFeatures"):+ problems.append(+ "manifestVersion is "+ f"{manifest['manifestVersion']} and a bot declares the 'team' "+ "scope, so supportsChannelFeatures is required — set it to "+ "'tier1'"+ )+ if problems:+ raise SystemExit(+ "This manifest would be rejected:\n - " + "\n - ".join(problems)+ )+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Build the Agent Switch Teams app package (.zip).",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ parser.add_argument(+ "--app-id", help="Azure Bot Application (client) ID; fills all three places"+ )+ parser.add_argument("--public-host", help="host of your public_base_url")+ parser.add_argument("--privacy-url", help="your organization's privacy policy")+ parser.add_argument("--terms-url", help="your organization's terms of use")+ parser.add_argument("--website-url", help="your organization's site")+ parser.add_argument("--app-name", help='override the app name ("Agent Switch")')+ parser.add_argument("--app-name-full", help="the long form, if it differs")+ parser.add_argument("--version", help="set the manifest version outright")+ parser.add_argument(+ "--bump",+ action="store_true",+ help="raise the patch version — required for Teams to update an app "+ "that is already installed",+ )+ parser.add_argument(+ "-o",+ "--output",+ type=Path,+ default=Path("agent-switch-teams.zip"),+ help="where to write the package (default: ./agent-switch-teams.zip)",+ )+ args = parser.parse_args()++ manifest = json.loads(MANIFEST.read_text())+ unresolved = _apply(manifest, args)+ _check(manifest)++ icons = {}+ for key in ICON_KEYS:+ name = manifest["icons"][key]+ path = PACKAGE_DIR / name+ if not path.is_file():+ raise SystemExit(f"{name} is missing from {PACKAGE_DIR}")+ if _png_size(path) != EXPECTED_ICON_SIZE[key]:+ w, h = _png_size(path)+ expect = "x".join(str(n) for n in EXPECTED_ICON_SIZE[key])+ raise SystemExit(f"{name} is {w}x{h}; Teams requires {expect}")+ icons[name] = path++ args.output.parent.mkdir(parents=True, exist_ok=True)+ with zipfile.ZipFile(args.output, "w", zipfile.ZIP_DEFLATED) as zf:+ # arcname without a directory: Teams rejects a nested package.+ zf.writestr("manifest.json", json.dumps(manifest, indent=4) + "\n")+ for name, path in icons.items():+ zf.write(path, arcname=name)++ print(f"Wrote {args.output} ({args.output.stat().st_size} bytes)")+ print(+ f" manifest.json schema v{manifest['manifestVersion']}, "+ f"app version {manifest['version']}, app id {manifest['id']}"+ )+ for name in icons:+ print(f" {name}")+ if not (args.bump or args.version):+ # The single most common reason an edit appears not to have worked.+ # Teams matches on `id` and ignores an upload whose `version` is not+ # higher than the installed one — without saying so.+ print(+ f"\nNote: app version is still {manifest['version']}. If this app is "+ "already installed,\nTeams will ignore this upload. Re-run with "+ "--bump to raise it."+ )+ if unresolved:+ print("\nStill a placeholder — Teams will accept this, your users will not:")+ for line in unresolved:+ print(f" ! {line}")+ return 1+ print("\nUpload it: Teams → Apps → Manage your apps → Upload an app.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())