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(bridges): render agents under their display name, defused on every platform (#330)

raullopez-sandboxba55cf93eac7
diff --git a/connectors/claude-code-plugin/skills/configure/SKILL.md b/connectors/claude-code-plugin/skills/configure/SKILL.md
index 021affb6b..b3b71f093 100644
--- a/connectors/claude-code-plugin/skills/configure/SKILL.md
+++ b/connectors/claude-code-plugin/skills/configure/SKILL.md
@@ -253,7 +253,8 @@ in one command, then reference it by name in the next.
Switch validates the name against `^[a-z0-9][a-z0-9._-]*$` — lowercase letters,
digits, dots, hyphens, underscores; must start with a letter or digit. **No
spaces, no `@`, no uppercase.** The name is used in Matrix room handles and
-`@mention` syntax.
+`@mention` syntax; an agent's human-readable display name is a separate
+optional field, so this one only has to route.
Suggest a default that **identifies the user**, not just the repo. Agent names
are visible to everyone in the rooms the agent joins. If two developers both
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index f249e2be1..9cb2011d8 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -352,6 +352,13 @@ none of it is needed to take part in a conversation.
sets the agent's parent (validated against self-parenting and cycles);
`clear_parent=true` detaches it to top-level.
+**Address by `name`, not `display_name`.** `list_agents` and
+`get_agent_detail` return both. `name` is the machine identifier and the only
+one that routes: `target_names`, mentions and room aliases all take it.
+`display_name` is a free-form human label for showing an agent to a person, and
+is null when the agent has none — fall back to `name`. A `target_names` entry
+carrying a display name addresses no one.
+
### Creating rooms
- **`list_bridges`** — the collaboration bridges configured on this instance:
diff --git a/connectors/codex-plugin/skills/configure/SKILL.md b/connectors/codex-plugin/skills/configure/SKILL.md
index 009e5ec63..e2c253b74 100644
--- a/connectors/codex-plugin/skills/configure/SKILL.md
+++ b/connectors/codex-plugin/skills/configure/SKILL.md
@@ -181,7 +181,8 @@ it, never write it to any file.
Switch validates the name against `^[a-z0-9][a-z0-9._-]*$` — lowercase letters,
digits, dots, hyphens, underscores; must start with a letter or digit. **No
spaces, no `@`, no uppercase.** The name is used in Matrix room handles and
-`@mention` syntax.
+`@mention` syntax; an agent's human-readable display name is a separate
+optional field, so this one only has to route.
Suggest a default that **identifies the user**, not just the repo. Agent names
are visible to everyone in the rooms the agent joins. If two developers both
diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.md
index 64ffa6809..691d512dc 100644
--- a/connectors/codex-plugin/skills/switch/SKILL.md
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -350,6 +350,13 @@ none of it is needed to take part in a conversation.
sets the agent's parent (validated against self-parenting and cycles);
`clear_parent=true` detaches it to top-level.
+**Address by `name`, not `display_name`.** `list_agents` and
+`get_agent_detail` return both. `name` is the machine identifier and the only
+one that routes: `target_names`, mentions and room aliases all take it.
+`display_name` is a free-form human label for showing an agent to a person, and
+is null when the agent has none — fall back to `name`. A `target_names` entry
+carrying a display name addresses no one.
+
### Creating rooms
- **`list_bridges`** — the collaboration bridges configured on this instance:
diff --git a/connectors/opencode-plugin/skills/switch/SKILL.md b/connectors/opencode-plugin/skills/switch/SKILL.md
index 6ba058eae..f251af523 100644
--- a/connectors/opencode-plugin/skills/switch/SKILL.md
+++ b/connectors/opencode-plugin/skills/switch/SKILL.md
@@ -358,6 +358,13 @@ none of it is needed to take part in a conversation.
sets the agent's parent (validated against self-parenting and cycles);
`clear_parent=true` detaches it to top-level.
+**Address by `name`, not `display_name`.** `list_agents` and
+`get_agent_detail` return both. `name` is the machine identifier and the only
+one that routes: `target_names`, mentions and room aliases all take it.
+`display_name` is a free-form human label for showing an agent to a person, and
+is null when the agent has none — fall back to `name`. A `target_names` entry
+carrying a display name addresses no one.
+
### Creating rooms
- **`list_bridges`** — the collaboration bridges configured on this instance:
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
index 28740a178..5c5bb36cd 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
@@ -100,6 +100,7 @@ function params(overrides: Record<string, unknown> = {}) {
providerId: 'codex' as const,
serverId: 'srv-1',
description: 'Codex running in repo',
+ displayName: null,
iconUrl: null,
autoSession: false,
autoApprove: false,
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
index dc7288902..014df7a72 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
@@ -43,6 +43,9 @@ export type AddAgentParams = {
/** The registered Switch server to mint the identity on. */
serverId: string;
description: string;
+ /** The human label chat platforms render the agent under. Null means it is
+ * shown under `name` instead — `name` stays the routing key either way. */
+ displayName: string | null;
/** The icon picked in the create form. Null means the form offered no
* choice, and the agent is registered with the avatar its name generates. */
iconUrl: string | null;
@@ -182,6 +185,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
const registered = await registerAgentIdentity(server, {
name: params.name,
description: params.description,
+ displayName: params.displayName,
repoDir: params.dir,
autoSession: params.autoSession,
agentType: knownAgentTypeForProvider(params.providerId),
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
index 5aef43a4b..e7a5d0218 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
@@ -135,6 +135,8 @@ async function resolveIdentity(
// Nobody is at a form to choose one, so it starts with the avatar its name
// generates — the same picture it would be shown with anyway.
iconUrl: agentAvatarUrlForName(name),
+ // The definition file carries no human label, so there is none to adopt.
+ displayName: null,
});
if (registered.kind !== 'created') {
const message = 'message' in registered ? registered.message : '';
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
index 4cfd9f92d..af9dbc2ad 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
@@ -15,6 +15,10 @@ export type RegisterAgentInput = {
/** The icon chosen in the create form, or null for none. Required so a new
* create flow has to say which it means. */
iconUrl: string | null;
+ /** The human label the agent is rendered under on chat platforms, or null to
+ * be shown under `name`. Required for the same reason as `iconUrl`: a flow
+ * that has a label to pass must not lose it by omission. */
+ displayName: string | null;
};
/**
@@ -41,6 +45,7 @@ export async function registerAgentIdentity(
description: input.description,
agentType: input.agentType,
iconUrl: input.iconUrl,
+ displayName: input.displayName,
options: {
channels_enabled: true,
repo_dir: input.repoDir,
@@ -53,7 +58,7 @@ export async function registerAgentIdentity(
if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
if (cause.kind === 'http' && cause.status === 409) return { kind: 'name-conflict' };
if (cause.kind === 'http' && cause.status === 400) {
- return { kind: 'invalid-name', message: cause.message };
+ return { kind: 'invalid-name', message: cause.detail ?? cause.message };
}
return { kind: 'error', message: cause.message };
}
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
index ebe68a6fb..f61363a00 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
@@ -139,6 +139,7 @@ services:
MM_SERVICESETTINGS_ENABLEBOTACCOUNTCREATION: "true"
MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS: "true"
MM_TEAMSETTINGS_ENABLEOPENSERVER: "true"
+ MM_TEAMSETTINGS_TEAMMATENAMEDISPLAY: "full_name"
# Neither plugin is usable in a bundled Switch deployment: Copilot has no
# configured provider and throws a 404 looking up its bot on every page
# load, and Calls ships a WebRTC service nothing here can reach.
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
index 04f7f994b..b765f6040 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
@@ -36,6 +36,7 @@ function agent(overrides: Partial<RemoteAgentSummary>): RemoteAgentSummary {
return {
id: 'a-1',
name: 'worker',
+ displayName: null,
description: '',
connectorType: 'claude-code',
ownerId: 'user-me',
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 f3bb0cdbd..71d65b0b5 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
@@ -769,6 +769,8 @@ export const switchServersController = createRPCController({
repoDir: params.dir,
autoSession: params.autoSession,
iconUrl: agentAvatarUrlForName(params.name),
+ // This flow asks for a name and nothing else, so there is no label to send.
+ displayName: null,
// Provisioning writes `.claude/settings.local.json` — this is the Claude
// Code path by construction, not a fallback.
agentType: knownAgentTypeForProvider('claude'),
@@ -825,6 +827,8 @@ export const switchServersController = createRPCController({
repoDir: params.remoteRepoDir,
autoSession: params.autoSession,
iconUrl: agentAvatarUrlForName(params.name),
+ // As locally: a name is all this flow collects.
+ displayName: null,
// Remote provisioning likewise writes `.claude/settings.local.json`.
agentType: knownAgentTypeForProvider('claude'),
});
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 e809a8fec..a8e84aecb 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
@@ -505,6 +505,7 @@ describe('registerKnownAgent', () => {
agentType: 'codex',
options: { channels_enabled: true, repo_dir: '/repo' },
iconUrl: null,
+ displayName: null,
});
expect(registered).toEqual({ id: 'sw-1', apiKey: 'tok-123' });
@@ -515,9 +516,30 @@ describe('registerKnownAgent', () => {
description: 'Codex running in repo',
options: { channels_enabled: true, repo_dir: '/repo' },
icon_url: null,
+ display_name: null,
overwrite: false,
});
});
+
+ it('sends the human display name alongside the identifier', async () => {
+ // The two are different strings on purpose: `name` routes, `display_name`
+ // is what a chat platform renders. Dropping the label here would leave the
+ // create form's field with nowhere to land.
+ await registerKnownAgent(SERVER, {
+ name: 'switch-dev',
+ description: 'Codex running in repo',
+ agentType: 'codex',
+ options: { channels_enabled: true, repo_dir: '/repo' },
+ iconUrl: null,
+ displayName: 'Switch Dev',
+ });
+
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, { body: string }];
+ expect(JSON.parse(init.body)).toMatchObject({
+ name: 'switch-dev',
+ display_name: 'Switch Dev',
+ });
+ });
});
describe('ownsOwnerAddressedAgent', () => {
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 bffffe26e..cf5b98038 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
@@ -317,6 +317,11 @@ export async function registerKnownAgent(
* one. Required rather than optional so a create flow states which it
* means instead of dropping the user's choice by forgetting the field. */
iconUrl: string | null;
+ /** The label chat platforms render the agent under, or null to leave it
+ * unset and be shown under `name`. Required rather than optional for the
+ * same reason as `iconUrl`: the create form holds a label the user typed,
+ * and an omitted field would drop it without saying so. */
+ displayName: string | null;
}
): Promise<RegisteredAgent> {
const res = await gatewayFetch(server, '/agents/register', {
@@ -328,6 +333,7 @@ export async function registerKnownAgent(
description: params.description,
options: params.options,
icon_url: params.iconUrl,
+ display_name: params.displayName,
overwrite: false,
},
});
@@ -341,6 +347,7 @@ export async function registerKnownAgent(
type AgentSummaryJson = {
id: string;
name: string;
+ display_name?: string | null;
description: string;
connector_type: string;
owner_id?: string | null;
@@ -358,6 +365,7 @@ function toRemoteAgentSummary(json: AgentSummaryJson): RemoteAgentSummary {
return {
id: json.id,
name: json.name,
+ displayName: json.display_name ?? null,
description: json.description,
connectorType: json.connector_type,
ownerId: json.owner_id ?? null,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
index 4a7664078..435c23376 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
@@ -295,7 +295,7 @@ export const AddAgentModal = observer(function AddAgentModal({
}
if (result.kind === 'invalid-name') {
toast({
- title: 'That agent name cannot be used',
+ title: 'Switch rejected these agent details',
description: result.message,
variant: 'destructive',
});
@@ -325,6 +325,7 @@ export const AddAgentModal = observer(function AddAgentModal({
providerId: pickState.providerId,
serverId: pickState.serverId,
description: form.description.trim(),
+ displayName: form.displayName.trim() || null,
instructions: form.instructions,
iconUrl: form.iconUrl,
autoSession: form.autoSession,
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 44bccba38..428feb0e5 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
@@ -234,6 +234,7 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({
*/
export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState }) {
const nameId = useId();
+ const displayNameId = useId();
const descriptionId = useId();
const instructionsId = useId();
const nameRef = useRef<HTMLInputElement>(null);
@@ -261,9 +262,7 @@ export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState })
ref={nameRef}
placeholder="Name this agent"
value={form.agentName}
- onChange={(e) =>
- form.setAgentName(e.target.value.replace(/[A-Z]/g, (c) => c.toLowerCase()))
- }
+ onChange={(e) => form.setAgentName(e.target.value)}
aria-invalid={form.nameIsRejected}
/>
{form.nameIsRejected ? (
@@ -286,7 +285,7 @@ export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState })
// button; without moving focus first it falls to the body and
// the tab order restarts.
onClick={() => {
- form.setAgentName(form.suggestedName);
+ form.acceptSuggestedName();
nameRef.current?.focus();
}}
>
@@ -311,6 +310,22 @@ export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState })
)}
</Field>
+ <Field>
+ <FieldLabel htmlFor={displayNameId}>
+ Display name <span className="text-foreground-muted">(optional)</span>
+ </FieldLabel>
+ <Input
+ id={displayNameId}
+ placeholder={form.agentName.length > 0 ? form.agentName : 'How to show this agent'}
+ value={form.displayName}
+ onChange={(e) => form.setDisplayName(e.target.value)}
+ />
+ <span className="text-xs text-foreground-muted">
+ The name this agent is shown under on Slack, Discord and other chat platforms. Leave it
+ empty and it shows up under its identifier.
+ </span>
+ </Field>
+
<Field>
<FieldLabel htmlFor={descriptionId}>Description</FieldLabel>
<Input
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 e890aa067..14501829f 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
@@ -40,7 +40,15 @@ export type PickModeState = ReturnType<typeof usePickMode>;
* was on screen, so the name and description the user had typed vanished.
*/
export function useConfigureAgentForm() {
- const [agentName, setAgentName] = useState('');
+ const [agentName, setAgentNameFolded] = useState('');
+ // What was typed, before the identifier folded it to lowercase. The slug
+ // offer hands this back as the display name, so the capitals in a typed
+ // "Switch Dev" outlive an identifier that cannot hold them.
+ const [typedName, setTypedName] = useState('');
+ // The label chat platforms render the agent under. Optional: an agent with
+ // none is shown under its identifier.
+ const [displayName, setDisplayNameRaw] = useState('');
+ const [displayNameTouched, setDisplayNameTouched] = useState(false);
const [description, setDescription] = useState('');
// What the agent is for, in its own words (CHOO-2228). Optional: an agent
// with none runs on its provider's defaults, and the description stands in
@@ -67,6 +75,24 @@ export function useConfigureAgentForm() {
setAutoApproveTouched(true);
}, []);
+ const setDisplayName = useCallback((value: string) => {
+ setDisplayNameRaw(value);
+ setDisplayNameTouched(true);
+ }, []);
+
+ /**
+ * Uppercase is the one thing the charset rejects that the reader never means
+ * — nobody wants a capital in a routing handle they did not know was one —
+ * so it is folded as they type rather than held against them. Everything
+ * else the charset refuses is left alone for the rejection banner and its
+ * slug offer to answer, because rewriting text under the cursor is worse
+ * than an error.
+ */
+ const setAgentName = useCallback((value: string) => {
+ setTypedName(value);
+ setAgentNameFolded(value.replace(/[A-Z]/g, (c) => c.toLowerCase()));
+ }, []);
+
/**
* What the run location implies, for as long as the user has not answered
* themselves: an agent on a host is put there to run unattended, and a
@@ -89,12 +115,28 @@ export function useConfigureAgentForm() {
const suggestedName = nameIsRejected ? slugifyAgentNamePart(agentName) : '';
const isValid = nameIsValid && description.trim().length > 0;
+ /**
+ * Take the offered slug as the name, keeping the text it was slugged from as
+ * the display name. "Switch Dev" is both the label someone wants and the
+ * thing the charset rejects, so the slug must not be all that survives it.
+ * A display name the user wrote themselves is an answer, not a guess, and
+ * stands.
+ */
+ const acceptSuggestedName = useCallback(() => {
+ if (suggestedName === '') return;
+ if (!displayNameTouched) setDisplayNameRaw(typedName);
+ setAgentName(suggestedName);
+ }, [typedName, displayNameTouched, suggestedName, setAgentName]);
+
return {
agentName,
setAgentName,
nameIsValid,
nameIsRejected,
suggestedName,
+ acceptSuggestedName,
+ displayName,
+ setDisplayName,
description,
setDescription,
instructions,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
index 50a9ed1fb..d81d8da8e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
@@ -33,7 +33,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
// Never the location's name: a directory is not an agent, and standing its
// basename in here also seeds the generated avatar from it, so the page
// presents a whole identity that belongs to no agent.
- const title = agent?.name ?? agentName ?? 'Agent';
+ const agentMachineName = agent?.name ?? agentName ?? 'Agent';
const provider = agent?.providerId ? providerDisplayName(agent.providerId) : null;
const serverId = agent?.serverId ?? null;
@@ -41,6 +41,11 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
const remote = (remoteAgents ?? []).find((a) => a.id === agent?.switchAgentId) ?? null;
const description = remote?.description ?? null;
+ // Use displayName as primary title, with fallback to the machine name
+ const title = remote?.displayName ?? agentMachineName;
+ // Show machine name as subtitle only if displayName exists and differs from name
+ const showMachineName = remote?.displayName != null && remote.displayName !== agentMachineName;
+
const roomable = serverId !== null && agent?.switchAgentId != null;
const queryClient = useQueryClient();
@@ -94,6 +99,11 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
</Badge>
)}
</div>
+ {showMachineName && (
+ <p className="text-sm text-foreground-muted">
+ Machine name: <span className="font-mono">{agentMachineName}</span>
+ </p>
+ )}
{description && <p className="text-sm text-foreground-muted">{description}</p>}
<div className="mt-2 flex flex-wrap items-center gap-2">
<Button
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-display-name.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-display-name.test.tsx
new file mode 100644
index 000000000..67e4a663c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-display-name.test.tsx
@@ -0,0 +1,211 @@
+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';
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: vi.fn() },
+ rpc: {
+ switchServers: {
+ listRemoteRooms: () => Promise.resolve([]),
+ listRemoteRoomGroups: () => Promise.resolve([]),
+ listRemoteExternalUsers: () => Promise.resolve([]),
+ listRemoteAgents: () => Promise.resolve([]),
+ listRemoteBridges: () => Promise.resolve([]),
+ listMyIdentities: () => Promise.resolve([]),
+ },
+ },
+}));
+/**
+ * What accepting the offered slug does to the text it was slugged from.
+ *
+ * The create form asks for one name and gets two things out of it: the
+ * identifier rooms route by, and the label a chat platform renders. Typing
+ * "Switch Dev" and accepting `switch-dev` used to overwrite the field, so the
+ * label the user had already written was gone before they could be asked for it.
+ */
+import { AgentIdentityFields } from '@renderer/features/locations/components/add-agent-modal/configure-agent-panel';
+import {
+ type ConfigureAgentFormState,
+ useConfigureAgentForm,
+} from '@renderer/features/locations/components/add-agent-modal/modes';
+
+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;
+});
+
+/** Mount the real hook and hand the caller its live state to drive. */
+async function mountForm(): Promise<() => ConfigureAgentFormState> {
+ let latest: ConfigureAgentFormState | null = null;
+ function Probe() {
+ latest = useConfigureAgentForm();
+ 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 () => {
+ if (latest === null) throw new Error('the form never rendered');
+ return latest;
+ };
+}
+
+describe('the display name on a new agent', () => {
+ it('starts empty', async () => {
+ const form = await mountForm();
+ expect(form().displayName).toBe('');
+ });
+
+ it('keeps the typed text as the display name when the slug is accepted', async () => {
+ const form = await mountForm();
+
+ await act(async () => form().setAgentName('Switch Dev'));
+ expect(form().suggestedName).toBe('switch-dev');
+
+ await act(async () => form().acceptSuggestedName());
+
+ expect(form().agentName).toBe('switch-dev');
+ expect(form().displayName).toBe('Switch Dev');
+ });
+
+ it('leaves a display name the user typed themselves alone', async () => {
+ const form = await mountForm();
+
+ await act(async () => form().setDisplayName('The Dev'));
+ await act(async () => form().setAgentName('Switch Dev'));
+ await act(async () => form().acceptSuggestedName());
+
+ expect(form().agentName).toBe('switch-dev');
+ expect(form().displayName).toBe('The Dev');
+ });
+
+ it('treats a display name the user cleared as an answer, not an absence', async () => {
+ // Emptying the field is a decision — "show this agent under its
+ // identifier" — so the slug must not read it as "never asked" and refill
+ // it. A falsy check on the value alone passes every other test here and
+ // fails this one.
+ const form = await mountForm();
+
+ await act(async () => form().setDisplayName('The Dev'));
+ await act(async () => form().setDisplayName(''));
+ await act(async () => form().setAgentName('Switch Dev'));
+ await act(async () => form().acceptSuggestedName());
+
+ expect(form().agentName).toBe('switch-dev');
+ expect(form().displayName).toBe('');
+ });
+
+ it('does nothing when there is no suggestion to accept', async () => {
+ const form = await mountForm();
+
+ await act(async () => form().setAgentName('switch-dev'));
+ expect(form().suggestedName).toBe('');
+
+ await act(async () => form().acceptSuggestedName());
+
+ expect(form().agentName).toBe('switch-dev');
+ expect(form().displayName).toBe('');
+ });
+});
+
+let domContainer: HTMLDivElement | null = null;
+let domRoot: Root | null = null;
+let domForm: ReturnType<typeof useConfigureAgentForm> | null = null;
+
+afterEach(async () => {
+ if (domRoot) await act(async () => domRoot!.unmount());
+ domContainer?.remove();
+ domContainer = null;
+ domRoot = null;
+ domForm = null;
+});
+
+function Fields() {
+ domForm = useConfigureAgentForm();
+ return <AgentIdentityFields form={domForm} />;
+}
+
+async function renderFields(): Promise<HTMLDivElement> {
+ domContainer = document.createElement('div');
+ document.body.appendChild(domContainer);
+ domRoot = createRoot(domContainer);
+ await act(async () => domRoot!.render(<Fields />));
+ return domContainer;
+}
+
+async function typeName(el: HTMLElement, value: string) {
+ const field = el.querySelector<HTMLInputElement>('input[placeholder="Name this agent"]');
+ expect(field, 'no Name input').not.toBeNull();
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setter.call(field!, value);
+ field!.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+async function typeDisplayName(el: HTMLElement, value: string) {
+ const label = [...el.querySelectorAll('label')].find((l) =>
+ /^Display name/.test(l.textContent ?? '')
+ );
+ expect(label, 'no Display name label').not.toBeUndefined();
+ const field = el.querySelector<HTMLInputElement>(`#${label!.htmlFor}`);
+ expect(field, 'no Display name input').not.toBeNull();
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setter.call(field!, value);
+ field!.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+function suggestionButton(el: HTMLElement): HTMLButtonElement | undefined {
+ return [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
+ /^Use\b/.test(b.textContent?.trim() ?? '')
+ );
+}
+
+describe('the display name field in the DOM', () => {
+ it('renders an input labelled Display name', async () => {
+ const el = await renderFields();
+
+ const label = [...el.querySelectorAll('label')].find((l) =>
+ /^Display name/.test(l.textContent ?? '')
+ );
+ expect(label, 'no Display name label').not.toBeUndefined();
+ const field = el.querySelector<HTMLInputElement>(`#${label!.htmlFor}`);
+ expect(field, 'no Display name input').not.toBeNull();
+ });
+
+ it('updates form.displayName when typed into', async () => {
+ const el = await renderFields();
+
+ await typeDisplayName(el, 'The Dev');
+
+ expect(domForm?.displayName).toBe('The Dev');
+ });
+
+ it('shows the name in the Display name input after accepting the slug', async () => {
+ const el = await renderFields();
+ await typeName(el, 'Switch Dev');
+ await act(async () => suggestionButton(el)!.click());
+
+ const label = [...el.querySelectorAll('label')].find((l) =>
+ /^Display name/.test(l.textContent ?? '')
+ );
+ const field = el.querySelector<HTMLInputElement>(`#${label!.htmlFor}`);
+ expect(field?.value).toBe('Switch Dev');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx
index dcea7b18b..1270d11a5 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx
@@ -72,6 +72,29 @@ function suggestionButton(el: HTMLElement): HTMLButtonElement | undefined {
const REJECTION = 'Use lowercase letters, digits';
+describe('an agent name typed with capitals', () => {
+ it('folds them as they are typed rather than rejecting them', async () => {
+ const el = await renderFields();
+ await typeName(el, 'SwitchDev');
+
+ const field = el.querySelector<HTMLInputElement>('input[placeholder="Name this agent"]');
+ expect(field?.value).toBe('switchdev');
+ expect(form?.nameIsValid).toBe(true);
+ expect(el.textContent).not.toContain(REJECTION);
+ });
+
+ it('still remembers them for the display name the slug offer hands back', async () => {
+ // The fold above is what makes this worth pinning: the identifier no longer
+ // holds the capitals, so only the typed text can supply them.
+ const el = await renderFields();
+ await typeName(el, 'Switch Dev');
+ await act(async () => suggestionButton(el)!.click());
+
+ expect(form?.agentName).toBe('switch-dev');
+ expect(form?.displayName).toBe('Switch Dev');
+ });
+});
+
describe('a rejected agent name', () => {
it('offers the slug of what was typed', async () => {
const el = await renderFields();
@@ -93,6 +116,7 @@ describe('a rejected agent name', () => {
expect(form?.agentName).toBe('switch-dev');
expect(form?.nameIsValid).toBe(true);
+ expect(form?.displayName).toBe('Switch Dev');
expect(el.textContent).not.toContain(REJECTION);
expect(suggestionButton(el)).toBeUndefined();
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
index aaa114c2d..7bd3b8a25 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
@@ -55,6 +55,7 @@ function remoteAgent(iconUrl: string | null): RemoteAgentSummary {
return {
id: SWITCH_AGENT_ID,
name: AGENT_NAME,
+ displayName: null,
description: '',
connectorType: 'agent',
ownerId: null,
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 626e677db..bd7840f5e 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
@@ -194,6 +194,10 @@ export type RemoteAgentSummary = {
* name-derived avatar instead, so the fallback can change without every
* agent needing rewriting. */
iconUrl: string | null;
+ /** The human label chat platforms render the agent under, or null when it has
+ * none and is shown under `name`. Presentation only — `name` remains the key
+ * rooms, sessions and lookups are routed by. */
+ displayName: string | null;
createdAt: string;
};
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 09dbfc2f1..34ff80077 100644
--- a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
@@ -366,6 +366,13 @@ none of it is needed to take part in a conversation.
sets the agent's parent (validated against self-parenting and cycles);
\`clear_parent=true\` detaches it to top-level.
+**Address by \`name\`, not \`display_name\`.** \`list_agents\` and
+\`get_agent_detail\` return both. \`name\` is the machine identifier and the only
+one that routes: \`target_names\`, mentions and room aliases all take it.
+\`display_name\` is a free-form human label for showing an agent to a person, and
+is null when the agent has none — fall back to \`name\`. A \`target_names\` entry
+carrying a display name addresses no one.
+
### Creating rooms
- **\`list_bridges\`** — the collaboration bridges configured on this instance:
diff --git a/core/switch_core/agent_display_name.py b/core/switch_core/agent_display_name.py
index 2cd8ce8d8..bffb4b13c 100644
--- a/core/switch_core/agent_display_name.py
+++ b/core/switch_core/agent_display_name.py
@@ -1,4 +1,4 @@
-"""Validation for an agent's human display name.
+"""Validating an agent's human display name, and writing it into a message.
An agent's `name` is a machine identifier — lowercase, no spaces — because it
is addressed, mentioned and matched on. A display name is the other half: the
@@ -6,9 +6,14 @@ label a person reads ("Switch Dev" beside "switchdev"), so uppercase, spaces
and punctuation are exactly what it exists to allow.
It is rendered into message headers on the collaboration bridges, which is what
-the rules below constrain: a newline or a control character in a header is a
-way to forge a line the platform never sent, and length has to fit the
+the validation rules constrain: a newline or a control character in a header is
+a way to forge a line the platform never sent, and length has to fit the
narrowest consumer rather than the widest.
+
+Everything punctuation-shaped that survives validation is then the render
+helpers' problem — see `defuse_label_markup`. They live here, free of any
+bridge or database import, so the `!` command surface and the collaboration
+adapters can share one rule rather than each growing their own.
"""
from typing import NoReturn
@@ -18,6 +23,8 @@ from typing import NoReturn
# that a display name stays a label rather than a sentence.
MAX_DISPLAY_NAME_LENGTH = 64
+_ZERO_WIDTH_SPACE = "\u200b"
+
class InvalidDisplayName(ValueError):
"""Raised when a display name is empty, over-long, or unsafe to render."""
@@ -78,3 +85,62 @@ def normalise_display_name(value: str | None) -> str | None:
return None
return validate_display_name(value)
+
+
+def defuse_label_markup(label: str) -> str:
+ """Neutralise the markup a label can use to claim something it is not.
+
+ A display name is free text an agent's owner chooses, and it is inlined
+ into message bodies that reach chat platforms. Two constructs are near
+ universal there:
+
+ - `@…` addresses somebody. Whether the reader's platform resolves
+ `@channel`, `@here`, a person, or one of Switch's own agent handles on
+ the way out, an un-defused label gets to notify people the message was
+ never aimed at. A zero-width space after every `@` leaves the sigil
+ legible and the resolution dead.
+ - `[text](url)` renders an anchor whose destination the label chose and
+ whose visible text hides it. The zero-width space goes after the `]`,
+ breaking the `](` adjacency every Markdown dialect requires — after the
+ `[` it lands inside the visible text and the link still matches.
+
+ Defused rather than escaped, because the result has to survive as far as
+ whatever renders it: a backslash escape would have to match the dialect at
+ the far end, while a zero-width space is inert in every escaping pipeline
+ it may pass through afterwards, so it cannot compound with one.
+ """
+ return label.replace("@", "@" + _ZERO_WIDTH_SPACE).replace(
+ "]", "]" + _ZERO_WIDTH_SPACE
+ )
+
+
+def agent_label(display_name: str | None, name: str) -> str:
+ """How to write an agent where the text is pure attribution.
+
+ The display name when there is one, otherwise the identifier — defused
+ with `defuse_label_markup`, because the caller is putting it into a body
+ that nothing downstream escapes for it.
+
+ For text a reader also has to type or copy back, use
+ `agent_label_with_identifier`: this one can render a label that addresses
+ nothing.
+ """
+ return defuse_label_markup(display_name or name)
+
+
+def agent_label_with_identifier(display_name: str | None, name: str) -> str:
+ """How to write an agent where the reader both reads and copies the name.
+
+ ``Switch Dev (`switchdev`)`` — the defused display name, then the
+ identifier that actually routes, so a reader can act on the line as well as
+ read it. The identifier is in backticks because Discord and Slack resolve
+ no mention inside a code span: it stays copyable without becoming a live
+ ping of whoever happens to hold that handle on the platform.
+
+ An agent with no display name renders as the bare identifier; there is
+ nothing to disambiguate, and ``switchdev (`switchdev`)`` reads as noise.
+ """
+ if not display_name:
+ return name
+
+ return f"{defuse_label_markup(display_name)} (`{name}`)"
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index da877182a..0df3ad946 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -1185,7 +1185,10 @@ async def list_task_agents(
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e)) from e
- agents = [AgentInfo(id=p.id, name=p.name, description="") for p in performers]
+ agents = [
+ AgentInfo(id=p.id, name=p.name, description="", display_name=p.display_name)
+ for p in performers
+ ]
return TaskAgentsResponse(agents=agents)
@@ -1488,7 +1491,13 @@ async def list_agents(
agents = await protocol.list_all_agents(agent.id)
return AgentListResponse(
agents=[
- AgentInfo(id=a.id, name=a.name, description=a.description) for a in agents
+ AgentInfo(
+ id=a.id,
+ name=a.name,
+ description=a.description,
+ display_name=a.display_name,
+ )
+ for a in agents
]
)
diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.py
index 31343fe47..9a5784cb6 100644
--- a/core/switch_core/bridges/agent/api/schemas.py
+++ b/core/switch_core/bridges/agent/api/schemas.py
@@ -352,6 +352,7 @@ class AgentInfo(BaseModel):
id: str
name: str
description: str
+ display_name: str | None
class TaskAgentsResponse(BaseModel):
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.py
index 3449d6fa6..2d4235718 100644
--- a/core/switch_core/bridges/agent/commands.py
+++ b/core/switch_core/bridges/agent/commands.py
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Literal, cast
from nio import MatrixRoom
+from switch_core.agent_display_name import agent_label, agent_label_with_identifier
from switch_core.aliases import (
AliasError,
check_alias_collisions,
@@ -448,7 +449,8 @@ async def _cmd_list_room_agents(
agent = await client._agent_store.get(session, agent_id)
if agent:
desc = f" — {agent.description}" if agent.description else ""
- lines.append(f"- **{agent.name}**{desc}")
+ label = agent_label_with_identifier(agent.display_name, agent.name)
+ lines.append(f"- **{label}**{desc}")
await _reply(client, room, event, "\n".join(lines))
@@ -472,11 +474,15 @@ async def _cmd_list_aliases(
lines = ["**Aliases in this room:**"]
for agent_id, alias in aliases.items():
agent = await client._agent_store.get(session, agent_id)
- name = agent.name if agent else agent_id
+ label = (
+ agent_label_with_identifier(agent.display_name, agent.name)
+ if agent
+ else agent_id
+ )
# Render the alias WITHOUT a leading `@`: this text is posted as a
# room message, and a live `@<alias>` would be re-parsed as a mention
# and address the aliased agent.
- lines.append(f"- `{alias}` → **{name}**")
+ lines.append(f"- `{alias}` → **{label}**")
await _reply(client, room, event, "\n".join(lines))
@@ -547,7 +553,7 @@ async def _cmd_set_alias(
client,
room,
event,
- f"Alias set — address **{target.name}** as `{alias}` in this room.",
+ f"Alias set — address **{agent_label_with_identifier(target.display_name, target.name)}** as `{alias}` in this room.",
)
@@ -642,7 +648,10 @@ async def _cmd_invite(
room_agent_ids = await client._room_store.get_agent_ids(session, meta.room_id)
if target.id in room_agent_ids:
await _reply(
- client, room, event, f"**{target.name}** is already in this room."
+ client,
+ room,
+ event,
+ f"**{agent_label_with_identifier(target.display_name, target.name)}** is already in this room.",
)
return
@@ -654,7 +663,12 @@ async def _cmd_invite(
await cast("AdminClient", client)._room_service.add_agents_to_room(
meta.room_id, agent_names=[target.name]
)
- await _reply(client, room, event, f"Added **{target.name}** to this room.")
+ await _reply(
+ client,
+ room,
+ event,
+ f"Added **{agent_label_with_identifier(target.display_name, target.name)}** to this room.",
+ )
# Emoji + label shown per status by the !status command.
@@ -680,20 +694,22 @@ def _format_status_lines(
runtime_states: dict[str, str],
deeplinks: dict[str, str],
) -> str:
- """Render the !status summary: one line per agent (sorted by name) with
- its presence emoji + label, runtime state (if any), agent_type, task
- capabilities, and a Switch Console deeplink to its session when one is known.
+ """Render the !status summary: one line per agent (sorted by the name it is
+ shown under) with its presence emoji + label, runtime state (if any),
+ agent_type, task capabilities, and a Switch Console deeplink to its session
+ when one is known.
The deeplink is shown only for an agent whose session is LIVE in this room:
the stored link is per (agent, room) and survives a room switch, so once the
session moves away it would point at a session no longer here. Gating on
LIVE keeps the link from going stale when an agent hops rooms."""
lines = ["**Agent status in this room:**"]
- for agent in sorted(agents, key=lambda a: a.name):
+ for agent in sorted(agents, key=lambda a: (a.display_name or a.name).lower()):
status = statuses.get(agent.id, AgentStatus.NO_SESSION)
emoji, label = _STATUS_DISPLAY.get(status, ("", status.value))
runtime = _RUNTIME_STATE_DISPLAY.get(runtime_states.get(agent.id, ""))
- head = f"{emoji} **{agent.name}** — {label}"
+ name = agent_label_with_identifier(agent.display_name, agent.name)
+ head = f"{emoji} **{name}** — {label}"
if runtime is not None:
head += f" · {runtime}"
parts = [head, agent.agent_type]
@@ -777,7 +793,7 @@ async def _cmd_roles(
for holder_id in {h for ids in holders.values() for h in ids}:
holder = await client._agent_store.get(session, holder_id)
if holder is not None:
- holder_names[holder_id] = holder.name
+ holder_names[holder_id] = agent_label(holder.display_name, holder.name)
lines = ["**Roles in this room:**"]
for role in roles:
@@ -821,7 +837,9 @@ async def _cmd_list_documents(
if d.created_by_agent_id:
agent = await client._agent_store.get(session, d.created_by_agent_id)
if agent:
- creator = f" — created by {agent.name}"
+ creator = (
+ f" — created by {agent_label(agent.display_name, agent.name)}"
+ )
desc = f" — {d.description}" if d.description else ""
if client._frontend_base_url is None:
name_md = f"**{d.name}**"
@@ -915,7 +933,8 @@ async def _cmd_list_all_agents(
lines = ["**Available agents:**"]
for agent in agents:
desc = f" — {agent.description}" if agent.description else ""
- lines.append(f"- **{agent.name}**{desc}")
+ label = agent_label_with_identifier(agent.display_name, agent.name)
+ lines.append(f"- **{label}**{desc}")
await _reply(client, room, event, "\n".join(lines))
@@ -997,11 +1016,15 @@ async def _cmd_agents_greet(
event: CommandEvent,
is_direct: bool,
) -> None:
- name = client.agent.name
+ async with client.session_factory() as session:
+ agent = await client._fresh_agent(session)
if is_direct:
- await _reply(client, room, event, f"Hi! I'm {name} — how can I help?")
+ label = agent_label(agent.display_name, agent.name)
+ await _reply(client, room, event, f"Hi! I'm {label} — how can I help?")
else:
- greeting = random.choice(AGENT_GREETINGS).format(name=name)
+ # `@{name}` here is a live mention handle the reader tags back, so it
+ # stays the identifier whatever the agent is displayed as.
+ greeting = random.choice(AGENT_GREETINGS).format(name=agent.name)
await _reply(client, room, event, greeting)
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index a056f4e23..399a1913c 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -1596,6 +1596,8 @@ async def list_agents(
known_agent_options}.
`icon_url` is null when the agent has no icon set. `display_name` is
null when the agent has no display name set; fall back to `name`.
+ Address agents by `name`: `display_name` is a human label that routes
+ nothing, and `name_contains` matches `name` alone.
Use `get_agent_detail` for the full detail of one agent.
"""
agent_id = get_agent_id()
@@ -1624,6 +1626,7 @@ async def get_agent_detail(agent_id: str) -> dict[str, Any]:
rooms, sessions, children}.
`icon_url` is null when the agent has no icon set. `display_name` is
null when the agent has no display name set; fall back to `name`.
+ Address agents by `name`; `display_name` routes nothing.
"""
caller_id = get_agent_id()
protocol = get_protocol()
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 8673462ca..9c46258af 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -782,6 +782,7 @@ class ProtocolService:
name=agent.name,
type="agent",
agent_type=agent.agent_type,
+ display_name=agent.display_name,
can_delegate=bool(task_protocol.get("can_delegate", False)),
can_accept=bool(task_protocol.get("can_accept", False)),
status=statuses[agent.id],
@@ -2202,6 +2203,7 @@ class ProtocolService:
name=agent.name,
type="agent",
agent_type=agent.agent_type,
+ display_name=agent.display_name,
can_delegate=bool(task_protocol.get("can_delegate", False)),
can_accept=bool(task_protocol.get("can_accept", False)),
status=statuses[agent.id],
diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.py
index 6dcc89e98..186752348 100644
--- a/core/switch_core/bridges/agent/protocol/types.py
+++ b/core/switch_core/bridges/agent/protocol/types.py
@@ -130,6 +130,7 @@ class ParticipantDescriptor(BaseModel):
name: str
type: Literal["agent", "user"]
agent_type: str | None = None
+ display_name: str | None = None
can_delegate: bool = False
can_accept: bool = False
status: AgentStatus | None = None
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 47f2629f9..e4df7bea6 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -7,6 +7,7 @@ from collections.abc import Awaitable, Callable
from dataclasses import dataclass, replace
from typing import ClassVar
+from switch_core.agent_display_name import defuse_label_markup
from switch_core.agent_icon import default_icon_url
from switch_core.bridges.collaboration.models import (
BridgeInstallLink,
@@ -45,6 +46,37 @@ def format_elapsed(seconds: float) -> str:
return f"{hours}h{minutes:02d}m"
+@dataclass(frozen=True)
+class AgentPresentation:
+ """The presentation columns of one agent, exactly as they are stored.
+
+ Raw on purpose: ``None`` in either field means the agent was given no value
+ for it, and what stands in for a missing value is per-platform — Mattermost
+ wants a default icon in a format it can upload, Slack wants one drawn on its
+ own background. Deciding that here would take the choice away from the
+ adapter that has to live with it.
+ """
+
+ display_name: str | None
+ icon_url: str | None
+
+
+@dataclass(frozen=True)
+class AgentRendering:
+ """How one agent is presented on one send, resolved for this platform.
+
+ The two labels are separate members rather than one because they are not
+ interchangeable: ``field_label`` is safe only in a platform field that
+ carries a name on its own, and putting it in message text is how a display
+ name forges markup. A caller building a body string reaches for the member
+ whose name says so.
+ """
+
+ field_label: str
+ body_label: str
+ icon_url: str
+
+
@dataclass(frozen=True)
class LiveRuntimeIndicator:
"""The runtime status message currently posted for one agent in one channel.
@@ -126,11 +158,14 @@ class CollaborationAdapter(ABC):
# Set by set_channel_migration_handler. Called with (old_id, new_id)
# when the platform reissues a channel's id.
self._on_channel_migrated: Callable[[str, str], Awaitable[None]] | None = None
- # Set by set_agent_icon_resolver. Returns an agent's own icon URL, or
- # None when it has not been given one. Left unset an adapter still
- # works — every agent just gets the default — so adapters stay usable
- # without a bridge core wired up behind them.
- self._resolve_agent_icon: Callable[[str], Awaitable[str | None]] | None = None
+ # Set by set_agent_presentation_resolver. Returns the agent's stored
+ # presentation, or None for a name that is not an agent. Left unset an
+ # adapter still works — every agent renders under its identifier with
+ # the platform default icon — so adapters stay usable without a bridge
+ # core wired up behind them.
+ self._resolve_agent_presentation: (
+ Callable[[str], Awaitable[AgentPresentation | None]] | None
+ ) = None
# Inbound attachment size ceiling, set by the lifecycle service from
# config.agent_media_max_bytes. Adapters check a platform-reported file
# size against this before downloading so an oversize file is rejected
@@ -603,14 +638,15 @@ class CollaborationAdapter(ABC):
Returns the posted message ref so callers that can remove it (Slack,
Mattermost) track it for cleanup when the turn ends."""
+ label = await self.agent_label_for_body(agent_name)
reason = detail.strip() if detail and detail.strip() else ""
need = f"hit an error: {reason}" if reason else "needs your input"
lead = "⚠️ " if reason else ""
if mention_handle:
- text = f"@{mention_handle} {lead}**{agent_name}** {need}."
+ text = f"@{mention_handle} {lead}**{label}** {need}."
else:
text = (
- f"{lead}**{agent_name}** {need} — but nobody here is linked "
+ f"{lead}**{label}** {need} — 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."
)
@@ -825,16 +861,19 @@ class CollaborationAdapter(ABC):
the platform forwards them, while nothing inbound matches a room again."""
self._on_channel_migrated = handler
- def set_agent_icon_resolver(
- self, resolver: Callable[[str], Awaitable[str | None]]
+ def set_agent_presentation_resolver(
+ self, resolver: Callable[[str], Awaitable[AgentPresentation | None]]
) -> None:
- """Install the lookup for an agent's own icon URL (None if it has none).
+ """Install the lookup for how an agent is presented — its label and its
+ icon — returning None for a name that is not an agent at all.
The bridge core supplies this because the adapter has no database of
- its own. Resolution happens per send rather than being cached, so
- changing an agent's icon shows up on its next message instead of at the
- next restart."""
- self._resolve_agent_icon = resolver
+ its own. One resolver rather than one per field because a send needs
+ both at once and they come off the same row: two would be two round
+ trips for one message. Resolution happens per send rather than being
+ cached, so a renamed or re-iconed agent reads correctly on its next
+ message instead of at the next restart."""
+ self._resolve_agent_presentation = resolver
def default_agent_icon(self, agent_name: str) -> str:
"""The avatar for an agent that has set no icon.
@@ -844,13 +883,87 @@ class CollaborationAdapter(ABC):
pins the response format."""
return default_icon_url(agent_name)
+ def adapt_icon_url(self, raw: str | None, agent_name: str) -> str:
+ """Turn the stored icon URL into the one this platform should be handed.
+
+ `raw` is the agent's own icon, or None when it has none and the
+ platform default stands in. Pure and synchronous so it composes with a
+ single lookup: an override adjusts the URL, it does not go looking for
+ one."""
+ return raw or self.default_agent_icon(agent_name)
+
+ def escape_label_for_body(self, label: str) -> str:
+ """Neutralise a label's markup before it goes into message text.
+
+ A display name is presentation text an agent's owner chooses, and
+ `_ping_operator` inlines it into a body. Two constructs are near
+ universal across chat platforms and are the ones a name can use to
+ claim something it is not:
+
+ - `@…` addresses somebody. Whether the platform resolves `@channel`,
+ `@here`, a person or one of our own agent handles, the label gets to
+ notify people the message was never aimed at. A zero-width space
+ after every `@` leaves the sigil legible and the resolution dead.
+ - `[text](url)` renders an anchor whose destination the label chose
+ and whose visible text hides it. The zero-width space goes after the
+ `]`, breaking the `](` adjacency every Markdown dialect requires —
+ after the `[` it lands inside the visible text and the link still
+ matches.
+
+ Defused rather than escaped, because the escape has to survive as far
+ as whatever renders it: on most platforms nothing of ours resolves
+ these, so there is no matcher here to defeat, only the platform's own
+ rendering. A zero-width space is also inert in every escaping pipeline
+ it may pass through afterwards, so it cannot compound with one.
+
+ Safe by default and specialised by override: the failure mode of the
+ other order is silent, since a platform whose adapter forgets this
+ renders a forged name correctly and says nothing. An override adds its
+ platform's own rule on top and calls up to this one — Teams its `<at>`
+ tags, Slack and Discord their markup escaping. None of them replaces
+ it, and the `@` rule is why: a platform's escaper defends against the
+ label carrying that platform's syntax, but Switch's own outbound
+ mention pass runs over the finished body and turns a plain `@handle`
+ into a real mention, needing no syntax from the label at all.
+
+ Not covered anywhere: emphasis, where a label's `*` or `_` can
+ unbalance the run around it. That is cosmetic, and the line held here
+ is that forged markup is closed while broken formatting is not worth
+ an escape that would show up in every ordinary name."""
+ return defuse_label_markup(label)
+
+ async def agent_rendering(self, agent_name: str) -> AgentRendering:
+ """Everything a send needs to present an agent, from ONE lookup.
+
+ The paired accessor, for the common case of a post that carries both a
+ name and an avatar. The single-field accessors below are for callers
+ that need one of them alone — an unescaped label is not among them:
+ :attr:`AgentRendering.field_label` is reachable only alongside the
+ escaped one, so choosing it is a choice."""
+ raw = AgentPresentation(display_name=None, icon_url=None)
+ if self._resolve_agent_presentation is not None:
+ found = await self._resolve_agent_presentation(agent_name)
+ if found is not None:
+ raw = found
+ label = raw.display_name or agent_name
+ return AgentRendering(
+ field_label=label,
+ body_label=self.escape_label_for_body(label),
+ icon_url=self.adapt_icon_url(raw.icon_url, agent_name),
+ )
+
async def agent_icon_url(self, agent_name: str) -> str:
"""The icon URL to render for an agent on this platform.
Adapters call this wherever they need a per-message avatar: the agent's
own icon when it has one, otherwise this platform's existing default."""
- if self._resolve_agent_icon is not None:
- chosen = await self._resolve_agent_icon(agent_name)
- if chosen:
- return chosen
- return self.default_agent_icon(agent_name)
+ return (await self.agent_rendering(agent_name)).icon_url
+
+ async def agent_label_for_body(self, agent_name: str) -> str:
+ """The label to inline into message text, escaped for this platform.
+
+ A display name is free text — punctuation is the point of it — so
+ inlining it raw lets a name break the surrounding markup or forge
+ markup of its own. Every caller that builds a body string must use
+ this, or :attr:`AgentRendering.body_label`."""
+ return (await self.agent_rendering(agent_name)).body_label
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 27fe1bcd0..7165ffff9 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -19,7 +19,10 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.aliases import AliasError, validate_alias_format
from switch_core.attachments import parse_attachment_group
-from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.adapter import (
+ AgentPresentation,
+ CollaborationAdapter,
+)
from switch_core.bridges.collaboration.models import (
ChannelType,
InboundAgentJoin,
@@ -184,7 +187,7 @@ class BridgeCore:
await self._load_channel_map()
await self._load_existing_puppets()
self._adapter.set_channel_migration_handler(self._handle_channel_migrated)
- self._adapter.set_agent_icon_resolver(self._agent_icon_url)
+ self._adapter.set_agent_presentation_resolver(self._agent_presentation)
await self._adapter.start(
on_message=self._handle_inbound_message,
on_command=self._handle_inbound_command,
@@ -314,17 +317,23 @@ class BridgeCore:
# ── Inbound (platform → room) ───────────────────────────────────────────
- async def _agent_icon_url(self, agent_name: str) -> str | None:
- """An agent's own icon URL, or None if it has not been given one.
+ async def _agent_presentation(self, agent_name: str) -> AgentPresentation | None:
+ """How an agent is presented — its label and its icon — off one row.
- Installed on the adapter as its icon resolver; None sends the adapter
- to its existing default. A name matching no agent — an alias, or a bot
- the platform reports that Switch does not own — also yields None rather
- than an error, since the caller only wants to know whether to override.
+ Installed on the adapter as its presentation resolver. A name matching
+ no agent — an alias, or a bot the platform reports that Switch does not
+ own — yields None rather than an error, since the caller only wants to
+ know whether to override what it already has. Either field being None
+ within a hit means the same thing one field down: the agent was given
+ no value, and the adapter's default stands.
"""
async with self._session_factory() as session:
agent = await self._agent_store.get_by_name(session, agent_name)
- return agent.icon_url if agent else None
+ if agent is None:
+ return None
+ return AgentPresentation(
+ display_name=agent.display_name, icon_url=agent.icon_url
+ )
async def _is_registered_agent(self, name: str) -> bool:
"""Whether `name` is a registered Switch agent. Switch creates each
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 0285b23ee..f29ec2058 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -53,6 +53,71 @@ _WORKING_REACTION = "👀"
# Discord's error code for "Maximum number of guild roles reached" (250).
_MAX_GUILD_ROLES_CODE = 30005
+# Applied to the bot posts that inline an agent's name into the body — the DM
+# path, which has no webhook identity to carry it. Escaping the text is not
+# enough on its own: Discord decides who a message pings from the raw content
+# it receives, so `@everyone` in a name is refused here rather than in markup.
+# Only the mass mentions are withheld; a user or role the agent deliberately
+# mentioned still resolves.
+_NO_MASS_MENTIONS = discord.AllowedMentions(everyone=False)
+
+# Inserted after the `<` of anything that looks like a Discord entity. Discord
+# has no escape for `<`, so the syntax is broken rather than escaped — the same
+# technique discord.py uses on `@`.
+_ZERO_WIDTH_SPACE = "\u200b"
+
+
+class _WebhookIdentity:
+ """The username one send posts under, across every webhook call it makes.
+
+ Discord validates a webhook username server-side and answers one it
+ dislikes with a 400. The exact rule is Discord's and is not pinned by
+ anything in this tree, so rather than guess at a blocklist the send is
+ attempted and a refusal falls back to the identifier, which the platform
+ has always accepted.
+
+ The refusal is remembered for the rest of the send because a send is
+ several webhook calls — one per chunk, plus any truncation notice — and
+ re-offering a name Discord has already refused doubles every one of them
+ and repeats the same warning per part. Held per send rather than per agent
+ so a name is re-offered on the next message: the refusal may have been
+ about something Discord has since changed its mind on, and a process-long
+ latch would hide a rename until the next restart.
+ """
+
+ def __init__(self, label: str, identifier: str) -> None:
+ self._label = label
+ self._identifier = identifier
+ self._refused = False
+
+ async def send(self, webhook: discord.Webhook, payload: dict[str, Any]) -> Any:
+ """Post `payload`, which must survive being sent twice."""
+ return await self.send_rebuilding(webhook, lambda: payload)
+
+ async def send_rebuilding(
+ self, webhook: discord.Webhook, build_payload: Callable[[], dict[str, Any]]
+ ) -> Any:
+ """Post a payload rebuilt for each attempt.
+
+ For the attachment path alone: an attempt reads the `discord.File` it
+ was handed, so a retry that reused it would upload nothing."""
+ if self._refused:
+ return await webhook.send(username=self._identifier, **build_payload())
+ try:
+ return await webhook.send(username=self._label, **build_payload())
+ except discord.HTTPException as e:
+ if e.status != 400 or self._label == self._identifier:
+ raise
+ self._refused = True
+ logger.warning(
+ "Discord refused the display name %r as a webhook username (%s); "
+ "posting as %r instead",
+ self._label,
+ e,
+ self._identifier,
+ )
+ return await webhook.send(username=self._identifier, **build_payload())
+
class DiscordConnectionConfig(BridgeConnectionConfig):
bot_token: str
@@ -282,9 +347,14 @@ class DiscordAdapter(CollaborationAdapter):
if self._channel_type_of(target) == "lobby":
# DM channels have no webhooks, so no per-message identity — fall
# back to a bot post with the agent name inlined.
+ label = await self.agent_label_for_body(sender_name)
return await self._send_chunked(
- f"**{sender_name}**: {content}",
- lambda part: target.send(part, suppress_embeds=True),
+ f"**{label}**: {content}",
+ lambda part: target.send(
+ part,
+ suppress_embeds=True,
+ allowed_mentions=_NO_MASS_MENTIONS,
+ ),
where=f"DM {channel_id}",
)
@@ -312,16 +382,19 @@ class DiscordAdapter(CollaborationAdapter):
# Resolved once here rather than inside the send callback: that callback
# is synchronous, and a chunked message would otherwise re-resolve per
# chunk and could split one message across two different avatars.
- avatar_url = await self.agent_icon_url(sender_name)
+ agent = await self.agent_rendering(sender_name)
+ identity = _WebhookIdentity(agent.field_label, sender_name)
return await self._send_chunked(
content,
- lambda part: webhook.send(
- content=part,
- username=sender_name,
- avatar_url=avatar_url,
- suppress_embeds=True,
- wait=True,
- **kwargs,
+ lambda part: identity.send(
+ webhook,
+ {
+ "content": part,
+ "avatar_url": agent.icon_url,
+ "suppress_embeds": True,
+ "wait": True,
+ **kwargs,
+ },
),
where=f"channel {channel_id}",
)
@@ -414,10 +487,13 @@ class DiscordAdapter(CollaborationAdapter):
body = self.translate_outbound(caption) if caption else ""
if self._channel_type_of(target) == "lobby":
- content = f"**{sender_name}**: {body}" if body else f"**{sender_name}**"
+ label = await self.agent_label_for_body(sender_name)
+ content = f"**{label}**: {body}" if body else f"**{label}**"
try:
msg = await target.send(
- content, file=discord.File(io.BytesIO(data), filename=filename)
+ content,
+ file=discord.File(io.BytesIO(data), filename=filename),
+ allowed_mentions=_NO_MASS_MENTIONS,
)
return f"{msg.channel.id}:{msg.id}"
except discord.HTTPException:
@@ -449,13 +525,17 @@ class DiscordAdapter(CollaborationAdapter):
kwargs: dict[str, Any] = {}
if thread is not None:
kwargs["thread"] = thread
- sent: Any = await webhook.send(
- content=body,
- username=sender_name,
- avatar_url=await self.agent_icon_url(sender_name),
- file=discord.File(io.BytesIO(data), filename=filename),
- wait=True,
- **kwargs,
+ agent = await self.agent_rendering(sender_name)
+ identity = _WebhookIdentity(agent.field_label, sender_name)
+ sent: Any = await identity.send_rebuilding(
+ webhook,
+ lambda: {
+ "content": body,
+ "avatar_url": agent.icon_url,
+ "file": discord.File(io.BytesIO(data), filename=filename),
+ "wait": True,
+ **kwargs,
+ },
)
return f"{sent.channel.id}:{sent.id}"
except discord.HTTPException as e:
@@ -1081,6 +1161,44 @@ class DiscordAdapter(CollaborationAdapter):
return re.sub(r"@([a-z0-9][a-z0-9._-]*)", _replace, content)
+ def escape_label_for_body(self, label: str) -> str:
+ """Defuse Discord's markdown, mentions and `<…>` entity syntax.
+
+ Three things a name can otherwise do to the body it is inlined into:
+
+ - Markdown. `Bo*b` eats the bolding of the prefix it sits in, so
+ discord.py's `escape_markdown` backslashes its emphasis characters.
+ `ignore_links=False` because a label is a name, not prose: there is
+ no URL in it worth keeping legible, and the exemption is a hole.
+ - Mass and user mentions. `escape_mentions` breaks `@everyone`,
+ `@here` and `<@id>` with a zero-width space after the `@`. It does
+ nothing for a plain `@opsbot`, which needs no Discord syntax at all:
+ `translate_outbound` runs over the finished body after the label is
+ inlined and resolves any handle it holds an id for into a real
+ `<@id>` or `<@&role>`. The base class's `@` rule is what closes that,
+ which is why this builds on it rather than replacing it.
+ - Everything else Discord resolves from `<…>` — a channel link
+ (`<#id>`), a custom emoji (`<:name:id>`), a timestamp (`<t:ts:F>`),
+ a slash-command link (`</cmd:id>`). `escape_mentions` covers none of
+ these ("this does not include channel mentions") and backslash does
+ not escape `<` on Discord, so the syntax is broken instead: a
+ zero-width space goes after every `<`. Each of those forms needs its
+ sigil immediately after the `<`, so this defuses all of them and
+ leaves an ordinary name alone.
+
+ Not covered: a bare URL in a display name still auto-links. Discord
+ linkifies one straight out of the raw content and offers no escape for
+ it, so a name that is a URL renders as a clickable link. Cosmetic
+ rather than a forgery — the link goes where the name says it does."""
+ return discord.utils.escape_markdown(
+ discord.utils.escape_mentions(
+ super()
+ .escape_label_for_body(label)
+ .replace("<", "<" + _ZERO_WIDTH_SPACE)
+ ),
+ ignore_links=False,
+ )
+
def translate_inbound(self, raw_message: str) -> str:
def _replace_user(match: re.Match[str]) -> str:
# The cache only knows people who have posted. Someone picked from
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index f415c0dc6..f1539402f 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -55,6 +55,11 @@ _JOINABLE_MM_CHANNEL_TYPES = frozenset({"O", "P"})
# Emoji marking the message an agent is currently working on.
_WORKING_REACTION = "eyes"
+# The values of `TeamSettings.TeammateNameDisplay` under which Mattermost puts
+# a bot's display name in the post header. Under any other value — including
+# the server default, "username" — the display name is stored and never shown.
+_NAME_DISPLAY_SHOWS_LABEL = frozenset({"full_name", "nickname_full_name"})
+
class MattermostConnectionConfig(BridgeConnectionConfig):
url: str
@@ -127,6 +132,14 @@ class MattermostAdapter(CollaborationAdapter):
# channel id -> channel name (URL slug), for building channel deeplinks.
self._channel_name_cache: dict[str, str] = {}
+ # The server's `TeamSettings.TeammateNameDisplay`, read once per run:
+ # it decides whether a bot's display name is rendered anywhere, and
+ # under the default ("username") it never is. None once a read has been
+ # attempted and could not answer.
+ self._name_display_setting: str | None = None
+ self._name_display_read = False
+ self._name_display_warned = False
+
# ── Lifecycle ────────────────────────────────────────────────────────────
async def start(
@@ -975,9 +988,25 @@ class MattermostAdapter(CollaborationAdapter):
loop = self._main_loop
+ # The username is the routing handle — the mention, the member-list key
+ # and the key this adapter adopts a bot back by — so it stays the
+ # identifier. Only the bot's own display name carries the label.
+ label = (await self.agent_rendering(agent_name)).field_label
+ if label != agent_name:
+ self._warn_once_if_display_names_are_hidden()
+
existing = await self._find_existing_bot(agent_name)
if existing:
bot_id: str = str(existing["user_id"])
+ if existing.get("display_name") != label:
+ try:
+ self._mm_api("put", f"/bots/{bot_id}", {"display_name": label})
+ except Exception as e:
+ logger.exception(
+ "Failed to update the display name of Mattermost bot %s: %s",
+ agent_name,
+ e,
+ )
else:
try:
bot = self._mm_api(
@@ -985,7 +1014,7 @@ class MattermostAdapter(CollaborationAdapter):
"/bots",
{
"username": agent_name,
- "display_name": agent_name,
+ "display_name": label,
"description": f"Switch agent: {agent_description}",
},
)
@@ -1215,6 +1244,53 @@ class MattermostAdapter(CollaborationAdapter):
agent_names.append(bot_name)
return agent_names
+ def _read_name_display_setting(self) -> str | None:
+ """`TeamSettings.TeammateNameDisplay`, read at most once per run.
+
+ None when the read could not answer — the server config is readable
+ only by a system admin, and an agent's bot is worth having either
+ way, so the caller reports the blind spot instead of failing on it."""
+ if self._name_display_read:
+ return self._name_display_setting
+ self._name_display_read = True
+ try:
+ config = self._mm_api("get", "/config")
+ setting = (config.get("TeamSettings") or {}).get("TeammateNameDisplay")
+ except Exception as e:
+ logger.warning(
+ "Could not read the Mattermost server config (%s), so whether "
+ "agent display names are rendered on this server is unknown",
+ e,
+ )
+ return None
+ if not isinstance(setting, str):
+ logger.warning(
+ "The Mattermost server config carries no "
+ "TeamSettings.TeammateNameDisplay, so whether agent display "
+ "names are rendered on this server is unknown"
+ )
+ return None
+ self._name_display_setting = setting
+ return setting
+
+ def _warn_once_if_display_names_are_hidden(self) -> None:
+ """Say so when this server will store an agent's display name and show
+ nobody. Mattermost renders a bot under its username unless the server
+ is told otherwise, so a display name Switch sets can be invisible with
+ nothing about the write itself failing."""
+ if self._name_display_warned:
+ return
+ setting = self._read_name_display_setting()
+ if setting is None or setting in _NAME_DISPLAY_SHOWS_LABEL:
+ return
+ self._name_display_warned = True
+ logger.warning(
+ "Mattermost TeamSettings.TeammateNameDisplay is '%s', so agent "
+ "display names will not appear in the post header on this server — "
+ "set it to 'full_name' or 'nickname_full_name' to render them",
+ setting,
+ )
+
# ── Bot icons ────────────────────────────────────────────────────────────
def default_agent_icon(self, agent_name: str) -> str:
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 194bd9a2d..fb6beebfc 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -412,12 +412,13 @@ class SlackAdapter(CollaborationAdapter):
elif self._channel_type_cache.get(channel_id) in ("im", "mpim"):
thread_ts = self._last_user_message_ts.get(channel_id)
+ agent = await self.agent_rendering(sender_name)
try:
result = await self._web_client.chat_postMessage(
channel=channel_id,
text=content,
- username=sender_name,
- icon_url=await self.agent_icon_url(sender_name),
+ username=agent.field_label,
+ icon_url=agent.icon_url,
thread_ts=thread_ts,
unfurl_links=False,
unfurl_media=False,
@@ -430,11 +431,11 @@ class SlackAdapter(CollaborationAdapter):
)
return None
- async def agent_icon_url(self, agent_name: str) -> str:
+ def adapt_icon_url(self, raw: str | None, agent_name: str) -> str:
# Overridden for Slack alone: it flattens a transparent avatar onto
- # white. Wrapping the resolver rather than each call site keeps every
- # place that posts as an agent on the same background.
- return on_slack_background(await super().agent_icon_url(agent_name))
+ # white. Adjusting here rather than at each call site keeps every place
+ # that posts as an agent on the same background.
+ return on_slack_background(super().adapt_icon_url(raw, agent_name))
def slash_invite_hint(self) -> str:
# Slack passes a slash command's whole tail through as free text, so the
@@ -517,10 +518,11 @@ class SlackAdapter(CollaborationAdapter):
else thread_root_id
)
+ label = await self.agent_label_for_body(sender_name)
comment = (
- f"*{sender_name}*: {self.translate_outbound(caption)}"
+ f"*{label}*: {self.translate_outbound(caption)}"
if caption
- else f"*{sender_name}* sent `{filename}`"
+ else f"*{label}* sent `{filename}`"
)
try:
@@ -587,10 +589,11 @@ class SlackAdapter(CollaborationAdapter):
)
names = ", ".join(f"`{file.filename}`" for file in files)
+ label = await self.agent_label_for_body(sender_name)
comment = (
- f"*{sender_name}*: {self.translate_outbound(caption)}"
+ f"*{label}*: {self.translate_outbound(caption)}"
if caption
- else f"*{sender_name}* sent {names}"
+ else f"*{label}* sent {names}"
)
try:
@@ -687,12 +690,13 @@ class SlackAdapter(CollaborationAdapter):
thread_ts = self._last_thread_ts.get(channel_id)
+ agent = await self.agent_rendering(sender_name)
try:
result = await self._web_client.chat_postMessage(
channel=channel_id,
text="_thinking..._",
- username=sender_name,
- icon_url=await self.agent_icon_url(sender_name),
+ username=agent.field_label,
+ icon_url=agent.icon_url,
thread_ts=thread_ts,
)
ts = result.get("ts")
@@ -1156,7 +1160,7 @@ class SlackAdapter(CollaborationAdapter):
agent_name,
)
return
- icon_url = await self.agent_icon_url(agent_name)
+ agent = await self.agent_rendering(agent_name)
open_ts = await self._call_session_api(
lambda: client.chat_startStream(
channel=channel_id,
@@ -1164,8 +1168,8 @@ class SlackAdapter(CollaborationAdapter):
recipient_user_id=requester,
recipient_team_id=self._team_id,
task_display_mode="timeline",
- username=agent_name,
- icon_url=icon_url,
+ username=agent.field_label,
+ icon_url=agent.icon_url,
),
agent_name=agent_name,
channel_id=channel_id,
@@ -1822,6 +1826,33 @@ class SlackAdapter(CollaborationAdapter):
def translate_outbound(self, content: str) -> str:
return self._markdown_to_mrkdwn(self._translate_mentions_to_slack(content))
+ def escape_label_for_body(self, label: str) -> str:
+ """Escape the three characters Slack reserves, over the base defusal.
+
+ `&`, `<` and `>` are how every piece of Slack markup is written, so
+ escaping them is what stops a label from writing a link, a user mention
+ or a `<!channel>` broadcast in Slack's own syntax.
+
+ That is not on its own enough, which is why this builds on the
+ inherited rule rather than replacing it. A label never has to reach
+ Slack in Slack's syntax: `_translate_mentions_to_slack` runs over the
+ finished body *after* the label is inlined, so a plain `@opsbot` in a
+ display name is turned into a real `<!subteam^S…>` by this bridge,
+ from text these three replacements do not touch. The `@` the base class
+ defuses is what closes that.
+
+ mrkdwn's emphasis characters (`*`, `_`, `~`, backtick) have no escape
+ sequence — Slack documents none — so a label containing them can still
+ unbalance the bold run it sits in. That is cosmetic; the markup a label
+ could forge is not, and this closes it."""
+ return (
+ super()
+ .escape_label_for_body(label)
+ .replace("&", "&amp;")
+ .replace("<", "&lt;")
+ .replace(">", "&gt;")
+ )
+
def translate_inbound(self, raw_message: str) -> str:
return self._translate_links_to_markdown(
self._translate_mentions_to_markdown(raw_message)
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
index 463316cc3..9168776ae 100644
--- a/core/switch_core/bridges/collaboration/teams/adapter.py
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -64,6 +64,7 @@ _HANDLE_SHAPE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")
# being a prefix of a longer one: `@ada` must not match inside `@adaline`.
_MENTION_END = r"(?![A-Za-z0-9._-])"
_AT_TAG = re.compile(r"<at>(.*?)</at>", re.DOTALL)
+_ZERO_WIDTH_SPACE = "\u200b"
# A Teams identifier standing where a person's name should be: a channel
# account (`29:…`, `8:orgid:…`) or a bare Entra object id.
_TEAMS_ID = re.compile(
@@ -807,18 +808,15 @@ class TeamsAdapter(CollaborationAdapter):
return self._last_post.get(channel_id)
async def _message_activity(self, sender_name: str, body: str) -> dict[str, Any]:
- icon_url = await self.agent_icon_url(sender_name)
+ agent = await self.agent_rendering(sender_name)
mentions = self._mention_entities(body)
return {
"type": "message",
# Notification/preview text; without it Teams renders a
# "cards.unsupported" placeholder in toasts, mobile, and link previews.
- "summary": f"{sender_name}: {body}",
- "attachments": [
- card_attachment(
- agent_message_card(sender_name, body, icon_url, mentions=mentions)
- )
- ],
+ # Plain text, rendered by no markup engine, so the label goes in raw.
+ "summary": f"{agent.field_label}: {body}",
+ "attachments": [card_attachment(agent_message_card(agent, body, mentions))],
}
# ── Messaging ────────────────────────────────────────────────────────────
@@ -1341,6 +1339,26 @@ class TeamsAdapter(CollaborationAdapter):
def translate_outbound(self, content: str) -> str:
return _hard_wrap(self._mark_mentions(content))
+ def escape_label_for_body(self, label: str) -> str:
+ """Add the `<at>` tag to what the base class already defuses.
+
+ The inherited `@` rule is what stops `_mark_mentions` marking up an
+ `@alice` a label carried in, and the inherited `]` rule is what stops
+ a card's TextBlock, which renders markdown, turning a label's
+ `[text](url)` into a link of its own choosing. Teams needs one
+ more: `<at>alice</at>` written straight into a label skips the marking
+ pass but is still found by `_mention_entities`, which scans the
+ rendered body for the markup and pairs whatever it finds with an entity
+ that notifies whoever `alice` actually is. A zero-width space after
+ every `<` breaks the tag.
+
+ Broken syntax rather than entity escaping, because an Adaptive Card is
+ not HTML: `&lt;` here is shown to the reader as those four
+ characters."""
+ return (
+ super().escape_label_for_body(label).replace("<", "<" + _ZERO_WIDTH_SPACE)
+ )
+
def _mark_mentions(self, content: str) -> str:
"""Wrap ``@name`` in Teams' ``<at>`` markup for people we can address.
diff --git a/core/switch_core/bridges/collaboration/teams/cards.py b/core/switch_core/bridges/collaboration/teams/cards.py
index 6731e8956..7de5e8f1c 100644
--- a/core/switch_core/bridges/collaboration/teams/cards.py
+++ b/core/switch_core/bridges/collaboration/teams/cards.py
@@ -2,14 +2,15 @@ from __future__ import annotations
from typing import Any
+from switch_core.bridges.collaboration.adapter import AgentRendering
+
ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive"
def agent_message_card(
- agent_name: str,
+ agent: AgentRendering,
body: str,
- icon_url: str,
- mentions: list[dict[str, Any]] | None = None,
+ mentions: list[dict[str, Any]],
) -> dict[str, Any]:
"""An Adaptive Card that labels a message with the sending agent's identity.
@@ -19,8 +20,11 @@ def agent_message_card(
be run through ``translate_outbound`` (Adaptive Card TextBlocks render a
markdown subset: bold, italic, links, lists).
- ``icon_url`` is resolved by the caller — the agent's own icon or the shared
- default — because looking it up is async and this builder is not.
+ ``agent`` is resolved by the caller — one lookup gives the label, its escaped
+ form and the icon — because resolving it is async and this builder is not.
+ Which form goes where is the point of taking the whole rendering: the header
+ is an ordinary TextBlock and so renders the markdown subset, while
+ ``altText`` is read out verbatim by a screen reader.
``mentions`` are Bot Framework mention entities matching ``<at>`` markup in
``body``. A card carries them under ``msteams`` rather than on the activity,
@@ -33,7 +37,7 @@ def agent_message_card(
# Plain-text representation for surfaces that can't render the card
# inline (mobile, notification toasts, copy-link/search previews); its
# absence is what makes Teams show the "cards.unsupported" placeholder.
- "fallbackText": f"{agent_name}: {body}",
+ "fallbackText": f"{agent.body_label}: {body}",
"body": [
{
"type": "ColumnSet",
@@ -44,10 +48,10 @@ def agent_message_card(
"items": [
{
"type": "Image",
- "url": icon_url,
+ "url": agent.icon_url,
"size": "Small",
"style": "Person",
- "altText": agent_name,
+ "altText": agent.field_label,
}
],
},
@@ -58,7 +62,7 @@ def agent_message_card(
"items": [
{
"type": "TextBlock",
- "text": agent_name,
+ "text": agent.body_label,
"weight": "Bolder",
"wrap": True,
"spacing": "None",
diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.py
index 688e7d2a5..06883fd45 100644
--- a/core/switch_core/bridges/collaboration/telegram/adapter.py
+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py
@@ -611,7 +611,8 @@ class TelegramAdapter(CollaborationAdapter):
Telegram offers no per-message identity, so the name is part of the body
— the same degradation Discord falls back to in DMs, applied everywhere.
"""
- body = self._attribute(sender_name, content)
+ agent = await self.agent_rendering(sender_name)
+ body = self._attribute(sender_name, agent.body_label, content)
return await self._send_text(channel_id, body, thread_root_id)
async def send_attachment(
@@ -631,8 +632,9 @@ class TelegramAdapter(CollaborationAdapter):
Falls back to the base text notice on failure so a file is never
silently dropped.
"""
+ agent = await self.agent_rendering(sender_name)
attributed = self._attribute(
- sender_name, self.translate_outbound(caption or "")
+ sender_name, agent.body_label, self.translate_outbound(caption or "")
)
caption_text, overflow_ref = await self._split_caption(
channel_id, attributed, thread_root_id
@@ -715,8 +717,9 @@ class TelegramAdapter(CollaborationAdapter):
channel_id, sender_name, files, caption, thread_root_id
)
+ agent = await self.agent_rendering(sender_name)
attributed = self._attribute(
- sender_name, self.translate_outbound(caption or "")
+ sender_name, agent.body_label, self.translate_outbound(caption or "")
)
caption_text, overflow_ref = await self._split_caption(
channel_id, attributed, thread_root_id
@@ -1012,10 +1015,11 @@ class TelegramAdapter(CollaborationAdapter):
body = self._working_body(detail, deeplink_url)
existing = self._working_msg.get(key)
if existing is not None:
+ agent = await self.agent_rendering(agent_name)
await self.update_message(
channel_id,
existing.message_ref,
- self._attribute(agent_name, body),
+ self._attribute(agent_name, agent.body_label, body),
)
self._working_msg[key] = replace(existing, body=body)
return
@@ -1900,10 +1904,18 @@ class TelegramAdapter(CollaborationAdapter):
talking. A mark that is always the same for the same agent gives a
reader something to recognise at a glance, the way an avatar would.
- Derived from the name rather than configured, so it needs no state and
- no migration and cannot disagree between two bridges. `blake2b` and not
- `hash()`: the built-in is salted per process, so it would hand the same
- agent a different colour after every restart.
+ Derived from the identifier rather than configured, so it needs no
+ state and no migration and cannot disagree between two bridges.
+ `blake2b` and not `hash()`: the built-in is salted per process, so it
+ would hand the same agent a different colour after every restart.
+
+ Keyed on the identifier and not the display name, which is the change
+ this rules out. `display_name` and `icon_url` are both owner-settable,
+ so the mark is the only per-speaker signal on a Telegram message that
+ an impersonating agent cannot control. Keyed on the label instead, two
+ agents sharing a display name would collapse onto one mark and an
+ agent's mark would move when it is renamed — losing the
+ recognisability the mark exists for.
Deliberately not a provider logo. The server only distinguishes
`claude-code` from `codex`, and Switch Console registers every other
@@ -1914,14 +1926,35 @@ class TelegramAdapter(CollaborationAdapter):
return _AGENT_MARKERS[digest[0] % len(_AGENT_MARKERS)]
@classmethod
- def _attribute(cls, sender_name: str, content: str) -> str:
+ def _attribute(cls, sender_name: str, label: str, content: str) -> str:
"""Put the agent's mark and name at the head of the body.
This is the whole of Telegram's per-message identity: one bot posts for
- every agent, so without the name a reader cannot tell them apart."""
+ every agent, so without the name a reader cannot tell them apart.
+
+ Two names, deliberately. `label` is what the reader sees; the mark
+ comes from `sender_name`, the identifier, for the reasons
+ `_agent_marker` gives.
+
+ `label` is the escaped form — `AgentRendering.body_label`, never
+ `field_label`. This prefix is message text, not a name field, and
+ Telegram has no name field at all, so the escaped form is the only one
+ that may reach here: a bare `@handle` in a display name is linked by
+ Telegram out of ordinary message text, with no markup involved, so the
+ unescaped form would notify that account from the prefix alone.
+
+ Two escapes, both needed and neither redundant. `escape_label_for_body`
+ defuses the markup, and `html.escape` below neutralises the tags; a
+ zero-width space is not an entity, so the two never compound. This
+ prefix is finished HTML — assembled after `translate_outbound` has
+ already run over `content`, and never fed back through it — so
+ `html.escape` is the whole of the tag escaping it needs. The ping line
+ the base `_ping_operator` builds is the other pipeline: it inlines the
+ same escaped label into Markdown source and lets `translate_outbound`
+ escape the whole line. Neither pipeline knows about the other and each
+ escapes exactly once."""
name = (
- f"{cls._agent_marker(sender_name)} "
- f"<b>{html.escape(sender_name, quote=False)}</b>"
+ f"{cls._agent_marker(sender_name)} <b>{html.escape(label, quote=False)}</b>"
)
if not content:
return name
diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.py
index 41909fd1d..6d460b923 100644
--- a/core/switch_core/clients/admin_client.py
+++ b/core/switch_core/clients/admin_client.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, Literal
from nio import MatrixRoom, RoomMessage, RoomMessageText
+from switch_core.agent_display_name import agent_label_with_identifier
from switch_core.bridges.agent.commands import dispatch_admin_command
from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
from switch_core.clients.admin_messages import (
@@ -201,10 +202,12 @@ class AdminClient(ClientBase[ClientConfig]):
agent = await self._agent_store.get_by_name_insensitive(session, token)
if agent is None or agent.id in member_ids:
continue
- absent.append(agent.name)
+ absent.append(
+ agent_label_with_identifier(agent.display_name, agent.name)
+ )
if not absent:
return
- names = ", ".join(f"**{name}**" for name in absent)
+ names = ", ".join(f"**{label}**" for label in absent)
verb = "isn't" if len(absent) == 1 else "aren't"
pronoun = "it" if len(absent) == 1 else "them"
handle = self._sender_handle(event)
diff --git a/core/tests/switch_core/bridges/agent/test_commands_aliases.py b/core/tests/switch_core/bridges/agent/test_commands_aliases.py
index c547ea0b3..47a100e9d 100644
--- a/core/tests/switch_core/bridges/agent/test_commands_aliases.py
+++ b/core/tests/switch_core/bridges/agent/test_commands_aliases.py
@@ -78,9 +78,15 @@ def _event(args: str) -> SimpleNamespace:
return SimpleNamespace(command="set-alias", args=args, thread_id=None)
+def _agent(
+ agent_id: str, name: str, display_name: str | None = None
+) -> SimpleNamespace:
+ return SimpleNamespace(id=agent_id, name=name, display_name=display_name)
+
+
_AGENTS = {
- "a1": SimpleNamespace(id="a1", name="claude-code.alice"),
- "a2": SimpleNamespace(id="a2", name="moderator"),
+ "a1": _agent("a1", "claude-code.alice"),
+ "a2": _agent("a2", "moderator"),
}
@@ -120,6 +126,85 @@ class TestListAliasesCommand:
assert _MENTION.search(posted[0]) is None
+class TestAliasCommandsRenderDisplayNames:
+ async def test_set_alias_names_the_agent_and_keeps_its_identifier(self) -> None:
+ agents = {"a1": _agent("a1", "switchdev", "Switch Dev")}
+ client, posted = _build_client(agents=agents, aliases={}, role_names=[])
+ await _cmd_set_alias(
+ client, _Room(room_id="!m:x"), _event("@switchdev @boss"), False
+ )
+ assert "Switch Dev (`switchdev`)" in posted[0]
+
+ async def test_set_alias_without_a_display_name_names_it_once(self) -> None:
+ client, posted = _build_client(agents=_AGENTS, aliases={}, role_names=[])
+ await _cmd_set_alias(
+ client, _Room(room_id="!m:x"), _event("@claude-code.alice @boss"), False
+ )
+ assert "**claude-code.alice**" in posted[0]
+ assert "(`claude-code.alice`)" not in posted[0]
+
+ async def test_set_alias_display_name_cannot_ping_the_channel(self) -> None:
+ agents = {"a1": _agent("a1", "switchdev", "@everyone")}
+ client, posted = _build_client(agents=agents, aliases={}, role_names=[])
+ await _cmd_set_alias(
+ client, _Room(room_id="!m:x"), _event("@switchdev @boss"), False
+ )
+ assert _MENTION.search(posted[0]) is None
+ assert "switchdev" in posted[0]
+
+ async def test_set_alias_display_name_cannot_forge_a_link(self) -> None:
+ agents = {"a1": _agent("a1", "switchdev", "[here](https://example.invalid)")}
+ client, posted = _build_client(agents=agents, aliases={}, role_names=[])
+ await _cmd_set_alias(
+ client, _Room(room_id="!m:x"), _event("@switchdev @boss"), False
+ )
+ assert "](https://example.invalid)" not in posted[0]
+
+ async def test_set_alias_echoes_a_mistyped_token_verbatim(self) -> None:
+ # The user typed the identifier, so the "no such agent" line has to
+ # quote what they typed — not some other agent's display name.
+ agents = {"a1": _agent("a1", "switchdev", "Switch Dev")}
+ client, posted = _build_client(agents=agents, aliases={}, role_names=[])
+ await _cmd_set_alias(
+ client, _Room(room_id="!m:x"), _event("@switchdevv @boss"), False
+ )
+ assert "No agent named `switchdevv`" in posted[0]
+ assert "Switch Dev" not in posted[0]
+
+ async def test_list_aliases_names_the_agent_and_keeps_its_identifier(self) -> None:
+ agents = {"a1": _agent("a1", "switchdev", "Switch Dev")}
+ client, posted = _build_client(
+ agents=agents, aliases={"a1": "boss"}, role_names=[]
+ )
+ await _cmd_list_aliases(client, _Room(room_id="!m:x"), _event(""), False)
+ # The alias itself stays bare and typeable; the agent gets its label.
+ assert "- `boss` → **Switch Dev (`switchdev`)**" in posted[0]
+
+ async def test_list_aliases_without_a_display_name_names_it_once(self) -> None:
+ client, posted = _build_client(
+ agents=_AGENTS, aliases={"a1": "boss"}, role_names=[]
+ )
+ await _cmd_list_aliases(client, _Room(room_id="!m:x"), _event(""), False)
+ assert "- `boss` → **claude-code.alice**" in posted[0]
+
+ async def test_list_aliases_display_name_cannot_ping_the_channel(self) -> None:
+ agents = {"a1": _agent("a1", "switchdev", "@everyone")}
+ client, posted = _build_client(
+ agents=agents, aliases={"a1": "boss"}, role_names=[]
+ )
+ await _cmd_list_aliases(client, _Room(room_id="!m:x"), _event(""), False)
+ assert _MENTION.search(posted[0]) is None
+ assert "switchdev" in posted[0]
+
+ async def test_list_aliases_display_name_cannot_forge_a_link(self) -> None:
+ agents = {"a1": _agent("a1", "switchdev", "[here](https://example.invalid)")}
+ client, posted = _build_client(
+ agents=agents, aliases={"a1": "boss"}, role_names=[]
+ )
+ await _cmd_list_aliases(client, _Room(room_id="!m:x"), _event(""), False)
+ assert "](https://example.invalid)" not in posted[0]
+
+
class TestAliasCommandRegistration:
def test_alias_commands_are_admin_owned(self) -> None:
# The admin client owns and renders the alias commands; agents never
diff --git a/core/tests/switch_core/bridges/agent/test_commands_display_names.py b/core/tests/switch_core/bridges/agent/test_commands_display_names.py
new file mode 100644
index 000000000..2390193ed
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_commands_display_names.py
@@ -0,0 +1,307 @@
+"""The `!` command surface renders agents under their display name.
+
+An agent's `name` routes; its `display_name` is what a person reads. These
+commands print both, one or the other, depending on whether the reader has to
+type the name back — and every one of them has to defuse the label first. A
+command reply is built here and handed straight to the bridge, which escapes
+nothing on the way out but *does* turn a plain `@handle` into a real mention,
+so a display name of `@everyone` would otherwise become a mass ping.
+"""
+
+from __future__ import annotations
+
+import re
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.agent.commands import (
+ _cmd_agents_greet,
+ _cmd_list_all_agents,
+ _cmd_list_documents,
+ _cmd_list_room_agents,
+ _cmd_roles,
+)
+
+# Matches a live `@<handle>` mention token (same char class Switch re-parses).
+_MENTION = re.compile(r"@[A-Za-z0-9._-]+")
+
+_FORGED_LINK = "[here](https://example.invalid)"
+
+
+class _Room(SimpleNamespace):
+ pass
+
+
+def _agent(
+ agent_id: str,
+ name: str,
+ display_name: str | None = None,
+ description: str = "",
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=agent_id, name=name, display_name=display_name, description=description
+ )
+
+
+def _document(doc_id: str, name: str, created_by: str | None) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=doc_id,
+ name=name,
+ description="",
+ room_id="room-1",
+ created_by_agent_id=created_by,
+ )
+
+
+def _role(role_id: str, name: str) -> SimpleNamespace:
+ return SimpleNamespace(id=role_id, name=name, exclusive=True)
+
+
+def _event(command: str) -> SimpleNamespace:
+ return SimpleNamespace(command=command, args="", thread_id=None)
+
+
+def _build_client(
+ *,
+ agents: dict[str, Any] | None = None,
+ roles: list[Any] | None = None,
+ holders: dict[str, list[str]] | None = None,
+ documents: list[Any] | None = None,
+ this_agent: Any = None,
+) -> tuple[SimpleNamespace, list[str]]:
+ """A fake host client capturing every reply body it posts."""
+ posted: list[str] = []
+ by_id = dict(agents or {})
+
+ @asynccontextmanager
+ async def _session_factory(): # type: ignore[no-untyped-def]
+ yield SimpleNamespace()
+
+ async def _resolve_room_meta(_room_id: str) -> SimpleNamespace:
+ return SimpleNamespace(room_id="room-1", name="Feature room")
+
+ async def _reply_command(_room_id, body, **_kw): # type: ignore[no-untyped-def]
+ posted.append(body)
+
+ async def _get_agent_ids(_session, _room_id): # type: ignore[no-untyped-def]
+ return list(by_id)
+
+ async def _agent_get(_session, agent_id): # type: ignore[no-untyped-def]
+ return by_id.get(agent_id)
+
+ async def _get_all(_session): # type: ignore[no-untyped-def]
+ return list(by_id.values())
+
+ async def _list_roles(_session, _room_id): # type: ignore[no-untyped-def]
+ return list(roles or [])
+
+ async def _live_holders_for_room(_session, _room_id, _live_ids): # type: ignore[no-untyped-def]
+ return dict(holders or {})
+
+ async def _list_for_room(_session, _room_id): # type: ignore[no-untyped-def]
+ return list(documents or [])
+
+ async def _fresh_agent(_session): # type: ignore[no-untyped-def]
+ return this_agent
+
+ client = SimpleNamespace(
+ agent=this_agent,
+ _fresh_agent=_fresh_agent,
+ session_factory=_session_factory,
+ _resolve_room_meta=_resolve_room_meta,
+ reply_command=_reply_command,
+ _frontend_base_url=None,
+ _room_store=SimpleNamespace(get_agent_ids=_get_agent_ids),
+ _agent_store=SimpleNamespace(get=_agent_get, get_all=_get_all),
+ _room_role_store=SimpleNamespace(
+ list_roles=_list_roles, live_holders_for_room=_live_holders_for_room
+ ),
+ _document_store=SimpleNamespace(list_for_room=_list_for_room),
+ _connections=SimpleNamespace(live_agent_ids=lambda: set()),
+ )
+ return client, posted
+
+
+class TestListRoomAgents:
+ async def test_display_name_precedes_the_identifier(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "Switch Dev", "Builds Switch")}
+ )
+ await _cmd_list_room_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert "- **Switch Dev (`switchdev`)** — Builds Switch" in posted[0]
+
+ async def test_no_display_name_names_the_identifier_once(self) -> None:
+ client, posted = _build_client(agents={"a1": _agent("a1", "switchdev")})
+ await _cmd_list_room_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert "- **switchdev**" in posted[0]
+ assert "(`switchdev`)" not in posted[0]
+
+ async def test_display_name_cannot_ping_the_channel(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "@everyone")}
+ )
+ await _cmd_list_room_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert _MENTION.search(posted[0]) is None
+ assert "switchdev" in posted[0]
+
+ async def test_display_name_cannot_forge_a_link(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", _FORGED_LINK)}
+ )
+ await _cmd_list_room_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert "](https://example.invalid)" not in posted[0]
+
+
+class TestListAllAgents:
+ async def test_display_name_precedes_the_identifier(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "Switch Dev", "Builds Switch")}
+ )
+ await _cmd_list_all_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert "- **Switch Dev (`switchdev`)** — Builds Switch" in posted[0]
+
+ async def test_no_display_name_names_the_identifier_once(self) -> None:
+ client, posted = _build_client(agents={"a1": _agent("a1", "switchdev")})
+ await _cmd_list_all_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert "- **switchdev**" in posted[0]
+ assert "(`switchdev`)" not in posted[0]
+
+ async def test_display_name_cannot_ping_the_channel(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "@everyone")}
+ )
+ await _cmd_list_all_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert _MENTION.search(posted[0]) is None
+ assert "switchdev" in posted[0]
+
+ async def test_display_name_cannot_forge_a_link(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", _FORGED_LINK)}
+ )
+ await _cmd_list_all_agents(client, _Room(room_id="!m:x"), _event("x"), False)
+ assert "](https://example.invalid)" not in posted[0]
+
+
+class TestRoles:
+ async def test_holder_is_named_by_its_display_name_alone(self) -> None:
+ # Pure attribution: there is nothing here for the reader to type, so
+ # the identifier does not need to ride along.
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "Switch Dev")},
+ roles=[_role("r1", "reviewer")],
+ holders={"r1": ["a1"]},
+ )
+ await _cmd_roles(client, _Room(room_id="!m:x"), _event("roles"), False)
+ assert (
+ "- **reviewer** _(exclusive)_ — 🟢 held by Switch Dev"
+ == posted[0].splitlines()[1]
+ )
+
+ async def test_holder_without_a_display_name_falls_back(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev")},
+ roles=[_role("r1", "reviewer")],
+ holders={"r1": ["a1"]},
+ )
+ await _cmd_roles(client, _Room(room_id="!m:x"), _event("roles"), False)
+ assert "held by switchdev" in posted[0]
+
+ async def test_holder_display_name_cannot_ping_the_channel(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "@everyone")},
+ roles=[_role("r1", "reviewer")],
+ holders={"r1": ["a1"]},
+ )
+ await _cmd_roles(client, _Room(room_id="!m:x"), _event("roles"), False)
+ assert _MENTION.search(posted[0]) is None
+
+ async def test_holder_display_name_cannot_forge_a_link(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", _FORGED_LINK)},
+ roles=[_role("r1", "reviewer")],
+ holders={"r1": ["a1"]},
+ )
+ await _cmd_roles(client, _Room(room_id="!m:x"), _event("roles"), False)
+ assert "](https://example.invalid)" not in posted[0]
+
+
+class TestListDocuments:
+ async def test_creator_is_named_by_its_display_name_alone(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "Switch Dev")},
+ documents=[_document("d1", "Runbook", "a1")],
+ )
+ await _cmd_list_documents(client, _Room(room_id="!m:x"), _event("docs"), False)
+ assert "created by Switch Dev" in posted[0]
+ assert "(`switchdev`)" not in posted[0]
+
+ async def test_creator_without_a_display_name_falls_back(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev")},
+ documents=[_document("d1", "Runbook", "a1")],
+ )
+ await _cmd_list_documents(client, _Room(room_id="!m:x"), _event("docs"), False)
+ assert "created by switchdev" in posted[0]
+
+ async def test_creator_display_name_cannot_ping_the_channel(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", "@everyone")},
+ documents=[_document("d1", "Runbook", "a1")],
+ )
+ await _cmd_list_documents(client, _Room(room_id="!m:x"), _event("docs"), False)
+ assert _MENTION.search(posted[0]) is None
+
+ async def test_creator_display_name_cannot_forge_a_link(self) -> None:
+ client, posted = _build_client(
+ agents={"a1": _agent("a1", "switchdev", _FORGED_LINK)},
+ documents=[_document("d1", "Runbook", "a1")],
+ )
+ await _cmd_list_documents(client, _Room(room_id="!m:x"), _event("docs"), False)
+ assert "](https://example.invalid)" not in posted[0]
+
+
+class TestAgentsGreet:
+ async def test_direct_greeting_uses_the_display_name(self) -> None:
+ client, posted = _build_client(
+ this_agent=_agent("a1", "switchdev", "Switch Dev")
+ )
+ await _cmd_agents_greet(client, _Room(room_id="!m:x"), _event("greet"), True)
+ assert posted[0] == "Hi! I'm Switch Dev — how can I help?"
+
+ async def test_direct_greeting_falls_back_to_the_identifier(self) -> None:
+ client, posted = _build_client(this_agent=_agent("a1", "switchdev"))
+ await _cmd_agents_greet(client, _Room(room_id="!m:x"), _event("greet"), True)
+ assert posted[0] == "Hi! I'm switchdev — how can I help?"
+
+ async def test_direct_greeting_display_name_cannot_ping_the_channel(self) -> None:
+ client, posted = _build_client(
+ this_agent=_agent("a1", "switchdev", "@everyone")
+ )
+ await _cmd_agents_greet(client, _Room(room_id="!m:x"), _event("greet"), True)
+ assert _MENTION.search(posted[0]) is None
+
+ async def test_direct_greeting_display_name_cannot_forge_a_link(self) -> None:
+ client, posted = _build_client(
+ this_agent=_agent("a1", "switchdev", _FORGED_LINK)
+ )
+ await _cmd_agents_greet(client, _Room(room_id="!m:x"), _event("greet"), True)
+ assert "](https://example.invalid)" not in posted[0]
+
+ async def test_room_greeting_keeps_the_live_mention_handle(self) -> None:
+ # The room greeting exists to teach the reader what to tag, so it stays
+ # the routing identifier however the agent is displayed.
+ client, posted = _build_client(
+ this_agent=_agent("a1", "switchdev", "Switch Dev")
+ )
+ await _cmd_agents_greet(client, _Room(room_id="!m:x"), _event("greet"), False)
+ assert "@switchdev" in posted[0]
+ assert "Switch Dev" not in posted[0]
+
+ async def test_greeting_reads_the_agent_fresh(self) -> None:
+ # `client.agent` is a boot-time snapshot; a display name edited in the
+ # gateway has to show up without restarting the client.
+ client, posted = _build_client(this_agent=_agent("a1", "switchdev"))
+ client.agent = _agent("a1", "switchdev", "Stale Name")
+ await _cmd_agents_greet(client, _Room(room_id="!m:x"), _event("greet"), True)
+ assert posted[0] == "Hi! I'm switchdev — how can I help?"
diff --git a/core/tests/switch_core/bridges/agent/test_commands_invite.py b/core/tests/switch_core/bridges/agent/test_commands_invite.py
index 88927f699..17cdc2325 100644
--- a/core/tests/switch_core/bridges/agent/test_commands_invite.py
+++ b/core/tests/switch_core/bridges/agent/test_commands_invite.py
@@ -1,11 +1,15 @@
from __future__ import annotations
+import re
from contextlib import asynccontextmanager
from types import SimpleNamespace
from typing import Any
from switch_core.bridges.agent.commands import COMMANDS_BY_NAME, _cmd_invite
+# Matches a live `@<handle>` mention token (same char class Switch re-parses).
+_MENTION = re.compile(r"@[A-Za-z0-9._-]+")
+
class _Room(SimpleNamespace):
pass
@@ -56,7 +60,13 @@ def _event(args: str) -> SimpleNamespace:
return SimpleNamespace(command="invite-agent", args=args, thread_id=None)
-_ALICE = SimpleNamespace(id="a1", name="claude-code.alice")
+def _agent(
+ agent_id: str, name: str, display_name: str | None = None
+) -> SimpleNamespace:
+ return SimpleNamespace(id=agent_id, name=name, display_name=display_name)
+
+
+_ALICE = _agent("a1", "claude-code.alice")
class TestInviteCommand:
@@ -96,6 +106,62 @@ class TestInviteCommand:
assert "Usage" in posted[0]
+class TestInviteCommandDisplayNames:
+ async def test_added_notice_names_the_agent_and_keeps_its_identifier(self) -> None:
+ agent = _agent("a1", "switchdev", "Switch Dev")
+ client, posted, added = _build_client(
+ registry={"switchdev": agent}, room_agent_ids=[]
+ )
+ await _cmd_invite(client, _Room(room_id="!m:x"), _event("@switchdev"), False)
+ # Routing still goes by the identifier, whatever it is displayed as.
+ assert added == [("room-1", ["switchdev"])]
+ assert "Added **Switch Dev (`switchdev`)** to this room." == posted[0]
+
+ async def test_already_present_notice_names_the_agent(self) -> None:
+ agent = _agent("a1", "switchdev", "Switch Dev")
+ client, posted, _added = _build_client(
+ registry={"switchdev": agent}, room_agent_ids=["a1"]
+ )
+ await _cmd_invite(client, _Room(room_id="!m:x"), _event("@switchdev"), False)
+ assert "**Switch Dev (`switchdev`)** is already in this room." == posted[0]
+
+ async def test_no_display_name_names_the_identifier_once(self) -> None:
+ client, posted, _added = _build_client(
+ registry={"claude-code.alice": _ALICE}, room_agent_ids=[]
+ )
+ await _cmd_invite(
+ client, _Room(room_id="!m:x"), _event("@claude-code.alice"), False
+ )
+ assert "Added **claude-code.alice** to this room." == posted[0]
+ assert "(`claude-code.alice`)" not in posted[0]
+
+ async def test_display_name_cannot_ping_the_channel(self) -> None:
+ agent = _agent("a1", "switchdev", "@everyone")
+ client, posted, _added = _build_client(
+ registry={"switchdev": agent}, room_agent_ids=[]
+ )
+ await _cmd_invite(client, _Room(room_id="!m:x"), _event("@switchdev"), False)
+ assert _MENTION.search(posted[0]) is None
+ assert "switchdev" in posted[0]
+
+ async def test_display_name_cannot_forge_a_link(self) -> None:
+ agent = _agent("a1", "switchdev", "[here](https://example.invalid)")
+ client, posted, _added = _build_client(
+ registry={"switchdev": agent}, room_agent_ids=["a1"]
+ )
+ await _cmd_invite(client, _Room(room_id="!m:x"), _event("@switchdev"), False)
+ assert "](https://example.invalid)" not in posted[0]
+
+ async def test_unknown_token_is_echoed_verbatim(self) -> None:
+ agent = _agent("a1", "switchdev", "Switch Dev")
+ client, posted, _added = _build_client(
+ registry={"switchdev": agent}, room_agent_ids=[]
+ )
+ await _cmd_invite(client, _Room(room_id="!m:x"), _event("@switchdevv"), False)
+ assert "No agent named `switchdevv`" in posted[0]
+ assert "Switch Dev" not in posted[0]
+
+
class TestInviteCommandRegistration:
def test_invite_is_admin_owned(self) -> None:
# The always-present admin client owns and executes `!invite-agent`;
diff --git a/core/tests/switch_core/bridges/agent/test_commands_status.py b/core/tests/switch_core/bridges/agent/test_commands_status.py
index f008dc9b4..2eac30463 100644
--- a/core/tests/switch_core/bridges/agent/test_commands_status.py
+++ b/core/tests/switch_core/bridges/agent/test_commands_status.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
from types import SimpleNamespace
from switch_core.bridges.agent.commands import (
@@ -8,18 +9,23 @@ from switch_core.bridges.agent.commands import (
)
from switch_core.bridges.agent.protocol.types import AgentStatus
+# Matches a live `@<handle>` mention token (same char class Switch re-parses).
+_MENTION = re.compile(r"@[A-Za-z0-9._-]+")
+
def _agent(
agent_id: str,
name: str,
agent_type: str,
*,
+ display_name: str | None = None,
can_delegate: bool = False,
can_accept: bool = False,
) -> SimpleNamespace:
return SimpleNamespace(
id=agent_id,
name=name,
+ display_name=display_name,
agent_type=agent_type,
integration_profile={
"task_protocol": {
@@ -132,6 +138,59 @@ class TestFormatStatusLines:
assert "Switch Console" not in out
+class TestFormatStatusLinesDisplayNames:
+ def test_display_name_precedes_the_identifier_in_backticks(self) -> None:
+ agents = [_agent("a", "switchdev", "always_on", display_name="Switch Dev")]
+ out = _format_status_lines(agents, {"a": AgentStatus.LIVE}, {}, {})
+ assert "**Switch Dev (`switchdev`)** — live" in out
+
+ def test_no_display_name_renders_the_identifier_once(self) -> None:
+ agents = [_agent("a", "switchdev", "always_on")]
+ out = _format_status_lines(agents, {"a": AgentStatus.LIVE}, {}, {})
+ assert "**switchdev** — live" in out
+ assert "(`switchdev`)" not in out
+
+ def test_a_display_name_cannot_ping_the_channel(self) -> None:
+ agents = [_agent("a", "switchdev", "always_on", display_name="@everyone")]
+ out = _format_status_lines(agents, {"a": AgentStatus.LIVE}, {}, {})
+ assert _MENTION.search(out) is None
+ assert "switchdev" in out
+
+ def test_a_display_name_cannot_forge_a_link(self) -> None:
+ agents = [
+ _agent(
+ "a",
+ "switchdev",
+ "always_on",
+ display_name="[click here](https://example.invalid)",
+ )
+ ]
+ out = _format_status_lines(agents, {"a": AgentStatus.LIVE}, {}, {})
+ assert "](https://example.invalid)" not in out
+
+ def test_order_follows_the_displayed_label(self) -> None:
+ # Sorted by identifier this reads zeta, alpha; the reader sees the
+ # display names, so those are what the order has to follow.
+ agents = [
+ _agent("z", "zeta", "always_on", display_name="Alpha Bot"),
+ _agent("a", "alpha", "always_on", display_name="Zeta Bot"),
+ ]
+ statuses = {"z": AgentStatus.LIVE, "a": AgentStatus.LIVE}
+ lines = _format_status_lines(agents, statuses, {}, {}).splitlines()
+ assert "Alpha Bot" in lines[1]
+ assert "Zeta Bot" in lines[2]
+
+ def test_order_mixes_displayed_and_bare_identifiers(self) -> None:
+ agents = [
+ _agent("w", "worker", "always_on"),
+ _agent("b", "zeta", "always_on", display_name="Bravo Bot"),
+ ]
+ statuses = {"w": AgentStatus.LIVE, "b": AgentStatus.LIVE}
+ lines = _format_status_lines(agents, statuses, {}, {}).splitlines()
+ assert "Bravo Bot" in lines[1]
+ assert "worker" in lines[2]
+
+
class TestStatusCommandRegistration:
def test_registered_and_admin_owned(self) -> None:
# Primary name is `agents-status` (Slack reserves `/status`).
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
new file mode 100644
index 000000000..39785e159
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
@@ -0,0 +1,2144 @@
+"""An agent's display name reaches the collaboration bridges — and nothing else.
+
+`agents.name` is the identifier every lookup runs on: echo suppression, the
+icon resolver, the runtime-indicator dictionaries. `agents.display_name` is
+only ever a label. These pin both halves of that: the label reaching the places
+a person reads, and the identifier still reaching the places the code matches
+on.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+import discord
+import pytest
+
+from switch_core.agent_icon import default_icon_url
+from switch_core.bridges.collaboration.adapter import (
+ AgentPresentation,
+ CollaborationAdapter,
+)
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ MattermostConnectionConfig,
+)
+from switch_core.bridges.collaboration.models import InboundMessage, OutboundAttachment
+from switch_core.bridges.collaboration.slack.adapter import (
+ SlackAdapter,
+ SlackConnectionConfig,
+)
+from switch_core.bridges.collaboration.slack.avatar import SLACK_SURFACE
+from switch_core.bridges.collaboration.teams.adapter import (
+ TeamsAdapter,
+ TeamsConnectionConfig,
+)
+from switch_core.bridges.collaboration.telegram.adapter import (
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
+
+GUILD_ID = 900
+CHANNEL_ID = 100
+DM_CHANNEL_ID = 555
+BOT_USER_ID = 42
+WEBHOOK_ID = 77
+SLACK_CHANNEL = "C123"
+SLACK_BOT_ID = "B999"
+TEAMS_CHAT = "a:1chat"
+TELEGRAM_CHAT = "-1001234567890"
+
+# A DiceBear URL with no background of its own — the only shape Slack's avatar
+# recolour can act on.
+_DICEBEAR = "https://api.dicebear.com/9.x/bottts/png?seed=worker&size=256"
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+# ── Bridge core plumbing ─────────────────────────────────────────────────────
+
+
+class _Session:
+ async def __aenter__(self) -> _Session:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+
+class _AgentStore:
+ def __init__(self, agents: dict[str, SimpleNamespace]) -> None:
+ self._agents = agents
+ self.lookups: list[str] = []
+
+ async def get_by_name(self, session: Any, name: str) -> SimpleNamespace | None:
+ self.lookups.append(name)
+ return self._agents.get(name)
+
+
+def _agent(
+ name: str, display_name: str | None, icon_url: str | None = None
+) -> SimpleNamespace:
+ return SimpleNamespace(name=name, display_name=display_name, icon_url=icon_url)
+
+
+def _bridge(*agents: SimpleNamespace) -> BridgeCore:
+ """A BridgeCore with only the two collaborators the resolver and the echo
+ check touch — the rest of `__init__` needs a live Matrix stack."""
+ bridge = BridgeCore.__new__(BridgeCore)
+ bridge._agent_store = _AgentStore({a.name: a for a in agents}) # type: ignore[assignment]
+ bridge._session_factory = _Session # type: ignore[assignment]
+ return bridge
+
+
+class _BareAdapter(CollaborationAdapter):
+ """Concrete only so it can be instantiated: the label plumbing under test
+ lives on the base class and no platform method is called."""
+
+ async def start(self, *a: Any, **k: Any) -> Any: ...
+ async def stop(self, *a: Any, **k: Any) -> Any: ...
+ async def send_message(self, *a: Any, **k: Any) -> Any: ...
+ async def send_typing(self, *a: Any, **k: Any) -> Any: ...
+ async def update_message(self, *a: Any, **k: Any) -> Any: ...
+ async def delete_message(self, *a: Any, **k: Any) -> Any: ...
+ async def create_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def get_channel_type(self, *a: Any, **k: Any) -> Any: ...
+ async def get_channel_agent_names(self, *a: Any, **k: Any) -> Any: ...
+ async def add_agents_to_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def add_users_to_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...
+ async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...
+ def translate_inbound(self, *a: Any, **k: Any) -> Any: ...
+ def translate_outbound(self, *a: Any, **k: Any) -> Any: ...
+
+
+class TestBridgeCoreResolver:
+ async def test_returns_the_agents_display_name(self) -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ found = await bridge._agent_presentation("worker")
+ assert found is not None
+ assert found.display_name == "Worker Bee"
+
+ async def test_returns_none_when_the_agent_has_no_display_name(self) -> None:
+ bridge = _bridge(_agent("worker", None))
+ found = await bridge._agent_presentation("worker")
+ assert found is not None
+ assert found.display_name is None
+
+ async def test_returns_none_for_a_name_that_is_not_an_agent(self) -> None:
+ """Bridges render aliases and third-party bots too. An unknown name is
+ not an error — the caller only wants to know whether to override."""
+ bridge = _bridge()
+ assert await bridge._agent_presentation("some-slack-bot") is None
+
+ async def test_the_label_and_the_icon_come_off_a_single_lookup(self) -> None:
+ """They live on the same row, and a send needs both — resolving them
+ separately was two round trips per message."""
+ bridge = _bridge(_agent("worker", "Worker Bee", _DICEBEAR))
+
+ assert await bridge._agent_presentation("worker") == AgentPresentation(
+ display_name="Worker Bee", icon_url=_DICEBEAR
+ )
+ assert bridge._agent_store.lookups == ["worker"] # type: ignore[attr-defined]
+
+
+class TestAdapterLabelSelection:
+ async def test_falls_back_to_the_identifier_with_no_resolver(self) -> None:
+ adapter = _BareAdapter()
+ assert (await adapter.agent_rendering("worker")).field_label == "worker"
+ assert await adapter.agent_label_for_body("worker") == "worker"
+
+ async def test_an_end_to_end_override_through_the_bridge_resolver(self) -> None:
+ """The two halves wired together, which is the thing that has to work
+ and which neither half proves on its own."""
+ bridge = _bridge(_agent("worker", "Worker Bee"), _agent("plain", None))
+ adapter = _BareAdapter()
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+
+ assert (await adapter.agent_rendering("worker")).field_label == "Worker Bee"
+ assert (await adapter.agent_rendering("plain")).field_label == "plain"
+
+ async def test_the_body_accessor_runs_the_platform_escape(self) -> None:
+ class _Escaping(_BareAdapter):
+ def escape_label_for_body(self, label: str) -> str:
+ return f"<{label}>"
+
+ adapter = _Escaping()
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+
+ assert await adapter.agent_label_for_body("worker") == "<Worker Bee>"
+ assert (await adapter.agent_rendering("worker")).field_label == "Worker Bee"
+
+ async def test_the_default_escape_leaves_a_label_alone(self) -> None:
+ """A platform whose bodies are plain text needs no escape, so the base
+ hook must not invent one."""
+ assert _BareAdapter().escape_label_for_body("a*b<c>&d") == "a*b<c>&d"
+
+ async def test_a_label_is_resolved_per_call(self) -> None:
+ """Uncached, like the icon: a renamed agent reads correctly on its next
+ message rather than at the next restart."""
+ names = iter(["First", "Second"])
+ adapter = _BareAdapter()
+
+ async def resolver(name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=next(names), icon_url=None)
+
+ adapter.set_agent_presentation_resolver(resolver)
+ assert (await adapter.agent_rendering("worker")).field_label == "First"
+ assert (await adapter.agent_rendering("worker")).field_label == "Second"
+
+ async def test_the_paired_accessor_keeps_the_body_label_separate(self) -> None:
+ """The one property the two accessors exist to hold: a caller building
+ message text cannot reach an unescaped label without saying so."""
+
+ class _Escaping(_BareAdapter):
+ def escape_label_for_body(self, label: str) -> str:
+ return f"<{label}>"
+
+ adapter = _Escaping()
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+
+ rendering = await adapter.agent_rendering("worker")
+ assert rendering.field_label == "Worker Bee"
+ assert rendering.body_label == "<Worker Bee>"
+
+ async def test_the_paired_accessor_resolves_the_icon_too(self) -> None:
+ adapter = _BareAdapter()
+ bridge = _bridge(_agent("worker", "Worker Bee", _DICEBEAR))
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+
+ assert (await adapter.agent_rendering("worker")).icon_url == _DICEBEAR
+
+ async def test_a_name_that_is_no_agent_renders_as_itself(self) -> None:
+ """A resolver answering None must leave the adapter exactly where it
+ would be with no resolver at all."""
+ adapter = _BareAdapter()
+ bridge = _bridge()
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+
+ rendering = await adapter.agent_rendering("some-slack-bot")
+ assert rendering.field_label == "some-slack-bot"
+ assert rendering.icon_url == default_icon_url("some-slack-bot")
+
+ async def test_mattermost_still_pins_the_format_of_its_default_icon(self) -> None:
+ """`default_agent_icon` is consulted through `self`, so the platform
+ that uploads the bytes rather than passing a link on keeps the response
+ format it can accept."""
+ adapter = MattermostAdapter.__new__(MattermostAdapter)
+ CollaborationAdapter.__init__(adapter)
+
+ assert await adapter.agent_icon_url("worker") == default_icon_url(
+ "worker", image_format="png"
+ )
+
+
+def test_the_resolver_is_installed_before_the_adapter_starts() -> None:
+ """Every other test here installs the resolver by hand, so without this the
+ one line that wires the two halves together in production could be deleted
+ and the whole suite would still pass — while every agent silently rendered
+ under its identifier."""
+ installed: list[Any] = []
+ started: list[str] = []
+
+ class _Adapter:
+ def set_channel_migration_handler(self, handler: Any) -> None:
+ return None
+
+ def set_agent_presentation_resolver(self, resolver: Any) -> None:
+ installed.append(resolver)
+
+ async def start(self, **kwargs: Any) -> None:
+ started.append("started")
+ assert installed, "the resolver must be installed before start()"
+
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ bridge._adapter = _Adapter() # type: ignore[assignment]
+ bridge._identity_task = None
+
+ async def _noop() -> None:
+ return None
+
+ bridge._load_channel_map = _noop # type: ignore[assignment,method-assign]
+ bridge._load_existing_puppets = _noop # type: ignore[assignment,method-assign]
+ bridge._ensure_channel_captures = _noop # type: ignore[assignment,method-assign]
+ bridge._create_agent_identities = _noop # type: ignore[assignment,method-assign]
+
+ asyncio.run(BridgeCore.start(bridge))
+
+ assert started == ["started"]
+ assert installed == [bridge._agent_presentation]
+
+
+# ── Slack ────────────────────────────────────────────────────────────────────
+
+
+class _FakeSlackClient:
+ def __init__(self) -> None:
+ self.calls: list[dict[str, Any]] = []
+ self.uploads: list[dict[str, Any]] = []
+ self.deletes: list[dict[str, Any]] = []
+ self.streams: list[dict[str, Any]] = []
+ self.appends: list[dict[str, Any]] = []
+
+ async def chat_postMessage(self, **kwargs: Any) -> dict[str, str]:
+ self.calls.append(kwargs)
+ return {"ts": f"10{len(self.calls)}.0"}
+
+ async def chat_delete(self, **kwargs: Any) -> dict[str, bool]:
+ self.deletes.append(kwargs)
+ return {"ok": True}
+
+ async def files_upload_v2(self, **kwargs: Any) -> dict[str, Any]:
+ self.uploads.append(kwargs)
+ return {"files": []}
+
+ async def chat_startStream(self, **kwargs: Any) -> dict[str, str]:
+ self.streams.append(kwargs)
+ return {"ts": "301.0"}
+
+ async def chat_appendStream(self, **kwargs: Any) -> dict[str, str]:
+ self.appends.append(kwargs)
+ return {"ts": "301.0"}
+
+
+def _slack_adapter(bridge: BridgeCore | None) -> tuple[SlackAdapter, _FakeSlackClient]:
+ adapter = SlackAdapter(
+ config=SlackConnectionConfig(
+ bot_token="xoxb-test", app_token="xapp-test", workspace_id="T123"
+ )
+ )
+ client = _FakeSlackClient()
+ adapter._web_client = client # type: ignore[assignment]
+ adapter._bot_user_id = "U1"
+ adapter._bot_id = SLACK_BOT_ID
+ adapter._channel_name_cache[SLACK_CHANNEL] = "general"
+ if bridge is not None:
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+ return adapter, client
+
+
+def test_slack_posts_under_the_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+
+ assert client.calls[0]["username"] == "Worker Bee"
+
+
+def test_slack_posts_under_the_identifier_without_a_display_name() -> None:
+ bridge = _bridge(_agent("worker", None))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+
+ assert client.calls[0]["username"] == "worker"
+
+
+def test_slack_thinking_indicator_uses_the_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_typing(SLACK_CHANNEL, "worker", True))
+
+ assert client.calls[0]["username"] == "Worker Bee"
+ # The indicator is keyed on the identifier, or clearing it would miss.
+ assert (SLACK_CHANNEL, "worker") in adapter._thinking_ts
+
+
+def test_slack_attachment_comment_uses_the_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_attachment(SLACK_CHANNEL, "worker", "cat.png", "image/png", b"x"))
+
+ assert client.uploads[0]["initial_comment"] == "*Worker Bee* sent `cat.png`"
+
+
+def test_slack_escapes_the_markup_characters_it_reserves() -> None:
+ """`<!channel>` in a label would otherwise be a room-wide ping typed into a
+ name field."""
+ bridge = _bridge(_agent("worker", "<!channel> & co"))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_attachment(SLACK_CHANNEL, "worker", "cat.png", "image/png", b"x"))
+
+ comment = client.uploads[0]["initial_comment"]
+ assert "<!channel>" not in comment
+ assert comment == "*&lt;!channel&gt; &amp; co* sent `cat.png`"
+
+
+def test_slack_leaves_the_username_field_unescaped() -> None:
+ """`username` is a JSON field Slack renders verbatim, so escaping it would
+ show the entities to the reader."""
+ bridge = _bridge(_agent("worker", "Ops & Co"))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+
+ assert client.calls[0]["username"] == "Ops & Co"
+
+
+def test_slack_session_card_opens_under_the_display_name() -> None:
+ """The streamed session card names the agent too, and is the one Slack
+ surface that goes through neither `send_message` nor `send_typing`."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, client = _slack_adapter(bridge)
+ adapter._team_id = "T123"
+ adapter._thread_requester[(SLACK_CHANNEL, "500.0")] = "U-asker"
+
+ _run(
+ adapter._drive_stream(
+ SLACK_CHANNEL,
+ "500.0",
+ "worker",
+ working=True,
+ detail="Editing foo.py",
+ deeplink_url=None,
+ )
+ )
+
+ assert client.streams[0]["username"] == "Worker Bee"
+
+
+def test_slack_session_card_opens_under_the_identifier_without_one() -> None:
+ bridge = _bridge(_agent("worker", None))
+ adapter, client = _slack_adapter(bridge)
+ adapter._team_id = "T123"
+ adapter._thread_requester[(SLACK_CHANNEL, "500.0")] = "U-asker"
+
+ _run(
+ adapter._drive_stream(
+ SLACK_CHANNEL,
+ "500.0",
+ "worker",
+ working=True,
+ detail="Editing foo.py",
+ deeplink_url=None,
+ )
+ )
+
+ assert client.streams[0]["username"] == "worker"
+
+
+def test_slack_still_draws_an_agent_icon_on_its_own_background() -> None:
+ """Slack flattens a transparent avatar onto white, so it alone recolours the
+ URL. The adjustment hangs off the shared lookup, which is exactly the sort
+ of thing a refactor of that lookup drops silently."""
+ bridge = _bridge(_agent("worker", "Worker Bee", _DICEBEAR))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+
+ assert f"backgroundColor={SLACK_SURFACE}" in client.calls[0]["icon_url"]
+
+
+def test_slack_resolves_an_agent_once_per_send() -> None:
+ """One post needs the label and the icon; they come off one row, so it must
+ be one query. Two accessors awaited back to back made it two."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _client = _slack_adapter(bridge)
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+
+ assert bridge._agent_store.lookups == ["worker"] # type: ignore[attr-defined]
+
+
+def test_slack_awaiting_input_ping_uses_the_display_name_in_both_header_and_body() -> (
+ None
+):
+ """The awaiting-input ping posts with the display label as username AND
+ inlines it into the body — the identifier must not leak into the prose."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ SLACK_CHANNEL,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="U123",
+ thread_root_id=None,
+ deeplink_url=None,
+ )
+ )
+
+ assert client.calls[-1]["username"] == "Switch Dev"
+ body = client.calls[-1]["text"]
+ assert "Switch Dev" in body
+ assert "switchdev" not in body
+
+
+def test_slack_does_not_reimport_its_own_post_made_under_a_display_name() -> None:
+ """The echo test that matters: the real send, the real inbound handler, and
+ the bridge core's real `_handle_inbound_message` behind it."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, client = _slack_adapter(bridge)
+
+ routed: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ routed.append(msg)
+ await bridge._handle_inbound_message(msg)
+
+ adapter._on_message = on_message
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+ posted = client.calls[0]
+
+ echo = {
+ "bot_id": SLACK_BOT_ID,
+ "subtype": "bot_message",
+ "channel": SLACK_CHANNEL,
+ "channel_type": "channel",
+ "ts": "101.0",
+ "text": posted["text"],
+ "username": posted["username"],
+ }
+ _run(adapter._handle_message_event(echo))
+
+ assert routed == []
+
+
+def test_slack_still_bridges_a_foreign_app_posting_under_the_same_label() -> None:
+ """Proves the echo above is dropped on the bridge's own bot id and not by
+ accident on the name — otherwise a display name would silently start
+ swallowing third-party posts."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _client = _slack_adapter(bridge)
+
+ routed: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ routed.append(msg)
+
+ adapter._on_message = on_message
+
+ _run(
+ adapter._handle_message_event(
+ {
+ "bot_id": "B-other",
+ "subtype": "bot_message",
+ "channel": SLACK_CHANNEL,
+ "channel_type": "channel",
+ "ts": "202.0",
+ "text": "hello",
+ "username": "Worker Bee",
+ }
+ )
+ )
+
+ assert [m.sender_name for m in routed] == ["Worker Bee"]
+
+
+async def test_the_bridge_echo_check_still_matches_on_the_identifier() -> None:
+ """A display name must not move the name `_is_registered_agent` looks up.
+
+ The bridge is built without `_channel_to_room`, so anything that got past
+ the echo check would raise rather than quietly pass.
+ """
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+
+ await bridge._handle_inbound_message(
+ InboundMessage(
+ channel_id=SLACK_CHANNEL,
+ channel_type="channel_public",
+ sender_id="B1",
+ sender_name="worker",
+ content="hello",
+ message_ref=f"{SLACK_CHANNEL}:1",
+ root_id=None,
+ channel_name="general",
+ )
+ )
+
+ assert bridge._agent_store.lookups == ["worker"] # type: ignore[attr-defined]
+
+
+async def test_the_bridge_echo_check_does_not_match_on_the_display_name() -> None:
+ """The other side of the invariant, stated so it cannot drift: the label is
+ not an identity. Anything that routes an agent by the name a platform
+ reports has to be handed the identifier.
+ """
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+
+ assert await bridge._is_registered_agent("worker") is True
+ assert await bridge._is_registered_agent("Worker Bee") is False
+
+
+def test_a_slack_display_name_cannot_forge_a_usergroup_mention() -> None:
+ """Escaping `&<>` stops a label writing Slack's own markup, but
+ `_translate_mentions_to_slack` runs over the finished body and turns a
+ plain `@opsbot` in the label into a real usergroup ping."""
+ bridge = _bridge(_agent("switchdev", "@opsbot"), _agent("opsbot", None))
+ adapter, client = _slack_adapter(bridge)
+ adapter._remember_agent_group("S999", "opsbot")
+
+ _run(
+ adapter._apply_runtime_state(
+ SLACK_CHANNEL,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="U123",
+ thread_root_id=None,
+ deeplink_url=None,
+ )
+ )
+
+ text = client.calls[-1]["text"]
+ assert "<!subteam^S999>" not in text
+ assert "@\u200bopsbot" in text
+
+
+# ── Discord ──────────────────────────────────────────────────────────────────
+
+
+class _FakeResponse:
+ def __init__(self, status: int = 404) -> None:
+ self.status = status
+ self.reason = "Bad Request" if status == 400 else "Not Found"
+
+
+class _FakeGuild:
+ def __init__(self) -> None:
+ self.id = GUILD_ID
+
+
+class _FakeMessage:
+ def __init__(self, channel: Any, message_id: int) -> None:
+ self.id = message_id
+ self.channel = channel
+
+
+class _FakeWebhook:
+ def __init__(self) -> None:
+ self.id = WEBHOOK_ID
+ self.name = "Switch Bridge"
+ self.token = "tok"
+ self.sent: list[dict[str, Any]] = []
+ self.uploaded: list[bytes] = []
+ self.reject_usernames: set[str] = set()
+
+ async def send(self, **kwargs: Any) -> Any:
+ file = kwargs.get("file")
+ if file is not None:
+ # The real client streams the attachment out, so an attempt — even
+ # a refused one — leaves the buffer at its end. What each attempt
+ # would actually have uploaded is recorded here.
+ self.uploaded.append(file.fp.read())
+ self.sent.append(kwargs)
+ if kwargs.get("username") in self.reject_usernames:
+ raise discord.HTTPException(_FakeResponse(400), "Invalid Form Body")
+ return _FakeMessage(_FakeChannel(), 900 + len(self.sent))
+
+
+class _FakeChannel:
+ def __init__(self, channel_id: int = CHANNEL_ID, *, dm: bool = False) -> None:
+ self.id = channel_id
+ self.guild = None if dm else _FakeGuild()
+ self.name = None if dm else "general"
+ self.sent: list[dict[str, Any]] = []
+ self.webhook = _FakeWebhook()
+
+ async def send(self, content: str, **kwargs: Any) -> Any:
+ self.sent.append({"content": content, **kwargs})
+ return _FakeMessage(self, 500 + len(self.sent))
+
+ async def webhooks(self) -> list[Any]:
+ return [self.webhook]
+
+
+class _FakeDiscordClient:
+ def __init__(self, channels: dict[int, Any]) -> None:
+ self._channels = channels
+
+ def get_channel(self, channel_id: int) -> Any | None:
+ return self._channels.get(channel_id)
+
+
+class _Author:
+ def __init__(self, user_id: int, name: str) -> None:
+ self.id = user_id
+ self.name = name
+
+
+def _gateway_message(
+ *,
+ channel: Any,
+ content: str,
+ author: _Author,
+ webhook_id: int | None = None,
+ message_id: int = 1000,
+) -> Any:
+ return SimpleNamespace(
+ id=message_id,
+ channel=channel,
+ guild=channel.guild,
+ author=author,
+ content=content,
+ webhook_id=webhook_id,
+ type=discord.MessageType.default,
+ attachments=[],
+ )
+
+
+def _discord_adapter(
+ bridge: BridgeCore | None,
+) -> tuple[DiscordAdapter, _FakeChannel, _FakeChannel]:
+ adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+ adapter._bot_user_id = BOT_USER_ID
+ channel = _FakeChannel()
+ dm = _FakeChannel(DM_CHANNEL_ID, dm=True)
+ adapter._client = _FakeDiscordClient({CHANNEL_ID: channel, DM_CHANNEL_ID: dm}) # type: ignore[assignment]
+ if bridge is not None:
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+ return adapter, channel, dm
+
+
+def test_discord_guild_webhook_posts_under_the_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(CHANNEL_ID), "worker", "hello"))
+
+ assert channel.webhook.sent[0]["username"] == "Worker Bee"
+
+
+def test_discord_guild_webhook_posts_under_the_identifier_without_one() -> None:
+ bridge = _bridge(_agent("worker", None))
+ adapter, channel, _dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(CHANNEL_ID), "worker", "hello"))
+
+ assert channel.webhook.sent[0]["username"] == "worker"
+
+
+def test_discord_dm_prefix_uses_the_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(DM_CHANNEL_ID), "worker", "hello"))
+
+ assert dm.sent[0]["content"] == "**Worker Bee**: hello"
+
+
+def test_discord_dm_prefix_uses_the_identifier_without_one() -> None:
+ bridge = _bridge(_agent("worker", None))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(DM_CHANNEL_ID), "worker", "hello"))
+
+ assert dm.sent[0]["content"] == "**worker**: hello"
+
+
+def test_discord_dm_attachment_prefix_uses_the_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(
+ adapter.send_attachment(
+ str(DM_CHANNEL_ID), "worker", "cat.png", "image/png", b"x"
+ )
+ )
+
+ assert dm.sent[0]["content"] == "**Worker Bee**"
+
+
+def test_discord_dm_attachment_does_not_let_a_display_name_ping_the_channel() -> None:
+ """The attachment branch builds its own body and passes its own send
+ options, so it has to close the same hole `send_message` does rather than
+ inherit the fix."""
+ bridge = _bridge(_agent("worker", "@everyone"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(
+ adapter.send_attachment(
+ str(DM_CHANNEL_ID), "worker", "cat.png", "image/png", b"x"
+ )
+ )
+
+ sent = dm.sent[0]
+ assert sent["content"] == "**@\u200beveryone**"
+ assert sent["allowed_mentions"].everyone is False
+
+
+def test_discord_dm_attachment_escapes_markdown_in_a_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Bo*b"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(
+ adapter.send_attachment(
+ str(DM_CHANNEL_ID), "worker", "cat.png", "image/png", b"x"
+ )
+ )
+
+ assert dm.sent[0]["content"] == r"**Bo\*b**"
+
+
+def test_discord_guild_attachment_posts_under_the_display_name() -> None:
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+
+ _run(
+ adapter.send_attachment(str(CHANNEL_ID), "worker", "cat.png", "image/png", b"x")
+ )
+
+ assert channel.webhook.sent[0]["username"] == "Worker Bee"
+
+
+def test_discord_guild_attachment_posts_under_the_identifier_without_one() -> None:
+ bridge = _bridge(_agent("worker", None))
+ adapter, channel, _dm = _discord_adapter(bridge)
+
+ _run(
+ adapter.send_attachment(str(CHANNEL_ID), "worker", "cat.png", "image/png", b"x")
+ )
+
+ assert channel.webhook.sent[0]["username"] == "worker"
+
+
+def test_a_refused_attachment_username_is_retried_with_a_fresh_file() -> None:
+ """The reason the attachment payload is rebuilt per attempt: the first
+ attempt reads the stream, so a retry that reused the same `discord.File`
+ would upload an empty file under the right name."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+ channel.webhook.reject_usernames = {"Worker Bee"}
+
+ _run(
+ adapter.send_attachment(
+ str(CHANNEL_ID), "worker", "cat.png", "image/png", b"cat-bytes"
+ )
+ )
+
+ attempts = channel.webhook.sent
+ assert [call["username"] for call in attempts] == ["Worker Bee", "worker"]
+ first, second = attempts[0]["file"], attempts[1]["file"]
+ assert isinstance(first, discord.File) and isinstance(second, discord.File)
+ assert first is not second
+ # The retry carried the whole file, not the empty tail of the first one.
+ assert channel.webhook.uploaded == [b"cat-bytes", b"cat-bytes"]
+
+
+def test_discord_dm_prefix_escapes_markdown_in_a_display_name() -> None:
+ """`**Bo*b**: hi` renders as broken bold. The label is body text, so it is
+ escaped; the identifier the send was made for is untouched."""
+ bridge = _bridge(_agent("worker", "Bo*b _the_ ~builder~"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(DM_CHANNEL_ID), "worker", "hello"))
+
+ assert dm.sent[0]["content"] == r"**Bo\*b \_the\_ \~builder\~**: hello"
+
+
+def test_discord_dm_does_not_let_a_display_name_ping_the_channel() -> None:
+ """`@everyone` in a name is an abuse vector, not a cosmetic bug. Discord
+ decides who a message pings from the raw content, so the text is defused
+ AND the send withholds the permission."""
+ bridge = _bridge(_agent("worker", "@everyone"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(DM_CHANNEL_ID), "worker", "hello"))
+
+ sent = dm.sent[0]
+ assert "@everyone" not in sent["content"]
+ assert sent["content"] == "**@\u200beveryone**: hello"
+ assert sent["allowed_mentions"].everyone is False
+
+
+def test_discord_dm_still_delivers_a_mention_the_agent_wrote() -> None:
+ """Only the mass mentions are withheld — muting everything would silently
+ break an agent that meant to tag someone."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(DM_CHANNEL_ID), "worker", "ping <@12345>"))
+
+ mentions = dm.sent[0]["allowed_mentions"]
+ assert mentions.everyone is False
+ assert mentions.users is not False
+
+
+def test_discord_leaves_the_webhook_username_unescaped() -> None:
+ """The webhook `username` is a JSON field rendered verbatim — the escaping
+ that the DM body needs would show as backslashes here."""
+ bridge = _bridge(_agent("worker", "Bo*b"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(CHANNEL_ID), "worker", "hello"))
+
+ assert channel.webhook.sent[0]["username"] == "Bo*b"
+
+
+def test_a_username_discord_refuses_falls_back_to_the_identifier() -> None:
+ """Discord validates a webhook username server-side and answers a name it
+ dislikes with a 400. Without the retry every chunk — and the truncation
+ notice — would be refused the same way and the message would be lost."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+ channel.webhook.reject_usernames = {"Worker Bee"}
+
+ ref = _run(adapter.send_message(str(CHANNEL_ID), "worker", "hello"))
+
+ assert [call["username"] for call in channel.webhook.sent] == [
+ "Worker Bee",
+ "worker",
+ ]
+ assert [call["content"] for call in channel.webhook.sent] == ["hello", "hello"]
+ assert ref is not None
+
+
+def test_a_refused_username_is_decided_once_for_the_whole_send(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """The retry lives inside the per-chunk callback, so a long message once
+ re-offered the same rejected name for every part — doubling the requests
+ and logging the substitution over and over. The refusal is latched for the
+ rest of the send instead."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+ channel.webhook.reject_usernames = {"Worker Bee"}
+
+ with caplog.at_level("WARNING"):
+ _run(adapter.send_message(str(CHANNEL_ID), "worker", "x" * 5000))
+
+ assert [call["username"] for call in channel.webhook.sent] == [
+ "Worker Bee",
+ "worker",
+ "worker",
+ "worker",
+ ]
+ refusals = [
+ r for r in caplog.records if "refused the display name" in r.getMessage()
+ ]
+ assert len(refusals) == 1
+
+
+def test_discord_resolves_an_agent_once_per_send() -> None:
+ """One webhook post needs the label and the avatar; they come off one row,
+ so it must be one query."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _channel, _dm = _discord_adapter(bridge)
+
+ _run(adapter.send_message(str(CHANNEL_ID), "worker", "hello"))
+
+ assert bridge._agent_store.lookups == ["worker"] # type: ignore[attr-defined]
+
+
+def test_a_400_is_not_retried_when_there_is_no_display_name() -> None:
+ """Retrying under the same name would just double a failure that is about
+ something other than the username."""
+ bridge = _bridge(_agent("worker", None))
+ adapter, channel, _dm = _discord_adapter(bridge)
+ channel.webhook.reject_usernames = {"worker"}
+
+ _run(adapter.send_message(str(CHANNEL_ID), "worker", "hello"))
+
+ attempts = [call for call in channel.webhook.sent if call["content"] == "hello"]
+ assert [call["username"] for call in attempts] == ["worker"]
+
+
+def test_discord_does_not_reimport_its_own_webhook_post() -> None:
+ """The guild echo path end to end: the real send registers the webhook id,
+ and the platform's echo of it is dropped before the bridge core sees it."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+
+ routed: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ routed.append(msg)
+ await bridge._handle_inbound_message(msg)
+
+ adapter._on_message = on_message
+
+ _run(adapter.send_message(str(CHANNEL_ID), "worker", "hello"))
+ posted = channel.webhook.sent[0]
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=channel,
+ content=posted["content"],
+ author=_Author(555_001, posted["username"]),
+ webhook_id=WEBHOOK_ID,
+ )
+ )
+ )
+
+ assert routed == []
+
+
+def test_discord_does_not_reimport_its_own_dm_post() -> None:
+ """The DM path posts as the bot, so the bot's own user id is what drops the
+ echo — again not the rendered name."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _channel, dm = _discord_adapter(bridge)
+
+ routed: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ routed.append(msg)
+ await bridge._handle_inbound_message(msg)
+
+ adapter._on_message = on_message
+
+ _run(adapter.send_message(str(DM_CHANNEL_ID), "worker", "hello"))
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=dm,
+ content=dm.sent[0]["content"],
+ author=_Author(BOT_USER_ID, "Worker Bee"),
+ )
+ )
+ )
+
+ assert routed == []
+
+
+def test_discord_still_bridges_a_foreign_webhook_using_the_same_label() -> None:
+ """As on Slack: the drop is keyed on the bridge's own webhook id, so a
+ display name cannot start swallowing third-party posts."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+
+ routed: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ routed.append(msg)
+
+ adapter._on_message = on_message
+ adapter._webhook_ids.add(WEBHOOK_ID)
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=channel,
+ content="hello",
+ author=_Author(555_002, "Worker Bee"),
+ webhook_id=WEBHOOK_ID + 1,
+ )
+ )
+ )
+
+ assert [m.sender_name for m in routed] == ["Worker Bee"]
+
+
+ ("label", "expected"),
+ [
+ ("plain", "plain"),
+ ("Bo*b", r"Bo\*b"),
+ ("@here", "@\u200bhere"),
+ ("<@123456789012345678>", "<\u200b@\u200b123456789012345678>"),
+ ("a`b`c", r"a\`b\`c"),
+ # Everything else Discord resolves from `<…>`: a channel link, a
+ # timestamp, a custom emoji, a slash-command link. `escape_mentions`
+ # covers none of them and backslash does not escape `<`, so the opener
+ # is broken instead.
+ ("<#123456789012345678>", "<\u200b#123456789012345678>"),
+ ("<t:1700000000:R>", "<\u200bt:1700000000:R>"),
+ ("<:name:123456789012345678>", "<\u200b:name:123456789012345678>"),
+ ("</deploy:123456789012345678>", "<\u200b/deploy:123456789012345678>"),
+ ],
+)
+def test_discord_body_escape_cases(label: str, expected: str) -> None:
+ adapter, _channel, _dm = _discord_adapter(None)
+ assert adapter.escape_label_for_body(label) == expected
+
+
+def test_a_discord_display_name_cannot_forge_a_role_mention() -> None:
+ """`escape_mentions` breaks Discord's own `@everyone`/`<@id>` syntax, but a
+ label needs no Discord syntax: `translate_outbound` resolves a bare handle
+ into a real mention after the label is already in the body."""
+ bridge = _bridge(_agent("switchdev", "@opsbot"), _agent("opsbot", None))
+ adapter, channel, _dm = _discord_adapter(bridge)
+ adapter._agent_role_ids["opsbot"] = 4242
+
+ _run(
+ adapter._apply_runtime_state(
+ str(CHANNEL_ID),
+ "switchdev",
+ "awaiting-input",
+ mention_handle="123",
+ thread_root_id=None,
+ deeplink_url=None,
+ )
+ )
+
+ content = channel.webhook.sent[-1]["content"]
+ assert "<@&4242>" not in content
+ assert "@\u200bopsbot" in content
+
+
+def test_a_discord_display_name_cannot_forge_a_user_mention() -> None:
+ bridge = _bridge(_agent("switchdev", "@alice"))
+ adapter, channel, _dm = _discord_adapter(bridge)
+ adapter._username_to_id["alice"] = 777
+
+ _run(
+ adapter._apply_runtime_state(
+ str(CHANNEL_ID),
+ "switchdev",
+ "awaiting-input",
+ mention_handle="123",
+ thread_root_id=None,
+ deeplink_url=None,
+ )
+ )
+
+ content = channel.webhook.sent[-1]["content"]
+ assert "<@777>" not in content
+ assert "@\u200balice" in content
+
+
+# ── Teams ────────────────────────────────────────────────────────────────────
+
+
+class _FakeTeamsConnector:
+ def __init__(self) -> None:
+ self.sends: list[dict[str, Any]] = []
+
+ async def send_to_conversation(
+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]
+ ) -> str:
+ self.sends.append(activity)
+ return f"MSG{len(self.sends)}"
+
+ async def update_activity(
+ self,
+ *,
+ service_url: str,
+ conversation_id: str,
+ activity_id: str,
+ activity: dict[str, Any],
+ ) -> None:
+ self.sends.append(activity)
+
+
+def _teams_adapter(
+ bridge: BridgeCore | None,
+) -> tuple[TeamsAdapter, _FakeTeamsConnector]:
+ adapter = TeamsAdapter(
+ config=TeamsConnectionConfig(
+ app_id="app-123",
+ app_password="secret",
+ tenant_id="tenant-1",
+ team_id="team-1",
+ public_base_url="https://switch.example",
+ client_state="s3cr3t",
+ )
+ )
+ connector = _FakeTeamsConnector()
+ adapter._connector = connector # type: ignore[assignment]
+ adapter._default_service_url = "https://smba.example/amer/"
+ # A flat chat, so the send is one call and nothing consults Graph for a
+ # channel layout.
+ adapter._channel_type[TEAMS_CHAT] = "direct"
+ if bridge is not None:
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+ return adapter, connector
+
+
+def _teams_card(activity: dict[str, Any]) -> dict[str, Any]:
+ return activity["attachments"][0]["content"] # type: ignore[no-any-return]
+
+
+def _teams_header(activity: dict[str, Any]) -> str:
+ return _teams_card(activity)["body"][0]["columns"][1]["items"][0]["text"] # type: ignore[no-any-return]
+
+
+def _teams_body(activity: dict[str, Any]) -> str:
+ return _teams_card(activity)["body"][1]["text"] # type: ignore[no-any-return]
+
+
+def test_teams_card_names_the_agent_by_its_display_name() -> None:
+ """Teams has one bot identity and no name field, so every surface that
+ names the agent is inside the card or the notification preview."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, connector = _teams_adapter(bridge)
+
+ _run(adapter.send_message(TEAMS_CHAT, "worker", "hello"))
+
+ activity = connector.sends[0]
+ card = _teams_card(activity)
+ assert _teams_header(activity) == "Worker Bee"
+ assert card["fallbackText"] == "Worker Bee: hello"
+ assert activity["summary"] == "Worker Bee: hello"
+ assert card["body"][0]["columns"][0]["items"][0]["altText"] == "Worker Bee"
+ assert "worker" not in _teams_header(activity)
+ assert "worker" not in card["fallbackText"]
+ assert "worker" not in activity["summary"]
+
+
+def test_teams_card_names_the_agent_by_its_identifier_without_one() -> None:
+ bridge = _bridge(_agent("worker", None))
+ adapter, connector = _teams_adapter(bridge)
+
+ _run(adapter.send_message(TEAMS_CHAT, "worker", "hello"))
+
+ activity = connector.sends[0]
+ assert _teams_header(activity) == "worker"
+ assert _teams_card(activity)["fallbackText"] == "worker: hello"
+ assert activity["summary"] == "worker: hello"
+
+
+def test_teams_awaiting_input_ping_uses_the_display_name_in_both_header_and_body() -> (
+ None
+):
+ """The ping is a card like any other message, so the label has to reach the
+ header AND the prose the base class writes — the identifier neither."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, connector = _teams_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ TEAMS_CHAT,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="Alice Example",
+ thread_root_id=None,
+ deeplink_url=None,
+ )
+ )
+
+ activity = connector.sends[-1]
+ assert _teams_header(activity) == "Switch Dev"
+ assert "Switch Dev" in _teams_body(activity)
+ assert "switchdev" not in _teams_body(activity)
+ assert "switchdev" not in _teams_header(activity)
+
+
+def test_teams_resolves_an_agent_once_per_send() -> None:
+ """The card needs the label and the avatar; they come off one row, so the
+ single icon lookup this replaced must not have become two."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, _connector = _teams_adapter(bridge)
+
+ _run(adapter.send_message(TEAMS_CHAT, "worker", "hello"))
+
+ assert bridge._agent_store.lookups == ["worker"] # type: ignore[attr-defined]
+
+
+def test_a_teams_display_name_cannot_forge_a_mention_of_a_real_person() -> None:
+ """`@alice` in a display name is a ping of whoever alice is, not a cosmetic
+ bug: the base ping inlines the label into Markdown source that
+ `translate_outbound` then runs the mention pass over, so both halves of a
+ real Teams mention are forgeable from a name alone."""
+ bridge = _bridge(_agent("switchdev", "@alice the Bot"))
+ adapter, connector = _teams_adapter(bridge)
+ adapter.prime_mention_targets({"alice": "aad-alice"})
+
+ _run(
+ adapter._apply_runtime_state(
+ TEAMS_CHAT,
+ "switchdev",
+ "awaiting-input",
+ mention_handle=None,
+ thread_root_id=None,
+ deeplink_url=None,
+ )
+ )
+
+ activity = connector.sends[-1]
+ assert "msteams" not in _teams_card(activity)
+ assert "<at>" not in _teams_body(activity)
+ assert "<at>" not in _teams_header(activity)
+
+
+def test_a_teams_display_name_cannot_carry_the_mention_markup_itself() -> None:
+ """The other half of the same hole: `<at>…</at>` written straight into a
+ name skips the marking pass, but the entity pass reads the markup back out
+ of the rendered body and pairs it."""
+ bridge = _bridge(_agent("switchdev", "<at>alice</at>"))
+ adapter, connector = _teams_adapter(bridge)
+ adapter.prime_mention_targets({"alice": "aad-alice"})
+
+ _run(
+ adapter._apply_runtime_state(
+ TEAMS_CHAT,
+ "switchdev",
+ "awaiting-input",
+ mention_handle=None,
+ thread_root_id=None,
+ deeplink_url=None,
+ )
+ )
+
+ activity = connector.sends[-1]
+ assert "msteams" not in _teams_card(activity)
+ assert "<at>alice</at>" not in _teams_body(activity)
+
+
+def test_teams_still_delivers_a_mention_the_agent_wrote() -> None:
+ """The defusal must land on the label alone — an agent that meant to tag
+ someone still tags them."""
+ bridge = _bridge(_agent("worker", "Worker Bee"))
+ adapter, connector = _teams_adapter(bridge)
+ adapter.prime_mention_targets({"alice": "aad-alice"})
+
+ _run(
+ adapter.send_message(
+ TEAMS_CHAT, "worker", adapter.translate_outbound("hi @alice")
+ )
+ )
+
+ entities = _teams_card(connector.sends[0])["msteams"]["entities"]
+ assert entities[0]["mentioned"]["id"] == "aad-alice"
+
+
+ ("label", "expected"),
+ [
+ ("plain", "plain"),
+ ("@alice the Bot", "@\u200balice the Bot"),
+ ("<at>alice</at>", "<\u200bat>alice<\u200b/at>"),
+ ("[email protected]", "mail@\u200bexample.test"),
+ (
+ "[Switch Support](https://evil.example)",
+ "[Switch Support]\u200b(https://evil.example)",
+ ),
+ ],
+)
+def test_teams_body_escape_cases(label: str, expected: str) -> None:
+ adapter, _connector = _teams_adapter(None)
+ assert adapter.escape_label_for_body(label) == expected
+
+
+def test_teams_puts_the_defused_label_only_where_markdown_renders() -> None:
+ """`altText` and `summary` render no markup, so a zero-width space in them
+ is pollution a screen reader and a notification toast would carry for
+ nothing. The header and `fallbackText` do render markdown and must carry
+ the defused form. Every other Teams test here uses a name whose two forms
+ coincide, so none of them can catch a slot swapped to the wrong one."""
+ bridge = _bridge(_agent("switchdev", "@alice the Bot"))
+ adapter, connector = _teams_adapter(bridge)
+
+ _run(adapter.send_message(TEAMS_CHAT, "switchdev", "hello"))
+
+ activity = connector.sends[0]
+ card = _teams_card(activity)
+ alt_text = card["body"][0]["columns"][0]["items"][0]["altText"]
+
+ assert _teams_header(activity) == "@\u200balice the Bot"
+ assert card["fallbackText"] == "@\u200balice the Bot: hello"
+ assert "@alice the Bot" not in _teams_header(activity)
+ assert "@alice the Bot" not in card["fallbackText"]
+
+ assert alt_text == "@alice the Bot"
+ assert activity["summary"] == "@alice the Bot: hello"
+ assert "@\u200balice the Bot" not in alt_text
+ assert "@\u200balice the Bot" not in activity["summary"]
+
+
+def test_a_teams_display_name_cannot_forge_a_link_in_the_header() -> None:
+ """An Adaptive Card TextBlock renders markdown links, and the header is
+ where the speaker's name goes — so `[text](url)` in a name is a destination
+ of the name's choosing wearing the speaker's identity."""
+ bridge = _bridge(_agent("switchdev", "[Switch Support](https://evil.example)"))
+ adapter, connector = _teams_adapter(bridge)
+
+ _run(adapter.send_message(TEAMS_CHAT, "switchdev", "hello"))
+
+ activity = connector.sends[0]
+ for rendered in (
+ _teams_header(activity),
+ _teams_card(activity)["fallbackText"],
+ _teams_body(activity),
+ ):
+ assert "](" not in rendered
+ assert "](https://evil.example)" not in rendered
+
+
+# ── Telegram ─────────────────────────────────────────────────────────────────
+
+
+class _FakeTelegramBot:
+ def __init__(self) -> None:
+ self.messages: list[dict[str, Any]] = []
+ self.photos: list[dict[str, Any]] = []
+ self.albums: list[dict[str, Any]] = []
+ self.edits: list[dict[str, Any]] = []
+ self._next_id = 500
+
+ def _mint(self, chat_id: Any) -> Any:
+ self._next_id += 1
+ return SimpleNamespace(
+ chat=SimpleNamespace(id=int(chat_id)), message_id=self._next_id
+ )
+
+ async def send_message(self, **kwargs: Any) -> Any:
+ self.messages.append(kwargs)
+ return self._mint(kwargs["chat_id"])
+
+ async def send_photo(self, **kwargs: Any) -> Any:
+ self.photos.append(kwargs)
+ return self._mint(kwargs["chat_id"])
+
+ async def send_media_group(self, **kwargs: Any) -> list[Any]:
+ self.albums.append(kwargs)
+ return [self._mint(kwargs["chat_id"]) for _ in kwargs["media"]]
+
+ async def edit_message_text(self, **kwargs: Any) -> None:
+ self.edits.append(kwargs)
+
+
+def _telegram_adapter(
+ bridge: BridgeCore | None,
+) -> tuple[TelegramAdapter, _FakeTelegramBot]:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(
+ bot_token="token", bot_username="acme_switch_bot"
+ )
+ )
+ bot = _FakeTelegramBot()
+ adapter._bot = bot # type: ignore[assignment]
+ adapter._bot_user_id = BOT_USER_ID
+ if bridge is not None:
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+ return adapter, bot
+
+
+def _telegram_mark(text: str) -> str:
+ return text.split()[0]
+
+
+def test_telegram_prefixes_a_message_with_the_display_name() -> None:
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, bot = _telegram_adapter(bridge)
+
+ _run(adapter.send_message(TELEGRAM_CHAT, "switchdev", "on it"))
+
+ text = bot.messages[0]["text"]
+ assert text.endswith("<b>Switch Dev</b>: on it")
+ assert "switchdev" not in text
+
+
+def test_telegram_prefixes_a_message_with_the_identifier_without_one() -> None:
+ bridge = _bridge(_agent("switchdev", None))
+ adapter, bot = _telegram_adapter(bridge)
+
+ _run(adapter.send_message(TELEGRAM_CHAT, "switchdev", "on it"))
+
+ assert bot.messages[0]["text"].endswith("<b>switchdev</b>: on it")
+
+
+def test_telegram_attachment_caption_uses_the_display_name() -> None:
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, bot = _telegram_adapter(bridge)
+
+ _run(
+ adapter.send_attachment(
+ TELEGRAM_CHAT, "switchdev", "chart.png", "image/png", b"x", "the chart"
+ )
+ )
+
+ caption = bot.photos[0]["caption"]
+ assert caption.endswith("<b>Switch Dev</b>: the chart")
+ assert "switchdev" not in caption
+
+
+def test_telegram_album_caption_uses_the_display_name() -> None:
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, bot = _telegram_adapter(bridge)
+ files = [
+ OutboundAttachment(filename="a.png", mimetype="image/png", data=b"a"),
+ OutboundAttachment(filename="b.png", mimetype="image/png", data=b"b"),
+ ]
+
+ _run(adapter.send_attachments(TELEGRAM_CHAT, "switchdev", files, "two charts"))
+
+ caption = bot.albums[0]["media"][0].caption
+ assert caption.endswith("<b>Switch Dev</b>: two charts")
+ assert "switchdev" not in caption
+
+
+def test_telegram_runtime_status_edit_keeps_the_display_name() -> None:
+ """The live "working on it…" card is edited in place rather than reposted,
+ and that edit rebuilds the prefix itself instead of going through
+ `send_message`."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, bot = _telegram_adapter(bridge)
+
+ for detail in ("Reading foo.py", "Editing foo.py"):
+ _run(
+ adapter._apply_runtime_state(
+ TELEGRAM_CHAT,
+ "switchdev",
+ "working",
+ mention_handle=None,
+ thread_root_id=None,
+ detail=detail,
+ )
+ )
+
+ edited = bot.edits[0]["text"]
+ assert "<b>Switch Dev</b>" in edited
+ assert "switchdev" not in edited
+ assert "Editing foo.py" in edited
+
+
+def test_telegram_escapes_a_display_name_exactly_once_in_the_prefix() -> None:
+ """The prefix is finished HTML, escaped by `_attribute` and nothing else,
+ so one `html.escape` is the whole of what it needs. The body escape inserts
+ zero-width spaces rather than entities, so it cannot contribute a second
+ round here."""
+ bridge = _bridge(_agent("switchdev", "R&D <Bot>"))
+ adapter, bot = _telegram_adapter(bridge)
+
+ _run(adapter.send_message(TELEGRAM_CHAT, "switchdev", "on it"))
+
+ text = bot.messages[0]["text"]
+ assert text.endswith("<b>R&amp;D &lt;Bot&gt;</b>: on it")
+ assert "&amp;amp;" not in text
+
+
+def test_telegram_escapes_a_display_name_exactly_once_in_the_ping() -> None:
+ """The other pipeline, and the one that double-escaped: the base builds the
+ ping text around the label and hands the whole line to `translate_outbound`,
+ which escapes it. Both halves of this message carry the same name, and both
+ must have been escaped once."""
+ bridge = _bridge(_agent("switchdev", "R&D <Bot>"))
+ adapter, bot = _telegram_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ TELEGRAM_CHAT,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="opslead",
+ thread_root_id=None,
+ )
+ )
+
+ text = bot.messages[-1]["text"]
+ assert text.count("R&amp;D &lt;Bot&gt;") == 2
+ assert "&amp;amp;" not in text
+ assert "&lt;b&gt;" not in text
+
+
+def test_telegram_marks_two_agents_sharing_a_display_name_apart() -> None:
+ """The mark is the only thing distinguishing agents under one bot identity.
+ Keyed on the label, two agents a person happened to name the same would be
+ indistinguishable — which is the whole failure the mark exists to prevent."""
+ bridge = _bridge(_agent("scout", "Switch Dev"), _agent("ranger", "Switch Dev"))
+ adapter, bot = _telegram_adapter(bridge)
+
+ _run(adapter.send_message(TELEGRAM_CHAT, "scout", "one"))
+ _run(adapter.send_message(TELEGRAM_CHAT, "ranger", "two"))
+
+ scout, ranger = bot.messages[0]["text"], bot.messages[1]["text"]
+ assert _telegram_mark(scout) != _telegram_mark(ranger)
+ assert "<b>Switch Dev</b>" in scout
+ assert "<b>Switch Dev</b>" in ranger
+
+
+def test_a_telegram_agents_mark_does_not_move_when_it_is_renamed() -> None:
+ """A mark that jumped on a rename would stop being something a reader can
+ learn, so it stays keyed on the identifier."""
+ named, _bot_named = _telegram_adapter(_bridge(_agent("scout", "Switch Dev")))
+ plain, _bot_plain = _telegram_adapter(_bridge(_agent("scout", None)))
+
+ _run(named.send_message(TELEGRAM_CHAT, "scout", "one"))
+ _run(plain.send_message(TELEGRAM_CHAT, "scout", "one"))
+
+ assert _telegram_mark(_bot_named.messages[0]["text"]) == _telegram_mark(
+ _bot_plain.messages[0]["text"]
+ )
+
+
+ ("label", "expected"),
+ [
+ ("plain", "plain"),
+ ("@ceo_person", "@\u200bceo_person"),
+ (
+ "[Switch Support](https://evil.example)",
+ "[Switch Support]\u200b(https://evil.example)",
+ ),
+ # No entities inserted, which is what lets the prefix and the ping each
+ # stay a single escape.
+ ("R&D <Bot>", "R&D <Bot>"),
+ ],
+)
+def test_telegram_body_escape_cases(label: str, expected: str) -> None:
+ adapter, _bot = _telegram_adapter(None)
+ assert adapter.escape_label_for_body(label) == expected
+
+
+def test_a_telegram_display_name_cannot_forge_a_mention_of_a_real_person() -> None:
+ """A `tg://user?id=` anchor is a hard mention: Telegram notifies that
+ account whatever the visible text says. The ping inlines the label into
+ Markdown source the mention pass then runs over, so one is forgeable from a
+ display name alone."""
+ bridge = _bridge(_agent("switchdev", "@ceo_person"))
+ adapter, bot = _telegram_adapter(bridge)
+ adapter._username_to_id["ceo_person"] = 777
+
+ _run(
+ adapter._apply_runtime_state(
+ TELEGRAM_CHAT,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="opslead",
+ thread_root_id=None,
+ )
+ )
+
+ text = bot.messages[-1]["text"]
+ assert "tg://user?id=777" not in text
+ assert "tg://user" not in text
+
+
+def test_a_telegram_display_name_cannot_forge_a_link() -> None:
+ """Both halves of `[text](url)` are the name's to choose, and the anchor
+ lands in the sentence naming who is speaking."""
+ bridge = _bridge(_agent("switchdev", "[Switch Support](https://evil.example)"))
+ adapter, bot = _telegram_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ TELEGRAM_CHAT,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="opslead",
+ thread_root_id=None,
+ )
+ )
+
+ text = bot.messages[-1]["text"]
+ assert 'href="https://evil.example"' not in text
+ assert "<a href" not in text
+
+
+def test_a_telegram_display_name_cannot_mention_from_the_prefix() -> None:
+ """The prefix is message text, not a name field, so it takes the escaped
+ label too. Telegram links a bare `@handle` out of ordinary text with no
+ markup involved, so an undefused prefix notifies that account without ever
+ producing the `tg://user` anchor the ping-half tests look for — which is
+ why this asserts on the handle rather than on the anchor."""
+ bridge = _bridge(_agent("switchdev", "@ceo_person"))
+ adapter, bot = _telegram_adapter(bridge)
+ adapter._username_to_id["ceo_person"] = 777
+
+ _run(adapter.send_message(TELEGRAM_CHAT, "switchdev", "on it"))
+
+ text = bot.messages[-1]["text"]
+ assert "@\u200bceo_person" in text
+ assert "@ceo_person" not in text
+
+
+def test_telegram_defuses_the_label_in_every_prefix_it_builds() -> None:
+ """Four call sites build a prefix; the plain send is only one of them. An
+ attachment caption, an album caption and the in-place runtime edit each
+ assemble their own, so each has to reach for the escaped label itself."""
+ bridge = _bridge(_agent("switchdev", "@ceo_person"))
+ adapter, bot = _telegram_adapter(bridge)
+ files = [
+ OutboundAttachment(filename="a.png", mimetype="image/png", data=b"a"),
+ OutboundAttachment(filename="b.png", mimetype="image/png", data=b"b"),
+ ]
+
+ _run(
+ adapter.send_attachment(
+ TELEGRAM_CHAT, "switchdev", "chart.png", "image/png", b"x", "the chart"
+ )
+ )
+ _run(adapter.send_attachments(TELEGRAM_CHAT, "switchdev", files, "two charts"))
+ for detail in ("Reading foo.py", "Editing foo.py"):
+ _run(
+ adapter._apply_runtime_state(
+ TELEGRAM_CHAT,
+ "switchdev",
+ "working",
+ mention_handle=None,
+ thread_root_id=None,
+ detail=detail,
+ )
+ )
+
+ built = [
+ bot.photos[0]["caption"],
+ bot.albums[0]["media"][0].caption,
+ bot.edits[0]["text"],
+ ]
+ for prefix in built:
+ assert "@\u200bceo_person" in prefix
+ assert "@ceo_person" not in prefix
+
+
+def test_telegram_still_delivers_a_mention_the_agent_wrote() -> None:
+ """The defusal must land on the label alone — an agent that meant to tag
+ someone still tags them."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, bot = _telegram_adapter(bridge)
+ adapter.prime_mention_targets({"opslead": "777"})
+
+ _run(
+ adapter.send_message(
+ TELEGRAM_CHAT, "switchdev", adapter.translate_outbound("ping @opslead")
+ )
+ )
+
+ assert '<a href="tg://user?id=777">@opslead</a>' in bot.messages[-1]["text"]
+
+
+def test_telegram_resolves_an_agent_once_per_send() -> None:
+ """The prefix needs the label and the mark; both come off one row, so one
+ message must be one query."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, _bot = _telegram_adapter(bridge)
+
+ _run(adapter.send_message(TELEGRAM_CHAT, "switchdev", "on it"))
+
+ assert bridge._agent_store.lookups == ["switchdev"] # type: ignore[attr-defined]
+
+
+def test_telegram_resolves_an_agent_once_for_a_whole_album() -> None:
+ """An album is one message however many files it carries. Resolving inside
+ the per-file loop made it one query per file, growing with the batch."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, _bot = _telegram_adapter(bridge)
+ files = [
+ OutboundAttachment(filename="a.png", mimetype="image/png", data=b"a"),
+ OutboundAttachment(filename="b.png", mimetype="image/png", data=b"b"),
+ ]
+
+ _run(adapter.send_attachments(TELEGRAM_CHAT, "switchdev", files, "two charts"))
+
+ assert bridge._agent_store.lookups == ["switchdev"] # type: ignore[attr-defined]
+
+
+# ── Mattermost ───────────────────────────────────────────────────────────────
+
+
+MATTERMOST_CHANNEL = "mm-channel-1"
+
+
+def _mattermost_adapter(
+ bridge: BridgeCore | None,
+) -> tuple[MattermostAdapter, list[str]]:
+ """Mattermost carries the label in two places: the inherited operator ping,
+ covered here, and the per-agent bot's own `display_name`, covered by the
+ identity tests below. This capture is of `send_message` rather than of a
+ platform client because the ping never reaches one."""
+ adapter = MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mattermost.invalid",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+ sent: list[str] = []
+
+ async def send_message(
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str:
+ sent.append(content)
+ return "post-1"
+
+ adapter.send_message = send_message # type: ignore[method-assign]
+ if bridge is not None:
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+ return adapter, sent
+
+
+ ("label", "expected"),
+ [
+ ("plain", "plain"),
+ ("Switch Dev", "Switch Dev"),
+ ("@channel", "@\u200bchannel"),
+ ("@here", "@\u200bhere"),
+ ("@all", "@\u200ball"),
+ (
+ "[Switch Support](https://evil.example)",
+ "[Switch Support]\u200b(https://evil.example)",
+ ),
+ ("Bo*b_x", "Bo*b_x"),
+ ],
+)
+def test_mattermost_body_escape_cases(label: str, expected: str) -> None:
+ adapter, _sent = _mattermost_adapter(None)
+ assert adapter.escape_label_for_body(label) == expected
+
+
+def test_mattermost_awaiting_input_ping_uses_the_display_name() -> None:
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, sent = _mattermost_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ MATTERMOST_CHANNEL,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="opslead",
+ thread_root_id=None,
+ )
+ )
+
+ assert "**Switch Dev**" in sent[-1]
+ assert "switchdev" not in sent[-1]
+
+
+def test_a_mattermost_display_name_cannot_address_the_whole_channel() -> None:
+ """Switch ships Markdown verbatim, so an undefused `@channel` in the label
+ is resolved by Mattermost itself and notifies everyone in the room."""
+ bridge = _bridge(_agent("switchdev", "@channel"))
+ adapter, sent = _mattermost_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ MATTERMOST_CHANNEL,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="opslead",
+ thread_root_id=None,
+ )
+ )
+
+ assert "@\u200bchannel" in sent[-1]
+ assert "@channel" not in sent[-1]
+
+
+def test_a_mattermost_display_name_cannot_forge_a_link() -> None:
+ bridge = _bridge(_agent("switchdev", "[Switch Support](https://evil.example)"))
+ adapter, sent = _mattermost_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ MATTERMOST_CHANNEL,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="opslead",
+ thread_root_id=None,
+ )
+ )
+
+ assert "](https://evil.example)" not in sent[-1]
+ assert "]\u200b(https://evil.example)" in sent[-1]
+
+
+def test_mattermost_still_delivers_the_owner_ping() -> None:
+ """The defusal lands on the label alone — the operator handle the ping is
+ built around is not the label and must still resolve."""
+ bridge = _bridge(_agent("switchdev", "@channel"))
+ adapter, sent = _mattermost_adapter(bridge)
+
+ _run(
+ adapter._apply_runtime_state(
+ MATTERMOST_CHANNEL,
+ "switchdev",
+ "awaiting-input",
+ mention_handle="opslead",
+ thread_root_id=None,
+ )
+ )
+
+ assert sent[-1].startswith("@opslead ")
+
+
+# ── Mattermost bot identities ────────────────────────────────────────────────
+#
+# Mattermost is the one platform that gives an agent an account of its own. Its
+# `username` is the routing handle — the mention, the channel member-list key,
+# the key an existing bot is adopted back by — and is also constrained to 3-22
+# lowercase alphanumerics, so it stays the identifier. The bot's separate
+# `display_name` field is the presentation half, and the only place the label
+# may land.
+
+
+class _MattermostAdmin:
+ """The slice of a Mattermost `Driver` the identity path reaches.
+
+ Every `_mm_api` call goes through `client.make_request`, so the fake
+ answers at that level and records the calls verbatim — the assertions are
+ about the exact bodies Switch sends to `/bots`."""
+
+ def __init__(self, bots: list[dict[str, Any]], name_display: str | None) -> None:
+ self._bots = bots
+ self._name_display = name_display
+ self.requests: list[tuple[str, str, dict[str, Any] | None]] = []
+ self.client = SimpleNamespace(make_request=self._make_request)
+ self.teams = SimpleNamespace(add_user_to_team=lambda team_id, body: None)
+
+ def _make_request(
+ self, method: str, endpoint: str, options: dict[str, Any] | None = None
+ ) -> Any:
+ self.requests.append((method, endpoint, options))
+ payload = self._respond(method, endpoint, options)
+ return SimpleNamespace(json=lambda: payload)
+
+ def _respond(
+ self, method: str, endpoint: str, options: dict[str, Any] | None
+ ) -> Any:
+ if method == "get" and endpoint == "/config":
+ if self._name_display is None:
+ raise RuntimeError("config is readable by system admins only")
+ return {"TeamSettings": {"TeammateNameDisplay": self._name_display}}
+ if method == "get" and endpoint.startswith("/bots?"):
+ return self._bots
+ if method == "post" and endpoint == "/bots":
+ assert options is not None
+ return {"user_id": f"bot-{options['username']}"}
+ if method == "put" and endpoint.startswith("/bots/"):
+ return {}
+ if method == "post" and endpoint.endswith("/tokens"):
+ return {"token": "placeholder-bot-token"}
+ raise AssertionError(f"unexpected Mattermost call: {method} {endpoint}")
+
+ def bodies(self, method: str, endpoint: str) -> list[dict[str, Any] | None]:
+ return [
+ options for m, e, options in self.requests if m == method and e == endpoint
+ ]
+
+
+class _MattermostBot:
+ """A per-agent bot driver. It logs in and then parks in its websocket, as
+ the real one does — the identity path starts that thread as a daemon and
+ never joins it."""
+
+ def login(self) -> None:
+ return None
+
+ async def init_websocket(self, handler: Any) -> None:
+ await asyncio.Event().wait()
+
+
+def _mattermost_identity_adapter(
+ bridge: BridgeCore, bots: list[dict[str, Any]], name_display: str | None
+) -> tuple[MattermostAdapter, _MattermostAdmin]:
+ """An adapter wired for `create_agent_identity`: a fake admin driver, and
+ stubs for the icon upload (its own concern, covered elsewhere) and the bot
+ driver factory. `name_display` of None makes the config read fail, which is
+ what a non-admin bridge account sees."""
+ adapter = MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mattermost.invalid",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+ admin = _MattermostAdmin(bots, name_display)
+ adapter._admin_driver = admin # type: ignore[assignment]
+ adapter._team_id = "team-1"
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
+
+ async def set_bot_icon(bot_id: str, agent_name: str) -> None:
+ return None
+
+ adapter._set_bot_icon = set_bot_icon # type: ignore[method-assign]
+ adapter._create_driver = lambda **kwargs: _MattermostBot() # type: ignore[assignment,method-assign,return-value]
+ return adapter, admin
+
+
+def _create_mattermost_identity(adapter: MattermostAdapter, *agent_names: str) -> None:
+ async def _go() -> None:
+ adapter._main_loop = asyncio.get_running_loop()
+ for name in agent_names:
+ await adapter.create_agent_identity(name, "a Switch agent")
+
+ _run(_go())
+
+
+def test_mattermost_creates_the_bot_under_the_display_name() -> None:
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, admin = _mattermost_identity_adapter(bridge, [], "full_name")
+
+ _create_mattermost_identity(adapter, "switchdev")
+
+ assert admin.bodies("post", "/bots") == [
+ {
+ "username": "switchdev",
+ "display_name": "Switch Dev",
+ "description": "Switch agent: a Switch agent",
+ }
+ ]
+
+
+def test_a_mattermost_bot_username_is_never_the_display_name() -> None:
+ """The hazard the whole split exists for: a username is the routing handle
+ and is also constrained to lowercase alphanumerics, so a label like this
+ one would not even be a legal username."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev (EMEA)"))
+ adapter, admin = _mattermost_identity_adapter(bridge, [], "full_name")
+
+ _create_mattermost_identity(adapter, "switchdev")
+
+ body = admin.bodies("post", "/bots")[0]
+ assert body is not None
+ assert body["username"] == "switchdev"
+ assert adapter._agent_bots["switchdev"]["username"] == "switchdev"
+ assert adapter._bot_id_to_username == {"bot-switchdev": "switchdev"}
+
+
+def test_a_mattermost_bot_display_name_is_not_escaped_for_message_text() -> None:
+ """`display_name` is a name field Mattermost renders on its own, so it
+ takes the label verbatim. Sending the body form instead would bake the
+ zero-width spaces that defuse markup into the stored name — invisible in a
+ diff, and permanent on the account."""
+ bridge = _bridge(_agent("switchdev", "Switch @ Dev [EMEA]"))
+ adapter, admin = _mattermost_identity_adapter(bridge, [], "full_name")
+
+ _create_mattermost_identity(adapter, "switchdev")
+
+ body = admin.bodies("post", "/bots")[0]
+ assert body is not None
+ assert body["display_name"] == "Switch @ Dev [EMEA]"
+ assert "​" not in body["display_name"]
+
+
+def test_a_mattermost_bot_falls_back_to_the_identifier() -> None:
+ bridge = _bridge(_agent("switchdev", None))
+ adapter, admin = _mattermost_identity_adapter(bridge, [], "full_name")
+
+ _create_mattermost_identity(adapter, "switchdev")
+
+ body = admin.bodies("post", "/bots")[0]
+ assert body is not None
+ assert body["display_name"] == "switchdev"
+
+
+def test_adopting_a_mattermost_bot_repairs_a_stale_display_name() -> None:
+ """The icon is re-applied on the adopt path as well as the create path, so
+ a renamed agent whose bot already exists must not be the one thing that
+ keeps its old name forever."""
+ existing = {
+ "user_id": "bot-switchdev",
+ "username": "switchdev",
+ "display_name": "Switch Dev",
+ }
+ bridge = _bridge(_agent("switchdev", "Switch Developer"))
+ adapter, admin = _mattermost_identity_adapter(bridge, [existing], "full_name")
+
+ _create_mattermost_identity(adapter, "switchdev")
+
+ assert admin.bodies("put", "/bots/bot-switchdev") == [
+ {"display_name": "Switch Developer"}
+ ]
+ assert admin.bodies("post", "/bots") == []
+
+
+def test_adopting_a_mattermost_bot_leaves_a_current_display_name_alone() -> None:
+ existing = {
+ "user_id": "bot-switchdev",
+ "username": "switchdev",
+ "display_name": "Switch Dev",
+ }
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, admin = _mattermost_identity_adapter(bridge, [existing], "full_name")
+
+ _create_mattermost_identity(adapter, "switchdev")
+
+ assert [m for m, _e, _o in admin.requests if m == "put"] == []
+
+
+def _name_display_warnings(caplog: pytest.LogCaptureFixture) -> list[str]:
+ return [
+ r.getMessage()
+ for r in caplog.records
+ if r.levelname == "WARNING" and "TeammateNameDisplay" in r.getMessage()
+ ]
+
+
+def test_mattermost_warns_when_the_server_will_not_render_display_names(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """`TeammateNameDisplay` defaults to "username", under which the display
+ name is stored and never seen. Setting it silently would be the degrade
+ that looks fine."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, _admin = _mattermost_identity_adapter(bridge, [], "username")
+
+ with caplog.at_level("WARNING"):
+ _create_mattermost_identity(adapter, "switchdev")
+
+ assert len(_name_display_warnings(caplog)) == 1
+ assert "will not appear in the post header" in _name_display_warnings(caplog)[0]
+
+
+def test_mattermost_does_not_warn_when_the_server_renders_display_names(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, _admin = _mattermost_identity_adapter(bridge, [], "full_name")
+
+ with caplog.at_level("WARNING"):
+ _create_mattermost_identity(adapter, "switchdev")
+
+ assert _name_display_warnings(caplog) == []
+
+
+def test_mattermost_does_not_warn_when_no_agent_has_a_display_name(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Nothing to render, nothing to warn about — and no reason to ask the
+ server about a setting that changes nothing here."""
+ bridge = _bridge(_agent("switchdev", None))
+ adapter, admin = _mattermost_identity_adapter(bridge, [], "username")
+
+ with caplog.at_level("WARNING"):
+ _create_mattermost_identity(adapter, "switchdev")
+
+ assert _name_display_warnings(caplog) == []
+ assert [e for _m, e, _o in admin.requests if e == "/config"] == []
+
+
+def test_mattermost_reads_the_name_display_setting_once_per_run(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ bridge = _bridge(_agent("switchdev", "Switch Dev"), _agent("opsbot", "Ops Bot"))
+ adapter, admin = _mattermost_identity_adapter(bridge, [], "username")
+
+ with caplog.at_level("WARNING"):
+ _create_mattermost_identity(adapter, "switchdev", "opsbot")
+
+ assert [e for _m, e, _o in admin.requests if e == "/config"] == ["/config"]
+ assert len(_name_display_warnings(caplog)) == 1
+
+
+def test_a_mattermost_bot_is_created_even_when_the_setting_cannot_be_read(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """The server config is readable by a system admin only. Not knowing is
+ said out loud, and is not a reason to leave the agent without a bot."""
+ bridge = _bridge(_agent("switchdev", "Switch Dev"))
+ adapter, admin = _mattermost_identity_adapter(bridge, [], None)
+
+ with caplog.at_level("WARNING"):
+ _create_mattermost_identity(adapter, "switchdev")
+
+ body = admin.bodies("post", "/bots")[0]
+ assert body is not None
+ assert body["display_name"] == "Switch Dev"
+ assert "switchdev" in adapter._agent_bots
+ warnings = [
+ r.getMessage()
+ for r in caplog.records
+ if r.levelname == "WARNING" and "server config" in r.getMessage()
+ ]
+ assert len(warnings) == 1
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
index 948089706..f4c95fcf7 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
@@ -12,7 +12,10 @@ from types import SimpleNamespace
from typing import Any
from switch_core.agent_icon import default_icon_url
-from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.adapter import (
+ AgentPresentation,
+ CollaborationAdapter,
+)
from switch_core.bridges.collaboration.bridge_core import BridgeCore
_CUSTOM = "https://cdn.example.com/9.x/bottts/png?seed=chosen"
@@ -42,7 +45,7 @@ def _bridge(agents: dict[str, SimpleNamespace]) -> BridgeCore:
def _agent(icon_url: str | None) -> SimpleNamespace:
- return SimpleNamespace(name="worker", icon_url=icon_url)
+ return SimpleNamespace(name="worker", display_name=None, icon_url=icon_url)
class _Adapter(CollaborationAdapter):
@@ -70,19 +73,23 @@ class _Adapter(CollaborationAdapter):
class TestBridgeCoreResolver:
async def test_returns_the_agents_own_icon(self) -> None:
bridge = _bridge({"worker": _agent(_CUSTOM)})
- assert await bridge._agent_icon_url("worker") == _CUSTOM
+ found = await bridge._agent_presentation("worker")
+ assert found is not None
+ assert found.icon_url == _CUSTOM
async def test_returns_none_when_the_agent_has_no_icon(self) -> None:
"""None, not a default — choosing the default is the adapter's job, so
each platform keeps the one it has always produced."""
bridge = _bridge({"worker": _agent(None)})
- assert await bridge._agent_icon_url("worker") is None
+ found = await bridge._agent_presentation("worker")
+ assert found is not None
+ assert found.icon_url is None
async def test_returns_none_for_a_name_that_is_not_an_agent(self) -> None:
"""Bridges also render aliases and third-party bots. An unknown name is
not an error here — the caller only wants to know whether to override."""
bridge = _bridge({})
- assert await bridge._agent_icon_url("some-slack-bot") is None
+ assert await bridge._agent_presentation("some-slack-bot") is None
class TestAdapterIconSelection:
@@ -93,19 +100,19 @@ class TestAdapterIconSelection:
async def test_prefers_the_agents_own_icon(self) -> None:
adapter = _Adapter()
- async def resolver(name: str) -> str | None:
- return _CUSTOM
+ async def resolver(name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=None, icon_url=_CUSTOM)
- adapter.set_agent_icon_resolver(resolver)
+ adapter.set_agent_presentation_resolver(resolver)
assert await adapter.agent_icon_url("worker") == _CUSTOM
async def test_falls_back_to_the_default_when_the_agent_has_none(self) -> None:
adapter = _Adapter()
- async def resolver(name: str) -> str | None:
- return None
+ async def resolver(name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=None, icon_url=None)
- adapter.set_agent_icon_resolver(resolver)
+ adapter.set_agent_presentation_resolver(resolver)
assert await adapter.agent_icon_url("worker") == default_icon_url("worker")
async def test_an_end_to_end_override_through_the_bridge_resolver(self) -> None:
@@ -113,7 +120,7 @@ class TestAdapterIconSelection:
to work and which neither test above proves on its own."""
bridge = _bridge({"worker": _agent(_CUSTOM), "plain": _agent(None)})
adapter = _Adapter()
- adapter.set_agent_icon_resolver(bridge._agent_icon_url)
+ adapter.set_agent_presentation_resolver(bridge._agent_presentation)
assert await adapter.agent_icon_url("worker") == _CUSTOM
assert await adapter.agent_icon_url("plain") == default_icon_url("plain")
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
index 710ca695c..0d502a6bf 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
@@ -84,7 +84,7 @@ def test_the_handler_is_installed_before_the_adapter_starts() -> None:
def set_channel_migration_handler(self, handler: Any) -> None:
installed.append(handler)
- def set_agent_icon_resolver(self, resolver: Any) -> None:
+ def set_agent_presentation_resolver(self, resolver: Any) -> None:
# Not what this test is about; present so the stub satisfies what
# `start` installs on its adapter.
return None
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py
index 73021b84c..6987db83a 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py
@@ -23,7 +23,7 @@ class _FakeAdapter:
def set_channel_migration_handler(self, handler: Any) -> None:
pass
- def set_agent_icon_resolver(self, resolver: Any) -> None:
+ def set_agent_presentation_resolver(self, resolver: Any) -> None:
pass
async def start(self, **kwargs: Any) -> None:
@@ -48,7 +48,7 @@ def _core(provision: Any) -> tuple[BridgeCore, _FakeAdapter]:
core._load_existing_puppets = _noop # type: ignore[assignment]
core._ensure_channel_captures = _noop # type: ignore[assignment]
core._handle_channel_migrated = None # type: ignore[attr-defined]
- core._agent_icon_url = None # type: ignore[attr-defined]
+ core._agent_presentation = None # type: ignore[attr-defined]
core._handle_inbound_message = None # type: ignore[attr-defined]
core._handle_inbound_command = None # type: ignore[attr-defined]
core._handle_agent_joined_channel = None # type: ignore[attr-defined]
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py b/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
index 92ef51239..b909e0fb1 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
@@ -2,6 +2,7 @@ import asyncio
from urllib.parse import parse_qs, urlsplit
from switch_core.agent_icon import default_icon_url
+from switch_core.bridges.collaboration.adapter import AgentPresentation
from switch_core.bridges.collaboration.slack.adapter import (
SlackAdapter,
SlackConnectionConfig,
@@ -73,10 +74,10 @@ def test_the_slack_adapter_applies_it_to_a_resolved_icon() -> None:
)
)
- async def resolver(name: str) -> str | None:
- return DICEBEAR
+ async def resolver(name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=None, icon_url=DICEBEAR)
- adapter.set_agent_icon_resolver(resolver)
+ adapter.set_agent_presentation_resolver(resolver)
resolved = asyncio.run(adapter.agent_icon_url("worker"))
assert _background(resolved) == [SLACK_SURFACE]
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 f2471ffe4..48f3118f3 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
@@ -4,6 +4,7 @@ import asyncio
from typing import Any
from switch_core.agent_icon import default_icon_url
+from switch_core.bridges.collaboration.adapter import AgentPresentation, AgentRendering
from switch_core.bridges.collaboration.models import InboundCommand, InboundMessage
from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
@@ -820,8 +821,14 @@ def test_typing_false_is_noop() -> None:
# ── Adaptive card ────────────────────────────────────────────────────────────
+def _rendering(label: str, icon_url: str) -> AgentRendering:
+ return AgentRendering(field_label=label, body_label=label, icon_url=icon_url)
+
+
def test_agent_card_carries_name_and_body() -> None:
- card = agent_message_card("worker", "the message body", "https://example.com/i.png")
+ card = agent_message_card(
+ _rendering("worker", "https://example.com/i.png"), "the message body", []
+ )
# Name appears in the header column; body appears as its own TextBlock.
header = card["body"][0]["columns"][1]["items"][0]
assert header["text"] == "worker"
@@ -829,7 +836,9 @@ def test_agent_card_carries_name_and_body() -> None:
def test_agent_card_renders_the_supplied_icon() -> None:
- card = agent_message_card("worker", "body", "https://example.com/custom.png")
+ card = agent_message_card(
+ _rendering("worker", "https://example.com/custom.png"), "body", []
+ )
image = card["body"][0]["columns"][0]["items"][0]
assert image["url"] == "https://example.com/custom.png"
@@ -849,10 +858,11 @@ async def test_message_activity_carries_notification_summary_and_fallback() -> N
async def test_message_activity_uses_the_agents_own_icon_when_it_has_one() -> None:
adapter = _adapter()
- async def _resolver(agent_name: str) -> str | None:
- return "https://example.com/worker.png" if agent_name == "worker" else None
+ async def _resolver(agent_name: str) -> AgentPresentation | None:
+ icon = "https://example.com/worker.png" if agent_name == "worker" else None
+ return AgentPresentation(display_name=None, icon_url=icon)
- adapter.set_agent_icon_resolver(_resolver)
+ adapter.set_agent_presentation_resolver(_resolver)
activity = await adapter._message_activity("worker", "hello")
image = activity["attachments"][0]["content"]["body"][0]["columns"][0]["items"][0]
@@ -862,10 +872,10 @@ async def test_message_activity_uses_the_agents_own_icon_when_it_has_one() -> No
async def test_message_activity_falls_back_to_the_default_icon() -> None:
adapter = _adapter()
- async def _resolver(agent_name: str) -> str | None:
- return None
+ async def _resolver(agent_name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=None, icon_url=None)
- adapter.set_agent_icon_resolver(_resolver)
+ adapter.set_agent_presentation_resolver(_resolver)
activity = await adapter._message_activity("worker", "hello")
image = activity["attachments"][0]["content"]["body"][0]["columns"][0]["items"][0]
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py b/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py
index a3963582e..1e7b8966c 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
from typing import Any
+from switch_core.bridges.collaboration.adapter import AgentRendering
from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
TeamsConnectionConfig,
@@ -143,7 +144,11 @@ def test_the_card_carries_mentions_where_teams_looks_for_them() -> None:
def test_a_card_with_no_mentions_carries_no_msteams_block() -> None:
- assert "msteams" not in agent_message_card("james", "hello", "http://icon")
+ agent = AgentRendering(
+ field_label="james", body_label="james", icon_url="http://icon"
+ )
+
+ assert "msteams" not in agent_message_card(agent, "hello", [])
# ── the app's own handle ─────────────────────────────────────────────────────
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 a5c37d12d..34a7cf139 100644
--- a/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py
@@ -918,11 +918,13 @@ def test_two_agents_get_different_marks_and_keep_them() -> None:
# Telegram gives a bot no per-message avatar, so a stable mark is the only
# thing a reader can learn to recognise. It must not move between restarts,
# which rules out the salted built-in hash.
- first = TelegramAdapter._attribute("scout", "hello")
- second = TelegramAdapter._attribute("ranger", "hello")
+ first = TelegramAdapter._attribute("scout", "scout", "hello")
+ second = TelegramAdapter._attribute("ranger", "ranger", "hello")
assert first.split()[0] != second.split()[0]
- assert TelegramAdapter._attribute("scout", "again").startswith(first.split()[0])
+ assert TelegramAdapter._attribute("scout", "scout", "again").startswith(
+ first.split()[0]
+ )
def test_editing_a_message_targets_its_chat_and_id() -> None:
diff --git a/core/tests/switch_core/clients/test_admin_client.py b/core/tests/switch_core/clients/test_admin_client.py
index 1129456e2..2f0017bfe 100644
--- a/core/tests/switch_core/clients/test_admin_client.py
+++ b/core/tests/switch_core/clients/test_admin_client.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
from contextlib import asynccontextmanager
from types import SimpleNamespace
@@ -8,6 +9,9 @@ from switch_core.clients.admin_client import AdminClient
from switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageType
from switch_core.events import CommandEvent
+# Matches a live `@<handle>` mention token (same char class Switch re-parses).
+_MENTION = re.compile(r"@[A-Za-z0-9._-]+")
+
def _no_connections() -> SimpleNamespace:
"""A connection registry with nothing live.
@@ -177,7 +181,11 @@ class TestAdminUnreachableRoleWarning:
class TestAdminAbsentAgentWarning:
async def test_warns_when_agent_absent(self) -> None:
- agents = {"web-searcher": SimpleNamespace(id="a-web", name="web-searcher")}
+ agents = {
+ "web-searcher": SimpleNamespace(
+ id="a-web", name="web-searcher", display_name=None
+ )
+ }
client, sent = _admin_client(agents_by_name=agents)
event = _event("@web-searcher can you look this up?")
await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
@@ -187,7 +195,11 @@ class TestAdminAbsentAgentWarning:
assert _marker_type(sent[0]) == AdminMessageType.ABSENT_AGENT.value
async def test_warning_tags_the_asker(self) -> None:
- agents = {"web-searcher": SimpleNamespace(id="a-web", name="web-searcher")}
+ agents = {
+ "web-searcher": SimpleNamespace(
+ id="a-web", name="web-searcher", display_name=None
+ )
+ }
client, sent = _admin_client(agents_by_name=agents)
event = _event("@web-searcher ping", sender_name="carol")
await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
@@ -195,7 +207,11 @@ class TestAdminAbsentAgentWarning:
assert sent[0]["mentions"] == ["@carol:switch.local"]
async def test_warning_threads_under_trigger(self) -> None:
- agents = {"web-searcher": SimpleNamespace(id="a-web", name="web-searcher")}
+ agents = {
+ "web-searcher": SimpleNamespace(
+ id="a-web", name="web-searcher", display_name=None
+ )
+ }
client, sent = _admin_client(agents_by_name=agents)
event = _event("@web-searcher ping")
await AdminClient._warn_absent_agents(
@@ -204,7 +220,11 @@ class TestAdminAbsentAgentWarning:
assert sent[0]["thread_root_id"] == "thread-42"
async def test_no_warning_when_agent_is_member(self) -> None:
- agents = {"web-searcher": SimpleNamespace(id="a-web", name="web-searcher")}
+ agents = {
+ "web-searcher": SimpleNamespace(
+ id="a-web", name="web-searcher", display_name=None
+ )
+ }
client, sent = _admin_client(members={"a-web"}, agents_by_name=agents)
event = _event("@web-searcher status?")
await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
@@ -218,7 +238,11 @@ class TestAdminAbsentAgentWarning:
assert sent == []
async def test_prefix_name_not_falsely_warned(self) -> None:
- agents = {"cc-bug-fixing": SimpleNamespace(id="a-ccbf", name="cc-bug-fixing")}
+ agents = {
+ "cc-bug-fixing": SimpleNamespace(
+ id="a-ccbf", name="cc-bug-fixing", display_name=None
+ )
+ }
client, sent = _admin_client(agents_by_name=agents)
event = _event("@cc-bug-fixing-2 please run")
await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
@@ -234,8 +258,12 @@ class TestAdminAbsentAgentWarning:
async def test_combines_multiple_absent_agents(self) -> None:
agents = {
- "web-searcher": SimpleNamespace(id="a-web", name="web-searcher"),
- "doc-expert": SimpleNamespace(id="a-doc", name="doc-expert"),
+ "web-searcher": SimpleNamespace(
+ id="a-web", name="web-searcher", display_name=None
+ ),
+ "doc-expert": SimpleNamespace(
+ id="a-doc", name="doc-expert", display_name=None
+ ),
}
client, sent = _admin_client(agents_by_name=agents)
event = _event("@web-searcher @doc-expert can you pair up?")
@@ -245,6 +273,56 @@ class TestAdminAbsentAgentWarning:
assert "doc-expert" in sent[0]["body"]
assert "aren't in this room" in sent[0]["body"]
+ async def test_warning_names_the_agent_and_keeps_its_identifier(self) -> None:
+ # The reader just mistyped a mention, so the identifier they have to
+ # retype has to stay on the line beside the label.
+ agents = {
+ "switchdev": SimpleNamespace(
+ id="a-sd", name="switchdev", display_name="Switch Dev"
+ )
+ }
+ client, sent = _admin_client(agents_by_name=agents)
+ event = _event("@switchdev can you look this up?")
+ await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
+ assert "**Switch Dev (`switchdev`)**" in sent[0]["body"]
+
+ async def test_warning_without_a_display_name_names_it_once(self) -> None:
+ agents = {
+ "switchdev": SimpleNamespace(id="a-sd", name="switchdev", display_name=None)
+ }
+ client, sent = _admin_client(agents_by_name=agents)
+ event = _event("@switchdev ping")
+ await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
+ assert "**switchdev**" in sent[0]["body"]
+ assert "(`switchdev`)" not in sent[0]["body"]
+
+ async def test_warning_display_name_cannot_ping_the_channel(self) -> None:
+ agents = {
+ "switchdev": SimpleNamespace(
+ id="a-sd", name="switchdev", display_name="@everyone"
+ )
+ }
+ client, sent = _admin_client(agents_by_name=agents)
+ event = _event("@switchdev ping", sender_name="carol")
+ await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
+ body = sent[0]["body"]
+ # The one live mention left is the asker the notice is addressed to.
+ assert _MENTION.findall(body) == ["@carol"]
+ assert "switchdev" in body
+
+ async def test_warning_display_name_cannot_forge_a_link(self) -> None:
+ agents = {
+ "switchdev": SimpleNamespace(
+ id="a-sd",
+ name="switchdev",
+ display_name="[here](https://example.invalid)",
+ )
+ }
+ client, sent = _admin_client(agents_by_name=agents)
+ event = _event("@switchdev ping")
+ await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)
+ assert "](https://example.invalid)" not in sent[0]["body"]
+
def _cmd_event(command: str, args: str = "") -> CommandEvent:
return CommandEvent(
diff --git a/deploy/local/docker-compose.yml b/deploy/local/docker-compose.yml
index c0d8da90c..97255f60b 100644
--- a/deploy/local/docker-compose.yml
+++ b/deploy/local/docker-compose.yml
@@ -60,6 +60,7 @@ services:
MM_SERVICESETTINGS_ENABLEBOTACCOUNTCREATION: "true"
MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS: "true"
MM_TEAMSETTINGS_ENABLEOPENSERVER: "true"
+ MM_TEAMSETTINGS_TEAMMATENAMEDISPLAY: "full_name"
# Both of these exist for Switch Console's embedded room view (CHOO-1674):
# the onboarding checklist opens a modal over a dimmed page inside the
# pane, and Mattermost only turns known schemes into links, so without
diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.yml
index 6d6dea8b4..43f1ca0a3 100644
--- a/deploy/local/standalone-docker-compose.yml
+++ b/deploy/local/standalone-docker-compose.yml
@@ -132,6 +132,7 @@ services:
MM_SERVICESETTINGS_ENABLEBOTACCOUNTCREATION: "true"
MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS: "true"
MM_TEAMSETTINGS_ENABLEOPENSERVER: "true"
+ MM_TEAMSETTINGS_TEAMMATENAMEDISPLAY: "full_name"
# Neither plugin is usable in a bundled Switch deployment: Copilot has no
# configured provider and throws a 404 looking up its bot on every page
# load, and Calls ships a WebRTC service nothing here can reach.
diff --git a/deploy/remote/helm/switch/templates/mattermost/deployment.yaml b/deploy/remote/helm/switch/templates/mattermost/deployment.yaml
index 6aab98e8e..078058403 100644
--- a/deploy/remote/helm/switch/templates/mattermost/deployment.yaml
+++ b/deploy/remote/helm/switch/templates/mattermost/deployment.yaml
@@ -53,6 +53,8 @@ spec:
value: "true"
- name: MM_TEAMSETTINGS_ENABLEOPENSERVER
value: "true"
+ - name: MM_TEAMSETTINGS_TEAMMATENAMEDISPLAY
+ value: "full_name"
# For Switch Console's embedded room view (CHOO-1674): suppress the
# onboarding modal, and linkify the `switchdash://` deeplinks
# agents post. Kept in step with the standalone compose.
diff --git a/docs/old/ARCHITECTURE.md b/docs/old/ARCHITECTURE.md
index a92454067..3ef6ae348 100644
--- a/docs/old/ARCHITECTURE.md
+++ b/docs/old/ARCHITECTURE.md
@@ -118,8 +118,11 @@ The relational schema is defined in
- **User** — a human principal; `role == "admin"` is a global authorization
bypass. **ExternalUser** maps a platform identity (Slack/etc.) to a puppet.
-- **Agent** — a registered AI agent, owned by a User. An agent inherits exactly
- its owner's permissions. **AgentSession** / **AgentRuntimeState** track a live
+- **Agent** — a registered AI agent, owned by a User. Its `name` is a lowercase
+ identifier and the routing key everything addresses it by (mentions, Matrix
+ handle, per-platform handles), while the optional `display_name` is
+ presentation only and falls back to `name`. An agent inherits exactly its
+ owner's permissions. **AgentSession** / **AgentRuntimeState** track a live
session and its surfaced state (working / needs-input).
- **ApiKey** — a hashed credential, of type `"agent"` or `"registration"`.
- **Client** / **ClientRoom** — the Matrix client backing each participant and
diff --git a/docs/old/bridges/DISCORD_SETUP.md b/docs/old/bridges/DISCORD_SETUP.md
index 0f0542e7d..a3011a5ac 100644
--- a/docs/old/bridges/DISCORD_SETUP.md
+++ b/docs/old/bridges/DISCORD_SETUP.md
@@ -2,9 +2,11 @@
Connects a Discord server (**guild**) to Switch. A **single bot application**
backs every Switch agent; per-agent presentation is done with **per-channel
-webhooks** (Discord webhooks accept a per-message username and avatar). Inbound
-events arrive over an outbound **Gateway WebSocket** scoped to the configured
-guild, so **no public ingress is required**; outbound goes through the REST API.
+webhooks** (Discord webhooks accept a per-message username and avatar), the
+username carrying the agent's display name or its identifier when it has none.
+Inbound events arrive over an outbound **Gateway WebSocket** scoped to the
+configured guild, so **no public ingress is required**; outbound goes through
+the REST API.
Rooms are provisioned **lazily**: Discord has no "app invited to channel" signal
(the bot sees every channel its permissions allow), so a channel's Switch room is
@@ -87,10 +89,11 @@ the first bridged message.
An agent is not a Discord member — one bot serves all of them, differentiated
per message by a webhook override — so by default nothing Discord knows about
carries an agent's name and typing `@` never offers one. With this on, each
-agent gets a **mentionable role named exactly after it**, so `@flint-tracker`
-completes in the composer and arrives as a real pill. The role is empty and
-carries no permissions: mentioning it notifies nobody, and Switch resolves the
-mention back to the agent's name on the way in.
+agent gets a **mentionable role named exactly after its identifier** — the
+lowercase name, not the agent's display name — so `@flint-tracker` completes in
+the composer and arrives as a real pill. The role is empty and carries no
+permissions: mentioning it notifies nobody, and Switch resolves the mention back
+to the agent's name on the way in.
Roles are provisioned for every existing agent when the bridge starts, and for
each new agent as it registers. Two limits are worth knowing before you turn it
@@ -100,12 +103,13 @@ on:
one warning naming it, and the bridge stops trying — agents stay addressable
by typing their name.
- **A role carries no metadata**, so there is nowhere to record that a role
- belongs to Switch. An agent's role is therefore the one whose name matches it
- **exactly**. Two consequences: a role you created by hand for an agent is
- adopted rather than duplicated (which is how to use this on a server where
- the bot may not manage roles), and when an agent is deleted its role is only
- deleted if **nobody holds it** — one with members is left in place, and the
- bridge says so.
+ belongs to Switch. An agent's role is therefore the one whose name matches the
+ agent's **identifier** exactly — never its display name, so a role made under
+ a display name belongs to no agent and autocompletes nothing. Two
+ consequences: a role you created by hand for an agent is adopted rather than
+ duplicated (which is how to use this on a server where the bot may not manage
+ roles), and when an agent is deleted its role is only deleted if **nobody
+ holds it** — one with members is left in place, and the bridge says so.
Renaming an agent leaves its old role behind; delete it by hand.
diff --git a/docs/old/bridges/MATTERMOST_SETUP.md b/docs/old/bridges/MATTERMOST_SETUP.md
index 86148a0d2..f375bb97e 100644
--- a/docs/old/bridges/MATTERMOST_SETUP.md
+++ b/docs/old/bridges/MATTERMOST_SETUP.md
@@ -21,6 +21,15 @@ required**.
2. Have (or create) the **admin** user the bridge will authenticate as, and the
**team** (its URL name / slug) that channels will be created under.
3. Make sure the admin can create channels and manage members on that team.
+4. Set **Teammate Name Display** to *Show first and last name* (System Console →
+ Site Configuration → Users and Teams → Teammate Name Display, or
+ `TeamSettings.TeammateNameDisplay` = `full_name`; `nickname_full_name` works
+ too). Mattermost's default is `username`, under which every account is
+ rendered by its username and an agent's display name is stored but never
+ shown. The setting is **server-wide** — it changes how human members' names
+ render as well, so it is a decision for the server, not for Switch. Switch's
+ own Mattermost deployments (the local and standalone compose stacks and the
+ Helm chart) set it; a server you bring yourself does not.
## 2. Onboard the bridge in Switch
@@ -65,7 +74,15 @@ don't onboard Mattermost by hand — it's already there after setup. Log in at
## Notes
- **Identity.** Each agent gets its own Mattermost bot account, so agent messages
- appear as distinct users (not a single relayed bot).
+ appear as distinct users (not a single relayed bot). The bot's **username** is
+ the agent's identifier — the handle a mention resolves, and the key the bridge
+ finds an existing bot back by — and the bot account's own display-name field
+ carries the agent's display name, falling back to the identifier. A bot whose
+ display name has drifted from the agent's is corrected when the bridge adopts
+ it. Whether Mattermost shows any of it is the **Teammate Name Display** server
+ setting from [step 1](#1-prepare-the-mattermost-server); the bridge logs one
+ warning when it writes an agent display name on a server whose setting would
+ hide it.
- **DMs.** Switch-initiated DM rooms are user-initiated on Mattermost — a user
starts the DM with the agent's bot and Switch picks it up.
- **Deeplinks.** Set `GATEWAY_PUBLIC_URL` on switch-core for clickable "Open in
@@ -90,9 +107,10 @@ Three signals, in order of how long they last. Nothing here needs configuring.
progress signal.
**What Mattermost cannot do.** There is no equivalent of Slack's native AI
-progress card — the live panel that streams what an agent is doing under its own
-name. The one thing in Mattermost that looks like it, the "thinking" UI in
-Mattermost's own [Agents plugin](https://github.com/mattermost/mattermost-plugin-agents),
+progress card — the live panel that streams what an agent is doing under the
+agent's own name and icon. The one thing in Mattermost that looks like it, the
+"thinking" UI in Mattermost's own
+[Agents plugin](https://github.com/mattermost/mattermost-plugin-agents),
is not a platform feature: progress travels over a plugin-private websocket
event and is drawn by a webapp bundle that plugin registers. Neither half is
reachable from a bot token or the REST API, and ephemeral posts cannot be edited
diff --git a/docs/old/bridges/README.md b/docs/old/bridges/README.md
index 6d4dde73b..fffa6b0bf 100644
--- a/docs/old/bridges/README.md
+++ b/docs/old/bridges/README.md
@@ -4,8 +4,9 @@ A **collaboration bridge** is a two-way relay between an external chat platform
(Slack, Mattermost, Microsoft Teams, Discord, Telegram) and Switch's internal Matrix
rooms. Humans talk in their normal chat client; Switch agents see those messages
as room events and reply back into the same channel. Each external channel maps
-to a Switch room, and each Switch agent is presented in the channel under its own
-name and avatar.
+to a Switch room, and each Switch agent is presented in the channel under the
+agent's own display name and avatar, as far as the platform's identity model
+allows.
This directory documents how to set up each bridge. Read this page first for the
shared onboarding model, then the per-platform guide:
@@ -16,7 +17,7 @@ shared onboarding model, then the per-platform guide:
| Mattermost | [`MATTERMOST_SETUP.md`](MATTERMOST_SETUP.md) | one bot account per agent | WebSocket (outbound) | not required |
| Microsoft Teams | [`TEAMS_SETUP.md`](TEAMS_SETUP.md) | single Azure bot app | HTTP push (Bot Framework + Graph) | **required** |
| Discord | [`DISCORD_SETUP.md`](DISCORD_SETUP.md) | single bot app | Gateway WebSocket (outbound) | not required |
-| Telegram | [`TELEGRAM_SETUP.md`](TELEGRAM_SETUP.md) | single bot, name in the message body | long polling (outbound) | not required |
+| Telegram | [`TELEGRAM_SETUP.md`](TELEGRAM_SETUP.md) | single bot, agent named in the message body | long polling (outbound) | not required |
## The onboarding model (same for every bridge)
@@ -43,6 +44,18 @@ show nothing, and their app is installed through the platform's own admin UI as
their guide describes. The links are built by the running bridge, so they appear
only while it is up, and only for an admin.
+### The two names an agent has
+
+An agent has a **name** — a lowercase identifier such as `flint-tracker` — and,
+optionally, a free-form **display name** such as "Flint Tracker". The identifier
+is the routing key and the only thing that addresses anything: mentions,
+in-room command arguments, and the per-agent handles a bridge mints (Slack user
+groups, Discord roles, Mattermost bot usernames) are all built from it. The
+agent's display name is presentation only — the name a bridged message is
+attributed to, wherever the platform gives Switch somewhere to put it. An agent
+with no display name is presented under its identifier, so the two coincide
+until one is set. Each guide says where its platform renders the display name.
+
### Registered bridge types
`slack`, `mattermost`, `teams`, `discord`, `telegram`. The dashboard's registration
diff --git a/docs/old/bridges/SLACK_SETUP.md b/docs/old/bridges/SLACK_SETUP.md
index f8d99c682..da8182690 100644
--- a/docs/old/bridges/SLACK_SETUP.md
+++ b/docs/old/bridges/SLACK_SETUP.md
@@ -175,7 +175,9 @@ from-scratch path and as a reference for what the app needs.
Under **OAuth & Permissions → Scopes → Bot Token Scopes**:
- `chat:write`, `chat:write.customize` — post agent messages, with the
- per-message username + avatar override each agent is presented under.
+ per-message username + avatar override each agent is presented under. The
+ username carries the agent's display name, or its identifier when it has
+ none.
- `commands` — the `/…` slash commands.
- `channels:read`, `channels:manage` — look up, create, set topic on, and invite
into public channels; `groups:read`, `groups:write` — the same for private
@@ -212,9 +214,10 @@ rather than a scope you tick.
### Agent name autocomplete (`agent_usergroups`)
-**On by default.** Every agent gets a Slack **user group** whose handle is its
-name. Set `agent_usergroups: false` in the bridge's connection config to turn
-it off.
+**On by default.** Every agent gets a Slack **user group** whose handle is the
+agent's identifier — the lowercase name a mention has to use, never the agent's
+display name. Set `agent_usergroups: false` in the bridge's connection config to
+turn it off.
This is a workaround and worth naming as one: Slack offers no way to make an
app's agents mentionable, so Switch borrows the one mentionable object an app
@@ -234,9 +237,12 @@ their description and ignores the workspace's own.
**Groups made by hand are adopted.** Where a workspace will not let the bot
create them, making them manually is the only way to use the feature — so a
-group whose **handle or name is exactly an agent's name** is taken to be that
-agent's, and the marker is stamped on it. The match is exact, so a workspace
-group is never captured by an agent that happens to be named similarly.
+group whose **handle or name is exactly an agent's identifier** is taken to be
+that agent's, and the marker is stamped on it. The match is exact, so a
+workspace group is never captured by an agent that happens to be named
+similarly. It is also against the identifier and nothing else: a group made
+under an agent's **display name** matches no agent, is left alone, and leaves
+that agent without autocomplete.
Two things gate it, both outside Switch:
diff --git a/docs/old/bridges/TEAMS_SETUP.md b/docs/old/bridges/TEAMS_SETUP.md
index f9e65d1c7..acc0ea2be 100644
--- a/docs/old/bridges/TEAMS_SETUP.md
+++ b/docs/old/bridges/TEAMS_SETUP.md
@@ -2,7 +2,8 @@
Connects a Microsoft Teams tenant to Switch. A **single Azure bot app** backs
every Switch agent (like Slack); each agent's messages render as an **Adaptive
-Card** headed with the agent's name and avatar.
+Card** headed with the agent's display name — its identifier where it has
+none — and avatar.
Teams is the most involved bridge to set up. Unlike Slack or Mattermost it has
no persistent socket, so it is **push-based**: Microsoft calls Switch, not the
diff --git a/docs/old/bridges/TELEGRAM_SETUP.md b/docs/old/bridges/TELEGRAM_SETUP.md
index 6a707fb73..b633ef505 100644
--- a/docs/old/bridges/TELEGRAM_SETUP.md
+++ b/docs/old/bridges/TELEGRAM_SETUP.md
@@ -3,9 +3,10 @@
Connects Telegram groups and channels to Switch. A **single bot** backs every
Switch agent. Telegram has **no per-message identity override** — nothing like a
Discord webhook's username/avatar — so an agent is identified by its **name
-rendered at the head of each message**. Inbound events arrive by **long polling**
-(an outbound connection), so **no public ingress is required**; outbound goes
-through the Bot API.
+rendered at the head of each message**: the agent's display name, or its
+identifier where it has none. Addressing runs the other way and is always by
+identifier. Inbound events arrive by **long polling** (an outbound connection),
+so **no public ingress is required**; outbound goes through the Bot API.
Rooms are **adopted, never created**: the Bot API gives a bot no way to create a
chat. A chat's Switch room is provisioned when the bot is **added to the group**
@@ -259,7 +260,8 @@ bare.
Rather than answer that with a usage line — whose only route out is to type the
whole command by hand, which is what the menu was for — the bot asks for what
is missing and Telegram opens the composer already replying to it. Answer with
-the agent's name alone and the command runs:
+the agent's identifier alone — the same name `@agent-name` uses, not the agent's
+display name — and the command runs:
> **/invite_agent** needs one more thing — the registered agent to add to this
> room.