Skip to content

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

feat: owner-only agent addressing, and linking an owner to a messaging account (CHOO-2137) (#226)

Louis Amaudruze198a0e6cd2a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00766ffd6..ce2dd4b24 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,97 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+
+- A Switch user can claim their messaging-app account as their own, linking a
+ Slack / Mattermost / Teams / Discord identity to their Switch login
+ (`external_user_claims`). Claiming searches the platform's own user
+ directory, so someone can be recognised before they have ever posted —
+ previously Switch only learned of a person when they first spoke, which left
+ a freshly connected workspace with nobody to pick. Each platform is searched
+ in its own way: Slack filters a paged listing, Mattermost and Discord have
+ server-side search, and Teams queries the directory through Graph. Telegram
+ has no directory a bot may search at all, so there the list falls back to the
+ accounts Switch has already seen and says why it is narrower — a smaller
+ answer rather than a refusal, since refusing would leave owner-only
+ addressing unusable on the platform for people Switch already knows. Claims
+ are not exclusive: several Switch users may claim the same account, so nobody
+ can keep the real person from being recognised by claiming it first
+ (CHOO-2137).
+- An addressing rule can name the agent's **owner**, or **any agent that owner
+ runs**, rather than a list of identities. Both resolve when the message
+ arrives, so they survive connecting a new workspace, recreating a bridge,
+ registering another agent, or the agent changing hands. The second is what
+ lets one person's manager agent keep dispatching their own workers under an
+ owner-scoped policy — that is the owner acting through a program, where
+ someone else's agent is not (CHOO-2137).
+- `GET /agents` reports each agent's `addressing_policy`, which until now was
+ only on `GET /agents/{id}`. So "which of these agents answers only its owner"
+ is one list read rather than a read per agent — the shape a client needs to
+ ask that at all, instead of a request storm (CHOO-2137).
+
+#### Changed
+
+- A messaging app declares **whether its user directory can be searched**
+ (`directory_search_supported`, beside `channel_creation_supported`). False
+ for Telegram, where a bot can only name people who have messaged it. Read
+ from the adapter class, so it is answerable before a connection of that type
+ exists — which is when a client has to decide whether asking someone to pick
+ themselves out of a directory is a question worth putting (CHOO-2137).
+- **Disconnecting a messaging app now removes the identities Switch made for
+ it** — the app's own Matrix client and the puppet behind every person Switch
+ saw on it. They were left behind, and the app's own client is not merely
+ untidy: its Matrix name was derived from the app's type and display name, so
+ disconnecting an app and connecting one named the same failed outright on the
+ leftover (`duplicate key value violates unique constraint
+ "clients_matrix_user_id_key"`). The name now carries a random tail as well,
+ because deleting the row is necessary but not sufficient: the homeserver has
+ no call for removing an account, so the old Matrix user is still there, and
+ adopting it would mean logging in with a password Switch no longer holds —
+ shared-secret registration reports an existing user as success without
+ applying the new one, which reads as a working connection that can never
+ connect. Abandoned homeserver accounts are logged on removal rather than
+ passed over in silence (CHOO-2137).
+- **An agent pings its owner, not a handle typed into its config.** The
+ per-agent `notify_user` option is gone; who to @-mention when an agent needs
+ input is now the agent's owner, resolved through the messaging account that
+ person has claimed on the platform the room is bridged to. A handle only ever
+ means something on one platform — the same person is one name on Slack and
+ another on Telegram — so a single configured string was at best right in one
+ room, and on Discord and Teams it went out as plain text that notified nobody
+ while looking like it had. An agent with no owner, or an owner who has linked
+ no account there, now **says so in the nudge** instead of posting a line with
+ the mention silently missing: a ping that reaches no one and an agent that
+ never asked look identical otherwise. Existing `notify_user` values are
+ ignored rather than migrated, and drop out of an agent's options the next
+ time they are written (CHOO-2137).
+- **Newly created agents are owner-only by default**: only their owner may
+ address them, from any room, and no agent unless the owner says so. The
+ default is applied where every registration path converges, so it holds
+ for Switch Console, the gateway, the agent bridge, the configure skill and
+ bulk subagent registration alike. Existing agents are left open — the default
+ is not applied retroactively, since that would mute every agent whose owner
+ has not yet claimed an identity. Server-side connector agents opt out: they
+ are services a deployment offers everyone, not one person's assistant
+ (CHOO-2137).
+- In-room commands are subject to the addressing policy, not just messages —
+ `!reset`, `!interrupt` and `!compact` drive an agent as surely as a mention
+ does, and previously reached a restricted agent from anyone in the room. A
+ command naming the agent draws the same one-line refusal; a room-wide command
+ is declined quietly rather than producing a refusal from every restricted
+ agent present (CHOO-2137).
+- `send_targeted_message` reports a target whose policy forbids the sender as
+ `not_permitted`, rather than as "live" for a message that will never move it.
+ The message is still sent and the target still declines it in the room: a
+ refusal belongs where the request was made, not only in the sender's account
+ of it, and the same request should not succeed or fail depending on which
+ tool carried it — a plain `@name` was never blocked. `delegate_task` remains
+ the exception and fails at the sender, because a task is a row somebody is
+ expected to work rather than something a room can decline (CHOO-2137).
+- An agent that refuses a sender because its owner cannot be identified says
+ so, and points at linking the account in Switch Console — rather than giving
+ the owner the generic refusal from their own agent (CHOO-2137).
+
### [0.15.0] - 2026-08-14
#### Added
@@ -510,6 +601,106 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+
+- **You can tell Switch which messaging-app account is yours.** A new dialog
+ searches the workspace's own user directory — Slack, Mattermost — and links
+ the account you pick to your Switch login. It searches the platform rather
+ than Switch's record of who has spoken, so you can find yourself in a
+ workspace you have never posted in, and it shows the display name, handle and
+ email so you can tell two similar accounts apart. An account someone else has
+ already linked says who — linking is not exclusive, so that is information
+ about who else is recognised on it rather than a lock — and one you have
+ linked yourself offers to unlink instead of linking it twice. A platform with
+ no searchable directory says so — and says a message has to arrive first —
+ instead of showing an empty list (CHOO-2137).
+- The dialog is offered as step 2 of connecting a messaging app, straight after
+ the connection succeeds, because that is the one moment the workspace is on
+ your mind — **except on an app whose directory cannot be searched**, where it
+ is not offered at all. On Telegram, Switch can only name people who have
+ messaged it, and nobody has messaged a connection made a second ago: the
+ search was guaranteed to come back empty, which reads as "you are not in your
+ own workspace" rather than "not yet". Linking waits for the server page,
+ where the warning that you own an agent nobody can reach is what prompts it,
+ and by then someone has messaged the app and there is a name to pick. The
+ search prompt no longer promises a "workspace directory" on a platform that
+ has neither. It is skippable, and linking lives on the server page for later:
+ **Messaging apps** lists one row per app — the app, the account on it that is
+ you, and what you can do with it — where your handle is the button that
+ changes it and a Link button stands in when there is none, opening the
+ dialog already pointed at that app. So you can see at a glance where you
+ are recognised and where you are not, without a separate list to reconcile
+ against. Linking is not an admin action: a member of the server sees the same
+ card and can link on any app in it, and only the Connect button is withheld.
+- **Each messaging app carries its own menu**, holding the actions that are rare
+ or destructive: unlinking your account, whether the app may create channels,
+ and disconnecting it. The row itself is left saying one thing — which account
+ here is you — in one control whether or not there is one. Unlinking in
+ particular is off the row: it used to be a bare cross sitting beside the
+ handle, one mis-click from the button you press to *change* an account, with
+ no confirmation between. The **Default** badge also sits against the app's
+ name now rather than drifting into the middle of a wide row.
+- **The server page warns when an owner-only agent cannot recognise you**, and
+ only then. One line at the top of **Messaging apps** names the apps you have
+ not linked — shown when you own an agent on that server whose rule admits its
+ owner, and never otherwise. Link everywhere, or own no such agent, and there
+ is nothing to see: a warning shown to everybody teaches people to ignore it.
+- **A new agent now answers only its owner.** Agents used to be created open to
+ everyone in every room; the add-agent dialog now defaults to *Only me*. The
+ rule names the owner rather than a list of identities, so it survives
+ connecting a new workspace or the agent changing hands. *Only me and my
+ agents* is one step away when an agent of yours has to hand this one work.
+ Existing agents are untouched.
+- **A messaging app can be disconnected from the server page**, by an admin, on
+ the same **Messaging apps** row that connects one. It is not a pause: the
+ server deletes every Switch room on that app before removing it, so the rooms
+ and their conversations go with it, and an app another admin has already
+ removed says so rather than reporting a disconnect that never happened
+ (CHOO-2137).
+
+#### Changed
+
+- **Who can send instructions to an agent is one question with four answers** —
+ *Only me (default)*, *Only me and my agents*, *Anyone*, or *Custom rules* —
+ rather than an open / restricted switch above a rule builder. The two
+ owner-scoped answers differ in one thing: whether agents you own may hand this
+ one work. Anyone drops the policy entirely; Custom rules opens the rule
+ editor, seeded from whichever answer the agent was on, so nothing has to be
+ rebuilt to add one exception. Rules built by hand are kept while the chooser
+ is on a shortcut, and a policy too specific for any of them reads back as
+ Custom rules rather than being flattened into one. The same control is on the
+ add-agent dialog and on the agent's Settings tab, so a policy is changed the
+ way it was set. The box shows the answer that was picked, rather than the
+ word stored behind it.
+- **The add-agent dialog offered "Advanced configuration" twice** for Claude
+ Code. A provider keeps its per-agent settings in one place — a repo-agent
+ definition or a launch profile — and the agent's Settings tab picks between
+ them by asking which; the creation form rendered both sections instead, and
+ the launch-profile one reads a "the fields, from wherever they live" call
+ that falls back to the definition fields. So the same settings appeared in
+ two identical boxes writing to two different places. It now picks the same
+ way the Settings tab does.
+- An agent's Settings tab no longer boxes **Advanced configuration** and **Who
+ can send instructions** in borders of their own. Every section on the page is
+ already a section; drawing two of them again was one frame too many.
+
+- **You and your agents appear in the rule editor's own pickers**, as *Me* in
+ the Users list and *My agents* in the Agents list, rather than as a checkbox
+ off to the side. They read as what they are — two more senders to admit —
+ and they compose: "me and Alice" is one rule. Setting either list to *Any* or
+ *None* clears the matching entry, so a rule cannot say "no humans" and "the
+ owner may" at once.
+- An owner rule can only recognise an owner who has linked their messaging
+ account, so the addressing editor warns — with a button into the linking
+ dialog — when the signed-in user has linked none. A privacy control that
+ silently admits nobody is the failure this exists to prevent.
+- The linking dialog is opened on one workspace rather than asking which. It is
+ titled for the platform it is linking on — "Link your Discord user account" —
+ and its search names the workspace, not the platform, since two workspaces on
+ the same platform can be connected and only the name tells them apart.
+
+### [0.23.0] - 2026-08-14
+
#### Removed
- The "Give Feedback" feature — modal, Help menu entry, command-palette command
@@ -1579,6 +1770,13 @@ compatibility signal. History for those is in the git log.
### [Unreleased]
+#### Changed
+
+- The room-workflow skill describes owner-only addressing — the new default for
+ agents created in Switch Console — and states that `send_targeted_message`
+ now fails outright for a disallowed sender, and that in-room commands are
+ covered by the policy too (CHOO-2137).
+
### [0.9.3] - 2026-08-14
#### Changed
@@ -1672,6 +1870,13 @@ manifest history.
### [Unreleased]
+#### Changed
+
+- The room-workflow skill describes owner-only addressing — the new default for
+ agents created in Switch Console — and states that `send_targeted_message`
+ now fails outright for a disallowed sender, and that in-room commands are
+ covered by the policy too (CHOO-2137).
+
### [0.3.4] - 2026-08-14
#### Changed
@@ -1773,6 +1978,13 @@ the app version that wrote it rather than a version of its own.
### [Unreleased]
+#### Changed
+
+- The room-workflow skill describes owner-only addressing — the new default for
+ agents created in Switch Console — and states that `send_targeted_message`
+ now fails outright for a disallowed sender, and that in-room commands are
+ covered by the policy too (CHOO-2137).
+
### [0.1.1] - 2026-08-14
#### Changed
diff --git a/connectors/claude-code-plugin/skills/configure/SKILL.md b/connectors/claude-code-plugin/skills/configure/SKILL.md
index 8d06fbbe7..ab09b9090 100644
--- a/connectors/claude-code-plugin/skills/configure/SKILL.md
+++ b/connectors/claude-code-plugin/skills/configure/SKILL.md
@@ -45,7 +45,7 @@ id, which file) and use `AskUserQuestion` to offer three choices:
- **Keep it** — stop the skill. Re-registering would mint a fresh agent
and orphan the old one in Switch.
- **Add subagents** — keep the existing main agent and jump straight to
- Step 12 to bring in `.claude/agents/*.md` subagents under it. The
+ Step 11 to bring in `.claude/agents/*.md` subagents under it. The
parent is the already-configured agent: use its id (`env.SWITCH_AGENT_ID`
from the settings file / environment) as `parent_agent_id`. Skip steps
2–11 entirely — you are not re-registering the main agent, only adding
@@ -264,36 +264,7 @@ pass an empty string — leave the key out so the schema default of
The answer is passed as `options.repo_dir` in the register payload.
-## Step 8 — Notify user (`notify_user`)
-
-When someone addresses this agent in a room but no Claude Code session is
-active, Switch posts the paste-ready terminal command from step 7. If you
-also want the operator to be **pinged** by the bridged platform (Slack /
-Mattermost push notification, mobile alert), Switch can prepend an
-`@username` mention to that message.
-
-Use `AskUserQuestion` to ask whether to record `notify_user`. Explain in
-plain terms: *"If you set this, the unavailable-session message will
-start with `@<name>` so the bridge fires a push notification at that
-person. Use the exact handle they have on the room's bridged platform
-(Slack / Mattermost), or their Switch user name for unbridged rooms —
-this is often NOT the same as the local/gateway username. If the handle
-doesn't match a real bridge user the mention silently does nothing (it
-just shows up as plain text and nobody is paged). If you skip, the
-message is posted without a mention."*
-
-If the user opts in, ask for the bare handle (no leading `@`). Do not
-assume a default — in particular, do not fall back to `$USER` or the
-local/gateway identity. Have the operator give the handle explicitly,
-and confirm before saving.
-
-If the user opts out, omit `notify_user` from the options payload (do not
-pass an empty string — leave the key out so the schema default of
-`None` applies).
-
-The answer is passed as `options.notify_user` in the register payload.
-
-## Step 9 — Register
+## Step 8 — Register
Call the bridge endpoint `POST /agents/register-known`. It takes the
registration token in the `Authorization` header, looks up the
@@ -313,18 +284,15 @@ curl -sf -X POST "$ENDPOINT/agents/register-known" \
-d "$(jq -nc --arg name "$NAME" --arg desc "$DESC" \
--argjson channels "$CHANNELS_ENABLED" \
--arg repo_dir "$REPO_DIR" \
- --arg notify_user "$NOTIFY_USER" \
'{agent_type:"claude-code", name:$name, description:$desc,
options:({channels_enabled:$channels}
- + (if $repo_dir == "" then {} else {repo_dir:$repo_dir} end)
- + (if $notify_user == "" then {} else {notify_user:$notify_user} end)),
+ + (if $repo_dir == "" then {} else {repo_dir:$repo_dir} end)),
overwrite:false}')"
```
`$CHANNELS_ENABLED` must be the JSON literal `true` or `false` (passed
via `--argjson`, not `--arg`). Set `$REPO_DIR` to the absolute path
-from step 7 (or empty to omit). Set `$NOTIFY_USER` to the bare handle
-from step 8 (or empty to omit).
+from step 7 (or empty to omit).
**Pitfall — env-var expansion order.** Do NOT prefix the curl command
with `SWITCH_REGISTRATION_TOKEN=... curl ...` while also referencing
@@ -358,7 +326,7 @@ show the user the HTTP status and response body, then stop.
retry with `overwrite:true` silently.
- Any other non-2xx — show the status and body, then stop.
-## Step 10 — Write settings, and the agent's credentials
+## Step 9 — Write settings, and the agent's credentials
Two files, with different jobs. The settings file is Claude Code's own and is
read by **every** session in the directory, so it carries no credential — only
@@ -408,7 +376,7 @@ too if it is not already covered.
The runtime reads this file itself (`switch-agent-runtime` 0.2.0+), so no `env`
block in any MCP config is needed to carry the credentials.
-## Step 11 — Confirm
+## Step 10 — Confirm
Report to the user:
@@ -423,7 +391,7 @@ Report to the user:
Do **not** print the API token. Echoing secrets into the transcript is a
common way they leak into logs or screenshots.
-## Step 12 — Bring in existing Claude Code subagents (optional)
+## Step 11 — Bring in existing Claude Code subagents (optional)
A user may already have **Claude Code subagents** defined as
`.claude/agents/*.md` files (a `name`, `description`, optional `tools`
@@ -491,7 +459,7 @@ declines all, skip the rest of this step.
### 12d — Bulk-register under the main agent
Call `POST /agents/register-known-bulk` with the same registration
-token as Step 9. The Switch agent name for each child is derived
+token as Step 8. The Switch agent name for each child is derived
server-side as `<main-agent-name>.<subagent_name>`, so you only send the
bare `subagent_name` and `description`. `options` is the shared base
applied to every subagent; the server merges each `subagent_name` in on
@@ -500,17 +468,16 @@ top.
**`parent_agent_id` is the dir's main agent — read it from the
environment, don't ask.** The running session's own agent id is in
`$SWITCH_AGENT_ID` (the same value written into the settings `env` block
-in Step 11). That is exactly the parent these subagents belong under, so
+in Step 10). That is exactly the parent these subagents belong under, so
default `parent_agent_id` to `$SWITCH_AGENT_ID`. When you registered the
-main agent earlier in *this same run* (Step 9), use that id instead — it
+main agent earlier in *this same run* (Step 8), use that id instead — it
is the same agent. Only ask the user if neither is available.
**Subagents inherit the parent's settings automatically.** The server
-reads the parent agent's recorded `channels_enabled`, `repo_dir`, and
-`notify_user` and applies them as the base for every subagent (so they
-page the same operator, run in the same channels mode, and share the
-repo dir) — you do **not** need to recover these from the parent or pass
-them. Only set a key in `options` to deliberately *override* the
+reads the parent agent's recorded `channels_enabled` and `repo_dir` and
+applies them as the base for every subagent (so they run in the same
+channels mode and share the repo dir) — you do **not** need to recover
+these from the parent or pass them. Only set a key in `options` to deliberately *override* the
inherited value; otherwise omit it.
```bash
@@ -526,9 +493,9 @@ curl -sf -X POST "$ENDPOINT/agents/register-known-bulk" \
`$SUBS_JSON` is a JSON array of `{"subagent_name": "...",
"description": "..."}` for the selected subagents. `$SWITCH_AGENT_ID` is
-the parent agent id read from the environment (or the id from Step 9 if
+the parent agent id read from the environment (or the id from Step 8 if
you just registered the main agent in this run). The same
-env-var-expansion pitfall and the token-handling rules from Step 9 apply
+env-var-expansion pitfall and the token-handling rules from Step 8 apply
— never inline the token.
The response is `{"results": [{"subagent_name","name","id","api_key"},
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index 9a89934b3..6d87afdf5 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -294,11 +294,19 @@ Whether you can delegate or accept is declared per agent
events. `cancel_task(task_id, reason)` abandons it.
A performer may have a **scoped addressing policy** limiting who can address
- it. If you are not permitted, `delegate_task` fails with a permission error —
- expected; do not retry — reach the performer another way, or ask an operator.
- Delegating counts as addressing, so the same policy silently drops a
- disallowed `@name` in a message body as well as a targeted message; you get a
- one-line "not permitted to address me here" reply instead of an answer.
+ it. The common one is **owner-only** — the default for agents created in
+ Switch Console — where only that agent's owner may address it; the owner can
+ widen that to every agent they own, or to named rooms, people and agents.
+ If you are not permitted, **`delegate_task` fails** with a permission error:
+ a task is work someone is expected to pick up, so it is refused at the point
+ of asking. Expected; do not retry — reach the performer another way, or ask
+ an operator to allow you.
+ **Messages are not blocked.** `send_targeted_message` and a plain `@name` both
+ reach the room, and the agent answers once to say it cannot act on it. What
+ you get back from `send_targeted_message` is `not_permitted` in that agent's
+ `target_statuses` instead of a reachability value — read its reply rather
+ than sending again. Commands are covered too, so `!reset` on a restricted
+ agent is declined the same way.
- **Accepting.** On a `task_delegate` event, `accept_task(task_id)` moves it to
`ongoing`. `update_task(task_id, update)` records progress.
`finalise_task(task_id, outcome)` closes it with a single string describing
@@ -349,7 +357,7 @@ none of it is needed to take part in a conversation.
**Owner-only**: the agent's owner must match your own. `options` is a
PARTIAL map of known-agent options merged over the current ones, and the
keys differ per type — for `opencode` and `codex`: `repo_dir` (working
- directory), `notify_user`, `auto_session`; for `claude-code`: those plus
+ directory), `auto_session`; for `claude-code`: those plus
`channels_enabled` and `subagent_name`. Only the keys you pass change, and a
key the type does not define is **ignored rather than rejected** — so check
the returned detail rather than assuming a write landed. `parent_agent_id`
diff --git a/connectors/codex-plugin/skills/configure/SKILL.md b/connectors/codex-plugin/skills/configure/SKILL.md
index bc8641f81..616883874 100644
--- a/connectors/codex-plugin/skills/configure/SKILL.md
+++ b/connectors/codex-plugin/skills/configure/SKILL.md
@@ -208,7 +208,7 @@ Default: `Codex running in <repo-name-or-hostname>`.
> equivalent, so the bulk endpoint would mint indistinguishable children. Do not
> call it.
-## Step 5 — Repository directory and notify user
+## Step 5 — Repository directory
Switch shows room participants a paste-ready command when the agent is
addressed with no live session:
@@ -226,14 +226,7 @@ session has no identity.
Ask whether to record it, defaulting to the current working directory. Validate
that it is absolute (`startswith("/")`) and exists (`test -d`).
-Then ask whether to record `notify_user` — a handle to `@`-mention on the
-bridged platform so the operator gets a push notification. Explain: *"Use the
-exact handle they have on the room's bridged platform (Slack / Mattermost), or
-their Switch user name for unbridged rooms — often NOT the local username. If it
-doesn't match a real bridge user the mention silently does nothing."* Ask for
-the bare handle, no leading `@`, and do not default to `$USER`.
-
-Omit either key entirely if the user opts out — leave it out rather than passing
+Omit the key entirely if the user opts out — leave it out rather than passing
an empty string, so the schema default applies.
**Do not set `auto_session`.** It means "Switch Console watches rooms and auto-spawns
@@ -252,10 +245,9 @@ curl -sf -X POST "$ENDPOINT/agents/register-known" \
-H "Authorization: Bearer $SWITCH_REGISTRATION_TOKEN" \
-H "Content-Type: application/json" \
-d "$(jq -nc --arg name "$NAME" --arg desc "$DESC" \
- --arg repo_dir "$REPO_DIR" --arg notify_user "$NOTIFY_USER" \
+ --arg repo_dir "$REPO_DIR" \
'{agent_type:"codex", name:$name, description:$desc,
- options:((if $repo_dir == "" then {} else {repo_dir:$repo_dir} end)
- + (if $notify_user == "" then {} else {notify_user:$notify_user} end)),
+ options:(if $repo_dir == "" then {} else {repo_dir:$repo_dir} end),
overwrite:false}')"
```
@@ -334,10 +326,10 @@ there.
>
> The quoted heredoc (`<<'SCRIPT'`) is what keeps the body intact.
-`ENDPOINT`, `NAME`, `DESC`, `REPO_DIR`, `NOTIFY_USER` and
-`SWITCH_REGISTRATION_TOKEN` must be exported in the environment the script runs
-in. `REPO_DIR` and `NOTIFY_USER` may be empty strings — the server normalises a
-blank to "unset", so there is no need to build the payload conditionally.
+`ENDPOINT`, `NAME`, `DESC`, `REPO_DIR` and `SWITCH_REGISTRATION_TOKEN` must be
+exported in the environment the script runs in. `REPO_DIR` may be an empty
+string — the server normalises a blank to "unset", so there is no need to build
+the payload conditionally.
```bash
set -eu
@@ -349,9 +341,9 @@ http_status=$(curl -s -o "$resp" -w '%{http_code}' -X POST "$ENDPOINT/agents/reg
-H "Authorization: Bearer $SWITCH_REGISTRATION_TOKEN" \
-H 'Content-Type: application/json' \
-d "$(jq -nc --arg name "$NAME" --arg desc "$DESC" \
- --arg repo_dir "$REPO_DIR" --arg notify_user "$NOTIFY_USER" \
+ --arg repo_dir "$REPO_DIR" \
'{agent_type:"codex", name:$name, description:$desc,
- options:{repo_dir:$repo_dir, notify_user:$notify_user},
+ options:{repo_dir:$repo_dir},
overwrite:false}')")
if [ "$http_status" != "200" ]; then
diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.md
index d0791d6e6..7fb62817b 100644
--- a/connectors/codex-plugin/skills/switch/SKILL.md
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -295,11 +295,19 @@ Whether you can delegate or accept is declared per agent
demand. `cancel_task(task_id, reason)` abandons it.
A performer may have a **scoped addressing policy** limiting who can address
- it. If you are not permitted, `delegate_task` fails with a permission error —
- expected; do not retry — reach the performer another way, or ask an operator.
- Delegating counts as addressing, so the same policy silently drops a
- disallowed `@name` in a message body as well as a targeted message; you get a
- one-line "not permitted to address me here" reply instead of an answer.
+ it. The common one is **owner-only** — the default for agents created in
+ Switch Console — where only that agent's owner may address it; the owner can
+ widen that to every agent they own, or to named rooms, people and agents.
+ If you are not permitted, **`delegate_task` fails** with a permission error:
+ a task is work someone is expected to pick up, so it is refused at the point
+ of asking. Expected; do not retry — reach the performer another way, or ask
+ an operator to allow you.
+ **Messages are not blocked.** `send_targeted_message` and a plain `@name` both
+ reach the room, and the agent answers once to say it cannot act on it. What
+ you get back from `send_targeted_message` is `not_permitted` in that agent's
+ `target_statuses` instead of a reachability value — read its reply rather
+ than sending again. Commands are covered too, so `!reset` on a restricted
+ agent is declined the same way.
- **Accepting.** A delegation arrives as `[Switch] Task delegated to you in
room …`, carrying the summary and description but **not** the task id — call
`list_tasks(role='assigned', status='pending')` to find it, then
@@ -353,7 +361,7 @@ none of it is needed to take part in a conversation.
**Owner-only**: the agent's owner must match your own. `options` is a
PARTIAL map of known-agent options merged over the current ones, and the
keys differ per type — for `opencode` and `codex`: `repo_dir` (working
- directory), `notify_user`, `auto_session`; for `claude-code`: those plus
+ directory), `auto_session`; for `claude-code`: those plus
`channels_enabled` and `subagent_name`. Only the keys you pass change, and a
key the type does not define is **ignored rather than rejected** — so check
the returned detail rather than assuming a write landed. `parent_agent_id`
diff --git a/connectors/opencode-plugin/skills/switch/SKILL.md b/connectors/opencode-plugin/skills/switch/SKILL.md
index 7b3d3ba96..98f5f0b18 100644
--- a/connectors/opencode-plugin/skills/switch/SKILL.md
+++ b/connectors/opencode-plugin/skills/switch/SKILL.md
@@ -303,11 +303,19 @@ Whether you can delegate or accept is declared per agent
demand. `cancel_task(task_id, reason)` abandons it.
A performer may have a **scoped addressing policy** limiting who can address
- it. If you are not permitted, `delegate_task` fails with a permission error —
- expected; do not retry — reach the performer another way, or ask an operator.
- Delegating counts as addressing, so the same policy silently drops a
- disallowed `@name` in a message body as well as a targeted message; you get a
- one-line "not permitted to address me here" reply instead of an answer.
+ it. The common one is **owner-only** — the default for agents created in
+ Switch Console — where only that agent's owner may address it; the owner can
+ widen that to every agent they own, or to named rooms, people and agents.
+ If you are not permitted, **`delegate_task` fails** with a permission error:
+ a task is work someone is expected to pick up, so it is refused at the point
+ of asking. Expected; do not retry — reach the performer another way, or ask
+ an operator to allow you.
+ **Messages are not blocked.** `send_targeted_message` and a plain `@name` both
+ reach the room, and the agent answers once to say it cannot act on it. What
+ you get back from `send_targeted_message` is `not_permitted` in that agent's
+ `target_statuses` instead of a reachability value — read its reply rather
+ than sending again. Commands are covered too, so `!reset` on a restricted
+ agent is declined the same way.
- **Accepting.** A delegation arrives as `[Switch] Task delegated to you in
room …`, carrying the summary and description but **not** the task id — call
`list_tasks(role='assigned', status='pending')` to find it, then
@@ -361,7 +369,7 @@ none of it is needed to take part in a conversation.
**Owner-only**: the agent's owner must match your own. `options` is a
PARTIAL map of known-agent options merged over the current ones, and the
keys differ per type — for `opencode` and `codex`: `repo_dir` (working
- directory), `notify_user`, `auto_session`; for `claude-code`: those plus
+ directory), `auto_session`; for `claude-code`: those plus
`channels_enabled` and `subagent_name`. Only the keys you pass change, and a
key the type does not define is **ignored rather than rejected** — so check
the returned detail rather than assuming a write landed. `parent_agent_id`
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts
index a5bf95a86..dc3940e26 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts
@@ -19,6 +19,7 @@ function bridge(overrides: Partial<RemoteBridge>): RemoteBridge {
homeUrl: null,
channelCreationSupported: true,
canCreateChannels: true,
+ directorySearchSupported: true,
...overrides,
};
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index 9e0b09c45..5d10751af 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -25,11 +25,17 @@ import type {
AddServerParams,
AgentDefaults,
AgentVerifyResult,
+ BridgeDirectorySearchResult,
BundledChatSignIn,
+ ClaimIdentityParams,
+ ClaimIdentityResult,
CreateBridgeParams,
CreateBridgeResult,
CreateRoomParams,
CreateRoomResult,
+ DeleteBridgeParams,
+ DeleteBridgeResult,
+ LinkedIdentity,
PasswordLoginParams,
ProvisionAgentParams,
ProvisionAgentResult,
@@ -60,6 +66,7 @@ import { createRoomOnServer } from './create-room';
import {
addRoomAgents,
agentExistsOnServer,
+ deleteBridge,
fetchAddressingPolicy,
fetchAgentDetail,
fetchAgentRooms,
@@ -69,15 +76,19 @@ import {
fetchBridges,
fetchBridgeTypes,
fetchMe,
+ fetchMyIdentities,
fetchRoomAgentIds,
fetchRoomGroups,
fetchRoomRoles,
fetchRooms,
GatewayError,
+ ownsOwnerAddressedAgent,
+ releaseBridgeIdentity,
removeRoomAgent,
updateAddressingPolicy,
} from './gateway-client';
import { openAuthenticatedGatewayPage } from './gateway-web';
+import { claimIdentityOnServer, searchDirectoryOnServer } from './identities';
import {
addServer,
deleteSessionCookie,
@@ -260,6 +271,15 @@ export const switchServersController = createRPCController({
});
},
+ /**
+ * Disconnect a messaging app from the chosen server. Admin-only, and the
+ * gateway deletes every Switch room on the bridge on the way — see
+ * `deleteBridge`. The renderer owns the confirmation; by the time this runs
+ * the rooms are being given up deliberately.
+ */
+ deleteBridge: async (params: DeleteBridgeParams): Promise<DeleteBridgeResult> =>
+ deleteBridge(await requireReachableServer(params.serverId), params.bridgeId),
+
/**
* Create a room on the chosen server, owned by the signed-in user. Room
* provisioning stays server-side (`POST /gateway/rooms`); this only maps
@@ -314,6 +334,58 @@ export const switchServersController = createRPCController({
listRemoteExternalUsers: async (serverId: string): Promise<RemoteExternalUser[]> =>
fetchAllExternalUsers(await requireServer(serverId)),
+ /**
+ * Search a bridge's own user directory so the signed-in user can find
+ * themselves before they have ever posted in the workspace (CHOO-2137).
+ */
+ searchBridgeDirectory: async (params: {
+ serverId: string;
+ bridgeId: string;
+ query: string;
+ }): Promise<BridgeDirectorySearchResult> =>
+ searchDirectoryOnServer(
+ await requireReachableServer(params.serverId),
+ params.bridgeId,
+ params.query
+ ),
+
+ /** Claim a messaging-app account as the signed-in Switch user's own. */
+ claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> =>
+ claimIdentityOnServer(await requireReachableServer(params.serverId), {
+ bridgeId: params.bridgeId,
+ externalUserId: params.externalUserId,
+ username: params.username,
+ }),
+
+ /** Give up a claim on a messaging-app account, leaving any other user's claim
+ * on it in place. `userId` is whose claim to drop — null for the signed-in
+ * user, which is the only one this app offers. Failures propagate: unclaiming
+ * is a deliberate act, and reporting success for one that did not happen
+ * would leave the user thinking an agent is no longer reachable by them when
+ * it still is. */
+ releaseBridgeIdentity: async (params: {
+ serverId: string;
+ bridgeId: string;
+ identityId: string;
+ userId: string | null;
+ }): Promise<void> =>
+ releaseBridgeIdentity(
+ await requireReachableServer(params.serverId),
+ params.bridgeId,
+ params.identityId,
+ params.userId
+ ),
+
+ /** The messaging accounts the signed-in user has claimed on this server. */
+ listMyIdentities: async (serverId: string): Promise<LinkedIdentity[]> =>
+ fetchMyIdentities(await requireServer(serverId)),
+
+ /** Whether the signed-in user owns an agent here that is set to answer its
+ * owner, which is what makes an unlinked messaging account worth warning
+ * about. One agent-list read, so callers need not ration it. */
+ ownsOwnerAddressedAgent: async (serverId: string): Promise<boolean> =>
+ ownsOwnerAddressedAgent(await requireServer(serverId)),
+
getAddressingPolicy: async (params: {
serverId: string;
agentId: string;
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts
index c617aa9b5..519713c1c 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts
@@ -93,6 +93,7 @@ describe('createBridgeOnServer', () => {
// capability behaves as if every bridge could create a channel.
channelCreationSupported: true,
canCreateChannels: true,
+ directorySearchSupported: true,
},
});
});
@@ -311,7 +312,7 @@ describe('fetchBridgeTypes', () => {
// capability, which is the same "every platform could" default as the
// bridge list uses.
await expect(fetchBridgeTypes(SERVER)).resolves.toEqual([
- { key: 'stub', fields: [], channelCreationSupported: true },
+ { key: 'stub', fields: [], channelCreationSupported: true, directorySearchSupported: true },
]);
});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
index cfa1c3c5f..14a9bc9b3 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -8,6 +8,7 @@ import {
HostUnreachableError,
unknownHostReachability,
} from '@shared/core/remote-hosts/reachability';
+import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';
const getSessionCookie = vi.hoisted(() => vi.fn());
const refreshSession = vi.hoisted(() => vi.fn());
@@ -26,8 +27,15 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
vi.mock('./servers-store', () => ({ getSessionCookie }));
vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
-const { createRoom, fetchBridges, fetchMe, registerKnownAgent, updateBridge } =
- await import('./gateway-client');
+const {
+ createRoom,
+ deleteBridge,
+ fetchBridges,
+ fetchMe,
+ ownsOwnerAddressedAgent,
+ registerKnownAgent,
+ updateBridge,
+} = await import('./gateway-client');
const SERVER = {
id: 'srv-1',
@@ -340,6 +348,7 @@ describe('room creation', () => {
homeUrl: 'mattermost://chat.example.com/switch',
channelCreationSupported: true,
canCreateChannels: true,
+ directorySearchSupported: true,
},
{
id: 'b2',
@@ -353,6 +362,7 @@ describe('room creation', () => {
// where every bridge could create a channel.
channelCreationSupported: true,
canCreateChannels: true,
+ directorySearchSupported: true,
},
]);
});
@@ -508,6 +518,114 @@ describe('registerKnownAgent', () => {
});
});
+describe('ownsOwnerAddressedAgent', () => {
+ let listedAgents: unknown[] = [];
+ const routedFetch = vi.fn<(url: string) => Promise<Response>>();
+
+ /** An agent as `GET /agents` returns it, with only the fields the probe uses
+ * spelled out per case. */
+ function listedAgent(fields: {
+ id: string;
+ owner_id: string | null;
+ addressing_policy?: unknown;
+ }): unknown {
+ return {
+ name: fields.id,
+ description: '',
+ connector_type: 'http',
+ owner_name: null,
+ known_agent_type: null,
+ created_at: '2026-01-01T00:00:00Z',
+ ...fields,
+ };
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listedAgents = [];
+ // `GET /auth/me` answers as `u1`; everything else is the agent list.
+ routedFetch.mockImplementation(async (url: string) =>
+ url.endsWith('/auth/me') ? okMeResponse() : jsonResponse(listedAgents)
+ );
+ vi.stubGlobal('fetch', routedFetch);
+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('reads the whole answer off the agent list', async () => {
+ // The policy is on the list response now, so the probe costs `/auth/me`
+ // plus `/agents` and nothing per agent — however many the user owns
+ // (CHOO-2137).
+ listedAgents = Array.from({ length: 20 }, (_, i) =>
+ listedAgent({
+ id: `a${i}`,
+ owner_id: 'u1',
+ addressing_policy: ownerOnlyPolicy(),
+ })
+ );
+
+ await expect(ownsOwnerAddressedAgent(SERVER)).resolves.toBe(true);
+ expect(routedFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores an owner-restricted agent belonging to somebody else', async () => {
+ listedAgents = [
+ listedAgent({ id: 'theirs', owner_id: 'u2', addressing_policy: ownerOnlyPolicy() }),
+ ];
+
+ await expect(ownsOwnerAddressedAgent(SERVER)).resolves.toBe(false);
+ });
+
+ it('ignores an agent of the user’s that anyone may address', async () => {
+ listedAgents = [
+ listedAgent({ id: 'open', owner_id: 'u1', addressing_policy: null }),
+ listedAgent({ id: 'rule-less', owner_id: 'u1', addressing_policy: { rules: [] } }),
+ ];
+
+ await expect(ownsOwnerAddressedAgent(SERVER)).resolves.toBe(false);
+ });
+
+ it('counts a hand-built policy that names the owner, not just the shortcut', async () => {
+ // A rule set the chooser calls `custom` still leans on owner recognition,
+ // so an unlinked account costs the user just as much there.
+ listedAgents = [
+ listedAgent({
+ id: 'scoped',
+ owner_id: 'u1',
+ addressing_policy: {
+ rules: [
+ { rooms: ['room-1'], room_groups: '*', users: [], agents: [], owner: true },
+ { rooms: '*', room_groups: '*', users: ['u9'], agents: [], owner: false },
+ ],
+ },
+ }),
+ ];
+
+ await expect(ownsOwnerAddressedAgent(SERVER)).resolves.toBe(true);
+ });
+
+ it('stays quiet against a server that does not report policies on the list', async () => {
+ // Older switch-core carries `addressing_policy` only on `GET /agents/{id}`.
+ // Absent has to read as "nothing to warn about" rather than warn on a guess.
+ listedAgents = [listedAgent({ id: 'unknown-policy', owner_id: 'u1' })];
+
+ await expect(ownsOwnerAddressedAgent(SERVER)).resolves.toBe(false);
+ });
+
+ it('propagates a failed list read instead of answering false', async () => {
+ // The caller turns a rejection into a log line and no warning; a false here
+ // would be indistinguishable from a real "you own nothing restricted".
+ routedFetch.mockImplementation(async (url: string) =>
+ url.endsWith('/auth/me') ? okMeResponse() : errorResponse(503, 'gateway down')
+ );
+
+ await expect(ownsOwnerAddressedAgent(SERVER)).rejects.toMatchObject({ status: 503 });
+ });
+});
+
describe('updateBridge', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -559,3 +677,60 @@ describe('updateBridge', () => {
expect(JSON.parse(init.body)).toEqual({});
});
});
+
+describe('deleteBridge', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('DELETEs the bridge and reports it deleted', async () => {
+ fetchMock.mockResolvedValue(jsonResponse({ ok: true }) as never);
+
+ await expect(deleteBridge(SERVER, 'b1')).resolves.toEqual({ kind: 'deleted' });
+
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, { method: string }];
+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b1');
+ expect(init.method).toBe('DELETE');
+ });
+
+ it('escapes the bridge id into the path', async () => {
+ fetchMock.mockResolvedValue(jsonResponse({ ok: true }) as never);
+
+ await deleteBridge(SERVER, 'b/1 2');
+
+ const [url] = fetchMock.mock.calls[0] as unknown as [string];
+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b%2F1%202');
+ });
+
+ it('reports a non-admin as forbidden', async () => {
+ fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Admin only"}') as never);
+
+ await expect(deleteBridge(SERVER, 'b1')).resolves.toEqual({ kind: 'forbidden' });
+ });
+
+ it('reports an unknown bridge as not-found rather than deleted', async () => {
+ // Somebody else's deletion, or a stale list — either way the rooms this
+ // call would have taken with it were not this call's to take.
+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Bridge not found"}') as never);
+
+ await expect(deleteBridge(SERVER, 'gone')).resolves.toEqual({ kind: 'not-found' });
+ });
+
+ it('reports an expired session as unauthenticated', async () => {
+ fetchMock.mockResolvedValue(unauthorizedResponse() as never);
+
+ await expect(deleteBridge(SERVER, 'b1')).resolves.toEqual({ kind: 'unauthenticated' });
+ });
+
+ it('propagates a failure it has no case for instead of claiming success', async () => {
+ fetchMock.mockResolvedValue(errorResponse(500, 'adapter shutdown failed') as never);
+
+ await expect(deleteBridge(SERVER, 'b1')).rejects.toMatchObject({ status: 500 });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 7215693c1..7ecd52ecf 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -5,9 +5,13 @@ import {
} from '@main/core/managed-switch-server/managed-server-status';
import { ManagedServerStoppedError } from '@shared/core/managed-switch-server/managed-switch-server';
import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';
+import { policyNamesOwner } from '@shared/core/switch-servers/owner-policy';
import type {
AddressingPolicy,
BridgeConfigField,
+ BridgeDirectoryUser,
+ DeleteBridgeResult,
+ LinkedIdentity,
RemoteAgentRoom,
RemoteAgentSummary,
RemoteBridge,
@@ -279,7 +283,6 @@ export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {
export type RegisterKnownAgentOptions = {
channels_enabled: boolean;
repo_dir?: string;
- notify_user?: string;
/** When true, the agent registers with the `auto_session` connection model:
* Switch Console watches its rooms and auto-spawns a session on notification. */
auto_session?: boolean;
@@ -333,8 +336,10 @@ export async function fetchAgents(server: SwitchServer): Promise<RemoteAgentSumm
name: string;
description: string;
connector_type: string;
+ owner_id?: string | null;
owner_name: string | null;
known_agent_type: string | null;
+ addressing_policy?: AddressingPolicy | null;
created_at: string;
}>;
return json.map((a) => ({
@@ -342,8 +347,10 @@ export async function fetchAgents(server: SwitchServer): Promise<RemoteAgentSumm
name: a.name,
description: a.description,
connectorType: a.connector_type,
+ ownerId: a.owner_id ?? null,
ownerName: a.owner_name,
knownAgentType: a.known_agent_type,
+ addressingPolicy: a.addressing_policy ?? null,
createdAt: a.created_at,
}));
}
@@ -366,8 +373,10 @@ export async function fetchAgentDetail(
name: string;
description: string;
connector_type: string;
+ owner_id?: string | null;
owner_name: string | null;
known_agent_type: string | null;
+ addressing_policy?: AddressingPolicy | null;
created_at: string;
};
return {
@@ -375,8 +384,10 @@ export async function fetchAgentDetail(
name: json.name,
description: json.description,
connectorType: json.connector_type,
+ ownerId: json.owner_id ?? null,
ownerName: json.owner_name,
knownAgentType: json.known_agent_type,
+ addressingPolicy: json.addressing_policy ?? null,
createdAt: json.created_at,
};
}
@@ -502,6 +513,26 @@ export async function fetchAddressingPolicy(
return json.addressing_policy ?? null;
}
+/**
+ * Whether the signed-in user owns an agent here whose addressing policy admits
+ * its owner — the only case in which having claimed no messaging account costs
+ * them anything (CHOO-2137).
+ *
+ * Both halves of the answer are on the agent list — `GET /agents` carries each
+ * agent's `owner_id` and its policy — so this costs that list and `/auth/me`,
+ * however many agents the user owns.
+ *
+ * A server too old to report the policy on the list leaves every agent reading
+ * as open, so the warning stays quiet. That is the same answer as owning no
+ * restricted agent, and the safe direction for a warning to be wrong in.
+ */
+export async function ownsOwnerAddressedAgent(server: SwitchServer): Promise<boolean> {
+ const [me, agents] = await Promise.all([fetchMe(server), fetchAgents(server)]);
+ return agents.some(
+ (agent) => agent.ownerId === me.id && policyNamesOwner(agent.addressingPolicy)
+ );
+}
+
/**
* Set (or clear, with `policy = null`) an agent's addressing policy
* (`PUT /agents/{id}/addressing-policy`). Only the agent's owner (or an admin)
@@ -542,6 +573,8 @@ type BridgeJson = {
// could be asked to create a channel, and none had it withheld.
channel_creation_supported?: boolean;
channel_creation_enabled?: boolean;
+ // Absent on a server predating Telegram, where every bridge had a directory.
+ directory_search_supported?: boolean;
};
function mapBridge(b: BridgeJson): RemoteBridge {
@@ -556,6 +589,7 @@ function mapBridge(b: BridgeJson): RemoteBridge {
homeUrl: b.home_url ?? null,
channelCreationSupported,
canCreateChannels: channelCreationSupported && channelCreationEnabled,
+ directorySearchSupported: b.directory_search_supported ?? true,
};
}
@@ -620,6 +654,7 @@ export async function fetchBridgeTypes(server: SwitchServer): Promise<RemoteBrid
key: string;
config_schema: BridgeConfigSchema;
channel_creation_supported?: boolean;
+ directory_search_supported?: boolean;
}>;
return json.map((t) => ({
key: t.key,
@@ -627,6 +662,7 @@ export async function fetchBridgeTypes(server: SwitchServer): Promise<RemoteBrid
// Absent on a server predating the capability — every platform could be
// registered to create channels before it existed, so default true.
channelCreationSupported: t.channel_creation_supported ?? true,
+ directorySearchSupported: t.directory_search_supported ?? true,
}));
}
@@ -691,6 +727,57 @@ export async function updateBridge(
return mapBridge((await res.json()) as BridgeJson);
}
+/**
+ * Disconnect a collaboration bridge from `server` (admin-only
+ * `DELETE /collaborations/{id}`).
+ *
+ * **This deletes every Switch room on the bridge before removing it**, along
+ * with the conversations in them. It is the most destructive call on the
+ * gateway's collaboration router, not a pause that can be undone by attaching
+ * the platform again, and the caller is responsible for saying so before it is
+ * made.
+ *
+ * Recoverable failures are mapped so the caller can name them: a non-admin gets
+ * `forbidden`, and a bridge that is already gone gets `not-found` rather than a
+ * success. Anything else — a rejected adapter shutdown, an unexpected 500 —
+ * still throws, so a delete that did not happen can never read as one that did.
+ */
+export async function deleteBridge(
+ server: SwitchServer,
+ bridgeId: string
+): Promise<DeleteBridgeResult> {
+ try {
+ await gatewayFetch(server, `/collaborations/${encodeURIComponent(bridgeId)}`, {
+ authenticated: true,
+ method: 'DELETE',
+ });
+ return { kind: 'deleted' };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };
+ if (cause.kind === 'http' && cause.status === 404) return { kind: 'not-found' };
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
+
+/** The gateway `IdentityClaimant` wire shape. */
+type IdentityClaimantJson = {
+ user_id: string;
+ user_name: string;
+};
+
+/** The gateway `ExternalUserSummary` wire shape. */
+type ExternalUserSummaryJson = {
+ id: string;
+ bridge_id: string;
+ external_user_id: string;
+ external_username: string;
+ claimed_by?: IdentityClaimantJson[];
+};
+
/**
* Union of external (bridged human) users across every bridge on the server
* (`GET /collaborations`, then each bridge's `/users`). The addressing policy's
@@ -705,12 +792,137 @@ export async function fetchAllExternalUsers(server: SwitchServer): Promise<Remot
`/collaborations/${encodeURIComponent(bridge.id)}/users`,
{ authenticated: true }
);
- const users = (await res.json()) as Array<{ id: string; external_username: string }>;
+ const users = (await res.json()) as ExternalUserSummaryJson[];
for (const u of users) byId.set(u.id, { id: u.id, username: u.external_username });
}
return [...byId.values()];
}
+/**
+ * Search one bridge's own user directory (`GET /collaborations/{id}/directory`).
+ *
+ * This asks the messaging platform rather than Switch's record of who has
+ * spoken, which is what lets someone claim their account in a workspace they
+ * have never posted in. A platform with no searchable directory answers 501 and
+ * a stopped bridge 409; both surface as a `GatewayError` the caller maps onto
+ * something it can say out loud rather than an empty result list.
+ */
+export async function searchBridgeDirectory(
+ server: SwitchServer,
+ bridgeId: string,
+ query: string
+): Promise<{ users: BridgeDirectoryUser[]; note: string | null }> {
+ const res = await gatewayFetch(
+ server,
+ `/collaborations/${encodeURIComponent(bridgeId)}/directory?query=${encodeURIComponent(query)}`,
+ { authenticated: true }
+ );
+ type DirectoryUserJson = {
+ external_user_id: string;
+ username: string;
+ display_name: string;
+ email?: string | null;
+ known_external_user_id?: string | null;
+ claimed_by?: IdentityClaimantJson[];
+ };
+ // A switch-core predating the known-accounts fallback returns the bare array
+ // and refuses the search outright when the platform has no directory. Both
+ // shapes read the same here; the older one simply never carries a note.
+ const json = (await res.json()) as
+ | DirectoryUserJson[]
+ | { source?: string; note?: string | null; users?: DirectoryUserJson[] };
+ const rows = Array.isArray(json) ? json : (json.users ?? []);
+ return {
+ note: Array.isArray(json) ? null : (json.note ?? null),
+ users: rows.map((u) => ({
+ externalUserId: u.external_user_id,
+ username: u.username,
+ displayName: u.display_name,
+ email: u.email ?? null,
+ knownExternalUserId: u.known_external_user_id ?? null,
+ claimedBy: (u.claimed_by ?? []).map((c) => ({ userId: c.user_id, userName: c.user_name })),
+ })),
+ };
+}
+
+/**
+ * Claim a platform identity for the signed-in user
+ * (`POST /collaborations/{id}/identities`). `user_id` is deliberately omitted:
+ * Switch Console only ever claims on behalf of whoever is signed in, and
+ * claiming for someone else is an admin action that belongs in the operator
+ * dashboard. Claims are not exclusive, so an account someone else has already
+ * claimed is claimed normally; a 409 means only that the bridge is stopped and
+ * an unseen account cannot be provisioned, and surfaces as a `GatewayError`
+ * with that status.
+ */
+export async function claimBridgeIdentity(
+ server: SwitchServer,
+ bridgeId: string,
+ params: { externalUserId: string; username: string }
+): Promise<ExternalUserSummaryJson> {
+ const res = await gatewayFetch(
+ server,
+ `/collaborations/${encodeURIComponent(bridgeId)}/identities`,
+ {
+ authenticated: true,
+ method: 'POST',
+ body: { external_user_id: params.externalUserId, username: params.username },
+ }
+ );
+ return (await res.json()) as ExternalUserSummaryJson;
+}
+
+/**
+ * Drop one claim on a platform account
+ * (`DELETE /collaborations/{id}/identities/{rowId}`). `externalUserRowId` is
+ * the `ExternalUser` row id, not the platform's id.
+ *
+ * Several users can hold a claim on the same account, so `userId` says whose
+ * to drop; anyone else's is left standing. Null falls back to the server's
+ * default — the caller — which is what the app wants when the signed-in user's
+ * id has not been read from the server yet. Releasing someone else's claim is
+ * admin-only server-side.
+ */
+export async function releaseBridgeIdentity(
+ server: SwitchServer,
+ bridgeId: string,
+ externalUserRowId: string,
+ userId: string | null
+): Promise<void> {
+ const query = userId === null ? '' : `?user_id=${encodeURIComponent(userId)}`;
+ await gatewayFetch(
+ server,
+ `/collaborations/${encodeURIComponent(bridgeId)}/identities/${encodeURIComponent(externalUserRowId)}${query}`,
+ { authenticated: true, method: 'DELETE' }
+ );
+}
+
+/**
+ * The messaging accounts the signed-in user has claimed
+ * (`GET /auth/me/identities`). An agent whose policy names its owner is
+ * unreachable by that owner on any bridge missing from this list, so this is
+ * what the addressing UI checks before letting a policy seal an agent off.
+ */
+export async function fetchMyIdentities(server: SwitchServer): Promise<LinkedIdentity[]> {
+ const res = await gatewayFetch(server, '/auth/me/identities', { authenticated: true });
+ const json = (await res.json()) as Array<{
+ id: string;
+ bridge_id: string;
+ bridge_display_name: string;
+ bridge_type: string;
+ external_user_id: string;
+ external_username: string;
+ }>;
+ return json.map((i) => ({
+ id: i.id,
+ bridgeId: i.bridge_id,
+ bridgeDisplayName: i.bridge_display_name,
+ bridgeType: i.bridge_type,
+ externalUserId: i.external_user_id,
+ externalUsername: i.external_username,
+ }));
+}
+
/** A subagent registered via the bulk endpoint. `apiKey` is a secret — keep it
* in the main process (write it to the subagent's settings file); never pass it
* to the renderer. */
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
new file mode 100644
index 000000000..920157230
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
@@ -0,0 +1,105 @@
+import {
+ claimBridgeIdentity,
+ fetchBridges,
+ GatewayError,
+ searchBridgeDirectory,
+} from '@main/core/switch-servers/gateway-client';
+import type {
+ BridgeDirectorySearchResult,
+ ClaimIdentityParams,
+ ClaimIdentityResult,
+ SwitchServer,
+} from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * Linking a Switch user to their messaging-app account (CHOO-2137), with the
+ * gateway's recoverable failures mapped onto typed results.
+ *
+ * The mapping matters more here than elsewhere: a platform with no searchable
+ * directory and a platform where nobody matched are the same empty screen
+ * unless the difference is carried through, and the server's own wording is
+ * the only thing that tells the user what to do instead. Current servers
+ * narrow such a search to the accounts they have already seen and say so in a
+ * note; only an older one refuses it outright.
+ */
+
+/**
+ * Search a bridge's user directory. Anything the user can act on becomes a
+ * variant; an unexpected failure still throws, because inventing an empty
+ * result for a broken server is how a claim flow silently stops working.
+ */
+export async function searchDirectoryOnServer(
+ server: SwitchServer,
+ bridgeId: string,
+ query: string
+): Promise<BridgeDirectorySearchResult> {
+ try {
+ const { users, note } = await searchBridgeDirectory(server, bridgeId, query);
+ return { kind: 'results', users, note };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ // 501 — the platform has no directory to search. The detail explains that
+ // a message has to arrive first, which is the only route left.
+ if (cause.kind === 'http' && cause.status === 501) {
+ return { kind: 'unsupported', message: cause.detail ?? cause.message };
+ }
+ // 409 — the bridge is registered but its adapter is not running.
+ if (cause.kind === 'http' && cause.status === 409) {
+ return { kind: 'bridge-unavailable', message: cause.detail ?? cause.message };
+ }
+ // 502 — the platform itself refused or failed the lookup.
+ if (cause.kind === 'http' && cause.status === 502) {
+ return { kind: 'error', message: cause.detail ?? cause.message };
+ }
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
+
+/**
+ * Claim a directory entry as the signed-in user's own account, resolving the
+ * bridge's display name so the caller gets a complete `LinkedIdentity` rather
+ * than a row it has to name itself.
+ *
+ * Nothing here refuses an account other people have claimed — the server
+ * allows it, and each claimant is recognised as themselves on the account.
+ */
+export async function claimIdentityOnServer(
+ server: SwitchServer,
+ params: Omit<ClaimIdentityParams, 'serverId'>
+): Promise<ClaimIdentityResult> {
+ try {
+ const claimed = await claimBridgeIdentity(server, params.bridgeId, {
+ externalUserId: params.externalUserId,
+ username: params.username,
+ });
+ const bridge = (await fetchBridges(server)).find((b) => b.id === claimed.bridge_id);
+ return {
+ kind: 'claimed',
+ identity: {
+ id: claimed.id,
+ bridgeId: claimed.bridge_id,
+ // A bridge deleted between the claim and this read leaves nothing to
+ // name it by; its id still identifies the row rather than hiding it.
+ bridgeDisplayName: bridge?.displayName ?? claimed.bridge_id,
+ bridgeType: bridge?.type ?? '',
+ externalUserId: claimed.external_user_id,
+ externalUsername: claimed.external_username,
+ },
+ };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ // 409 — the bridge is not running, so an account Switch has never seen
+ // cannot be provisioned. Claiming an account someone else has claimed is
+ // not a conflict: claims are not exclusive.
+ if (cause.kind === 'http' && cause.status === 409) {
+ return { kind: 'bridge-unavailable', message: cause.detail ?? cause.message };
+ }
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts
index 8eaad67d0..fd62ec8bf 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts
@@ -85,6 +85,7 @@ describe('updateBridgeOnServer', () => {
homeUrl: null,
channelCreationSupported: true,
canCreateChannels: false,
+ directorySearchSupported: true,
},
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
index 3a860b044..8f90a698b 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
@@ -9,9 +9,11 @@ import { RenameSessionModal } from '@renderer/features/sessions/rename-session-m
import { AddAgentsToRoomModal } from '@renderer/features/switch-rooms/AddAgentsToRoomModal';
import { AddServerModal } from '@renderer/features/switch-servers/AddServerModal';
import { AssignServerModal } from '@renderer/features/switch-servers/assign-server-modal';
+import { ClaimIdentityModal } from '@renderer/features/switch-servers/ClaimIdentityModal';
import { ConnectMessagingAppModal } from '@renderer/features/switch-servers/ConnectMessagingAppModal';
import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomModal';
import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServerModal';
+import { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';
import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';
import { ConfirmActionDialog } from '@renderer/lib/components/confirm-action-dialog';
import { ExternalLinkChoiceDialog } from '@renderer/lib/components/external-link-choice-dialog';
@@ -68,6 +70,14 @@ export const modalRegistry = {
size: 'md',
dismissOnOutsideClick: false,
}),
+ claimIdentityModal: createModal(ClaimIdentityModal, {
+ size: 'md',
+ dismissOnOutsideClick: false,
+ }),
+ disconnectMessagingAppModal: createModal(DisconnectMessagingAppModal, {
+ size: 'sm',
+ dismissOnOutsideClick: false,
+ }),
addAgentsToRoomModal: createModal(AddAgentsToRoomModal, {
size: 'sm',
dismissOnOutsideClick: false,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
index e320a6b8c..97fb7bd14 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
@@ -3,11 +3,10 @@ import { CircleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useId } from 'react';
import { InfoTooltip } from '@renderer/features/settings/components/InfoTooltip';
-import {
- AddressingPolicyEditor,
- type OptionItem,
-} from '@renderer/features/switch-servers/addressing-policy-editor';
+import { AddressingPolicyControl } from '@renderer/features/switch-servers/addressing-policy-control';
+import type { OptionItem } from '@renderer/features/switch-servers/addressing-policy-editor';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
import { rpc } from '@renderer/lib/ipc';
import { Button } from '@renderer/lib/ui/button';
import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
@@ -79,6 +78,10 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({
label: a.name,
}));
+ // Read here rather than inside the editor so the owner-only default can be
+ // questioned before the agent exists, not after it has gone quiet.
+ const { identities } = useMyIdentities(serverId);
+
if (servers.length === 0) {
return (
<div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">
@@ -185,23 +188,25 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({
<Field>
<FieldLabel>
<span className="flex items-center gap-1.5">
- Who can address this agent
+ Who can send instructions
<InfoTooltip
label="More info about addressing"
- content="Addressing means an @mention, a targeted message, or a delegated task. Open allows any room participant; restricted permits only senders matching a rule. You can change this later from the agent's settings."
+ content="Sending instructions means an @mention, a targeted message, or a delegated task. A new agent answers only you; grant other agents to let them delegate to it. You can change this later from the agent's settings."
/>
</span>
</FieldLabel>
- <span className="text-xs text-foreground-muted">
- Open to everyone, or restricted to matching senders.
- </span>
- <AddressingPolicyEditor
+ <AddressingPolicyControl
value={form.addressingPolicy}
onChange={form.setAddressingPolicy}
rooms={roomOptions}
roomGroups={groupOptions}
users={userOptions}
agents={agentOptions}
+ linkedIdentities={identities}
+ // No claim button: this panel is inside a modal, and the app shows one
+ // at a time — opening the claim dialog here would throw away the form
+ // the user is halfway through. The warning names where to go instead.
+ onClaimIdentity={null}
/>
</Field>
</FieldGroup>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx
index f97c88cf1..86d00b455 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx
@@ -47,12 +47,27 @@ export function LaunchProfileConfig({
}) {
const [open, setOpen] = useState(false);
+ // Which surface this provider actually keeps its settings in. `advancedFields`
+ // below answers "the fields, from wherever they live" and falls back to the
+ // definition fields for a provider that has those — which is the same list
+ // `AgentAdvancedConfig` renders beside this, so Claude Code showed two
+ // identical "Advanced configuration" sections. Only one of the two surfaces
+ // exists per provider; this is how the agent's Settings tab picks, and the
+ // creation form has to pick the same way or the two disagree about what an
+ // agent even has.
+ const { data: surface } = useQuery({
+ queryKey: ['agentAdvancedSurface', providerId],
+ queryFn: () =>
+ providerId ? rpc.agents.advancedSurface({ providerId }) : Promise.resolve('none' as const),
+ enabled: !!providerId,
+ });
+
const { data } = useQuery({
queryKey: ['agentAdvancedFields', providerId],
queryFn: () => (providerId ? rpc.agents.advancedFields({ providerId }) : Promise.resolve([])),
enabled: !!providerId,
});
- const fields = useMemo(() => data ?? [], [data]);
+ const fields = useMemo(() => (surface === 'launch-profile' ? (data ?? []) : []), [data, surface]);
// The models that host offers, for the fields bound to it. Asked of the host
// the agent will run on, since that is what decides the answer — and only once
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
index 232a202c4..734e91ea5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { rpc } from '@renderer/lib/ipc';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';
import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';
import { basenameFromAnyPath } from '@shared/path-name';
@@ -65,9 +66,11 @@ export function useConfigureAgentForm(
const [descriptionTouched, setDescriptionTouched] = useState(false);
const [autoSession, setAutoSession] = useState(true);
const [autoApprove, setAutoApprove] = useState(defaultAutoApprove);
- // Scoped addressing policy (CHOO-1585). null = open (default); set to restrict
- // who can address the new agent. Applied via a follow-up PUT after creation.
- const [addressingPolicy, setAddressingPolicy] = useState<AddressingPolicy | null>(null);
+ // Scoped addressing policy (CHOO-1585). null = open; a new agent starts
+ // owner-scoped (CHOO-2137). Applied via a follow-up PUT after creation.
+ const [addressingPolicy, setAddressingPolicy] = useState<AddressingPolicy | null>(() =>
+ ownerOnlyPolicy()
+ );
const trimmedDir = dir.trim();
// suggestAgentDefaults derives name/description from the directory basename and
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
index cb0c7d5f2..ef232d401 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
@@ -1,14 +1,16 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { InfoTooltip } from '@renderer/features/settings/components/InfoTooltip';
+import { AddressingPolicyControl } from '@renderer/features/switch-servers/addressing-policy-control';
import {
- AddressingPolicyEditor,
type OptionItem,
policyHasDeadRule,
} from '@renderer/features/switch-servers/addressing-policy-editor';
+import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
import { rpc } from '@renderer/lib/ipc';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
-import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';
+import { Field, FieldTitle } from '@renderer/lib/ui/field';
import { log } from '@renderer/utils/logger';
import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';
@@ -39,16 +41,13 @@ export function AddressingPolicySettingsSection({
<Field>
<FieldTitle>
<span className="flex items-center gap-1.5">
- Who can address this agent
+ Who can send instructions
<InfoTooltip
label="More info about addressing"
- content="Addressing means an @mention, a targeted message, or a delegated task. Open allows any room participant; restricted permits only senders matching a rule."
+ content="Sending instructions means an @mention, a targeted message, or a delegated task. Only you, anyone in the agent's rooms, or whoever a rule admits."
/>
</span>
</FieldTitle>
- <FieldDescription className="text-foreground-muted">
- Open to everyone, or restricted to matching senders.
- </FieldDescription>
<div className="flex flex-col gap-4">
{switchAgents.map((agent) => (
<AddressingPolicyRow
@@ -76,6 +75,8 @@ function AddressingPolicyRow({
showName: boolean;
}) {
const queryClient = useQueryClient();
+ const showClaimIdentity = useShowModal('claimIdentityModal');
+ const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);
const [draft, setDraft] = useState<AddressingPolicy | null>(null);
const [dirty, setDirty] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -101,6 +102,15 @@ function AddressingPolicyRow({
queryKey: ['remote-agents', serverId],
queryFn: () => rpc.switchServers.listRemoteAgents(serverId),
});
+ const bridges = useQuery({
+ queryKey: ['remote-bridges', serverId],
+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ });
+ // Which workspace the "link my account" button opens on. The claim modal is
+ // per-bridge, so one has to be named: the default bridge is where this
+ // server's rooms land, and the rest are reachable from the server page.
+ const claimBridge =
+ (bridges.data ?? []).find((b) => b.isDefault) ?? (bridges.data ?? [])[0] ?? null;
// Until the user edits, show the saved policy; once dirty, show the draft.
const value = dirty ? draft : (saved ?? null);
@@ -133,9 +143,9 @@ function AddressingPolicyRow({
const displayName = agentOptions.find((o) => o.id === agentId)?.label ?? agentName;
return (
- <div className="flex flex-col gap-2 rounded-md border border-border p-3">
+ <div className="flex flex-col gap-2">
{showName && <span className="text-sm font-medium">{displayName}</span>}
- <AddressingPolicyEditor
+ <AddressingPolicyControl
value={value}
onChange={(next) => {
setDraft(next);
@@ -145,6 +155,17 @@ function AddressingPolicyRow({
roomGroups={groupOptions}
users={userOptions}
agents={agentOptions}
+ linkedIdentities={identities}
+ onClaimIdentity={
+ claimBridge === null
+ ? null
+ : () =>
+ showClaimIdentity({
+ serverId,
+ bridgeId: claimBridge.id,
+ onSuccess: () => refreshIdentities(),
+ })
+ }
disabled={mutation.isPending}
/>
{error && <span className="text-destructive text-xs">{error}</span>}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
index fbe8b3745..a25d1678a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
@@ -201,7 +201,7 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti
<FieldDescription className="text-foreground-muted">
The agent&apos;s model, reasoning effort, tools, and system prompt. The agent name is fixed.
</FieldDescription>
- <div className="flex flex-col gap-4 rounded-md border border-border px-3 py-3">
+ <div className="flex flex-col gap-4">
{fields.map((field) => {
const catalogueState = fieldCatalogueState(field, form, catalogue);
const rendered = fieldWithCatalogue(field, catalogueState);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
new file mode 100644
index 000000000..cfa3aa07c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
@@ -0,0 +1,414 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { CircleAlert, Info } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useState } from 'react';
+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { useDebounce } from '@renderer/lib/hooks/useDebounce';
+import { rpc } from '@renderer/lib/ipc';
+import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
+import { Badge } from '@renderer/lib/ui/badge';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Field, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import type {
+ BridgeDirectorySearchResult,
+ BridgeDirectoryUser,
+ ClaimIdentityResult,
+ LinkedIdentity,
+} from '@shared/core/switch-servers/switch-servers';
+import { switchServersStore } from './switch-servers-store';
+import { useMyIdentities } from './use-my-identities';
+
+/** How long to wait after the last keystroke before asking the platform. Every
+ * search is a live call out to Slack or Mattermost, so this is a courtesy to
+ * their rate limits as much as to ours. */
+const SEARCH_DEBOUNCE_MS = 300;
+
+/** Below this the directory returns most of the workspace, which is neither
+ * useful to scan nor cheap to fetch. */
+const MIN_QUERY_LENGTH = 2;
+
+type ClaimIdentityModalArgs = {
+ /** Claim on this server instead of the active one. */
+ serverId?: string;
+ /** The messaging app to claim an account in. Required: an account is claimed
+ * in one workspace, and every entry point knows which one it opened from —
+ * asking again would be a question the caller has already answered. */
+ bridgeId: string;
+};
+
+type Props = BaseModalProps<{ identity: LinkedIdentity }> & ClaimIdentityModalArgs;
+
+/**
+ * Link the signed-in Switch user to their own messaging-app account
+ * (CHOO-2137).
+ *
+ * Until Switch knows which platform account is which person, an addressing rule
+ * that names an agent's owner can never recognise them — so this is what makes
+ * owner-only addressing work at all, and why it is offered straight after a
+ * messaging app is connected.
+ *
+ * The search goes to the platform's own directory rather than Switch's record
+ * of who has spoken, so a user can find themselves in a workspace they have
+ * never posted in.
+ */
+export const ClaimIdentityModal = observer(function ClaimIdentityModal({
+ serverId: overrideServerId,
+ bridgeId,
+ onSuccess,
+ onClose,
+}: Props) {
+ const { setCloseGuard } = useModalContext();
+ const queryClient = useQueryClient();
+
+ const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';
+ const currentUserId = switchServersStore.statusFor(serverId)?.user?.id ?? null;
+
+ const [search, setSearch] = useState('');
+ const [claiming, setClaiming] = useState<string | null>(null);
+ const [releasing, setReleasing] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const { identities, refresh: refreshIdentities } = useMyIdentities(serverId || null);
+
+ const bridgesQuery = useQuery({
+ queryKey: ['remote-bridges', serverId],
+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ enabled: !!serverId,
+ });
+ const bridges = bridgesQuery.data ?? [];
+
+ // Names the workspace being searched. Null only while the list is in flight
+ // or when the named bridge has since been removed — the second is reported
+ // rather than searched around.
+ const selectedBridge = bridges.find((b) => b.id === bridgeId) ?? null;
+ const bridgeIsGone = !bridgesQuery.isLoading && bridges.length > 0 && selectedBridge === null;
+ const alreadyLinked = (identities ?? []).find((i) => i.bridgeId === bridgeId) ?? null;
+
+ const debouncedQuery = useDebounce(search.trim(), SEARCH_DEBOUNCE_MS);
+ const searchable = !!serverId && debouncedQuery.length >= MIN_QUERY_LENGTH;
+ const directoryQuery = useQuery({
+ queryKey: ['bridge-directory', serverId, bridgeId, debouncedQuery],
+ queryFn: () =>
+ rpc.switchServers.searchBridgeDirectory({
+ serverId,
+ bridgeId,
+ query: debouncedQuery,
+ }),
+ enabled: searchable,
+ });
+
+ const handleClaim = async (person: BridgeDirectoryUser) => {
+ setClaiming(person.externalUserId);
+ setCloseGuard(true);
+ setError(null);
+ try {
+ const result = await rpc.switchServers.claimBridgeIdentity({
+ serverId,
+ bridgeId,
+ externalUserId: person.externalUserId,
+ username: person.username,
+ });
+ if (result.kind !== 'claimed') {
+ setError(claimFailureText(result));
+ return;
+ }
+ refreshIdentities();
+ onSuccess({ identity: result.identity });
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setClaiming(null);
+ setCloseGuard(false);
+ }
+ };
+
+ // Undo, in place: the row the user just linked is the row they look at when
+ // they realise it is the wrong account, so the modal stays open and the
+ // directory is re-read to show who is left holding the account.
+ const handleRelease = async (person: BridgeDirectoryUser) => {
+ if (person.knownExternalUserId === null) return;
+ setReleasing(person.externalUserId);
+ setCloseGuard(true);
+ setError(null);
+ try {
+ await rpc.switchServers.releaseBridgeIdentity({
+ serverId,
+ bridgeId,
+ identityId: person.knownExternalUserId,
+ userId: currentUserId,
+ });
+ refreshIdentities();
+ await queryClient.invalidateQueries({ queryKey: ['bridge-directory', serverId, bridgeId] });
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setReleasing(null);
+ setCloseGuard(false);
+ }
+ };
+
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>
+ Link your {bridgePlatformLabel(selectedBridge?.type)} user account
+ </DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="pt-0">
+ <div className="flex w-full flex-col gap-5">
+ <p className="text-xs text-foreground-muted">
+ Tell Switch which account is you, so your own agents can tell it&apos;s you.
+ </p>
+
+ {!serverId && (
+ <p className="text-destructive text-xs">
+ No Switch server is selected. Choose a server in the sidebar first.
+ </p>
+ )}
+
+ {bridgeIsGone && (
+ <p className="text-destructive text-xs">
+ That messaging app is no longer connected to this server.
+ </p>
+ )}
+
+ {alreadyLinked && (
+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">
+ <Info className="mt-0.5 size-3.5 shrink-0 text-foreground-muted" />
+ <span>
+ You are already linked to{' '}
+ <span className="font-medium">{alreadyLinked.externalUsername}</span> on{' '}
+ {alreadyLinked.bridgeDisplayName}. Linking another account here keeps that one too —
+ search for it to unlink it, or use that app&apos;s row on the server page.
+ </span>
+ </div>
+ )}
+
+ {/* The workspace, not the platform: two of them on the same platform
+ can be connected, and only the name tells them apart. */}
+ <Field>
+ <FieldLabel>Search {selectedBridge?.displayName ?? 'the workspace'}</FieldLabel>
+ <Input
+ autoFocus
+ placeholder="Your name, handle or email"
+ value={search}
+ spellCheck={false}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setError(null);
+ }}
+ />
+ </Field>
+
+ <DirectoryResults
+ query={debouncedQuery}
+ searchable={searchable}
+ platform={bridgePlatformLabel(selectedBridge?.type ?? '')}
+ hasDirectory={selectedBridge?.directorySearchSupported ?? true}
+ isFetching={directoryQuery.isFetching}
+ result={directoryQuery.data ?? null}
+ fetchError={directoryQuery.error}
+ currentUserId={currentUserId}
+ claimingId={claiming}
+ releasingId={releasing}
+ onClaim={(person) => void handleClaim(person)}
+ onRelease={(person) => void handleRelease(person)}
+ />
+
+ {error && <p className="text-destructive text-xs">{error}</p>}
+ </div>
+ </DialogContentArea>
+ <DialogFooter>
+ {/* Skippable on purpose: this modal interrupts whatever the user came to
+ do, and an unlinked account costs them nothing until they restrict an
+ agent to its owner. */}
+ <Button
+ variant="outline"
+ onClick={onClose}
+ disabled={claiming !== null || releasing !== null}
+ >
+ Skip for now
+ </Button>
+ </DialogFooter>
+ </>
+ );
+});
+
+function DirectoryResults({
+ query,
+ searchable,
+ platform,
+ hasDirectory,
+ isFetching,
+ result,
+ fetchError,
+ currentUserId,
+ claimingId,
+ releasingId,
+ onClaim,
+ onRelease,
+}: {
+ query: string;
+ searchable: boolean;
+ /** The platform as a person names it, for the line that says what is being
+ * searched. */
+ platform: string;
+ /** Whether the platform has a directory at all. When it does not, the only
+ * people findable are those Switch has already seen — so the prompt has to
+ * say that rather than promise a workspace directory the platform has no
+ * concept of. */
+ hasDirectory: boolean;
+ isFetching: boolean;
+ result: BridgeDirectorySearchResult | null;
+ fetchError: unknown;
+ currentUserId: string | null;
+ /** The platform id of the account being linked, or null when none is. */
+ claimingId: string | null;
+ /** The platform id of the account being unlinked, or null when none is. */
+ releasingId: string | null;
+ onClaim: (person: BridgeDirectoryUser) => void;
+ onRelease: (person: BridgeDirectoryUser) => void;
+}) {
+ if (!searchable) {
+ return (
+ <p className="text-xs text-foreground-muted">
+ {hasDirectory
+ ? `Type at least ${MIN_QUERY_LENGTH} characters to search the workspace directory.`
+ : `Type at least ${MIN_QUERY_LENGTH} characters to search the people Switch has seen on ${platform}. It has no directory to search — someone appears here once they have sent a message.`}
+ </p>
+ );
+ }
+ if (fetchError) {
+ return (
+ <p className="text-destructive text-xs">
+ Could not search the directory:{' '}
+ {fetchError instanceof Error ? fetchError.message : String(fetchError)}
+ </p>
+ );
+ }
+ if (isFetching && result === null) {
+ return (
+ <p className="flex items-center gap-2 text-xs text-foreground-muted">
+ <Spinner className="size-3.5" />
+ Searching…
+ </p>
+ );
+ }
+ if (result === null) return null;
+
+ // A platform with no directory to search is not an empty result — the server
+ // says what has to happen instead, and that is the only useful thing to show.
+ if (result.kind === 'unsupported' || result.kind === 'bridge-unavailable') {
+ return (
+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">
+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />
+ <span>{result.message}</span>
+ </div>
+ );
+ }
+ if (result.kind === 'unauthenticated') {
+ return (
+ <p className="text-destructive text-xs">
+ Your session for this server expired. Sign in again, then retry.
+ </p>
+ );
+ }
+ if (result.kind === 'error') {
+ return <p className="text-destructive text-xs">{result.message}</p>;
+ }
+ // Set when the platform has no directory and the server answered from the
+ // accounts it has already seen. The list is real but cannot be complete, so
+ // it is captioned rather than replaced — replacing it is what left Telegram
+ // with a warning and no way forward.
+ const narrowed = result.note !== null && (
+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">
+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />
+ <span>{result.note}</span>
+ </div>
+ );
+
+ if (result.users.length === 0) {
+ return (
+ <div className="flex flex-col gap-2">
+ {narrowed}
+ <p className="text-xs text-foreground-muted">
+ {result.note === null
+ ? `Nobody in this workspace matches “${query}”.`
+ : `Nobody Switch has seen here matches “${query}”.`}
+ </p>
+ </div>
+ );
+ }
+
+ // Nothing here is disabled because someone else holds the account: several
+ // people can be recognised on the same one, and the other claimants are shown
+ // so a shared or misidentified account is visible rather than silent.
+ const pending = claimingId !== null || releasingId !== null;
+ return (
+ <div className="flex flex-col gap-2">
+ {narrowed}
+ <ul className="flex max-h-64 flex-col gap-1 overflow-y-auto">
+ {result.users.map((person) => {
+ const linkedToMe = person.claimedBy.some((c) => c.userId === currentUserId);
+ const others = person.claimedBy.filter((c) => c.userId !== currentUserId);
+ return (
+ <li
+ key={person.externalUserId}
+ className="flex items-center justify-between gap-3 rounded-md border border-border p-2"
+ >
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate text-sm text-foreground">{person.displayName}</span>
+ <span className="truncate text-xs text-foreground-muted">
+ @{person.username}
+ {person.email ? ` · ${person.email}` : ''}
+ </span>
+ {others.length > 0 && (
+ <span className="truncate text-xs text-foreground-muted">
+ Also linked to {others.map((c) => c.userName).join(', ')}
+ </span>
+ )}
+ </div>
+ {linkedToMe ? (
+ <span className="flex shrink-0 items-center gap-2">
+ <Badge variant="secondary">Linked to you</Badge>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={pending || person.knownExternalUserId === null}
+ onClick={() => onRelease(person)}
+ >
+ {releasingId === person.externalUserId ? 'Unlinking…' : 'Unlink'}
+ </Button>
+ </span>
+ ) : (
+ <Button size="sm" disabled={pending} onClick={() => onClaim(person)}>
+ {claimingId === person.externalUserId ? 'Linking…' : 'This is me'}
+ </Button>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
+
+/** Turn a failed claim into something the user can act on. */
+function claimFailureText(result: Exclude<ClaimIdentityResult, { kind: 'claimed' }>): string {
+ switch (result.kind) {
+ case 'unauthenticated':
+ return 'Your session for this server expired. Sign in again, then retry.';
+ case 'bridge-unavailable':
+ return result.message;
+ case 'error':
+ return result.message;
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
index 068b89f5d..8899cb9da 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
@@ -34,7 +34,13 @@ type ConnectMessagingAppModalArgs = {
serverId?: string;
};
-type Props = BaseModalProps<{ bridgeId: string }> & ConnectMessagingAppModalArgs;
+/** What the caller needs to decide what to do next. `directorySearchSupported`
+ * says whether there is any point offering the link-your-account step: on a
+ * platform without a directory, a connection nobody has used yet knows nobody,
+ * so the search would be a form that cannot be filled in. */
+type ConnectedApp = { bridgeId: string; directorySearchSupported: boolean };
+
+type Props = BaseModalProps<ConnectedApp> & ConnectMessagingAppModalArgs;
export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModal({
serverId: overrideServerId,
@@ -119,7 +125,10 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
setError(messageFor(result));
return;
}
- onSuccess({ bridgeId: result.bridge.id });
+ onSuccess({
+ bridgeId: result.bridge.id,
+ directorySearchSupported: selectedType.directorySearchSupported,
+ });
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
} finally {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
new file mode 100644
index 000000000..46cef34e4
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
@@ -0,0 +1,138 @@
+import { TriangleAlert } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useState } from 'react';
+import { rpc } from '@renderer/lib/ipc';
+import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
+import { Button } from '@renderer/lib/ui/button';
+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import type { DeleteBridgeResult } from '@shared/core/switch-servers/switch-servers';
+
+type DisconnectMessagingAppModalArgs = {
+ serverId: string;
+ bridgeId: string;
+ bridgeDisplayName: string;
+};
+
+type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;
+
+/**
+ * Confirm disconnecting a messaging app from a Switch server (CHOO-2137).
+ *
+ * "Disconnect" undersells it: the server deletes every Switch room on the
+ * bridge before removing the bridge itself, so this is the most destructive
+ * thing on the server page after deleting the server. It is guarded the same
+ * way — type the name — because an accidental click here costs rooms, not a
+ * setting.
+ *
+ * No room count is shown. The renderer's room list is what the signed-in user
+ * is allowed to see, which is not necessarily every room on the bridge, and a
+ * number that undercounts on a dialog like this is worse than no number.
+ */
+export const DisconnectMessagingAppModal = observer(function DisconnectMessagingAppModal({
+ bridgeDisplayName,
+ bridgeId,
+ serverId,
+ onSuccess,
+ onClose,
+}: Props) {
+ const [confirmText, setConfirmText] = useState('');
+ const [isDeleting, setIsDeleting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const typeConfirmed = confirmText.trim() === bridgeDisplayName.trim();
+
+ const handleDelete = useCallback(async () => {
+ if (!typeConfirmed) return;
+ setIsDeleting(true);
+ setError(null);
+ try {
+ const result = await rpc.switchServers.deleteBridge({ serverId, bridgeId });
+ if (result.kind !== 'deleted') {
+ setError(failureText(result));
+ setIsDeleting(false);
+ return;
+ }
+ onSuccess();
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ setIsDeleting(false);
+ }
+ }, [typeConfirmed, serverId, bridgeId, onSuccess]);
+
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <div className="flex items-center gap-2">
+ <TriangleAlert className="size-4 text-red-500" />
+ <DialogTitle>Disconnect “{bridgeDisplayName}”?</DialogTitle>
+ </div>
+ </DialogHeader>
+ <DialogContentArea className="space-y-3 pt-0">
+ <p className="text-sm text-foreground-muted">
+ This deletes <strong className="text-foreground">every Switch room on this app</strong>,
+ along with their history, and then removes the connection. This can’t be undone.
+ </p>
+ <p className="text-sm text-foreground-muted">
+ The channels in {bridgeDisplayName} are not deleted — they stay where they are, with
+ nothing bridging them to Switch.
+ </p>
+
+ <FieldGroup>
+ <Field>
+ <FieldLabel>
+ Type <span className="font-medium text-foreground">{bridgeDisplayName}</span> to
+ confirm
+ </FieldLabel>
+ <Input
+ value={confirmText}
+ onChange={(e) => {
+ setConfirmText(e.target.value);
+ setError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && typeConfirmed) void handleDelete();
+ }}
+ autoFocus
+ />
+ </Field>
+ </FieldGroup>
+
+ {error && <p className="text-destructive text-xs">{error}</p>}
+ </DialogContentArea>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose} disabled={isDeleting}>
+ Cancel
+ </Button>
+ <ConfirmButton
+ variant="destructive"
+ onClick={() => void handleDelete()}
+ disabled={!typeConfirmed || isDeleting}
+ >
+ {isDeleting ? 'Disconnecting…' : 'Disconnect app'}
+ </ConfirmButton>
+ </DialogFooter>
+ </>
+ );
+});
+
+/** Turn a refused disconnect into something the user can act on. */
+function failureText(result: Exclude<DeleteBridgeResult, { kind: 'deleted' }>): string {
+ switch (result.kind) {
+ case 'unauthenticated':
+ return 'Your session for this server expired. Sign in again, then retry.';
+ case 'forbidden':
+ return 'Disconnecting a messaging app requires an admin account on this server.';
+ case 'not-found':
+ return 'That messaging app is no longer connected to this server.';
+ case 'error':
+ return result.message;
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
index def606463..38943a7fc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
@@ -1,7 +1,16 @@
import { useQueryClient, useQuery } from '@tanstack/react-query';
-import { ExternalLink, MessageSquare, Plus } from 'lucide-react';
+import {
+ CircleAlert,
+ ExternalLink,
+ Link2,
+ MessageSquare,
+ MoreVertical,
+ Plus,
+ Trash2,
+ Unlink,
+} from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { rpc } from '@renderer/lib/ipc';
@@ -9,22 +18,43 @@ import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { openExternalUrl } from '@renderer/lib/open-external';
import { Badge } from '@renderer/lib/ui/badge';
import { Button } from '@renderer/lib/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@renderer/lib/ui/dropdown-menu';
import { Spinner } from '@renderer/lib/ui/spinner';
-import { Switch } from '@renderer/lib/ui/switch';
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@renderer/lib/ui/tooltip';
-import type { RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import { log } from '@renderer/utils/logger';
+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
import { BundledChatSignIn } from './BundledChatSignIn';
+import {
+ hasUnlinkedMessagingApp,
+ shouldOfferIdentityLinkOnConnect,
+ unrecognisedMessagingApps,
+ unrecognisedMessagingAppsMessage,
+} from './messaging-apps-warning';
import { switchRoomsStore } from './switch-rooms-store';
import { switchServersStore } from './switch-servers-store';
+import { useMyIdentities } from './use-my-identities';
/**
- * The messaging apps bridged to a server, and — for an admin — the way to
- * connect another (CHOO-1784).
+ * The messaging apps bridged to a server, which account in each one is the
+ * signed-in user, and — for an admin — the way to connect another
+ * (CHOO-1784, CHOO-2137).
+ *
+ * One row per app, read as a table: the app on the left, your account on it in
+ * a column of its own, its actions on the right. An app you have not linked
+ * says so by offering a Link button and nothing else — the fact is worth one
+ * control, not a sentence repeated down the card.
*
* Listing is offered on every server type, not just managed ones: a bridge is
* registered through the server's own admin API, so there is nothing
* Switch Console has to own locally for this to work. Attaching is gated on the
- * signed-in user being an admin, because the endpoint is.
+ * signed-in user being an admin, because the endpoint is; linking an account is
+ * not, because claiming an identity is something every user does for themselves.
*/
export const MessagingAppsCard = observer(function MessagingAppsCard({
serverId,
@@ -35,6 +65,8 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
}) {
const queryClient = useQueryClient();
const showConnectMessagingApp = useShowModal('connectMessagingAppModal');
+ const showClaimIdentity = useShowModal('claimIdentityModal');
+ const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');
const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';
// Only a stack Switch Console runs has a chat whose credentials it generated and
// can therefore show; anyone else's Mattermost is their own to hand out.
@@ -48,6 +80,47 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
const bridges = bridgesQuery.data ?? [];
+ const {
+ identities,
+ error: identitiesError,
+ refresh: refreshIdentities,
+ } = useMyIdentities(serverId);
+ // Whose claim to drop when unlinking. Every account here is one the signed-in
+ // user claimed, and other people may hold the same one — so name the user
+ // rather than let the server infer it. Null until the session is read back,
+ // where the server falls back to the caller, which is the same person.
+ const currentUserId = switchServersStore.statusFor(serverId)?.user?.id ?? null;
+
+ // Whether an unlinked app actually costs this user anything. Asked only once
+ // the cheap half of the condition holds — there is an app they have not
+ // linked — because a user who has linked everywhere has nothing to be warned
+ // about, so the answer would go nowhere. The probe itself is one agent-list
+ // read, so it is not cached beyond that: linking an account or changing an
+ // agent's policy should stop the warning on the next look, not a minute later.
+ const anyUnlinked = hasUnlinkedMessagingApp(bridges, identities);
+ const ownerAgentsQuery = useQuery({
+ queryKey: ['owns-owner-addressed-agent', serverId],
+ queryFn: () => rpc.switchServers.ownsOwnerAddressedAgent(serverId),
+ enabled: !!serverId && anyUnlinked,
+ });
+ // The probe failing costs no data on screen, only the warning — so it is
+ // logged rather than shown, and the card does not warn on a guess.
+ const ownerAgentsError = ownerAgentsQuery.error;
+ useEffect(() => {
+ if (ownerAgentsError) {
+ log.warn('Could not check for owner-addressed agents', {
+ serverId,
+ error: ownerAgentsError,
+ });
+ }
+ }, [ownerAgentsError, serverId]);
+
+ const unrecognisedIn = unrecognisedMessagingApps({
+ bridges,
+ identities,
+ ownsOwnerAddressedAgent: ownerAgentsQuery.isSuccess ? ownerAgentsQuery.data : null,
+ });
+
// Which bridge's channel-creation switch is mid-flight, so only that row
// disables rather than the whole list, and the surfaced error names the one
// connection that failed.
@@ -91,11 +164,26 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
onClick={() =>
showConnectMessagingApp({
serverId,
- onSuccess: () => {
+ onSuccess: ({ bridgeId, directorySearchSupported }) => {
// Refresh the bridge list everywhere it is consumed — this
// card and the room-creation picker share the query key.
void queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });
void switchRoomsStore.refreshRoomState();
+ // Step 2 of connecting a workspace: say which account in it
+ // is yours (CHOO-2137). Offered here because this is the one
+ // moment the workspace is on the user's mind, and it is
+ // skippable — the new bridge's own row reopens it later.
+ //
+ // Not offered at all on a platform with no searchable
+ // directory: Switch can only name people who have spoken to
+ // it there, and nobody has spoken to a connection made a
+ // second ago. The search would be guaranteed empty, which
+ // teaches the user that they are not in their own workspace.
+ // Linking waits for the server page, by which time someone
+ // has messaged the app and there is a name to pick.
+ if (shouldOfferIdentityLinkOnConnect({ directorySearchSupported })) {
+ showClaimIdentity({ serverId, bridgeId });
+ }
},
})
}
@@ -106,6 +194,26 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
)}
</div>
+ <p className="mt-1 text-xs text-foreground-muted">
+ Which account is you in each app, so your agents can recognise you.
+ </p>
+
+ {/* Same shape as the addressing editor's owner warning, so the two
+ readings of one problem look like one problem. */}
+ {unrecognisedIn.length > 0 && (
+ <div className="mt-2 flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">
+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />
+ <span>{unrecognisedMessagingAppsMessage(unrecognisedIn)}</span>
+ </div>
+ )}
+
+ {identitiesError !== null && (
+ <p className="text-destructive mt-2 text-xs">
+ Could not load your linked accounts:{' '}
+ {identitiesError instanceof Error ? identitiesError.message : String(identitiesError)}
+ </p>
+ )}
+
{bridgesQuery.isError ? (
<p className="text-destructive mt-3 text-xs">
Could not load messaging apps:{' '}
@@ -120,74 +228,41 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
: 'No messaging app is connected. An admin on this server can connect one.'}
</p>
) : (
- <ul className="mt-3 space-y-2">
+ <ul className="mt-2 divide-y divide-border">
{bridges.map((bridge) => (
- <li key={bridge.id} className="text-sm">
- <div className="flex items-center gap-2">
- {hasBridgeIcon(bridge.type) ? (
- <BridgeIcon bridgeType={bridge.type} size={16} />
- ) : (
- <MessageSquare className="size-4 text-foreground-muted" />
- )}
- <span className="min-w-0 flex-1 truncate text-foreground">
- {bridge.displayName}
- </span>
- {/* Offered only when the link resolves — an older server, or a
- bridge that is down, reports none, and a button that cannot
- do anything is worse than no button. */}
- {bridge.homeUrl && (
- <Button
- variant="ghost"
- size="sm"
- aria-label={`Open ${bridgePlatformLabel(bridge.type)}`}
- onClick={() =>
- void openExternalUrl(
- bridge.homeUrl as string,
- `Could not open ${bridgePlatformLabel(bridge.type)}`
- )
- }
- >
- <ExternalLink className="size-3.5" />
- Open
- </Button>
- )}
- {bridge.isDefault && <Badge variant="secondary">Default</Badge>}
- {/* Surfaced only when it is NOT active: a bridge that is down
- cannot back a new room, and the room-creation picker silently
- omits it, so this is where that becomes visible. */}
- {bridge.status !== 'active' && <Badge variant="destructive">{bridge.status}</Badge>}
- <TooltipProvider delay={150}>
- <Tooltip>
- <TooltipTrigger>
- <span className="flex shrink-0 items-center gap-1.5 text-xs text-foreground-muted">
- Channels
- <Switch
- size="sm"
- checked={bridge.canCreateChannels}
- disabled={
- !isAdmin ||
- !bridge.channelCreationSupported ||
- savingBridgeId === bridge.id
- }
- onCheckedChange={(next) => void handleToggleChannelCreation(bridge, next)}
- aria-label={`${bridge.canCreateChannels ? 'Disallow' : 'Allow'} ${bridgePlatformLabel(bridge.type)} creating channels from Switch`}
- />
- </span>
- </TooltipTrigger>
- <TooltipContent side="top" className="max-w-56 text-xs">
- {!bridge.channelCreationSupported
- ? `${bridgePlatformLabel(bridge.type)} cannot create channels from Switch — create the chat in the app and add the bot to it instead.`
- : bridge.canCreateChannels
- ? 'Can create a channel here for a new room. Turn off to only ever adopt channels made in the app.'
- : 'Channel creation is turned off for this connection — a new room can only adopt a channel made in the app.'}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- {isManaged && bridge.type === 'mattermost' && (
- <BundledChatSignIn serverId={serverId} />
- )}
- </li>
+ <MessagingAppRow
+ key={bridge.id}
+ serverId={serverId}
+ bridge={bridge}
+ /* Nothing is drawn in the identity column until the list
+ arrives: "not linked" and "not known yet" look identical, and
+ offering to link an account the user already has is the more
+ confusing of the two. */
+ identities={identities}
+ currentUserId={currentUserId}
+ onReleased={refreshIdentities}
+ showBundledSignIn={isManaged && bridge.type === 'mattermost'}
+ isAdmin={isAdmin}
+ savingChannelCreation={savingBridgeId === bridge.id}
+ onToggleChannelCreation={(enabled) =>
+ void handleToggleChannelCreation(bridge, enabled)
+ }
+ onDisconnect={() =>
+ showDisconnectMessagingApp({
+ serverId,
+ bridgeId: bridge.id,
+ bridgeDisplayName: bridge.displayName,
+ onSuccess: () => {
+ void queryClient.invalidateQueries({
+ queryKey: ['remote-bridges', serverId],
+ });
+ // The rooms on that bridge went with it, so the sidebar is
+ // stale in a way the bridge list alone does not repair.
+ void switchRoomsStore.refreshRoomState();
+ },
+ })
+ }
+ />
))}
</ul>
)}
@@ -196,6 +271,200 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
);
});
+/**
+ * One app: its name, which account on it is the signed-in user, and a menu of
+ * everything else.
+ *
+ * The row states one fact — which account here is you — and offers the one
+ * action that changes it. Everything rarer or more dangerous (unlinking,
+ * channel creation, disconnecting the app) sits behind the menu, so the common
+ * reading is not competing with five controls. The identity column is a fixed
+ * width and the trailing controls always occupy their slot, so several apps
+ * line up as columns rather than as differently ragged lines.
+ */
+export function MessagingAppRow({
+ serverId,
+ bridge,
+ identities,
+ currentUserId,
+ onReleased,
+ showBundledSignIn,
+ isAdmin,
+ savingChannelCreation,
+ onToggleChannelCreation,
+ onDisconnect,
+}: {
+ serverId: string;
+ bridge: RemoteBridge;
+ /** Accounts the user has claimed on this server, or null while unknown. */
+ identities: LinkedIdentity[] | null;
+ currentUserId: string | null;
+ onReleased: () => void;
+ showBundledSignIn: boolean;
+ isAdmin: boolean;
+ savingChannelCreation: boolean;
+ onToggleChannelCreation: (enabled: boolean) => void;
+ onDisconnect: () => void;
+}) {
+ const showClaimIdentity = useShowModal('claimIdentityModal');
+ const [releasing, setReleasing] = useState(false);
+ const [releaseError, setReleaseError] = useState<string | null>(null);
+
+ const identity = identities?.find((i) => i.bridgeId === bridge.id) ?? null;
+ const platform = bridgePlatformLabel(bridge.type);
+ const claim = () => showClaimIdentity({ serverId, bridgeId: bridge.id });
+
+ const release = async (identityId: string) => {
+ setReleasing(true);
+ setReleaseError(null);
+ try {
+ await rpc.switchServers.releaseBridgeIdentity({
+ serverId,
+ bridgeId: bridge.id,
+ identityId,
+ userId: currentUserId,
+ });
+ onReleased();
+ } catch (cause) {
+ setReleaseError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setReleasing(false);
+ }
+ };
+
+ return (
+ <li className="py-1 text-sm">
+ <div className="flex items-center gap-2">
+ {/* The badges belong to the name, so they travel with it rather than
+ drifting into the middle of the row on a wide card. */}
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {hasBridgeIcon(bridge.type) ? (
+ <BridgeIcon bridgeType={bridge.type} size={16} />
+ ) : (
+ <MessageSquare className="size-4 text-foreground-muted" />
+ )}
+ <span className="truncate text-foreground">{bridge.displayName}</span>
+ {bridge.isDefault && <Badge variant="secondary">Default</Badge>}
+ {/* Surfaced only when it is NOT active: a bridge that is down cannot
+ back a new room, and the room-creation picker silently omits it, so
+ this is where that becomes visible. */}
+ {bridge.status !== 'active' && <Badge variant="destructive">{bridge.status}</Badge>}
+ </div>
+
+ {/* One control in both states, so the column reads as a column: the
+ handle when there is one, the invitation to supply it when not. */}
+ <div className="flex w-40 shrink-0 items-center justify-end">
+ {identities === null ? null : identity === null ? (
+ <Button variant="outline" size="xs" onClick={claim}>
+ <Link2 className="size-3" />
+ Link
+ </Button>
+ ) : (
+ <Button
+ variant="ghost"
+ size="xs"
+ className="min-w-0 text-foreground-muted"
+ title={`Change which ${bridge.displayName} account is you`}
+ onClick={claim}
+ >
+ <span className="truncate">{handleOf(identity)}</span>
+ </Button>
+ )}
+ </div>
+
+ {/* Offered only when the link resolves — an older server, or a bridge
+ that is down, reports none, and a button that cannot do anything is
+ worse than no button. The slot is held either way so the rows keep a
+ straight right edge. */}
+ {bridge.homeUrl ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={`Open ${platform}`}
+ title={`Open ${platform}`}
+ onClick={() =>
+ void openExternalUrl(bridge.homeUrl as string, `Could not open ${platform}`)
+ }
+ >
+ <ExternalLink className="size-3" />
+ </Button>
+ ) : (
+ <span aria-hidden className="size-6 shrink-0" />
+ )}
+
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={`${bridge.displayName} actions`}
+ disabled={releasing}
+ >
+ {releasing ? <Spinner className="size-3" /> : <MoreVertical className="size-3" />}
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={claim}>
+ <Link2 className="size-4" />
+ {identity === null ? 'Link my account…' : 'Change my account…'}
+ </DropdownMenuItem>
+ {identity !== null && (
+ <DropdownMenuItem onClick={() => void release(identity.id)}>
+ <Unlink className="size-4" />
+ Unlink {handleOf(identity)}
+ </DropdownMenuItem>
+ )}
+
+ <DropdownMenuSeparator />
+ <DropdownMenuCheckboxItem
+ checked={bridge.canCreateChannels}
+ disabled={!isAdmin || !bridge.channelCreationSupported || savingChannelCreation}
+ onCheckedChange={(next) => onToggleChannelCreation(next)}
+ >
+ Can create channels
+ </DropdownMenuCheckboxItem>
+ {/* A disabled empty tick reads as "off", which is a different
+ claim from "this platform cannot do it at all". Plain text rather
+ than a menu label: a label is a heading for a group of items, and
+ Base UI requires one to sit inside a group — this is a caption
+ for the item above it. */}
+ {!bridge.channelCreationSupported && (
+ <p className="max-w-56 px-2 py-1 text-xs text-foreground-muted">
+ {platform} cannot create channels from Switch. Make the chat in the app and add the
+ bot to it.
+ </p>
+ )}
+
+ {isAdmin && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={onDisconnect}>
+ <Trash2 className="size-4" />
+ Disconnect app…
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ {releaseError !== null && (
+ <p className="text-destructive mt-0.5 ml-6 text-xs">{releaseError}</p>
+ )}
+ {showBundledSignIn && <BundledChatSignIn serverId={serverId} />}
+ </li>
+ );
+}
+
+/** The claimed account as a handle. Platforms differ on whether the username
+ * they report already carries the sigil, so add one only when it is missing. */
+function handleOf(identity: LinkedIdentity): string {
+ const username = identity.externalUsername;
+ return username.startsWith('@') ? username : `@${username}`;
+}
+
/** Turn a failed channel-creation toggle into something the user can act on. */
function messageForUpdate(result: { kind: string; message?: string }): string {
switch (result.kind) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx
new file mode 100644
index 000000000..61385d305
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-control.tsx
@@ -0,0 +1,163 @@
+import { CircleAlert } from 'lucide-react';
+import { useState } from 'react';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@renderer/lib/ui/select';
+import {
+ type AddressingMode,
+ addressingModeOf,
+ policyForMode,
+ policyNamesOwner,
+} from '@shared/core/switch-servers/owner-policy';
+import type { AddressingPolicy, LinkedIdentity } from '@shared/core/switch-servers/switch-servers';
+import { AddressingPolicyEditor, type OptionItem } from './addressing-policy-editor';
+
+const MODE_ORDER: AddressingMode[] = ['owner', 'ownerAndAgents', 'anyone', 'custom'];
+
+const MODE_LABELS: Record<AddressingMode, string> = {
+ owner: 'Only me (default)',
+ ownerAndAgents: 'Only me and my agents',
+ anyone: 'Anyone',
+ custom: 'Custom rules',
+};
+
+const MODE_HINTS: Record<AddressingMode, string> = {
+ ownerAndAgents:
+ 'You, and any agent you own — so one of your agents can hand this one work. Nobody else.',
+ owner: 'Only you, in person. Agents cannot send it instructions, including your own.',
+ anyone: 'Anyone in this agent’s rooms can send it instructions.',
+ custom: 'Rules say exactly who can send instructions, and in which rooms.',
+};
+
+/**
+ * Who may address an agent, as one choice out of four (CHOO-2137).
+ *
+ * The three answers people actually want are each a policy shape rather than a
+ * form to fill in; the rule editor stays available behind the fourth for
+ * everything else. Shared by the creation modal and the agent's settings page
+ * so a policy is changed the same way it was set.
+ */
+export function AddressingPolicyControl({
+ value,
+ onChange,
+ rooms,
+ roomGroups,
+ users,
+ agents,
+ linkedIdentities,
+ onClaimIdentity,
+ disabled = false,
+}: {
+ value: AddressingPolicy | null;
+ onChange: (next: AddressingPolicy | null) => void;
+ rooms: OptionItem[];
+ roomGroups: OptionItem[];
+ users: OptionItem[];
+ agents: OptionItem[];
+ /** Messaging accounts the signed-in user has claimed on this server. An
+ * owner rule resolves through these, so an empty list means such a rule
+ * admits nobody. Null while unknown — no warning is drawn from a list that
+ * has not arrived. */
+ linkedIdentities: LinkedIdentity[] | null;
+ /** Opens the claim-your-identity modal. Null where a modal cannot be opened
+ * over the current one (the add-agent dialog), which turns the warning into
+ * a statement rather than an action that would discard the form. */
+ onClaimIdentity: (() => void) | null;
+ disabled?: boolean;
+}) {
+ // Custom is sticky while it is chosen: a rule set can pass through a shape
+ // one of the shortcuts also describes (owner-only, or no rules at all), and
+ // the editor closing under the user mid-edit would be the wrong reading of
+ // that. Every other mode is read straight off the policy, so a value that
+ // arrives after mount — the settings page loads it — selects itself.
+ const [customChosen, setCustomChosen] = useState(false);
+ // The rules the user last had in the editor, kept across a trip through one
+ // of the shortcuts so choosing Custom again does not start from scratch.
+ const [customDraft, setCustomDraft] = useState<AddressingPolicy | null>(null);
+
+ const mode: AddressingMode = customChosen ? 'custom' : addressingModeOf(value);
+
+ const selectMode = (next: AddressingMode) => {
+ if (next === mode) return;
+ if (mode === 'custom') setCustomDraft(value);
+ setCustomChosen(next === 'custom');
+ onChange(policyForMode(next, next === 'custom' ? (customDraft ?? value) : value));
+ };
+
+ return (
+ <div className="flex flex-col gap-3">
+ <Select
+ value={mode}
+ onValueChange={(next) => selectMode(next as AddressingMode)}
+ disabled={disabled}
+ >
+ <SelectTrigger className="w-full">
+ {/* The label, not the value. Left to itself the trigger renders what
+ is stored — "ownerAndAgents" — so the box contradicted the option
+ just picked from it. */}
+ <SelectValue>{MODE_LABELS[mode]}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {MODE_ORDER.map((option) => (
+ <SelectItem key={option} value={option}>
+ {MODE_LABELS[option]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <span className="text-xs text-foreground-muted">{MODE_HINTS[mode]}</span>
+
+ {policyNamesOwner(value) && linkedIdentities?.length === 0 && (
+ <OwnerUnreachableWarning onClaimIdentity={onClaimIdentity} />
+ )}
+
+ {mode === 'custom' && value !== null && (
+ <AddressingPolicyEditor
+ value={value}
+ onChange={onChange}
+ rooms={rooms}
+ roomGroups={roomGroups}
+ users={users}
+ agents={agents}
+ disabled={disabled}
+ />
+ )}
+ </div>
+ );
+}
+
+/**
+ * Shown when a rule admits the agent's owner but the signed-in user has claimed
+ * no messaging account, which is exactly the case where a privacy control ends
+ * up admitting nobody. Silence here would look like a working restriction right
+ * up until someone wonders why the agent never answers.
+ */
+function OwnerUnreachableWarning({ onClaimIdentity }: { onClaimIdentity: (() => void) | null }) {
+ return (
+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">
+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <span>
+ This admits the agent&apos;s owner, but you have not linked a messaging account on this
+ server — so Switch cannot tell that a message from you is from you, and the agent will
+ answer nobody.
+ </span>
+ {onClaimIdentity === null ? (
+ <span className="text-foreground-muted">
+ Link your account from the server page, under “Messaging apps”.
+ </span>
+ ) : (
+ <Button variant="outline" size="sm" className="self-start" onClick={onClaimIdentity}>
+ Link my messaging account
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx
index fe5c24dee..fe328677e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx
@@ -20,7 +20,64 @@ export type OptionItem = { id: string; label: string };
type DimKey = 'rooms' | 'room_groups' | 'users' | 'agents';
-const EMPTY_RULE: AddressingRule = { rooms: '*', room_groups: '*', users: '*', agents: '*' };
+const EMPTY_RULE: AddressingRule = {
+ rooms: '*',
+ room_groups: '*',
+ users: '*',
+ agents: '*',
+ owner: false,
+ owner_agents: false,
+};
+
+/**
+ * The two symbolic subjects, as ids that sit in the Users and Agents pickers
+ * beside real ones.
+ *
+ * They are booleans on the rule, not members of those lists — but to the person
+ * filling the form they answer the same question ("who counts as a sender
+ * here?"), so they are offered in the same place and mapped on the way in and
+ * out. That also keeps them composable: "me and Alice" is one rule, which a
+ * separate checkbox made possible but a separate dropdown mode would not.
+ *
+ * The `@` prefix is what keeps them from colliding with a real id — the picker
+ * accepts free text, and neither Switch ids nor platform handles start with one
+ * here.
+ */
+const ME = '@me';
+const MY_AGENTS = '@my-agents';
+
+const ME_OPTION: OptionItem = { id: ME, label: 'Me (the agent’s owner)' };
+const MY_AGENTS_OPTION: OptionItem = { id: MY_AGENTS, label: 'My agents (anyone I own)' };
+
+/** The Users dimension as the picker sees it: the owner reads as one more
+ * entry in the list. `Any` already includes them, so it stays `*`. */
+function usersOf(rule: AddressingRule): AddressingDimension {
+ if (rule.users === '*') return '*';
+ return rule.owner === true ? [ME, ...rule.users] : rule.users;
+}
+
+function agentsOf(rule: AddressingRule): AddressingDimension {
+ if (rule.agents === '*') return '*';
+ return rule.owner_agents === true ? [MY_AGENTS, ...rule.agents] : rule.agents;
+}
+
+/** Split a picked Users list back into stored ids and the symbolic flag. Any
+ * and None both clear the flag: "anyone" already covers the owner, and "none"
+ * means no human at all — leaving it set would contradict the choice just
+ * made. */
+function withUsers(rule: AddressingRule, next: AddressingDimension): AddressingRule {
+ if (next === '*') return { ...rule, users: '*', owner: false };
+ return { ...rule, users: next.filter((id) => id !== ME), owner: next.includes(ME) };
+}
+
+function withAgents(rule: AddressingRule, next: AddressingDimension): AddressingRule {
+ if (next === '*') return { ...rule, agents: '*', owner_agents: false };
+ return {
+ ...rule,
+ agents: next.filter((id) => id !== MY_AGENTS),
+ owner_agents: next.includes(MY_AGENTS),
+ };
+}
/** A "Specific" dimension with an empty list matches nobody. */
function matchesNobody(dim: AddressingDimension): boolean {
@@ -31,14 +88,16 @@ function matchesNobody(dim: AddressingDimension): boolean {
* Why a rule can never match (so it would silently never apply), or null when it
* is effective. A context dimension (rooms / room groups) that matches nobody
* kills the rule outright; the sender is dead only when BOTH users and agents
- * match nobody (an empty list on just one kind is the intentional "none").
+ * match nobody, symbolic entries included (an empty list on just one kind is
+ * the intentional "none", and owner-only is the whole point of the default
+ * policy).
*/
function deadRuleReason(rule: AddressingRule): string | null {
if (matchesNobody(rule.rooms)) return 'Rooms is Specific but empty — this rule never applies.';
if (matchesNobody(rule.room_groups)) {
return 'Room groups is Specific but empty — this rule never applies.';
}
- if (matchesNobody(rule.users) && matchesNobody(rule.agents)) {
+ if (matchesNobody(usersOf(rule)) && matchesNobody(agentsOf(rule))) {
return 'Both Users and Agents are empty — no sender can match, so this rule never applies.';
}
return null;
@@ -51,10 +110,11 @@ export function policyHasDeadRule(policy: AddressingPolicy | null): boolean {
}
/**
- * Controlled editor for an agent's scoped addressing policy (CHOO-1585). A null
- * value means "open" (anyone may address the agent); a policy value restricts to
- * senders matching a rule. Option lists (rooms / room groups / users / agents)
- * are supplied by the parent so this component stays presentational and reusable
+ * Controlled editor for the rule list of an agent's scoped addressing policy
+ * (CHOO-1585). Rendered only behind the "Custom rules" choice in
+ * {@link AddressingPolicyControl}, which owns the open/restricted decision and
+ * the owner warning. Option lists (rooms / room groups / users / agents) are
+ * supplied by the parent so this component stays presentational and reusable
* across the settings page and the creation modal.
*/
export function AddressingPolicyEditor({
@@ -66,16 +126,15 @@ export function AddressingPolicyEditor({
agents,
disabled = false,
}: {
- value: AddressingPolicy | null;
- onChange: (next: AddressingPolicy | null) => void;
+ value: AddressingPolicy;
+ onChange: (next: AddressingPolicy) => void;
rooms: OptionItem[];
roomGroups: OptionItem[];
users: OptionItem[];
agents: OptionItem[];
disabled?: boolean;
}) {
- const restricted = value !== null;
- const rules = value?.rules ?? [];
+ const rules = value.rules;
// Which rule (by index) is currently open for editing. Loaded rules start
// collapsed (shown as a read-only summary); a freshly added rule opens for
// editing. Only one rule is edited at a time.
@@ -84,8 +143,10 @@ export function AddressingPolicyEditor({
const optionsFor = (key: DimKey): OptionItem[] => {
if (key === 'rooms') return rooms;
if (key === 'room_groups') return roomGroups;
- if (key === 'users') return users;
- return agents;
+ // The symbolic entry leads its list: it is the one most rules want, and it
+ // is the only entry that stays correct as people and agents come and go.
+ if (key === 'users') return [ME_OPTION, ...users];
+ return [MY_AGENTS_OPTION, ...agents];
};
const setRules = (next: AddressingRule[]) => onChange({ rules: next });
@@ -105,121 +166,98 @@ export function AddressingPolicyEditor({
return (
<div className="flex flex-col gap-3">
- <Select
- value={restricted ? 'restricted' : 'open'}
- onValueChange={(next) => onChange(next === 'restricted' ? { rules } : null)}
- disabled={disabled}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="open">Open — anyone in the room can address it</SelectItem>
- <SelectItem value="restricted">Restricted — only matching rules</SelectItem>
- </SelectContent>
- </Select>
-
- {restricted && (
- <div className="flex flex-col gap-3">
- {rules.length === 0 && (
- <p className="text-destructive text-xs">
- No rules — a restricted policy with no rules means nobody can address this agent. Add
- a rule or switch back to Open.
- </p>
- )}
- {rules.map((rule, index) =>
- index === editingIndex ? (
- <div
- key={index}
- className="border-primary/50 flex flex-col gap-2 rounded-md border bg-background-2/40 p-2"
- >
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium">Editing rule {index + 1}</span>
- {!disabled && (
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => removeRule(index)}
- aria-label="Remove rule"
- >
- <Trash2 className="size-4" />
- </Button>
- )}
- </div>
- <DimensionRow
- label="Rooms"
- value={rule.rooms}
- options={optionsFor('rooms')}
- allowNone={false}
- disabled={disabled}
- onChange={(rooms) => updateRule(index, { ...rule, rooms })}
- />
- <DimensionRow
- label="Room groups"
- value={rule.room_groups}
- options={optionsFor('room_groups')}
- allowNone={false}
- disabled={disabled}
- onChange={(room_groups) => updateRule(index, { ...rule, room_groups })}
- />
- <DimensionRow
- label="Users"
- value={rule.users}
- options={optionsFor('users')}
- allowNone
- disabled={disabled}
- onChange={(users) => updateRule(index, { ...rule, users })}
- />
- <DimensionRow
- label="Agents"
- value={rule.agents}
- options={optionsFor('agents')}
- allowNone
- disabled={disabled}
- onChange={(agents) => updateRule(index, { ...rule, agents })}
- />
- {deadRuleReason(rule) !== null && (
- <p className="text-destructive text-xs">{deadRuleReason(rule)}</p>
- )}
- {!disabled && (
- <div className="flex justify-end">
- <Button
- size="sm"
- disabled={deadRuleReason(rule) !== null}
- onClick={() => setEditingIndex(null)}
- >
- Apply rule
- </Button>
- </div>
- )}
- </div>
- ) : (
- <RuleSummary
- key={index}
- index={index}
- rule={rule}
- rooms={rooms}
- roomGroups={roomGroups}
- users={users}
- agents={agents}
- disabled={disabled}
- onEdit={() => setEditingIndex(index)}
- onRemove={() => removeRule(index)}
- />
- )
- )}
- {!disabled && (
- <div>
- <Button
- variant="outline"
- size="sm"
- disabled={editingIndex !== null}
- onClick={addRule}
- >
- Add rule
- </Button>
+ {rules.length === 0 && (
+ <p className="text-xs text-foreground-muted">
+ No rules — a policy with no rules restricts nothing, so anyone in the agent&apos;s rooms
+ can address it. Add a rule, or choose “Anyone” above.
+ </p>
+ )}
+ {rules.map((rule, index) =>
+ index === editingIndex ? (
+ <div
+ key={index}
+ className="border-primary/50 flex flex-col gap-2 rounded-md border bg-background-2/40 p-2"
+ >
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Editing rule {index + 1}</span>
+ {!disabled && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => removeRule(index)}
+ aria-label="Remove rule"
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ )}
</div>
- )}
+ <DimensionRow
+ label="Rooms"
+ value={rule.rooms}
+ options={optionsFor('rooms')}
+ allowNone={false}
+ disabled={disabled}
+ onChange={(rooms) => updateRule(index, { ...rule, rooms })}
+ />
+ <DimensionRow
+ label="Room groups"
+ value={rule.room_groups}
+ options={optionsFor('room_groups')}
+ allowNone={false}
+ disabled={disabled}
+ onChange={(room_groups) => updateRule(index, { ...rule, room_groups })}
+ />
+ <DimensionRow
+ label="Users"
+ value={usersOf(rule)}
+ options={optionsFor('users')}
+ allowNone
+ disabled={disabled}
+ onChange={(users) => updateRule(index, withUsers(rule, users))}
+ />
+ <DimensionRow
+ label="Agents"
+ value={agentsOf(rule)}
+ options={optionsFor('agents')}
+ allowNone
+ disabled={disabled}
+ onChange={(agents) => updateRule(index, withAgents(rule, agents))}
+ />
+ {deadRuleReason(rule) !== null && (
+ <p className="text-destructive text-xs">{deadRuleReason(rule)}</p>
+ )}
+ {!disabled && (
+ <div className="flex justify-end">
+ <Button
+ size="sm"
+ disabled={deadRuleReason(rule) !== null}
+ onClick={() => setEditingIndex(null)}
+ >
+ Apply rule
+ </Button>
+ </div>
+ )}
+ </div>
+ ) : (
+ <RuleSummary
+ key={index}
+ index={index}
+ rule={rule}
+ rooms={rooms}
+ roomGroups={roomGroups}
+ users={users}
+ agents={agents}
+ disabled={disabled}
+ onEdit={() => setEditingIndex(index)}
+ onRemove={() => removeRule(index)}
+ />
+ )
+ )}
+ {!disabled && (
+ <div>
+ <Button variant="outline" size="sm" disabled={editingIndex !== null} onClick={addRule}>
+ Add rule
+ </Button>
</div>
)}
</div>
@@ -270,10 +308,12 @@ function RuleSummary({
{dimLabel(rule.room_groups, roomGroups)}
</span>
<span>
- <span className="font-medium">Users:</span> {dimLabel(rule.users, users)}
+ <span className="font-medium">Users:</span>{' '}
+ {dimLabel(usersOf(rule), [ME_OPTION, ...users])}
</span>
<span>
- <span className="font-medium">Agents:</span> {dimLabel(rule.agents, agents)}
+ <span className="font-medium">Agents:</span>{' '}
+ {dimLabel(agentsOf(rule), [MY_AGENTS_OPTION, ...agents])}
</span>
</div>
{dead !== null && <span className="text-destructive text-xs">{dead}</span>}
@@ -294,6 +334,14 @@ function RuleSummary({
type DimMode = 'any' | 'specific' | 'none';
+// A Base UI select trigger renders the stored value unless it is given
+// something else, so the labels have to be readable from both ends.
+const DIM_MODE_LABELS: Record<DimMode, string> = {
+ any: 'Any',
+ specific: 'Specific',
+ none: 'None',
+};
+
function initialMode(value: AddressingDimension, allowNone: boolean): DimMode {
if (value === '*') return 'any';
if (value.length === 0) return allowNone ? 'none' : 'specific';
@@ -365,12 +413,12 @@ function DimensionRow({
<span className="w-24 text-xs font-medium text-foreground-muted">{label}</span>
<Select value={mode} onValueChange={(m) => changeMode(m as DimMode)} disabled={disabled}>
<SelectTrigger className="h-7 w-32">
- <SelectValue />
+ <SelectValue>{DIM_MODE_LABELS[mode]}</SelectValue>
</SelectTrigger>
<SelectContent>
- <SelectItem value="any">Any</SelectItem>
- <SelectItem value="specific">Specific</SelectItem>
- {allowNone && <SelectItem value="none">None</SelectItem>}
+ <SelectItem value="any">{DIM_MODE_LABELS.any}</SelectItem>
+ <SelectItem value="specific">{DIM_MODE_LABELS.specific}</SelectItem>
+ {allowNone && <SelectItem value="none">{DIM_MODE_LABELS.none}</SelectItem>}
</SelectContent>
</Select>
{mode === 'specific' && ids.length > 0 && (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts
new file mode 100644
index 000000000..f9d895418
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it } from 'vitest';
+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import {
+ hasUnlinkedMessagingApp,
+ shouldOfferIdentityLinkOnConnect,
+ unrecognisedMessagingApps,
+ unrecognisedMessagingAppsMessage,
+} from './messaging-apps-warning';
+
+function bridge(id: string, displayName: string): RemoteBridge {
+ return {
+ id,
+ type: 'slack',
+ displayName,
+ status: 'active',
+ isDefault: false,
+ homeUrl: null,
+ channelCreationSupported: true,
+ canCreateChannels: true,
+ directorySearchSupported: true,
+ };
+}
+
+function identity(bridgeId: string): LinkedIdentity {
+ return {
+ id: `identity-${bridgeId}`,
+ bridgeId,
+ bridgeDisplayName: bridgeId,
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'me',
+ };
+}
+
+const slack = bridge('b-slack', 'Slack Test');
+const mattermost = bridge('b-mm', 'Mattermost');
+const telegram = bridge('b-tg', 'Telegram louis');
+
+describe('unrecognisedMessagingApps', () => {
+ it('names the apps with no claimed account when an owner-addressed agent is owned', () => {
+ expect(
+ unrecognisedMessagingApps({
+ bridges: [slack, mattermost, telegram],
+ identities: [identity('b-slack')],
+ ownsOwnerAddressedAgent: true,
+ })
+ ).toEqual([mattermost, telegram]);
+ });
+
+ it('stays quiet when every app is linked', () => {
+ expect(
+ unrecognisedMessagingApps({
+ bridges: [slack, mattermost],
+ identities: [identity('b-slack'), identity('b-mm')],
+ ownsOwnerAddressedAgent: true,
+ })
+ ).toEqual([]);
+ });
+
+ it('stays quiet when the user owns no owner-addressed agent', () => {
+ expect(
+ unrecognisedMessagingApps({
+ bridges: [slack, mattermost],
+ identities: [],
+ ownsOwnerAddressedAgent: false,
+ })
+ ).toEqual([]);
+ });
+
+ it('stays quiet while the identity list is unknown', () => {
+ expect(
+ unrecognisedMessagingApps({
+ bridges: [slack, mattermost],
+ identities: null,
+ ownsOwnerAddressedAgent: true,
+ })
+ ).toEqual([]);
+ });
+
+ it('stays quiet while the policy probe has not answered', () => {
+ expect(
+ unrecognisedMessagingApps({
+ bridges: [slack, mattermost],
+ identities: [],
+ ownsOwnerAddressedAgent: null,
+ })
+ ).toEqual([]);
+ });
+
+ it('stays quiet when no messaging app is connected', () => {
+ expect(
+ unrecognisedMessagingApps({
+ bridges: [],
+ identities: [],
+ ownsOwnerAddressedAgent: true,
+ })
+ ).toEqual([]);
+ });
+
+ it('warns about a down bridge the user has not linked, as the card still offers Link there', () => {
+ const down = { ...bridge('b-down', 'test'), status: 'error' };
+ expect(
+ unrecognisedMessagingApps({
+ bridges: [down],
+ identities: [],
+ ownsOwnerAddressedAgent: true,
+ })
+ ).toEqual([down]);
+ });
+});
+
+describe('hasUnlinkedMessagingApp', () => {
+ it('is false while the identity list is unknown, so nothing is probed on load', () => {
+ expect(hasUnlinkedMessagingApp([slack], null)).toBe(false);
+ });
+
+ it('is false when every app is linked', () => {
+ expect(hasUnlinkedMessagingApp([slack], [identity('b-slack')])).toBe(false);
+ });
+
+ it('is true when one app is unlinked', () => {
+ expect(hasUnlinkedMessagingApp([slack, mattermost], [identity('b-slack')])).toBe(true);
+ });
+});
+
+describe('unrecognisedMessagingAppsMessage', () => {
+ it('names one app', () => {
+ expect(unrecognisedMessagingAppsMessage([mattermost])).toBe(
+ 'Agents set to answer only you can’t recognise you in Mattermost — link your account there.'
+ );
+ });
+
+ it('joins two apps with "or"', () => {
+ expect(unrecognisedMessagingAppsMessage([mattermost, telegram])).toBe(
+ 'Agents set to answer only you can’t recognise you in Mattermost or Telegram louis — link your account there.'
+ );
+ });
+
+ it('joins three apps with commas and a final "or"', () => {
+ expect(unrecognisedMessagingAppsMessage([mattermost, telegram, bridge('b-t', 'test')])).toBe(
+ 'Agents set to answer only you can’t recognise you in Mattermost, Telegram louis or test — link your account there.'
+ );
+ });
+});
+
+describe('offering the link step after connecting an app', () => {
+ it('offers it on a platform with a directory to search', () => {
+ expect(shouldOfferIdentityLinkOnConnect({ directorySearchSupported: true })).toBe(true);
+ });
+
+ it('does not on one without, where the search cannot find anyone yet', () => {
+ // Telegram. Switch only knows people who have messaged it, and nobody has
+ // messaged a connection made a second ago — so the dialog offered a search
+ // box that was guaranteed to come back empty, which reads as "you are not
+ // in your own workspace" rather than "not yet".
+ expect(shouldOfferIdentityLinkOnConnect({ directorySearchSupported: false })).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts
new file mode 100644
index 000000000..ef7133039
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts
@@ -0,0 +1,80 @@
+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * When the "Messaging apps" card should warn that owner-only agents cannot
+ * recognise the signed-in user, and which apps to name (CHOO-2137).
+ *
+ * Kept apart from the card because the interesting part is when it stays quiet.
+ * A warning everyone sees is noise, and the two ways this rots — into always-on
+ * or into never-on — both look fine on the screen it was written against.
+ */
+
+/**
+ * The connected messaging apps the signed-in user has claimed no account in,
+ * and only when not being recognised there costs them something: they own an
+ * agent on this server that is set to answer its owner. Empty means draw no
+ * warning.
+ *
+ * Both inputs are nullable because "not known yet" is not "no". An identity
+ * list that has not arrived would make every app look unlinked, and a policy
+ * probe that has not answered would make every user look at risk — either read
+ * as `false` is the false alarm on every page load that this guards against.
+ */
+export function unrecognisedMessagingApps({
+ bridges,
+ identities,
+ ownsOwnerAddressedAgent,
+}: {
+ bridges: RemoteBridge[];
+ /** Accounts the user has claimed on this server; null while unknown. */
+ identities: LinkedIdentity[] | null;
+ /** Whether the user owns an agent here whose policy admits its owner; null
+ * while unknown or not asked. */
+ ownsOwnerAddressedAgent: boolean | null;
+}): RemoteBridge[] {
+ if (identities === null || ownsOwnerAddressedAgent !== true) return [];
+ return bridges.filter((bridge) => !identities.some((i) => i.bridgeId === bridge.id));
+}
+
+/** Whether any listed app has no claimed account — the half of the condition
+ * that needs no extra request, and the gate on asking the other half at all.
+ * Null identities mean unknown, so nothing is asked yet. */
+export function hasUnlinkedMessagingApp(
+ bridges: RemoteBridge[],
+ identities: LinkedIdentity[] | null
+): boolean {
+ if (identities === null) return false;
+ return bridges.some((bridge) => !identities.some((i) => i.bridgeId === bridge.id));
+}
+
+/** The warning, as one sentence naming the apps. Callers pass a non-empty list
+ * — an empty one has nothing to warn about. */
+export function unrecognisedMessagingAppsMessage(apps: RemoteBridge[]): string {
+ return `Agents set to answer only you can’t recognise you in ${joinWithOr(
+ apps.map((app) => app.displayName)
+ )} — link your account there.`;
+}
+
+/** "A", "A or B", "A, B or C". */
+function joinWithOr(names: string[]): string {
+ if (names.length <= 1) return names.join('');
+ return `${names.slice(0, -1).join(', ')} or ${names[names.length - 1]}`;
+}
+
+/**
+ * Whether to offer "which account here is you" straight after connecting an
+ * app (CHOO-2137).
+ *
+ * No, on a platform whose user directory cannot be searched. There, Switch can
+ * only name people who have sent it a message — and nobody has sent one to a
+ * connection made a second ago, so the search is guaranteed to come back
+ * empty. That does not read as "not yet", it reads as "you are not in your own
+ * workspace". Linking waits for the server page, by which time someone has
+ * messaged the app and there is a name to pick; the warning there is what
+ * prompts it.
+ */
+export function shouldOfferIdentityLinkOnConnect(app: {
+ directorySearchSupported: boolean;
+}): boolean {
+ return app.directorySearchSupported;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
new file mode 100644
index 000000000..6e8a1fa2d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
@@ -0,0 +1,45 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { useCallback } from 'react';
+import { rpc } from '@renderer/lib/ipc';
+import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers';
+
+/** Shared so every surface that claims or releases an identity refreshes the
+ * same cache entry the owner-only warning reads. */
+export function myIdentitiesQueryKey(serverId: string | null): unknown[] {
+ return ['my-switch-identities', serverId];
+}
+
+/**
+ * The messaging accounts the signed-in user has claimed on a server
+ * (CHOO-2137).
+ *
+ * `identities` is null while the answer is unknown — not signed in, no server
+ * chosen, still loading, or the read failed. Callers must treat that as
+ * "unknown" rather than "none": warning that an owner-only agent is
+ * unreachable, on the strength of a list that has not arrived, is the same
+ * false alarm every time the page opens.
+ */
+export function useMyIdentities(serverId: string | null): {
+ identities: LinkedIdentity[] | null;
+ isLoading: boolean;
+ error: unknown;
+ refresh: () => void;
+} {
+ const queryClient = useQueryClient();
+ const query = useQuery({
+ queryKey: myIdentitiesQueryKey(serverId),
+ queryFn: () => rpc.switchServers.listMyIdentities(serverId as string),
+ enabled: serverId !== null,
+ });
+
+ const refresh = useCallback(() => {
+ void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(serverId) });
+ }, [queryClient, serverId]);
+
+ return {
+ identities: query.isSuccess ? query.data : null,
+ isLoading: query.isLoading,
+ error: query.error,
+ refresh,
+ };
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx
new file mode 100644
index 000000000..75d4b22c4
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/addressing-policy.test.tsx
@@ -0,0 +1,270 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// The control's siblings reach the renderer IPC bridge at import time, which
+// only exists inside Electron. Hoisted so it is in place before those modules
+// are evaluated. Nothing asserted here calls through it.
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+/**
+ * "Who can send instructions", as the person setting it sees it (CHOO-2137).
+ *
+ * The chooser and the rule editor answer the same question at two levels of
+ * detail, and the thing that goes wrong is the seam between them: the owner and
+ * the owner's agents are booleans on a rule, but they are offered as entries in
+ * the Users and Agents pickers. These pin down that translation in both
+ * directions, and that no shortcut quietly loses what the rule said.
+ */
+import { AddressingPolicyControl } from '@renderer/features/switch-servers/addressing-policy-control';
+import { AddressingPolicyEditor } from '@renderer/features/switch-servers/addressing-policy-editor';
+import type { AddressingPolicy, AddressingRule } from '@shared/core/switch-servers/switch-servers';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(node: React.ReactNode): Promise<HTMLDivElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root!.render(node));
+ return container;
+}
+
+const USERS = [{ id: 'ext-1', label: 'alice' }];
+const AGENTS = [{ id: 'agent-a', label: 'helper' }];
+
+function rule(patch: Partial<AddressingRule> = {}): AddressingRule {
+ return { rooms: '*', room_groups: '*', users: [], agents: [], ...patch };
+}
+
+/** Renders the editor on one rule and returns the last policy it emitted. */
+async function editing(only: AddressingRule): Promise<{
+ el: HTMLDivElement;
+ emitted: () => AddressingRule | null;
+}> {
+ let last: AddressingPolicy | null = null;
+ const el = await render(
+ <AddressingPolicyEditor
+ value={{ rules: [only] }}
+ onChange={(next) => {
+ last = next;
+ }}
+ rooms={[]}
+ roomGroups={[]}
+ users={USERS}
+ agents={AGENTS}
+ />
+ );
+ // A rule that arrives already saved opens collapsed; the dimension pickers
+ // only exist once it is being edited.
+ const edit = [...el.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'Edit');
+ await act(async () => edit!.click());
+ return { el, emitted: () => (last === null ? null : (last as AddressingPolicy).rules[0]) };
+}
+
+/** Opens a Base UI select and returns its option labels. The listbox is
+ * portalled out of the component, so this reads the whole document. */
+async function openSelect(trigger: HTMLElement): Promise<string[]> {
+ await act(async () => trigger.click());
+ return [...document.querySelectorAll('[role="option"]')].map((o) => o.textContent?.trim() ?? '');
+}
+
+async function pickOption(label: string): Promise<void> {
+ const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (o) => o.textContent?.trim() === label
+ );
+ expect(option, `no option labelled ${label}`).toBeDefined();
+ await act(async () => option!.click());
+}
+
+describe('the chooser', () => {
+ async function control(value: AddressingPolicy | null) {
+ let last: AddressingPolicy | null | 'unset' = 'unset';
+ const el = await render(
+ <AddressingPolicyControl
+ value={value}
+ onChange={(next) => {
+ last = next;
+ }}
+ rooms={[]}
+ roomGroups={[]}
+ users={USERS}
+ agents={AGENTS}
+ linkedIdentities={[]}
+ onClaimIdentity={null}
+ />
+ );
+ return { el, emitted: () => last };
+ }
+
+ it('offers only-me and my-agents as separate answers', async () => {
+ const { el } = await control(null);
+
+ const labels = await openSelect(el.querySelector('button')!);
+ expect(labels).toEqual([
+ 'Only me (default)',
+ 'Only me and my agents',
+ 'Anyone',
+ 'Custom rules',
+ ]);
+ });
+
+ it('shows the answer in the box, not the value stored behind it', async () => {
+ // Base UI renders the stored value unless the trigger is given something
+ // else, so the box read "ownerAndAgents" — a word that appears nowhere in
+ // the list it was picked from.
+ const { el } = await control({ rules: [rule({ owner: true, owner_agents: true })] });
+
+ const trigger = el.querySelector('button')!;
+ expect(trigger.textContent).toContain('Only me and my agents');
+ expect(trigger.textContent).not.toContain('ownerAndAgents');
+ });
+
+ it('writes the wider shape when my agents are included', async () => {
+ const { el, emitted } = await control(null);
+ await openSelect(el.querySelector('button')!);
+
+ await pickOption('Only me and my agents');
+
+ expect(emitted()).toEqual({
+ rules: [
+ {
+ rooms: '*',
+ room_groups: '*',
+ users: [],
+ agents: [],
+ owner: true,
+ owner_agents: true,
+ },
+ ],
+ });
+ });
+
+ it('shuts the owner’s agents out again when only-me is chosen', async () => {
+ // The narrowing direction is the one that matters: leaving owner_agents
+ // set here would make the stricter choice a no-op.
+ const { el, emitted } = await control({
+ rules: [rule({ owner: true, owner_agents: true })],
+ });
+ await openSelect(el.querySelector('button')!);
+
+ await pickOption('Only me (default)');
+
+ expect((emitted() as AddressingPolicy).rules[0].owner_agents).toBe(false);
+ });
+
+ it('no longer asks which agents to allow — that is what the wider choice is for', async () => {
+ // The picker used to sit under "Only me", which made the option's own
+ // label untrue.
+ const { el } = await control({ rules: [rule({ owner: true })] });
+
+ expect(el.textContent).not.toContain('Add an agent that may address it');
+ expect(el.textContent).not.toContain('Also allow these agents');
+ });
+
+ it('says an unlinked owner will be recognised as nobody', async () => {
+ const { el } = await control({ rules: [rule({ owner: true })] });
+
+ expect(el.textContent).toContain('you have not linked a messaging account');
+ });
+
+ it('stays quiet when only the owner’s agents are admitted', async () => {
+ // Agent senders are recognised by their agent id, so no messaging account
+ // has to be linked for this rule to work. Warning here would be a warning
+ // nobody can act on.
+ const { el } = await control({ rules: [rule({ owner_agents: true })] });
+
+ expect(el.textContent).not.toContain('you have not linked a messaging account');
+ });
+});
+
+describe('the rule editor', () => {
+ it('has no separate checkbox for the owner', async () => {
+ // It was a third control answering the same question as the Users row,
+ // sitting between Room groups and Users where nothing else about senders
+ // was.
+ const { el } = await editing(rule({ users: '*', agents: '*' }));
+
+ expect(el.textContent).not.toContain('The agent’s owner');
+ expect(el.querySelector('[role="checkbox"]')).toBeNull();
+ });
+
+ it('names each dimension’s mode rather than showing the stored word', async () => {
+ // Same defect as the chooser's, in the row below it: the boxes read "any"
+ // and "specific".
+ const { el } = await editing(rule({ users: '*', agents: '*' }));
+
+ const triggers = [...el.querySelectorAll<HTMLElement>('button')].filter((b) =>
+ b.hasAttribute('aria-haspopup')
+ );
+ // The trailing chevron is part of the trigger's text.
+ for (const trigger of triggers) expect(trigger.textContent).toContain('Any');
+ });
+
+ it('shows the owner as an entry in the Users list', async () => {
+ const { el } = await editing(rule({ owner: true, agents: '*' }));
+
+ expect(el.querySelector('[aria-label^="Remove Me"]')).not.toBeNull();
+ });
+
+ it('shows the owner’s agents as an entry in the Agents list', async () => {
+ const { el } = await editing(rule({ users: '*', owner_agents: true }));
+
+ expect(el.querySelector('[aria-label^="Remove My agents"]')).not.toBeNull();
+ });
+
+ it('takes the owner back out when that entry is removed', async () => {
+ const { el, emitted } = await editing(rule({ owner: true, users: ['ext-1'], agents: '*' }));
+
+ const remove = el.querySelector<HTMLElement>('[aria-label^="Remove Me"]');
+ await act(async () => remove!.click());
+
+ // The named user survives: the symbolic entry is one member of the list,
+ // not a mode the whole row is in.
+ expect(emitted()).toMatchObject({ owner: false, users: ['ext-1'] });
+ });
+
+ it('drops the owner when Users is set to None', async () => {
+ // "No humans at all" and "the owner may" are contradictory, and the row
+ // that was just set is the one that should win.
+ const { el, emitted } = await editing(rule({ owner: true, agents: '*' }));
+
+ const rows = [...el.querySelectorAll<HTMLElement>('button')].filter((b) =>
+ b.hasAttribute('aria-haspopup')
+ );
+ // Rooms, Room groups, Users, Agents — in the order the rows are laid out.
+ await openSelect(rows[2]);
+ await pickOption('None');
+
+ expect(emitted()).toMatchObject({ owner: false, users: [] });
+ });
+
+ it('calls a rule with only the owner in it live, not dead', async () => {
+ // The empty `users` list is what dead-rule detection looks at, and the
+ // owner is not in it — so the default policy read as a rule that never
+ // applies unless the symbolic entries are counted.
+ const { el } = await editing(rule({ owner: true }));
+
+ expect(el.textContent).not.toContain('no sender can match');
+ });
+
+ it('still calls a rule with no sender at all dead', async () => {
+ const { el } = await editing(rule());
+
+ expect(el.textContent).toContain('no sender can match');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx
new file mode 100644
index 000000000..de5ef131a
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx
@@ -0,0 +1,121 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * One "Advanced configuration" per agent, in the add-agent modal.
+ *
+ * A provider keeps its per-agent settings in exactly one place — a repo-agent
+ * definition (Claude Code) or a launch profile (Codex, OpenCode) — and the
+ * agent's Settings tab picks between them by asking which. The creation form
+ * did not ask: it rendered the definition section and the launch-profile
+ * section side by side, and the launch-profile one reads a "give me the fields,
+ * from wherever they live" call that falls back to the definition fields. So a
+ * Claude Code agent got the same section twice, offering to configure the same
+ * thing in two boxes that wrote to different places.
+ */
+
+const definitionFields = vi.hoisted(() => vi.fn());
+const advancedFields = vi.hoisted(() => vi.fn());
+const advancedSurface = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: {
+ agents: {
+ definitionFields,
+ advancedFields,
+ advancedSurface,
+ modelCatalogue: vi.fn(() =>
+ Promise.resolve({ kind: 'unavailable', reason: 'not asked in this test' })
+ ),
+ },
+ },
+}));
+
+import { AgentAdvancedConfig } from '@renderer/features/locations/components/add-agent-modal/agent-advanced-config';
+import { LaunchProfileConfig } from '@renderer/features/locations/components/add-agent-modal/launch-profile-config';
+
+const FIELD = {
+ key: 'model',
+ label: 'Model',
+ type: 'string' as const,
+ required: false,
+ advanced: true,
+};
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ definitionFields.mockReset();
+ advancedFields.mockReset();
+ advancedSurface.mockReset();
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+/** Renders the pair exactly as the modal does, and returns how many
+ * "Advanced configuration" sections ended up on screen. */
+async function sectionCount(): Promise<number> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <AgentAdvancedConfig providerId={'claude' as never} onChange={() => {}} />
+ <LaunchProfileConfig
+ providerId={'claude' as never}
+ sshHost={null}
+ dir="/tmp/repo"
+ onChange={() => {}}
+ />
+ </QueryClientProvider>
+ )
+ );
+ // Both sections load their fields over RPC, so the first paint has neither.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ return [...container.querySelectorAll('button')].filter(
+ (b) => b.textContent?.trim() === 'Advanced configuration'
+ ).length;
+}
+
+describe('the add-agent modal’s advanced sections', () => {
+ it('shows one for a provider that keeps its settings in a definition', async () => {
+ // Claude Code. Note both calls answer with fields — that overlap is the
+ // whole bug, and it is what the surface has to arbitrate.
+ advancedSurface.mockResolvedValue('definition');
+ definitionFields.mockResolvedValue([FIELD]);
+ advancedFields.mockResolvedValue([FIELD]);
+
+ expect(await sectionCount()).toBe(1);
+ });
+
+ it('shows one for a provider that keeps them in a launch profile', async () => {
+ // Codex: no definition fields, so only the profile section has anything.
+ advancedSurface.mockResolvedValue('launch-profile');
+ definitionFields.mockResolvedValue([]);
+ advancedFields.mockResolvedValue([FIELD]);
+
+ expect(await sectionCount()).toBe(1);
+ });
+
+ it('shows none for a provider with no per-agent settings at all', async () => {
+ advancedSurface.mockResolvedValue('none');
+ definitionFields.mockResolvedValue([]);
+ advancedFields.mockResolvedValue([]);
+
+ expect(await sectionCount()).toBe(0);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
new file mode 100644
index 000000000..a73c3d77a
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
@@ -0,0 +1,246 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// The row's siblings reach the renderer IPC bridge at import time, which only
+// exists inside Electron. Hoisted so it is in place before those modules are
+// evaluated. Nothing asserted here calls through it.
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+/**
+ * One messaging app, one line (CHOO-2137).
+ *
+ * The card used to answer "which account is you here" in two different shapes:
+ * a linked app showed bare text plus a stray cross, an unlinked one showed a
+ * button. Same column, same question, two visual languages — and the cross put
+ * an irreversible unlink one mis-click from the control you press to *change*
+ * an account. These pin the shape down: one control in the column either way,
+ * the badges tied to the app name, and everything rare or destructive behind
+ * the row menu.
+ */
+import { MessagingAppRow } from '@renderer/features/switch-servers/MessagingAppsCard';
+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(node: React.ReactNode): Promise<HTMLDivElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root!.render(node));
+ return container;
+}
+
+function bridge(patch: Partial<RemoteBridge> = {}): RemoteBridge {
+ return {
+ id: 'b-slack',
+ type: 'slack',
+ displayName: 'Slack Test',
+ status: 'active',
+ isDefault: false,
+ homeUrl: null,
+ channelCreationSupported: true,
+ canCreateChannels: true,
+ directorySearchSupported: true,
+ ...patch,
+ };
+}
+
+const IDENTITY: LinkedIdentity = {
+ id: 'eu-1',
+ bridgeId: 'b-slack',
+ bridgeDisplayName: 'Slack Test',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'amaudruz.louis',
+};
+
+function row(
+ overrides: {
+ bridge?: RemoteBridge;
+ identities?: LinkedIdentity[] | null;
+ isAdmin?: boolean;
+ onDisconnect?: () => void;
+ } = {}
+) {
+ return (
+ <MessagingAppRow
+ serverId="srv-1"
+ bridge={overrides.bridge ?? bridge()}
+ identities={overrides.identities === undefined ? [] : overrides.identities}
+ currentUserId="u1"
+ onReleased={() => {}}
+ showBundledSignIn={false}
+ isAdmin={overrides.isAdmin ?? false}
+ savingChannelCreation={false}
+ onToggleChannelCreation={() => {}}
+ onDisconnect={overrides.onDisconnect ?? (() => {})}
+ />
+ );
+}
+
+function buttonLabels(el: HTMLElement): string[] {
+ return [...el.querySelectorAll('button')].map((b) => b.textContent?.trim() ?? '');
+}
+
+/** Opens the row's overflow menu and returns the menu item labels. Base UI
+ * portals the menu outside the row, so this reads the whole document. */
+async function openMenu(el: HTMLElement): Promise<string[]> {
+ const trigger = el.querySelector<HTMLButtonElement>('button[aria-label$="actions"]');
+ expect(trigger).not.toBeNull();
+ await act(async () => trigger!.click());
+ return [...document.querySelectorAll('[role="menuitem"], [role="menuitemcheckbox"]')].map(
+ (i) => i.textContent?.trim() ?? ''
+ );
+}
+
+describe('the identity column', () => {
+ it('offers one control, not two, once an account is linked', async () => {
+ // The second control was the unlink cross. Its removal is the point: the
+ // one thing on the row is the handle, and pressing it changes the account.
+ const el = await render(row({ identities: [IDENTITY] }));
+
+ const inColumn = buttonLabels(el).filter((l) => l.includes('amaudruz.louis'));
+ expect(inColumn).toEqual(['@amaudruz.louis']);
+ });
+
+ it('cannot unlink straight from the row', async () => {
+ const el = await render(row({ identities: [IDENTITY] }));
+
+ const unlinkOnRow = [...el.querySelectorAll('button')].filter((b) =>
+ (b.getAttribute('aria-label') ?? '').startsWith('Unlink')
+ );
+ expect(unlinkOnRow).toEqual([]);
+ });
+
+ it('asks for the account when there is none', async () => {
+ const el = await render(row({ identities: [] }));
+
+ expect(buttonLabels(el)).toContain('Link');
+ });
+
+ it('says nothing at all until the claimed accounts have loaded', async () => {
+ // "Not linked" and "not known yet" look identical, and inviting someone to
+ // link an account they already have is the more confusing of the two.
+ const el = await render(row({ identities: null }));
+
+ expect(buttonLabels(el)).not.toContain('Link');
+ });
+
+ it('adds the sigil only when the platform has not already', async () => {
+ const el = await render(
+ row({ identities: [{ ...IDENTITY, externalUsername: '@already.sigilled' }] })
+ );
+
+ expect(buttonLabels(el)).toContain('@already.sigilled');
+ });
+});
+
+describe('the app name and its badges', () => {
+ it('keeps Default beside the name rather than adrift in the row', async () => {
+ // With the name set to grow, the badge was pushed away from what it
+ // qualifies and ended up floating mid-row against the identity column.
+ const el = await render(row({ bridge: bridge({ isDefault: true }) }));
+
+ const label = [...el.querySelectorAll('span')].find(
+ (s) => s.textContent?.trim() === 'Slack Test'
+ );
+ expect(label).toBeDefined();
+ expect(label!.parentElement!.textContent).toContain('Default');
+ });
+
+ it('shows a bridge that is down, since a new room cannot use it', async () => {
+ const el = await render(row({ bridge: bridge({ status: 'error' }) }));
+
+ expect(el.textContent).toContain('error');
+ });
+});
+
+describe('the row menu', () => {
+ it('is where unlinking lives, and only when there is a link to undo', async () => {
+ const el = await render(row({ identities: [IDENTITY] }));
+
+ expect(await openMenu(el)).toContain('Unlink @amaudruz.louis');
+ });
+
+ it('offers no unlink when nothing is linked', async () => {
+ const el = await render(row({ identities: [] }));
+
+ expect(await openMenu(el)).not.toContain('Unlink @amaudruz.louis');
+ });
+
+ it('offers disconnecting the app to an admin', async () => {
+ const el = await render(row({ isAdmin: true }));
+
+ expect(await openMenu(el)).toContain('Disconnect app…');
+ });
+
+ it('does not offer it to anyone else — the endpoint would refuse them', async () => {
+ const el = await render(row({ isAdmin: false }));
+
+ expect(await openMenu(el)).not.toContain('Disconnect app…');
+ });
+
+ it('opens on a platform that cannot create channels at all', async () => {
+ // Telegram. The explanatory line under the channel toggle was a menu
+ // *label*, which Base UI requires to sit inside a group — so opening this
+ // menu threw and took the page down with it. Every other case here has a
+ // platform that supports channel creation, which is how it got through.
+ const el = await render(
+ row({ bridge: bridge({ channelCreationSupported: false, canCreateChannels: false }) })
+ );
+
+ expect(await openMenu(el)).toContain('Can create channels');
+ });
+
+ it('says a platform cannot create channels rather than just showing it off', async () => {
+ // An unticked disabled box reads as "switched off", which is a different
+ // claim from "this platform has no such thing".
+ const el = await render(
+ row({ bridge: bridge({ channelCreationSupported: false, canCreateChannels: false }) })
+ );
+ await openMenu(el);
+
+ const menu = document.querySelector('[role="menu"]');
+ expect(menu!.textContent).toContain('Slack cannot create channels from Switch');
+ });
+
+ it('leaves the channel toggle alone for a non-admin', async () => {
+ const el = await render(row({ isAdmin: false }));
+ await openMenu(el);
+
+ const item = [...document.querySelectorAll('[role="menuitemcheckbox"]')].find((i) =>
+ i.textContent?.includes('Can create channels')
+ );
+ expect(item!.getAttribute('data-disabled')).not.toBeNull();
+ });
+
+ it('asks before disconnecting rather than doing it on the click', async () => {
+ // The server deletes every room on the bridge first, so the menu item may
+ // only ever open a confirmation.
+ const onDisconnect = vi.fn();
+ const el = await render(row({ isAdmin: true, onDisconnect }));
+ await openMenu(el);
+
+ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (i) => i.textContent?.trim() === 'Disconnect app…'
+ );
+ await act(async () => item!.click());
+
+ expect(onDisconnect).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx
new file mode 100644
index 000000000..aac335dfa
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx
@@ -0,0 +1,74 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * What "Who can send instructions" starts on for a brand-new agent (CHOO-2137).
+ *
+ * This is the ticket's whole point — an agent created in Switch Console answers
+ * only its owner unless someone says otherwise — and it lives in one line of
+ * form state that nothing else would notice going wrong. An agent created open
+ * to everyone still works perfectly, which is exactly why this needs pinning
+ * rather than watching.
+ */
+
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: {
+ switchServers: {
+ // The form seeds its name and description from this; the policy is not
+ // derived from it and must not become so.
+ suggestAgentDefaults: vi.fn(() =>
+ Promise.resolve({ name: 'louis-ama', description: 'Claude Code running in repo' })
+ ),
+ },
+ },
+}));
+
+import { useConfigureAgentForm } from '@renderer/features/locations/components/add-agent-modal/modes';
+import { addressingModeOf } from '@shared/core/switch-servers/owner-policy';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+/** The mode the creation form starts on, read off the real hook. */
+async function initialMode(): Promise<string> {
+ let seen = '';
+ function Probe() {
+ const form = useConfigureAgentForm('/tmp/repo', false, 'claude' as never);
+ seen = addressingModeOf(form.addressingPolicy);
+ return null;
+ }
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ )
+ );
+ return seen;
+}
+
+describe('a new agent', () => {
+ it('starts answering only its owner', async () => {
+ expect(await initialMode()).toBe('owner');
+ });
+
+ it('does not start open to everyone', async () => {
+ // Stated separately because this is the failure that looks like nothing:
+ // an agent anyone can drive behaves normally right up until someone else
+ // drives it.
+ expect(await initialMode()).not.toBe('anyone');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.test.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.test.ts
new file mode 100644
index 000000000..5c068b6cb
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.test.ts
@@ -0,0 +1,180 @@
+import { describe, expect, it } from 'vitest';
+import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';
+import {
+ type AddressingMode,
+ addressingModeOf,
+ ownerAndMyAgentsPolicy,
+ ownerOnlyPolicy,
+ policyForMode,
+ policyNamesOwner,
+} from './owner-policy';
+
+describe('the two owner-scoped shapes', () => {
+ it('admits the owner and nobody else', () => {
+ expect(ownerOnlyPolicy()).toEqual({
+ rules: [
+ {
+ rooms: '*',
+ room_groups: '*',
+ users: [],
+ agents: [],
+ owner: true,
+ owner_agents: false,
+ },
+ ],
+ });
+ });
+
+ it('adds the owner’s own agents, and only theirs', () => {
+ // Symbolic rather than a list of ids: registering another agent must not
+ // require going back and editing every policy that should include it.
+ expect(ownerAndMyAgentsPolicy().rules[0]).toMatchObject({
+ owner: true,
+ owner_agents: true,
+ agents: [],
+ });
+ });
+
+ it('differ only in whether the owner’s agents are admitted', () => {
+ const [strict] = ownerOnlyPolicy().rules;
+ const [withAgents] = ownerAndMyAgentsPolicy().rules;
+ expect({ ...strict, owner_agents: true }).toEqual(withAgents);
+ });
+});
+
+/** A rule set no shortcut can express, so it can only be "Custom rules". */
+const HAND_BUILT: AddressingPolicy = {
+ rules: [
+ { rooms: ['room-1'], room_groups: '*', users: ['user-1'], agents: [], owner: true },
+ { rooms: '*', room_groups: ['group-1'], users: [], agents: ['agent-a'] },
+ ],
+};
+
+describe('policyNamesOwner', () => {
+ it('is false for a policy that admits everyone', () => {
+ expect(policyNamesOwner(null)).toBe(false);
+ expect(policyNamesOwner({ rules: [] })).toBe(false);
+ });
+
+ it('is true for both owner-scoped shortcuts', () => {
+ expect(policyNamesOwner(ownerOnlyPolicy())).toBe(true);
+ expect(policyNamesOwner(ownerAndMyAgentsPolicy())).toBe(true);
+ });
+
+ it('is true for a hand-built rule set that names the owner', () => {
+ // Not only the shape the chooser calls `owner`: what matters is whether the
+ // agent has to recognise its owner at all, and this one does.
+ expect(addressingModeOf(HAND_BUILT)).toBe('custom');
+ expect(policyNamesOwner(HAND_BUILT)).toBe(true);
+ });
+
+ it('is false for a rule that admits only the owner’s agents', () => {
+ // This one needs no linked messaging account: an agent sender is
+ // recognised by its agent id. Warning about an unlinked account here would
+ // be a warning nobody can act on.
+ expect(
+ policyNamesOwner({
+ rules: [{ rooms: '*', room_groups: '*', users: [], agents: [], owner_agents: true }],
+ })
+ ).toBe(false);
+ });
+
+ it('is false for rules that name people rather than the owner', () => {
+ expect(
+ policyNamesOwner({
+ rules: [
+ { rooms: '*', room_groups: '*', users: ['user-1'], agents: [], owner: false },
+ { rooms: '*', room_groups: '*', users: [], agents: ['agent-a'] },
+ ],
+ })
+ ).toBe(false);
+ });
+});
+
+describe('addressingModeOf', () => {
+ it('reads an absent policy as anyone', () => {
+ expect(addressingModeOf(null)).toBe('anyone');
+ });
+
+ it('reads a policy with no rules as anyone, as switch-core does', () => {
+ expect(addressingModeOf({ rules: [] })).toBe('anyone');
+ });
+
+ it('tells the two owner-scoped shapes apart', () => {
+ expect(addressingModeOf(ownerOnlyPolicy())).toBe('owner');
+ expect(addressingModeOf(ownerAndMyAgentsPolicy())).toBe('ownerAndAgents');
+ });
+
+ it('reads a policy stored before owner_agents existed as only-me', () => {
+ // An absent key is false server-side. Reading it as the wider choice would
+ // silently widen every agent created before this shipped.
+ expect(
+ addressingModeOf({
+ rules: [{ rooms: '*', room_groups: '*', users: [], agents: [], owner: true }],
+ })
+ ).toBe('owner');
+ });
+
+ it('reads owner-plus-named-agents as custom rather than flattening it', () => {
+ // The shape earlier builds wrote, now that the shortcut no longer has an
+ // agent picker. Calling it "Only me" would drop the names on the next save.
+ expect(
+ addressingModeOf({
+ rules: [{ rooms: '*', room_groups: '*', users: [], agents: ['agent-a'], owner: true }],
+ })
+ ).toBe('custom');
+ });
+
+ it('reads a hand-edited policy as custom', () => {
+ expect(addressingModeOf(HAND_BUILT)).toBe('custom');
+ });
+});
+
+describe('policyForMode', () => {
+ const modes: AddressingMode[] = ['ownerAndAgents', 'owner', 'anyone', 'custom'];
+
+ it('round-trips every mode back to itself', () => {
+ for (const mode of modes) {
+ expect(addressingModeOf(policyForMode(mode, null))).toBe(mode);
+ }
+ });
+
+ it('round-trips a hand-built policy through custom without touching it', () => {
+ expect(addressingModeOf(HAND_BUILT)).toBe('custom');
+ expect(policyForMode('custom', HAND_BUILT)).toBe(HAND_BUILT);
+ });
+
+ it('opens up to anyone by dropping the policy', () => {
+ expect(policyForMode('anyone', HAND_BUILT)).toBeNull();
+ });
+
+ it('replaces a hand-built policy when a shortcut is chosen', () => {
+ expect(policyForMode('owner', HAND_BUILT)).toEqual(ownerOnlyPolicy());
+ expect(policyForMode('ownerAndAgents', HAND_BUILT)).toEqual(ownerAndMyAgentsPolicy());
+ });
+
+ it('narrows when only-me is chosen from only-me-and-my-agents', () => {
+ expect(policyForMode('owner', ownerAndMyAgentsPolicy())).toEqual(ownerOnlyPolicy());
+ });
+
+ it('seeds custom rules from what the shortcut expressed', () => {
+ expect(policyForMode('custom', ownerAndMyAgentsPolicy())).toEqual(ownerAndMyAgentsPolicy());
+ });
+
+ it('seeds custom rules from what anyone expressed, rather than from nothing', () => {
+ const seeded = policyForMode('custom', null);
+ expect(seeded).toEqual({
+ rules: [
+ {
+ rooms: '*',
+ room_groups: '*',
+ users: '*',
+ agents: '*',
+ owner: false,
+ owner_agents: false,
+ },
+ ],
+ });
+ expect(addressingModeOf(seeded)).toBe('custom');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.ts
new file mode 100644
index 000000000..0354f8ffc
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/owner-policy.ts
@@ -0,0 +1,118 @@
+import type { AddressingPolicy, AddressingRule } from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * The addressing policy a newly created agent starts on, and the mapping
+ * between a stored policy and the choices the UI offers for it (CHOO-2137).
+ *
+ * Shared rather than renderer-local because the main process reads policies
+ * too — the owner-recognition probe in `gateway-client.ts` asks the same
+ * question of a policy the chooser does, and one reading of `owner: true` that
+ * both sides use is the point.
+ */
+
+/**
+ * Whether any rule admits the agent's owner. Such a policy leans on the owner
+ * having claimed a messaging identity, so it is the question both the rule
+ * editor's warning and the messaging-apps warning are really asking.
+ *
+ * Any rule carrying `owner: true` counts, not just the shortcut shapes: a
+ * hand-built rule set that names the owner depends on owner recognition
+ * exactly as much as a shortcut does. `owner_agents` deliberately does not
+ * count — an agent sender is recognised by its agent id, not by a claimed
+ * messaging account, so a rule admitting only the owner's agents needs no
+ * identity linked. A null policy is open, and an open agent answers everyone
+ * regardless of who they are recognised as.
+ */
+export function policyNamesOwner(policy: AddressingPolicy | null): boolean {
+ return policy !== null && policy.rules.some((rule) => rule.owner === true);
+}
+
+/**
+ * What the "Who can send instructions" chooser offers.
+ *
+ * Three answers people actually want, each backed by one policy shape, and
+ * `custom` — the rule editor — for everything else.
+ */
+export type AddressingMode = 'ownerAndAgents' | 'owner' | 'anyone' | 'custom';
+
+/**
+ * Its owner, and nobody and nothing else — not even the owner's own agents.
+ * The default for a new agent: the strictest thing on offer is what an agent
+ * running on someone's own machine should start on, and widening it is one
+ * choice away.
+ */
+export function ownerOnlyPolicy(): AddressingPolicy {
+ return { rules: [ownerRule(false)] };
+}
+
+/**
+ * Its owner, plus any agent that owner runs — the orchestration case, where a
+ * manager agent hands work to a worker and no human is in the loop.
+ *
+ * Both subjects are symbolic rather than lists of ids, so the rule keeps
+ * working when a new workspace is connected, another agent is registered, or
+ * the agent changes hands.
+ */
+export function ownerAndMyAgentsPolicy(): AddressingPolicy {
+ return { rules: [ownerRule(true)] };
+}
+
+function ownerRule(ownerAgents: boolean): AddressingRule {
+ return {
+ rooms: '*',
+ room_groups: '*',
+ users: [],
+ agents: [],
+ owner: true,
+ owner_agents: ownerAgents,
+ };
+}
+
+/**
+ * "Anyone" written as a rule, for the switch into the rule editor.
+ *
+ * An empty rule list is already open (both here and in switch-core, where
+ * `AddressingPolicy.is_open()` allows everything), but an editor with no rules
+ * in it does not show what the previous choice meant — this does.
+ */
+function anyoneRulePolicy(): AddressingPolicy {
+ return {
+ rules: [
+ { rooms: '*', room_groups: '*', users: '*', agents: '*', owner: false, owner_agents: false },
+ ],
+ };
+}
+
+/**
+ * Which choice a stored policy is. `custom` is everything the shortcuts cannot
+ * express — including the owner-plus-named-agents shape earlier builds wrote,
+ * which the editor shows faithfully as an `agents` list rather than flattening
+ * it into a shortcut that would drop the names.
+ */
+export function addressingModeOf(policy: AddressingPolicy | null): AddressingMode {
+ if (policy === null || policy.rules.length === 0) return 'anyone';
+ if (policy.rules.length !== 1) return 'custom';
+ const rule = policy.rules[0];
+ if (rule.owner !== true || rule.rooms !== '*' || rule.room_groups !== '*') return 'custom';
+ if (rule.users === '*' || rule.users.length > 0) return 'custom';
+ if (rule.agents === '*' || rule.agents.length > 0) return 'custom';
+ return rule.owner_agents === true ? 'ownerAndAgents' : 'owner';
+}
+
+/**
+ * The policy a chooser change produces, seeded from the policy being left.
+ *
+ * Moving to `custom` carries the current policy into the editor so the rules
+ * start from what the previous choice meant; moving to a shortcut replaces it,
+ * since none of them can hold arbitrary rules.
+ */
+export function policyForMode(
+ mode: AddressingMode,
+ current: AddressingPolicy | null
+): AddressingPolicy | null {
+ if (mode === 'anyone') return null;
+ if (mode === 'owner') return ownerOnlyPolicy();
+ if (mode === 'ownerAndAgents') return ownerAndMyAgentsPolicy();
+ if (current === null || current.rules.length === 0) return anyoneRulePolicy();
+ return current;
+}
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index 384f2eef2..7c0c699ad 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -178,8 +178,17 @@ export type RemoteAgentSummary = {
name: string;
description: string;
connectorType: string;
+ /** Switch user id of the agent's owner, or null for an agent registered
+ * before ownership was tracked. The id rather than the name is what an
+ * "is this mine" check can be made against. */
+ ownerId: string | null;
ownerName: string | null;
knownAgentType: string | null;
+ /** Who may address the agent, or null when it is open to everyone. On the
+ * summary as well as the detail, so "which of these agents answers only its
+ * owner" is one list read rather than a read per agent. Null also for a
+ * server older than the field, which reads the same as open. */
+ addressingPolicy: AddressingPolicy | null;
createdAt: string;
};
@@ -266,6 +275,15 @@ export type RemoteBridge = {
* false (a platform ceiling vs. an operator's choice).
*/
canCreateChannels: boolean;
+ /**
+ * Whether this platform has a user directory Switch can search. False where
+ * the only people it can name are the ones who have spoken to it, which is
+ * why the "which account is you" step is not offered while connecting one:
+ * on a connection nobody has used yet the answer is always nobody. Defaults
+ * to true for a server predating the field — every platform Switch bridged
+ * before Telegram had one.
+ */
+ directorySearchSupported: boolean;
};
/**
@@ -318,6 +336,10 @@ export type RemoteBridgeType = {
* adapter class, so it is answerable before any connection of this type
* exists, which is exactly when the attach form needs it. */
channelCreationSupported: boolean;
+ /** Whether this platform's user directory can be searched — read from the
+ * adapter class, so the connect flow can decide whether to offer the
+ * link-your-account step for a connection that does not exist yet. */
+ directorySearchSupported: boolean;
};
/**
@@ -381,6 +403,31 @@ export type UpdateBridgeResult =
| { kind: 'invalid'; message: string }
| { kind: 'error'; message: string };
+/** Parameters for disconnecting a bridge from a server
+ * (`DELETE /collaborations/{id}`). */
+export type DeleteBridgeParams = {
+ serverId: string;
+ bridgeId: string;
+};
+
+/**
+ * Outcome of disconnecting a bridge.
+ *
+ * `deleted` means the bridge *and every Switch room that lived on it* are gone
+ * — the gateway deletes the rooms first — so this is not the inverse of
+ * attaching one, and a caller must have said so before asking.
+ *
+ * `not-found` is its own case rather than a success: a bridge that is already
+ * absent is usually another operator's deletion, and reporting it as done hides
+ * a mistyped id just as effectively.
+ */
+export type DeleteBridgeResult =
+ | { kind: 'deleted' }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'not-found' }
+ | { kind: 'error'; message: string };
+
/** A bridged (external) human identity on a server. The `users` dimension of an
* addressing policy keys off these ids. */
export type RemoteExternalUser = {
@@ -388,6 +435,101 @@ export type RemoteExternalUser = {
username: string;
};
+/**
+ * A Switch user who says a platform account is theirs (mirrors the gateway
+ * `IdentityClaimant`).
+ */
+export type IdentityClaimant = {
+ userId: string;
+ userName: string;
+};
+
+/**
+ * Someone found in a messaging platform's own user directory (mirrors the
+ * gateway `DirectoryUserSummary`).
+ *
+ * Switch only records a person once they have spoken, so a freshly connected
+ * workspace has nobody to pick from. The directory is the platform's, which is
+ * what lets a user claim their account before ever posting.
+ */
+export type BridgeDirectoryUser = {
+ /** The platform's own id (a Slack `U…`, a Mattermost user id). */
+ externalUserId: string;
+ username: string;
+ displayName: string;
+ email: string | null;
+ /** The `ExternalUser` row id when Switch has already seen this person, else
+ * null. Present rows are reused on claim rather than duplicated. */
+ knownExternalUserId: string | null;
+ /** Everyone who has claimed this account. Claiming is not exclusive, so this
+ * is information about who else is recognised on the account rather than a
+ * reason to stop someone claiming it too. */
+ claimedBy: IdentityClaimant[];
+};
+
+/**
+ * Outcome of searching a bridge's user directory.
+ *
+ * `unsupported` is its own case rather than an empty list: a platform with no
+ * searchable directory (Telegram) answers 501, and the only way forward is to
+ * post a message so Switch learns the account exists. Showing "no matches"
+ * there would send the user searching harder for something that can never
+ * appear.
+ */
+export type BridgeDirectorySearchResult =
+ /**
+ * `note` is set when the platform has no searchable directory and the server
+ * answered from the accounts it has already seen instead. The results are
+ * real but narrower — someone who has never spoken is not among them — so it
+ * is shown alongside them, never in their place.
+ */
+ | { kind: 'results'; users: BridgeDirectoryUser[]; note: string | null }
+ /** Only reachable against a switch-core predating the fallback above, which
+ * refused the search outright rather than narrowing it. */
+ | { kind: 'unsupported'; message: string }
+ | { kind: 'bridge-unavailable'; message: string }
+ | { kind: 'unauthenticated' }
+ | { kind: 'error'; message: string };
+
+/** Claim a platform identity for the signed-in Switch user (CHOO-2137). */
+export type ClaimIdentityParams = {
+ serverId: string;
+ bridgeId: string;
+ /** The platform's own id, not an `ExternalUser` row id — the row may not
+ * exist yet, and the server creates it on demand. */
+ externalUserId: string;
+ username: string;
+};
+
+/**
+ * Outcome of claiming an identity. `bridge-unavailable` is the one failure a
+ * user can act on: an account Switch has never seen has to be provisioned on
+ * the platform's side, which a stopped bridge cannot do.
+ */
+export type ClaimIdentityResult =
+ | { kind: 'claimed'; identity: LinkedIdentity }
+ | { kind: 'bridge-unavailable'; message: string }
+ | { kind: 'unauthenticated' }
+ | { kind: 'error'; message: string };
+
+/**
+ * One messaging account the signed-in user has claimed (mirrors the gateway
+ * `LinkedIdentity`).
+ *
+ * An agent whose addressing policy names its owner is only reachable by that
+ * owner over a bridge that appears in this list — which is why the app reads it
+ * to warn before a policy seals an agent off from everybody.
+ */
+export type LinkedIdentity = {
+ /** The `ExternalUser` row id; what unclaiming addresses. */
+ id: string;
+ bridgeId: string;
+ bridgeDisplayName: string;
+ bridgeType: string;
+ externalUserId: string;
+ externalUsername: string;
+};
+
/**
* Scoped agent-addressing permissions (CHOO-1585). Each dimension is "*" (any)
* or an explicit id list ([] = none). A policy with no rules — or a null policy
@@ -401,6 +543,26 @@ export type AddressingRule = {
room_groups: AddressingDimension;
users: AddressingDimension;
agents: AddressingDimension;
+ /**
+ * Admit the agent's owner, resolved when the message arrives rather than
+ * frozen into the `users` list (CHOO-2137). It survives connecting a new
+ * workspace, recreating a bridge, or the agent changing hands — but it can
+ * only recognise an owner who has claimed their messaging account, so a rule
+ * that names the owner on a platform where they have not admits nobody.
+ *
+ * Optional because a policy written before the field exists carries no
+ * `owner` key; absent reads as false, as it does server-side.
+ */
+ owner?: boolean;
+ /**
+ * Admit any agent owned by the same person, resolved on arrival like
+ * {@link owner} (CHOO-2137). The owner's manager agent handing work to their
+ * worker is the owner acting through a program; naming each one in `agents`
+ * would go stale the next time they register one.
+ *
+ * Optional for the same reason as `owner`: absent reads as false.
+ */
+ owner_agents?: boolean;
};
export type AddressingPolicy = {
@@ -444,8 +606,6 @@ export type ProvisionAgentParams = {
name: string;
description: string;
providerKind: AgentProviderKind;
- /** Bridge handle to @-mention in offline-session notices; omit to skip. */
- notifyUser?: string;
/** Register with the `auto_session` connection model: Switch Console watches the
* agent's rooms and auto-spawns a session on notification. Defaults to off. */
autoSession?: boolean;
@@ -467,8 +627,6 @@ export type ProvisionRemoteAgentParams = {
name: string;
description: string;
providerKind: AgentProviderKind;
- /** Bridge handle to @-mention in offline-session notices; omit to skip. */
- notifyUser?: string;
/** Register with the `auto_session` connection model. Defaults to off. */
autoSession?: boolean;
};
diff --git a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
index 1c2748e23..5b366a755 100644
--- a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
@@ -311,11 +311,19 @@ Whether you can delegate or accept is declared per agent
demand. \`cancel_task(task_id, reason)\` abandons it.
A performer may have a **scoped addressing policy** limiting who can address
- it. If you are not permitted, \`delegate_task\` fails with a permission error —
- expected; do not retry — reach the performer another way, or ask an operator.
- Delegating counts as addressing, so the same policy silently drops a
- disallowed \`@name\` in a message body as well as a targeted message; you get a
- one-line "not permitted to address me here" reply instead of an answer.
+ it. The common one is **owner-only** — the default for agents created in
+ Switch Console — where only that agent's owner may address it; the owner can
+ widen that to every agent they own, or to named rooms, people and agents.
+ If you are not permitted, **\`delegate_task\` fails** with a permission error:
+ a task is work someone is expected to pick up, so it is refused at the point
+ of asking. Expected; do not retry — reach the performer another way, or ask
+ an operator to allow you.
+ **Messages are not blocked.** \`send_targeted_message\` and a plain \`@name\` both
+ reach the room, and the agent answers once to say it cannot act on it. What
+ you get back from \`send_targeted_message\` is \`not_permitted\` in that agent's
+ \`target_statuses\` instead of a reachability value — read its reply rather
+ than sending again. Commands are covered too, so \`!reset\` on a restricted
+ agent is declined the same way.
- **Accepting.** A delegation arrives as \`[Switch] Task delegated to you in
room …\`, carrying the summary and description but **not** the task id — call
\`list_tasks(role='assigned', status='pending')\` to find it, then
@@ -369,7 +377,7 @@ none of it is needed to take part in a conversation.
**Owner-only**: the agent's owner must match your own. \`options\` is a
PARTIAL map of known-agent options merged over the current ones, and the
keys differ per type — for \`opencode\` and \`codex\`: \`repo_dir\` (working
- directory), \`notify_user\`, \`auto_session\`; for \`claude-code\`: those plus
+ directory), \`auto_session\`; for \`claude-code\`: those plus
\`channels_enabled\` and \`subagent_name\`. Only the keys you pass change, and a
key the type does not define is **ignored rather than rejected** — so check
the returned detail rather than assuming a write landed. \`parent_agent_id\`
diff --git a/core/switch_core/addressing.py b/core/switch_core/addressing.py
index 1958f6b7b..f753a5dea 100644
--- a/core/switch_core/addressing.py
+++ b/core/switch_core/addressing.py
@@ -16,15 +16,31 @@ Model:
empty list ``[]`` is the "none" value: it matches nothing. The sender is
exactly one kind (user XOR agent), so a rule that should admit only humans
sets ``agents: []`` and vice-versa.
+ - A rule additionally carries two *symbolic* subjects (CHOO-2137), resolved
+ at enforcement time rather than stored as ids, so they survive the owner
+ claiming a new platform identity, a bridge being recreated, or the agent
+ changing hands:
+ * `owner` — the agent's own owner, whoever that currently is.
+ Human senders only.
+ * `owner_agents` — any agent owned by that same person. Agent senders
+ only. This is what keeps an owner's own orchestration
+ working under an owner-scoped policy: the manager
+ dispatching a worker is the owner acting through a
+ program, and naming each agent by id would break the
+ moment they register a new one.
+ Both are per-rule, so they carry that rule's room scoping like any other
+ dimension.
- A rule *allows* an attempt when the context matches (room AND group) AND
- the sender matches (its own kind's dimension). Addressing is permitted when
- **any** rule allows it.
+ the sender matches (its own kind's dimension, or `owner` for a human).
+ Addressing is permitted when **any** rule allows it.
-Defaults / precedence (agreed on CHOO-1585):
- - An agent with **no rules** preserves today's behaviour: anyone may address
- it (allow-all). Enforcement only kicks in once at least one rule exists.
+Defaults / precedence:
+ - An agent with **no rules** is open: anyone may address it. This is what a
+ pre-CHOO-2137 agent carries, and it is preserved rather than migrated.
- With rules present it is **deny-by-default**: only attempts matching a rule
are permitted.
+ - Agents created from CHOO-2137 onwards start owner-only (see
+ `owner_only_policy`) rather than open.
This module is deliberately pure (no DB, no I/O) so it is trivially testable
and reusable from the receive path, the protocol service, and the gateway.
@@ -54,6 +70,8 @@ class AddressingRule(BaseModel):
room_groups: Dimension = ANY
users: Dimension = ANY
agents: Dimension = ANY
+ owner: bool = False
+ owner_agents: bool = False
@field_validator("rooms", "room_groups", "users", "agents")
@classmethod
@@ -71,14 +89,54 @@ class AddressingRule(BaseModel):
group_id: str | None,
sender_kind: SenderKind,
sender_id: str,
+ sender_user_ids: list[str],
+ sender_owner_user_id: str | None,
+ owner_user_id: str | None,
) -> bool:
if not _dim_contains(self.rooms, room_id):
return False
if not _dim_contains(self.room_groups, group_id):
return False
+ if sender_kind == "user" and self._is_owner(sender_user_ids, owner_user_id):
+ return True
+ if sender_kind == "agent" and self._is_owners_agent(
+ sender_owner_user_id, owner_user_id
+ ):
+ return True
sender_dim = self.users if sender_kind == "user" else self.agents
return _dim_contains(sender_dim, sender_id)
+ def _is_owner(self, sender_user_ids: list[str], owner_user_id: str | None) -> bool:
+ """Whether this rule admits the sender as the agent's owner.
+
+ A platform account may be claimed by several Switch users, so the
+ sender arrives as the set of users who say it is theirs; the owner
+ need only be among them. An ownerless agent has no owner to match, and
+ an unclaimed account resolves to nobody — both answer "not the owner"
+ rather than making a permissive guess.
+ """
+ if not self.owner:
+ return False
+ if owner_user_id is None:
+ return False
+ return owner_user_id in sender_user_ids
+
+ def _is_owners_agent(
+ self, sender_owner_user_id: str | None, owner_user_id: str | None
+ ) -> bool:
+ """Whether this rule admits the sender as an agent of the same owner.
+
+ Both sides must be owned for this to mean anything: two ownerless
+ agents are not each other's, and an ownerless target has nobody whose
+ agents these would be. Either one missing answers "no" rather than
+ letting an unowned agent inherit the fleet's trust.
+ """
+ if not self.owner_agents:
+ return False
+ if owner_user_id is None or sender_owner_user_id is None:
+ return False
+ return sender_owner_user_id == owner_user_id
+
class AddressingPolicy(BaseModel):
"""An agent's addressing allow-list. Empty ``rules`` → allow-all."""
@@ -96,10 +154,20 @@ class AddressingPolicy(BaseModel):
group_id: str | None,
sender_kind: SenderKind,
sender_id: str,
+ sender_user_ids: list[str],
+ sender_owner_user_id: str | None,
+ owner_user_id: str | None,
) -> bool:
"""Whether an addressing attempt from this sender, in this room, is
permitted. Allow-all when the policy is open; otherwise permitted iff
- at least one rule matches."""
+ at least one rule matches.
+
+ `sender_user_ids` are the Switch users who have claimed a human
+ sender's platform account (empty when nobody has);
+ `sender_owner_user_id` is who owns an agent sender (None for a human
+ or an ownerless agent); `owner_user_id` is the addressed agent's
+ owner. Together they resolve the `owner` and `owner_agents` rules.
+ """
if self.is_open():
return True
return any(
@@ -108,10 +176,22 @@ class AddressingPolicy(BaseModel):
group_id=group_id,
sender_kind=sender_kind,
sender_id=sender_id,
+ sender_user_ids=sender_user_ids,
+ sender_owner_user_id=sender_owner_user_id,
+ owner_user_id=owner_user_id,
)
for rule in self.rules
)
+ def requires_owner_identity(self) -> bool:
+ """Whether any rule depends on resolving the owner's platform identity.
+
+ Used to warn an operator that an agent is unreachable until its owner
+ claims an identity on the bridges it works over — the difference
+ between a policy that is merely strict and one that admits nobody.
+ """
+ return any(rule.owner for rule in self.rules)
+
def _dim_contains(dimension: Dimension, value: str | None) -> bool:
"""Whether a single dimension admits ``value``. ``"*"`` admits anything;
@@ -131,6 +211,49 @@ def parse_policy(raw: dict | None) -> AddressingPolicy:
return AddressingPolicy.model_validate(raw)
+def owner_only_policy(allowed_agent_ids: list[str]) -> AddressingPolicy:
+ """Owner-only: the agent's owner anywhere, and nobody else.
+
+ No other human, and no agent except those explicitly granted.
+ `allowed_agent_ids` names individual dispatchers by id; empty means the
+ agent answers only to its owner, in person.
+ """
+ return AddressingPolicy(
+ rules=[
+ AddressingRule(
+ rooms=ANY,
+ room_groups=ANY,
+ users=[],
+ agents=list(allowed_agent_ids),
+ owner=True,
+ )
+ ]
+ )
+
+
+def owner_and_owner_agents_policy() -> AddressingPolicy:
+ """The owner, plus any agent that owner runs (CHOO-2137).
+
+ The default a Switch Console agent is created on. Strict owner-only is one
+ step too strict to be the thing everyone starts on: an owner's manager
+ agent dispatching their worker is still the owner acting, and an agent that
+ refuses its own owner's orchestration looks broken rather than private.
+ Somebody else's agent is admitted by neither.
+ """
+ return AddressingPolicy(
+ rules=[
+ AddressingRule(
+ rooms=ANY,
+ room_groups=ANY,
+ users=[],
+ agents=[],
+ owner=True,
+ owner_agents=True,
+ )
+ ]
+ )
+
+
def can_address(
policy: AddressingPolicy,
*,
@@ -138,6 +261,9 @@ def can_address(
group_id: str | None,
sender_kind: SenderKind,
sender_id: str,
+ sender_user_ids: list[str],
+ sender_owner_user_id: str | None,
+ owner_user_id: str | None,
) -> bool:
"""Convenience free function mirroring :meth:`AddressingPolicy.allows`."""
return policy.allows(
@@ -145,4 +271,7 @@ def can_address(
group_id=group_id,
sender_kind=sender_kind,
sender_id=sender_id,
+ sender_user_ids=sender_user_ids,
+ sender_owner_user_id=sender_owner_user_id,
+ owner_user_id=owner_user_id,
)
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index c3c75a4da..bd66f2b2d 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -276,8 +276,8 @@ async def register_known_agents_bulk_endpoint(
)
# Subagents inherit the parent's operational settings unless the caller
- # overrides them: they should page the same operator (`notify_user`), run
- # in the same channels mode, and use the same repo dir as their parent.
+ # overrides them: they should run in the same channels mode and use the
+ # same repo dir as their parent.
# The bridge exposes no GET-profile endpoint, so inheriting here means the
# caller (the configure skill) doesn't have to recover these from the
# parent — passing just `parent_agent_id` is enough.
@@ -285,7 +285,7 @@ async def register_known_agents_bulk_endpoint(
parent_opts = parent_md.get("known_agent_options")
inherited: dict[str, Any] = {}
if isinstance(parent_opts, dict):
- for key in ("channels_enabled", "repo_dir", "notify_user"):
+ for key in ("channels_enabled", "repo_dir"):
if parent_opts.get(key) is not None:
inherited[key] = parent_opts[key]
diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.py
index e61c54419..1f6669602 100644
--- a/core/switch_core/bridges/agent/api/schemas.py
+++ b/core/switch_core/bridges/agent/api/schemas.py
@@ -59,8 +59,8 @@ class BulkSubagentSpec(BaseModel):
class RegisterKnownAgentBulkRequest(BaseModel):
"""Register many subagents under one parent agent in a single call.
- `options` is the shared base (e.g. `channels_enabled`, `repo_dir`,
- `notify_user`) applied to every subagent; the per-subagent `subagent_name`
+ `options` is the shared base (e.g. `channels_enabled`, `repo_dir`) applied
+ to every subagent; the per-subagent `subagent_name`
is merged in on top. Used by the configure skill to bring a user's
existing `.claude/agents/*.md` subagents into Switch in one step.
"""
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.py
index 8f28d9287..a49f6f1d1 100644
--- a/core/switch_core/bridges/agent/commands.py
+++ b/core/switch_core/bridges/agent/commands.py
@@ -965,7 +965,11 @@ async def _cmd_run_cmd(
role_known = role_obj is not None
msg = spec.start_session_instructions(
- options, agent, meta.name, assume_role=role if role_known else None
+ options,
+ agent,
+ meta.name,
+ await client.owner_handle_in(agent, meta.bridge_id),
+ assume_role=role if role_known else None,
)
if msg is None:
await _reply(
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index ad91374a7..dec1e594b 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -709,6 +709,12 @@ async def send_targeted_message(
message until they reconnect). User targets are omitted — their
reachability is the collaboration bridge's concern. A role with no live
holder contributes no entries.
+
+ `not_permitted` is the one status that is not about reachability: that
+ agent's addressing policy does not admit you. The message is still
+ sent, and it will answer in the room saying it cannot act on it — so
+ read its reply rather than treating this as a failed send. Reaching it
+ another way is a matter for whoever owns it, not for a retry.
"""
agent_id = get_agent_id()
room_id = await require_connected_room()
@@ -1599,7 +1605,7 @@ async def update_agent_detail(
- `options`: a PARTIAL map of the agent's known-agent options to
change — only the keys you pass are updated; the rest are left as-is.
For a claude-code agent the options are `repo_dir` (the working
- directory), `channels_enabled`, `notify_user`, and `subagent_name`.
+ directory), `channels_enabled`, and `subagent_name`.
The merged options are validated against the agent type's schema and
its integration profile is rebuilt to match.
- `parent_agent_id`: set the agent's parent (e.g. to make it a subagent
diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.py
index 0d3c5e28b..15722e471 100644
--- a/core/switch_core/bridges/agent/protocol/agent_detail.py
+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py
@@ -76,6 +76,11 @@ async def build_agent_summary(
known_agent_options=known_agent_options
if isinstance(known_agent_options, dict)
else None,
+ addressing_policy=(
+ AddressingPolicy.model_validate(agent.addressing_policy)
+ if isinstance(agent.addressing_policy, dict)
+ else None
+ ),
)
@@ -251,12 +256,6 @@ async def assemble_agent_detail(
for child in child_agents
]
- addressing_policy = (
- AddressingPolicy.model_validate(agent.addressing_policy)
- if isinstance(agent.addressing_policy, dict)
- else None
- )
-
return AgentDetail(
**summary.model_dump(),
agent_type=agent.agent_type,
@@ -270,7 +269,6 @@ async def assemble_agent_detail(
rooms=memberships,
sessions=sessions,
children=children,
- addressing_policy=addressing_policy,
)
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 7a145dd36..5c251eb82 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -20,7 +20,12 @@ from nio import (
)
from sqlalchemy import func, select
-from switch_core.addressing import can_address, parse_policy
+from switch_core.addressing import (
+ AddressingPolicy,
+ can_address,
+ owner_only_policy,
+ parse_policy,
+)
from switch_core.aliases import check_alias_collisions, validate_alias_format
from switch_core.authz import Action, Principal, require, require_manage
from switch_core.bridges.agent.protocol.agent_detail import (
@@ -191,6 +196,8 @@ class ProtocolService:
parent_agent_id: str | None = None,
oauth_client_id: str | None = None,
overwrite: bool = False,
+ addressable_by_agent_ids: list[str] | None = None,
+ owner_only: bool = True,
) -> RegistrationResult:
"""Register or re-register an agent.
@@ -201,6 +208,13 @@ class ProtocolService:
Code subagent registered under the user's main agent); None for an
ordinary top-level agent.
+ New agents start **owner-only** (CHOO-2137): only the owner may address
+ them, from any room, and no other agent may unless named in
+ ``addressable_by_agent_ids`` — which is how a dispatcher (a manager or
+ orchestrator agent) is let in. Pass ``owner_only=False`` to create an
+ agent anyone may address, the pre-CHOO-2137 default. Re-registration
+ leaves an existing agent's policy alone either way.
+
If an agent with this name already exists, the call fails with
``AgentExistsError`` unless ``overwrite=True`` is passed. Re-registering
rotates the API key and replaces the integration profile, so callers
@@ -269,6 +283,11 @@ class ProtocolService:
encrypted_key=encrypted_key,
tools=tool_specs,
models=model_specs,
+ addressing_policy=(
+ owner_only_policy(addressable_by_agent_ids or [])
+ if owner_only
+ else None
+ ),
)
logger.info("Registered agent: %s (%s)", name, agent_id)
@@ -292,6 +311,8 @@ class ProtocolService:
models: list[ModelSpec] | None = None,
metadata: dict[str, Any] | None = None,
overwrite: bool = False,
+ addressable_by_agent_ids: list[str] | None = None,
+ owner_only: bool = True,
) -> RegistrationResult:
"""Resolve a registration token to its owner, then register the agent.
@@ -314,6 +335,8 @@ class ProtocolService:
metadata=metadata,
owner_id=key.user_id,
overwrite=overwrite,
+ addressable_by_agent_ids=addressable_by_agent_ids,
+ owner_only=owner_only,
)
async def _create_agent(
@@ -333,6 +356,7 @@ class ProtocolService:
encrypted_key: str,
tools: list[ToolSpec],
models: list[ModelSpec],
+ addressing_policy: AddressingPolicy | None,
) -> str:
api_key_record = ApiKey(
type="agent",
@@ -360,6 +384,11 @@ class ProtocolService:
parent_agent_id=parent_agent_id,
oauth_client_id=oauth_client_id,
metadata_=metadata,
+ addressing_policy=(
+ addressing_policy.model_dump()
+ if addressing_policy is not None
+ else None
+ ),
)
await self.agent_store.create(session, agent)
@@ -917,6 +946,64 @@ class ProtocolService:
"attachments": posted,
}
+ async def _require_can_address(
+ self,
+ target: Agent,
+ *,
+ room_id: str,
+ group_id: str | None,
+ sender_agent_id: str,
+ ) -> None:
+ """Raise unless `sender_agent_id` may address `target` in this room.
+
+ For delegation, which creates a row someone is expected to work. A
+ message the target can decline in the room is checked with
+ :meth:`_can_address` and reported instead.
+ """
+ if await self._can_address(
+ target,
+ room_id=room_id,
+ group_id=group_id,
+ sender_agent_id=sender_agent_id,
+ ):
+ return
+ raise PermissionError(
+ f"Agent {sender_agent_id} is not permitted to address "
+ f"{target.name} in this room."
+ )
+
+ async def _can_address(
+ self,
+ target: Agent,
+ *,
+ room_id: str,
+ group_id: str | None,
+ sender_agent_id: str,
+ ) -> bool:
+ """Whether `sender_agent_id` may address `target` in this room.
+
+ An agent sender is never the target's *owner* — owner rules admit the
+ human, not the programs acting for them — so an agent gets in through
+ the `agents` dimension, or through an `owner_agents` rule when both are
+ owned by the same person. The sender is looked up only once the target
+ is actually restricted, so the open case stays a single read.
+ """
+ policy = parse_policy(target.addressing_policy)
+ if policy.is_open():
+ return True
+ async with self.session_factory() as session:
+ sender = await self.agent_store.get(session, sender_agent_id)
+ return can_address(
+ policy,
+ room_id=room_id,
+ group_id=group_id,
+ sender_kind="agent",
+ sender_id=sender_agent_id,
+ sender_user_ids=[],
+ sender_owner_user_id=sender.owner_id if sender is not None else None,
+ owner_user_id=target.owner_id,
+ )
+
async def send_targeted_message(
self,
agent_id: str,
@@ -993,6 +1080,38 @@ class ProtocolService:
if holder is not None:
role_holder_names.add(holder.name)
+ # A target whose policy does not admit this sender is reported, not
+ # refused. The message goes to the room either way and the target
+ # declines it there, in the open, where whoever is reading can see that
+ # it was asked and why it will not act — which is the same thing that
+ # happens to an `@name` in a plain message. Refusing here would make
+ # the same request succeed or fail depending on which tool sent it, and
+ # would leave the sender's account of it the only one on record.
+ # Delegation is the exception, and raises: a task is a row someone is
+ # expected to work, not something a room can decline.
+ async with self.session_factory() as session:
+ room_row = await self.room_store.get(session, room_id)
+ group_id = room_row.group_id if room_row is not None else None
+ addressed_agent_names = {
+ name for name in target_names if participant_by_name[name].type == "agent"
+ } | role_holder_names
+ refused: set[str] = set()
+ async with self.session_factory() as session:
+ for name in sorted(addressed_agent_names):
+ participant = participant_by_name.get(name)
+ if participant is None:
+ continue
+ target_agent = await self.agent_store.get(session, participant.id)
+ if target_agent is None:
+ continue
+ if not await self._can_address(
+ target_agent,
+ room_id=room_id,
+ group_id=group_id,
+ sender_agent_id=agent_id,
+ ):
+ refused.add(name)
+
mention_tokens = [f"@{name}" for name in target_names]
mention_tokens += [f"@{role}" for role in roles]
body = f"{' '.join(mention_tokens)} {content}"
@@ -1006,11 +1125,19 @@ class ProtocolService:
and participant_by_name[name].type == "agent"
}
status_names |= role_holder_names
+ # A refused target reports why rather than how reachable it is. Both
+ # matter to the sender, but only one of them explains a reply that says
+ # no — and "live" for an agent that will decline is the reading that
+ # sends someone looking for a bug.
target_statuses = {
- name: participant_by_name[name].status
+ name: (
+ AgentStatus.NOT_PERMITTED
+ if name in refused
+ else participant_by_name[name].status
+ )
for name in status_names
if name in participant_by_name
- and participant_by_name[name].status is not None
+ and (name in refused or participant_by_name[name].status is not None)
}
return SendTargetedResult(event_id=event_id, target_statuses=target_statuses)
@@ -1111,6 +1238,7 @@ class ProtocolService:
agent = await self.agent_store.get(session, agent_id)
if agent is None:
raise ValueError(f"Agent not found: {agent_id}")
+ room_row = await self.room_store.get(session, room.id)
await self.agent_runtime_state_store.upsert(
session,
agent_id,
@@ -1127,7 +1255,9 @@ class ProtocolService:
matrix_room_id=room.matrix_room_id,
room_id=room.id,
state=state,
- notify_user=self._notify_user_for(agent),
+ mention_handle=await self._mention_handle_for(
+ agent, room_row.bridge_id if room_row is not None else None
+ ),
thread_id=thread_id,
deeplink_url=deeplink_url,
detail=detail,
@@ -1142,7 +1272,7 @@ class ProtocolService:
matrix_room_id: str,
room_id: str,
state: str,
- notify_user: str | None,
+ mention_handle: str | None,
thread_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -1162,7 +1292,7 @@ class ProtocolService:
"agent_name": agent_name,
"room_id": room_id,
"state": state,
- "notify_user": notify_user,
+ "mention_handle": mention_handle,
"thread_id": thread_id,
"deeplink_url": deeplink_url,
"detail": detail,
@@ -1213,25 +1343,38 @@ class ProtocolService:
matrix_room_id=room.matrix_room_id,
room_id=room.id,
state=RUNTIME_STATE_IDLE,
- notify_user=self._notify_user_for(agent),
+ mention_handle=await self._mention_handle_for(agent, room.bridge_id),
thread_id=None,
)
- @staticmethod
- def _notify_user_for(agent: Agent) -> str | None:
- """Read the configured operator handle from the agent's known options.
-
- Bare username (Slack/Mattermost handle or Switch user) the bridge
- @-mentions when the agent is awaiting input. Read straight from
- metadata to avoid importing the gateway layer here.
+ async def _mention_handle_for(
+ self, agent: Agent, bridge_id: str | None
+ ) -> str | None:
+ """The handle to @-mention when this agent needs its operator, on the
+ platform the room is bridged to.
+
+ Resolved from the agent's owner and the messaging account that owner
+ has claimed on this bridge (CHOO-2137), rather than from a handle typed
+ into the agent's config. A handle is per-platform — the same person is
+ one name on Slack and another on Telegram — so a single configured
+ string could only ever be right on one of them, and was silently plain
+ text everywhere else.
+
+ None when the agent has no owner, the room has no bridge, or the owner
+ has claimed nothing here. Callers disclose that rather than dropping
+ the notification quietly.
"""
- md = agent.metadata_ if isinstance(agent.metadata_, dict) else {}
- opts = md.get("known_agent_options")
- if isinstance(opts, dict):
- value = opts.get("notify_user")
- if isinstance(value, str) and value.strip():
- return value.strip()
- return None
+ if agent.owner_id is None or bridge_id is None:
+ return None
+ async with self.session_factory() as session:
+ claimed = await self.external_user_store.get_by_user(
+ session, agent.owner_id
+ )
+ # Claiming is not exclusive and one person may hold several accounts on
+ # a bridge. Sorted so a second account cannot change who gets pinged
+ # from one call to the next.
+ here = sorted(u.external_username for u in claimed if u.bridge_id == bridge_id)
+ return here[0] if here else None
@staticmethod
def _message_dict(event: Any) -> dict[str, Any]:
@@ -1701,22 +1844,16 @@ class ProtocolService:
await self.require_room_member(performer_id, room_id)
- # Scoped addressing policy (CHOO-1585): delegating a task addresses the
- # performer, so it is subject to the same allow-list as a message. Unlike
- # the message path (which demotes to unaddressed) a task is explicit, so a
+ # Scoped addressing policy: delegating a task addresses the performer,
+ # so it is subject to the same allow-list as a message. Unlike the
+ # message path (which demotes to unaddressed) a task is explicit, so a
# denied delegation fails loud rather than silently vanishing.
- performer_policy = parse_policy(performer.addressing_policy)
- if not performer_policy.is_open() and not can_address(
- performer_policy,
+ await self._require_can_address(
+ performer,
room_id=room.id,
group_id=room_row.group_id if room_row is not None else None,
- sender_kind="agent",
- sender_id=requester_id,
- ):
- raise PermissionError(
- f"Agent {requester_id} is not permitted to address "
- f"{performer.name} in this room."
- )
+ sender_agent_id=requester_id,
+ )
async with self.session_factory() as session:
task = Task(
diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.py
index 243a8d5c7..f861f1031 100644
--- a/core/switch_core/bridges/agent/protocol/types.py
+++ b/core/switch_core/bridges/agent/protocol/types.py
@@ -105,6 +105,10 @@ class AgentStatus(StrEnum):
# actively watching (global "watching" heartbeat) — it will spin up a
# session on demand when addressed.
DORMANT = "dormant"
+ # Reachable, but its addressing policy does not admit this sender, so it
+ # will decline in the room rather than act. Not a connectivity state: the
+ # message is still delivered and still answered, just with a refusal.
+ NOT_PERMITTED = "not_permitted"
class SendTargetedResult(BaseModel):
diff --git a/core/switch_core/bridges/agent/server_connectors/core.py b/core/switch_core/bridges/agent/server_connectors/core.py
index f777725e5..c19946116 100644
--- a/core/switch_core/bridges/agent/server_connectors/core.py
+++ b/core/switch_core/bridges/agent/server_connectors/core.py
@@ -144,6 +144,11 @@ class ConnectorCore:
models=agent.models,
metadata={"server_connector_id": self._connector_id},
overwrite=True,
+ # A server-side connector agent is a service the deployment
+ # offers everyone, not one person's assistant; it is owned by
+ # whoever holds the registration token only in the bookkeeping
+ # sense. Owner-only would make it answer to that account alone.
+ owner_only=False,
)
except Exception:
logger.exception(
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index c1547fe50..16d659f5b 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -11,6 +11,7 @@ from switch_core.bridges.collaboration.models import (
BridgeInstallLink,
ChannelCreationUnsupported,
ChannelType,
+ DirectoryUser,
InboundAgentJoin,
InboundAppJoin,
InboundCommand,
@@ -54,6 +55,18 @@ class CollaborationAdapter(ABC):
#: exactly those moments.
supports_channel_creation: ClassVar[bool] = True
+ #: Whether this platform has a user directory Switch can search.
+ #:
+ #: False where the only people Switch can name are the ones who have
+ #: spoken to it — a Telegram bot cannot enumerate anyone else. That is not
+ #: a smaller directory, it is a different question: on a freshly connected
+ #: connection of such a type the answer is always "nobody", so asking a
+ #: user to pick themselves from it is asking them to pick from an empty
+ #: list. Declared on the class for the same reason as
+ #: `supports_channel_creation` — the answer is needed before a connection
+ #: exists and while one is stopped.
+ supports_directory_search: ClassVar[bool] = True
+
#: Whether this platform renders a link whose scheme is not http(s).
#:
#: False for platforms that linkify only the web schemes. It matters
@@ -261,7 +274,7 @@ class CollaborationAdapter(ABC):
agent_name: str,
state: str,
*,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -273,7 +286,7 @@ class CollaborationAdapter(ABC):
channel_id,
agent_name,
state,
- notify_user=notify_user,
+ mention_handle=mention_handle,
thread_root_id=thread_root_id,
deeplink_url=deeplink_url,
detail=detail,
@@ -294,7 +307,7 @@ class CollaborationAdapter(ABC):
agent_name: str,
state: str,
*,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -323,7 +336,7 @@ class CollaborationAdapter(ABC):
elif state == "awaiting-input":
await self.send_typing(channel_id, agent_name, True)
await self._ping_operator(
- channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ channel_id, agent_name, mention_handle, thread_root_id, deeplink_url
)
else:
await self.send_typing(channel_id, agent_name, False)
@@ -417,19 +430,29 @@ class CollaborationAdapter(ABC):
self,
channel_id: str,
agent_name: str,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
) -> str | None:
"""Post a message nudging the operator that the agent needs input.
+ `mention_handle` is the agent owner's account on this platform, or None
+ when there is nobody to reach — no owner, or an owner who has not said
+ which account here is theirs. That case says so instead of posting a
+ line nobody is notified about: a nudge that reaches no one looks
+ identical to an agent that never asked.
+
Returns the posted message ref so callers that can remove it (Slack,
Mattermost) track it for cleanup when the turn ends."""
- mention = f"@{notify_user} " if notify_user else ""
- body = self.translate_outbound(
- f"{mention}**{agent_name}** needs your input."
- + self._deeplink_suffix(deeplink_url)
- )
+ if mention_handle:
+ text = f"@{mention_handle} **{agent_name}** needs your input."
+ else:
+ text = (
+ f"**{agent_name}** needs your input — but nobody here is linked "
+ f"to its owner, so this pings no one. Link your "
+ f"{self.platform_name} account in Switch Console to be notified."
+ )
+ body = self.translate_outbound(text + self._deeplink_suffix(deeplink_url))
return await self.send_message(channel_id, agent_name, body, thread_root_id)
@abstractmethod
@@ -455,10 +478,33 @@ class CollaborationAdapter(ABC):
where DMs can only be initiated by the user — and so cannot be created
from Switch — raise instead of pretending to succeed."""
raise ChannelCreationUnsupported(
- f"{type(self).__name__} cannot create DM channels — on this platform "
+ f"{self.platform_name} cannot create DM channels — on this platform "
"DMs are initiated by the user from the messaging client"
)
+ @property
+ def platform_name(self) -> str:
+ """The platform as a person would name it, for messages that reach a
+ user. The class name is the fallback rather than the source: "Telegram"
+ belongs in a dialog, "TelegramAdapter" does not."""
+ return type(self).__name__.removesuffix("Adapter")
+
+ async def search_directory_users(self, query: str) -> list[DirectoryUser]:
+ """Search the platform's own user directory (CHOO-2137).
+
+ Lets someone claim their platform identity before Switch has ever seen
+ them speak — `ExternalUser` rows are only created on first message, so
+ without this a freshly connected workspace offers nobody to pick from.
+
+ Platforms with no searchable directory raise instead of returning an
+ empty list, so the caller can say "you must post once first" rather
+ than showing an empty picker that looks broken.
+ """
+ raise NotImplementedError(
+ f"{self.platform_name} has no searchable user directory — on this "
+ "platform someone must send a message before Switch knows them"
+ )
+
async def channel_deeplink(self, external_channel_id: str) -> str | None:
"""Native deeplink that opens this channel in the platform's desktop
app (Switch Console → messaging app direction), or None when the platform
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 039072f97..7c62dfe76 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -978,6 +978,39 @@ class BridgeCore:
# ── Puppet lifecycle ─────────────────────────────────────────────────────
+ async def ensure_external_user(
+ self, *, external_user_id: str, external_username: str
+ ) -> ExternalUser:
+ """Get-or-create the `ExternalUser` record for a platform identity,
+ without waiting for that person to speak.
+
+ The inbound path creates these lazily on first message, which leaves
+ nobody to claim for a workspace that has only just been connected.
+ Claiming an identity (CHOO-2137) needs the record to exist up front, so
+ this provisions the same puppet the inbound path would have.
+ """
+ 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 not None:
+ return existing
+
+ client_id = self._user_puppets.get(external_user_id)
+ if client_id is None:
+ client_id = await self._create_puppet(external_user_id, external_username)
+
+ async with self._session_factory() as session:
+ created = await self._external_user_store.get_by_client_id(
+ session, client_id
+ )
+ if created is None:
+ raise RuntimeError(
+ f"Puppet for external user {external_user_id} on bridge "
+ f"{self._bridge_id} was created without an ExternalUser record"
+ )
+ return created
+
async def _create_puppet(
self, external_user_id: str, external_username: str
) -> str:
@@ -1429,7 +1462,7 @@ class BridgeCore:
channel_id,
event.agent_name,
event.state,
- notify_user=event.notify_user,
+ mention_handle=event.mention_handle,
thread_root_id=thread_root_ref,
deeplink_url=event.deeplink_url,
detail=event.detail,
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 5b1225564..452731c41 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -30,6 +30,7 @@ from switch_core.bridges.collaboration.models import (
AttachmentFailure,
BridgeConnectionConfig,
ChannelType,
+ DirectoryUser,
InboundAgentJoin,
InboundAppJoin,
InboundCommand,
@@ -574,7 +575,7 @@ class DiscordAdapter(CollaborationAdapter):
agent_name: str,
state: str,
*,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -610,7 +611,7 @@ class DiscordAdapter(CollaborationAdapter):
)
elif state == "awaiting-input":
ref = await self._ping_operator(
- channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ channel_id, agent_name, mention_handle, thread_root_id, deeplink_url
)
if ref is not None:
self._input_pings.setdefault(key, []).append(ref)
@@ -654,6 +655,48 @@ class DiscordAdapter(CollaborationAdapter):
)
return str(channel.id)
+ async def search_directory_users(self, query: str) -> list[DirectoryUser]:
+ """Find guild members whose username or nickname starts with `query`.
+
+ Asks Discord to do the matching rather than pulling the member list
+ and filtering here, so a large guild costs one request either way.
+ Discord matches on a prefix, so this searches by prefix — unlike the
+ Slack adapter, which has no server-side search and filters a full
+ listing on substrings.
+
+ Discord's bot API never exposes a member's email, so `email` is always
+ absent here — which is fine, since claiming an account identifies it
+ rather than proving who owns it.
+ """
+ term = query.strip()
+ if not term:
+ return []
+
+ guild = await self._get_guild()
+ try:
+ members = await guild.query_members(query=term, limit=100)
+ except (discord.HTTPException, discord.ClientException) as e:
+ raise RuntimeError(f"Discord member search failed: {e}") from e
+ except TimeoutError as e:
+ # A gateway query that never comes back would otherwise hang the
+ # request; surfacing it as a bridge failure gets the caller a 502.
+ raise RuntimeError("Discord member search timed out") from e
+
+ results = [
+ DirectoryUser(
+ external_user_id=str(member.id),
+ # `member.name` is what the inbound path records as the sender,
+ # so a claim made from this list matches messages that arrive.
+ username=str(member.name),
+ display_name=str(getattr(member, "display_name", None) or member.name),
+ email=None,
+ )
+ for member in members
+ if not getattr(member, "bot", False)
+ ]
+ results.sort(key=lambda u: u.display_name.lower())
+ return results
+
async def create_dm_channel(
self,
*,
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 2e27dc5d5..3e5769e8d 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -4,6 +4,7 @@ import asyncio
import logging
import re
from typing import TYPE_CHECKING
+from uuid import uuid4
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
@@ -28,6 +29,25 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+def _bridge_client_localpart(bridge_type: str, display_name: str) -> str:
+ """The Matrix localpart for a messaging app's own client.
+
+ The random tail is what makes disconnecting and reconnecting work. The
+ readable part is derived from the app's type and name, which an operator is
+ free to reuse — and the homeserver has no API for removing an account, so
+ the old one is still there when they do. Reusing the name meant either
+ colliding with it, or adopting an account whose password Switch no longer
+ holds: shared-secret registration reports an existing user as success
+ without applying the new one, so the second reads as a working connection
+ that can never log in.
+
+ A fresh name each time costs an abandoned account on the homeserver, which
+ is already the case and is logged on removal.
+ """
+ safe_name = re.sub(r"[^a-z0-9._=-]", "-", display_name.lower())[:16]
+ return f"switch-bridge-{bridge_type}-{safe_name}-{uuid4().hex[:8]}"
+
+
class CollaborationBridgeLifecycleService:
def __init__(
self,
@@ -95,6 +115,22 @@ class CollaborationBridgeLifecycleService:
return True
return adapter_cls.supports_channel_creation
+ def supports_directory_search(self, bridge_type: str) -> bool:
+ """Whether this platform has a user directory Switch can search.
+
+ Read from the adapter class for the same reason as
+ `supports_channel_creation`: the answer decides whether to even offer
+ someone the "which account is you" step while connecting, which is
+ before any connection exists. An unknown type is reported as
+ searchable — registration rejects it by name a moment later, which is a
+ better error than a capability claim about a platform Switch does not
+ have.
+ """
+ adapter_cls = self._adapter_registry.get(bridge_type)
+ if adapter_cls is None:
+ return True
+ return adapter_cls.supports_directory_search
+
def get_config_schema(self, bridge_type: str) -> dict[str, object]:
config_cls = self._config_registry.get(bridge_type)
if config_cls is None:
@@ -134,11 +170,10 @@ class CollaborationBridgeLifecycleService:
config_cls.model_validate(connection_config)
- safe_name = re.sub(r"[^a-z0-9._=-]", "-", display_name.lower())[:16]
bridge_client_record = await self._client_lifecycle.create_client(
client_type="bridge",
display_name=f"bridge-{bridge_type}-{display_name}",
- localpart=f"switch-bridge-{bridge_type}-{safe_name}",
+ localpart=_bridge_client_localpart(bridge_type, display_name),
)
bridge = CollaborationBridge(
@@ -283,8 +318,22 @@ class CollaborationBridgeLifecycleService:
await self.stop(bridge_id)
async def remove(self, bridge_id: str) -> None:
+ """Disconnect a messaging app and take its identities with it.
+
+ Everything Switch created to talk to this platform goes: the bridge's
+ own Matrix client, and the puppet client behind every person Switch saw
+ on it. Leaving those behind is not a tidiness problem — the bridge
+ client's Matrix name is derived from the app's type and display name,
+ so an operator who disconnects an app and reconnects one named the same
+ collided with the row left by the last one.
+
+ Order matters: the clients are children of nothing but the bridge and
+ external-user rows point at them, so those go first or the foreign keys
+ refuse.
+ """
await self.stop(bridge_id)
async with self._session_factory() as session:
+ bridge = await self._bridge_store.get(session, bridge_id)
dependent_rooms = await self._room_store.get_by_bridge(session, bridge_id)
if dependent_rooms:
logger.warning(
@@ -296,10 +345,29 @@ class CollaborationBridgeLifecycleService:
)
for room in dependent_rooms:
await self._room_store.clear_bridge(session, room.id)
+ puppets = await self._external_user_store.get_by_bridge(session, bridge_id)
+ puppet_client_ids = [u.client_id for u in puppets if u.client_id]
await self._external_user_store.delete_by_bridge(session, bridge_id)
await self._bridge_store.delete(session, bridge_id)
await session.commit()
- logger.info("Removed collaboration bridge %s", bridge_id)
+
+ removed = list(puppet_client_ids)
+ if bridge is not None:
+ removed.append(bridge.client_id)
+ for client_id in removed:
+ await self._client_lifecycle.remove(client_id)
+
+ # The Matrix accounts themselves outlive this: the homeserver offers no
+ # deprovisioning call Switch can make. Said out loud because it is the
+ # reason a reconnection cannot reuse the old name — see
+ # `_bridge_client_localpart`.
+ logger.info(
+ "Removed collaboration bridge %s and %d client identities; their "
+ "Matrix accounts remain on the homeserver, which has no API to "
+ "remove them",
+ bridge_id,
+ len(removed),
+ )
def get(self, bridge_id: str) -> BridgeCore | None:
return self._bridges.get(bridge_id)
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index ae10819eb..dc79714cc 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -27,6 +27,7 @@ from switch_core.bridges.collaboration.models import (
AttachmentFailure,
BridgeConnectionConfig,
ChannelType,
+ DirectoryUser,
InboundAgentJoin,
InboundAppJoin,
InboundCommand,
@@ -444,7 +445,7 @@ class MattermostAdapter(CollaborationAdapter):
agent_name: str,
state: str,
*,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -490,7 +491,7 @@ class MattermostAdapter(CollaborationAdapter):
)
elif state == "awaiting-input":
ref = await self._ping_operator(
- channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ channel_id, agent_name, mention_handle, thread_root_id, deeplink_url
)
if ref is not None:
self._input_pings.setdefault(key, []).append(ref)
@@ -1261,6 +1262,48 @@ class MattermostAdapter(CollaborationAdapter):
)
self._dispatch(coro, loop) # type: ignore[arg-type]
+ async def search_directory_users(self, query: str) -> list[DirectoryUser]:
+ """Find team members via Mattermost's own user search.
+
+ Scoped to the bridge's team, and bots are dropped — a bot is not a
+ person who can own an agent.
+ """
+ if not self._admin_driver or not self._main_loop:
+ raise RuntimeError("Mattermost adapter is not started")
+
+ term = query.strip()
+ if not term:
+ return []
+
+ driver = self._admin_driver
+ try:
+ found = await self._main_loop.run_in_executor(
+ None,
+ driver.users.search_users,
+ {"term": term, "team_id": self._team_id, "allow_inactive": False},
+ )
+ except Exception as e:
+ raise RuntimeError(f"Mattermost user directory lookup failed: {e}") from e
+
+ results: list[DirectoryUser] = []
+ for user in found or []:
+ if user.get("is_bot"):
+ continue
+ username = user.get("username", "") or ""
+ first = user.get("first_name", "") or ""
+ last = user.get("last_name", "") or ""
+ full_name = " ".join(part for part in (first, last) if part)
+ results.append(
+ DirectoryUser(
+ external_user_id=str(user.get("id")),
+ username=username,
+ display_name=(user.get("nickname") or full_name or username),
+ email=user.get("email") or None,
+ )
+ )
+ results.sort(key=lambda u: u.display_name.lower())
+ return results
+
@staticmethod
def _to_channel_type(mm_type: str) -> ChannelType:
if mm_type == "D":
diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.py
index 53feecbb8..3245d1fad 100644
--- a/core/switch_core/bridges/collaboration/models.py
+++ b/core/switch_core/bridges/collaboration/models.py
@@ -48,6 +48,23 @@ class AttachmentFailure(BaseModel):
reason: str
+class DirectoryUser(BaseModel):
+ """A person as the messaging platform's own directory describes them.
+
+ Distinct from an `ExternalUser`: that record only exists once Switch has
+ seen someone speak, whereas this comes straight from the platform, so a
+ user who has never posted can still be found and claimed (CHOO-2137).
+ `email` is whatever the platform exposes — absent on platforms that do not
+ carry one — and is offered to help a person recognise themselves in the
+ list, never as proof of identity.
+ """
+
+ external_user_id: str
+ username: str
+ display_name: str
+ email: str | None = None
+
+
class InboundMessage(BaseModel):
channel_id: str
channel_type: ChannelType
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 32119aa64..98418fbcb 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -7,6 +7,7 @@ import uuid
from collections import OrderedDict
from collections.abc import Awaitable, Callable
from dataclasses import replace
+from typing import Any
import httpx
from pydantic import BaseModel
@@ -25,6 +26,7 @@ from switch_core.bridges.collaboration.models import (
AttachmentFailure,
BridgeConnectionConfig,
ChannelType,
+ DirectoryUser,
InboundAgentJoin,
InboundAppJoin,
InboundCommand,
@@ -461,7 +463,7 @@ class SlackAdapter(CollaborationAdapter):
agent_name: str,
state: str,
*,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -504,7 +506,7 @@ class SlackAdapter(CollaborationAdapter):
elif state == "awaiting-input":
# Leave the working indicator up; add a ping and track it.
ref = await self._ping_operator(
- channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ channel_id, agent_name, mention_handle, thread_root_id, deeplink_url
)
if ref is not None:
self._input_pings.setdefault(key, []).append(ref)
@@ -1118,6 +1120,67 @@ class SlackAdapter(CollaborationAdapter):
return "\n".join(p.strip() for p in parts if str(p).strip())
+ async def search_directory_users(self, query: str) -> list[DirectoryUser]:
+ """Find workspace members by handle, real name or email.
+
+ Slack has no server-side user search, so this pages `users.list` and
+ filters locally. Deactivated accounts and bots are dropped — a bot is
+ not a person who can own an agent. `email` is only present when the
+ app holds the `users:read.email` scope; without it the field is simply
+ absent rather than the search failing.
+ """
+ if not self._web_client:
+ raise RuntimeError("Slack adapter is not started")
+
+ needle = query.strip().lower()
+ if not needle:
+ return []
+
+ matches: list[DirectoryUser] = []
+ cursor: str | None = None
+ while True:
+ try:
+ result = await self._web_client.users_list(
+ limit=200, cursor=cursor or None
+ )
+ except SlackApiError as e:
+ raise RuntimeError(f"Slack user directory lookup failed: {e}") from e
+
+ members: list[dict[str, Any]] = result.get("members") or []
+ for member in members:
+ if member.get("deleted") or member.get("is_bot"):
+ continue
+ if member.get("id") == "USLACKBOT":
+ continue
+ profile: dict[str, Any] = member.get("profile") or {}
+ handle = member.get("name", "") or ""
+ real_name = profile.get("real_name", "") or member.get("real_name", "")
+ display_name = profile.get("display_name", "") or real_name or handle
+ email = profile.get("email") or None
+ haystack = " ".join(
+ part.lower()
+ for part in (handle, real_name, display_name, email or "")
+ if part
+ )
+ if needle not in haystack:
+ continue
+ matches.append(
+ DirectoryUser(
+ external_user_id=str(member.get("id")),
+ username=handle or str(member.get("id")),
+ display_name=display_name or handle,
+ email=email,
+ )
+ )
+
+ metadata: dict[str, Any] = result.get("response_metadata") or {}
+ cursor = metadata.get("next_cursor")
+ if not cursor:
+ break
+
+ matches.sort(key=lambda u: u.display_name.lower())
+ return matches
+
async def _resolve_user_name(self, slack_user_id: str) -> SlackUser:
cached = self._user_cache.get(slack_user_id)
if cached:
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
index 2f33dd5ce..6a8501c11 100644
--- a/core/switch_core/bridges/collaboration/teams/adapter.py
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -23,6 +23,7 @@ from switch_core.bridges.collaboration.adapter import (
from switch_core.bridges.collaboration.models import (
BridgeConnectionConfig,
ChannelType,
+ DirectoryUser,
InboundAgentJoin,
InboundAppJoin,
InboundCommand,
@@ -538,7 +539,7 @@ class TeamsAdapter(CollaborationAdapter):
agent_name: str,
state: str,
*,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -573,7 +574,7 @@ class TeamsAdapter(CollaborationAdapter):
)
elif state == "awaiting-input":
ref = await self._ping_operator(
- channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ channel_id, agent_name, mention_handle, thread_root_id, deeplink_url
)
if ref is not None:
self._input_pings.setdefault(key, []).append(ref)
@@ -681,6 +682,34 @@ class TeamsAdapter(CollaborationAdapter):
self._channel_type[channel_id] = resolved
return resolved
+ async def search_directory_users(self, query: str) -> list[DirectoryUser]:
+ """Search the AAD directory for people to claim as an identity.
+
+ Teams identifies a message sender by AAD object id where one is
+ available, which is what Graph returns here, so a claim made from this
+ list matches what arrives on the inbound path.
+ """
+ if self._graph is None:
+ raise RuntimeError("Teams adapter not started")
+ term = query.strip()
+ if not term:
+ return []
+ users = await self._graph.search_users(query=term)
+ results = [
+ DirectoryUser(
+ external_user_id=str(user.get("id")),
+ username=str(user.get("userPrincipalName") or user.get("id") or ""),
+ display_name=str(
+ user.get("displayName") or user.get("userPrincipalName") or ""
+ ),
+ email=user.get("mail") or user.get("userPrincipalName") or None,
+ )
+ for user in users
+ if user.get("id")
+ ]
+ results.sort(key=lambda u: u.display_name.lower())
+ return results
+
async def channel_deeplink(self, external_channel_id: str) -> str | None:
"""`https://teams.microsoft.com/l/channel/...` opening the channel in the
Teams client. Built from the channel id, its team, and the tenant."""
diff --git a/core/switch_core/bridges/collaboration/teams/graph.py b/core/switch_core/bridges/collaboration/teams/graph.py
index cf81c070a..fd572407c 100644
--- a/core/switch_core/bridges/collaboration/teams/graph.py
+++ b/core/switch_core/bridges/collaboration/teams/graph.py
@@ -146,6 +146,32 @@ class GraphClient:
result: dict[str, Any] = resp.json()
return result
+ async def search_users(self, *, query: str, top: int = 25) -> list[dict[str, Any]]:
+ """Search the directory for people whose name, handle or mail matches.
+
+ Uses `$search` over the `users` collection, which needs the
+ ConsistencyLevel header. Returns the raw Graph user objects.
+ """
+ escaped = query.replace('"', '\\"')
+ headers = await self._headers()
+ headers["ConsistencyLevel"] = "eventual"
+ resp = await self._http.get(
+ f"{GRAPH_BASE}/users",
+ params={
+ "$search": f'"displayName:{escaped}" OR "mail:{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}"
+ )
+ payload: dict[str, Any] = resp.json()
+ users: list[dict[str, Any]] = payload.get("value", []) or []
+ return users
+
async def add_channel_member(
self, *, team_id: str, channel_id: str, user_aad_id: str
) -> None:
diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.py
index 924cf3325..b919829ad 100644
--- a/core/switch_core/bridges/collaboration/telegram/adapter.py
+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py
@@ -155,6 +155,7 @@ class TelegramAdapter(CollaborationAdapter):
"""
supports_channel_creation: ClassVar[bool] = False
+ supports_directory_search: ClassVar[bool] = False
renders_custom_url_schemes: ClassVar[bool] = False
def __init__(self, *, config: TelegramConnectionConfig) -> None:
@@ -862,7 +863,7 @@ class TelegramAdapter(CollaborationAdapter):
agent_name: str,
state: str,
*,
- notify_user: str | None,
+ mention_handle: str | None,
thread_root_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
@@ -899,7 +900,7 @@ class TelegramAdapter(CollaborationAdapter):
)
elif state == "awaiting-input":
ref = await self._ping_operator(
- channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ channel_id, agent_name, mention_handle, thread_root_id, deeplink_url
)
if ref is not None:
self._input_pings.setdefault(key, []).append(ref)
diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.py
index e8215d78d..5a0f8918d 100644
--- a/core/switch_core/clients/agent_client.py
+++ b/core/switch_core/clients/agent_client.py
@@ -5,7 +5,7 @@ import logging
import random
import re
from dataclasses import dataclass, field
-from typing import Literal
+from typing import Literal, NamedTuple
from nio import (
MatrixRoom,
@@ -148,15 +148,46 @@ _CONNECTED_NOT_LIVE_MESSAGE = (
# Posted (once, guarded by AUTO_REPLY_FLAG) when a sender tags this agent but
-# the agent's scoped addressing policy (CHOO-1585) does not permit that sender
-# to address it here. The message is demoted to unaddressed room chatter; this
-# reply is the sender's only feedback that the attempt was rejected.
+# the agent's scoped addressing policy does not permit that sender to address
+# it here. The message is demoted to unaddressed room chatter; this reply is
+# the sender's only feedback that the attempt was rejected.
_ADDRESSING_DENIED_MESSAGE = (
"You're not permitted to direct messages to me in this room — my operator "
"has restricted who can address me here."
)
+# The same refusal, for the case worth telling apart: the agent answers only to
+# its owner, and the sender's chat account is not linked to any Switch user, so
+# it cannot be recognised as the owner even if it is. Without this the owner
+# gets refused by their own agent with no idea why.
+_ADDRESSING_UNCLAIMED_MESSAGE = (
+ "I only take instructions from my owner, and this chat account isn't "
+ "linked to a Switch user yet — so I can't tell whether that's you. If it "
+ "is, link this account to your Switch user in Switch Console and try again."
+)
+
+
+class _SenderPrincipal(NamedTuple):
+ """Who a Matrix sender turned out to be, in the terms a policy is written
+ in. `user_ids` and `owner_user_id` are the two ways a symbolic subject
+ resolves, and are mutually exclusive: a human has claimants, an agent has
+ an owner."""
+
+ kind: SenderKind
+ id: str
+ user_ids: list[str]
+ owner_user_id: str | None
+
+
+class _AddressingDecision(NamedTuple):
+ """The outcome of checking a sender against an agent's addressing policy,
+ carrying the wording to reply with so the caller need not re-derive why."""
+
+ allowed: bool
+ refusal: str
+
+
# Shown to an agent addressed here while it holds a role in THIS room but the
# session that assumed the role has hopped away to other room(s) (the lease
# still routes here). `room_names` lists where that session is now active.
@@ -596,6 +627,9 @@ class AgentClient(ClientBase[ClientConfig]):
if not await addressed(self, event.args, meta.room_id):
return
+ if not await self._gate_command(room, event, meta):
+ return
+
handled = await self._handle_command(room, event)
if handled:
return
@@ -617,6 +651,53 @@ class AgentClient(ClientBase[ClientConfig]):
),
)
+ async def _command_targets_me_explicitly(self, args: str, room_id: str) -> bool:
+ """Whether the command names this agent, rather than reaching it as part
+ of a room-wide fan-out (`!reset-all-agents`, or a bare command with no
+ `@` token)."""
+ if "@" not in args:
+ return False
+ if self._args_tag_my_name(args):
+ return True
+ if await self._text_tags_my_alias(args, room_id):
+ return True
+ return await self._text_tags_my_role(args, room_id)
+
+ async def _gate_command(
+ self, room: MatrixRoom, event: CommandEvent, meta: RoomMeta
+ ) -> bool:
+ """Apply the addressing policy to a command aimed at this agent.
+
+ Commands drive the agent as surely as a message does — `!reset` wipes
+ its context, `!interrupt` stops it mid-task — so a sender who may not
+ address the agent may not command it either.
+
+ A refusal is posted only when the command named this agent. A room-wide
+ command (`!reset-all-agents`, or a bare one with no target) makes no
+ claim about this agent in particular, and answering every one of them
+ would flood a room holding several restricted agents; those are declined
+ quietly, with a warning in the log.
+ """
+ decision = await self._addressing_allowed(event.user_id, meta.room_id)
+ if decision.allowed:
+ return True
+ if await self._command_targets_me_explicitly(event.args, meta.room_id):
+ await self.reply_command(
+ room.room_id,
+ decision.refusal,
+ thread_root_id=event.thread_id,
+ )
+ else:
+ logger.warning(
+ "Command %s from %s declined for %s in room %s: sender may not "
+ "address this agent",
+ event.command,
+ event.user_id,
+ self.agent.name,
+ meta.room_id,
+ )
+ return False
+
# ── Command handling ──────────────────────────────────────────────────────
async def _handle_command(self, room: MatrixRoom, event: CommandEvent) -> bool:
@@ -752,23 +833,45 @@ class AgentClient(ClientBase[ClientConfig]):
# No role lease here, just sessions elsewhere: prefer the
# known-agent reply so the operator gets the paste-ready
# connect command alongside the "ask me there" alternative.
- return await self._unavailable_reply(
- meta.name, agent, other_room_names=names
- )
+ return await self._unavailable_reply(meta, agent, other_room_names=names)
# No live session in a distinct room. A session_addressable agent bound
# to THIS room but not live here was most likely launched without live
# channels: say a session is connected-but-not-live rather than imply
# there is none.
if connection_model == "session_addressable" and bound_here:
- return await self._unavailable_reply(
- meta.name, agent, connected_not_live=True
+ return await self._unavailable_reply(meta, agent, connected_not_live=True)
+ return await self._unavailable_reply(meta, agent)
+
+ async def owner_handle_in(self, agent: Agent, bridge_id: str | None) -> str | None:
+ """The agent owner's account on the platform this room is bridged to,
+ for @-mentioning them (CHOO-2137).
+
+ Resolved from who owns the agent and which account that person has
+ claimed on this bridge, rather than from a handle configured on the
+ agent. A handle only means anything on one platform — the same person
+ is one name on Slack and another on Telegram — so a single stored
+ string was at best right in one room and inert everywhere else.
+
+ None when the agent has no owner, the room has no bridge, or the owner
+ has claimed nothing on it. That is a message with no mention, not a
+ message withheld.
+ """
+ if agent.owner_id is None or bridge_id is None:
+ return None
+ async with self.session_factory() as session:
+ claimed = await self._external_user_store.get_by_user(
+ session, agent.owner_id
)
- return await self._unavailable_reply(meta.name, agent)
+ # Claiming is not exclusive and one person may hold several accounts on
+ # a bridge. Sorted so a second account cannot change who gets mentioned
+ # between one message and the next.
+ here = sorted(u.external_username for u in claimed if u.bridge_id == bridge_id)
+ return here[0] if here else None
async def _unavailable_reply(
self,
- room_name: str,
+ meta: RoomMeta,
agent: Agent,
other_room_names: list[str] | None = None,
connected_not_live: bool = False,
@@ -792,7 +895,8 @@ class AgentClient(ClientBase[ClientConfig]):
msg = spec.start_session_instructions(
options,
agent,
- room_name,
+ meta.name,
+ await self.owner_handle_in(agent, meta.bridge_id),
other_room_names=other_room_names,
connected_not_live=connected_not_live,
)
@@ -1025,68 +1129,113 @@ class AgentClient(ClientBase[ClientConfig]):
async def _resolve_sender_principal(
self, session: AsyncSession, matrix_user_id: str
- ) -> tuple[SenderKind, str] | None:
+ ) -> _SenderPrincipal | None:
"""Resolve a Matrix sender to an addressing principal.
Maps the sender's mxid to its Client, then to either an Agent (an
agent-to-agent attempt) or an ExternalUser (a human on a bridge).
Returns ``None`` when the sender has no such record — an
unresolvable identity that a restricted agent should not trust.
+
+ The two symbolic subjects resolve from different fields, and only one
+ applies to any given sender: ``user_ids`` are the Switch users who have
+ claimed a human's platform account (empty for an agent — an agent is
+ never its owner, even its owner's own), and ``owner_user_id`` is who
+ owns an agent sender (None for a human).
"""
client = await self.client_store.get_by_matrix_user_id(session, matrix_user_id)
if client is None:
return None
agent = await self._agent_store.get_by_client_id(session, client.id)
if agent is not None:
- return ("agent", agent.id)
+ return _SenderPrincipal("agent", agent.id, [], agent.owner_id)
external_user = await self._external_user_store.get_by_client_id(
session, client.id
)
if external_user is not None:
- return ("user", external_user.id)
+ claimants = await self._external_user_store.claimant_ids(
+ session, external_user.id
+ )
+ return _SenderPrincipal("user", external_user.id, claimants, None)
return None
- async def _addressing_allowed(self, event: RoomMessage, meta: RoomMeta) -> bool:
- """Whether the message's sender may address this agent, per the agent's
- scoped addressing policy (CHOO-1585).
-
- An agent with no policy is open to anyone (today's behaviour), so this
- returns True without a DB round-trip. With a policy set it is
- deny-by-default: an unresolvable sender is rejected (fail-closed).
+ async def _addressing_allowed(
+ self, matrix_sender: str, room_id: str
+ ) -> _AddressingDecision:
+ """Whether `matrix_sender` may address this agent in `room_id`, per the
+ agent's scoped addressing policy.
+
+ An agent with no policy is open to anyone, so this returns allowed
+ without a DB round-trip. With a policy set it is deny-by-default: an
+ unresolvable sender is rejected (fail-closed). A denial carries the
+ wording to send back, which differs when the sender looks like someone
+ whose platform identity simply has not been claimed yet.
"""
agent = await self._fresh_agent()
policy = parse_policy(agent.addressing_policy)
if policy.is_open():
- return True
+ return _AddressingDecision(allowed=True, refusal="")
async with self.session_factory() as session:
- principal = await self._resolve_sender_principal(session, event.sender)
- room = await self._room_store.get(session, meta.room_id)
+ principal = await self._resolve_sender_principal(session, matrix_sender)
+ room = await self._room_store.get(session, room_id)
if principal is None:
logger.warning(
"Addressing denied for %s: unresolvable sender %s in room %s",
self.agent.name,
- event.sender,
- meta.room_id,
+ matrix_sender,
+ room_id,
)
- return False
- sender_kind, sender_id = principal
+ return _AddressingDecision(
+ allowed=False, refusal=_ADDRESSING_DENIED_MESSAGE
+ )
+ sender_kind, sender_id, sender_user_ids = (
+ principal.kind,
+ principal.id,
+ principal.user_ids,
+ )
group_id = room.group_id if room is not None else None
allowed = can_address(
policy,
- room_id=meta.room_id,
+ room_id=room_id,
group_id=group_id,
sender_kind=sender_kind,
sender_id=sender_id,
+ sender_user_ids=sender_user_ids,
+ sender_owner_user_id=principal.owner_user_id,
+ owner_user_id=agent.owner_id,
)
- if not allowed:
+ if allowed:
+ return _AddressingDecision(allowed=True, refusal="")
+ unclaimed = (
+ sender_kind == "user"
+ and not sender_user_ids
+ and policy.requires_owner_identity()
+ )
+ if unclaimed:
+ logger.warning(
+ "Addressing denied for %s: sender %s in room %s has not been "
+ "claimed by any Switch user, so an owner-scoped rule cannot "
+ "match them — the owner may need to link this identity",
+ self.agent.name,
+ sender_id,
+ room_id,
+ )
+ else:
logger.warning(
"Addressing denied for %s: %s %s not permitted in room %s",
self.agent.name,
sender_kind,
sender_id,
- meta.room_id,
+ room_id,
)
- return allowed
+ return _AddressingDecision(
+ allowed=False,
+ refusal=(
+ _ADDRESSING_UNCLAIMED_MESSAGE
+ if unclaimed
+ else _ADDRESSING_DENIED_MESSAGE
+ ),
+ )
async def _gate_addressed(
self,
@@ -1107,14 +1256,15 @@ class AgentClient(ClientBase[ClientConfig]):
"""
if not is_addressed:
return False
- if await self._addressing_allowed(event, meta):
+ decision = await self._addressing_allowed(event.sender, meta.room_id)
+ if decision.allowed:
return True
triggered_by_auto_reply = bool(
event.source.get("content", {}).get(AUTO_REPLY_FLAG)
)
if not triggered_by_auto_reply:
handle = self._sender_handle(event)
- msg = _ADDRESSING_DENIED_MESSAGE
+ msg = decision.refusal
already_tagged = _mention_regex(handle).search(msg) is not None
body = msg if already_tagged else f"@{handle} {msg}"
await self.send_message(
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 14140ea58..304653762 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -568,6 +568,36 @@ class ExternalUser(Base):
)
+class ExternalUserClaim(Base):
+ """A Switch user's claim that a platform account is theirs (CHOO-2137).
+
+ Deliberately many-to-many rather than a single owner per account: an
+ exclusive claim would let whoever claimed first keep everyone else from
+ ever being recognised on that account, which is a quiet way to break
+ someone. Several Switch users may claim the same account, and an
+ owner-scoped rule is satisfied when the agent's owner is among them.
+
+ An account with no claim at all satisfies no owner rule — unclaimed is
+ not "trusted by default".
+ """
+
+ __tablename__ = "external_user_claims"
+
+ external_user_id: Mapped[str] = mapped_column(
+ Text,
+ ForeignKey("external_users.id", ondelete="CASCADE"),
+ primary_key=True,
+ )
+ user_id: Mapped[str] = mapped_column(
+ Text,
+ ForeignKey("users.id", ondelete="CASCADE"),
+ primary_key=True,
+ )
+ created_at: Mapped[str] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), nullable=False
+ )
+
+
# ── Agent Sessions ────────────────────────────────────────────────────────────
diff --git a/core/switch_core/db/stores/external_user_store.py b/core/switch_core/db/stores/external_user_store.py
index 6f7cd739c..321cffcbd 100644
--- a/core/switch_core/db/stores/external_user_store.py
+++ b/core/switch_core/db/stores/external_user_store.py
@@ -1,7 +1,10 @@
-from sqlalchemy import delete, select
+from typing import Any, cast
+
+from sqlalchemy import CursorResult, delete, select
+from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import ClientRoom, ExternalUser
+from switch_core.db.models import ClientRoom, ExternalUser, ExternalUserClaim
class ExternalUserStore:
@@ -63,6 +66,85 @@ class ExternalUserStore:
)
return list(result.scalars().all())
+ async def get_by_user(
+ self, session: AsyncSession, switch_user_id: str
+ ) -> list[ExternalUser]:
+ """Every platform identity claimed by this Switch user, across bridges."""
+ result = await session.execute(
+ select(ExternalUser)
+ .join(
+ ExternalUserClaim,
+ ExternalUserClaim.external_user_id == ExternalUser.id,
+ )
+ .where(ExternalUserClaim.user_id == switch_user_id)
+ )
+ return list(result.scalars().all())
+
+ async def claimant_ids(
+ self, session: AsyncSession, external_user_id: str
+ ) -> list[str]:
+ """The Switch users who have claimed this platform identity.
+
+ More than one is allowed and expected: see `ExternalUserClaim`.
+ """
+ result = await session.execute(
+ select(ExternalUserClaim.user_id).where(
+ ExternalUserClaim.external_user_id == external_user_id
+ )
+ )
+ return list(result.scalars().all())
+
+ async def claimant_ids_for(
+ self, session: AsyncSession, external_user_ids: list[str]
+ ) -> dict[str, list[str]]:
+ """`claimant_ids` for several identities at once, to avoid a query per
+ row when listing a bridge's users."""
+ if not external_user_ids:
+ return {}
+ result = await session.execute(
+ select(ExternalUserClaim.external_user_id, ExternalUserClaim.user_id).where(
+ ExternalUserClaim.external_user_id.in_(external_user_ids)
+ )
+ )
+ claims: dict[str, list[str]] = {}
+ for external_user_id, user_id in result.all():
+ claims.setdefault(external_user_id, []).append(user_id)
+ return claims
+
+ async def claim(
+ self, session: AsyncSession, external_user: ExternalUser, switch_user_id: str
+ ) -> None:
+ """Record that a Switch user considers this platform account theirs.
+
+ Idempotent, and never a conflict: claiming an account someone else has
+ also claimed is allowed by design. Left to the database rather than a
+ read-then-write, so a double-clicked button races to the same row
+ instead of to a primary-key violation.
+ """
+ await session.execute(
+ pg_insert(ExternalUserClaim)
+ .values(external_user_id=external_user.id, user_id=switch_user_id)
+ .on_conflict_do_nothing(index_elements=["external_user_id", "user_id"])
+ )
+ await session.flush()
+
+ async def release(
+ self, session: AsyncSession, external_user: ExternalUser, switch_user_id: str
+ ) -> bool:
+ """Drop one Switch user's claim, leaving anyone else's in place.
+
+ Returns whether there was a claim to drop, so a caller can tell a real
+ unlink from a no-op rather than reporting success either way.
+ """
+ result = await session.execute(
+ delete(ExternalUserClaim).where(
+ ExternalUserClaim.external_user_id == external_user.id,
+ ExternalUserClaim.user_id == switch_user_id,
+ )
+ )
+ await session.flush()
+ return cast("CursorResult[Any]", result).rowcount > 0
+
async def delete(self, session: AsyncSession, user_id: str) -> None:
user = await session.get(ExternalUser, user_id)
if user:
diff --git a/core/switch_core/events.py b/core/switch_core/events.py
index 0f9874db3..dcd46ac9d 100644
--- a/core/switch_core/events.py
+++ b/core/switch_core/events.py
@@ -143,7 +143,11 @@ class AgentRuntimeStateEvent(SwitchEvent):
room_id: str
# "working" | "awaiting-input" | "idle"
state: str
- notify_user: str | None = None
+ # The agent owner's account on the platform this room is bridged to, for
+ # @-mentioning them when the state is "awaiting-input" (CHOO-2137). None
+ # when the agent has no owner or that owner has claimed no account here —
+ # the bridge says so rather than posting a nudge that reaches nobody.
+ mention_handle: str | None = None
thread_id: str | None = None
# A `switchdash://session?…` deeplink the reporting client (Switch Console)
# built so the bridged message can link back to its session. Relayed as-is;
diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.py
index 5f0749c6c..36c8784bc 100644
--- a/core/switch_core/gateway/agents.py
+++ b/core/switch_core/gateway/agents.py
@@ -192,8 +192,8 @@ async def register_known_subagents(
endpoint: the signed-in user must own the parent. Each child's Switch name
is derived as ``<parent-name>.<subagent_name>``; a name clash fails the whole
batch up front rather than leaving a partial set registered. Subagents
- inherit the parent's `channels_enabled` / `repo_dir` / `notify_user` unless
- overridden in `options`.
+ inherit the parent's `channels_enabled` / `repo_dir` unless overridden in
+ `options`.
"""
spec = KNOWN_AGENTS.get(req.agent_type)
if spec is None:
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 94749a3a2..5229182c3 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -8,6 +8,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.config import SwitchConfig
from switch_core.db.models import User
+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
+from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.auth import (
get_current_user,
@@ -16,10 +18,17 @@ from switch_core.gateway.auth import (
set_session_cookie,
verify_password,
)
-from switch_core.gateway.dependencies import get_config, get_session, get_user_store
+from switch_core.gateway.dependencies import (
+ get_bridge_store,
+ get_config,
+ get_external_user_store,
+ get_session,
+ get_user_store,
+)
from switch_core.gateway.schemas import (
AuthConfigResponse,
CreateUserRequest,
+ LinkedIdentity,
LoginRequest,
ServerDeclaration,
SessionUserResponse,
@@ -135,6 +144,38 @@ async def me(
return _session_response(user)
[email protected]("/auth/me/identities")
+async def my_identities(
+ session: Annotated[AsyncSession, Depends(get_session)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> list[LinkedIdentity]:
+ """The messaging-app accounts this user has claimed (CHOO-2137).
+
+ An owner-only agent is only reachable by its owner over a bridge that
+ appears in this list, so Switch Console reads it to warn when an agent has
+ been sealed on a platform where its owner cannot be recognised.
+ """
+ identities = await external_user_store.get_by_user(session, user.id)
+ linked: list[LinkedIdentity] = []
+ for identity in identities:
+ bridge = await bridge_store.get(session, identity.bridge_id)
+ if bridge is None:
+ continue
+ linked.append(
+ LinkedIdentity(
+ id=identity.id,
+ bridge_id=identity.bridge_id,
+ bridge_display_name=bridge.display_name,
+ bridge_type=bridge.type,
+ external_user_id=identity.external_user_id,
+ external_username=identity.external_username,
+ )
+ )
+ return linked
+
+
@router.get("/users")
async def list_users(
session: Annotated[AsyncSession, Depends(get_session)],
diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py
index 1eb36ad6a..87c8cd542 100644
--- a/core/switch_core/gateway/collaborations.py
+++ b/core/switch_core/gateway/collaborations.py
@@ -1,7 +1,8 @@
from __future__ import annotations
import logging
-from typing import Annotated
+from collections.abc import Iterable
+from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException
from pydantic import ValidationError
@@ -10,11 +11,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
-from switch_core.bridges.collaboration.models import BridgeInstallLink
-from switch_core.db.models import CollaborationBridge, User
+from switch_core.bridges.collaboration.models import BridgeInstallLink, DirectoryUser
+from switch_core.db.models import CollaborationBridge, ExternalUser, User
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.room_store import RoomStore
+from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.auth import get_current_user, require_admin
from switch_core.gateway.dependencies import (
get_bridge_store,
@@ -23,13 +25,18 @@ from switch_core.gateway.dependencies import (
get_room_service,
get_room_store,
get_session,
+ get_user_store,
)
from switch_core.gateway.schemas import (
BridgeCreateRequest,
BridgeDetail,
BridgeTypeInfo,
BridgeUpdateRequest,
+ ClaimIdentityRequest,
+ DirectorySearchResponse,
+ DirectoryUserSummary,
ExternalUserSummary,
+ IdentityClaimant,
)
from switch_core.room_service import RoomService
@@ -118,6 +125,9 @@ async def _detail(
bridge.type
),
channel_creation_enabled=bridge.channel_creation_enabled,
+ directory_search_supported=collab_lifecycle.supports_directory_search(
+ bridge.type
+ ),
)
@@ -133,6 +143,7 @@ async def list_bridge_types(
key=t,
config_schema=collab_lifecycle.get_config_schema(t),
channel_creation_supported=collab_lifecycle.supports_channel_creation(t),
+ directory_search_supported=collab_lifecycle.supports_directory_search(t),
)
for t in collab_lifecycle.get_registered_types()
]
@@ -274,6 +285,7 @@ async def list_bridge_users(
session: Annotated[AsyncSession, Depends(get_session)],
bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
_user: Annotated[User, Depends(get_current_user)],
) -> list[ExternalUserSummary]:
bridge = await bridge_store.get(session, bridge_id)
@@ -281,17 +293,353 @@ async def list_bridge_users(
raise HTTPException(status_code=404, detail="Bridge not found")
users = await external_user_store.get_by_bridge(session, bridge_id)
+ claims = await external_user_store.claimant_ids_for(session, [u.id for u in users])
+ names = await _user_names(session, user_store, claims)
return [
ExternalUserSummary(
id=u.id,
bridge_id=u.bridge_id,
external_user_id=u.external_user_id,
external_username=u.external_username,
+ claimed_by=_claimants(claims.get(u.id, []), names),
)
for u in users
]
+async def _user_names(
+ session: AsyncSession,
+ user_store: UserStore,
+ claims: dict[str, list[str]],
+) -> dict[str, str]:
+ """Display names for every Switch user appearing in these claims.
+
+ Resolved in one pass over the user table rather than a lookup per
+ claimant: a bridge's user list is otherwise N+1 in the number of claims.
+ """
+ wanted = {uid for ids in claims.values() for uid in ids}
+ if not wanted:
+ return {}
+ return {u.id: u.name for u in await user_store.get_all(session) if u.id in wanted}
+
+
+def _claimants(user_ids: list[str], names: dict[str, str]) -> list[IdentityClaimant]:
+ def label(user_id: str) -> str:
+ return names.get(user_id) or user_id
+
+ return [
+ IdentityClaimant(user_id=user_id, user_name=label(user_id))
+ for user_id in sorted(user_ids, key=lambda uid: label(uid).lower())
+ ]
+
+
[email protected]("/{bridge_id}/directory")
+async def search_bridge_directory(
+ bridge_id: str,
+ query: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ collab_lifecycle: Annotated[
+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
+ ],
+ _user: Annotated[User, Depends(get_current_user)],
+) -> DirectorySearchResponse:
+ """Find someone on a messaging platform so they can be claimed.
+
+ Switch only records someone as an `ExternalUser` once they have spoken, so
+ a freshly connected workspace has nobody to pick from. Asking the platform
+ instead is what makes claiming an identity possible before you have ever
+ posted.
+
+ Platforms with no searchable directory — Telegram, where a bot can only see
+ who has spoken to it — fall back to exactly that: the accounts Switch has
+ already seen on this bridge. The response says which of the two answered, so
+ the caller can explain why the list is narrower rather than presenting a
+ partial answer as a whole one. It is a smaller list, not an error: refusing
+ outright would leave owner-only addressing unusable on those platforms even
+ for someone Switch knows perfectly well.
+ """
+ bridge = await bridge_store.get(session, bridge_id)
+ if bridge is None:
+ raise HTTPException(status_code=404, detail="Bridge not found")
+
+ adapter = collab_lifecycle.get_adapter(bridge_id)
+ if adapter is None:
+ raise HTTPException(
+ status_code=409,
+ detail="Bridge is not running — start it before searching its directory",
+ )
+
+ known = {
+ u.external_user_id: u
+ for u in await external_user_store.get_by_bridge(session, bridge_id)
+ }
+
+ source: Literal["directory", "known"] = "directory"
+ note: str | None = None
+ try:
+ found = await adapter.search_directory_users(query)
+ except NotImplementedError as e:
+ source = "known"
+ note = str(e)
+ found = _known_as_directory_users(known.values(), query)
+ except RuntimeError as e:
+ raise HTTPException(status_code=502, detail=str(e)) from e
+
+ claims = await external_user_store.claimant_ids_for(
+ session, [u.id for u in known.values()]
+ )
+ names = await _user_names(session, user_store, claims)
+ return DirectorySearchResponse(
+ source=source,
+ note=note,
+ users=[
+ DirectoryUserSummary(
+ external_user_id=person.external_user_id,
+ username=person.username,
+ display_name=person.display_name,
+ email=person.email,
+ known_external_user_id=(
+ known[person.external_user_id].id
+ if person.external_user_id in known
+ else None
+ ),
+ claimed_by=(
+ _claimants(claims.get(known[person.external_user_id].id, []), names)
+ if person.external_user_id in known
+ else []
+ ),
+ )
+ for person in found
+ ],
+ )
+
+
+def _known_as_directory_users(
+ known: Iterable[ExternalUser], query: str
+) -> list[DirectoryUser]:
+ """The accounts Switch has already seen, shaped like a directory answer.
+
+ Substring rather than prefix matching, because this list is what someone
+ falls back to when the platform cannot be searched, and being unable to
+ find yourself there is the end of the road. No email: an account is
+ recorded from a message, which carries no address.
+ """
+ needle = query.strip().casefold()
+ if not needle:
+ return []
+ return sorted(
+ (
+ DirectoryUser(
+ external_user_id=u.external_user_id,
+ username=u.external_username,
+ display_name=u.external_username,
+ email=None,
+ )
+ for u in known
+ if needle in u.external_username.casefold()
+ ),
+ key=lambda u: u.display_name.casefold(),
+ )
+
+
+async def _require_directory_account(
+ collab_lifecycle: CollaborationBridgeLifecycleService,
+ *,
+ bridge_id: str,
+ external_user_id: str,
+ username: str,
+) -> None:
+ """Raise unless the platform's directory really lists this account.
+
+ This is an existence check, not an ownership one — anyone may claim any
+ real account, deliberately. What it prevents is provisioning a Matrix
+ puppet for an id that came from nowhere: the claim body is user-supplied,
+ and the row it creates is permanent.
+
+ Only reached for an account Switch has never seen. One it has recorded is
+ already proof the account exists, and the caller claims it without asking
+ the platform — which is the only path open on a platform whose directory
+ cannot be searched.
+ """
+ adapter = collab_lifecycle.get_adapter(bridge_id)
+ if adapter is None:
+ raise HTTPException(
+ status_code=409,
+ detail="Bridge is not running — cannot look this account up",
+ )
+ try:
+ candidates = await adapter.search_directory_users(username)
+ except NotImplementedError as e:
+ raise HTTPException(
+ status_code=501,
+ detail=(
+ f"{e} — so this account cannot be linked before it has been "
+ "seen. Send one message in the workspace, then link it."
+ ),
+ ) from e
+ except RuntimeError as e:
+ raise HTTPException(status_code=502, detail=str(e)) from e
+
+ if not any(c.external_user_id == external_user_id for c in candidates):
+ raise HTTPException(
+ status_code=404,
+ detail=(
+ f"No account {username!r} with that id exists on this "
+ "workspace's directory"
+ ),
+ )
+
+
[email protected]("/{bridge_id}/identities")
+async def claim_bridge_identity(
+ bridge_id: str,
+ payload: ClaimIdentityRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ collab_lifecycle: Annotated[
+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
+ ],
+ user: Annotated[User, Depends(get_current_user)],
+) -> ExternalUserSummary:
+ """Claim a platform identity for a Switch user (CHOO-2137).
+
+ This is what makes owner-only addressing enforceable: until the person
+ behind a Slack or Mattermost account is known to be a particular Switch
+ user, an owner-scoped rule can never recognise them.
+
+ Claiming one for someone else is an admin action; claiming one for
+ yourself is not. Claims are **not exclusive** — several Switch users may
+ claim the same account, and each is then recognised as themselves on it.
+ An exclusive claim would let whoever got there first keep the real person
+ from ever being recognised by their own agents, so a second claim is
+ ordinary rather than a conflict.
+ """
+ bridge = await bridge_store.get(session, bridge_id)
+ if bridge is None:
+ raise HTTPException(status_code=404, detail="Bridge not found")
+
+ target_user_id = payload.user_id or user.id
+ if target_user_id != user.id and user.role != "admin":
+ raise HTTPException(
+ status_code=403,
+ detail="Only an admin may claim a messaging identity for another user",
+ )
+ if await user_store.get(session, target_user_id) is None:
+ raise HTTPException(status_code=404, detail="Switch user not found")
+
+ external_user = await external_user_store.get_by_external_id(
+ session, bridge_id, payload.external_user_id
+ )
+ if external_user is None:
+ # Nobody has seen this person speak yet, which is the normal case right
+ # after connecting a workspace. Provision the identity now rather than
+ # making them post something first — but only once the platform agrees
+ # the account exists. Provisioning mints a Matrix puppet, so taking the
+ # request's word for it would let any signed-in user conjure accounts
+ # for people who do not exist.
+ await _require_directory_account(
+ collab_lifecycle,
+ bridge_id=bridge_id,
+ external_user_id=payload.external_user_id,
+ username=payload.username,
+ )
+ bridge_core = collab_lifecycle.get(bridge_id)
+ if bridge_core is None:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "Bridge is not running — start it before claiming an "
+ "identity Switch has not seen yet"
+ ),
+ )
+ try:
+ external_user = await bridge_core.ensure_external_user(
+ external_user_id=payload.external_user_id,
+ external_username=payload.username,
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=409, detail=str(e)) from e
+ session.expire_all()
+ external_user = await external_user_store.get_by_external_id(
+ session, bridge_id, payload.external_user_id
+ )
+ if external_user is None:
+ raise HTTPException(
+ status_code=500,
+ detail="Identity was provisioned but could not be read back",
+ )
+
+ await external_user_store.claim(session, external_user, target_user_id)
+ await session.commit()
+
+ return await _identity_summary(
+ session, external_user_store, user_store, external_user
+ )
+
+
+async def _identity_summary(
+ session: AsyncSession,
+ external_user_store: ExternalUserStore,
+ user_store: UserStore,
+ external_user: ExternalUser,
+) -> ExternalUserSummary:
+ claims = {
+ external_user.id: await external_user_store.claimant_ids(
+ session, external_user.id
+ )
+ }
+ names = await _user_names(session, user_store, claims)
+ return ExternalUserSummary(
+ id=external_user.id,
+ bridge_id=external_user.bridge_id,
+ external_user_id=external_user.external_user_id,
+ external_username=external_user.external_username,
+ claimed_by=_claimants(claims[external_user.id], names),
+ )
+
+
[email protected]("/{bridge_id}/identities/{external_user_row_id}")
+async def release_bridge_identity(
+ bridge_id: str,
+ external_user_row_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ user: Annotated[User, Depends(get_current_user)],
+ user_id: str | None = None,
+) -> ExternalUserSummary:
+ """Drop a claim on a platform account — your own, or someone else's if you
+ are an admin. Anyone else's claim on the same account is left standing."""
+ external_user = await external_user_store.get(session, external_user_row_id)
+ if external_user is None or external_user.bridge_id != bridge_id:
+ raise HTTPException(status_code=404, detail="Identity not found")
+
+ target_user_id = user_id or user.id
+ if target_user_id != user.id and user.role != "admin":
+ raise HTTPException(
+ status_code=403,
+ detail="Only an admin may release another user's messaging identity",
+ )
+
+ released = await external_user_store.release(session, external_user, target_user_id)
+ if not released:
+ # Deleting nothing and reporting success would make a mistyped user id
+ # look like an unlink that worked.
+ raise HTTPException(
+ status_code=404,
+ detail="That user has no claim on this messaging account",
+ )
+ await session.commit()
+ return await _identity_summary(
+ session, external_user_store, user_store, external_user
+ )
+
+
@router.delete("/{bridge_id}")
async def delete_bridge(
bridge_id: str,
diff --git a/core/switch_core/gateway/known_agents.py b/core/switch_core/gateway/known_agents.py
index c9a944399..5e472be12 100644
--- a/core/switch_core/gateway/known_agents.py
+++ b/core/switch_core/gateway/known_agents.py
@@ -54,6 +54,7 @@ class KnownAgent(ABC):
options: KnownAgentOptions,
agent: Agent,
room_name: str,
+ owner_handle: str | None,
assume_role: str | None = None,
other_room_names: list[str] | None = None,
connected_not_live: bool = False,
@@ -63,6 +64,14 @@ class KnownAgent(ABC):
automatically when the agent is addressed but has no live session,
and on demand via `!run-cmd`.
+ `owner_handle` is the agent owner's account on the platform this room
+ is bridged to, @-mentioned so they are actually notified — None when
+ the agent has no owner or that owner has claimed no account there, in
+ which case the message still posts and simply says "my operator". It
+ is passed in rather than read from `options`: the right handle depends
+ on which platform the room is on, which the caller knows and a
+ per-agent setting could not.
+
When `assume_role` is set, the generated connect prompt also tells the
agent to assume that role on connect (e.g. `!run-cmd @agent @role`).
@@ -114,12 +123,6 @@ class ClaudeCodeOptions(KnownAgentOptions):
active. Leave None if the directory is unknown — a fallback guidance
message is shown instead."""
- notify_user: str | None = None
- """Username (on the room's bridged platform — Slack/Mattermost handle, or
- a Switch user name) to `@`-mention in the unavailable-session message so
- the operator gets a notification. Bare name, no leading `@`. Leave None
- to post without a mention."""
-
subagent_name: str | None = None
"""When set, this agent is a Claude Code *subagent* (a `.claude/agents/*.md`
definition) rather than a top-level Claude Code install. The value is the
@@ -131,7 +134,7 @@ class ClaudeCodeOptions(KnownAgentOptions):
session authenticates to Switch as the subagent, not the parent). Leave
None for ordinary top-level agents."""
- @field_validator("repo_dir", "notify_user", "subagent_name", mode="before")
+ @field_validator("repo_dir", "subagent_name", mode="before")
@classmethod
def _blank_string_to_none(cls, value: object) -> object:
# The gateway edit form submits an empty string when the user clears
@@ -194,6 +197,7 @@ class ClaudeCodeKnownAgent(KnownAgent):
options: KnownAgentOptions,
agent: Agent,
room_name: str,
+ owner_handle: str | None,
assume_role: str | None = None,
other_room_names: list[str] | None = None,
connected_not_live: bool = False,
@@ -253,11 +257,7 @@ class ClaudeCodeKnownAgent(KnownAgent):
# session_passive: reads asynchronously, so the operator must
# trigger a pull (from an open session or a fresh one). Mention the
# configured operator inline so they get pinged.
- operator = (
- f"my operator @{options.notify_user}"
- if options.notify_user
- else "my operator"
- )
+ operator = f"my operator @{owner_handle}" if owner_handle else "my operator"
return (
f"I read room messages asynchronously, not in real time — "
f"{operator} has to trigger me to pull the latest messages. "
@@ -270,7 +270,7 @@ class ClaudeCodeKnownAgent(KnownAgent):
# session_addressable: an optional @-mention so the operator gets a
# push from the bridged platform. The bridge re-parses these as
# addressed events.
- prefix = f"@{options.notify_user}\n\n" if options.notify_user else ""
+ prefix = f"@{owner_handle}\n\n" if owner_handle else ""
if connected_not_live:
opening = (
"I have a session connected to this room, but it isn't "
@@ -312,18 +312,13 @@ class CodexOptions(KnownAgentOptions):
command shown when the agent is addressed with no live session. None → a
`<codex-dir>` placeholder is shown instead."""
- notify_user: str | None = None
- """Username (on the room's bridged platform) to `@`-mention in the
- unavailable-session message so the operator gets a notification. Bare name,
- no leading `@`. None → post without a mention."""
-
# No `channels_enabled`: Switch Console sends it for every provider, but Codex
# has no connector channel of its own, so nothing here could act on it.
# `KnownAgentOptions` ignores unknown keys, so the shared registration path
# still works — and the schema-driven gateway form does not render a control
# that silently does nothing.
- @field_validator("repo_dir", "notify_user", mode="before")
+ @field_validator("repo_dir", mode="before")
@classmethod
def _blank_string_to_none(cls, value: object) -> object:
if isinstance(value, str) and value.strip() == "":
@@ -376,6 +371,7 @@ class CodexKnownAgent(KnownAgent):
options: KnownAgentOptions,
agent: Agent,
room_name: str,
+ owner_handle: str | None,
assume_role: str | None = None,
other_room_names: list[str] | None = None,
connected_not_live: bool = False,
@@ -394,7 +390,7 @@ class CodexKnownAgent(KnownAgent):
prompt += f" and assume the role {assume_role}"
cmd = f'cd "{dir_token}" && codex "{prompt}"'
- prefix = f"@{options.notify_user}\n\n" if options.notify_user else ""
+ prefix = f"@{owner_handle}\n\n" if owner_handle else ""
if connected_not_live:
opening = (
"I have a session connected to this room, but it isn't reporting "
@@ -436,15 +432,10 @@ class OpenCodeOptions(KnownAgentOptions):
switch room …"` command shown when the agent is addressed with no live
session. None → an `<opencode-dir>` placeholder is shown instead."""
- notify_user: str | None = None
- """Username (on the room's bridged platform) to `@`-mention in the
- unavailable-session message so the operator gets a notification. Bare name,
- no leading `@`. None → post without a mention."""
-
# No `channels_enabled`, for the same reason as Codex: Switch Console sends it
# for every provider, but OpenCode has no connector channel for it to act on.
- @field_validator("repo_dir", "notify_user", mode="before")
+ @field_validator("repo_dir", mode="before")
@classmethod
def _blank_string_to_none(cls, value: object) -> object:
if isinstance(value, str) and value.strip() == "":
@@ -502,6 +493,7 @@ class OpenCodeKnownAgent(KnownAgent):
options: KnownAgentOptions,
agent: Agent,
room_name: str,
+ owner_handle: str | None,
assume_role: str | None = None,
other_room_names: list[str] | None = None,
connected_not_live: bool = False,
@@ -520,7 +512,7 @@ class OpenCodeKnownAgent(KnownAgent):
prompt += f" and assume the role {assume_role}"
cmd = f'cd "{dir_token}" && opencode --prompt "{prompt}"'
- prefix = f"@{options.notify_user}\n\n" if options.notify_user else ""
+ prefix = f"@{owner_handle}\n\n" if owner_handle else ""
if connected_not_live:
opening = (
"I have a session connected to this room, but it isn't reporting "
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 628126ee0..fcae15397 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Literal
from pydantic import BaseModel, Field
@@ -231,6 +231,12 @@ class AgentSummary(BaseModel):
# they let the UI render an "edit options" form against the spec's schema.
known_agent_type: str | None = None
known_agent_options: dict[str, Any] | None = None
+ # Scoped agent-addressing permissions. null → open (anyone may address the
+ # agent); otherwise the allow-list that governs who can. On the summary,
+ # not just the detail, so a caller can tell which of someone's agents are
+ # owner-restricted without fetching each one — the console warns about
+ # exactly that, and per-agent reads would make it a request storm.
+ addressing_policy: AddressingPolicy | None = None
class AgentToolSummary(BaseModel):
@@ -287,9 +293,6 @@ class AgentDetail(AgentSummary):
rooms: list[AgentRoomMembership]
sessions: list[AgentSessionDetail]
children: list[AgentSummary]
- # Scoped agent-addressing permissions (CHOO-1585). null → open (anyone may
- # address the agent); otherwise the allow-list that governs who can.
- addressing_policy: AddressingPolicy | None = None
class UpdateAddressingPolicyRequest(BaseModel):
@@ -333,8 +336,8 @@ class RegisterKnownSubagentsRequest(BaseModel):
Session-authed counterpart of the agent-bridge `register-known-bulk`
endpoint: the caller must own the parent. `options` is the shared base
applied to every subagent (the per-subagent `subagent_name` is merged on
- top); when omitted, each subagent inherits the parent's `channels_enabled`,
- `repo_dir`, and `notify_user`.
+ top); when omitted, each subagent inherits the parent's `channels_enabled`
+ and `repo_dir`.
"""
agent_type: str
@@ -436,6 +439,12 @@ class BridgeDetail(BaseModel):
# switch you can flip, the second a disabled switch with a reason.
channel_creation_supported: bool = True
channel_creation_enabled: bool = True
+ # Whether the platform has a user directory Switch can search. False where
+ # the only people Switch can name are those who have spoken to it, which
+ # makes "pick yourself from the directory" an empty list on a connection
+ # nobody has used yet — a question worth not asking rather than asking
+ # badly.
+ directory_search_supported: bool = True
class BridgeUpdateRequest(BaseModel):
@@ -453,6 +462,10 @@ class BridgeTypeInfo(BaseModel):
# class, so it is answerable before any connection of this type exists —
# which is exactly when the registration form needs it.
channel_creation_supported: bool = True
+ # Likewise for its user directory: read here because the connect flow has
+ # to decide whether to offer the "which account is you" step for a
+ # connection that does not exist yet.
+ directory_search_supported: bool = True
class BridgeCreateRequest(BaseModel):
@@ -469,11 +482,80 @@ class BridgeCreateRequest(BaseModel):
channel_creation_enabled: bool = True
+class IdentityClaimant(BaseModel):
+ """A Switch user who says a platform account is theirs."""
+
+ user_id: str
+ user_name: str
+
+
class ExternalUserSummary(BaseModel):
id: str
bridge_id: str
external_user_id: str
external_username: str
+ # Everyone who has claimed this platform account. A list, not one user:
+ # claiming is not exclusive, so an account shared by several Switch users
+ # satisfies an owner rule for any of them.
+ claimed_by: list[IdentityClaimant] = []
+
+
+class DirectoryUserSummary(BaseModel):
+ """Someone found in the messaging platform's own directory, and whether
+ Switch already knows them."""
+
+ external_user_id: str
+ username: str
+ display_name: str
+ email: str | None = None
+ # Set when this person has already spoken on the bridge and so has an
+ # ExternalUser row; claiming reuses it rather than creating a duplicate.
+ known_external_user_id: str | None = None
+ # Who has already claimed this account. Shown so a picker can say the
+ # account is spoken for, not to stop anyone else claiming it too.
+ claimed_by: list[IdentityClaimant] = []
+
+
+class DirectorySearchResponse(BaseModel):
+ """Who a search turned up, and which of the two possible sources answered.
+
+ `source` is not decoration. A platform whose directory cannot be searched
+ falls back to the accounts Switch has already seen, which is a genuinely
+ narrower answer: someone who has never spoken is absent from it, and a
+ caller that presented it as a whole-workspace search would be telling the
+ user that person does not exist. `note` carries the platform's own
+ explanation, for showing alongside the results rather than instead of them.
+ """
+
+ source: Literal["directory", "known"]
+ note: str | None = None
+ users: list[DirectoryUserSummary] = []
+
+
+class ClaimIdentityRequest(BaseModel):
+ """Claim a platform identity for a Switch user.
+
+ `external_user_id` is the platform's own id (a Slack `U…`, a Mattermost
+ user id), not an `ExternalUser.id` — that row may not exist yet for
+ someone who has never posted, and is created on demand.
+ """
+
+ external_user_id: str
+ username: str
+ # Omitted means "claim it for me"; only an admin may claim on behalf of
+ # someone else.
+ user_id: str | None = None
+
+
+class LinkedIdentity(BaseModel):
+ """One platform identity claimed by a Switch user."""
+
+ id: str
+ bridge_id: str
+ bridge_display_name: str
+ bridge_type: str
+ external_user_id: str
+ external_username: str
# ── Server-Side Connectors ──────────────────────────────────────────────────
diff --git a/core/switch_core/gateway/subagent_registration.py b/core/switch_core/gateway/subagent_registration.py
index c41231274..de8229736 100644
--- a/core/switch_core/gateway/subagent_registration.py
+++ b/core/switch_core/gateway/subagent_registration.py
@@ -12,7 +12,7 @@ from typing import Any
from pydantic import BaseModel
# Parent operational options a subagent inherits unless the caller overrides them.
-_INHERITED_OPTION_KEYS = ("channels_enabled", "repo_dir", "notify_user")
+_INHERITED_OPTION_KEYS = ("channels_enabled", "repo_dir")
class DerivedSubagent(BaseModel):
diff --git a/core/switch_core/migrations/versions/c2137e4a9b7d_link_external_users_to_switch_users.py b/core/switch_core/migrations/versions/c2137e4a9b7d_link_external_users_to_switch_users.py
new file mode 100644
index 000000000..e586e66cc
--- /dev/null
+++ b/core/switch_core/migrations/versions/c2137e4a9b7d_link_external_users_to_switch_users.py
@@ -0,0 +1,47 @@
+"""link external users to switch users (CHOO-2137)
+
+Revision ID: c2137e4a9b7d
+Revises: d1a7c3e58b40
+Create Date: 2026-08-14 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "c2137e4a9b7d"
+down_revision: str | None = "d1a7c3e58b40"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "external_user_claims",
+ sa.Column("external_user_id", sa.Text(), nullable=False),
+ sa.Column("user_id", sa.Text(), nullable=False),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.func.now(),
+ nullable=False,
+ ),
+ sa.ForeignKeyConstraint(
+ ["external_user_id"], ["external_users.id"], ondelete="CASCADE"
+ ),
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
+ sa.PrimaryKeyConstraint("external_user_id", "user_id"),
+ )
+ op.create_index(
+ "ix_external_user_claims_user_id",
+ "external_user_claims",
+ ["user_id"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_external_user_claims_user_id", table_name="external_user_claims")
+ op.drop_table("external_user_claims")
diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.py
index 9eaff31df..6d5af63f1 100644
--- a/core/tests/integration/conftest.py
+++ b/core/tests/integration/conftest.py
@@ -278,6 +278,10 @@ class Harness:
integration_profile=_PROFILE,
owner_id=self.owner_id,
overwrite=True,
+ # Harness agents address each other; the owner-only default would
+ # block every agent-to-agent message. Tests that exercise scoped
+ # addressing set a policy explicitly.
+ owner_only=False,
)
self._registered.append(result.agent_id)
return result
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
index 5b6350ee1..2e7438c49 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
@@ -194,7 +194,6 @@ class TestUpdateAgentDetail:
assert detail.known_agent_options["repo_dir"] == "/work/dir"
# ...and the untouched fields keep their prior values (partial merge).
assert detail.known_agent_options["channels_enabled"] is True
- assert detail.known_agent_options["notify_user"] is None
async def test_options_rebuild_integration_profile(
self, session_factory: async_sessionmaker[AsyncSession]
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py
index dbdda7c20..1c7118e91 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py
@@ -153,6 +153,56 @@ class TestDelegateAddressingGate:
result = await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")
assert result.task_id
+ async def test_the_owners_own_manager_may_still_dispatch(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The case the default has to survive: one person's manager agent
+ # handing work to their worker. Under strict owner-only this raised,
+ # which is a working setup broken by a privacy default.
+ svc = _service(session_factory)
+ async with session_factory() as session:
+ owner = await _make_user(session, "owner")
+ manager = await _make_agent(session, "manager", owner_id=owner.id)
+ worker = await _make_agent(
+ session,
+ "worker",
+ owner_id=owner.id,
+ addressing_policy={
+ "rules": [{"users": [], "agents": [], "owner_agents": True}]
+ },
+ )
+ room = await _make_room(session, svc.room_store, [manager.id, worker.id])
+ await session.commit()
+ mgr_id, worker_id, room_id = manager.id, worker.id, room.id
+
+ result = await svc.delegate_task(mgr_id, room_id, worker_id, "do it", "details")
+ assert result.task_id
+
+ async def test_but_not_somebody_elses_manager(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Same rule, different owner. "My agents" has to mean mine, or the
+ # setting is just "any agent" with a friendlier name.
+ svc = _service(session_factory)
+ async with session_factory() as session:
+ owner = await _make_user(session, "owner")
+ other = await _make_user(session, "other")
+ manager = await _make_agent(session, "their-manager", owner_id=other.id)
+ worker = await _make_agent(
+ session,
+ "worker",
+ owner_id=owner.id,
+ addressing_policy={
+ "rules": [{"users": [], "agents": [], "owner_agents": True}]
+ },
+ )
+ room = await _make_room(session, svc.room_store, [manager.id, worker.id])
+ await session.commit()
+ mgr_id, worker_id, room_id = manager.id, worker.id, room.id
+
+ with pytest.raises(PermissionError, match="not permitted to address"):
+ await svc.delegate_task(mgr_id, room_id, worker_id, "do it", "details")
+
async def test_open_policy_allows_delegation(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
new file mode 100644
index 000000000..d28006b33
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
@@ -0,0 +1,269 @@
+"""Registration sets the new agent's default addressing policy (CHOO-2137)."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.addressing import parse_policy
+from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.bridges.agent.protocol.types import (
+ IntegrationProfile,
+ TaskProtocolConfig,
+)
+from switch_core.db.models import Client, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.api_key_store import ApiKeyStore
+
+_PROFILE = IntegrationProfile(
+ connection_model="session_passive",
+ message_exchange=True,
+ pre_invocation_mediation=[],
+ post_invocation_mediation=[],
+ event_reporting=[],
+ task_protocol=TaskProtocolConfig(can_delegate=False, can_accept=False),
+)
+
+
+class _FakeClientLifecycle:
+ """Creates the Client row `_create_agent` attaches the Agent to; the real
+ lifecycle also starts a Matrix sync loop, which a policy test does not need."""
+
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
+ self._session_factory = session_factory
+ self.started: list[str] = []
+
+ async def create_client(self, *, client_type: str, display_name: str) -> Client:
+ async with self._session_factory() as session:
+ client = Client(
+ matrix_user_id=f"@{display_name}:test",
+ display_name=display_name,
+ type=client_type,
+ password="x",
+ )
+ session.add(client)
+ await session.commit()
+ return client
+
+ def start_client(self, client: Client) -> None:
+ self.started.append(client.id)
+
+
+class _NoBridges:
+ def all_bridges(self) -> list[object]:
+ return []
+
+
+def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:
+ svc = object.__new__(ProtocolService)
+ svc.session_factory = session_factory # type: ignore[attr-defined]
+ svc.agent_store = AgentStore() # type: ignore[attr-defined]
+ svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]
+ svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
+ svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
+ svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]
+ return svc
+
+
+async def _make_owner(session_factory: async_sessionmaker[AsyncSession]) -> str:
+ async with session_factory() as session:
+ user = User(name="owner", email="owner@test", role="user", password_hash="x")
+ session.add(user)
+ await session.commit()
+ return user.id
+
+
+async def _register(
+ svc: ProtocolService, name: str, owner_id: str, **kwargs: object
+) -> str:
+ result = await svc.register_agent(
+ name=name,
+ description=f"{name} desc",
+ connector_type="test",
+ integration_profile=_PROFILE,
+ owner_id=owner_id,
+ **kwargs, # type: ignore[arg-type]
+ )
+ return result.agent_id
+
+
+async def _policy_of(
+ svc: ProtocolService,
+ session_factory: async_sessionmaker[AsyncSession],
+ agent_id: str,
+) -> dict | None:
+ async with session_factory() as session:
+ agent = await svc.agent_store.get(session, agent_id)
+ assert agent is not None
+ return agent.addressing_policy
+
+
+class TestRegistrationDefaultPolicy:
+ async def test_new_agent_is_owner_only(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = _service(session_factory)
+ owner_id = await _make_owner(session_factory)
+ agent_id = await _register(svc, "fresh", owner_id)
+
+ raw = await _policy_of(svc, session_factory, agent_id)
+ policy = parse_policy(raw)
+ assert policy.is_open() is False
+ assert policy.requires_owner_identity() is True
+ # The owner gets in from anywhere; nobody else does.
+ assert (
+ policy.allows(
+ room_id="any-room",
+ group_id=None,
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=[owner_id],
+ sender_owner_user_id=None,
+ owner_user_id=owner_id,
+ )
+ is True
+ )
+ assert (
+ policy.allows(
+ room_id="any-room",
+ group_id=None,
+ sender_kind="agent",
+ sender_id="other-agent",
+ sender_user_ids=[],
+ sender_owner_user_id=None,
+ owner_user_id=owner_id,
+ )
+ is False
+ )
+
+ async def test_addressable_by_agent_ids_are_admitted(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = _service(session_factory)
+ owner_id = await _make_owner(session_factory)
+ agent_id = await _register(
+ svc, "dispatched", owner_id, addressable_by_agent_ids=["dispatcher"]
+ )
+
+ policy = parse_policy(await _policy_of(svc, session_factory, agent_id))
+ assert (
+ policy.allows(
+ room_id="any-room",
+ group_id=None,
+ sender_kind="agent",
+ sender_id="dispatcher",
+ sender_user_ids=[],
+ sender_owner_user_id=None,
+ owner_user_id=owner_id,
+ )
+ is True
+ )
+ assert (
+ policy.allows(
+ room_id="any-room",
+ group_id=None,
+ sender_kind="agent",
+ sender_id="stranger",
+ sender_user_ids=[],
+ sender_owner_user_id=None,
+ owner_user_id=owner_id,
+ )
+ is False
+ )
+
+ async def test_owner_only_false_leaves_the_agent_open(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # A service the deployment offers everyone (a server-side connector
+ # agent) is owned by someone only in the bookkeeping sense.
+ svc = _service(session_factory)
+ owner_id = await _make_owner(session_factory)
+ agent_id = await _register(svc, "shared", owner_id, owner_only=False)
+
+ raw = await _policy_of(svc, session_factory, agent_id)
+ assert raw is None
+ assert parse_policy(raw).is_open() is True
+
+ async def test_reregistration_leaves_the_policy_alone(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = _service(session_factory)
+ owner_id = await _make_owner(session_factory)
+ agent_id = await _register(svc, "kept", owner_id, owner_only=False)
+
+ async with session_factory() as session:
+ await svc.agent_store.update(
+ session,
+ agent_id,
+ addressing_policy={"rules": [{"users": ["ext-3"], "agents": []}]},
+ )
+ await session.commit()
+
+ again = await _register(svc, "kept", owner_id, overwrite=True)
+ assert again == agent_id
+ raw = await _policy_of(svc, session_factory, agent_id)
+ assert raw == {"rules": [{"users": ["ext-3"], "agents": []}]}
+
+
+class TestRegisterWithTokenPassesThrough:
+ async def test_token_registration_defaults_to_owner_only(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = _service(session_factory)
+ owner_id = await _make_owner(session_factory)
+ captured: dict[str, object] = {}
+
+ async def _register_agent(**kwargs: object) -> object:
+ captured.update(kwargs)
+ return SimpleNamespace(agent_id="a1", api_key="k", oauth_client_id=None)
+
+ svc.register_agent = _register_agent # type: ignore[assignment, method-assign]
+ svc.api_key_store = SimpleNamespace( # type: ignore[assignment]
+ get_by_hash=_stub_key(owner_id)
+ )
+
+ await svc.register_agent_with_token(
+ registration_token="tok",
+ name="tokenised",
+ description="d",
+ connector_type="test",
+ integration_profile=_PROFILE,
+ )
+ assert captured["owner_only"] is True
+ assert captured["addressable_by_agent_ids"] is None
+
+ async def test_token_registration_forwards_the_overrides(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = _service(session_factory)
+ owner_id = await _make_owner(session_factory)
+ captured: dict[str, object] = {}
+
+ async def _register_agent(**kwargs: object) -> object:
+ captured.update(kwargs)
+ return SimpleNamespace(agent_id="a1", api_key="k", oauth_client_id=None)
+
+ svc.register_agent = _register_agent # type: ignore[assignment, method-assign]
+ svc.api_key_store = SimpleNamespace( # type: ignore[assignment]
+ get_by_hash=_stub_key(owner_id)
+ )
+
+ await svc.register_agent_with_token(
+ registration_token="tok",
+ name="tokenised",
+ description="d",
+ connector_type="test",
+ integration_profile=_PROFILE,
+ owner_only=False,
+ addressable_by_agent_ids=["dispatcher"],
+ )
+ assert captured["owner_only"] is False
+ assert captured["addressable_by_agent_ids"] == ["dispatcher"]
+
+
+def _stub_key(owner_id: str): # type: ignore[no-untyped-def]
+ async def _get_by_key(_session: AsyncSession, _token: str) -> object:
+ return SimpleNamespace(user_id=owner_id, type="registration")
+
+ return _get_by_key
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py
index c73c99632..37addab8d 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py
@@ -72,11 +72,13 @@ def _service(
async def _an_agent(*_a: Any, **_kw: Any) -> Any:
- return SimpleNamespace(id=AGENT, name="agent", integration_profile={}, metadata_={})
+ return SimpleNamespace(
+ id=AGENT, name="agent", integration_profile={}, metadata_={}, owner_id=None
+ )
async def _a_room(*_a: Any, **_kw: Any) -> Any:
- return SimpleNamespace(id=ROOM, matrix_room_id="!m:server")
+ return SimpleNamespace(id=ROOM, matrix_room_id="!m:server", bridge_id=None)
def _session_factory() -> Any:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py
index 7d4660a7e..368350465 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py
@@ -44,8 +44,29 @@ class _FakeAgentStore:
return self._agents.get(agent_id)
-def _participant(name: str, ptype: str, status: AgentStatus | None) -> SimpleNamespace:
- return SimpleNamespace(name=name, type=ptype, status=status)
+class _FakeRoomStore:
+ def __init__(self, group_id: str | None) -> None:
+ self._group_id = group_id
+
+ async def get(self, _session: Any, _room_id: str) -> Any:
+ return SimpleNamespace(group_id=self._group_id)
+
+
+def _participant(
+ name: str, ptype: str, status: AgentStatus | None, *, agent_id: str | None = None
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=agent_id if agent_id is not None else f"a-{name}",
+ name=name,
+ type=ptype,
+ status=status,
+ )
+
+
+def _agent(name: str, addressing_policy: dict | None = None) -> SimpleNamespace:
+ return SimpleNamespace(
+ name=name, addressing_policy=addressing_policy, owner_id="owner-1"
+ )
def _build_service(
@@ -54,6 +75,7 @@ def _build_service(
roles: list[Any],
holders: dict[str, list[str]],
agents: dict[str, Any],
+ group_id: str | None = None,
) -> tuple[ProtocolService, list[str]]:
sent_bodies: list[str] = []
@@ -64,6 +86,7 @@ def _build_service(
svc.session_factory = _session_factory # type: ignore[assignment]
svc.room_role_store = _FakeRoomRoleStore(roles, holders) # type: ignore[assignment]
svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]
+ svc.room_store = _FakeRoomStore(group_id) # type: ignore[assignment]
async def _list_participants(_room_id: str) -> list[Any]:
return list(participants)
@@ -89,10 +112,7 @@ class TestSendTargetedRoles:
],
roles=[role],
holders={"r-mgr": ["a-alice", "a-bob"]},
- agents={
- "a-alice": SimpleNamespace(name="alice"),
- "a-bob": SimpleNamespace(name="bob"),
- },
+ agents={"a-alice": _agent("alice"), "a-bob": _agent("bob")},
)
result = await svc.send_targeted_message(
@@ -116,7 +136,7 @@ class TestSendTargetedRoles:
],
roles=[role],
holders={"r-mgr": ["a-alice"]},
- agents={"a-alice": SimpleNamespace(name="alice")},
+ agents={"a-alice": _agent("alice"), "a-carol": _agent("carol")},
)
result = await svc.send_targeted_message(
@@ -163,3 +183,140 @@ class TestSendTargetedRoles:
assert bodies == ["@manager anyone?"]
assert result.target_statuses == {}
+
+
+class TestSendTargetedAddressingGate:
+ """Targeting an agent whose policy does not admit you is reported, not
+ refused (CHOO-2137).
+
+ The message goes to the room and the target declines it there, the same as
+ an `@name` in an ordinary message — so the refusal is on the record in the
+ room rather than only in the sender's account of it. What the sender gets
+ back is `not_permitted` in place of a reachability status, because "live"
+ for an agent that is about to say no is the reading that sends someone
+ looking for a bug. Delegation still raises; a task is a row someone is
+ expected to work.
+ """
+
+ def _restricted(self) -> dict:
+ """Admits one specific other agent, so `sender` is not permitted."""
+ return {"rules": [{"agents": ["someone-else"], "users": []}]}
+
+ async def test_a_restricted_target_still_receives_the_message(self) -> None:
+ svc, bodies = _build_service(
+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],
+ roles=[],
+ holders={},
+ agents={"a-alice": _agent("alice", self._restricted())},
+ )
+
+ result = await svc.send_targeted_message("sender", "room-1", ["alice"], "ping")
+
+ assert bodies == ["@alice ping"]
+ assert result.event_id
+
+ async def test_and_the_sender_is_told_it_will_be_declined(self) -> None:
+ # Without this the sender reads "live" and has no way to tell a refusal
+ # apart from an agent that simply had nothing to say.
+ svc, _bodies = _build_service(
+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],
+ roles=[],
+ holders={},
+ agents={"a-alice": _agent("alice", self._restricted())},
+ )
+
+ result = await svc.send_targeted_message("sender", "room-1", ["alice"], "ping")
+
+ assert result.target_statuses == {"alice": AgentStatus.NOT_PERMITTED}
+
+ async def test_permitted_name_target_posts(self) -> None:
+ svc, bodies = _build_service(
+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],
+ roles=[],
+ holders={},
+ agents={
+ "a-alice": _agent(
+ "alice", {"rules": [{"agents": ["sender"], "users": []}]}
+ )
+ },
+ )
+
+ result = await svc.send_targeted_message("sender", "room-1", ["alice"], "ping")
+ assert bodies == ["@alice ping"]
+ assert result.target_statuses == {"alice": AgentStatus.LIVE}
+
+ async def test_owner_rule_does_not_admit_an_agent_sender(self) -> None:
+ # The sender agent shares alice's owner, but an owner rule admits the
+ # human, not the agents acting for them.
+ svc, bodies = _build_service(
+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],
+ roles=[],
+ holders={},
+ agents={
+ "a-alice": _agent(
+ "alice",
+ {"rules": [{"agents": [], "users": [], "owner": True}]},
+ )
+ },
+ )
+
+ result = await svc.send_targeted_message("sender", "room-1", ["alice"], "ping")
+ assert result.target_statuses == {"alice": AgentStatus.NOT_PERMITTED}
+
+ async def test_a_restricted_role_holder_is_reported_too(self) -> None:
+ # Role targets are resolved to their live holders and checked the same
+ # way, so a role mention cannot be used to make the answer look better
+ # than naming the agent would.
+ role = SimpleNamespace(id="r-mgr", name="manager")
+ svc, bodies = _build_service(
+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],
+ roles=[role],
+ holders={"r-mgr": ["a-alice"]},
+ agents={"a-alice": _agent("alice", self._restricted())},
+ )
+
+ result = await svc.send_targeted_message(
+ "sender", "room-1", [], "standup", target_roles=["manager"]
+ )
+
+ assert bodies == ["@manager standup"]
+ assert result.target_statuses == {"alice": AgentStatus.NOT_PERMITTED}
+
+ async def test_user_target_is_not_gated(self) -> None:
+ # The policy governs addressing an AGENT; a human target is the
+ # bridge's business.
+ svc, bodies = _build_service(
+ participants=[_participant("dana", "user", None)],
+ roles=[],
+ holders={},
+ agents={},
+ )
+
+ await svc.send_targeted_message("sender", "room-1", ["dana"], "ping")
+ assert bodies == ["@dana ping"]
+
+ async def test_group_scoped_policy_uses_the_rooms_group(self) -> None:
+ policy = {"rules": [{"room_groups": ["g1"], "agents": ["sender"], "users": []}]}
+ allowed, _bodies = _build_service(
+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],
+ roles=[],
+ holders={},
+ agents={"a-alice": _agent("alice", policy)},
+ group_id="g1",
+ )
+ in_group = await allowed.send_targeted_message(
+ "sender", "room-1", ["alice"], "ping"
+ )
+ assert in_group.target_statuses == {"alice": AgentStatus.LIVE}
+
+ denied, _denied_bodies = _build_service(
+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],
+ roles=[],
+ holders={},
+ agents={"a-alice": _agent("alice", policy)},
+ group_id="g2",
+ )
+ out_of_group = await denied.send_targeted_message(
+ "sender", "room-1", ["alice"], "ping"
+ )
+ assert out_of_group.target_statuses == {"alice": AgentStatus.NOT_PERMITTED}
diff --git a/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py b/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py
index d7337bedb..5822460ee 100644
--- a/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py
+++ b/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py
@@ -191,7 +191,7 @@ def _fake_client(*, role_exists: bool) -> SimpleNamespace:
yield object()
async def _resolve_room_meta(_matrix_room_id: str): # type: ignore[no-untyped-def]
- return SimpleNamespace(room_id="room-1", name="Feature Room")
+ return SimpleNamespace(room_id="room-1", name="Feature Room", bridge_id=None)
async def _agent_get(_session, _agent_id): # type: ignore[no-untyped-def]
return None # fall back to client.agent
@@ -202,6 +202,10 @@ def _fake_client(*, role_exists: bool) -> SimpleNamespace:
async def _send_message(_room_id, body, **_kw): # type: ignore[no-untyped-def]
sent.append(body)
+ async def _owner_handle_in(_agent, _bridge_id): # type: ignore[no-untyped-def]
+ # No linked owner: these cover the connect command, not the mention.
+ return None
+
client = SimpleNamespace(
agent=SimpleNamespace(id="a1", name="cc-bug-fixing"),
session_factory=_session_factory,
@@ -210,6 +214,7 @@ def _fake_client(*, role_exists: bool) -> SimpleNamespace:
_room_role_store=SimpleNamespace(get_role=_get_role),
send_message=_send_message,
reply_command=_send_message,
+ owner_handle_in=_owner_handle_in,
sent=sent,
)
return client
@@ -222,6 +227,7 @@ def _patch_known_agent(monkeypatch: pytest.MonkeyPatch) -> None:
_options: Any,
_agent: Any,
room_name: str,
+ _owner_handle: str | None,
assume_role: str | None = None,
) -> str:
prompt = f"connect to switch room {room_name}"
diff --git a/core/tests/switch_core/bridges/collaboration/test_directory_search_capability.py b/core/tests/switch_core/bridges/collaboration/test_directory_search_capability.py
new file mode 100644
index 000000000..9e0e3a4aa
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_directory_search_capability.py
@@ -0,0 +1,72 @@
+"""Whether a platform's user directory can be searched, declared (CHOO-2137).
+
+Switch asks this before a connection exists, to decide whether to offer someone
+the "which account is you" step while connecting a messaging app. On a platform
+with no directory the honest answer on a fresh connection is always "nobody" —
+a Telegram bot can only name people who have spoken to it — so the step is a
+form that cannot be filled in rather than a search that comes back empty.
+
+The flag is a claim about behaviour, and a claim can drift from the behaviour it
+describes. These hold the two together.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.discord.adapter import DiscordAdapter
+from switch_core.bridges.collaboration.mattermost.adapter import MattermostAdapter
+from switch_core.bridges.collaboration.slack.adapter import SlackAdapter
+from switch_core.bridges.collaboration.teams.adapter import TeamsAdapter
+from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapter
+
+ADAPTERS = [
+ DiscordAdapter,
+ MattermostAdapter,
+ SlackAdapter,
+ TeamsAdapter,
+ TelegramAdapter,
+]
+
+
[email protected]("adapter_cls", ADAPTERS, ids=lambda c: c.__name__)
+async def test_the_flag_agrees_with_what_the_adapter_actually_does(
+ adapter_cls: type[CollaborationAdapter],
+) -> None:
+ """A platform declaring a directory must implement the search, and one
+ declaring none must not — otherwise the flag is decoration and the UI is
+ deciding on a claim nothing keeps true.
+
+ Only the *refusal* is exercised: an adapter that implements the search
+ reaches its platform, which is not this test's business. Reaching a
+ network call is itself the evidence that it was implemented.
+ """
+ implements = (
+ adapter_cls.search_directory_users
+ is not CollaborationAdapter.search_directory_users
+ )
+
+ assert adapter_cls.supports_directory_search == implements, (
+ f"{adapter_cls.__name__} declares "
+ f"supports_directory_search={adapter_cls.supports_directory_search} "
+ f"but {'does not implement' if not implements else 'implements'} "
+ "search_directory_users"
+ )
+
+
+async def test_a_platform_without_one_refuses_rather_than_answering_emptily() -> None:
+ # The refusal is what the directory fallback keys on; an empty list would
+ # read as "this workspace has nobody in it".
+ adapter = TelegramAdapter.__new__(TelegramAdapter)
+
+ with pytest.raises(NotImplementedError):
+ await adapter.search_directory_users("lou")
+
+
+def test_telegram_is_the_one_that_cannot_be_searched() -> None:
+ # Pinned rather than inferred: if a new platform arrives with no directory
+ # this list should be updated deliberately, by someone who checked.
+ unsearchable = {c.__name__ for c in ADAPTERS if not c.supports_directory_search}
+
+ assert unsearchable == {"TelegramAdapter"}
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
index c9aa94550..3d353f48f 100644
--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
@@ -888,7 +888,7 @@ def test_runtime_state_working_posts_persistent_indicator() -> None:
str(CHANNEL_ID),
"my-agent",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -910,7 +910,7 @@ def test_runtime_state_detail_edits_message_in_place() -> None:
str(CHANNEL_ID),
"my-agent",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -919,7 +919,7 @@ def test_runtime_state_detail_edits_message_in_place() -> None:
str(CHANNEL_ID),
"my-agent",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
detail="Editing adapter.py",
)
@@ -943,13 +943,17 @@ def test_runtime_state_idle_clears_working_message() -> None:
str(CHANNEL_ID),
"my-agent",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
_run(
adapter.apply_runtime_state(
- str(CHANNEL_ID), "my-agent", "idle", notify_user=None, thread_root_id=None
+ str(CHANNEL_ID),
+ "my-agent",
+ "idle",
+ mention_handle=None,
+ thread_root_id=None,
)
)
@@ -966,7 +970,7 @@ def test_runtime_state_awaiting_input_pings_and_resume_clears_pings() -> None:
str(CHANNEL_ID),
"my-agent",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -975,7 +979,7 @@ def test_runtime_state_awaiting_input_pings_and_resume_clears_pings() -> None:
str(CHANNEL_ID),
"my-agent",
"awaiting-input",
- notify_user="louis",
+ mention_handle="louis",
thread_root_id=None,
)
)
@@ -993,7 +997,7 @@ def test_runtime_state_awaiting_input_pings_and_resume_clears_pings() -> None:
str(CHANNEL_ID),
"my-agent",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -1212,3 +1216,29 @@ def test_start_times_out_when_never_ready_and_stops() -> None:
assert adapter._client is None
_run(scenario())
+
+
+def test_awaiting_input_with_nobody_linked_says_so() -> None:
+ # The ping used to post with the mention simply missing, which on the
+ # channel reads exactly like a ping that worked — an agent waiting on input
+ # nobody knows to give. The handle is the agent owner's linked account
+ # (CHOO-2137), so "nobody" now means the owner has not said which account
+ # here is theirs, and the line says that instead of trailing off.
+ adapter, _channel, webhook = _runtime_setup()
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "awaiting-input",
+ mention_handle=None,
+ thread_root_id=None,
+ )
+ )
+
+ content = webhook.sent[-1]["content"]
+ assert "needs your input" in content
+ assert "pings no one" in content
+ # Named as a person would name it, not as the class is.
+ assert "Discord" in content
+ assert "Adapter" not in content
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_directory_search.py b/core/tests/switch_core/bridges/collaboration/test_discord_directory_search.py
new file mode 100644
index 000000000..7febe7f4c
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_directory_search.py
@@ -0,0 +1,139 @@
+"""Discord member search backs identity claiming (CHOO-2137).
+
+Without it the adapter falls through to the base class, which reports that the
+platform has no searchable directory — so someone on Discord could only be
+linked after they had spoken, even though Discord can answer the question.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import discord
+import pytest
+
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
+
+GUILD_ID = 900
+
+
+def _adapter(guild: Any) -> DiscordAdapter:
+ adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+ adapter._get_guild = lambda: _completed(guild) # type: ignore[method-assign]
+ return adapter
+
+
+async def _completed(value: Any) -> Any:
+ return value
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeMember:
+ def __init__(
+ self, user_id: int, name: str, display_name: str, *, bot: bool = False
+ ) -> None:
+ self.id = user_id
+ self.name = name
+ self.display_name = display_name
+ self.bot = bot
+
+
+class _FakeGuild:
+ def __init__(self, members: list[_FakeMember] | Exception) -> None:
+ self._members = members
+ self.queries: list[tuple[str, int]] = []
+
+ async def query_members(self, *, query: str, limit: int) -> list[_FakeMember]:
+ self.queries.append((query, limit))
+ if isinstance(self._members, Exception):
+ raise self._members
+ return self._members
+
+
+def test_members_map_to_directory_users() -> None:
+ guild = _FakeGuild([_FakeMember(11, "louisa", "Louis A")])
+ found = _run(_adapter(guild).search_directory_users("lou"))
+
+ assert len(found) == 1
+ person = found[0]
+ # The id and username must be exactly what the inbound path records as the
+ # sender, or a claim made here would never match an arriving message.
+ assert person.external_user_id == "11"
+ assert person.username == "louisa"
+ assert person.display_name == "Louis A"
+ # Discord's bot API never discloses a member's email.
+ assert person.email is None
+
+
+def test_query_is_passed_to_discord() -> None:
+ guild = _FakeGuild([])
+ _run(_adapter(guild).search_directory_users(" lou "))
+ # Trimmed, and within Discord's accepted 5..100 limit range.
+ assert guild.queries == [("lou", 100)]
+
+
+def test_bots_are_excluded() -> None:
+ guild = _FakeGuild(
+ [
+ _FakeMember(1, "a-human", "A Human"),
+ _FakeMember(2, "some-bot", "Some Bot", bot=True),
+ ]
+ )
+ found = _run(_adapter(guild).search_directory_users("a"))
+ # A bot cannot own an agent, so offering it as "you" is never right.
+ assert [p.username for p in found] == ["a-human"]
+
+
+def test_results_are_sorted_by_display_name() -> None:
+ guild = _FakeGuild(
+ [
+ _FakeMember(1, "zoe", "Zoe"),
+ _FakeMember(2, "adam", "adam"),
+ _FakeMember(3, "mia", "Mia"),
+ ]
+ )
+ found = _run(_adapter(guild).search_directory_users("x"))
+ assert [p.display_name for p in found] == ["adam", "Mia", "Zoe"]
+
+
+def test_blank_query_does_not_hit_discord() -> None:
+ guild = _FakeGuild([_FakeMember(1, "someone", "Someone")])
+ assert _run(_adapter(guild).search_directory_users(" ")) == []
+ assert guild.queries == []
+
+
+class _FakeResponse:
+ status = 500
+ reason = "Internal Server Error"
+
+
+def _errors() -> list[BaseException]:
+ """The three failures `Guild.query_members` documents, minus ValueError,
+ which only fires on parameters this adapter hard-codes correctly."""
+ return [
+ discord.ClientException("presences intent is not enabled"),
+ discord.HTTPException(_FakeResponse(), "boom"),
+ TimeoutError(),
+ ]
+
+
[email protected]("index", range(3))
+def test_failures_surface_as_runtime_error(index: int) -> None:
+ # The gateway going quiet or refusing must reach the caller as a bridge
+ # failure, not an empty list that reads as "nobody by that name".
+ guild = _FakeGuild(_errors()[index])
+ with pytest.raises(RuntimeError):
+ _run(_adapter(guild).search_directory_users("lou"))
diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py
index 32462a437..33d0a8e29 100644
--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py
+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
import uuid
from unittest.mock import MagicMock
@@ -8,13 +9,31 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
+ _bridge_client_localpart,
)
from switch_core.db.models import Client, CollaborationBridge, ExternalUser, Room
+from switch_core.db.stores.client_store import ClientStore
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.room_store import RoomStore
+class _ClientLifecycle:
+ """Deletes the row, as the real service does, and remembers what it was
+ asked for. The real one also stops a live client; none of these are
+ running, and a MagicMock here would let a missing deletion pass."""
+
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
+ self._session_factory = session_factory
+ self.removed: list[str] = []
+
+ async def remove(self, client_id: str) -> None:
+ self.removed.append(client_id)
+ async with self._session_factory() as session:
+ await ClientStore().delete(session, client_id)
+ await session.commit()
+
+
def _service(
session_factory: async_sessionmaker[AsyncSession],
) -> CollaborationBridgeLifecycleService:
@@ -26,7 +45,7 @@ def _service(
room_store=RoomStore(),
agent_store=MagicMock(),
client_store=MagicMock(),
- client_lifecycle=MagicMock(),
+ client_lifecycle=_ClientLifecycle(session_factory),
room_service=MagicMock(),
matrix_admin=MagicMock(),
session_factory=session_factory,
@@ -46,7 +65,7 @@ async def _make_client(session: AsyncSession, *, client_type: str) -> str:
return client.id
-async def _make_bridge(session: AsyncSession) -> str:
+async def _make_bridge(session: AsyncSession) -> tuple[str, str]:
client_id = await _make_client(session, client_type="bridge")
bridge = CollaborationBridge(
type="mattermost",
@@ -56,7 +75,7 @@ async def _make_bridge(session: AsyncSession) -> str:
)
session.add(bridge)
await session.flush()
- return bridge.id
+ return bridge.id, client_id
async def _make_bridged_room(session: AsyncSession, *, bridge_id: str) -> str:
@@ -73,7 +92,9 @@ async def _make_bridged_room(session: AsyncSession, *, bridge_id: str) -> str:
return room.id
-async def _make_external_user(session: AsyncSession, *, bridge_id: str) -> str:
+async def _make_external_user(
+ session: AsyncSession, *, bridge_id: str
+) -> tuple[str, str]:
client_id = await _make_client(session, client_type="external_user")
user = ExternalUser(
bridge_id=bridge_id,
@@ -83,7 +104,7 @@ async def _make_external_user(session: AsyncSession, *, bridge_id: str) -> str:
)
session.add(user)
await session.flush()
- return user.id
+ return user.id, client_id
@pytest.mark.asyncio
@@ -99,9 +120,9 @@ async def test_remove_detaches_dependent_rooms(
"""
service = _service(session_factory)
async with session_factory() as session:
- bridge_id = await _make_bridge(session)
+ bridge_id, _ = await _make_bridge(session)
room_id = await _make_bridged_room(session, bridge_id=bridge_id)
- external_user_id = await _make_external_user(session, bridge_id=bridge_id)
+ external_user_id, _ = await _make_external_user(session, bridge_id=bridge_id)
await session.commit()
await service.remove(bridge_id)
@@ -126,10 +147,81 @@ async def test_remove_without_dependent_rooms_still_deletes(
) -> None:
service = _service(session_factory)
async with session_factory() as session:
- bridge_id = await _make_bridge(session)
+ bridge_id, _ = await _make_bridge(session)
await session.commit()
await service.remove(bridge_id)
async with session_factory() as session:
assert await CollaborationBridgeStore().get(session, bridge_id) is None
+
+
+async def test_disconnecting_takes_every_identity_switch_made_for_it(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """The bridge's own Matrix client and the puppet behind each person it saw.
+
+ These were left behind, and the bridge one is not merely untidy: its Matrix
+ name is derived from the app's type and display name, so disconnecting an
+ app and reconnecting one named the same hit the leftover row —
+ `duplicate key value violates unique constraint "clients_matrix_user_id_key"`.
+ """
+ service = _service(session_factory)
+ async with session_factory() as session:
+ bridge_id, bridge_client_id = await _make_bridge(session)
+ _external_user_id, puppet_client_id = await _make_external_user(
+ session, bridge_id=bridge_id
+ )
+ await session.commit()
+
+ await service.remove(bridge_id)
+
+ async with session_factory() as session:
+ assert await ClientStore().get(session, bridge_client_id) is None
+ assert await ClientStore().get(session, puppet_client_id) is None
+
+
+async def test_an_app_with_nobody_on_it_still_loses_its_own_client(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ # Louis's case exactly: a Telegram connection nobody had messaged yet.
+ service = _service(session_factory)
+ async with session_factory() as session:
+ bridge_id, bridge_client_id = await _make_bridge(session)
+ await session.commit()
+
+ await service.remove(bridge_id)
+
+ async with session_factory() as session:
+ assert await ClientStore().get(session, bridge_client_id) is None
+
+
+class TestTheBridgeClientName:
+ """Why deleting the row is necessary but not sufficient.
+
+ The homeserver has no API for removing an account, so the Matrix user
+ outlives the row. Reusing the name would then adopt an account whose
+ password Switch no longer holds — and shared-secret registration reports an
+ existing user as success without applying the new one, which reads as a
+ working connection that can never log in. A quiet failure in place of a
+ loud one is the wrong trade, so each registration takes a fresh name.
+ """
+
+ def test_two_connections_of_the_same_name_do_not_collide(self) -> None:
+ first = _bridge_client_localpart("telegram", "Telegram louiss")
+ second = _bridge_client_localpart("telegram", "Telegram louiss")
+
+ assert first != second
+
+ def test_the_name_still_says_which_app_it_is(self) -> None:
+ # It shows up as a Matrix user in rooms; a pure uuid would be unreadable.
+ localpart = _bridge_client_localpart("telegram", "Telegram louiss")
+
+ assert localpart.startswith("switch-bridge-telegram-telegram-louiss")
+
+ def test_it_stays_a_legal_matrix_localpart(self) -> None:
+ localpart = _bridge_client_localpart("slack", "Ops & Eng (US)")
+
+ assert re.fullmatch(r"[a-z0-9._=/-]+", localpart)
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_runtime_state.py
index c467172b4..f85bf2393 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
@@ -117,7 +117,7 @@ def test_a_finished_turn_retires_the_indicator_in_place() -> None:
_run(
adapter.apply_runtime_state(
- "chan-1", "worker", "idle", notify_user=None, thread_root_id=None
+ "chan-1", "worker", "idle", mention_handle=None, thread_root_id=None
)
)
@@ -140,7 +140,7 @@ def test_the_done_marker_carries_no_session_link() -> None:
"chan-1",
"worker",
"idle",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
deeplink_url="https://switch.example/session/1",
)
@@ -157,7 +157,7 @@ def test_an_operator_ping_is_resolved_rather_than_removed() -> None:
_run(
adapter.apply_runtime_state(
- "chan-1", "worker", "idle", notify_user=None, thread_root_id=None
+ "chan-1", "worker", "idle", mention_handle=None, thread_root_id=None
)
)
@@ -183,12 +183,12 @@ def test_a_turn_posts_one_status_line_and_deletes_nothing() -> None:
"chan-1",
"worker",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
detail=detail,
)
await adapter.apply_runtime_state(
- "chan-1", "worker", "idle", notify_user=None, thread_root_id=None
+ "chan-1", "worker", "idle", mention_handle=None, thread_root_id=None
)
_run(turn())
@@ -209,7 +209,7 @@ def test_idle_without_an_indicator_does_nothing() -> None:
_run(
adapter.apply_runtime_state(
- "chan-1", "worker", "idle", notify_user=None, thread_root_id=None
+ "chan-1", "worker", "idle", mention_handle=None, thread_root_id=None
)
)
diff --git a/core/tests/switch_core/bridges/collaboration/test_runtime_indicator_race.py b/core/tests/switch_core/bridges/collaboration/test_runtime_indicator_race.py
index 4df3ad68d..546f2d522 100644
--- a/core/tests/switch_core/bridges/collaboration/test_runtime_indicator_race.py
+++ b/core/tests/switch_core/bridges/collaboration/test_runtime_indicator_race.py
@@ -89,7 +89,7 @@ def _refresh(adapter: SlackAdapter, detail: str) -> Any:
CHANNEL,
AGENT,
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
detail=detail,
)
@@ -180,7 +180,7 @@ async def test_the_turn_end_clear_removes_everything() -> None:
CHANNEL,
AGENT,
"idle",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
index 1e2c189b8..190d90c76 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
@@ -614,7 +614,7 @@ def test_runtime_state_working_posts_generic_indicator() -> None:
_run(
adapter.apply_runtime_state(
- "C123", "agent-bot", "working", notify_user=None, thread_root_id=None
+ "C123", "agent-bot", "working", mention_handle=None, thread_root_id=None
)
)
@@ -632,7 +632,7 @@ def test_runtime_state_detail_edits_message_in_place() -> None:
_run(
adapter.apply_runtime_state(
- "C123", "agent-bot", "working", notify_user=None, thread_root_id=None
+ "C123", "agent-bot", "working", mention_handle=None, thread_root_id=None
)
)
_run(
@@ -640,7 +640,7 @@ def test_runtime_state_detail_edits_message_in_place() -> None:
"C123",
"agent-bot",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
detail="Editing room-connection.ts",
)
@@ -662,12 +662,12 @@ def test_runtime_state_idle_clears_working_message() -> None:
_run(
adapter.apply_runtime_state(
- "C123", "agent-bot", "working", notify_user=None, thread_root_id=None
+ "C123", "agent-bot", "working", mention_handle=None, thread_root_id=None
)
)
_run(
adapter.apply_runtime_state(
- "C123", "agent-bot", "idle", notify_user=None, thread_root_id=None
+ "C123", "agent-bot", "idle", mention_handle=None, thread_root_id=None
)
)
@@ -688,7 +688,7 @@ def test_reposition_reposts_indicator_below_newer_traffic() -> None:
"C123",
"agent-bot",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
detail="Editing adapter.py",
)
@@ -713,7 +713,7 @@ def test_reposition_stays_in_the_thread_when_the_message_is_in_it() -> None:
"C123",
"agent-bot",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id="C123:111.1",
)
)
@@ -734,7 +734,7 @@ def test_reposition_follows_the_agent_into_a_different_thread() -> None:
"C123",
"agent-bot",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id="C123:111.1",
)
)
@@ -754,7 +754,7 @@ def test_reposition_follows_the_agent_back_out_to_the_channel_root() -> None:
"C123",
"agent-bot",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id="C123:111.1",
)
)
@@ -785,12 +785,12 @@ def test_a_turn_ending_during_a_move_clears_what_the_move_left() -> None:
async def scenario() -> None:
await adapter.apply_runtime_state(
- "C123", "agent-bot", "working", notify_user=None, thread_root_id=None
+ "C123", "agent-bot", "working", mention_handle=None, thread_root_id=None
)
await asyncio.gather(
adapter.reposition_runtime_state("C123", "agent-bot", None),
adapter.apply_runtime_state(
- "C123", "agent-bot", "idle", notify_user=None, thread_root_id=None
+ "C123", "agent-bot", "idle", mention_handle=None, thread_root_id=None
),
)
@@ -811,7 +811,7 @@ def test_reposition_leaves_the_original_when_the_repost_fails() -> None:
_run(
adapter.apply_runtime_state(
- "C123", "agent-bot", "working", notify_user=None, thread_root_id=None
+ "C123", "agent-bot", "working", mention_handle=None, thread_root_id=None
)
)
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
index d2048b92e..82b81c20c 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
@@ -901,7 +901,7 @@ def test_working_posts_status_card() -> None:
"worker",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -920,7 +920,7 @@ def test_working_detail_refreshes_in_place() -> None:
"worker",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -929,7 +929,7 @@ def test_working_detail_refreshes_in_place() -> None:
"worker",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
detail="Editing adapter.py",
)
@@ -952,7 +952,7 @@ def test_idle_clears_working_message() -> None:
"worker",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -961,7 +961,7 @@ def test_idle_clears_working_message() -> None:
"worker",
"idle",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -981,7 +981,7 @@ def test_awaiting_input_keeps_working_and_pings() -> None:
"worker",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
@@ -990,7 +990,7 @@ def test_awaiting_input_keeps_working_and_pings() -> None:
"worker",
"awaiting-input",
- notify_user="louis",
+ mention_handle="louis",
thread_root_id=None,
)
)
@@ -1004,7 +1004,7 @@ def test_awaiting_input_keeps_working_and_pings() -> None:
"worker",
"idle",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
)
)
diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py b/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py
index 4cfdccf29..856012e9a 100644
--- a/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py
@@ -1137,7 +1137,7 @@ def test_working_posts_a_status_message() -> None:
_run(
adapter.apply_runtime_state(
- str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None
)
)
@@ -1149,7 +1149,7 @@ def test_working_again_edits_the_status_rather_than_reposting() -> None:
adapter = _adapter()
_run(
adapter.apply_runtime_state(
- str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None
)
)
@@ -1158,7 +1158,7 @@ def test_working_again_edits_the_status_rather_than_reposting() -> None:
str(CHAT_ID),
"scout",
"working",
- notify_user=None,
+ mention_handle=None,
thread_root_id=None,
detail="Editing adapter.py",
)
@@ -1176,7 +1176,7 @@ def test_awaiting_input_pings_the_operator() -> None:
str(CHAT_ID),
"scout",
"awaiting-input",
- notify_user="alice",
+ mention_handle="alice",
thread_root_id=None,
)
)
@@ -1189,7 +1189,7 @@ def test_going_idle_removes_the_status_and_the_pings() -> None:
adapter = _adapter()
_run(
adapter.apply_runtime_state(
- str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None
)
)
_run(
@@ -1197,14 +1197,14 @@ def test_going_idle_removes_the_status_and_the_pings() -> None:
str(CHAT_ID),
"scout",
"awaiting-input",
- notify_user="alice",
+ mention_handle="alice",
thread_root_id=None,
)
)
_run(
adapter.apply_runtime_state(
- str(CHAT_ID), "scout", "idle", notify_user=None, thread_root_id=None
+ str(CHAT_ID), "scout", "idle", mention_handle=None, thread_root_id=None
)
)
@@ -1219,7 +1219,7 @@ def test_the_status_message_follows_the_conversation() -> None:
adapter = _adapter()
_run(
adapter.apply_runtime_state(
- str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None
)
)
original = adapter._working_msg[(str(CHAT_ID), "scout")].message_ref
diff --git a/core/tests/switch_core/clients/test_addressing_enforcement.py b/core/tests/switch_core/clients/test_addressing_enforcement.py
index c69d8a2d2..0e07d4f58 100644
--- a/core/tests/switch_core/clients/test_addressing_enforcement.py
+++ b/core/tests/switch_core/clients/test_addressing_enforcement.py
@@ -5,8 +5,11 @@ from types import SimpleNamespace
from switch_core.clients.agent_client import (
_ADDRESSING_DENIED_MESSAGE,
+ _ADDRESSING_UNCLAIMED_MESSAGE,
AUTO_REPLY_FLAG,
AgentClient,
+ _AddressingDecision,
+ _SenderPrincipal,
)
@@ -34,9 +37,10 @@ def _event(
class TestResolveSenderPrincipal:
- """mxid → Client → Agent (agent sender) or ExternalUser (human sender)."""
+ """mxid → Client → Agent (agent sender) or ExternalUser (human sender),
+ plus every Switch user who has claimed the human's platform identity."""
- def _client(self, *, client, agent, external_user) -> SimpleNamespace: # type: ignore[no-untyped-def]
+ def _client(self, *, client, agent, external_user, claimants=()) -> SimpleNamespace: # type: ignore[no-untyped-def]
async def _get_by_mxid(_session, _mxid): # type: ignore[no-untyped-def]
return client
@@ -46,33 +50,67 @@ class TestResolveSenderPrincipal:
async def _ext_by_client(_session, _cid): # type: ignore[no-untyped-def]
return external_user
+ async def _claimant_ids(_session, _external_user_id): # type: ignore[no-untyped-def]
+ return list(claimants)
+
return SimpleNamespace(
client_store=SimpleNamespace(get_by_matrix_user_id=_get_by_mxid),
_agent_store=SimpleNamespace(get_by_client_id=_agent_by_client),
- _external_user_store=SimpleNamespace(get_by_client_id=_ext_by_client),
+ _external_user_store=SimpleNamespace(
+ get_by_client_id=_ext_by_client, claimant_ids=_claimant_ids
+ ),
)
async def test_agent_sender(self) -> None:
+ # An agent carries no Switch user: it is never its owner, even its
+ # owner's own agent.
client = self._client(
client=SimpleNamespace(id="c1"),
- agent=SimpleNamespace(id="agent-7"),
+ agent=SimpleNamespace(id="agent-7", owner_id="user-1"),
external_user=None,
)
result = await AgentClient._resolve_sender_principal(
client, object(), "@a:switch.local"
)
- assert result == ("agent", "agent-7")
+ assert result == ("agent", "agent-7", [], "user-1")
+
+ async def test_human_sender_claimed(self) -> None:
+ client = self._client(
+ client=SimpleNamespace(id="c1"),
+ agent=None,
+ external_user=SimpleNamespace(id="ext-3"),
+ claimants=["user-1"],
+ )
+ result = await AgentClient._resolve_sender_principal(
+ client, object(), "@u:switch.local"
+ )
+ assert result == ("user", "ext-3", ["user-1"], None)
- async def test_human_sender(self) -> None:
+ async def test_human_sender_claimed_by_several(self) -> None:
+ # Claiming is not exclusive, so the principal carries every claimant
+ # rather than picking one.
client = self._client(
client=SimpleNamespace(id="c1"),
agent=None,
external_user=SimpleNamespace(id="ext-3"),
+ claimants=["user-1", "user-2"],
)
result = await AgentClient._resolve_sender_principal(
client, object(), "@u:switch.local"
)
- assert result == ("user", "ext-3")
+ assert result == ("user", "ext-3", ["user-1", "user-2"], None)
+
+ async def test_human_sender_unclaimed(self) -> None:
+ # Nobody has linked this platform identity to a Switch user.
+ client = self._client(
+ client=SimpleNamespace(id="c1"),
+ agent=None,
+ external_user=SimpleNamespace(id="ext-3"),
+ )
+ result = await AgentClient._resolve_sender_principal(
+ client, object(), "@u:switch.local"
+ )
+ assert result == ("user", "ext-3", [], None)
async def test_unknown_client_is_none(self) -> None:
client = self._client(client=None, agent=None, external_user=None)
@@ -96,19 +134,25 @@ class TestResolveSenderPrincipal:
def _allowed_client(
*,
policy: dict | None,
- principal: tuple[str, str] | None,
+ principal: tuple[str, str, list[str]] | None,
+ sender_owner_id: str | None = None,
group_id: str | None = None,
+ owner_id: str | None = None,
) -> SimpleNamespace:
- """Fake client for _addressing_allowed: the agent carries `policy`, the
- sender resolves to `principal`, and the room has `group_id`."""
+ """Fake client for _addressing_allowed: the agent carries `policy` and is
+ owned by `owner_id`, the sender resolves to `principal` (kind, id,
+ claimants) owned by `sender_owner_id`, and the room has `group_id`."""
- agent = SimpleNamespace(name="fixer", addressing_policy=policy)
+ agent = SimpleNamespace(name="fixer", addressing_policy=policy, owner_id=owner_id)
async def _fresh_agent(): # type: ignore[no-untyped-def]
return agent
async def _resolve(_session, _mxid): # type: ignore[no-untyped-def]
- return principal
+ if principal is None:
+ return None
+ kind, sender_id, claimants = principal
+ return _SenderPrincipal(kind, sender_id, claimants, sender_owner_id) # type: ignore[arg-type]
async def _get_room(_session, _room_id): # type: ignore[no-untyped-def]
return SimpleNamespace(group_id=group_id)
@@ -122,44 +166,208 @@ def _allowed_client(
)
+async def _decide(client: SimpleNamespace, room_id: str = "room-1"): # type: ignore[no-untyped-def]
+ return await AgentClient._addressing_allowed(client, "@u:switch.local", room_id)
+
+
class TestAddressingAllowed:
async def test_open_policy_allows_without_lookup(self) -> None:
# No policy → open; must not even need a resolvable sender.
client = _allowed_client(policy=None, principal=None)
- assert await AgentClient._addressing_allowed(client, _event(), _meta()) is True
+ assert (await _decide(client)).allowed is True
async def test_permitted_sender(self) -> None:
policy = {"rules": [{"users": ["ext-3"], "agents": []}]}
- client = _allowed_client(policy=policy, principal=("user", "ext-3"))
- assert await AgentClient._addressing_allowed(client, _event(), _meta()) is True
+ client = _allowed_client(policy=policy, principal=("user", "ext-3", []))
+ assert (await _decide(client)).allowed is True
async def test_denied_sender(self) -> None:
policy = {"rules": [{"users": ["ext-3"], "agents": []}]}
- client = _allowed_client(policy=policy, principal=("user", "someone-else"))
- assert await AgentClient._addressing_allowed(client, _event(), _meta()) is False
+ client = _allowed_client(policy=policy, principal=("user", "someone-else", []))
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
async def test_unresolvable_sender_fails_closed(self) -> None:
# A restricted agent must not be addressable by an unresolvable sender.
policy = {"rules": [{"users": ["ext-3"], "agents": []}]}
client = _allowed_client(policy=policy, principal=None)
- assert await AgentClient._addressing_allowed(client, _event(), _meta()) is False
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
async def test_group_scoped_policy(self) -> None:
policy = {"rules": [{"room_groups": ["g1"], "agents": []}]}
allowed = _allowed_client(
- policy=policy, principal=("user", "u1"), group_id="g1"
+ policy=policy, principal=("user", "u1", []), group_id="g1"
)
- denied = _allowed_client(policy=policy, principal=("user", "u1"), group_id="g2")
- assert await AgentClient._addressing_allowed(allowed, _event(), _meta()) is True
- assert await AgentClient._addressing_allowed(denied, _event(), _meta()) is False
+ denied = _allowed_client(
+ policy=policy, principal=("user", "u1", []), group_id="g2"
+ )
+ assert (await _decide(allowed)).allowed is True
+ assert (await _decide(denied)).allowed is False
+
+class TestOwnerAddressing:
+ """An owner-scoped policy resolves the owner at enforcement time from the
+ agent's `owner_id` and the Switch users who have claimed the sender's
+ platform account."""
-def _gate_client(*, allowed: bool) -> SimpleNamespace:
+ _POLICY = {"rules": [{"users": [], "agents": [], "owner": True}]}
+
+ async def test_owner_allowed(self) -> None:
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("user", "ext-3", ["user-1"]),
+ owner_id="user-1",
+ )
+ assert (await _decide(client)).allowed is True
+
+ async def test_owner_among_several_claimants_allowed(self) -> None:
+ # Someone else claiming the same account does not lock the owner out.
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("user", "ext-3", ["user-2", "user-1"]),
+ owner_id="user-1",
+ )
+ assert (await _decide(client)).allowed is True
+
+ async def test_other_user_denied_with_generic_wording(self) -> None:
+ # This sender IS claimed — they just aren't the owner, so telling them
+ # to link their account would be wrong.
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("user", "ext-9", ["user-2"]),
+ owner_id="user-1",
+ )
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
+
+ async def test_claimed_by_others_only_denied_with_generic_wording(self) -> None:
+ # Several claimants, none of them the owner: still claimed, so the
+ # "link your account" wording would be misleading.
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("user", "ext-9", ["user-2", "user-3"]),
+ owner_id="user-1",
+ )
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
+
+ async def test_unclaimed_sender_gets_link_your_account_wording(self) -> None:
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("user", "ext-3", []),
+ owner_id="user-1",
+ )
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_UNCLAIMED_MESSAGE
+
+ async def test_unclaimed_sender_without_owner_rule_gets_generic_wording(
+ self,
+ ) -> None:
+ # Nothing to link an account for: the policy never consults the owner.
+ client = _allowed_client(
+ policy={"rules": [{"users": ["ext-3"], "agents": []}]},
+ principal=("user", "someone-else", []),
+ owner_id="user-1",
+ )
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
+
+ async def test_agent_sender_denied_generically(self) -> None:
+ # An agent is never the owner, and the unclaimed wording is meaningless
+ # for it — it has no chat account to link.
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("agent", "agent-7", []),
+ owner_id="user-1",
+ )
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
+
+ async def test_ownerless_agent_denies_its_would_be_owner(self) -> None:
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("user", "ext-3", ["user-1"]),
+ owner_id=None,
+ )
+ assert (await _decide(client)).allowed is False
+
+ async def test_allowed_agent_still_gets_in(self) -> None:
+ policy = {"rules": [{"users": [], "agents": ["agent-7"], "owner": True}]}
+ client = _allowed_client(
+ policy=policy,
+ principal=("agent", "agent-7", []),
+ owner_id="user-1",
+ )
+ assert (await _decide(client)).allowed is True
+
+
+class TestOwnerAgentsAddressing:
+ """`owner_agents` on the room-message path (CHOO-2137)."""
+
+ _POLICY = {"rules": [{"users": [], "agents": [], "owner_agents": True}]}
+
+ async def test_an_agent_of_the_same_owner_is_let_in(self) -> None:
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("agent", "manager", []),
+ sender_owner_id="user-1",
+ owner_id="user-1",
+ )
+ assert (await _decide(client)).allowed is True
+
+ async def test_somebody_elses_agent_is_refused(self) -> None:
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("agent", "their-manager", []),
+ sender_owner_id="user-2",
+ owner_id="user-1",
+ )
+ decision = await _decide(client)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
+
+ async def test_the_owner_in_person_is_not_covered_by_it(self) -> None:
+ # Only `owner` admits the human. A rule that says "my agents may" and
+ # silently also meant "I may" would make the two shortcuts identical.
+ client = _allowed_client(
+ policy=self._POLICY,
+ principal=("user", "ext-3", ["user-1"]),
+ owner_id="user-1",
+ )
+ assert (await _decide(client)).allowed is False
+
+ async def test_the_refusal_does_not_tell_an_agent_to_link_an_account(
+ self,
+ ) -> None:
+ # The unclaimed-identity wording is for a human whose chat account
+ # nobody has claimed. An agent has none to link, so pointing it at that
+ # would send whoever reads the room down the wrong path.
+ policy = {
+ "rules": [{"users": [], "agents": [], "owner": True, "owner_agents": True}]
+ }
+ client = _allowed_client(
+ policy=policy,
+ principal=("agent", "stranger", []),
+ sender_owner_id="user-2",
+ owner_id="user-1",
+ )
+ assert (await _decide(client)).refusal == _ADDRESSING_DENIED_MESSAGE
+
+
+def _gate_client(*, allowed: bool, refusal: str = _ADDRESSING_DENIED_MESSAGE): # type: ignore[no-untyped-def]
"""Fake client for _gate_addressed: records any auto-reply sent."""
sent: list[dict] = []
- async def _addressing_allowed(_event, _meta): # type: ignore[no-untyped-def]
- return allowed
+ async def _addressing_allowed(_matrix_sender, _room_id): # type: ignore[no-untyped-def]
+ return _AddressingDecision(allowed=allowed, refusal="" if allowed else refusal)
async def _send_message(room_id, body, **kwargs): # type: ignore[no-untyped-def]
sent.append({"room_id": room_id, "body": body, **kwargs})
@@ -219,3 +427,143 @@ class TestGateAddressed:
)
assert result is False
assert client.sent == []
+
+ async def test_reply_carries_the_decision_wording(self) -> None:
+ # The refusal the decision chose is what the sender sees, not a
+ # re-derived generic one.
+ client = _gate_client(allowed=False, refusal=_ADDRESSING_UNCLAIMED_MESSAGE)
+ await AgentClient._gate_addressed(
+ client, _room(), _event(), _meta(), "$root", True
+ )
+ assert _ADDRESSING_UNCLAIMED_MESSAGE in client.sent[0]["body"]
+
+
+def _command(
+ args: str = "", user_id: str = "@u:switch.local", command: str = "reset"
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ command=command, args=args, user_id=user_id, thread_id="$cmd"
+ )
+
+
+def _command_client(*, allowed: bool, targets_me: bool): # type: ignore[no-untyped-def]
+ """Fake client for _gate_command: records any command reply posted."""
+ replies: list[dict] = []
+
+ async def _addressing_allowed(_matrix_sender, _room_id): # type: ignore[no-untyped-def]
+ return _AddressingDecision(
+ allowed=allowed, refusal="" if allowed else _ADDRESSING_DENIED_MESSAGE
+ )
+
+ async def _targets_me(_args, _room_id): # type: ignore[no-untyped-def]
+ return targets_me
+
+ async def _reply_command(room_id, body, **kwargs): # type: ignore[no-untyped-def]
+ replies.append({"room_id": room_id, "body": body, **kwargs})
+
+ client = SimpleNamespace(
+ agent=SimpleNamespace(name="fixer"),
+ _addressing_allowed=_addressing_allowed,
+ _command_targets_me_explicitly=_targets_me,
+ reply_command=_reply_command,
+ )
+ client.replies = replies # type: ignore[attr-defined]
+ return client
+
+
+class TestGateCommand:
+ """Commands drive the agent as surely as a message does, so they run
+ through the same policy — but a room-wide command is declined quietly."""
+
+ async def test_allowed_passes_through(self) -> None:
+ client = _command_client(allowed=True, targets_me=True)
+ result = await AgentClient._gate_command(
+ client, _room(), _command(args="@fixer"), _meta()
+ )
+ assert result is True
+ assert client.replies == []
+
+ async def test_denied_and_explicitly_targeted_replies(self) -> None:
+ client = _command_client(allowed=False, targets_me=True)
+ result = await AgentClient._gate_command(
+ client, _room(), _command(args="@fixer"), _meta()
+ )
+ assert result is False
+ assert len(client.replies) == 1
+ reply = client.replies[0]
+ assert reply["room_id"] == "!matrix:switch.local"
+ assert reply["body"] == _ADDRESSING_DENIED_MESSAGE
+ assert reply["thread_root_id"] == "$cmd"
+
+ async def test_denied_room_wide_command_is_declined_quietly(self) -> None:
+ # `!reset-all-agents` (or a bare `!reset`) makes no claim about this
+ # agent; answering every one would flood a room of restricted agents.
+ client = _command_client(allowed=False, targets_me=False)
+ result = await AgentClient._gate_command(
+ client, _room(), _command(command="reset-all-agents", args=""), _meta()
+ )
+ assert result is False
+ assert client.replies == []
+
+
+class TestCommandTargetsMeExplicitly:
+ """Only an `@` token naming this agent (name, alias, or a role it holds)
+ counts as explicit targeting."""
+
+ def _client(self, *, name: str = "fixer", alias: bool = False, role: bool = False): # type: ignore[no-untyped-def]
+ async def _tags_alias(_text, _room_id): # type: ignore[no-untyped-def]
+ return alias
+
+ async def _tags_role(_text, _room_id): # type: ignore[no-untyped-def]
+ return role
+
+ client = SimpleNamespace(
+ agent=SimpleNamespace(name=name),
+ _text_tags_my_alias=_tags_alias,
+ _text_tags_my_role=_tags_role,
+ )
+ client._args_tag_my_name = lambda text: AgentClient._args_tag_my_name( # type: ignore[attr-defined]
+ client, text
+ )
+ return client
+
+ async def test_no_at_token_is_not_explicit(self) -> None:
+ client = self._client()
+ assert (
+ await AgentClient._command_targets_me_explicitly(client, "", "room-1")
+ is False
+ )
+
+ async def test_own_name_is_explicit(self) -> None:
+ client = self._client()
+ assert (
+ await AgentClient._command_targets_me_explicitly(client, "@fixer", "room-1")
+ is True
+ )
+
+ async def test_another_agents_name_is_not_explicit(self) -> None:
+ client = self._client()
+ assert (
+ await AgentClient._command_targets_me_explicitly(
+ client, "@someone-else", "room-1"
+ )
+ is False
+ )
+
+ async def test_alias_is_explicit(self) -> None:
+ client = self._client(alias=True)
+ assert (
+ await AgentClient._command_targets_me_explicitly(
+ client, "@nickname", "room-1"
+ )
+ is True
+ )
+
+ async def test_held_role_is_explicit(self) -> None:
+ client = self._client(role=True)
+ assert (
+ await AgentClient._command_targets_me_explicitly(
+ client, "@manager", "room-1"
+ )
+ is True
+ )
diff --git a/core/tests/switch_core/clients/test_owner_notification_handle.py b/core/tests/switch_core/clients/test_owner_notification_handle.py
new file mode 100644
index 000000000..c11d42f4a
--- /dev/null
+++ b/core/tests/switch_core/clients/test_owner_notification_handle.py
@@ -0,0 +1,96 @@
+"""Who gets pinged when an agent needs its operator (CHOO-2137).
+
+This used to be `notify_user`: one handle typed into the agent's config. A
+handle only means something on one platform, so the same string was at best
+right in one room and inert everywhere else — and on Discord and Teams it never
+rendered as a mention at all, so it notified nobody while looking like it did.
+
+It is now the agent's owner, resolved through the account that person has
+claimed on the bridge the room is on. The link is already per messaging app,
+which is exactly the granularity a handle needs.
+"""
+
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+
+from switch_core.clients.agent_client import AgentClient
+
+
+@asynccontextmanager
+async def _session_factory(): # type: ignore[no-untyped-def]
+ yield object()
+
+
+def _claimed(bridge_id: str, username: str) -> SimpleNamespace:
+ """An `ExternalUser` row, with only the fields the resolver reads."""
+ return SimpleNamespace(bridge_id=bridge_id, external_username=username)
+
+
+def _client(claimed: list[SimpleNamespace]) -> SimpleNamespace:
+ async def _get_by_user(_session, _user_id): # type: ignore[no-untyped-def]
+ return claimed
+
+ return SimpleNamespace(
+ session_factory=_session_factory,
+ _external_user_store=SimpleNamespace(get_by_user=_get_by_user),
+ )
+
+
+def _agent(owner_id: str | None) -> SimpleNamespace:
+ return SimpleNamespace(id="a1", name="worker", owner_id=owner_id)
+
+
+class TestResolvingTheOwnersHandle:
+ async def test_the_owners_account_on_this_bridge(self) -> None:
+ client = _client([_claimed("slack-1", "louis.amaudruz")])
+
+ handle = await AgentClient.owner_handle_in(client, _agent("u1"), "slack-1")
+
+ assert handle == "louis.amaudruz"
+
+ async def test_the_right_one_when_they_are_on_several_platforms(self) -> None:
+ # The whole reason a single configured handle could not work: this
+ # person is one name on Slack and another on Telegram.
+ client = _client(
+ [_claimed("slack-1", "louis.amaudruz"), _claimed("telegram-1", "louisa")]
+ )
+
+ assert (
+ await AgentClient.owner_handle_in(client, _agent("u1"), "telegram-1")
+ == "louisa"
+ )
+
+ async def test_nobody_when_the_owner_has_claimed_nothing_here(self) -> None:
+ # Claimed on Slack, but this room is on Telegram. Naming the Slack
+ # handle here would @ a stranger or nobody at all.
+ client = _client([_claimed("slack-1", "louis.amaudruz")])
+
+ assert (
+ await AgentClient.owner_handle_in(client, _agent("u1"), "telegram-1")
+ is None
+ )
+
+ async def test_nobody_for_an_ownerless_agent(self) -> None:
+ client = _client([_claimed("slack-1", "louis.amaudruz")])
+
+ assert (
+ await AgentClient.owner_handle_in(client, _agent(None), "slack-1") is None
+ )
+
+ async def test_nobody_for_a_room_with_no_bridge(self) -> None:
+ # An internal-only room has no platform to mention anyone on.
+ client = _client([_claimed("slack-1", "louis.amaudruz")])
+
+ assert await AgentClient.owner_handle_in(client, _agent("u1"), None) is None
+
+ async def test_the_same_account_every_time_when_they_hold_several(self) -> None:
+ # Claiming is not exclusive. Whichever is picked, it must not change
+ # between one message and the next.
+ client = _client([_claimed("slack-1", "zoe"), _claimed("slack-1", "adam")])
+
+ first = await AgentClient.owner_handle_in(client, _agent("u1"), "slack-1")
+ second = await AgentClient.owner_handle_in(client, _agent("u1"), "slack-1")
+
+ assert first == second == "adam"
diff --git a/core/tests/switch_core/db/stores/test_external_user_claims.py b/core/tests/switch_core/db/stores/test_external_user_claims.py
new file mode 100644
index 000000000..41e22b5a1
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_external_user_claims.py
@@ -0,0 +1,337 @@
+"""Claiming a platform identity is non-exclusive (CHOO-2137).
+
+Several Switch users may claim the same messaging account. An exclusive claim
+would let whoever got there first keep the real person from ever being
+recognised by their own agents, so the store records claims as a set rather
+than as a single owner column on `external_users`.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import (
+ Client,
+ CollaborationBridge,
+ ExternalUser,
+ User,
+)
+from switch_core.db.stores.external_user_store import ExternalUserStore
+
+_STORE = ExternalUserStore()
+
+
+async def _make_client(session: AsyncSession, *, client_type: str) -> str:
+ client = Client(
+ matrix_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",
+ display_name=f"{client_type} client",
+ type=client_type,
+ password="x",
+ )
+ session.add(client)
+ await session.flush()
+ return client.id
+
+
+async def _make_bridge(session: AsyncSession) -> str:
+ bridge = CollaborationBridge(
+ type="mattermost",
+ display_name="MM",
+ client_id=await _make_client(session, client_type="bridge"),
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ return bridge.id
+
+
+async def _make_external_user(
+ session: AsyncSession, *, bridge_id: str, username: str = "alice"
+) -> ExternalUser:
+ external_user = ExternalUser(
+ bridge_id=bridge_id,
+ external_user_id=f"U{uuid.uuid4().hex[:8]}",
+ external_username=username,
+ client_id=await _make_client(session, client_type="external_user"),
+ )
+ session.add(external_user)
+ await session.flush()
+ return external_user
+
+
+async def _make_user(session: AsyncSession, *, name: str) -> str:
+ user = User(
+ name=name,
+ email=f"{name}-{uuid.uuid4().hex[:8]}@test",
+ role="user",
+ password_hash="x",
+ )
+ session.add(user)
+ await session.flush()
+ return user.id
+
+
+class TestClaimIsNonExclusive:
+ async def test_two_users_claim_the_same_account(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ first = await _make_user(session, name="first")
+ second = await _make_user(session, name="second")
+
+ await _STORE.claim(session, external_user, first)
+ await _STORE.claim(session, external_user, second)
+ await session.commit()
+
+ async with session_factory() as session:
+ claimants = await _STORE.claimant_ids(session, external_user.id)
+ assert sorted(claimants) == sorted([first, second])
+
+ async def test_claim_is_idempotent(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Re-claiming an account you already claimed is a no-op, not a
+ # duplicate row and not a conflict.
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="repeat")
+
+ await _STORE.claim(session, external_user, user_id)
+ await _STORE.claim(session, external_user, user_id)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, external_user.id) == [user_id]
+
+ async def test_unclaimed_account_has_no_claimants(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, external_user.id) == []
+
+
+class TestRelease:
+ async def test_release_drops_only_the_named_users_claim(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The point of non-exclusivity: one person walking away from a shared
+ # account must not un-claim it for everyone else.
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ leaving = await _make_user(session, name="leaving")
+ staying = await _make_user(session, name="staying")
+ await _STORE.claim(session, external_user, leaving)
+ await _STORE.claim(session, external_user, staying)
+ await session.commit()
+
+ async with session_factory() as session:
+ await _STORE.release(session, external_user, leaving)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, external_user.id) == [staying]
+
+ async def test_releasing_a_claim_that_was_never_made_is_a_no_op(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ holder = await _make_user(session, name="holder")
+ stranger = await _make_user(session, name="stranger")
+ await _STORE.claim(session, external_user, holder)
+ await session.commit()
+
+ async with session_factory() as session:
+ await _STORE.release(session, external_user, stranger)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, external_user.id) == [holder]
+
+ async def test_claim_after_release_works_again(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="returning")
+ await _STORE.claim(session, external_user, user_id)
+ await _STORE.release(session, external_user, user_id)
+ await _STORE.claim(session, external_user, user_id)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, external_user.id) == [user_id]
+
+
+class TestGetByUser:
+ async def test_returns_every_identity_the_user_claimed(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ mine_a = await _make_external_user(
+ session, bridge_id=bridge_id, username="mine-a"
+ )
+ mine_b = await _make_external_user(
+ session, bridge_id=bridge_id, username="mine-b"
+ )
+ theirs = await _make_external_user(
+ session, bridge_id=bridge_id, username="theirs"
+ )
+ me = await _make_user(session, name="me")
+ them = await _make_user(session, name="them")
+ await _STORE.claim(session, mine_a, me)
+ await _STORE.claim(session, mine_b, me)
+ await _STORE.claim(session, theirs, them)
+ await session.commit()
+
+ async with session_factory() as session:
+ got = await _STORE.get_by_user(session, me)
+ assert sorted(u.id for u in got) == sorted([mine_a.id, mine_b.id])
+
+ async def test_a_shared_account_is_returned_to_both_claimants(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ shared = await _make_external_user(session, bridge_id=bridge_id)
+ first = await _make_user(session, name="first")
+ second = await _make_user(session, name="second")
+ await _STORE.claim(session, shared, first)
+ await _STORE.claim(session, shared, second)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert [u.id for u in await _STORE.get_by_user(session, first)] == [
+ shared.id
+ ]
+ assert [u.id for u in await _STORE.get_by_user(session, second)] == [
+ shared.id
+ ]
+
+ async def test_user_without_claims_gets_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ await _make_external_user(session, bridge_id=bridge_id)
+ nobody = await _make_user(session, name="nobody")
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.get_by_user(session, nobody) == []
+
+
+class TestClaimantIdsFor:
+ async def test_batches_claims_by_identity(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ shared = await _make_external_user(
+ session, bridge_id=bridge_id, username="shared"
+ )
+ solo = await _make_external_user(
+ session, bridge_id=bridge_id, username="solo"
+ )
+ unclaimed = await _make_external_user(
+ session, bridge_id=bridge_id, username="unclaimed"
+ )
+ first = await _make_user(session, name="first")
+ second = await _make_user(session, name="second")
+ await _STORE.claim(session, shared, first)
+ await _STORE.claim(session, shared, second)
+ await _STORE.claim(session, solo, first)
+ await session.commit()
+
+ async with session_factory() as session:
+ claims = await _STORE.claimant_ids_for(
+ session, [shared.id, solo.id, unclaimed.id]
+ )
+ assert sorted(claims[shared.id]) == sorted([first, second])
+ assert claims[solo.id] == [first]
+ # An unclaimed identity is absent rather than mapped to []: callers
+ # read it with .get(id, []).
+ assert unclaimed.id not in claims
+
+ async def test_only_the_requested_identities_are_returned(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ asked = await _make_external_user(
+ session, bridge_id=bridge_id, username="asked"
+ )
+ other = await _make_external_user(
+ session, bridge_id=bridge_id, username="other"
+ )
+ user_id = await _make_user(session, name="claimant")
+ await _STORE.claim(session, asked, user_id)
+ await _STORE.claim(session, other, user_id)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids_for(session, [asked.id]) == {
+ asked.id: [user_id]
+ }
+
+ async def test_empty_input_short_circuits(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids_for(session, []) == {}
+
+
+class TestClaimsAreCascaded:
+ async def test_deleting_the_switch_user_drops_their_claims(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # ON DELETE CASCADE on users.id: closing a Switch account must not
+ # leave a dangling claim that keeps satisfying an owner rule.
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ leaving = await _make_user(session, name="leaving")
+ staying = await _make_user(session, name="staying")
+ await _STORE.claim(session, external_user, leaving)
+ await _STORE.claim(session, external_user, staying)
+ await session.commit()
+
+ async with session_factory() as session:
+ await session.delete(await session.get(User, leaving))
+ await session.commit()
+
+ async with session_factory() as session:
+ # The platform identity itself survives — only the claim goes.
+ assert await _STORE.get(session, external_user.id) is not None
+ assert await _STORE.claimant_ids(session, external_user.id) == [staying]
+
+ async def test_deleting_the_identity_drops_its_claims(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ external_user = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="claimant")
+ await _STORE.claim(session, external_user, user_id)
+ await session.commit()
+
+ async with session_factory() as session:
+ await _STORE.delete(session, external_user.id)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.get_by_user(session, user_id) == []
diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py
index 6f9d48204..5ac9704e4 100644
--- a/core/tests/switch_core/gateway/test_collaborations_authz.py
+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py
@@ -20,17 +20,26 @@ from __future__ import annotations
import importlib
import uuid
+from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.auth import PUBLIC_PATH_PREFIXES
+from switch_core.bridges.collaboration.models import DirectoryUser
from switch_core.db.models import Client, CollaborationBridge, User
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.gateway.auth import get_current_user, require_admin
-from switch_core.gateway.collaborations import router, set_default_bridge
+from switch_core.gateway.collaborations import (
+ _require_directory_account,
+ claim_bridge_identity,
+ release_bridge_identity,
+ router,
+ set_default_bridge,
+)
+from switch_core.gateway.schemas import ClaimIdentityRequest
_BRIDGE_STORE = CollaborationBridgeStore()
_ROOM_STORE = RoomStore()
@@ -68,6 +77,18 @@ def test_collab_api_module_is_gone() -> None:
WRITE_METHODS = {"POST", "PATCH", "PUT", "DELETE"}
+# Identity claiming (CHOO-2137) is the one collaboration write with an owner to
+# scope to: the row it mutates is a link between a platform account and one
+# Switch user, not part of the bridge itself, and a user must be able to claim
+# their own without an admin. These routes carry a self-or-admin check inside
+# the handler instead — asserted by
+# `test_owner_scoped_identity_routes_check_self_or_admin` below, so the
+# exemption cannot hide an unauthorized route.
+_OWNER_SCOPED_PATHS = {
+ "/{bridge_id}/identities",
+ "/{bridge_id}/identities/{external_user_row_id}",
+}
+
def test_bridge_write_routes_require_admin() -> None:
"""EVERY state-changing route must be gated on require_admin — a bridge is an
@@ -81,6 +102,7 @@ def test_bridge_write_routes_require_admin() -> None:
f"{sorted(route.methods & WRITE_METHODS)} {route.path}"
for route in router.routes
if route.methods & WRITE_METHODS
+ and route.path not in _OWNER_SCOPED_PATHS
and require_admin not in _dependency_calls(route.dependant)
)
assert not unguarded, (
@@ -88,6 +110,137 @@ def test_bridge_write_routes_require_admin() -> None:
)
+def test_owner_scoped_exemptions_name_real_routes() -> None:
+ """Guard the exemption list itself: a path that no longer exists would
+ silently excuse nothing, or worse, a renamed route."""
+ paths = {route.path for route in router.routes}
+ assert _OWNER_SCOPED_PATHS <= paths
+
+
+class TestIdentityRoutesAreSelfOrAdmin:
+ """The check the require_admin exemption trades away moved into the
+ handler; it did not disappear."""
+
+ async def test_claiming_for_another_user_is_refused(self) -> None:
+ with pytest.raises(HTTPException) as excinfo:
+ await claim_bridge_identity(
+ bridge_id="b1",
+ payload=ClaimIdentityRequest(
+ external_user_id="U123",
+ username="them",
+ user_id="someone-else",
+ ),
+ session=object(), # type: ignore[arg-type]
+ bridge_store=_StubGet(object()), # type: ignore[arg-type]
+ external_user_store=_StubGet(None), # type: ignore[arg-type]
+ user_store=_StubGet(None), # type: ignore[arg-type]
+ collab_lifecycle=object(), # type: ignore[arg-type]
+ user=_user(id="me", role="user"),
+ )
+ assert excinfo.value.status_code == 403
+
+ async def test_releasing_another_users_claim_is_refused(self) -> None:
+ # Releasing names the claimant to drop; anyone else's claim on the same
+ # account is not the caller's to touch.
+ theirs = SimpleNamespace(id="ext-1", bridge_id="b1")
+ with pytest.raises(HTTPException) as excinfo:
+ await release_bridge_identity(
+ bridge_id="b1",
+ external_user_row_id="ext-1",
+ session=object(), # type: ignore[arg-type]
+ external_user_store=_StubGet(theirs), # type: ignore[arg-type]
+ user_store=_StubGet(None), # type: ignore[arg-type]
+ user=_user(id="me", role="user"),
+ user_id="someone-else",
+ )
+ assert excinfo.value.status_code == 403
+
+
+class TestProvisioningNeedsARealAccount:
+ """Claiming an account Switch has not seen mints a Matrix puppet, and the
+ id comes from the request body. Anyone signed in may claim any *real*
+ account — that is the point of non-exclusive claims — but conjuring rows
+ for ids the platform has never heard of is a different thing."""
+
+ async def test_account_in_the_directory_is_accepted(self) -> None:
+ await _require_directory_account(
+ _StubLifecycle([_directory_user("U123")]),
+ bridge_id="b1",
+ external_user_id="U123",
+ username="someone",
+ )
+
+ async def test_invented_id_is_refused(self) -> None:
+ with pytest.raises(HTTPException) as excinfo:
+ await _require_directory_account(
+ _StubLifecycle([_directory_user("U-real")]),
+ bridge_id="b1",
+ external_user_id="U-invented",
+ username="someone",
+ )
+ assert excinfo.value.status_code == 404
+
+ async def test_platform_without_a_directory_is_refused(self) -> None:
+ # Nothing can be checked, so the person has to be seen speaking first
+ # rather than have a puppet minted on their behalf.
+ with pytest.raises(HTTPException) as excinfo:
+ await _require_directory_account(
+ _StubLifecycle(NotImplementedError("no searchable directory")),
+ bridge_id="b1",
+ external_user_id="U123",
+ username="someone",
+ )
+ assert excinfo.value.status_code == 501
+
+ async def test_stopped_bridge_is_refused(self) -> None:
+ with pytest.raises(HTTPException) as excinfo:
+ await _require_directory_account(
+ _StubLifecycle(None),
+ bridge_id="b1",
+ external_user_id="U123",
+ username="someone",
+ )
+ assert excinfo.value.status_code == 409
+
+
+def _directory_user(external_user_id: str) -> DirectoryUser:
+ return DirectoryUser(
+ external_user_id=external_user_id,
+ username="someone",
+ display_name="Someone",
+ email=None,
+ )
+
+
+class _StubLifecycle:
+ """Holds an adapter that returns the given directory results, raises the
+ given error, or is absent entirely (a stopped bridge)."""
+
+ def __init__(self, result: list[DirectoryUser] | Exception | None) -> None:
+ self._result = result
+
+ def get_adapter(self, _bridge_id: str) -> object | None:
+ return None if self._result is None else self
+
+ async def search_directory_users(self, _query: str) -> list[DirectoryUser]:
+ if isinstance(self._result, Exception):
+ raise self._result
+ assert self._result is not None
+ return self._result
+
+
+class _StubGet:
+ def __init__(self, value: object) -> None:
+ self._value = value
+
+ async def get(self, *_args: object, **_kwargs: object) -> object:
+ return self._value
+
+
+def _user(*, id: str, role: str) -> SimpleNamespace:
+ return SimpleNamespace(id=id, role=role, name=id)
+
+
def test_known_bridge_write_routes_are_present() -> None:
"""Guard against the check above passing vacuously if a route is renamed or
dropped: the four writes we know about must still exist."""
@@ -151,6 +304,10 @@ class _NoRunningBridges:
live adapter."""
return True
+ def supports_directory_search(self, bridge_type: str) -> bool:
+ """Read from the adapter class for the same reason."""
+ return True
+
async def test_set_default_promotes_and_demotes(
session_factory: async_sessionmaker[AsyncSession],
diff --git a/core/tests/switch_core/gateway/test_directory_fallback.py b/core/tests/switch_core/gateway/test_directory_fallback.py
new file mode 100644
index 000000000..d4cd15109
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_directory_fallback.py
@@ -0,0 +1,213 @@
+"""Claiming an identity on a platform with no searchable directory (CHOO-2137).
+
+Telegram is the case that exposed this. A bot there can only see who has spoken
+to it, so `search_directory_users` raises — and the endpoint used to turn that
+into a 501, leaving the link dialog with a warning and nothing to pick. Switch
+knew perfectly well who those people were; it just refused to say. Owner-only
+addressing was therefore unreachable on the platform, which is the failure the
+whole feature exists to prevent.
+
+The search now falls back to the accounts Switch has already recorded, and says
+so. It is a narrower answer, not an error — and the response has to admit the
+difference, because presenting it as a whole-workspace search would tell the
+user that someone who has never spoken does not exist.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from switch_core.bridges.collaboration.models import DirectoryUser
+from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapter
+from switch_core.gateway.collaborations import (
+ _known_as_directory_users,
+ search_bridge_directory,
+)
+
+NO_DIRECTORY = NotImplementedError(
+ "Telegram has no searchable user directory — on this platform someone must "
+ "send a message before Switch knows them"
+)
+
+
+def _known(external_user_id: str, username: str) -> SimpleNamespace:
+ """An `ExternalUser` row, with only the fields the fallback reads."""
+ return SimpleNamespace(
+ id=f"row-{external_user_id}",
+ bridge_id="b1",
+ external_user_id=external_user_id,
+ external_username=username,
+ )
+
+
+class _StubLifecycle:
+ def __init__(self, result: list[DirectoryUser] | Exception | None) -> None:
+ self._result = result
+
+ def get_adapter(self, _bridge_id: str) -> object | None:
+ return None if self._result is None else self
+
+ async def search_directory_users(self, _query: str) -> list[DirectoryUser]:
+ if isinstance(self._result, Exception):
+ raise self._result
+ assert self._result is not None
+ return self._result
+
+
+class _StubExternalUserStore:
+ def __init__(self, rows: list[SimpleNamespace]) -> None:
+ self._rows = rows
+
+ async def get_by_bridge(
+ self, _session: object, _bridge_id: str
+ ) -> list[SimpleNamespace]:
+ return self._rows
+
+ async def claimant_ids_for(
+ self, _session: object, _row_ids: list[str]
+ ) -> dict[str, list[str]]:
+ return {}
+
+
+class _StubBridgeStore:
+ async def get(self, _session: object, _bridge_id: str) -> object:
+ return SimpleNamespace(id="b1", display_name="Telegram louis")
+
+
+class _StubUserStore:
+ async def get_all(self, _session: object) -> list[object]:
+ return []
+
+
+async def _search(
+ *,
+ adapter_result: list[DirectoryUser] | Exception | None,
+ known: list[SimpleNamespace],
+ query: str = "lou",
+) -> object:
+ return await search_bridge_directory(
+ "b1",
+ query,
+ None, # type: ignore[arg-type]
+ _StubBridgeStore(), # type: ignore[arg-type]
+ _StubExternalUserStore(known), # type: ignore[arg-type]
+ _StubUserStore(), # type: ignore[arg-type]
+ _StubLifecycle(adapter_result), # type: ignore[arg-type]
+ SimpleNamespace(id="u1", role="user", name="u1"), # type: ignore[arg-type]
+ )
+
+
+class TestFallsBackToWhoSwitchHasSeen:
+ async def test_a_platform_without_a_directory_still_answers(self) -> None:
+ # The whole point: a 501 here is what made Telegram unusable.
+ result = await _search(
+ adapter_result=NO_DIRECTORY,
+ known=[_known("11", "louis"), _known("22", "someone-else")],
+ )
+
+ assert [u.username for u in result.users] == ["louis"]
+
+ async def test_it_says_the_answer_is_narrower(self) -> None:
+ # Without this the caller cannot tell a whole-workspace search from the
+ # handful of people who happen to have spoken.
+ result = await _search(
+ adapter_result=NO_DIRECTORY, known=[_known("11", "louis")]
+ )
+
+ assert result.source == "known"
+ assert result.note is not None
+ assert "send a message" in result.note
+
+ async def test_the_row_id_is_carried_so_the_claim_reuses_it(self) -> None:
+ # An account Switch already has must not be provisioned a second time.
+ result = await _search(
+ adapter_result=NO_DIRECTORY, known=[_known("11", "louis")]
+ )
+
+ assert result.users[0].known_external_user_id == "row-11"
+
+ async def test_nobody_seen_yet_is_an_empty_list_not_an_error(self) -> None:
+ result = await _search(adapter_result=NO_DIRECTORY, known=[])
+
+ assert result.users == []
+ assert result.source == "known"
+
+
+class TestAPlatformWithADirectoryIsUnaffected:
+ async def test_it_reports_the_directory_as_the_source(self) -> None:
+ found = [
+ DirectoryUser(
+ external_user_id="U1",
+ username="louis",
+ display_name="Louis A",
+ )
+ ]
+ result = await _search(adapter_result=found, known=[])
+
+ assert result.source == "directory"
+ assert result.note is None
+ assert [u.email for u in result.users] == ["[email protected]"]
+
+ async def test_a_platform_that_failed_still_raises(self) -> None:
+ # A refusal from Slack is not "nobody has spoken here" — turning it into
+ # the fallback would report a broken workspace as an empty one.
+ with pytest.raises(HTTPException) as excinfo:
+ await _search(adapter_result=RuntimeError("slack said no"), known=[])
+ assert excinfo.value.status_code == 502
+
+ async def test_a_stopped_bridge_still_refuses(self) -> None:
+ with pytest.raises(HTTPException) as excinfo:
+ await _search(adapter_result=None, known=[])
+ assert excinfo.value.status_code == 409
+
+
+class TestMatchingKnownAccounts:
+ def test_matches_anywhere_in_the_handle(self) -> None:
+ # Prefix matching would hide someone whose handle starts with a team
+ # prefix, and this list is the last resort — not finding yourself in it
+ # is the end of the road.
+ found = _known_as_directory_users([_known("11", "team-louis")], "louis")
+
+ assert [u.username for u in found] == ["team-louis"]
+
+ def test_ignores_case(self) -> None:
+ found = _known_as_directory_users([_known("11", "Louis")], "lOuIs")
+
+ assert len(found) == 1
+
+ def test_a_blank_query_matches_nobody(self) -> None:
+ # Returning the entire workspace for an empty box is not a search.
+ found = _known_as_directory_users([_known("11", "louis")], " ")
+
+ assert found == []
+
+ def test_results_are_ordered_by_name_regardless_of_case(self) -> None:
+ rows = [_known("1", "zoe-a"), _known("2", "Adam-a"), _known("3", "mia-a")]
+
+ found = _known_as_directory_users(rows, "-a")
+
+ assert [u.username for u in found] == ["Adam-a", "mia-a", "zoe-a"]
+
+ def test_carries_no_email_it_cannot_know(self) -> None:
+ # The row is built from a message, which carries no address. Inventing
+ # one would put a wrong address next to a face in the picker.
+ found = _known_as_directory_users([_known("11", "louis")], "lou")
+
+ assert found[0].email is None
+
+
+async def test_the_platform_names_itself_in_the_refusal() -> None:
+ """The refusal is shown verbatim in the link dialog, so it has to name the
+ platform a person would recognise — it read "TelegramAdapter has no
+ searchable user directory" on screen."""
+ adapter = TelegramAdapter.__new__(TelegramAdapter)
+
+ with pytest.raises(NotImplementedError) as excinfo:
+ await adapter.search_directory_users("lou")
+
+ assert str(excinfo.value).startswith("Telegram has no searchable user directory")
+ assert "Adapter" not in str(excinfo.value)
diff --git a/core/tests/switch_core/gateway/test_known_agents.py b/core/tests/switch_core/gateway/test_known_agents.py
index 3cf196045..4cf1674e6 100644
--- a/core/tests/switch_core/gateway/test_known_agents.py
+++ b/core/tests/switch_core/gateway/test_known_agents.py
@@ -65,7 +65,9 @@ class TestBuildProfileCommandCapabilities:
class TestStartSessionInstructions:
def test_channels_enabled_appends_dev_flag_after_prompt(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/Users/x/aq-switch")
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
# The flag must come AFTER the prompt argument so claude treats the
# quoted text as the initial prompt, not as a value for the flag.
@@ -78,7 +80,9 @@ class TestStartSessionInstructions:
def test_channels_disabled_passive_message_shape(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/srv/agent")
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "ops")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "ops", None
+ )
assert msg is not None
assert "--dangerously-load-development-channels" not in msg
# The connect prompt itself instructs a pull (passive sessions get no
@@ -93,7 +97,9 @@ class TestStartSessionInstructions:
def test_channels_enabled_is_not_passive_shaped(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/srv/agent")
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "ops")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "ops", None
+ )
assert msg is not None
assert "pull the latest messages" not in msg
assert "Anthropic API key or subscription" not in msg
@@ -105,7 +111,9 @@ class TestStartSessionInstructions:
opts = ClaudeCodeOptions(
channels_enabled=False, auto_session=True, repo_dir="/srv/agent"
)
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "ops")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "ops", None
+ )
assert msg is not None
assert "--dangerously-load-development-channels" not in msg
assert (
@@ -116,7 +124,7 @@ class TestStartSessionInstructions:
def test_connected_not_live_opening(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/srv/agent")
msg = ClaudeCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", connected_not_live=True
+ opts, _agent({}), "ops", None, connected_not_live=True
)
assert msg is not None
# Acknowledges a connected-but-not-live session and steers to relaunch
@@ -129,7 +137,7 @@ class TestStartSessionInstructions:
def test_no_repo_dir_uses_placeholder(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=True, repo_dir=None)
msg = ClaudeCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "triage"
+ opts, _agent({}), "triage", None
)
assert msg is not None
assert "cd <claude-dir>" in msg
@@ -143,39 +151,47 @@ class TestStartSessionInstructions:
opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="")
assert opts.repo_dir is None
msg = ClaudeCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "triage"
+ opts, _agent({}), "triage", None
)
assert msg is not None
assert "cd <claude-dir>" in msg
- def test_notify_user_is_prepended_as_at_mention(self) -> None:
- opts = ClaudeCodeOptions(
- channels_enabled=True, repo_dir="/x", notify_user="louisa"
+ def test_the_owner_is_prepended_as_an_at_mention(self) -> None:
+ # The handle is the owner's account on the platform this room is
+ # bridged to, resolved by the caller (CHOO-2137) — it used to be a
+ # single string configured on the agent, which could only ever be
+ # right on one platform.
+ opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/x")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", "louisa"
)
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
assert msg is not None
assert msg.startswith("@louisa\n\n")
- def test_empty_string_notify_user_normalised_to_none(self) -> None:
- opts = ClaudeCodeOptions(channels_enabled=True, notify_user="")
- assert opts.notify_user is None
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ def test_an_unlinked_owner_leaves_the_message_unmentioned(self) -> None:
+ # Nobody to mention is not a reason to withhold the instructions.
+ opts = ClaudeCodeOptions(channels_enabled=True)
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert not msg.startswith("@")
def test_passive_mentions_operator_inline(self) -> None:
# Passive message names the operator inline ("my operator @louisa")
# rather than as a leading prefix, so they still get pinged to pull.
- opts = ClaudeCodeOptions(
- channels_enabled=False, repo_dir="/x", notify_user="louisa"
+ opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/x")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", "louisa"
)
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
assert msg is not None
assert "my operator @louisa" in msg
- def test_passive_without_notify_user_says_my_operator(self) -> None:
+ def test_passive_without_a_linked_owner_says_my_operator(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/x")
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert "my operator has to trigger me" in msg
assert "@" not in msg
@@ -186,7 +202,9 @@ class TestStartSessionInstructions:
repo_dir="/Users/x/repo",
subagent_name="seo-writer",
)
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
# --agent / --settings come after the quoted prompt and before the
# dev-channels flag; the settings path matches what the configure skill
@@ -203,7 +221,9 @@ class TestStartSessionInstructions:
opts = ClaudeCodeOptions(
channels_enabled=False, repo_dir="/r", subagent_name="reviewer"
)
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "ops")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "ops", None
+ )
assert msg is not None
assert "--agent reviewer" in msg
assert "--settings .claude/switch-subagents/reviewer.settings.json" in msg
@@ -211,7 +231,9 @@ class TestStartSessionInstructions:
def test_no_subagent_name_omits_agent_flag(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/r")
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert "--agent" not in msg
assert "switch-subagents" not in msg
@@ -219,7 +241,9 @@ class TestStartSessionInstructions:
def test_empty_string_subagent_name_normalised_to_none(self) -> None:
opts = ClaudeCodeOptions(channels_enabled=True, subagent_name="")
assert opts.subagent_name is None
- msg = ClaudeCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = ClaudeCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert "--agent" not in msg
@@ -228,7 +252,7 @@ class TestStartSessionInstructions:
# message reads the same regardless of where it's posted.
opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/x")
msg = ClaudeCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "Some Long Room Name"
+ opts, _agent({}), "Some Long Room Name", None
)
assert msg is not None
# The room name still appears once inside the quoted `connect to switch
@@ -275,7 +299,7 @@ class TestCodexKnownAgent:
def test_start_session_instructions_emit_codex_not_claude(self) -> None:
opts = CodexOptions(repo_dir="/Users/x/repo")
- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub", None)
assert msg is not None
# The path is quoted so a repo_dir with spaces still produces a valid
# paste command.
@@ -290,14 +314,14 @@ class TestCodexKnownAgent:
def test_repo_dir_with_spaces_stays_quoted(self) -> None:
opts = CodexOptions(repo_dir="/Users/alice/my project")
- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub", None)
assert msg is not None
assert 'cd "/Users/alice/my project" && codex' in msg
def test_connected_not_live_opening(self) -> None:
opts = CodexOptions(repo_dir="/r")
msg = CodexKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", connected_not_live=True
+ opts, _agent({}), "ops", None, connected_not_live=True
)
assert msg is not None
assert "isn't reporting" in msg
@@ -307,7 +331,7 @@ class TestCodexKnownAgent:
def test_other_room_names_branch(self) -> None:
opts = CodexOptions(repo_dir="/r")
msg = CodexKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", other_room_names=["hub", "triage"]
+ opts, _agent({}), "ops", None, other_room_names=["hub", "triage"]
)
assert msg is not None
assert "**hub**" in msg
@@ -317,7 +341,7 @@ class TestCodexKnownAgent:
def test_assume_role_folded_into_prompt(self) -> None:
opts = CodexOptions(repo_dir="/r")
msg = CodexKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", assume_role="reviewer"
+ opts, _agent({}), "ops", None, assume_role="reviewer"
)
assert msg is not None
assert 'codex "connect to switch room ops and assume the role reviewer"' in msg
@@ -325,27 +349,30 @@ class TestCodexKnownAgent:
def test_empty_string_repo_dir_normalised_to_placeholder(self) -> None:
opts = CodexOptions(repo_dir="")
assert opts.repo_dir is None
- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "triage")
+ msg = CodexKnownAgent.start_session_instructions(
+ opts, _agent({}), "triage", None
+ )
assert msg is not None
assert 'cd "<codex-dir>"' in msg
- def test_empty_string_notify_user_normalised_to_none(self) -> None:
- opts = CodexOptions(notify_user="")
- assert opts.notify_user is None
- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ def test_an_unlinked_owner_leaves_the_message_unmentioned(self) -> None:
+ opts = CodexOptions()
+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub", None)
assert msg is not None
assert not msg.startswith("@")
def test_no_repo_dir_uses_codex_placeholder(self) -> None:
msg = CodexKnownAgent.start_session_instructions(
- CodexOptions(repo_dir=None), _agent({}), "triage"
+ CodexOptions(repo_dir=None), _agent({}), "triage", None
)
assert msg is not None
assert 'cd "<codex-dir>"' in msg
- def test_notify_user_prepended_as_at_mention(self) -> None:
- opts = CodexOptions(repo_dir="/x", notify_user="cmcd")
- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ def test_the_owner_is_prepended_as_an_at_mention(self) -> None:
+ opts = CodexOptions(repo_dir="/x")
+ msg = CodexKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", "cmcd"
+ )
assert msg is not None
assert msg.startswith("@cmcd\n\n")
@@ -421,7 +448,9 @@ class TestOpenCodeKnownAgent:
# `opencode "connect to switch room hub"` asks it to open a directory of
# that name. The prompt must go through --prompt.
opts = OpenCodeOptions(repo_dir="/Users/x/repo")
- msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert (
'cd "/Users/x/repo" && opencode --prompt "connect to switch room hub"'
@@ -431,7 +460,9 @@ class TestOpenCodeKnownAgent:
def test_start_session_instructions_emit_opencode_only(self) -> None:
opts = OpenCodeOptions(repo_dir="/Users/x/repo")
- msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert "claude" not in msg
assert "codex" not in msg
@@ -441,14 +472,16 @@ class TestOpenCodeKnownAgent:
def test_repo_dir_with_spaces_stays_quoted(self) -> None:
opts = OpenCodeOptions(repo_dir="/Users/alice/my project")
- msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert 'cd "/Users/alice/my project" && opencode' in msg
def test_assume_role_is_folded_into_the_prompt(self) -> None:
opts = OpenCodeOptions(repo_dir="/r")
msg = OpenCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", assume_role="reviewer"
+ opts, _agent({}), "ops", None, assume_role="reviewer"
)
assert msg is not None
assert (
@@ -457,27 +490,31 @@ class TestOpenCodeKnownAgent:
def test_blank_repo_dir_uses_placeholder(self) -> None:
msg = OpenCodeKnownAgent.start_session_instructions(
- OpenCodeOptions(repo_dir=""), _agent({}), "triage"
+ OpenCodeOptions(repo_dir=""), _agent({}), "triage", None
)
assert msg is not None
assert 'cd "<opencode-dir>"' in msg
def test_no_repo_dir_uses_placeholder(self) -> None:
msg = OpenCodeKnownAgent.start_session_instructions(
- OpenCodeOptions(repo_dir=None), _agent({}), "triage"
+ OpenCodeOptions(repo_dir=None), _agent({}), "triage", None
)
assert msg is not None
assert 'cd "<opencode-dir>"' in msg
- def test_blank_notify_user_produces_no_mention(self) -> None:
- opts = OpenCodeOptions(notify_user="")
- msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ def test_an_unlinked_owner_produces_no_mention(self) -> None:
+ opts = OpenCodeOptions()
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", None
+ )
assert msg is not None
assert not msg.startswith("@")
- def test_notify_user_is_mentioned(self) -> None:
- opts = OpenCodeOptions(repo_dir="/x", notify_user="cmcd")
- msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ def test_the_owner_is_mentioned(self) -> None:
+ opts = OpenCodeOptions(repo_dir="/x")
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "hub", "cmcd"
+ )
assert msg is not None
assert msg.startswith("@cmcd")
diff --git a/core/tests/switch_core/gateway/test_subagent_registration.py b/core/tests/switch_core/gateway/test_subagent_registration.py
index d9a7a915f..418298076 100644
--- a/core/tests/switch_core/gateway/test_subagent_registration.py
+++ b/core/tests/switch_core/gateway/test_subagent_registration.py
@@ -16,19 +16,17 @@ class TestInheritedParentOptions:
"known_agent_options": {
"channels_enabled": False,
"repo_dir": "/repo",
- "notify_user": "alice",
"subagent_name": "should-not-inherit",
}
}
assert inherited_parent_options(md) == {
"channels_enabled": False,
"repo_dir": "/repo",
- "notify_user": "alice",
}
def test_skips_none_values(self) -> None:
- md = {"known_agent_options": {"repo_dir": None, "notify_user": "bob"}}
- assert inherited_parent_options(md) == {"notify_user": "bob"}
+ md = {"known_agent_options": {"repo_dir": None, "channels_enabled": True}}
+ assert inherited_parent_options(md) == {"channels_enabled": True}
def test_empty_when_metadata_missing_or_malformed(self) -> None:
assert inherited_parent_options(None) == {}
diff --git a/core/tests/switch_core/test_addressing.py b/core/tests/switch_core/test_addressing.py
index f8c00df86..78d0c7fc9 100644
--- a/core/tests/switch_core/test_addressing.py
+++ b/core/tests/switch_core/test_addressing.py
@@ -7,12 +7,22 @@ from switch_core.addressing import (
AddressingPolicy,
AddressingRule,
can_address,
+ owner_and_owner_agents_policy,
+ owner_only_policy,
parse_policy,
)
def _allows(policy: AddressingPolicy, **kw: object) -> bool:
- defaults = dict(room_id="room-1", group_id=None, sender_kind="user", sender_id="u1")
+ defaults = dict(
+ room_id="room-1",
+ group_id=None,
+ sender_kind="user",
+ sender_id="u1",
+ sender_user_ids=[],
+ sender_owner_user_id=None,
+ owner_user_id=None,
+ )
defaults.update(kw)
return can_address(policy, **defaults) # type: ignore[arg-type]
@@ -125,6 +135,477 @@ class TestMultipleRules:
)
+class TestOwnerRule:
+ """`owner=True` admits the agent's owner as a symbolic subject, resolved
+ at enforcement time from `owner_user_id` and the set of Switch users who
+ have claimed the sender's platform account."""
+
+ def _policy(self) -> AddressingPolicy:
+ # Owner and nobody else: no other human, no agent.
+ return AddressingPolicy(rules=[AddressingRule(users=[], agents=[], owner=True)])
+
+ def test_owner_matches(self) -> None:
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+
+ def test_different_user_denied(self) -> None:
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="user",
+ sender_id="ext-9",
+ sender_user_ids=["user-2"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_owner_among_several_claimants_matches(self) -> None:
+ # Claiming is not exclusive: a shared or duplicated account may be
+ # claimed by several Switch users, and the owner need only be one of
+ # them. Requiring them to be the sole claimant would let anyone else
+ # deny the owner their own agent just by claiming the account too.
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-2", "user-1", "user-3"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+
+ def test_claimants_without_the_owner_denied(self) -> None:
+ # Claimed, just not by the owner — a stranger's claim admits nobody.
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="user",
+ sender_id="ext-9",
+ sender_user_ids=["user-2", "user-3"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_ownerless_agent_denies(self) -> None:
+ # No owner to match against — not a permissive guess.
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-1"],
+ owner_user_id=None,
+ )
+ is False
+ )
+
+ def test_unclaimed_identity_denies(self) -> None:
+ # The platform identity belongs to no Switch user, so it cannot be
+ # recognised as the owner even if the human behind it is.
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=[],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_both_none_denies(self) -> None:
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=[],
+ owner_user_id=None,
+ )
+ is False
+ )
+
+ def test_agent_sender_is_never_the_owner(self) -> None:
+ # An agent owned by the same person is still just an agent: it must be
+ # admitted through `agents`, never through `owner`.
+ assert (
+ _allows(
+ self._policy(),
+ sender_kind="agent",
+ sender_id="agent-7",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_owner_still_scoped_by_room(self) -> None:
+ # `owner` widens the sender dimension, not the room/group ones.
+ policy = AddressingPolicy(
+ rules=[AddressingRule(rooms=["r1"], users=[], agents=[], owner=True)]
+ )
+ assert (
+ _allows(
+ policy,
+ room_id="r1",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+ assert (
+ _allows(
+ policy,
+ room_id="r2",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_owner_flag_off_ignores_the_ids(self) -> None:
+ policy = AddressingPolicy(rules=[AddressingRule(users=[], agents=[])])
+ assert (
+ _allows(
+ policy,
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+
+class TestOwnerAgentsRule:
+ """`owner_agents`: any agent the target's owner also owns (CHOO-2137).
+
+ The counterpart to `owner` on the other side of the sender split. It exists
+ because an owner's orchestration is the owner acting: a manager agent
+ handing work to a worker both belong to the same person, and listing each
+ one by id goes stale the next time they register one.
+ """
+
+ OWNED = AddressingPolicy(
+ rules=[AddressingRule(users=[], agents=[], owner_agents=True)]
+ )
+
+ def test_an_agent_of_the_same_owner_is_admitted(self) -> None:
+ assert (
+ _allows(
+ self.OWNED,
+ sender_kind="agent",
+ sender_id="manager",
+ sender_owner_user_id="user-1",
+ owner_user_id="user-1",
+ )
+ is True
+ )
+
+ def test_somebody_elses_agent_is_not(self) -> None:
+ assert (
+ _allows(
+ self.OWNED,
+ sender_kind="agent",
+ sender_id="their-manager",
+ sender_owner_user_id="user-2",
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_an_unowned_sender_does_not_inherit_the_fleet(self) -> None:
+ # Ownerless is not a wildcard. An agent registered without an owner
+ # must not slip into every owner-scoped policy at once.
+ assert (
+ _allows(
+ self.OWNED,
+ sender_kind="agent",
+ sender_id="orphan",
+ sender_owner_user_id=None,
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_an_unowned_target_admits_nobody_this_way(self) -> None:
+ # Two ownerless agents are not each other's, and matching None to None
+ # would make them so.
+ assert (
+ _allows(
+ self.OWNED,
+ sender_kind="agent",
+ sender_id="orphan",
+ sender_owner_user_id=None,
+ owner_user_id=None,
+ )
+ is False
+ )
+
+ def test_it_does_not_let_the_owner_in_as_a_human(self) -> None:
+ # The two subjects are separate on purpose: "my agents may" is not
+ # "I may". Only `owner` admits the person.
+ assert (
+ _allows(
+ self.OWNED,
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_it_is_still_scoped_by_room(self) -> None:
+ policy = AddressingPolicy(
+ rules=[AddressingRule(rooms=["r1"], users=[], agents=[], owner_agents=True)]
+ )
+ for room, expected in (("r1", True), ("r2", False)):
+ assert (
+ _allows(
+ policy,
+ room_id=room,
+ sender_kind="agent",
+ sender_id="manager",
+ sender_owner_user_id="user-1",
+ owner_user_id="user-1",
+ )
+ is expected
+ )
+
+ def test_off_by_default_for_a_policy_written_before_it_existed(self) -> None:
+ # Stored policies carry no `owner_agents` key. Reading absence as true
+ # would quietly widen every existing owner-only agent.
+ policy = parse_policy({"rules": [{"users": [], "agents": [], "owner": True}]})
+ assert policy.rules[0].owner_agents is False
+ assert (
+ _allows(
+ policy,
+ sender_kind="agent",
+ sender_id="manager",
+ sender_owner_user_id="user-1",
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+
+class TestOwnerAndOwnerAgentsPolicy:
+ """The shape a Switch Console agent is created on."""
+
+ def test_admits_the_owner_and_their_agents(self) -> None:
+ policy = owner_and_owner_agents_policy()
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+ assert (
+ _allows(
+ policy,
+ sender_kind="agent",
+ sender_id="manager",
+ sender_owner_user_id="user-1",
+ owner_user_id="user-1",
+ )
+ is True
+ )
+
+ def test_and_nobody_else(self) -> None:
+ policy = owner_and_owner_agents_policy()
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="ext-9",
+ sender_user_ids=["user-2"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+ assert (
+ _allows(
+ policy,
+ sender_kind="agent",
+ sender_id="their-agent",
+ sender_owner_user_id="user-2",
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_shape(self) -> None:
+ assert owner_and_owner_agents_policy().model_dump() == {
+ "rules": [
+ {
+ "rooms": "*",
+ "room_groups": "*",
+ "users": [],
+ "agents": [],
+ "owner": True,
+ "owner_agents": True,
+ }
+ ]
+ }
+
+
+class TestOwnerOnlyPolicy:
+ """Strictly the owner: the narrower of the two shortcuts."""
+
+ def test_admits_only_the_owner(self) -> None:
+ policy = owner_only_policy([])
+ assert policy.is_open() is False
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="ext-9",
+ sender_user_ids=["user-2"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+ assert (
+ _allows(
+ policy,
+ sender_kind="agent",
+ sender_id="agent-7",
+ sender_user_ids=[],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+
+ def test_allowed_agent_is_let_in(self) -> None:
+ # How a dispatcher (manager / orchestrator) is granted access.
+ policy = owner_only_policy(["dispatcher"])
+ assert (
+ _allows(
+ policy,
+ sender_kind="agent",
+ sender_id="dispatcher",
+ sender_user_ids=[],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+ assert (
+ _allows(
+ policy,
+ sender_kind="agent",
+ sender_id="other-agent",
+ sender_user_ids=[],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+ # Still owner-only on the human side.
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="dispatcher",
+ sender_user_ids=["user-2"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+
+ def test_applies_in_every_room(self) -> None:
+ policy = owner_only_policy([])
+ assert (
+ _allows(
+ policy,
+ room_id="any-room",
+ group_id="any-group",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+ assert (
+ _allows(
+ policy,
+ room_id="other-room",
+ group_id=None,
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+
+ def test_shape(self) -> None:
+ assert owner_only_policy(["a1"]).model_dump() == {
+ "rules": [
+ {
+ "rooms": "*",
+ "room_groups": "*",
+ "users": [],
+ "agents": ["a1"],
+ "owner": True,
+ "owner_agents": False,
+ }
+ ]
+ }
+
+
+class TestRequiresOwnerIdentity:
+ """Flags a policy that admits nobody until the owner claims an identity."""
+
+ def test_false_when_open(self) -> None:
+ assert AddressingPolicy().requires_owner_identity() is False
+
+ def test_false_without_owner_rules(self) -> None:
+ policy = AddressingPolicy(rules=[AddressingRule(users=["u1"], agents=[])])
+ assert policy.requires_owner_identity() is False
+
+ def test_true_when_any_rule_is_owner_scoped(self) -> None:
+ policy = AddressingPolicy(
+ rules=[
+ AddressingRule(users=["u1"], agents=[]),
+ AddressingRule(users=[], agents=[], owner=True),
+ ]
+ )
+ assert policy.requires_owner_identity() is True
+
+ def test_true_for_owner_only_policy(self) -> None:
+ assert owner_only_policy([]).requires_owner_identity() is True
+
+
class TestValidation:
def test_rejects_bad_dimension_scalar(self) -> None:
with pytest.raises(ValidationError):
@@ -139,3 +620,12 @@ class TestValidation:
rules=[AddressingRule(rooms=["r1"], users=["u1"], agents=[])]
)
assert parse_policy(policy.model_dump()) == policy
+
+ def test_owner_flag_roundtrips(self) -> None:
+ policy = owner_only_policy(["a1"])
+ assert parse_policy(policy.model_dump()) == policy
+
+ def test_stored_policy_without_owner_key_defaults_to_false(self) -> None:
+ # A pre-CHOO-2137 blob has no `owner` key; it must not become truthy.
+ policy = parse_policy({"rules": [{"users": ["u1"], "agents": []}]})
+ assert policy.requires_owner_identity() is False
diff --git a/core/tests/switch_core/test_dm_rooms.py b/core/tests/switch_core/test_dm_rooms.py
index a41e5cdd4..619861ee6 100644
--- a/core/tests/switch_core/test_dm_rooms.py
+++ b/core/tests/switch_core/test_dm_rooms.py
@@ -165,10 +165,13 @@ async def test_create_dm_room_refused_when_operator_withheld_channel_creation()
async def test_base_adapter_rejects_dm_channel_creation() -> None:
# The default raises so platforms whose DMs are user-initiated (Mattermost)
- # fail loud rather than silently no-op.
- with pytest.raises(ChannelCreationUnsupported, match="cannot create DM channels"):
+ # fail loud rather than silently no-op. The refusal reaches whoever asked
+ # for the room, so it names the platform rather than its adapter class.
+ with pytest.raises(
+ ChannelCreationUnsupported, match="Mattermost cannot create DM channels"
+ ):
await CollaborationAdapter.create_dm_channel(
- SimpleNamespace(),
+ SimpleNamespace(platform_name="Mattermost"),
agent_name="a",
user_name="u",
user_external_id="U1",
diff --git a/core/tests/switch_core/test_migration_chain.py b/core/tests/switch_core/test_migration_chain.py
new file mode 100644
index 000000000..10108b0c8
--- /dev/null
+++ b/core/tests/switch_core/test_migration_chain.py
@@ -0,0 +1,79 @@
+"""The migration chain is well-formed.
+
+The test suite builds its schema with `Base.metadata.create_all`, so nothing
+else here ever loads the migrations — a duplicated revision id or a second
+head passes every other test and only fails on a real deployment. These are
+cheap enough to run everywhere and catch exactly that class of mistake.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from pathlib import Path
+
+from alembic.config import Config
+from alembic.script import ScriptDirectory
+
+_CORE = Path(__file__).resolve().parents[2]
+_VERSIONS = _CORE / "switch_core" / "migrations" / "versions"
+
+_REVISION_RE = re.compile(r'^revision: str = "([^"]+)"', re.MULTILINE)
+
+
+def _script_directory() -> ScriptDirectory:
+ config = Config(str(_CORE / "alembic.ini"))
+ config.set_main_option("script_location", str(_CORE / "switch_core" / "migrations"))
+ return ScriptDirectory.from_config(config)
+
+
+def test_revision_ids_are_unique() -> None:
+ """Two files declaring the same revision id make the graph ambiguous.
+
+ Read from the files rather than through Alembic: Alembic resolves the
+ collision itself and the duplicate would go unnoticed here.
+ """
+ by_revision: dict[str, list[str]] = defaultdict(list)
+ for path in _VERSIONS.glob("*.py"):
+ match = _REVISION_RE.search(path.read_text())
+ if match is not None:
+ by_revision[match.group(1)].append(path.name)
+
+ duplicates = {rev: files for rev, files in by_revision.items() if len(files) > 1}
+ assert not duplicates, f"duplicate migration revision ids: {duplicates}"
+
+
+def test_single_head() -> None:
+ """Two heads mean `alembic upgrade head` is ambiguous and deployment fails."""
+ heads = _script_directory().get_heads()
+ assert len(heads) == 1, f"expected exactly one migration head, got {heads}"
+
+
+def test_every_down_revision_exists() -> None:
+ """A migration pointing at a revision that was renamed or removed breaks
+ the walk, and does so only when the chain is actually replayed."""
+ script = _script_directory()
+ known = {revision.revision for revision in script.walk_revisions()}
+ dangling = {
+ revision.revision: revision.down_revision
+ for revision in script.walk_revisions()
+ if revision.down_revision is not None and revision.down_revision not in known
+ }
+ assert not dangling, f"migrations pointing at unknown parents: {dangling}"
+
+
+def test_filename_matches_revision_id() -> None:
+ """The `<revision>_<slug>.py` convention is what makes a duplicate visible
+ in a directory listing; a file whose name has drifted from its id hides
+ one."""
+ mismatched: dict[str, str] = {}
+ for path in _VERSIONS.glob("*.py"):
+ match = _REVISION_RE.search(path.read_text())
+ if match is None:
+ continue
+ revision = match.group(1)
+ if not path.name.startswith(f"{revision}_"):
+ mismatched[path.name] = revision
+ assert not mismatched, (
+ f"migration filenames disagree with their revision ids: {mismatched}"
+ )
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 9c7760223..8dc6999be 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -204,14 +204,42 @@ agent (by `@name`, room alias, or a held role), and enqueues an `AgentEvent`.
An agent may carry a **scoped addressing policy** (`Agent.addressing_policy`, see
[`addressing.py`](../core/switch_core/addressing.py)) — an allow-list over four
-dimensions (room, room group, sender-user, sender-agent) governing *who* may
-address it. With no policy an agent is open to any room participant (today's
-behaviour). When a policy is set and the sender is not permitted, `AgentClient`
-demotes the message to unaddressed room chatter and posts a one-shot reply to the
-sender; `delegate_task` (an explicit, tracked addressing vector) instead fails
-loud with a `PermissionError`. Configured via
-`PUT /gateway/agents/{id}/addressing-policy` — a gateway route under cookie-JWT
-auth with an owner-or-admin check, not an agent-facing one.
+dimensions (room, room group, sender-user, sender-agent) plus two symbolic
+subjects resolved at delivery, `owner` (the agent's owner, whoever that
+currently is) and `owner_agents` (any agent that same person owns), governing
+*who* may address it. With no policy an agent is open to any room participant;
+agents created since CHOO-2137 instead start **owner-only** — a single rule
+admitting the owner anywhere and nobody else, which the owner can widen to
+their own agents. Pre-existing agents are left open rather than migrated.
+
+A message is never blocked at the sender: `send_targeted_message` posts, and
+reports `not_permitted` for that target instead of a reachability status, so the
+refusal happens in the room where everyone can see it rather than only in the
+sender's account of it. `delegate_task` is the exception and raises — a task is
+a row someone is expected to work, not something a room can decline.
+
+When the sender is not permitted, `AgentClient` demotes the message to
+unaddressed room chatter and posts a one-shot reply to the sender; commands are
+gated the same way (a command naming the agent draws a reply, a room-wide one is
+declined quietly); `delegate_task` and `send_targeted_message` — explicit,
+tracked addressing vectors — instead fail loud with a `PermissionError`.
+
+The `owner` flag is a **symbolic subject resolved at delivery time**, not a
+stored id: `external_user_claims` records which Switch users have claimed a
+platform account, and a human sender matches when the agent's owner is among
+them. Claiming is deliberately **not exclusive** — several Switch users may
+claim the same account — because an exclusive claim would let whoever claimed
+first keep the real person from ever being recognised. An unclaimed account
+matches nobody — fail-closed — and the refusal says so, since an owner refused
+by their own agent with no explanation is the worst failure mode here. Identities are claimed from
+Switch Console against the platform's own user directory
+(`GET /collaborations/{id}/directory`), so someone can be recognised before they
+have ever posted; platforms with no searchable directory answer `501` rather than
+an empty list.
+
+Policies are configured via `PUT /gateway/agents/{id}/addressing-policy` — a
+gateway route under cookie-JWT auth with an owner-or-admin check, not an
+agent-facing one.
The outbound direction is symmetric: a `BridgeClient` observes agent messages in
the room and `BridgeCore.handle_outbound_message` relays them back out under the
diff --git a/docs/api/AGENT_PROTOCOL.md b/docs/api/AGENT_PROTOCOL.md
index 2dd03495d..544c2dcab 100644
--- a/docs/api/AGENT_PROTOCOL.md
+++ b/docs/api/AGENT_PROTOCOL.md
@@ -458,7 +458,15 @@ data: {"type":"message","room_id":"…","bridge_id":"…","channel_type":"channe
`addressed` is computed server-side: true for a `direct` channel, an `@name` or
`@alias` mention, or an `@role` mention whose role this agent holds. The
addressing policy is applied at this point — a mention from a sender not
-permitted to address this agent is demoted to unaddressed.
+permitted to address this agent is demoted to unaddressed, and the sender gets
+a one-shot reply saying so. This is where a refused *message* is refused —
+including one sent with `send_targeted_message`, which posts either way and
+reports `not_permitted` for that target. Only `delegate_task` refuses at the
+sender. Agents created in Switch Console are **owner-only** by default: only
+the Switch user who owns the agent may address it, which the owner can widen to
+every agent they own. A human is recognised as the owner only when they
+have claimed that messaging-app account as theirs; an unclaimed account never
+matches, and the reply says as much rather than leaving them guessing.
Attachments carry a pointer, never bytes; fetch via the media endpoint.