Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Make adding a messaging platform a self-contained change (CHOO-3324) (#720)
Louis Amaudruz5810ae45fc31
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex c14b725e6..e809bb3c5 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -31,3 +31,39 @@ paste here- [ ] creating an agent with it and picking a model- [ ] the agent replying in a room- [ ] a shell command asking for permission first++---++## Adding or changing a messaging platform++<!--+Only for a pull request that adds support for a messaging platform or changes+one. Otherwise delete this section. How to do each step:+docs/contributing/new-messaging-platform.md+-->++**Platform:**++**How it connects:** <!-- dials out (Switch connects to the platform) / webhooks (the platform calls Switch) -->++**Adapter test summary** (paste what+`uv run --project core pytest core/tests/switch_core/bridges/collaboration/test_<your-platform>_*.py` prints at the end):++```+paste here+```++**Video** (link or attachment). It shows:++- [ ] the platform in Switch Console's "Connect a messaging app" list, with its own name and icon+- [ ] filling in its connect form and connecting it+- [ ] webhook platforms only: the address from the "connected" step pasted into the platform+- [ ] an agent's message reaching the platform+- [ ] a message sent on the platform reaching the room, and the agent replying+- [ ] an approval card answered from the platform, and Switch showing it was answered from your platform++**Checks:**++- [ ] Nothing changed outside the platform's adapter folder, its line in `platforms.py` and its docs page (or the PR says why)+- [ ] What the platform can't do is declared on the adapter (channel creation, user search, …)+- [ ] The docs page `docs/messaging-platforms/<key>.md` is writtendiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5ddd47393..1ba2c72ac 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -82,6 +82,13 @@ the steps in order, and what your pull request has to show (a real-CLI testsummary and a short video). The technical details are in[Add an agent provider](console/docs/add-an-agent-provider.md).+## Adding a messaging platform++Start with [Adding support for a new messaging platform](docs/contributing/new-messaging-platform.md):+the steps in order, and what your pull request has to show (your adapter's+test summary and a short video). The technical details are in+[Add a messaging platform](docs/contributing/add-a-messaging-platform.md).+## TestingTests live in `core/tests/switch_core/` and mirror the module structure. Thediff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-embed.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-embed.tsindex 2d8508060..99f539e66 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-embed.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-embed.ts@@ -158,10 +158,7 @@ export async function resolveChannelEmbed(params: {if (externalChannelUrl) {return { kind: 'external', url: externalChannelUrl, platform: bridgeType };}- return {- kind: 'unavailable',- reason: `This room is bridged to ${bridgeType}, which cannot be shown inside Switch Console.`,- };+ return { kind: 'unlinked', platform: bridgeType };}const origin = await mattermostOriginFor(serverId);diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.tsindex fcd850bfe..22034b4c1 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts@@ -23,6 +23,8 @@ function bridge(overrides: Partial<RemoteBridge>): RemoteBridge {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,...overrides,};}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.tsindex c41e82e98..ef5057c07 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts@@ -100,6 +100,8 @@ describe('createBridgeOnServer', () => {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,},});});@@ -356,10 +358,42 @@ describe('fetchBridgeTypes', () => {// capability, which is the same "every platform could" default as the// bridge list uses.await expect(fetchBridgeTypes(SERVER)).resolves.toEqual([- { key: 'stub', fields: [], channelCreationSupported: true, directorySearchSupported: true },+ {+ key: 'stub',+ displayName: null,+ docsSlug: null,+ iconSvg: null,+ receivesWebhooks: false,+ fields: [],+ channelCreationSupported: true,+ directorySearchSupported: true,+ },]);});+ it('carries what the server says about the platform itself', async () => {+ fetchMock.mockResolvedValue(+ response(200, [+ {+ key: 'dummychat',+ display_name: 'Dummy Chat',+ docs_slug: 'dummy-chat',+ icon_svg: '<svg/>',+ receives_webhooks: true,+ config_schema: {},+ },+ ])+ );++ const [dummy] = await fetchBridgeTypes(SERVER);+ expect(dummy).toMatchObject({+ displayName: 'Dummy Chat',+ docsSlug: 'dummy-chat',+ iconSvg: '<svg/>',+ receivesWebhooks: true,+ });+ });+it('reports a platform that cannot create channels at all', async () => {fetchMock.mockResolvedValue(response(200, [{ key: 'telegram', config_schema: {}, channel_creation_supported: false }])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.tsindex 18002b6ff..9f8c4745c 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@@ -473,6 +473,8 @@ describe('room creation', () => {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,},{id: 'b2',@@ -490,6 +492,8 @@ describe('room creation', () => {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,},]);});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.tsindex 7c27d713e..4c90b02a2 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@@ -7,6 +7,7 @@ import {managedServerStoppedPhase,noteManagedServerUnanswered,} from '@main/core/managed-switch-server/managed-server-status';+import { rememberBridgePlatforms } from '@main/core/telemetry/bridge-platform';import { assertedTenant } from '@main/core/workspaces/asserted-tenant';import { type CloudMachine, cloudMachineSchema } from '@shared/core/cloud-agents/cloud-agents';import type { RemoteFeatureFlag } from '@shared/core/feature-flags/feature-flags';@@ -1196,6 +1197,9 @@ type BridgeJson = {attention?: string | null;team_placement_supported?: boolean;channel_ids_refused?: string | null;+ // Absent on a server predating per-connection webhooks, where none had one.+ receives_webhooks?: boolean;+ webhook_url?: string | null;};function mapBridge(b: BridgeJson): RemoteBridge {@@ -1214,6 +1218,8 @@ function mapBridge(b: BridgeJson): RemoteBridge {attention: b.attention ?? null,teamPlacementSupported: b.team_placement_supported ?? false,channelIdsRefused: b.channel_ids_refused ?? null,+ receivesWebhooks: b.receives_webhooks ?? false,+ webhookUrl: b.webhook_url ?? null,};}@@ -1412,12 +1418,23 @@ export async function fetchBridgeTypes(server: SwitchServer): Promise<RemoteBridconst res = await gatewayFetch(server, '/collaborations/types', { authenticated: true });const json = (await res.json()) as Array<{key: string;+ display_name?: string;+ docs_slug?: string | null;+ icon_svg?: string | null;+ receives_webhooks?: boolean;config_schema: BridgeConfigSchema;channel_creation_supported?: boolean;directory_search_supported?: boolean;}>;+ rememberBridgePlatforms(json.map((t) => t.key));return json.map((t) => ({key: t.key,+ // The four below are absent on a server predating platform metadata; the+ // renderer falls back to the names and icons it bundles for that case.+ displayName: t.display_name ?? null,+ docsSlug: t.docs_slug ?? null,+ iconSvg: t.icon_svg ?? null,+ receivesWebhooks: t.receives_webhooks ?? false,fields: toConfigFields(t.config_schema ?? {}),// Absent on a server predating the capability — every platform could be// registered to create channels before it existed, so default true.diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.tsindex be9b5ebe6..522e93970 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts@@ -92,6 +92,8 @@ describe('updateBridgeOnServer', () => {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,},});});diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/bridge-platform.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/bridge-platform.test.tsnew file mode 100644index 000000000..195428d88--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/bridge-platform.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';+import { bridgePlatformOfType, rememberBridgePlatforms } from './bridge-platform';++describe('bridgePlatformOfType', () => {+ it('reports the bundled platforms by name', () => {+ expect(bridgePlatformOfType('slack')).toBe('slack');+ expect(bridgePlatformOfType('teams')).toBe('teams');+ });++ it('reports a platform no server has listed as other', () => {+ expect(bridgePlatformOfType('zulip')).toBe('other');+ });++ it('reports a platform by name once a server lists it as registered', () => {+ rememberBridgePlatforms(['google_chat']);+ expect(bridgePlatformOfType('google_chat')).toBe('google_chat');+ });++ it('never learns a value that is not shaped like a platform key', () => {+ rememberBridgePlatforms(['[email protected]', 'Has Spaces', 'x']);+ expect(bridgePlatformOfType('[email protected]')).toBe('other');+ expect(bridgePlatformOfType('x')).toBe('other');+ });++ it('reports a missing type as unknown, not other', () => {+ expect(bridgePlatformOfType(null)).toBe('unknown');+ expect(bridgePlatformOfType('')).toBe('unknown');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/bridge-platform.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/bridge-platform.tsindex ad3198e09..a3f945455 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/bridge-platform.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/bridge-platform.ts@@ -1,25 +1,44 @@import type { TelemetryBridgePlatform } from './events';/**- * The messaging platforms this app knows the names of.- *- * The server decides what bridge types exist and names them as free text, so- * there is no union to import — the list is fetched at runtime and could contain- * anything. This is the same treatment provider ids get: an unrecognised value- * is reported as unrecognised rather than passed through, because a platform key- * we have never heard of is still a string arriving from outside this app.+ * The shape switch-core holds every platform key to+ * (`messaging_platforms.PLATFORM_KEY_PATTERN`): lowercase, short, no+ * punctuation. A value of this shape cannot carry an identifier or free text.*/-const KNOWN_PLATFORMS = new Set(['slack', 'mattermost', 'discord', 'teams', 'telegram']);+const PLATFORM_KEY = /^[a-z][a-z0-9_]{1,31}$/;++/**+ * The platforms this build shipped knowing, reportable before any server has+ * been asked which platforms it has.+ */+const BUNDLED_PLATFORMS = ['slack', 'mattermost', 'discord', 'teams', 'telegram'];++/**+ * Every platform key a server listed as a registered bridge type. Those are its+ * adapters, which are code rather than anything a user typed — so once a server+ * has named a platform this way, it is reportable by name.+ */+const knownPlatforms = new Set<string>(BUNDLED_PLATFORMS);++/** Note the platforms a server registered, from its bridge types list. */+export function rememberBridgePlatforms(keys: readonly string[]): void {+ for (const key of keys) {+ if (PLATFORM_KEY.test(key)) knownPlatforms.add(key);+ }+}/*** Narrow a bridge type to something reportable.*- * `other` means the server named a platform we do not have a value for — worth- * knowing, and distinct from `unknown`, which means we could not find out at- * all. Collapsing the two would make a new platform look like a lookup failure.+ * A bridge's type is free text as far as this app can verify, so it is reported+ * by name only when a server listed it as a registered platform; anything else+ * is `other`. `other` means the server named a platform we cannot vouch for —+ * worth knowing, and distinct from `unknown`, which means we could not find out+ * at all. Collapsing the two would make a new platform look like a lookup+ * failure.*/export function bridgePlatformOfType(type: string | null | undefined): TelemetryBridgePlatform {if (type === null || type === undefined || type === '') return 'unknown';const normalised = type.trim().toLowerCase();- return KNOWN_PLATFORMS.has(normalised) ? (normalised as TelemetryBridgePlatform) : 'other';+ return knownPlatforms.has(normalised) ? (normalised as TelemetryBridgePlatform) : 'other';}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.tsindex d102ea7e5..a6951f987 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts@@ -159,21 +159,21 @@ export type TelemetryCliFailure =declare const durationMsBrand: unique symbol;export type TelemetryDurationMs = number & { readonly [durationMsBrand]: true };+declare const platformKeyBrand: unique symbol;+/*** Which messaging platform a room or bridge is on.** The server names the platform as free text, so this is narrowed at the emitter- * rather than trusted — the same treatment provider ids get. `other` is a- * platform we do not know about, `unknown` is one we could not read.+ * rather than trusted (see `bridgePlatformOfType`): a platform key a server+ * listed as one of its registered platforms, `other` for a platform we cannot+ * vouch for, `unknown` for one we could not read. Branded so only the narrowing+ * produces one.*/export type TelemetryBridgePlatform =- | 'slack'- | 'mattermost'- | 'discord'- | 'teams'- | 'telegram'| 'other'- | 'unknown';+ | 'unknown'+ | (string & { readonly [platformKeyBrand]: true });/*** What asked for an update check.diff --git a/console/apps/switch-console-desktop/src/renderer/App.tsx b/console/apps/switch-console-desktop/src/renderer/App.tsxindex d673c676c..7f5052e0c 100644--- a/console/apps/switch-console-desktop/src/renderer/App.tsx+++ b/console/apps/switch-console-desktop/src/renderer/App.tsx@@ -3,6 +3,7 @@ import { AgentCrudEvents } from './app/agent-crud-events';import { AppMenuEvents } from './app/app-menu-events';import { Workspace } from './app/workspace';import { SessionDeeplinkListener } from './features/switch-rooms/session-deeplink-listener';+import { BridgePlatformsLoader } from './features/switch-servers/bridge-platforms-loader';import { TelemetryConsentGate } from './features/telemetry/TelemetryConsentGate';import { WorkspaceLayoutContextProvider } from './lib/layout/layout-provider';import { WorkspaceViewProvider } from './lib/layout/provider';@@ -20,6 +21,7 @@ function AppContent() {<AppMenuEvents /><AgentCrudEvents /><SessionDeeplinkListener />+ <BridgePlatformsLoader /><RightSidebarProvider><ThemeProvider><ModalRenderer />diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsxindex 09542aa83..fa8e1ae16 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx@@ -12,6 +12,7 @@ import { useState } from 'react';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { sidebarStore } from '@renderer/lib/stores/app-state';import {@@ -83,7 +84,7 @@ const ViewGroupingToggle = observer(function ViewGroupingToggle() {/** Human label for a messaging-app filter value. */function bridgeLabel(value: string): string {if (value === UNBRIDGED_FILTER_VALUE) return 'No messaging app';- return value.charAt(0).toUpperCase() + value.slice(1);+ return bridgePlatformLabel(value);}/**diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex afb66e379..eec5daefd 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -1,4 +1,4 @@-import { ChevronRight, DoorOpen, MoreVertical, Plus, Trash2 } from 'lucide-react';+import { ChevronRight, DoorOpen, ExternalLink, MoreVertical, Plus, Trash2 } from 'lucide-react';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { openRoomChannel } from '@renderer/features/switch-rooms/room-links';import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';@@ -179,7 +179,9 @@ export function RoomRow({/** Bridge platform type (`slack`, `mattermost`, …) when the room is bridged. */bridgeType?: string | null;}) {- const channelLinkable = onOpenChannel !== null && hasBridgeIcon(bridgeType);+ // Offered wherever the room has a channel to open, whether or not its+ // platform has a logo: the link is what makes the action work, not the icon.+ const channelLinkable = onOpenChannel !== null && !!bridgeType;const hasRoomActions = onAddAgent !== null || channelLinkable || onDelete !== null;return (<SidebarMenuRow@@ -244,7 +246,11 @@ export function RoomRow({)}{channelLinkable && (<DropdownMenuItem onClick={() => onOpenChannel?.()}>- <BridgeIcon bridgeType={bridgeType} size={16} className="size-4" />+ {hasBridgeIcon(bridgeType) ? (+ <BridgeIcon bridgeType={bridgeType} size={16} className="size-4" />+ ) : (+ <ExternalLink className="size-4" />+ )}Open in {bridgePlatformLabel(bridgeType)}</DropdownMenuItem>)}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsxindex bb989ae7c..4bbf48cf0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx@@ -2,6 +2,7 @@ import { ExternalLink, Loader2, MessagesSquare, RefreshCw } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useEffect, useRef, useState } from 'react';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';import { useTheme } from '@renderer/lib/hooks/useTheme';import { rpc } from '@renderer/lib/ipc';@@ -207,10 +208,17 @@ export const RoomEmbedLayer = observer(function RoomEmbedLayer() {<RoomNotice icon={<MessagesSquare className="size-6" />} title={active.embed.reason} />) : null}+ {visible && active?.phase === 'ready' && active.embed.kind === 'unlinked' ? (+ <RoomNotice+ icon={<MessagesSquare className="size-6" />}+ title={`This room is bridged to ${bridgePlatformLabel(active.embed.platform)}, which cannot be shown inside Switch Console.`}+ />+ ) : null}+{visible && active?.phase === 'ready' && active.embed.kind === 'external' ? (<RoomNoticeicon={<MessagesSquare className="size-6" />}- title={`This room lives in ${capitalise(active.embed.platform)}`}+ title={`This room lives in ${bridgePlatformLabel(active.embed.platform)}`}detail="Conversations on external platforms open in their own app, or in your browser when it is not installed."action={<Button@@ -219,7 +227,7 @@ export const RoomEmbedLayer = observer(function RoomEmbedLayer() {onClick={() => activeRoomId && openRoomChannel(activeRoomId)}><ExternalLink className="size-3" />- Open in {capitalise(active.embed.platform)}+ Open in {bridgePlatformLabel(active.embed.platform)}</Button>}/>@@ -249,7 +257,3 @@ export const RoomEmbedLayer = observer(function RoomEmbedLayer() {</div>);});--function capitalise(value: string): string {- return value.charAt(0).toUpperCase() + value.slice(1);-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsxindex 9c9b66f83..079c39caf 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx@@ -30,9 +30,11 @@ import {} from '@renderer/lib/ui/select';import { cn } from '@renderer/utils/utils';import type { CreateBridgeResult } from '@shared/core/switch-servers/switch-servers';+import { bridgeTypesQueryKey, fetchBridgeTypes } from './bridge-platforms-loader';import { ConnectChatPanel } from './ConnectChatPanel';import { InstallMessagingAppPanel } from './InstallMessagingAppPanel';import { switchServersStore } from './switch-servers-store';+import { WebhookAddressStep } from './webhook-address-step';import { administersWorkspaceInScope } from './workspace-admin';type ConnectMessagingAppModalArgs = {@@ -82,11 +84,19 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod// this staying true for one that can't rather than us guessing wrong.const [channelCreationEnabled, setChannelCreationEnabled] = useState(true);const [isSubmitting, setIsSubmitting] = useState(false);+ // Set once a webhook platform is connected: the dialog stays open on its+ // address instead of closing, since the platform needs it before anything+ // arrives.+ const [awaitingWebhookSetup, setAwaitingWebhookSetup] = useState<{+ app: ConnectedApp;+ platform: string;+ webhookUrl: string | null;+ } | null>(null);const [error, setError] = useState<string | null>(null);const typesQuery = useQuery({- queryKey: ['remote-bridge-types', workspaceId],- queryFn: () => rpc.workspaces.listBridgeTypes(workspaceId as string),+ queryKey: bridgeTypesQueryKey(workspaceId),+ queryFn: () => fetchBridgeTypes(workspaceId as string),enabled: workspaceId !== null,});@@ -186,11 +196,20 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModsetError(messageFor(result));return;}- onSuccess({+ const app = {bridgeId: result.bridge.id,displayName: result.bridge.displayName,directorySearchSupported: selectedType.directorySearchSupported,- });+ };+ if (result.bridge.receivesWebhooks) {+ setAwaitingWebhookSetup({+ app,+ platform: selectedType.key,+ webhookUrl: result.bridge.webhookUrl,+ });+ return;+ }+ onSuccess(app);} catch (cause) {setError(failureText(cause, 'Could not connect the messaging app.'));} finally {@@ -233,240 +252,269 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod: `Connect a messaging app${server ? ` to ${server.name}` : ''}`}</DialogTitle></DialogHeader>- <DialogContentArea className="pt-0">- <div className="flex w-full flex-col gap-5">- {!server && (- <p className="text-xs text-destructive">- No Switch server is selected. Choose a server in the sidebar first.- </p>- )}+ {awaitingWebhookSetup !== null ? (+ <>+ <DialogContentArea className="pt-0">+ <WebhookAddressStep+ platform={awaitingWebhookSetup.platform}+ webhookUrl={awaitingWebhookSetup.webhookUrl}+ />+ </DialogContentArea>+ <DialogFooter>+ <ConfirmButton onClick={() => onSuccess(awaitingWebhookSetup.app)}>Done</ConfirmButton>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogContentArea className="pt-0">+ <div className="flex w-full flex-col gap-5">+ {!server && (+ <p className="text-xs text-destructive">+ No Switch server is selected. Choose a server in the sidebar first.+ </p>+ )}- {server && !isAdmin && (- <p className="text-xs text-destructive">- Connecting a messaging app requires an owner or admin of this workspace. You are a- member without admin rights, so the server would reject this.- </p>- )}+ {server && !isAdmin && (+ <p className="text-xs text-destructive">+ Connecting a messaging app requires an owner or admin of this workspace. You are a+ member without admin rights, so the server would reject this.+ </p>+ )}- {installableQuery.isError && (- <p className="text-xs text-destructive">- {failureText(- installableQuery.error,- 'Could not check which messaging apps this server can add for you, so only connecting your own app is offered.'+ {installableQuery.isError && (+ <p className="text-xs text-destructive">+ {failureText(+ installableQuery.error,+ 'Could not check which messaging apps this server can add for you, so only connecting your own app is offered.'+ )}+ </p>)}- </p>- )}- {isAdmin && installableQuery.isLoading && (- <p className="text-xs text-foreground-muted">Loading…</p>- )}+ {isAdmin && installableQuery.isLoading && (+ <p className="text-xs text-foreground-muted">Loading…</p>+ )}- {offerInstall && workspaceId !== null && (- <>- {claimingPlatform === null &&- installable.map((platform) => (- <InstallMessagingAppPanel- key={platform}- workspaceId={workspaceId}- platform={platform}- onInstalled={(bridge) => handleInstalled(platform, bridge)}- />- ))}- {claimable- .filter((c) => claimingPlatform === null || c.platform === claimingPlatform)- .map((c) => (- <ConnectChatPanel- key={c.platform}- workspaceId={workspaceId}- claimable={c}- onShown={() => setClaimingPlatform(c.platform)}- onConnected={(bridge) => handleInstalled(c.platform, bridge)}- />- ))}- {claimingPlatform === null && (- <button- type="button"- className="w-fit text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground"- onClick={() => setUseOwnApp(true)}- >- Use your own app instead- </button>+ {offerInstall && workspaceId !== null && (+ <>+ {claimingPlatform === null &&+ installable.map((platform) => (+ <InstallMessagingAppPanel+ key={platform}+ workspaceId={workspaceId}+ platform={platform}+ onInstalled={(bridge) => handleInstalled(platform, bridge)}+ />+ ))}+ {claimable+ .filter((c) => claimingPlatform === null || c.platform === claimingPlatform)+ .map((c) => (+ <ConnectChatPanel+ key={c.platform}+ workspaceId={workspaceId}+ claimable={c}+ onShown={() => setClaimingPlatform(c.platform)}+ onConnected={(bridge) => handleInstalled(c.platform, bridge)}+ />+ ))}+ {claimingPlatform === null && (+ <button+ type="button"+ className="w-fit text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground"+ onClick={() => setUseOwnApp(true)}+ >+ Use your own app instead+ </button>+ )}+ </>)}- </>- )}- {showForm && (- <Field>- <FieldLabel>Messaging app</FieldLabel>- <Select- value={typeKey ?? ''}- onValueChange={(next) => handleTypeChange(next ?? null)}- disabled={typesQuery.isLoading || types.length === 0 || !isAdmin}- >- <SelectTrigger>- <SelectValue- placeholder={typesQuery.isLoading ? 'Loading…' : 'Choose a platform'}+ {showForm && (+ <Field>+ <FieldLabel>Messaging app</FieldLabel>+ <Select+ value={typeKey ?? ''}+ onValueChange={(next) => handleTypeChange(next ?? null)}+ disabled={typesQuery.isLoading || types.length === 0 || !isAdmin}>- {selectedType ? bridgePlatformLabel(selectedType.key) : undefined}- </SelectValue>- </SelectTrigger>- <SelectContent>- {types.map((type) => (- <SelectItem key={type.key} value={type.key}>- <span className="flex items-center gap-2">- {hasBridgeIcon(type.key) && <BridgeIcon bridgeType={type.key} size={16} />}- {bridgePlatformLabel(type.key)}- </span>- </SelectItem>- ))}- </SelectContent>- </Select>- {typesQuery.isError && (- <p className="mt-1 text-xs text-destructive">- {failureText(typesQuery.error, 'Could not load the available messaging apps.')}- </p>+ <SelectTrigger>+ <SelectValue+ placeholder={typesQuery.isLoading ? 'Loading…' : 'Choose a platform'}+ >+ {selectedType ? bridgePlatformLabel(selectedType.key) : undefined}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {types.map((type) => (+ <SelectItem key={type.key} value={type.key}>+ <span className="flex items-center gap-2">+ {hasBridgeIcon(type.key) && (+ <BridgeIcon bridgeType={type.key} size={16} />+ )}+ {bridgePlatformLabel(type.key)}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {typesQuery.isError && (+ <p className="mt-1 text-xs text-destructive">+ {failureText(+ typesQuery.error,+ 'Could not load the available messaging apps.'+ )}+ </p>+ )}+ </Field>)}- </Field>- )}- {showForm && selectedType && (- <>- <Field>- <FieldLabel>Name</FieldLabel>- <Input- autoFocus- placeholder={`e.g. ${bridgePlatformLabel(selectedType.key)}`}- value={displayName}- onChange={(e) => {- setDisplayName(e.target.value);- setError(null);- }}- />- <p className="mt-1 text-xs text-foreground-muted">- How this connection is labelled in Switch Console when you pick it for a room.- </p>- </Field>+ {showForm && selectedType && (+ <>+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ autoFocus+ placeholder={`e.g. ${bridgePlatformLabel(selectedType.key)}`}+ value={displayName}+ onChange={(e) => {+ setDisplayName(e.target.value);+ setError(null);+ }}+ />+ <p className="mt-1 text-xs text-foreground-muted">+ How this connection is labelled in Switch Console when you pick it for a room.+ </p>+ </Field>- {/* The fields below are asked for without explanation — what a+ {/* The fields below are asked for without explanation — what a"bot token" is, and where to get one, lives in the platform'ssetup guide. Link to it at the point the question arises. */}- <button- type="button"- className="-mt-2 flex w-fit items-center gap-1 text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground"- onClick={() =>- void openExternalUrl(- bridgeSetupDocsUrl(selectedType.key),- 'Could not open the setup guide'- )- }- >- How to set up {bridgePlatformLabel(selectedType.key)}- <ExternalLink className="size-3" />- </button>+ <button+ type="button"+ className="-mt-2 flex w-fit items-center gap-1 text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground"+ onClick={() =>+ void openExternalUrl(+ bridgeSetupDocsUrl(selectedType.key),+ 'Could not open the setup guide'+ )+ }+ >+ How to set up {bridgePlatformLabel(selectedType.key)}+ <ExternalLink className="size-3" />+ </button>++ {selectedType.fields.map((field) =>+ field.kind === 'boolean' ? (+ <label+ key={field.key}+ className="group/field flex cursor-pointer items-start gap-2.5"+ >+ <Checkbox+ checked={config[field.key] === true}+ onCheckedChange={(checked) => {+ setConfig((prev) => ({ ...prev, [field.key]: checked === true }));+ setError(null);+ }}+ className="mt-0.5"+ />+ <span className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">{field.label}</span>+ {field.description && (+ <span className="text-xs text-foreground-muted">+ {field.description}+ </span>+ )}+ </span>+ </label>+ ) : (+ <Field key={field.key}>+ <FieldLabel>+ {field.label}+ {!field.required && (+ <span className="ml-1 font-normal text-foreground-muted">+ (optional)+ </span>+ )}+ </FieldLabel>+ <Input+ // Masked for credentials, so a token is not left readable on+ // screen while the user checks the rest of the form.+ type={field.secret ? 'password' : 'text'}+ autoComplete={field.secret ? 'new-password' : 'off'}+ spellCheck={false}+ value={+ typeof config[field.key] === 'string'+ ? (config[field.key] as string)+ : ''+ }+ onChange={(e) => {+ const { value } = e.target;+ setConfig((prev) => ({ ...prev, [field.key]: value }));+ setError(null);+ }}+ />+ {field.description && (+ <p className="mt-1 text-xs text-foreground-muted">{field.description}</p>+ )}+ </Field>+ )+ )}- {selectedType.fields.map((field) =>- field.kind === 'boolean' ? (<label- key={field.key}- className="group/field flex cursor-pointer items-start gap-2.5"+ className={cn(+ 'group/field flex items-start gap-2.5',+ channelCreationSupported ? 'cursor-pointer' : 'cursor-not-allowed'+ )}><Checkbox- checked={config[field.key] === true}- onCheckedChange={(checked) => {- setConfig((prev) => ({ ...prev, [field.key]: checked === true }));- setError(null);- }}+ checked={channelCreationSupported && channelCreationEnabled}+ disabled={!channelCreationSupported}+ onCheckedChange={(checked) => setChannelCreationEnabled(checked === true)}className="mt-0.5"/><span className="flex flex-col gap-0.5">- <span className="text-sm font-medium">{field.label}</span>- {field.description && (- <span className="text-xs text-foreground-muted">{field.description}</span>- )}+ <span className="text-sm font-medium">+ Allow creating channels from Switch+ </span>+ <span className="text-xs text-foreground-muted">+ {channelCreationSupported+ ? `Allows Switch users and agents to create channels in ${bridgePlatformLabel(selectedType.key)} from Switch. Turn it off to only ever use channels made in the app.`+ : `${bridgePlatformLabel(selectedType.key)} has no way to create channels from Switch, so this connection can only be used with channels made in the app.`}+ </span></span></label>- ) : (- <Field key={field.key}>- <FieldLabel>- {field.label}- {!field.required && (- <span className="ml-1 font-normal text-foreground-muted">(optional)</span>- )}- </FieldLabel>- <Input- // Masked for credentials, so a token is not left readable on- // screen while the user checks the rest of the form.- type={field.secret ? 'password' : 'text'}- autoComplete={field.secret ? 'new-password' : 'off'}- spellCheck={false}- value={- typeof config[field.key] === 'string' ? (config[field.key] as string) : ''- }- onChange={(e) => {- const { value } = e.target;- setConfig((prev) => ({ ...prev, [field.key]: value }));- setError(null);- }}++ <label className="group/field flex cursor-pointer items-start gap-2.5">+ <Checkbox+ checked={setAsDefault}+ onCheckedChange={(checked) => setSetAsDefault(checked === true)}+ className="mt-0.5"/>- {field.description && (- <p className="mt-1 text-xs text-foreground-muted">{field.description}</p>- )}- </Field>- )+ <span className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">Use for new rooms by default</span>+ <span className="text-xs text-foreground-muted">+ Rooms created without naming a messaging app will land here. Replaces the+ server’s current default; existing rooms are unaffected.+ </span>+ </span>+ </label>+ </>)}- <label- className={cn(- 'group/field flex items-start gap-2.5',- channelCreationSupported ? 'cursor-pointer' : 'cursor-not-allowed'- )}- >- <Checkbox- checked={channelCreationSupported && channelCreationEnabled}- disabled={!channelCreationSupported}- onCheckedChange={(checked) => setChannelCreationEnabled(checked === true)}- className="mt-0.5"- />- <span className="flex flex-col gap-0.5">- <span className="text-sm font-medium">Allow creating channels from Switch</span>- <span className="text-xs text-foreground-muted">- {channelCreationSupported- ? `Allows Switch users and agents to create channels in ${bridgePlatformLabel(selectedType.key)} from Switch. Turn it off to only ever use channels made in the app.`- : `${bridgePlatformLabel(selectedType.key)} has no way to create channels from Switch, so this connection can only be used with channels made in the app.`}- </span>- </span>- </label>-- <label className="group/field flex cursor-pointer items-start gap-2.5">- <Checkbox- checked={setAsDefault}- onCheckedChange={(checked) => setSetAsDefault(checked === true)}- className="mt-0.5"- />- <span className="flex flex-col gap-0.5">- <span className="text-sm font-medium">Use for new rooms by default</span>- <span className="text-xs text-foreground-muted">- Rooms created without naming a messaging app will land here. Replaces the- server’s current default; existing rooms are unaffected.- </span>- </span>- </label>- </>- )}-- {error && <p className="text-xs text-destructive">{error}</p>}- </div>- </DialogContentArea>- <DialogFooter>- <Button variant="outline" onClick={onClose} disabled={isSubmitting}>- {claimingPlatform !== null ? 'Close' : 'Cancel'}- </Button>- {showForm && (- <ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>- {isSubmitting ? 'Connecting…' : 'Connect'}- </ConfirmButton>- )}- </DialogFooter>+ {error && <p className="text-xs text-destructive">{error}</p>}+ </div>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={isSubmitting}>+ {claimingPlatform !== null ? 'Close' : 'Cancel'}+ </Button>+ {showForm && (+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>+ {isSubmitting ? 'Connecting…' : 'Connect'}+ </ConfirmButton>+ )}+ </DialogFooter>+ </>+ )}</>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsxindex d601a405d..023b5319c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx@@ -246,10 +246,9 @@ export const CreateRoomModal = observer(function CreateRoomModal({)}{noneCanCreateChannels && (<p className="text-xs text-destructive">- None of the running messaging apps can create a channel from Switch — for example, a- Telegram bot can't create chats on its own. Make the chat directly in the- messaging app instead (for Telegram, create the group and add the bot to it) and it- becomes a room here once it exists.+ None of the running messaging apps can create a channel from Switch. Make the chat+ directly in the messaging app instead and add the app's bot to it — it becomes+ a room here once it exists.</p>)}{bridgesQuery.isError && (diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsxindex d495b5701..15f9df92a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -1,6 +1,7 @@import { useQueryClient, useQuery } from '@tanstack/react-query';import {CircleAlert,+ Copy,ExternalLink,Info,KeyRound,@@ -20,7 +21,7 @@ import { workspacesStore } from '@renderer/features/workspaces/workspaces-store'import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';-import { useToast } from '@renderer/lib/hooks/use-toast';+import { toast as showToast, useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { openExternalUrl } from '@renderer/lib/open-external';@@ -637,6 +638,26 @@ export function MessagingAppRow({<p className="px-2 py-1 text-xs text-foreground-muted">{channelsLockedReason}</p>)}+ {bridge.receivesWebhooks && (+ <>+ <DropdownMenuSeparator />+ {/* The address the platform delivers this connection's events+ to. Nothing arrives until someone pastes it into the+ platform's settings, so it is offered right here. */}+ {bridge.webhookUrl ? (+ <DropdownMenuItem onClick={() => void copyWebhookAddress(bridge.webhookUrl!)}>+ <Copy className="size-4" />+ Copy webhook address+ </DropdownMenuItem>+ ) : (+ <p className="max-w-xs px-2 py-1 text-xs text-destructive">+ {platform} delivers events to a public address, and this server has none+ configured. Set MESSAGING_PUBLIC_URL on the server.+ </p>+ )}+ </>+ )}+{(showBundledSignIn || bridge.homeUrl) && <DropdownMenuSeparator />}{showBundledSignIn && (<DropdownMenuItem@@ -728,6 +749,19 @@ export function MessagingAppRow({);}+async function copyWebhookAddress(url: string): Promise<void> {+ try {+ await navigator.clipboard.writeText(url);+ showToast({ title: 'Webhook address copied', description: url });+ } catch {+ showToast({+ title: 'Copy failed',+ description: 'The webhook address could not be copied to the clipboard.',+ variant: 'destructive',+ });+ }+}+/** The claimed account as a handle. Platforms differ on whether the username* they report already carries the sigil, so add one only when it is missing. */function handleOf(identity: LinkedIdentity): string {diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-platforms-loader.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-platforms-loader.tsxnew file mode 100644index 000000000..34b5edcab--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-platforms-loader.tsx@@ -0,0 +1,41 @@+import { useQueries } from '@tanstack/react-query';+import { observer } from 'mobx-react-lite';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { learnBridgePlatforms } from '@renderer/lib/components/bridge-platform';+import { rpc } from '@renderer/lib/ipc';+import type { RemoteBridgeType } from '@shared/core/switch-servers/switch-servers';++/** The query key every reader of a workspace's bridge types shares. */+export function bridgeTypesQueryKey(workspaceId: string | null) {+ return ['remote-bridge-types', workspaceId] as const;+}++/**+ * A workspace's bridge types, learning what they say about their platforms on+ * the way through. Every query on {@link bridgeTypesQueryKey} uses this, so+ * whichever of them fetches first teaches the rest of the app.+ */+export async function fetchBridgeTypes(workspaceId: string): Promise<RemoteBridgeType[]> {+ const types = await rpc.workspaces.listBridgeTypes(workspaceId);+ learnBridgePlatforms(types);+ return types;+}++/**+ * Learn every workspace's messaging platforms — names, docs pages, logos — once+ * the app is up, so a platform is labelled and drawn properly wherever it first+ * appears rather than only after someone opens the connect dialog.+ *+ * A server that cannot be reached is skipped: its platforms keep the bundled+ * names, or their raw keys, until it answers.+ */+export const BridgePlatformsLoader = observer(function BridgePlatformsLoader() {+ useQueries({+ queries: workspacesStore.workspaces.map((workspace) => ({+ queryKey: bridgeTypesQueryKey(workspace.id),+ queryFn: () => fetchBridgeTypes(workspace.id),+ staleTime: 10 * 60 * 1000,+ })),+ });+ return null;+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.tsindex 019ee592b..97309d190 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.ts@@ -16,6 +16,8 @@ function bridge(id: string, displayName: string): RemoteBridge {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,};}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.tsindex 08083e14a..d0e34f0f7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts@@ -22,6 +22,8 @@ function bridge(id: string, displayName: string): RemoteBridge {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,};}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/webhook-address-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/webhook-address-step.tsxnew file mode 100644index 000000000..e8ce61a80--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/webhook-address-step.tsx@@ -0,0 +1,63 @@+import { Copy } from 'lucide-react';+import { useState } from 'react';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { Button } from '@renderer/lib/ui/button';+import { Input } from '@renderer/lib/ui/input';++/**+ * Shown straight after connecting a platform that delivers its events to an+ * address of the connection's own. Nothing arrives until someone gives the+ * platform that address, so this is the moment to hand it over — not a menu+ * they would have to know to look in afterwards.+ */+export function WebhookAddressStep({+ platform,+ webhookUrl,+}: {+ platform: string;+ webhookUrl: string | null;+}) {+ const label = bridgePlatformLabel(platform);+ const [copied, setCopied] = useState<'yes' | 'failed' | null>(null);++ if (webhookUrl === null) {+ return (+ <p className="text-xs text-destructive">+ {label} is connected, but it delivers events to a public address and this server has none+ configured, so no message from {label} can reach Switch yet. Set MESSAGING_PUBLIC_URL on the+ server; the address then appears in this connection's menu.+ </p>+ );+ }++ const copy = async () => {+ try {+ await navigator.clipboard.writeText(webhookUrl);+ setCopied('yes');+ } catch {+ setCopied('failed');+ }+ };++ return (+ <div className="flex flex-col gap-2">+ <p className="text-sm">+ {label} is connected. Give {label} this address so its messages reach Switch — the+ platform's setup guide says where it goes.+ </p>+ <div className="flex items-center gap-2">+ <Input readOnly value={webhookUrl} spellCheck={false} className="font-mono text-xs" />+ <Button variant="outline" size="sm" onClick={() => void copy()}>+ <Copy className="size-3" />+ {copied === 'yes' ? 'Copied' : 'Copy'}+ </Button>+ </div>+ {copied === 'failed' && (+ <p className="text-xs text-destructive">Could not copy it; select the address instead.</p>+ )}+ <p className="text-xs text-foreground-muted">+ You can copy it again later from this connection's menu.+ </p>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-icon.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-icon.tsxindex a81d83235..21d0809e7 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-icon.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-icon.tsx@@ -1,10 +1,13 @@+import { observer } from 'mobx-react-lite';import React from 'react';+import { learnedBridgeIconSvg } from '@renderer/lib/components/bridge-platform';import { coerceRawSvgContent } from '@renderer/utils/mcp-icon-data';// Brand logos for collaboration bridges (Slack, Mattermost, …), keyed by the-// gateway's `bridge_type`. Unlike MCP icons these keep their own brand colors,-// so the SVG fills are preserved (only width/height are stripped so the markup-// scales to the requested size).+// gateway's `bridge_type`. A server describes its own platforms' logos; these+// bundled copies cover a server too old to. Unlike MCP icons these keep their+// own brand colors, so the SVG fills are preserved (only width/height are+// stripped so the markup scales to the requested size).const svgs = import.meta.glob('../../../assets/images/bridges/*.svg', {query: '?raw',eager: true,@@ -25,7 +28,7 @@ const svgByKey = new Map(/** Whether a brand icon exists for the given `bridge_type`. */export function hasBridgeIcon(bridgeType: string | null | undefined): bridgeType is string {- return !!bridgeType && svgByKey.has(bridgeType);+ return !!bridgeType && (learnedBridgeIconSvg(bridgeType) !== null || svgByKey.has(bridgeType));}/** Strip authored width/height so the inline SVG fills the sized wrapper. */@@ -35,10 +38,10 @@ function sizeInlineSvg(svg: string): string {/*** The brand logo for a collaboration bridge, identified by its `bridge_type`- * (e.g. `slack`, `mattermost`). Renders nothing when no icon is bundled for the+ * (e.g. `slack`, `mattermost`). Renders nothing when no icon is known for the* type — callers gate on {@link hasBridgeIcon} and fall back to a generic icon.*/-export function BridgeIcon({+export const BridgeIcon = observer(function BridgeIcon({bridgeType,size = 16,className,@@ -47,6 +50,21 @@ export function BridgeIcon({size?: number;className?: string;}) {+ const served = learnedBridgeIconSvg(bridgeType);+ if (served !== null) {+ // Markup from a server, so drawn as an image: an SVG loaded through <img>+ // runs no script and reaches nothing, which inlining it would not promise.+ return (+ <img+ className={className}+ src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(served)}`}+ width={size}+ height={size}+ alt=""+ style={{ width: size, height: size, display: 'inline-block' }}+ />+ );+ }const svg = svgByKey.get(bridgeType);if (!svg) return null;return (@@ -57,4 +75,4 @@ export function BridgeIcon({dangerouslySetInnerHTML={{ __html: sizeInlineSvg(svg) }}/>);-}+});diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.tsindex 26dd52315..35dac47fd 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.ts@@ -4,9 +4,15 @@ import { fileURLToPath } from 'node:url';import { describe, expect, it } from 'vitest';import { SWITCH_DOCS_MESSAGING_APPS_URL } from '@shared/urls';import { hasBridgeIcon } from './bridge-icon';-import { bridgePlatformLabel, bridgeSetupDocsUrl } from './bridge-platform';+import {+ bridgePlatformLabel,+ bridgeSetupDocsUrl,+ learnBridgePlatforms,+ learnedBridgeIconSvg,+} from './bridge-platform';-/** Every bridge type switch-core registers today (`main.py` register_adapter). */+/** The bridge types this build bundles names and icons for, for servers too+ * old to describe their own platforms. */const BRIDGE_TYPES = ['slack', 'mattermost', 'discord', 'teams', 'telegram'];const BRIDGE_ICON_DIR = join(@@ -92,3 +98,36 @@ describe('bridge brand icons', () => {}});});++describe('platforms a server describes', () => {+ const dummy = {+ key: 'dummychat',+ displayName: 'Dummy Chat',+ docsSlug: 'dummy-chat',+ iconSvg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>',+ receivesWebhooks: true,+ fields: [],+ channelCreationSupported: false,+ directorySearchSupported: false,+ };++ it('names, links and draws a platform this build has never heard of', () => {+ learnBridgePlatforms([dummy]);+ expect(bridgePlatformLabel('dummychat')).toBe('Dummy Chat');+ expect(bridgeSetupDocsUrl('dummychat')).toBe(`${SWITCH_DOCS_MESSAGING_APPS_URL}/dummy-chat`);+ expect(learnedBridgeIconSvg('dummychat')).toBe(dummy.iconSvg);+ expect(hasBridgeIcon('dummychat')).toBe(true);+ });++ it('prefers what the server says over what this build bundles', () => {+ learnBridgePlatforms([{ ...dummy, key: 'teams', displayName: 'Teams (renamed)' }]);+ expect(bridgePlatformLabel('teams')).toBe('Teams (renamed)');+ learnBridgePlatforms([{ ...dummy, key: 'teams', displayName: 'Microsoft Teams' }]);+ });++ it('keeps what it learned when an older server describes nothing', () => {+ learnBridgePlatforms([dummy]);+ learnBridgePlatforms([{ ...dummy, displayName: null, docsSlug: null, iconSvg: null }]);+ expect(bridgePlatformLabel('dummychat')).toBe('Dummy Chat');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.tsindex d08a0accb..82bd09157 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.ts@@ -1,14 +1,50 @@+import { observable, runInAction } from 'mobx';+import type { RemoteBridgeType } from '@shared/core/switch-servers/switch-servers';import { SWITCH_DOCS_MESSAGING_APPS_URL } from '@shared/urls';/**- * Display names and setup guides for collaboration bridge platforms, keyed by- * the gateway's `bridge_type`.+ * Display names, setup guides and logos for collaboration bridge platforms,+ * keyed by the gateway's `bridge_type`.+ *+ * The server is the source: each platform's adapter declares its own name, docs+ * page and icon, and switch-core lists them with its bridge types. They are+ * learned here as those lists arrive ({@link learnBridgePlatforms}), so a+ * platform added server-side is named and drawn without an app release.** The raw key is a lowercase slug (`teams`, `mattermost`), which reads badly in* user-facing copy — "Open in teams" — so anything shown to a user goes through* {@link bridgePlatformLabel} rather than interpolating the key.*/-const PLATFORM_LABELS: Record<string, string> = {+type LearnedPlatform = {+ displayName: string | null;+ docsSlug: string | null;+ iconSvg: string | null;+};++const learned = observable.map<string, LearnedPlatform>();++/** Record what a server says about its platforms. */+export function learnBridgePlatforms(types: readonly RemoteBridgeType[]): void {+ runInAction(() => {+ for (const type of types) {+ // A server predating platform metadata sends none of it; keep whatever a+ // newer server already taught us rather than forgetting it.+ if (type.displayName === null && type.docsSlug === null && type.iconSvg === null) continue;+ learned.set(type.key, {+ displayName: type.displayName,+ docsSlug: type.docsSlug,+ iconSvg: type.iconSvg,+ });+ }+ });+}++/**+ * What this build shipped knowing, for a server too old to describe its own+ * platforms. A new platform never needs an entry here: any server that has it+ * also describes it.+ */+const BUNDLED_LABELS: Record<string, string> = {slack: 'Slack',mattermost: 'Mattermost',discord: 'Discord',@@ -16,37 +52,37 @@ const PLATFORM_LABELS: Record<string, string> = {telegram: 'Telegram',};+/** The docs site's slugs for the bundled platforms (`teams` is published as+ * `microsoft-teams`), for the same older servers. */+const BUNDLED_DOCS_SLUGS: Record<string, string> = {+ slack: 'slack',+ mattermost: 'mattermost',+ discord: 'discord',+ teams: 'microsoft-teams',+ telegram: 'telegram',+};+/*** How to name a bridge platform in the UI. Falls back to the raw key for a type- * a newer switch-core added but this build has no name for — wrong-looking, but- * still identifying, which beats hiding it.+ * no server has described — wrong-looking, but still identifying, which beats+ * hiding it.*/export function bridgePlatformLabel(bridgeType: string | null | undefined): string {if (!bridgeType) return 'messaging app';- return PLATFORM_LABELS[bridgeType] ?? bridgeType;+ return learned.get(bridgeType)?.displayName ?? BUNDLED_LABELS[bridgeType] ?? bridgeType;}/**- * Per-platform setup guide, for the "how do I get these credentials" link on- * the attach form.- *- * The slugs are the documentation site's, not the bridge keys: `teams` is- * published as `microsoft-teams`. Collected here rather than spread through the- * JSX so the mapping is checkable in one place.- */-const PLATFORM_DOCS: Record<string, string> = {- slack: `${SWITCH_DOCS_MESSAGING_APPS_URL}/slack`,- mattermost: `${SWITCH_DOCS_MESSAGING_APPS_URL}/mattermost`,- discord: `${SWITCH_DOCS_MESSAGING_APPS_URL}/discord`,- teams: `${SWITCH_DOCS_MESSAGING_APPS_URL}/microsoft-teams`,- telegram: `${SWITCH_DOCS_MESSAGING_APPS_URL}/telegram`,-};--/**- * The setup guide for a platform, or the index covering all of them when this- * build knows no specific page — so a bridge type added server-side still gets+ * The setup guide for a platform, or the index covering all of them when no+ * specific page is known — so a bridge type without a page of its own still gets* a link that lands somewhere useful instead of a 404.*/export function bridgeSetupDocsUrl(bridgeType: string): string {- return PLATFORM_DOCS[bridgeType] ?? SWITCH_DOCS_MESSAGING_APPS_URL;+ const slug = learned.get(bridgeType)?.docsSlug ?? BUNDLED_DOCS_SLUGS[bridgeType];+ return slug ? `${SWITCH_DOCS_MESSAGING_APPS_URL}/${slug}` : SWITCH_DOCS_MESSAGING_APPS_URL;+}++/** The logo a server provided for a platform, as SVG markup, or null. */+export function learnedBridgeIconSvg(bridgeType: string): string | null {+ return learned.get(bridgeType)?.iconSvg ?? null;}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsxindex 65234683a..ed6710607 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx@@ -72,6 +72,8 @@ function bridge(patch: Partial<RemoteBridge> = {}): RemoteBridge {attention: null,teamPlacementSupported: false,channelIdsRefused: null,+ receivesWebhooks: false,+ webhookUrl: null,...patch,};}@@ -194,6 +196,32 @@ describe('the app name and its badges', () => {});describe('the row menu', () => {+ it('offers the webhook address of a connection that receives events on one', async () => {+ const el = await render(+ row({+ bridge: bridge({+ receivesWebhooks: true,+ webhookUrl: 'https://switch.example/messaging/bridges/b-1/events',+ }),+ })+ );++ expect(await openMenu(el)).toContain('Copy webhook address');+ });++ it('says what is missing when the server has no public address to give', async () => {+ const el = await render(row({ bridge: bridge({ receivesWebhooks: true, webhookUrl: null }) }));++ await openMenu(el);+ expect(document.body.textContent).toContain('MESSAGING_PUBLIC_URL');+ });++ it('offers no webhook address for a connection that dials out', async () => {+ const el = await render(row());++ expect(await openMenu(el)).not.toContain('Copy webhook address');+ });+it('is where unlinking lives, and only when there is a link to undo', async () => {const el = await render(row({ identities: [IDENTITY] }));diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/webhook-address-step.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/webhook-address-step.test.tsxnew file mode 100644index 000000000..aaefe08f2--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/webhook-address-step.test.tsx@@ -0,0 +1,54 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { WebhookAddressStep } from '@renderer/features/switch-servers/webhook-address-step';+import { learnBridgePlatforms } from '@renderer/lib/components/bridge-platform';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(node: React.ReactNode): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => root!.render(node));+ return container;+}++describe('the step after connecting a webhook platform', () => {+ learnBridgePlatforms([+ {+ key: 'dummy_hook',+ displayName: 'Dummy Hook',+ docsSlug: null,+ iconSvg: null,+ receivesWebhooks: true,+ fields: [],+ channelCreationSupported: false,+ directorySearchSupported: false,+ },+ ]);++ it('hands over the address, naming the platform', async () => {+ const url = 'https://switch.example/messaging/bridges/b-1/events';+ const el = await render(<WebhookAddressStep platform="dummy_hook" webhookUrl={url} />);++ expect(el.textContent).toContain('Give Dummy Hook this address');+ expect(el.querySelector('input')?.value).toBe(url);+ expect(el.textContent).not.toContain('dummy_hook');+ });++ it('says what is missing when the server has no public address', async () => {+ const el = await render(<WebhookAddressStep platform="dummy_hook" webhookUrl={null} />);++ expect(el.textContent).toContain('MESSAGING_PUBLIC_URL');+ expect(el.querySelector('input')).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-rooms/room-embed.ts b/console/apps/switch-console-desktop/src/shared/core/switch-rooms/room-embed.tsindex 1277a0c75..0719197a8 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-rooms/room-embed.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-rooms/room-embed.ts@@ -30,7 +30,13 @@ export type RoomEmbed =*/| { kind: 'external'; url: string; platform: string }/** Nothing to show, with a reason worth surfacing rather than a blank pane. */- | { kind: 'unavailable'; reason: string };+ | { kind: 'unavailable'; reason: string }+ /**+ * Bridged to a platform that cannot be embedded, with no link to open it at.+ * Carries the platform key rather than a sentence, so the renderer names it+ * the way the server describes it.+ */+ | { kind: 'unlinked'; platform: string };/*** Mattermost deeplinks are `mattermost://<host>/<team>/channels/<name>`, whichdiff --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.tsindex e7f406aed..e1af174de 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@@ -384,6 +384,12 @@ export type RemoteBridge = {* Null on a server predating the field.*/channelIdsRefused: string | null;+ /** Whether this connection receives its platform's events on an address of+ * its own, which the operator has to give the platform. */+ receivesWebhooks: boolean;+ /** That address, or null where the connection takes none or the server has+ * no public origin configured (`MESSAGING_PUBLIC_URL`) to build it from. */+ webhookUrl: string | null;};/**@@ -485,6 +491,18 @@ export type BridgeConfigField = {export type RemoteBridgeType = {/** Platform key (`slack`, `mattermost`, …). */key: string;+ /** How a person names the platform ("Microsoft Teams"), as its adapter+ * declares it. Null from a server predating the field. */+ displayName: string | null;+ /** The platform's page under the messaging-apps docs, or null where the+ * server has none (or predates the field). */+ docsSlug: string | null;+ /** The platform's logo as SVG markup, or null where the server ships none.+ * It comes from the server, so it is drawn as an image, never inlined. */+ iconSvg: string | null;+ /** Whether connections of this type receive events on an address of their+ * own, which the operator has to give the platform. */+ receivesWebhooks: boolean;fields: BridgeConfigField[];/** Whether this platform can create channels at all — read from the* adapter class, so it is answerable before any connection of this typediff --git a/console/packages/shared/src/session-v1/contract.ts b/console/packages/shared/src/session-v1/contract.tsindex 680c85042..9e0b4aa9b 100644--- a/console/packages/shared/src/session-v1/contract.ts+++ b/console/packages/shared/src/session-v1/contract.ts@@ -1,13 +1,12 @@/** Session interaction wire contract, version 1. */export type Id = string;-export type Surface =- | 'console'- | 'switch-web'- | 'slack'- | 'mattermost'- | 'discord'- | 'teams'- | 'telegram';+/**+ * Where something was done: Switch's own two surfaces, or a messaging platform+ * by its key (`slack`, `teams`, `google_chat`, …). Any platform key is accepted+ * rather than a fixed list, so a newly registered platform needs no contract+ * change. The validator holds a key to the same pattern switch-core does.+ */+export type Surface = 'console' | 'switch-web' | (string & {});export type Provider = string;export type Origin = {surface: Surface;diff --git a/console/packages/shared/src/session-v1/session-v1.test.ts b/console/packages/shared/src/session-v1/session-v1.test.tsindex 7dafc8ed2..ee545059f 100644--- a/console/packages/shared/src/session-v1/session-v1.test.ts+++ b/console/packages/shared/src/session-v1/session-v1.test.ts@@ -448,6 +448,19 @@ it('validates the bridge question and activity recordings with the SDK reader',}});+it('accepts any messaging platform as a surface, and nothing that is not a platform key', () => {+ const answerFrom = (surface: string) => ({+ ...questions.platformFormAnswer,+ origin: { ...questions.platformFormAnswer.origin, surface },+ });+ for (const surface of ['console', 'switch-web', 'slack', 'google_chat']) {+ expect(commandSchema.parse(answerFrom(surface)).origin.surface).toBe(surface);+ }+ for (const surface of ['', 'Slack', 'google-chat', 'x', 'a'.repeat(33), 'slack@evil']) {+ expect(() => commandSchema.parse(answerFrom(surface))).toThrow();+ }+});+it('releases the composer after a durable stale-epoch rejection', async () => {const wire = transport();const client = new SessionChatClient('session-demo', wire.api);diff --git a/console/packages/shared/src/session-v1/validation.ts b/console/packages/shared/src/session-v1/validation.tsindex 9654aea3f..352155731 100644--- a/console/packages/shared/src/session-v1/validation.ts+++ b/console/packages/shared/src/session-v1/validation.ts@@ -6,15 +6,9 @@ const counter = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);const revision = counter;const sequence = counter.min(1);const timestamp = z.iso.datetime({ offset: true });-const surface = z.enum([- 'console',- 'switch-web',- 'slack',- 'mattermost',- 'discord',- 'teams',- 'telegram',-]);+// Switch's own surfaces, or a messaging platform key — the pattern is+// switch-core's `messaging_platforms.PLATFORM_KEY_PATTERN`.+const surface = z.string().regex(/^(console|switch-web|[a-z][a-z0-9_]{1,31})$/);const origin = z.strictObject({surface,actorId: id,diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex e6a993415..bd685a606 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -2,20 +2,24 @@ from __future__ import annotationsimport loggingimport math+import sysfrom abc import ABC, abstractmethodfrom collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclass, fieldfrom datetime import datetime+from pathlib import Pathfrom typing import Any, ClassVar, Literal, Protocol, final, runtime_checkablefrom switch_core.agent_display_name import defuse_label_markupfrom switch_core.agent_icon import generated_icon_url, initials_icon_urlfrom switch_core.bridges.collaboration.ingress import CallbackEndpoint+from switch_core.bridges.collaboration.install import InboundWebhook, WebhookRequestfrom switch_core.bridges.collaboration.models import (BridgeInstallLink,ChannelCreationUnsupported,ChannelType,DirectoryUser,+ FailureReason,InboundAgentJoin,InboundAppJoin,InboundCommand,@@ -34,6 +38,7 @@ from switch_core.bridges.collaboration.session.renderers.neutral import (request_summary,turn_summary,)+from switch_core.messaging_platforms import MessagingPlatformfrom switch_core.outbound import OutboundPolicyfrom switch_core.room_wide_mention import (ROOM_WIDE_TARGET,@@ -343,6 +348,31 @@ class SupportsSharedConnection(Protocol):class PlatformAdapter(ABC):+ #: The platform as a person names it — "Microsoft Teams", not "teams".+ #:+ #: Required: registration refuses an adapter without one. It is what+ #: Console labels the platform with, what a card says an answer came+ #: "from", and what the adapter's own messages call the platform.+ display_name: ClassVar[str]++ #: The page under the messaging-apps docs that explains how to connect+ #: this platform (`docs/.../messaging-apps/<docs_slug>`), or None where+ #: there is none yet. Console links "how do I set this up?" to it.+ docs_slug: ClassVar[str | None] = None++ #: The name of the logo file shipped in the adapter's own folder. Served to+ #: Console as the platform's icon; a platform without one is drawn with a+ #: generic icon. SVG only, because Console draws it at every size.+ icon_file: ClassVar[str] = "icon.svg"++ #: Whether this platform delivers its events by calling Switch over HTTP,+ #: on an address of each connection's own (`/messaging/bridges/<id>/events`).+ #:+ #: Set by an adapter that implements `verify_webhook` and `parse_webhook`.+ #: Most adapters dial out to their platform and are handed events on a+ #: connection they opened; they leave this False.+ receives_webhooks: ClassVar[bool] = False+#: Whether this platform draws agents' session activity: each turn step by#: step, and the approval and question cards a session waits on.draws_session_activity: ClassVar[bool] = False@@ -541,10 +571,57 @@ class PlatformAdapter(ABC):# size against this before downloading so an oversize file is rejected# loudly instead of being pulled down and discarded.self._max_attachment_bytes = 20 * 1024 * 1024+ # Set by `set_webhook_url` for an adapter that receives webhooks.+ self.webhook_url: str | None = Nonedef set_max_attachment_bytes(self, max_bytes: int) -> None:self._max_attachment_bytes = max_bytes+ @classmethod+ def describe(cls, key: str) -> MessagingPlatform:+ """What this adapter declares about its platform, registered as `key`."""+ display_name = getattr(cls, "display_name", None)+ if not isinstance(display_name, str) or not display_name.strip():+ raise ValueError(+ f"{cls.__name__} declares no display_name. Every adapter names "+ "its platform the way a person would "+ '(e.g. display_name = "Microsoft Teams").'+ )+ return MessagingPlatform(+ key=key,+ display_name=display_name,+ docs_slug=cls.docs_slug,+ icon_svg=cls.icon_svg(),+ )++ @classmethod+ def icon_svg(cls) -> str | None:+ """The logo shipped beside this adapter's module, or None if it has none."""+ module = sys.modules.get(cls.__module__)+ module_file = getattr(module, "__file__", None)+ if module_file is None:+ return None+ path = Path(module_file).parent / cls.icon_file+ if not path.is_file():+ return None+ return path.read_text(encoding="utf-8")++ @classmethod+ def classify_failure(cls, exc: BaseException) -> FailureReason | None:+ """Name why this platform's own SDK failed, or None to leave it to Switch.++ The lifecycle asks this first when a bridge fails, so the knowledge of+ what this platform's exceptions mean lives with the adapter that raises+ them. Answer only for exceptions of this platform's SDK; return None+ for anything else, and the shared classifier decides —+ `BridgeCredentialError` is `auth_failed`, a transport failure is+ `network`, `BridgeOperationError` is `platform_error`.++ An adapter that raises only `BridgeCredentialError` and+ `BridgeOperationError` for platform refusals needs no override.+ """+ return None+@classmethodasync def prepare_config(cls, connection_config: dict[str, object]@@ -690,7 +767,47 @@ class PlatformAdapter(ABC):raise WebhookDeliveryUnsupported(f"{type(self).__name__} does not receive events over HTTP, so the ""event posted for this bridge cannot be delivered. A bridge reached "- "this way was installed as a distributed app; this one was not."+ "this way was installed as a distributed app, or its adapter sets "+ "`receives_webhooks`; this one is neither."+ )++ async def verify_webhook(self, request: WebhookRequest) -> None:+ """Prove a request to this bridge's own webhook address is the platform's.++ For an adapter that sets `receives_webhooks`. Check the request against+ this connection's own secret — a signature header over `request.body`,+ a token in the query — and raise `WebhookAuthenticityError` if it does+ not prove itself. Nothing reads the request before this passes: it is a+ stranger's bytes until then, so do not log it either.++ Async because some platforms prove a request with a token whose keys+ have to be fetched (a signed JWT). Called inside the request the+ platform is waiting on, so keep it fast.+ """+ raise WebhookDeliveryUnsupported(+ f"{type(self).__name__} does not receive events on a webhook address "+ "of its own."+ )++ def parse_webhook(self, request: WebhookRequest) -> InboundWebhook:+ """Read a verified request into the event `dispatch_event` will be handed.++ Called only after `verify_webhook` passed. Raise `WebhookPayloadError`+ for a body this adapter cannot read. Set `handshake` instead of an event+ for a request that is the platform checking the address is ours (a+ challenge to echo back): it is answered with that text and nothing is+ dispatched. Set `external_event_id` to the platform's id for the+ delivery wherever it has one — that is what makes a retried delivery+ recognisable, so it is handled once. Set `answers_inline` False: a+ connection's own webhook address acknowledges first and handles after,+ and refuses an event that expects its answer in the response.++ Pure: no I/O. The platform is waiting for this request to be answered,+ and the work belongs in `dispatch_event`, which runs after it has been.+ """+ raise WebhookDeliveryUnsupported(+ f"{type(self).__name__} does not receive events on a webhook address "+ "of its own.")@abstractmethod@@ -1207,9 +1324,10 @@ class PlatformAdapter(ABC):@propertydef platform_name(self) -> str:"""The platform as a person would name it, for messages that reach a- user. The class name is the fallback rather than the source: "Telegram"- belongs in a dialog, "TelegramAdapter" does not."""- return type(self).__name__.removesuffix("Adapter")+ user. The class name stands in only for an adapter that was never+ registered, which declares no `display_name`."""+ declared = getattr(type(self), "display_name", None)+ return declared or type(self).__name__.removesuffix("Adapter")async def search_directory_users(self, query: str) -> list[DirectoryUser]:"""Search the platform's own user directory (CHOO-2137).@@ -1510,6 +1628,20 @@ class PlatformAdapter(ABC):mistake."""return None+ def set_webhook_url(self, url: str | None) -> None:+ """Hand a `receives_webhooks` adapter the public address its platform+ should deliver this connection's events to, before it starts.++ For a platform whose address is registered through its API rather than+ pasted into a settings page (Telegram's `setWebhook`): the adapter+ registers it in `start`. None where the deployment has no+ `MESSAGING_PUBLIC_URL`; an adapter that has to register its address+ should then fail to start with a `BridgeOperationError` saying so,+ since no event could ever reach it. Called only for adapters that set+ `receives_webhooks`; the default stores it on `self.webhook_url`.+ """+ self.webhook_url = url+def set_channel_migration_handler(self, handler: Callable[[str, str], Awaitable[None]]) -> None:diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 00500ba0e..a740f880c 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -50,6 +50,7 @@ from switch_core.bridges.collaboration.models import (BridgeConnectionConfig,ChannelType,DirectoryUser,+ FailureReason,InboundAgentJoin,InboundAppJoin,InboundCommand,@@ -503,6 +504,17 @@ class DiscordAdapter(PlatformAdapter):rather than eagerly for the whole guild."""+ display_name: ClassVar[str] = "Discord"+ docs_slug: ClassVar[str | None] = "discord"++ @classmethod+ def classify_failure(cls, exc: BaseException) -> FailureReason | None:+ if isinstance(exc, discord.LoginFailure):+ return "auth_failed"+ if isinstance(exc, discord.DiscordException):+ return "platform_error"+ return None+# Discord linkifies only http(s), so the `switchdash://` deeplink needs the# https redirect (`GATEWAY_PUBLIC_URL`) to be clickable here.renders_custom_url_schemes: ClassVar[bool] = Falsediff --git a/core/switch_core/bridges/collaboration/discord/icon.svg b/core/switch_core/bridges/collaboration/discord/icon.svgnew file mode 100644index 000000000..ef9e17e5a--- /dev/null+++ b/core/switch_core/bridges/collaboration/discord/icon.svg@@ -0,0 +1,3 @@+<svg width="127" height="127" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <path fill="#5865F2" d="M20.317 4.3698a19.7913 19.7913 0 0 0-4.8851-1.5152.0741.0741 0 0 0-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 0 0-.0785-.037 19.7363 19.7363 0 0 0-4.8852 1.515.0699.0699 0 0 0-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 0 0 .0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 0 0 .0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 0 0-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 0 1-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 0 1 .0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 0 1 .0785.0095c.1202.099.246.198.3728.2924a.077.077 0 0 1-.0066.1276 12.2986 12.2986 0 0 1-1.873.8914.0766.0766 0 0 0-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 0 0 .0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 0 0 .0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 0 0-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189z"/>+</svg>diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.pyindex c61643d31..b2e482f42 100644--- a/core/switch_core/bridges/collaboration/install.py+++ b/core/switch_core/bridges/collaboration/install.py@@ -152,6 +152,21 @@ class WebhookPayloadError(RuntimeError):WebhookEndpoint = Literal["events", "interactive", "commands", "notifications"]+@dataclass(frozen=True)+class WebhookRequest:+ """One request to a bridge's own webhook address, as the adapter sees it.++ Everything a platform might prove itself with or carry its event in: some+ sign the body and put the signature in a header, some verify an address+ with a GET carrying a challenge in the query. Header names are lowercase.+ """++ method: str+ headers: Mapping[str, str]+ query: Mapping[str, str]+ body: bytes++@dataclass(frozen=True)class InboundWebhook:"""One authenticated inbound event, in the shape a running adapter takes.diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 47301ee52..7a1be5969 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -12,6 +12,7 @@ import aiohttpimport httpxfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core import messaging_platformsfrom switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.ingress import CallbackEndpoint, CallbackIngress@@ -21,6 +22,13 @@ from switch_core.bridges.collaboration.models import (BridgeNotRunning,BridgeOperationError,BridgeStartRefused,+ FailureReason,+)+from switch_core.bridges.collaboration.webhooks import (+ BridgeWebhookTarget,+ WebhookBridgeStopped,+ WebhookBridgeUnknown,+ webhook_url,)from switch_core.clients.actor import Actorfrom switch_core.clients.client_factory import ClientFactory@@ -48,7 +56,7 @@ from switch_core.telemetry.deployment import (milestone_claimed,seconds_since_install,)-from switch_core.telemetry.snapshot import PLATFORMS, normalise_platform+from switch_core.telemetry.snapshot import normalise_platformfrom switch_core.tenant_context import current_tenant_id, no_tenantfrom switch_core.trust.client import NullTrustClient, TrustClient@@ -61,97 +69,13 @@ if TYPE_CHECKING:from switch_core.session_activity.listener import AgentSessionActivityListenerfrom switch_core.session_activity.service import AgentSessionActivityService-# Every platform SDK below is registered dynamically (`register_adapter`), so a-# deployment that only wires up some of the five is plausible even though-# every one is a hard dependency of switch-core today — hence guarded rather-# than assumed. A dependency that is genuinely missing degrades classification-# to `unknown` instead of taking the whole classifier down with an ImportError,-# which would turn a bridge failure into a second, worse one.-try:- from slack_sdk.errors import SlackApiError-except ImportError: # pragma: no cover - exercised only without slack-sdk installed- SlackApiError = None # type: ignore[assignment, misc]--try:- from discord.errors import DiscordException- from discord.errors import LoginFailure as DiscordLoginFailure-except ImportError: # pragma: no cover- DiscordException = None # type: ignore[assignment, misc]- DiscordLoginFailure = None # type: ignore[assignment, misc]--try:- from telegram.error import BadRequest as TelegramBadRequest- from telegram.error import ChatMigrated as TelegramChatMigrated- from telegram.error import Forbidden as TelegramForbidden- from telegram.error import InvalidToken as TelegramInvalidToken- from telegram.error import NetworkError as TelegramNetworkError- from telegram.error import TelegramError-except ImportError: # pragma: no cover- TelegramBadRequest = None # type: ignore[assignment, misc]- TelegramChatMigrated = None # type: ignore[assignment, misc]- TelegramForbidden = None # type: ignore[assignment, misc]- TelegramInvalidToken = None # type: ignore[assignment, misc]- TelegramNetworkError = None # type: ignore[assignment, misc]- TelegramError = None # type: ignore[assignment, misc]--try:- from mattermostdriver.exceptions import (- NoAccessTokenProvided as MattermostNoAccessTokenProvided,- )- from mattermostdriver.exceptions import (- NotEnoughPermissions as MattermostNotEnoughPermissions,- )-- # `mattermostdriver` raises its named exceptions only for the status codes- # it maps; anything else (including a bare connection failure) surfaces as- # the underlying `requests` exception, since that is the client it wraps.- from requests.exceptions import ConnectionError as RequestsConnectionError- from requests.exceptions import HTTPError as RequestsHTTPError- from requests.exceptions import InvalidJSONError as RequestsInvalidJSON- from requests.exceptions import Timeout as RequestsTimeout-except ImportError: # pragma: no cover- MattermostNoAccessTokenProvided = None # type: ignore[assignment, misc]- MattermostNotEnoughPermissions = None # type: ignore[assignment, misc]- RequestsConnectionError = None # type: ignore[assignment, misc]- RequestsHTTPError = None # type: ignore[assignment, misc]- RequestsInvalidJSON = None # type: ignore[assignment, misc]- RequestsTimeout = None # type: ignore[assignment, misc]-logger = logging.getLogger(__name__)-# Slack error codes that mean the credentials themselves are rejected, as-# opposed to Slack refusing a call for some other reason (rate limited, a-# scope not granted, an internal error). `SlackApiError` carries no separate-# type for this — the distinction lives entirely in `response["error"]`.-_SLACK_AUTH_ERROR_CODES = frozenset(- {- "invalid_auth",- "not_authed",- "account_inactive",- "token_revoked",- "token_expired",- }-)--# Telegram's own hierarchy already encodes "the server understood the request-# and refused it" for these three. `BadRequest` is a subclass of-# `NetworkError`, so they are checked ahead of `_NETWORK_EXCEPTIONS` below —-# the same ordering `telegram/adapter.py`'s `_as_rich_failure` uses, and for-# the same reason: checking `NetworkError` first would report a definite-# refusal as an unreachable network.-_TELEGRAM_DEFINITE_REFUSALS = tuple(- exc_type- for exc_type in (TelegramBadRequest, TelegramForbidden, TelegramChatMigrated)- if exc_type is not None-)--# Reaching the platform failed outright, across every transport an adapter-# uses: aiohttp (Slack's Socket Mode, Teams' inbound listener), httpx (Teams'-# token exchange and Graph calls) and requests (Mattermost, via-# `mattermostdriver`, which raises its own named exceptions only for the-# status codes it maps and lets a connection failure surface as the-# underlying `requests` exception unchanged).+# Reaching the platform failed outright, in the transports Switch itself+# depends on: aiohttp (Slack's Socket Mode, Teams' inbound listener) and httpx+# (Teams' token exchange and Graph calls). A platform whose SDK has a transport+# of its own names those exceptions in its adapter's `classify_failure`.## Each library's own base class for "the transport failed", not the individual# leaves. A timeout is the case that makes this worth stating: `ConnectTimeout`@@ -159,61 +83,20 @@ _TELEGRAM_DEFINITE_REFUSALS = tuple(# `ServerTimeoutError` is not a `ClientOSError` in aiohttp — so a list of# leaves classifies a refusal as `network` and the timeout beside it as# `unknown`, which are the two outcomes an operator most needs to tell apart.-_NETWORK_EXCEPTIONS = tuple(- exc_type- for exc_type in (- TelegramNetworkError,- aiohttp.ClientConnectionError,- httpx.TransportError,- RequestsConnectionError,- RequestsTimeout,- # The two builtins, for a failure that reaches here without a library's- # name on it: `asyncio.wait_for` raises the first, and a raw socket- # connect the second.- TimeoutError,- ConnectionError,- )- if exc_type is not None+_NETWORK_EXCEPTIONS = (+ aiohttp.ClientConnectionError,+ httpx.TransportError,+ # The two builtins, for a failure that reaches here without a library's+ # name on it: `asyncio.wait_for` raises the first, and a raw socket+ # connect the second.+ TimeoutError,+ ConnectionError,)-_MATTERMOST_AUTH_ERRORS = tuple(- exc_type- for exc_type in (MattermostNoAccessTokenProvided, MattermostNotEnoughPermissions)- if exc_type is not None-)--def _slack_failure_reason(exc: SlackApiError) -> str:- """`auth_failed` for a rejected token, `platform_error` for everything else- Slack refuses a call for (rate limits, a missing scope, an outage). Both- arrive as the same `SlackApiError`, so the code inside the response — not- the exception's type — is what tells them apart.-- A revoked or rotated bot token is the most common bridge failure in the- field, and reporting it as `platform_error` would send an operator to- Slack's status page instead of their own token.- """- # `.response` is not always a mapping. On the async client slack_sdk- # raises `SlackApiError(message, res)` with the raw `aiohttp.ClientResponse`- # whenever the body it was handed is not the JSON the content type claimed- # — an empty 502, a proxy's error page. That object has no `.get`, and this- # is evaluated inside the argument list of the `emit_safely` that reports- # the failure, so an `AttributeError` here would replace the bridge's real- # exception with a meaningless one *and* suppress the event. Nor does a- # `.get` promise a mapping: `AsyncSlackResponse.get` itself raises when- # the body it holds is text, as a proxy's plain-text 5xx is.- response = getattr(exc, "response", None)- reader = getattr(response, "get", None)- try:- code = reader("error") if callable(reader) else None- except Exception:- code = None- if code in _SLACK_AUTH_ERROR_CODES:- return "auth_failed"- return "platform_error"---def _failure_reason(exc: BaseException) -> str:+def _failure_reason(+ exc: BaseException, adapter_cls: type[PlatformAdapter] | None+) -> FailureReason:"""An enumerated reason for a bridge failure.Not the exception's message, which routinely carries a workspace name or a@@ -222,6 +105,10 @@ def _failure_reason(exc: BaseException) -> str:Never by matching words in the class name: "SlackApiError" contains "api",which reads a revoked token as a platform fault.+ The bridge's adapter is asked first, because what a platform SDK's+ exceptions mean is that platform's knowledge. `adapter_cls` is None for a+ bridge whose type is no longer registered; only the shared rules apply.+`KeyError` and `sqlalchemy.exc.DBAPIError` are deliberately leftunclassified and fall through to `unknown`. A `KeyError` here is adaptercode reading a platform payload whose shape changed — a bug in Switch, not@@ -231,43 +118,26 @@ def _failure_reason(exc: BaseException) -> str:if isinstance(exc, BridgeCredentialError):return "auth_failed"- if SlackApiError is not None and isinstance(exc, SlackApiError):- return _slack_failure_reason(exc)-- if DiscordLoginFailure is not None and isinstance(exc, DiscordLoginFailure):- return "auth_failed"-- if isinstance(exc, _MATTERMOST_AUTH_ERRORS):- return "auth_failed"-- if TelegramInvalidToken is not None and isinstance(exc, TelegramInvalidToken):- return "auth_failed"-- if isinstance(exc, _TELEGRAM_DEFINITE_REFUSALS):- return "platform_error"+ if adapter_cls is not None:+ # Guarded because this runs while a bridge failure is being reported:+ # a classifier that raised would replace the bridge's own exception+ # with its own and take the failure event with it.+ try:+ claimed = adapter_cls.classify_failure(exc)+ except Exception:+ logger.exception(+ "%s.classify_failure raised; classifying with the shared rules",+ adapter_cls.__name__,+ )+ claimed = None+ if claimed is not None:+ return claimedif isinstance(exc, _NETWORK_EXCEPTIONS):return "network"- # These four are each a platform's own SDK saying it was reached and it- # refused, never Switch's own database, which speaks neither- # vendor's exception language, so the label stays accurate even though the- # check is broad.if isinstance(exc, BridgeOperationError):return "platform_error"- if DiscordException is not None and isinstance(exc, DiscordException):- return "platform_error"- if RequestsHTTPError is not None and isinstance(exc, RequestsHTTPError):- return "platform_error"- if TelegramError is not None and isinstance(exc, TelegramError):- return "platform_error"-- # Ahead of the `ValueError` below, which it is one of: `requests` folds a- # body it could not parse into `InvalidJSONError`, and a Mattermost server- # answering with a proxy error page is the platform misbehaving, not a- # connection config somebody typed wrong.- if RequestsInvalidJSON is not None and isinstance(exc, RequestsInvalidJSON):- return "platform_error"if isinstance(exc, ValueError):return "config_invalid"@@ -400,6 +270,9 @@ class CollaborationBridgeLifecycleService:# series survives its last bridge being stopped rather than ending —# see the note there on why an absent series is the worst answer.self._platforms_seen: set[str] = set()+ # The adapter class of each running bridge, so a bridge that crashes+ # after it started has its failure read by its own platform's rules.+ self._running_adapter_classes: dict[str, type[PlatformAdapter]] = {}# The one listener every bridge that gets called back shares, and each# running bridge's place on it. Owned here rather than by an adapter# because the port is the process's, not a bridge's: two Mattermost@@ -432,9 +305,69 @@ class CollaborationBridgeLifecycleService:adapter_cls: type[PlatformAdapter],config_cls: type[BridgeConnectionConfig],) -> None:+ """Make a messaging platform available, under `bridge_type` as its key.++ The one line a new platform adds. What the adapter declares about+ itself — its name, docs page, icon — is published to+ `messaging_platforms` here, which is where telemetry, the gateway and+ the session renderers read it from.+ """+ messaging_platforms.register(adapter_cls.describe(bridge_type))self._adapter_registry[bridge_type] = adapter_clsself._config_registry[bridge_type] = config_cls+ async def webhook_target(self, bridge_id: str) -> BridgeWebhookTarget:+ """The running bridge that receives webhooks at `bridge_id`'s address.++ Here rather than in the webhook route because the bridge's tenant is+ not known until it is looked up by id, which is the exempt read this+ service already makes to start a bridge. The row is then re-read scoped+ to that tenant, so a wrong answer is a miss rather than a cross-tenant+ read.+ """+ tenant_id = await tenant_of_collaboration_bridge(+ self._session_factory, bridge_id+ )+ if tenant_id is None:+ raise WebhookBridgeUnknown(f"no bridge {bridge_id}")+ async with tenant_session(self._session_factory, tenant_id) as session:+ bridge = await self._bridge_store.get(session, bridge_id)+ if bridge is None:+ raise WebhookBridgeUnknown(f"no bridge {bridge_id} in its tenant")+ adapter_cls = self._adapter_registry.get(bridge.type)+ if adapter_cls is None or not adapter_cls.receives_webhooks:+ raise WebhookBridgeUnknown(+ f"bridge {bridge_id} is on {bridge.type}, which takes no webhooks"+ )+ adapter = self.get_adapter(bridge_id)+ if adapter is None:+ raise WebhookBridgeStopped(+ f"{bridge.type} bridge {bridge_id} is not running"+ )+ return BridgeWebhookTarget(+ tenant_id=tenant_id,+ bridge_id=bridge_id,+ bridge_type=bridge.type,+ adapter=adapter,+ )++ def receives_webhooks(self, bridge_type: str) -> bool:+ """Whether this platform's connections receive events on an address of+ their own. False for a type nobody registered."""+ adapter_cls = self._adapter_registry.get(bridge_type)+ return adapter_cls is not None and adapter_cls.receives_webhooks++ def webhook_url(self, bridge_id: str, bridge_type: str) -> str | None:+ """The address to give the platform for this connection's events, or+ None where it takes none or the public origin is not configured."""+ if not self.receives_webhooks(bridge_type):+ return None+ return webhook_url(self._config.messaging_public_url, bridge_id)++ def adapter_class(self, bridge_type: str) -> type[PlatformAdapter] | None:+ """The adapter registered for `bridge_type`, or None."""+ return self._adapter_registry.get(bridge_type)+def get_registered_types(self) -> list[str]:return list(self._adapter_registry.keys())@@ -1001,6 +934,7 @@ class CollaborationBridgeLifecycleService:# `none` would be a claim — and the one this catalogue reserves for a# room with no bridge at all.platform = "unknown"+ adapter_cls: type[PlatformAdapter] | None = None# Before the first statement that can fail, so a bridge that never gets# past reading its own row still reports how long that took.self._connect_started[bridge_id] = time.monotonic()@@ -1021,14 +955,7 @@ class CollaborationBridgeLifecycleService:bridge = await self._bridge_store.get(session, bridge_id)if bridge is None:raise ValueError(f"Bridge not found: {bridge_id}")- # A type the catalogue has no name for is still a bridge on some- # platform, so it is `unknown` here, not the `none` the normaliser- # gives it.- platform = (- normalise_platform(bridge.type)- if bridge.type in PLATFORMS- else "unknown"- )+ platform = normalise_platform(bridge.type)adapter_cls = self._adapter_registry.get(bridge.type)config_cls = self._config_registry.get(bridge.type)@@ -1097,6 +1024,8 @@ class CollaborationBridgeLifecycleService:)adapter.set_callback_endpoint(callback_endpoint)self._callback_endpoints[bridge_id] = callback_endpoint+ if adapter_cls.receives_webhooks:+ adapter.set_webhook_url(self.webhook_url(bridge_id, bridge.type))gateway_warning = gateway_url_warning(self._config.gateway_public_url, adapter_cls.renders_custom_url_schemes@@ -1171,6 +1100,7 @@ class CollaborationBridgeLifecycleService:self._tasks[bridge_id] = taskself._started.add(bridge_id)self._platforms_seen.add(normalise_platform(bridge.type))+ self._running_adapter_classes[bridge_id] = adapter_clsif wanted is not None:self._held_resources[bridge_id] = wantedif workspace is not None:@@ -1184,7 +1114,7 @@ class CollaborationBridgeLifecycleService:# anything it raised would escape the guard — replacing the# bridge's own exception with a meaningless one, and taking the# event this method exists to emit with it.- reason = _failure_reason(exc)+ reason = _failure_reason(exc, adapter_cls)duration_ms = self._connect_duration_ms(bridge_id)emit_safely(self._telemetry,@@ -1306,7 +1236,9 @@ class CollaborationBridgeLifecycleService:# outside `emit_safely`'s guard, and this one is on the path of# a task nobody awaits, where anything it raised would surface# only as "Task exception was never retrieved" at collection.- reason = _failure_reason(exc)+ reason = _failure_reason(+ exc, self._running_adapter_classes.pop(bridge_id, None)+ )if connected:emit_safely(self._telemetry,@@ -1471,6 +1403,7 @@ class CollaborationBridgeLifecycleService:self._bridges.pop(bridge_id, None)self._held_resources.pop(bridge_id, None)self._running_workspaces.pop(bridge_id, None)+ self._running_adapter_classes.pop(bridge_id, None)self._started.discard(bridge_id)# A bridge cancelled before it connected never reaches an outcome, and# `_run_bridge`'s handler does not catch `CancelledError`, so itsdiff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex 7a02df287..816836cde 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -60,6 +60,7 @@ from switch_core.bridges.collaboration.models import (BridgeConnectionConfig,ChannelType,DirectoryUser,+ FailureReason,InboundAgentJoin,InboundAppJoin,InboundCommand,@@ -299,6 +300,35 @@ def _ephemeral(text: str) -> dict[str, Any]:class MattermostAdapter(PlatformAdapter):+ display_name: ClassVar[str] = "Mattermost"+ docs_slug: ClassVar[str | None] = "mattermost"++ @classmethod+ def classify_failure(cls, exc: BaseException) -> FailureReason | None:+ """`mattermostdriver` raises its named exceptions only for the status+ codes it maps; anything else — including a bare connection failure —+ surfaces as the underlying `requests` exception, since that is the+ client it wraps. Its named exceptions are `HTTPError`s, so the 401 and+ 403 it maps are checked before the `HTTPError` that covers the rest.+ """+ if isinstance(exc, NoAccessTokenProvided | NotEnoughPermissions):+ return "auth_failed"+ if isinstance(+ exc,+ sync_requests.exceptions.ConnectionError | sync_requests.exceptions.Timeout,+ ):+ return "network"+ # `InvalidJSONError` is a `ValueError`, which the shared classifier+ # reads as a config somebody typed wrong. A Mattermost server answering+ # with a proxy's error page is the platform misbehaving.+ if isinstance(+ exc,+ sync_requests.exceptions.HTTPError+ | sync_requests.exceptions.InvalidJSONError,+ ):+ return "platform_error"+ return None+draws_session_activity: ClassVar[bool] = True#: A problem somebody has to act on still gets its own reply, so itdiff --git a/core/switch_core/bridges/collaboration/mattermost/icon.svg b/core/switch_core/bridges/collaboration/mattermost/icon.svgnew file mode 100644index 000000000..5d9294fa5--- /dev/null+++ b/core/switch_core/bridges/collaboration/mattermost/icon.svg@@ -0,0 +1 @@+<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#0058CC" d="M12.081 0C7.048-.034 2.339 3.125.637 8.153c-2.125 6.276 1.24 13.086 7.516 15.21 6.276 2.125 13.086-1.24 15.21-7.516 1.727-5.1-.172-10.552-4.311-13.557l.126 2.547c2.065 2.282 2.88 5.512 1.852 8.549-1.534 4.532-6.594 6.915-11.3 5.321-4.708-1.593-7.28-6.559-5.745-11.092 1.031-3.046 3.655-5.121 6.694-5.67l1.642-1.94A4.87 4.87 0 0 0 12.08 0zm3.528 1.094a.284.284 0 0 0-.123.024l-.004.001a.33.33 0 0 0-.109.071c-.145.142-.657.828-.657.828L13.6 3.4l-1.3 1.585-2.232 2.776s-1.024 1.278-.798 2.851c.226 1.574 1.396 2.34 2.304 2.648.907.307 2.302.408 3.438-.704 1.135-1.112 1.098-2.75 1.098-2.75l-.087-3.56-.07-2.05-.047-1.775s.01-.856-.02-1.057a.33.33 0 0 0-.035-.107l-.006-.012-.007-.011a.277.277 0 0 0-.229-.14z"/></svg>diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.pyindex 234363d01..3fa83cd6e 100644--- a/core/switch_core/bridges/collaboration/models.py+++ b/core/switch_core/bridges/collaboration/models.py@@ -202,6 +202,15 @@ class BridgeInstallLink(BaseModel):url: str+#: Why a bridge failed, in the closed set telemetry reports it as. Never the+#: exception's message, which routinely carries a workspace name or a token+#: fragment. `PlatformAdapter.classify_failure` answers with one of these for+#: its own SDK's exceptions; the lifecycle classifies everything else.+FailureReason = Literal[+ "auth_failed", "network", "platform_error", "config_invalid", "unknown"+]++class BridgeConnectionConfig(BaseModel):passdiff --git a/core/switch_core/bridges/collaboration/platforms.py b/core/switch_core/bridges/collaboration/platforms.pynew file mode 100644index 000000000..dc8661ff1--- /dev/null+++ b/core/switch_core/bridges/collaboration/platforms.py@@ -0,0 +1,62 @@+"""Every messaging platform this build ships.++Adding a platform is one line in `PLATFORMS`: its key, its adapter and its+connection config. Everything else Switch needs to know about it — its name,+icon, docs page, capabilities and how to read its failures — the adapter+declares itself.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, NamedTuple++from switch_core.bridges.collaboration.adapter import PlatformAdapter+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 BridgeConnectionConfig+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)+from switch_core.bridges.collaboration.telegram.adapter import (+ TelegramAdapter,+ TelegramConnectionConfig,+)++if TYPE_CHECKING:+ from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+ )+++class PlatformRegistration(NamedTuple):+ #: The platform's key: a bridge's `type`, a telemetry value, a surface in+ #: the session contract. See `messaging_platforms.PLATFORM_KEY_PATTERN`.+ key: str+ adapter: type[PlatformAdapter]+ config: type[BridgeConnectionConfig]+++PLATFORMS: tuple[PlatformRegistration, ...] = (+ PlatformRegistration("mattermost", MattermostAdapter, MattermostConnectionConfig),+ PlatformRegistration("slack", SlackAdapter, SlackConnectionConfig),+ PlatformRegistration("teams", TeamsAdapter, TeamsConnectionConfig),+ PlatformRegistration("discord", DiscordAdapter, DiscordConnectionConfig),+ PlatformRegistration("telegram", TelegramAdapter, TelegramConnectionConfig),+)+++def register_platforms(lifecycle: CollaborationBridgeLifecycleService) -> None:+ """Make every platform in `PLATFORMS` available to `lifecycle`."""+ for platform in PLATFORMS:+ lifecycle.register_adapter(platform.key, platform.adapter, platform.config)diff --git a/core/switch_core/bridges/collaboration/session/renderers/__init__.py b/core/switch_core/bridges/collaboration/session/renderers/__init__.pyindex 011dfa7f4..d18385d92 100644--- a/core/switch_core/bridges/collaboration/session/renderers/__init__.py+++ b/core/switch_core/bridges/collaboration/session/renderers/__init__.py@@ -15,6 +15,7 @@ import refrom collections.abc import Callablefrom dataclasses import dataclass+from switch_core import messaging_platformsfrom switch_core.sessions.contract import (TURN_ENDED,ApprovalContent,@@ -120,18 +121,23 @@ CLOSED = {"provider-error": "The provider failed before it was answered.",}-# Where the person who answered was, in the words a reader of that platform-# would use for it.-SURFACES: dict[Surface, str] = {+# Where the person who answered was, for the two surfaces that are Switch's+# own. Every other surface is a messaging platform and is named the way that+# platform's adapter names itself.+_SWITCH_SURFACES: dict[str, str] = {"console": "the console","switch-web": "Switch",- "slack": "Slack",- "mattermost": "Mattermost",- "discord": "Discord",- "teams": "Teams",- "telegram": "Telegram",}++def surface_label(surface: Surface) -> str:+ """Where the person who answered was, in the words a reader would use."""+ own = _SWITCH_SURFACES.get(surface)+ if own is not None:+ return own+ return messaging_platforms.display_name(surface)++# An approval with nothing to choose from. The same defect as a form with no# questions in it (see `unanswerable`) and refused the same way: there is no# number to type, no word to say and nothing to press, so an instruction herediff --git a/core/switch_core/bridges/collaboration/session/renderers/neutral.py b/core/switch_core/bridges/collaboration/session/renderers/neutral.pyindex 2a5dc8246..d7a712faa 100644--- a/core/switch_core/bridges/collaboration/session/renderers/neutral.py+++ b/core/switch_core/bridges/collaboration/session/renderers/neutral.py@@ -57,11 +57,11 @@ from switch_core.sessions.contract import (from . import (CLOSED,NO_OPTIONS,- SURFACES,Drawn,Markup,RequestReference,example_value,+ surface_label,turn_state,unanswerable,)@@ -1019,7 +1019,7 @@ def _actor(it only exists when the answer was given on this very platform, so wherethere is none the Switch identity is the only true thing to say."""- where = SURFACES[decided_by.surface]+ where = surface_label(decided_by.surface)if responder:return f"{responder} from {where}"return f"{_fit(decided_by.actor_id, _share(limit, 200, 8), escape=escape)} from {where}"diff --git a/core/switch_core/bridges/collaboration/session/renderers/slack.py b/core/switch_core/bridges/collaboration/session/renderers/slack.pyindex fb161079b..28a46c423 100644--- a/core/switch_core/bridges/collaboration/session/renderers/slack.py+++ b/core/switch_core/bridges/collaboration/session/renderers/slack.py@@ -57,9 +57,9 @@ from . import (INTERRUPT_LABEL,INTERRUPT_QUEUED_NOTE,NO_OPTIONS,- SURFACES,RequestReference,example_value,+ surface_label,turn_state,unanswerable,)@@ -624,9 +624,7 @@ def _answered(request: SnapshotRequest, content: ApprovalContent) -> str:def _actor(decided_by: DecidedBy) -> str:- return (- f"{_fit(decided_by.actor_id, _MAX_ACTOR)} from {SURFACES[decided_by.surface]}"- )+ return f"{_fit(decided_by.actor_id, _MAX_ACTOR)} from {surface_label(decided_by.surface)}"def _button(option: ApprovalOption, reference: RequestReference) -> dict[str, Any]:diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex ffc716ca5..0c1d39951 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -41,6 +41,7 @@ from switch_core.bridges.collaboration.models import (BridgeCredentialError,ChannelType,DirectoryUser,+ FailureReason,InboundAgentJoin,InboundAppJoin,InboundCommand,@@ -335,7 +336,61 @@ class _ActivityStream:blocks: dict[str, dict[str, Any]] = field(default_factory=dict)+# Slack error codes that mean the credentials themselves are rejected, as+# opposed to Slack refusing a call for some other reason (rate limited, a+# scope not granted, an internal error). `SlackApiError` carries no separate+# type for this — the distinction lives entirely in `response["error"]`.+_SLACK_AUTH_ERROR_CODES = frozenset(+ {+ "invalid_auth",+ "not_authed",+ "account_inactive",+ "token_revoked",+ "token_expired",+ }+)+++def _slack_failure_reason(exc: SlackApiError) -> FailureReason:+ """`auth_failed` for a rejected token, `platform_error` for everything else+ Slack refuses a call for (rate limits, a missing scope, an outage). Both+ arrive as the same `SlackApiError`, so the code inside the response — not+ the exception's type — is what tells them apart.++ A revoked or rotated bot token is the most common bridge failure in the+ field, and reporting it as `platform_error` would send an operator to+ Slack's status page instead of their own token.+ """+ # `.response` is not always a mapping. On the async client slack_sdk+ # raises `SlackApiError(message, res)` with the raw `aiohttp.ClientResponse`+ # whenever the body it was handed is not the JSON the content type claimed+ # — an empty 502, a proxy's error page. That object has no `.get`, and this+ # is evaluated inside the argument list of the `emit_safely` that reports+ # the failure, so an `AttributeError` here would replace the bridge's real+ # exception with a meaningless one *and* suppress the event. Nor does a+ # `.get` promise a mapping: `AsyncSlackResponse.get` itself raises when+ # the body it holds is text, as a proxy's plain-text 5xx is.+ response = getattr(exc, "response", None)+ reader = getattr(response, "get", None)+ try:+ code = reader("error") if callable(reader) else None+ except Exception:+ code = None+ if code in _SLACK_AUTH_ERROR_CODES:+ return "auth_failed"+ return "platform_error"++class SlackAdapter(PlatformAdapter):+ display_name: ClassVar[str] = "Slack"+ docs_slug: ClassVar[str | None] = "slack"++ @classmethod+ def classify_failure(cls, exc: BaseException) -> FailureReason | None:+ if isinstance(exc, SlackApiError):+ return _slack_failure_reason(exc)+ return None+draws_session_activity: ClassVar[bool] = Trueseparate_attention_slot: ClassVar[bool] = Truechannel_mention: ClassVar[str | None] = "<!channel>"diff --git a/core/switch_core/bridges/collaboration/slack/icon.svg b/core/switch_core/bridges/collaboration/slack/icon.svgnew file mode 100644index 000000000..86f521f37--- /dev/null+++ b/core/switch_core/bridges/collaboration/slack/icon.svg@@ -0,0 +1,6 @@+<svg width="127" height="127" viewBox="0 0 127 127" xmlns="http://www.w3.org/2000/svg">+ <path d="M27.2 80c0 7.3-5.9 13.2-13.2 13.2C6.7 93.2.8 87.3.8 80c0-7.3 5.9-13.2 13.2-13.2h13.2V80zm6.6 0c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2v33c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V80z" fill="#E01E5A"/>+ <path d="M47 27c-7.3 0-13.2-5.9-13.2-13.2C33.8 6.5 39.7.6 47 .6c7.3 0 13.2 5.9 13.2 13.2V27H47zm0 6.7c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H13.9C6.6 60.1.7 54.2.7 46.9c0-7.3 5.9-13.2 13.2-13.2H47z" fill="#36C5F0"/>+ <path d="M99.9 46.9c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H99.9V46.9zm-6.6 0c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V13.8C66.9 6.5 72.8.6 80.1.6c7.3 0 13.2 5.9 13.2 13.2v33.1z" fill="#2EB67D"/>+ <path d="M80.1 99.8c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V99.8h13.2zm0-6.6c-7.3 0-13.2-5.9-13.2-13.2 0-7.3 5.9-13.2 13.2-13.2h33.1c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H80.1z" fill="#ECB22E"/>+</svg>diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex 4b887a286..572b69ad0 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -765,6 +765,9 @@ class TeamsAdapter(PlatformAdapter):Microsoft Graph change-notification subscriptions."""+ display_name: ClassVar[str] = "Microsoft Teams"+ docs_slug: ClassVar[str | None] = "microsoft-teams"+# Teams keeps only http(s) anchors: a link on any other scheme is stripped# whole, label and all, so a `switchdash://` deeplink left the literal# brackets around it and rendered as "()". It needs the https redirect,diff --git a/core/switch_core/bridges/collaboration/teams/icon.svg b/core/switch_core/bridges/collaboration/teams/icon.svgnew file mode 100644index 000000000..0a3547a44--- /dev/null+++ b/core/switch_core/bridges/collaboration/teams/icon.svg@@ -0,0 +1,25 @@+<svg width="256px" height="239px" viewBox="0 0 256 239" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid">+ <defs>+ <linearGradient x1="17.372046%" y1="-6.51032331%" x2="82.6280767%" y2="106.510437%" id="Teams-linearGradient-1">+ <stop stop-color="#5A62C3" offset="0%"></stop>+ <stop stop-color="#4D55BD" offset="50%"></stop>+ <stop stop-color="#3940AB" offset="100%"></stop>+ </linearGradient>+ </defs>+ <g>+ <path d="M178.562984,89.3023389 L244.688409,89.3023389 C250.935667,89.3023389 256,94.3666717 256,100.61393 C256,100.61393 256,100.61393 256,100.61393 L256,160.8454 C256,183.805692 237.387095,202.418597 214.426804,202.418597 L214.426804,202.418597 L214.230281,202.418597 C191.269989,202.421813 172.654443,183.81155 172.651112,160.851258 C172.651112,160.849305 172.651112,160.847353 172.651112,160.845285 L172.651112,95.2142112 C172.651112,91.9491339 175.298022,89.3023389 178.562984,89.3023389 L178.562984,89.3023389 Z" fill="#5059C9"></path>+ <circle fill="#5059C9" cx="223.255847" cy="50.6046204" r="26.7907017"></circle>+ <circle fill="#7B83EB" cx="139.906959" cy="38.6977185" r="38.6977185"></circle>+ <path d="M191.505908,89.3023389 L82.3545595,89.3023389 C76.1817292,89.4551005 71.2986428,94.5778961 71.4418711,100.750956 L71.4418711,169.448288 C70.5798595,206.492276 99.8873366,237.23307 136.930291,238.139647 C173.973246,237.23307 203.280608,206.492276 202.418711,169.448288 L202.418711,100.750956 C202.56171,94.5778961 197.678739,89.4551005 191.505908,89.3023389 Z" fill="#7B83EB"></path>+ <path d="M142.883742,89.3023389 L142.883742,185.57026 C142.854109,189.98484 140.178944,193.950782 136.096765,195.631619 C134.797028,196.181446 133.400121,196.465146 131.988857,196.465146 L76.6809034,196.465146 C75.9069881,194.500494 75.1925694,192.535843 74.5971439,190.511695 C72.5131546,183.680267 71.4497964,176.578577 71.4417563,169.436343 L71.4417563,100.733038 C71.2986428,94.5698561 76.1736891,89.4551005 82.3366416,89.3023389 L142.883742,89.3023389 Z" fill="#000000" opacity="0.1"></path>+ <path d="M136.930291,89.3023389 L136.930291,191.523711 C136.930291,192.934975 136.646591,194.331882 136.096765,195.631619 C134.415928,199.713798 130.449985,202.389078 126.035406,202.418597 L79.4790817,202.418597 C78.4669502,200.453945 77.5144302,198.489294 76.6809034,196.465146 C75.8473766,194.440998 75.1925694,192.535843 74.5971439,190.511695 C72.5131546,183.680382 71.4497964,176.578577 71.4417563,169.436343 L71.4417563,100.733038 C71.2986428,94.5698561 76.1736891,89.4551005 82.3366416,89.3023389 L136.930291,89.3023389 Z" fill="#000000" opacity="0.2"></path>+ <path d="M136.930291,89.3023389 L136.930291,179.616809 C136.884922,185.615055 132.033652,190.466326 126.035406,190.511695 L74.5972587,190.511695 C72.5132695,183.680382 71.4499112,176.578577 71.4418711,169.436343 L71.4418711,100.733038 C71.2987577,94.5698561 76.173804,89.4551005 82.3367565,89.3023389 L136.930291,89.3023389 Z" fill="#000000" opacity="0.2"></path>+ <path d="M130.976725,89.3023389 L130.976725,179.616809 C130.931356,185.615055 126.080086,190.466326 120.08184,190.511695 L74.5972587,190.511695 C72.5132695,183.680382 71.4499112,176.578577 71.4418711,169.436343 L71.4418711,100.733038 C71.2987577,94.5698561 76.173804,89.4551005 82.3367565,89.3023389 L130.976725,89.3023389 Z" fill="#000000" opacity="0.2"></path>+ <path d="M142.883742,58.5228377 L142.883742,77.2763289 C141.871611,77.3358255 140.919091,77.395437 139.906959,77.395437 C138.894828,77.395437 137.942308,77.3359404 136.930176,77.2763289 C134.920615,77.1429784 132.927594,76.8241317 130.976725,76.3238089 C118.920852,73.4687758 108.960799,65.0138256 104.186024,53.5815182 C103.364442,51.6616615 102.726634,49.6681806 102.280869,47.6280672 L131.988742,47.6280672 C137.996406,47.6508092 142.860885,52.5151736 142.883742,58.5228377 Z" fill="#000000" opacity="0.1"></path>+ <path d="M136.930291,64.4762887 L136.930291,77.2763289 C134.92073,77.1429784 132.927709,76.8241317 130.97684,76.3238089 C118.920967,73.4687758 108.960914,65.0138256 104.186139,53.5815182 L126.035406,53.5815182 C132.042955,53.6042602 136.907435,58.4687395 136.930291,64.4762887 Z" fill="#000000" opacity="0.2"></path>+ <path d="M136.930291,64.4762887 L136.930291,77.2763289 C134.92073,77.1429784 132.927709,76.8241317 130.97684,76.3238089 C118.920967,73.4687758 108.960914,65.0138256 104.186139,53.5815182 L126.035406,53.5815182 C132.042955,53.6042602 136.907435,58.4687395 136.930291,64.4762887 Z" fill="#000000" opacity="0.2"></path>+ <path d="M130.976725,64.4762887 L130.976725,76.3236941 C118.920852,73.468661 108.960799,65.0137108 104.186024,53.5814034 L120.08184,53.5814034 C126.089504,53.6042602 130.953869,58.4687395 130.976725,64.4762887 Z" fill="#000000" opacity="0.2"></path>+ <path d="M10.9126884,53.5814034 L120.063922,53.5814034 C126.090883,53.5814034 130.976611,58.4672463 130.976611,64.4940918 L130.976611,173.645326 C130.976611,179.672286 126.090768,184.558014 120.063922,184.558014 L10.9126884,184.558014 C4.88572809,184.558014 0,179.672171 0,173.645326 L0,64.4940918 C0,58.4672463 4.88584295,53.5814034 10.9126884,53.5814034 Z" fill="url(#Teams-linearGradient-1)"></path>+ <polygon fill="#FFFFFF" points="94.2080524 95.1248514 72.3884185 95.1248514 72.3884185 154.540713 58.4871168 154.540713 58.4871168 95.1248514 36.768788 95.1248514 36.768788 83.5989345 94.2080524 83.5989345"></polygon>+ </g>+</svg>diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex 0a0d3ea9a..91c68a3ed 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -30,6 +30,8 @@ from telegram.error import (ChatMigrated,Conflict,Forbidden,+ InvalidToken,+ NetworkError,RetryAfter,TelegramError,)@@ -56,6 +58,7 @@ from switch_core.bridges.collaboration.models import (BridgeInstallLink,ChannelCreationUnsupported,ChannelType,+ FailureReason,InboundAgentJoin,InboundAppJoin,InboundCommand,@@ -519,6 +522,25 @@ class TelegramAdapter(PlatformAdapter):bridged message."""+ display_name: ClassVar[str] = "Telegram"+ docs_slug: ClassVar[str | None] = "telegram"++ @classmethod+ def classify_failure(cls, exc: BaseException) -> FailureReason | None:+ """`BadRequest` is a subclass of `NetworkError` in python-telegram-bot,+ so the definite refusals are checked before the network failure that+ would otherwise swallow them — the same ordering `_as_rich_failure`+ uses, for the same reason."""+ if isinstance(exc, InvalidToken):+ return "auth_failed"+ if isinstance(exc, BadRequest | Forbidden | ChatMigrated):+ return "platform_error"+ if isinstance(exc, NetworkError):+ return "network"+ if isinstance(exc, TelegramError):+ return "platform_error"+ return None+supports_channel_creation: ClassVar[bool] = Falsesupports_directory_search: ClassVar[bool] = Falserenders_custom_url_schemes: ClassVar[bool] = Falsediff --git a/core/switch_core/bridges/collaboration/telegram/icon.svg b/core/switch_core/bridges/collaboration/telegram/icon.svgnew file mode 100644index 000000000..480149bb5--- /dev/null+++ b/core/switch_core/bridges/collaboration/telegram/icon.svg@@ -0,0 +1,4 @@+<svg width="127" height="127" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <circle cx="12" cy="12" r="12" fill="#26A5E4"/>+ <path fill="#fff" d="M16.906 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/>+</svg>diff --git a/core/switch_core/bridges/collaboration/webhooks.py b/core/switch_core/bridges/collaboration/webhooks.pynew file mode 100644index 000000000..b065012dd--- /dev/null+++ b/core/switch_core/bridges/collaboration/webhooks.py@@ -0,0 +1,266 @@+"""Inbound webhooks for bridges whose platform calls Switch, one address each.++A platform that cannot hold a connection open to us — email, SMS, WhatsApp,+Google Chat — delivers each event by calling an address. A connection created+in Switch gets one of its own, `/messaging/bridges/<id>/events`, and the+request is proved+with that connection's own secret by its adapter (`verify_webhook`) rather than+with a secret the deployment holds. That is what separates this from the+shared `/messaging/<platform>/...` routes, which serve Switch's own distributed+apps and are verified with the deployment's app credentials.++What happens after verification is the same as there: answer the platform at+once, hand the event to the adapter in the background, and recognise a retried+delivery so it is handled once.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import TYPE_CHECKING++from fastapi import APIRouter, BackgroundTasks, Request, Response+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from starlette.responses import PlainTextResponse++from switch_core.bridges.collaboration.install import (+ PUBLIC_PATH_PREFIX,+ InboundWebhook,+ WebhookAuthenticityError,+ WebhookPayloadError,+ WebhookRequest,+ public_url,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.messaging_event_store import MessagingEventReceiptStore+from switch_core.tenant_context import no_tenant++if TYPE_CHECKING:+ from switch_core.bridges.collaboration.adapter import PlatformAdapter+ from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+ )++logger = logging.getLogger(__name__)+++def webhook_path(bridge_id: str) -> str:+ """The path a bridge receives its platform's events on.++ Under `/messaging` because that is already the prefix a deployment exposes+ to platforms dialling in from the internet, beside the distributed apps'+ routes — so an ingress that serves those serves these with no change.+ """+ return f"{PUBLIC_PATH_PREFIX}/bridges/{bridge_id}/events"+++def webhook_url(public_origin: str | None, bridge_id: str) -> str | None:+ """The address to give the platform, or None where the deployment has not+ said what its public origin is (`MESSAGING_PUBLIC_URL`)."""+ if not public_origin:+ return None+ return public_url(public_origin, webhook_path(bridge_id))+++class WebhookBridgeUnknown(RuntimeError):+ """No bridge here takes webhooks at this address.++ Covers a bridge id that does not exist and one whose platform does not+ receive webhooks alike, so an unauthenticated caller cannot tell the two+ apart.+ """+++class WebhookBridgeStopped(RuntimeError):+ """The bridge exists and takes webhooks, and is not running to take this one.++ Transient — a bridge mid-restart — so the platform is told to try again+ rather than having the event dropped.+ """+++@dataclass(frozen=True)+class BridgeWebhookTarget:+ """The running bridge a webhook address belongs to."""++ tenant_id: str+ bridge_id: str+ bridge_type: str+ adapter: PlatformAdapter+++class BridgeWebhookService:+ def __init__(+ self,+ *,+ lifecycle: CollaborationBridgeLifecycleService,+ session_factory: async_sessionmaker[AsyncSession],+ receipts: MessagingEventReceiptStore,+ ) -> None:+ self._lifecycle = lifecycle+ self._session_factory = session_factory+ self._receipts = receipts++ async def resolve(self, bridge_id: str) -> BridgeWebhookTarget:+ """The running bridge behind this address. Raises `WebhookBridgeUnknown`+ or `WebhookBridgeStopped`."""+ return await self._lifecycle.webhook_target(bridge_id)++ async def authenticate(+ self, target: BridgeWebhookTarget, request: WebhookRequest+ ) -> InboundWebhook:+ """Prove the request is the platform's, with this bridge's own secret,+ and read it. Verification is first and unconditional."""+ await target.adapter.verify_webhook(request)+ return target.adapter.parse_webhook(request)++ async def deliver(self, target: BridgeWebhookTarget, event: InboundWebhook) -> None:+ """Hand a verified event to the bridge, at most once.++ Claimed before it is dispatched, so a retry arriving while the first+ delivery is still working finds the event taken. The receipt is keyed+ by the bridge as well as the platform's event id: two connections to+ the same platform are two apps, whose event ids need not be distinct.++ Dispatched with nothing bound, as a socket-delivered event is — see+ `MessagingInstallService.deliver`.+ """+ if event.external_event_id is None:+ await self._dispatch(target, event)+ return++ async with tenant_session(self._session_factory, target.tenant_id) as session:+ receipt = await self._receipts.claim(+ session,+ platform=target.bridge_type,+ external_event_id=f"{target.bridge_id}:{event.external_event_id}",+ )+ if receipt is None:+ logger.info(+ "Dropped a repeat delivery of %s event %s to bridge %s; it "+ "has already been taken",+ target.bridge_type,+ event.external_event_id,+ target.bridge_id,+ )+ return+ receipt_id = receipt.id+ await session.commit()++ await self._dispatch(target, event)++ async with tenant_session(self._session_factory, target.tenant_id) as session:+ await self._receipts.mark_handled(session, receipt_id=receipt_id)+ await self._receipts.prune(session)+ await session.commit()++ async def _dispatch(+ self, target: BridgeWebhookTarget, event: InboundWebhook+ ) -> None:+ with no_tenant():+ await target.adapter.dispatch_event(+ envelope_type=event.envelope_type, payload=event.payload+ )+++def create_bridge_webhook_router(service: BridgeWebhookService) -> APIRouter:+ """`/messaging/bridges/<id>/events`, mounted where the outside world reaches+ Switch.++ The status codes are read by the platform, not a person: a 5xx is retried+ and a 4xx is not, so a permanent condition must not look transient and a+ transient one must not look permanent.+ """+ router = APIRouter()++ async def _deliver(target: BridgeWebhookTarget, event: InboundWebhook) -> None:+ # A background task: the platform has had its answer, and a traceback+ # here would otherwise surface only as an unretrieved task exception.+ try:+ await service.deliver(target, event)+ except Exception:+ logger.exception(+ "Failed to deliver a %s event to bridge %s",+ target.bridge_type,+ target.bridge_id,+ )++ async def _inbound(+ bridge_id: str, request: Request, background: BackgroundTasks+ ) -> Response:+ try:+ target = await service.resolve(bridge_id)+ except WebhookBridgeUnknown:+ return Response(status_code=404)+ except WebhookBridgeStopped as failure:+ logger.error("Could not deliver a webhook: %s", failure)+ return Response(status_code=503)++ webhook = WebhookRequest(+ method=request.method,+ headers={k.lower(): v for k, v in request.headers.items()},+ query=dict(request.query_params),+ body=await request.body(),+ )+ try:+ event = await service.authenticate(target, webhook)+ except WebhookAuthenticityError as failure:+ logger.warning(+ "Refused an unverified webhook for %s bridge %s: %s",+ target.bridge_type,+ bridge_id,+ failure,+ )+ return Response(status_code=401)+ except WebhookPayloadError as failure:+ # Verified, so this really is the platform sending something the+ # adapter cannot read — how a platform's change first shows up.+ logger.error(+ "Could not read a verified webhook for %s bridge %s: %s",+ target.bridge_type,+ bridge_id,+ failure,+ )+ return Response(status_code=400)++ if event.handshake is not None:+ logger.info(+ "Answered a %s address check for bridge %s",+ target.bridge_type,+ bridge_id,+ )+ return PlainTextResponse(event.handshake)++ if event.answers_inline:+ # A platform waiting on the answer in the response itself is served+ # only by the distributed apps' route today. Refused loudly rather+ # than acknowledged, so the adapter author sees it straight away.+ logger.error(+ "%s bridge %s parsed a webhook that answers inline, which a "+ "connection's own webhook address does not support",+ target.bridge_type,+ bridge_id,+ )+ return Response(status_code=501)++ # Answered first, handled after: the platform's deadline is short and a+ # turn can take minutes.+ background.add_task(_deliver, target, event)+ return Response(status_code=200)++ @router.post(webhook_path("{bridge_id}"))+ async def events(+ bridge_id: str, request: Request, background: BackgroundTasks+ ) -> Response:+ return await _inbound(bridge_id, request, background)++ # Some platforms prove an address is ours with a GET carrying a challenge+ # (WhatsApp's `hub.challenge`) before they post anything to it.+ @router.get(webhook_path("{bridge_id}"))+ async def address_check(+ bridge_id: str, request: Request, background: BackgroundTasks+ ) -> Response:+ return await _inbound(bridge_id, request, background)++ return routerdiff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 5960ccfa6..22a243941 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -9,6 +9,7 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import ValidationErrorfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core import messaging_platformsfrom switch_core.bridges.collaboration.adapter import (ConfigEditRefused,DirectorySearchBusy,@@ -245,6 +246,8 @@ async def _detail(),attention=await _attention(bridge.id, collab_lifecycle),team_placement_supported=_places_app_in_teams(bridge.id, collab_lifecycle),+ receives_webhooks=collab_lifecycle.receives_webhooks(bridge.type),+ webhook_url=collab_lifecycle.webhook_url(bridge.id, bridge.type),)@@ -255,15 +258,25 @@ async def list_bridge_types(],_user: Annotated[User, Depends(get_current_user)],) -> list[BridgeTypeInfo]:- return [- BridgeTypeInfo(- key=t,- config_schema=collab_lifecycle.get_config_schema(t),- channel_creation_supported=collab_lifecycle.supports_channel_creation(t),- directory_search_supported=collab_lifecycle.supports_directory_search(t),+ types: list[BridgeTypeInfo] = []+ for t in collab_lifecycle.get_registered_types():+ platform = messaging_platforms.lookup(t)+ adapter_cls = collab_lifecycle.adapter_class(t)+ if platform is None or adapter_cls is None:+ raise RuntimeError(f"Bridge type {t!r} is registered but not described.")+ types.append(+ BridgeTypeInfo(+ key=t,+ display_name=platform.display_name,+ docs_slug=platform.docs_slug,+ icon_svg=platform.icon_svg,+ receives_webhooks=adapter_cls.receives_webhooks,+ config_schema=collab_lifecycle.get_config_schema(t),+ channel_creation_supported=adapter_cls.supports_channel_creation,+ directory_search_supported=adapter_cls.supports_directory_search,+ ))- for t in collab_lifecycle.get_registered_types()- ]+ return types@router.post("")diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 0708384db..e84a22c87 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -543,6 +543,12 @@ class BridgeDetail(BaseModel):# nobody has used yet — a question worth not asking rather than asking# badly.directory_search_supported: bool = True+ # Whether this connection receives its platform's events on an address of+ # its own, and that address — the one the operator gives the platform. The+ # address is None where the deployment has not set `MESSAGING_PUBLIC_URL`,+ # which is then what stands between this connection and its events.+ receives_webhooks: bool = False+ webhook_url: str | None = Noneclass BridgeUpdateRequest(BaseModel):@@ -563,6 +569,19 @@ class BridgeUpdateRequest(BaseModel):class BridgeTypeInfo(BaseModel):key: str+ # How a person names the platform ("Microsoft Teams"). Clients label the+ # platform with this rather than keeping a list of names of their own.+ display_name: str+ # The platform's page under the messaging-apps docs, or None where there+ # is none yet.+ docs_slug: str | None+ # The platform's logo as SVG markup, or None where the adapter ships none.+ # Draw it as an image (a data: URL), never inline it into a page.+ icon_svg: str | None+ # Whether connections of this type receive their events over HTTP on an+ # address of their own (`/messaging/bridges/<id>/events`), which the operator has to+ # give the platform.+ receives_webhooks: boolconfig_schema: dict[str, Any]# Whether this platform can create channels at all. Read from the adapter# class, so it is answerable before any connection of this type exists —diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 32b3ae3e7..494ef75d7 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -52,7 +52,6 @@ from switch_core.bridges.agent.server_connectors.opencode.connector import (from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,- DiscordConnectionConfig,)from switch_core.bridges.collaboration.discord.connection import DiscordConnectionfrom switch_core.bridges.collaboration.discord.gateway import DiscordGatewayClient@@ -69,19 +68,8 @@ from switch_core.bridges.collaboration.install_service import MessagingInstallSefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)-from switch_core.bridges.collaboration.mattermost.adapter import (- MattermostAdapter,- MattermostConnectionConfig,-)-from switch_core.bridges.collaboration.slack.adapter import (- SlackAdapter,- SlackConnectionConfig,-)+from switch_core.bridges.collaboration.platforms import register_platformsfrom switch_core.bridges.collaboration.slack.install import SlackAppInstaller-from switch_core.bridges.collaboration.teams.adapter import (- TeamsAdapter,- TeamsConnectionConfig,-)from switch_core.bridges.collaboration.teams.app_package import (build_distributed_app_package,)@@ -89,13 +77,16 @@ from switch_core.bridges.collaboration.teams.install import TeamsAppInstallerfrom switch_core.bridges.collaboration.teams.shared_app import TeamsSharedAppfrom switch_core.bridges.collaboration.telegram.adapter import (TelegramAdapter,- TelegramConnectionConfig,)from switch_core.bridges.collaboration.telegram.app_client import (TelegramAppClient,bot_resource,)from switch_core.bridges.collaboration.telegram.install import TelegramAppInstaller+from switch_core.bridges.collaboration.webhooks import (+ BridgeWebhookService,+ create_bridge_webhook_router,+)from switch_core.bridges.resource.service import ResourceServicefrom switch_core.clients.actor import Actor, AgentActor, HumanActor, SystemActorfrom switch_core.clients.agent_consumer import AgentConsumer@@ -884,18 +875,7 @@ async def run(config: SwitchConfig) -> None:config=config,)- # Register collaboration bridge adapter types- collab_lifecycle.register_adapter(- "mattermost", MattermostAdapter, MattermostConnectionConfig- )- collab_lifecycle.register_adapter("slack", SlackAdapter, SlackConnectionConfig)- collab_lifecycle.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)- collab_lifecycle.register_adapter(- "discord", DiscordAdapter, DiscordConnectionConfig- )- collab_lifecycle.register_adapter(- "telegram", TelegramAdapter, TelegramConnectionConfig- )+ register_platforms(collab_lifecycle)# Liveness, and cheap on purpose: the gateway Deployment and the setup Job# wait on it at boot, so anything it checked would become a boot-ordering@@ -927,6 +907,16 @@ async def run(config: SwitchConfig) -> None:create_messaging_install_router(install_service),tags=["messaging-installs"],)+ agent_bridge_app.include_router(+ create_bridge_webhook_router(+ BridgeWebhookService(+ lifecycle=collab_lifecycle,+ session_factory=session_factory,+ receipts=MessagingEventReceiptStore(),+ )+ ),+ tags=["bridge-webhooks"],+ )if management is not None:management.install(diff --git a/core/switch_core/messaging_platforms.py b/core/switch_core/messaging_platforms.pynew file mode 100644index 000000000..55e0f2c87--- /dev/null+++ b/core/switch_core/messaging_platforms.py@@ -0,0 +1,93 @@+"""The messaging platforms this process can bridge to, as a person names them.++One directory, filled in by `CollaborationBridgeLifecycleService.register_adapter`+from what each adapter declares about itself. Everything outside the adapters+that needs to say something about a platform — telemetry deciding which values+it may report, a card saying where an answer came from, the gateway telling+Console what to draw — reads it from here rather than keeping a list of its own,+so adding a platform is one adapter and one registration line.++Process-wide rather than injected because what it holds is code, not state:+the set of adapter classes this build ships, fixed once the process has+registered them. Nothing here comes from a request or the database.+"""++from __future__ import annotations++import re+from dataclasses import dataclass++#: What a platform key may look like. Lowercase, starting with a letter, short.+#:+#: Enforced because the key goes places free text may not: it is a telemetry+#: value, part of a telemetry property name (`connector_<key>_count`), a path+#: segment and a surface in the session contract. A key that fits this cannot+#: carry an identifier, a URL or markup into any of them.+PLATFORM_KEY_PATTERN = r"[a-z][a-z0-9_]{1,31}"+_PLATFORM_KEY = re.compile(rf"^{PLATFORM_KEY_PATTERN}$")+++class PlatformKeyInvalid(ValueError):+ """A platform key that does not fit `PLATFORM_KEY_PATTERN`."""+++@dataclass(frozen=True)+class MessagingPlatform:+ """What Switch knows about a platform before any connection to it exists."""++ key: str+ #: The name a person uses for it: "Microsoft Teams", not "teams".+ display_name: str+ #: The page under the messaging-apps docs that explains how to connect it,+ #: or None where there is none yet.+ docs_slug: str | None+ #: The platform's logo as SVG markup, or None where the adapter ships none.+ #: Drawn by Console as an image, never inlined into a page.+ icon_svg: str | None+++_REGISTERED: dict[str, MessagingPlatform] = {}+++def check_key(key: str) -> None:+ """Raise `PlatformKeyInvalid` unless `key` is usable as a platform key."""+ if not _PLATFORM_KEY.fullmatch(key):+ raise PlatformKeyInvalid(+ f"{key!r} is not a valid messaging platform key: use 2-32 lowercase "+ "letters, digits or underscores, starting with a letter "+ "(e.g. 'google_chat')."+ )+++def register(platform: MessagingPlatform) -> None:+ """Add a platform, replacing whatever was registered under its key."""+ check_key(platform.key)+ if not platform.display_name.strip():+ raise ValueError(f"Messaging platform {platform.key!r} has no display name.")+ _REGISTERED[platform.key] = platform+++def lookup(key: str | None) -> MessagingPlatform | None:+ """The registered platform with this key, or None."""+ if key is None:+ return None+ return _REGISTERED.get(key)+++def keys() -> tuple[str, ...]:+ """Every registered platform key, in registration order."""+ return tuple(_REGISTERED)+++def display_name(key: str) -> str:+ """The platform's name for a reader, for any key.++ A key nobody registered — a connection whose adapter was removed, a frame+ from a newer peer — still gets a readable name rather than an error: the+ key itself, with underscores as spaces and an initial capital.+ """+ platform = _REGISTERED.get(key)+ if platform is not None:+ return platform.display_name+ words = key.replace("_", " ").strip()+ return words[:1].upper() + words[1:] if words else keydiff --git a/core/switch_core/session_activity/cards.py b/core/switch_core/session_activity/cards.pyindex dd453b4a9..82a334227 100644--- a/core/switch_core/session_activity/cards.py+++ b/core/switch_core/session_activity/cards.py@@ -8,11 +8,12 @@ while open and 2 once settled.from __future__ import annotations-from typing import Literal, get_args+from typing import Literalfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core import messaging_platformsfrom switch_core.bridges.collaboration.adapter import RequestCardfrom switch_core.bridges.collaboration.session.renderers import RequestReferencefrom switch_core.db.models import (@@ -35,10 +36,8 @@ from switch_core.sessions.contract import (QuestionsResult,RequestSettled,SnapshotRequest,- Surface,)-_SURFACES: frozenset[str] = frozenset(get_args(Surface))_STATES: dict[str, Literal["open", "resolved", "closed"]] = {"open": "open","answered": "resolved",@@ -172,7 +171,7 @@ async def answerer_of(.limit(1))).first()- if found is None or found.type not in _SURFACES:+ if found is None or messaging_platforms.lookup(found.type) is None:return (DecidedBy(actor_id=answered_by, surface="switch-web", command_id=row.request_iddiff --git a/core/switch_core/sessions/contract.py b/core/switch_core/sessions/contract.pyindex 34bc7490d..9ca6b0375 100644--- a/core/switch_core/sessions/contract.py+++ b/core/switch_core/sessions/contract.py@@ -53,14 +53,13 @@ Counter = Annotated[int, Field(ge=0, le=MAX_SAFE_INTEGER)]Sequence = Annotated[int, Field(ge=1, le=MAX_SAFE_INTEGER)]Timestamp = Annotated[str, AfterValidator(_iso_datetime)]-Surface = Literal[- "console",- "switch-web",- "slack",- "mattermost",- "discord",- "teams",- "telegram",+# Where something was done: Switch's own two surfaces, or a messaging platform+# by its key. Any platform key is accepted rather than a fixed list, so a newly+# registered platform's frames validate without a contract change; the pattern+# is `messaging_platforms.PLATFORM_KEY_PATTERN`, written out because the+# contract is mirrored in TypeScript and must not depend on the bridge layer.+Surface = Annotated[+ str, StringConstraints(pattern=r"^(console|switch-web|[a-z][a-z0-9_]{1,31})$")]Provider = Annotated[str, StringConstraints(min_length=1)]diff --git a/core/switch_core/telemetry/catalogue.py b/core/switch_core/telemetry/catalogue.pyindex c82d96521..b2ddf148c 100644--- a/core/switch_core/telemetry/catalogue.py+++ b/core/switch_core/telemetry/catalogue.py@@ -15,6 +15,8 @@ from __future__ import annotationsfrom collections.abc import Mappingfrom dataclasses import dataclass+from switch_core import messaging_platforms+# The wire prefix. One Amplitude project holds several products, so every event# is namespaced by the one that sent it — the Console sends `switch_console.*`# against the same relay.@@ -81,14 +83,47 @@ class TelemetryCatalogueError(Exception):# ── Shared value sets ────────────────────────────────────────────────────────-# The five collaboration platforms, plus the absence of one. `none` rather than-# omitting the property: see the module docstring on exact property sets.-# `unknown` is a third, distinct case — not "no bridge" but "there is one and-# we could not resolve it" (e.g. the lookup itself failed) — so a transient-# error is never misreported as an internal-only room.-BRIDGE_PLATFORM = one_of(- "slack", "mattermost", "discord", "teams", "telegram", "none", "unknown"-)++@dataclass(frozen=True)+class _RegisteredPlatform(PropertyType):+ """A messaging platform this build registered, or one of `extra`.++ Closed like `one_of`, but the set is read when an event is checked rather+ than written here: it is exactly the adapters registered with the+ collaboration lifecycle, so adding a platform adds its value without an+ edit to this file. Still no free text — a platform key is code, shaped by+ `messaging_platforms.PLATFORM_KEY_PATTERN`, and a value nobody registered+ is refused like any other undeclared value.+ """++ extra: frozenset[str]++ @property+ def values(self) -> frozenset[str]:+ return self.extra | frozenset(messaging_platforms.keys())++ def check(self, value: object) -> str | None:+ allowed = self.values+ if not isinstance(value, str):+ return f"expected one of {sorted(allowed)}, got {type(value).__name__}"+ if value not in allowed:+ return f"expected one of {sorted(allowed)}, got {value!r}"+ return None+++# Every registered collaboration platform, plus the absence of one. `none`+# rather than omitting the property: see the module docstring on exact property+# sets. `unknown` is a third, distinct case — not "no bridge" but "there is one+# and we could not resolve it" (the lookup itself failed, or its platform is no+# longer registered) — so a transient error is never misreported as an+# internal-only room.+BRIDGE_PLATFORM = _RegisteredPlatform(frozenset({"none", "unknown"}))+++def connector_count_property(platform: str) -> str:+ """The `usage_snapshot` property counting one platform's connections."""+ return f"connector_{platform}_count"+# `unknown` as for BRIDGE_PLATFORM: the room exists and the lookup that would# have named its type failed, which is not the same as it having none.@@ -193,11 +228,8 @@ _SNAPSHOT_COUNTS = (# "sessions started today" — nothing durable records one, so it could only# be an in-process tally a restart resets. `session_started` covers it."session_live_count",- "connector_slack_count",- "connector_mattermost_count",- "connector_discord_count",- "connector_teams_count",- "connector_telegram_count",+ # Plus one `connector_<platform>_count` per registered platform; see+ # `event_spec`."connector_configured_count","message_count_1d","message_from_human_1d",@@ -537,6 +569,25 @@ def wire_name(event: str) -> str:return f"{EVENT_NAME_PREFIX}.{event}"+def event_spec(event: str) -> Mapping[str, PropertyType] | None:+ """What `event` declares, with the per-platform counts filled in.++ `usage_snapshot` counts connections per platform, one property each, and+ the platforms are the ones this build registered — so those keys are added+ here, when the event is checked, rather than listed in `CATALOGUE`.+ """+ spec = CATALOGUE.get(event)+ if spec is None or event != "usage_snapshot":+ return spec+ return {+ **spec,+ **{+ connector_count_property(platform): NUMBER+ for platform in messaging_platforms.keys()+ },+ }++def validate(event: str, properties: Mapping[str, PropertyValue]) -> None:"""Raise unless `properties` is exactly what `event` declares.@@ -546,7 +597,7 @@ def validate(event: str, properties: Mapping[str, PropertyValue]) -> None:property is checked too — not for privacy but for the charts, since anevent whose keys vary between emissions cannot be grouped on them."""- spec = CATALOGUE.get(event)+ spec = event_spec(event)if spec is None:raise TelemetryCatalogueError(f"{event!r} is not a telemetry event. Add it to CATALOGUE in "diff --git a/core/switch_core/telemetry/snapshot.py b/core/switch_core/telemetry/snapshot.pyindex 998b6a116..d0b900555 100644--- a/core/switch_core/telemetry/snapshot.py+++ b/core/switch_core/telemetry/snapshot.py@@ -37,6 +37,7 @@ from sqlalchemy import (from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom sqlalchemy.orm import aliased+from switch_core import messaging_platformsfrom switch_core.clients.admin_messages import AUTO_REPLY_FLAGfrom switch_core.db.models import (Agent,@@ -59,6 +60,7 @@ from switch_core.db.models import ()from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.tenant_lookup import all_tenant_ids+from switch_core.telemetry.catalogue import connector_count_propertyfrom switch_core.telemetry.internal import internal_email_conditionlogger = logging.getLogger(__name__)@@ -68,10 +70,6 @@ logger = logging.getLogger(__name__)HUMAN_CLIENT_TYPE = "user"AGENT_CLIENT_TYPE = "agent"-# The platforms reported individually. Fixed rather than derived from what is-# configured, so a deployment with no Discord bridge reports zero rather than-# omitting the property — the catalogue requires every key every time.-PLATFORMS = ("slack", "mattermost", "discord", "teams", "telegram")# What a participant said, as opposed to everything else the transport stores in# the same table: arrivals, tool and LLM call reports, task transitions. A@@ -154,8 +152,11 @@ class UsageCounts:agent_opencode_count: int = 0agent_other_count: int = 0connector_configured_count: int = 0+ # Every platform this build registered, not every one configured, so a+ # deployment with no Discord bridge reports zero rather than omitting the+ # property — the catalogue requires every key every time.connector_counts: dict[str, int] = field(- default_factory=lambda: dict.fromkeys(PLATFORMS, 0)+ default_factory=lambda: dict.fromkeys(messaging_platforms.keys(), 0))message_count_1d: int = 0message_from_human_1d: int = 0@@ -227,8 +228,8 @@ class UsageCounts:"room_group_count": self.room_group_count,"api_key_count": self.api_key_count,}- for platform in PLATFORMS:- properties[f"connector_{platform}_count"] = self.connector_counts[platform]+ for platform, count in self.connector_counts.items():+ properties[connector_count_property(platform)] = countreturn properties@@ -1153,8 +1154,18 @@ def normalise_channel_type(channel_type: str | None) -> str:def normalise_platform(platform: str | None) -> str:- """A bridge type as the catalogue spells it."""- return platform if platform in PLATFORMS else "none"+ """A bridge type as the catalogue spells it.++ `none` only where there is no bridge at all. A type this build has not+ registered — a connection whose adapter was since removed — is still a+ bridge on some platform, so it is `unknown` rather than a claim that the+ room has no bridge.+ """+ if not platform:+ return "none"+ if messaging_platforms.lookup(platform) is None:+ return "unknown"+ return platformdef normalise_known_agent_type(metadata: dict | None) -> str:diff --git a/core/tests/conftest.py b/core/tests/conftest.pyindex 54a67d624..98d59b900 100644--- a/core/tests/conftest.py+++ b/core/tests/conftest.py@@ -22,6 +22,8 @@ from testcontainers.postgres import PostgresContainer# Importing the models module registers every table on Base.metadata so# create_all provisions the full schema (rooms, room_groups, FKs, …).import switch_core.db.models # noqa: F401+from switch_core import messaging_platforms+from switch_core.bridges.collaboration.platforms import PLATFORMSfrom switch_core.db import encrypted_jsonfrom switch_core.db.base import Basefrom switch_core.db.engine import create_session_factory@@ -39,6 +41,22 @@ TEST_KEYRING = Keyring.parse()encrypted_json.configure(TEST_KEYRING)+# Production publishes these when `main.run()` registers its adapters. Tests+# that read telemetry or render cards without building a lifecycle need the+# same platforms to exist.+for _platform in PLATFORMS:+ messaging_platforms.register(_platform.adapter.describe(_platform.key))++[email protected](autouse=True)+def _restore_messaging_platforms(monkeypatch: pytest.MonkeyPatch) -> None:+ """Undo whatever a test registers. Many register a stub adapter under a real+ platform's key, which would otherwise rename that platform for every test+ that runs after it."""+ monkeypatch.setattr(+ messaging_platforms, "_REGISTERED", dict(messaging_platforms._REGISTERED)+ )+async def _seed_tenant_zero(conn: AsyncConnection) -> None:"""Insert the one tenant every scoped row's `tenant_id` default points at.diff --git a/core/tests/switch_core/bridges/collaboration/dummy_platform/__init__.py b/core/tests/switch_core/bridges/collaboration/dummy_platform/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/core/tests/switch_core/bridges/collaboration/dummy_platform/adapter.py b/core/tests/switch_core/bridges/collaboration/dummy_platform/adapter.pynew file mode 100644index 000000000..d12f149c3--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/dummy_platform/adapter.py@@ -0,0 +1,206 @@+"""A messaging platform that exists only in the tests: Dummy Chat.++It is what "adding a platform is self-contained" is held to. Everything Switch+learns about Dummy Chat — its name, icon, docs page, capabilities, how to read+its failures and how to take its webhooks — is in this folder; the tests add it+with one `register_adapter` line and touch nothing else.++Two flavours, as real platforms come: `DummyChatAdapter` dials out and is+handed its events on a connection of its own, and `DummyHookAdapter` is called+by its platform on the bridge's own webhook address, proving each request with+an HMAC over the body keyed by this connection's own secret.+"""++from __future__ import annotations++import hashlib+import hmac+import json+from collections.abc import Awaitable, Callable+from typing import Any, ClassVar++from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.install import (+ InboundWebhook,+ WebhookAuthenticityError,+ WebhookPayloadError,+ WebhookRequest,+)+from switch_core.bridges.collaboration.models import (+ BridgeConnectionConfig,+ ChannelType,+ FailureReason,+ InboundAgentJoin,+ InboundAppJoin,+ InboundCommand,+ InboundMessage,+ InboundUserJoin,+)+++class DummyChatError(Exception):+ """What Dummy Chat's (imaginary) SDK raises."""++ def __init__(self, code: str) -> None:+ super().__init__(code)+ self.code = code+++class DummyChatConnectionConfig(BridgeConnectionConfig):+ api_token: str+++class DummyChatAdapter(PlatformAdapter):+ display_name: ClassVar[str] = "Dummy Chat"+ docs_slug: ClassVar[str | None] = "dummy-chat"+ supports_channel_creation: ClassVar[bool] = False+ supports_directory_search: ClassVar[bool] = False++ def __init__(self, *, config: DummyChatConnectionConfig) -> None:+ super().__init__()+ self.config = config+ self.sent: list[tuple[str, str, str]] = []++ @classmethod+ def classify_failure(cls, exc: BaseException) -> FailureReason | None:+ if isinstance(exc, DummyChatError):+ return "auth_failed" if exc.code == "bad_token" else "platform_error"+ return None++ async def start(+ self,+ on_message: Callable[[InboundMessage], Awaitable[None]],+ on_command: Callable[[InboundCommand], Awaitable[None]],+ on_agent_joined: Callable[[InboundAgentJoin], Awaitable[None]],+ on_user_joined: Callable[[InboundUserJoin], Awaitable[None]],+ on_app_joined: Callable[[InboundAppJoin], Awaitable[None]],+ ) -> None:+ self._on_message = on_message++ async def stop(self) -> None:+ return None++ async def send_message(+ self,+ channel_id: str,+ sender_name: str,+ content: str,+ thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,+ ) -> str | None:+ self.sent.append((channel_id, sender_name, content))+ return f"msg-{len(self.sent)}"++ async def update_message(self, *a: Any, **k: Any) -> Any:+ return None++ async def delete_message(self, *a: Any, **k: Any) -> Any:+ return None++ async def send_typing(self, *a: Any, **k: Any) -> Any:+ return None++ async def create_channel(self, *a: Any, **k: Any) -> Any:+ raise NotImplementedError++ async def get_channel_type(self, channel_id: str) -> ChannelType:+ return "channel_public"++ async def add_agents_to_channel(self, *a: Any, **k: Any) -> Any:+ return None++ async def add_users_to_channel(self, *a: Any, **k: Any) -> Any:+ return None++ async def create_agent_identity(self, *a: Any, **k: Any) -> Any:+ return None++ async def remove_agent_identity(self, *a: Any, **k: Any) -> Any:+ return None++ async def get_channel_agent_names(self, *a: Any, **k: Any) -> Any:+ return []++ def _render_outbound(self, content: str) -> str:+ return content++ def translate_inbound(self, raw: Any) -> str:+ return str(raw)+++class DummyHookConnectionConfig(BridgeConnectionConfig):+ signing_secret: str+++SIGNATURE_HEADER = "x-dummy-signature"+++def sign(secret: str, body: bytes) -> str:+ """What Dummy Hook's platform puts in `SIGNATURE_HEADER`."""+ return "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()+++class DummyHookAdapter(DummyChatAdapter):+ display_name: ClassVar[str] = "Dummy Hook"+ docs_slug: ClassVar[str | None] = "dummy-hook"+ receives_webhooks: ClassVar[bool] = True++ def __init__(self, *, config: DummyHookConnectionConfig) -> None: # type: ignore[override]+ PlatformAdapter.__init__(self)+ self.hook_config = config+ self.sent = []+ self.dispatched: list[tuple[str, dict[str, Any]]] = []++ async def verify_webhook(self, request: WebhookRequest) -> None:+ if request.method == "GET":+ # The platform's address check: it proves itself with the secret+ # in the query, as WhatsApp's verify token does.+ if request.query.get("token") != self.hook_config.signing_secret:+ raise WebhookAuthenticityError("wrong address-check token")+ return+ given = request.headers.get(SIGNATURE_HEADER, "")+ expected = sign(self.hook_config.signing_secret, request.body)+ if not hmac.compare_digest(given, expected):+ raise WebhookAuthenticityError("signature does not match")++ def parse_webhook(self, request: WebhookRequest) -> InboundWebhook:+ if request.method == "GET":+ return InboundWebhook(+ envelope_type="address_check",+ payload={},+ handshake=request.query.get("challenge", ""),+ external_event_id=None,+ delivery_attempt=0,+ answers_inline=False,+ )+ try:+ payload = json.loads(request.body)+ except ValueError as exc:+ raise WebhookPayloadError("body is not JSON") from exc+ if not isinstance(payload, dict) or "id" not in payload:+ raise WebhookPayloadError("event has no id")+ return InboundWebhook(+ envelope_type="message",+ payload=payload,+ handshake=None,+ external_event_id=str(payload["id"]),+ delivery_attempt=0,+ answers_inline=False,+ )++ async def dispatch_event(+ self, *, envelope_type: str, payload: dict[str, Any]+ ) -> None:+ self.dispatched.append((envelope_type, payload))+ if self._on_message is not None:+ await self._on_message(+ InboundMessage(+ channel_id=payload["channel"],+ channel_type="channel_public",+ sender_id=payload["user"],+ sender_name=payload["user"],+ content=payload["text"],+ message_ref=str(payload["id"]),+ )+ )diff --git a/core/tests/switch_core/bridges/collaboration/dummy_platform/icon.svg b/core/tests/switch_core/bridges/collaboration/dummy_platform/icon.svgnew file mode 100644index 000000000..dc6b6fab2--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/dummy_platform/icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#7c3aed"/></svg>diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.pyindex 2725c8a75..a73758ced 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py@@ -11,7 +11,7 @@ from __future__ import annotationsimport asynciofrom types import SimpleNamespace-from typing import Any+from typing import Any, ClassVarimport discordimport pytest@@ -113,6 +113,8 @@ class _BareAdapter(PlatformAdapter):"""Concrete only so it can be instantiated: the label plumbing under testlives on the base class and no platform method is called."""+ display_name: ClassVar[str] = "Stub"+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: ...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.pyindex 27ea5af4a..a0affbe15 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@@ -10,7 +10,7 @@ from __future__ import annotationsimport loggingfrom types import SimpleNamespace-from typing import Any+from typing import Any, ClassVarimport pytest@@ -57,6 +57,8 @@ class _Adapter(PlatformAdapter):lives entirely on the base class, and none of the platform methods arecalled here."""+ display_name: ClassVar[str] = "Stub"+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: ...diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.pyindex 028f5a02f..3c20dd873 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py@@ -27,7 +27,7 @@ import timeimport uuidfrom dataclasses import dataclassfrom datetime import UTC, datetime, timedelta-from typing import Any+from typing import Any, ClassVarfrom urllib.parse import urlencodeimport httpx@@ -97,6 +97,8 @@ class _SocketOnlyAdapter(PlatformAdapter):about."""+ display_name: ClassVar[str] = "Stub"+def __init__(self) -> None: ...async def start(self, *a: Any, **k: Any) -> Any: ...diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.pyindex 4bf5bbbbf..f7120f173 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py@@ -17,7 +17,7 @@ from __future__ import annotationsimport asyncioimport uuid-from typing import Any+from typing import Any, ClassVarfrom unittest.mock import MagicMockimport pytest@@ -78,6 +78,8 @@ def _service(class _StubAdapter(PlatformAdapter):"""Concrete only so `start` can build one; no platform call is made."""+ display_name: ClassVar[str] = "Stub"+def __init__(self, *, config: Any) -> None:self._config = configdiff --git a/core/tests/switch_core/bridges/collaboration/test_platform_self_contained.py b/core/tests/switch_core/bridges/collaboration/test_platform_self_contained.pynew file mode 100644index 000000000..87373abc0--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_platform_self_contained.py@@ -0,0 +1,396 @@+"""Adding a messaging platform touches its adapter folder and one line, nothing else.++Dummy Chat (`dummy_platform/`) is registered here the way `platforms.py`+registers a real platform, and every part of Switch that used to keep its own+list of platforms is asked about it: the gateway's platform list, telemetry,+the session contract, the cards that say where an answer came from, and the+failure classifier. Then Dummy Hook, its webhook flavour, takes a signed event+on its own address all the way to the adapter.+"""++from __future__ import annotations++import json+import uuid+from typing import Any+from unittest.mock import MagicMock++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core import messaging_platforms+from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+ _failure_reason,+)+from switch_core.bridges.collaboration.models import InboundMessage+from switch_core.bridges.collaboration.session.renderers import surface_label+from switch_core.bridges.collaboration.webhooks import (+ BridgeWebhookService,+ create_bridge_webhook_router,+ webhook_path,+)+from switch_core.db.models import Client, CollaborationBridge, Tenant+from switch_core.db.stores.messaging_event_store import MessagingEventReceiptStore+from switch_core.gateway.collaborations import list_bridge_types+from switch_core.sessions.contract import DecidedBy+from switch_core.telemetry.catalogue import validate+from switch_core.telemetry.snapshot import UsageCounts, normalise_platform++from .dummy_platform.adapter import (+ SIGNATURE_HEADER,+ DummyChatAdapter,+ DummyChatConnectionConfig,+ DummyChatError,+ DummyHookAdapter,+ DummyHookConnectionConfig,+ sign,+)+from .test_lifecycle_tenant_binding import _service+++def lifecycle(+ session_factory: async_sessionmaker[AsyncSession],+) -> CollaborationBridgeLifecycleService:+ service = _service(session_factory)+ service._config.messaging_public_url = "https://switch.example"+ # The one line a platform adds.+ service.register_adapter("dummychat", DummyChatAdapter, DummyChatConnectionConfig)+ service.register_adapter("dummyhook", DummyHookAdapter, DummyHookConnectionConfig)+ return service+++class TestEverythingLearnsThePlatformFromItsAdapter:+ async def test_the_gateway_lists_it_with_its_name_icon_docs_and_capabilities(+ self, lifecycle: CollaborationBridgeLifecycleService+ ) -> None:+ types = {t.key: t for t in await list_bridge_types(lifecycle, MagicMock())}++ dummy = types["dummychat"]+ assert dummy.display_name == "Dummy Chat"+ assert dummy.docs_slug == "dummy-chat"+ assert dummy.icon_svg is not None and dummy.icon_svg.startswith("<svg")+ assert dummy.channel_creation_supported is False+ assert dummy.directory_search_supported is False+ assert dummy.receives_webhooks is False+ assert dummy.config_schema["required"] == ["api_token"]+ assert types["dummyhook"].receives_webhooks is True++ async def test_telemetry_reports_it_by_name(+ self, lifecycle: CollaborationBridgeLifecycleService+ ) -> None:+ assert normalise_platform("dummychat") == "dummychat"+ validate(+ "bridge_connected",+ {+ "bridge": "collaboration",+ "bridge_platform": "dummychat",+ "outcome": "success",+ "failure_reason": "none",+ "duration_ms": 12,+ },+ )++ async def test_the_daily_snapshot_counts_its_connections(+ self, lifecycle: CollaborationBridgeLifecycleService+ ) -> None:+ counts = UsageCounts()+ counts.connector_counts["dummychat"] += 2+ properties = counts.as_event_properties(session_live_count=0)++ assert properties["connector_dummychat_count"] == 2+ assert properties["connector_slack_count"] == 0+ validate("usage_snapshot", properties)++ async def test_a_platform_nobody_registered_is_unknown_not_no_bridge(self) -> None:+ assert normalise_platform("neverregistered") == "unknown"+ assert normalise_platform(None) == "none"++ async def test_an_answer_given_on_it_is_valid_and_named_on_cards(+ self, lifecycle: CollaborationBridgeLifecycleService+ ) -> None:+ decided = DecidedBy(actor_id="ada", surface="dummychat", command_id="c-1")+ assert surface_label(decided.surface) == "Dummy Chat"++ async def test_its_own_failures_are_classified_by_its_adapter(self) -> None:+ assert _failure_reason(DummyChatError("bad_token"), DummyChatAdapter) == (+ "auth_failed"+ )+ assert _failure_reason(DummyChatError("down"), DummyChatAdapter) == (+ "platform_error"+ )++ async def test_an_adapter_that_does_not_name_its_platform_is_refused(+ self, lifecycle: CollaborationBridgeLifecycleService+ ) -> None:+ class _Nameless(DummyChatAdapter):+ display_name = ""++ with pytest.raises(ValueError, match="declares no display_name"):+ lifecycle.register_adapter("nameless", _Nameless, DummyChatConnectionConfig)++ async def test_a_key_that_could_carry_free_text_is_refused(+ self, lifecycle: CollaborationBridgeLifecycleService+ ) -> None:+ with pytest.raises(messaging_platforms.PlatformKeyInvalid):+ lifecycle.register_adapter(+ "Dummy Chat!", DummyChatAdapter, DummyChatConnectionConfig+ )+++class _RunningBridge:+ """What the lifecycle keeps for a running bridge, as far as webhooks look."""++ def __init__(self, adapter: Any) -> None:+ self.adapter = adapter+++async def _hook_bridge(+ session_factory: async_sessionmaker[AsyncSession], *, bridge_type: str+) -> str:+ tenant = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=tenant, slug=tenant, name=tenant))+ await session.flush()+ client = Client(+ tenant_id=tenant,+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ tenant_id=tenant,+ type=bridge_type,+ display_name="Dummy",+ client_id=client.id,+ status="active",+ connection_config={"signing_secret": "s3cret"},+ )+ session.add(bridge)+ await session.flush()+ bridge_id = bridge.id+ await session.commit()+ return bridge_id+++class TestAWebhookPlatformReceivesAVerifiedEventEndToEnd:+ @pytest.fixture+ async def hook(+ self,+ lifecycle: CollaborationBridgeLifecycleService,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]]:+ bridge_id = await _hook_bridge(session_factory, bridge_type="dummyhook")+ adapter = DummyHookAdapter(+ config=DummyHookConnectionConfig(signing_secret="s3cret")+ )+ heard: list[InboundMessage] = []++ async def on_message(message: InboundMessage) -> None:+ heard.append(message)++ async def ignore(_: Any) -> None:+ return None++ await adapter.start(on_message, ignore, ignore, ignore, ignore)+ lifecycle._bridges[bridge_id] = _RunningBridge(adapter) # type: ignore[assignment]++ app = FastAPI()+ app.include_router(+ create_bridge_webhook_router(+ BridgeWebhookService(+ lifecycle=lifecycle,+ session_factory=session_factory,+ receipts=MessagingEventReceiptStore(),+ )+ )+ )+ client = httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="https://switch.example"+ )+ return client, bridge_id, adapter, heard++ @staticmethod+ def _event(event_id: str, text: str = "hello") -> bytes:+ return json.dumps(+ {"id": event_id, "channel": "c-1", "user": "ada", "text": text}+ ).encode()++ async def test_a_signed_event_reaches_the_room_side_of_the_bridge(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ ) -> None:+ client, bridge_id, adapter, heard = hook+ body = self._event("evt-1")++ response = await client.post(+ webhook_path(bridge_id),+ content=body,+ headers={SIGNATURE_HEADER: sign("s3cret", body)},+ )++ assert response.status_code == 200+ assert [m.content for m in heard] == ["hello"]+ assert adapter.dispatched[0][0] == "message"++ async def test_an_event_signed_with_another_secret_is_refused(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ ) -> None:+ client, bridge_id, adapter, heard = hook+ body = self._event("evt-2")++ response = await client.post(+ webhook_path(bridge_id),+ content=body,+ headers={SIGNATURE_HEADER: sign("someone-elses", body)},+ )++ assert response.status_code == 401+ assert heard == []++ async def test_a_retried_delivery_is_handled_once(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ ) -> None:+ client, bridge_id, adapter, heard = hook+ body = self._event("evt-3")+ headers = {SIGNATURE_HEADER: sign("s3cret", body)}++ first = await client.post(+ webhook_path(bridge_id), content=body, headers=headers+ )+ again = await client.post(+ webhook_path(bridge_id), content=body, headers=headers+ )++ assert (first.status_code, again.status_code) == (200, 200)+ assert len(heard) == 1++ async def test_the_platforms_address_check_is_answered_and_nothing_dispatched(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ ) -> None:+ client, bridge_id, adapter, heard = hook++ response = await client.get(+ webhook_path(bridge_id), params={"token": "s3cret", "challenge": "abc123"}+ )++ assert response.status_code == 200+ assert response.text == "abc123"+ assert adapter.dispatched == []++ async def test_an_unreadable_verified_body_is_a_400(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ ) -> None:+ client, bridge_id, _adapter, _heard = hook+ body = b"not json"++ response = await client.post(+ webhook_path(bridge_id),+ content=body,+ headers={SIGNATURE_HEADER: sign("s3cret", body)},+ )++ assert response.status_code == 400++ async def test_an_address_nobody_owns_is_not_found(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ ) -> None:+ client, _bridge_id, _adapter, _heard = hook+ response = await client.post(webhook_path("no-such-bridge"), content=b"{}")+ assert response.status_code == 404++ async def test_a_stopped_bridge_asks_the_platform_to_retry(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ lifecycle: CollaborationBridgeLifecycleService,+ ) -> None:+ client, bridge_id, _adapter, _heard = hook+ lifecycle._bridges.pop(bridge_id)++ response = await client.post(webhook_path(bridge_id), content=b"{}")++ assert response.status_code == 503++ async def test_a_platform_without_webhooks_has_no_address(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ lifecycle: CollaborationBridgeLifecycleService,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> None:+ client, _bridge_id, _adapter, _heard = hook+ chat_bridge = await _hook_bridge(session_factory, bridge_type="dummychat")++ response = await client.post(webhook_path(chat_bridge), content=b"{}")++ assert response.status_code == 404+ assert lifecycle.webhook_url(chat_bridge, "dummychat") is None++ async def test_the_operator_is_given_the_address_to_paste_into_the_platform(+ self,+ hook: tuple[httpx.AsyncClient, str, DummyHookAdapter, list[InboundMessage]],+ lifecycle: CollaborationBridgeLifecycleService,+ ) -> None:+ _client, bridge_id, _adapter, _heard = hook+ assert lifecycle.webhook_url(bridge_id, "dummyhook") == (+ f"https://switch.example/messaging/bridges/{bridge_id}/events"+ )+++class TestAWebhookAdapterIsToldItsOwnAddress:+ """A platform that registers its address through an API (Telegram's+ `setWebhook`) has to know the address before it starts."""++ async def test_starting_the_bridge_hands_the_adapter_its_address(+ self,+ lifecycle: CollaborationBridgeLifecycleService,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> None:+ bridge_id = await _hook_bridge(session_factory, bridge_type="dummyhook")++ async def _run(*_: object) -> None:+ return None++ lifecycle._run_bridge = _run # type: ignore[method-assign]+ try:+ await lifecycle.start(bridge_id)+ adapter = lifecycle.get_adapter(bridge_id)+ assert adapter is not None+ assert adapter.webhook_url == (+ f"https://switch.example/messaging/bridges/{bridge_id}/events"+ )+ finally:+ await lifecycle.stop_all()++ async def test_a_dial_out_adapter_is_given_no_address(+ self,+ lifecycle: CollaborationBridgeLifecycleService,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> None:+ bridge_id = await _hook_bridge(session_factory, bridge_type="dummychat")+ async with session_factory() as session:+ bridge = await session.get(CollaborationBridge, bridge_id)+ assert bridge is not None+ bridge.connection_config = {"api_token": "t"}+ await session.commit()++ async def _run(*_: object) -> None:+ return None++ lifecycle._run_bridge = _run # type: ignore[method-assign]+ try:+ await lifecycle.start(bridge_id)+ adapter = lifecycle.get_adapter(bridge_id)+ assert adapter is not None+ assert adapter.webhook_url is None+ finally:+ await lifecycle.stop_all()diff --git a/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py b/core/tests/switch_core/bridges/collaboration/test_rich_content_port.pyindex edd1d54c7..d89b16a3d 100644--- a/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py+++ b/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py@@ -11,7 +11,7 @@ from __future__ import annotationsfrom collections.abc import Callablefrom dataclasses import replace-from typing import Any+from typing import Any, ClassVarimport pytest@@ -37,6 +37,8 @@ class _BareAdapter(PlatformAdapter):this base has to turn either into `RichContentFailed`."""+ display_name: ClassVar[str] = "Stub"+def __init__(self,*,diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.pyindex 89833ad2b..f3fc88bf9 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py@@ -3,7 +3,7 @@from __future__ import annotationsimport asyncio-from typing import Any+from typing import Any, ClassVarfrom unittest.mock import AsyncMock, MagicMockimport httpx@@ -252,6 +252,8 @@ async def test_verify_credentials_reports_an_unreachable_microsoft(class _RecordingAdapter(PlatformAdapter):"""Records the order register() drives the two hooks in."""+ display_name: ClassVar[str] = "Stub"+events: list[str] = []seen_config: dict[str, object] = {}fail_verification = Falsediff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.pyindex 6000ee150..e86ca7927 100644--- a/core/tests/switch_core/gateway/test_collaborations_authz.py+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py@@ -314,6 +314,12 @@ class _NoRunningBridges:"""Read from the adapter class for the same reason."""return True+ def receives_webhooks(self, bridge_type: str) -> bool:+ return False++ def webhook_url(self, bridge_id: str, bridge_type: str) -> str | None:+ return None+async def test_set_default_promotes_and_demotes(session_factory: async_sessionmaker[AsyncSession],diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.pyindex 45537d598..18e0072ea 100644--- a/core/tests/switch_core/gateway/test_held_connections.py+++ b/core/tests/switch_core/gateway/test_held_connections.py@@ -173,6 +173,12 @@ class _CollabLifecycle:def supports_directory_search(self, bridge_type: str) -> bool:return True+ def receives_webhooks(self, bridge_type: str) -> bool:+ return False++ def webhook_url(self, bridge_id: str, bridge_type: str) -> str | None:+ return None+async def check_edited_connection_config(self, **_: Any) -> None:self._calls.record("platform credential check")diff --git a/core/tests/switch_core/gateway/test_shared_bridge_registration.py b/core/tests/switch_core/gateway/test_shared_bridge_registration.pyindex f14d7c8aa..a20b5b916 100644--- a/core/tests/switch_core/gateway/test_shared_bridge_registration.py+++ b/core/tests/switch_core/gateway/test_shared_bridge_registration.py@@ -67,6 +67,12 @@ class _Lifecycle:def supports_directory_search(self, bridge_type: str) -> bool:return False+ def receives_webhooks(self, bridge_type: str) -> bool:+ return False++ def webhook_url(self, bridge_id: str, bridge_type: str) -> str | None:+ return None+async def register(self, **kwargs: object) -> None:self.registered.append(kwargs)diff --git a/core/tests/switch_core/telemetry/test_bridge_failure_reason.py b/core/tests/switch_core/telemetry/test_bridge_failure_reason.pyindex 1439d995e..d3c74cf3a 100644--- a/core/tests/switch_core/telemetry/test_bridge_failure_reason.py+++ b/core/tests/switch_core/telemetry/test_bridge_failure_reason.py@@ -38,14 +38,41 @@ from telegram.error import (NetworkError,)+from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.discord.adapter import DiscordAdapterfrom switch_core.bridges.collaboration.lifecycle_service import _failure_reason+from switch_core.bridges.collaboration.mattermost.adapter import MattermostAdapterfrom switch_core.bridges.collaboration.models import (BridgeCredentialError,BridgeOperationError,)+from switch_core.bridges.collaboration.slack.adapter import SlackAdapter+from switch_core.bridges.collaboration.teams.adapter import TeamsAdapter+from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapterfrom switch_core.telemetry.catalogue import BRIDGE_FAILURE_REASON+def _raised_by(exc: BaseException) -> type[PlatformAdapter]:+ """The adapter of the platform whose SDK raises `exc`.++ The lifecycle classifies a failure with the adapter of the bridge that+ failed, so each case is classified the way it would be in production: a+ Slack SDK error by the Slack adapter, a `requests` error by Mattermost's+ (the only adapter on `requests`), and a transport or Switch-raised error by+ the adapter that would see it — Teams, which adds no rules of its own.+ """+ module = type(exc).__module__+ if module.startswith("slack_sdk"):+ return SlackAdapter+ if module.startswith("discord"):+ return DiscordAdapter+ if module.startswith(("mattermostdriver", "requests")):+ return MattermostAdapter+ if module.startswith("telegram"):+ return TelegramAdapter+ return TeamsAdapter++def _slack_error(code: str) -> SlackApiError:"""A `SlackApiError` carrying the response Slack actually sends: the wholedistinction between a rejected token and every other refusal lives in@@ -200,7 +227,7 @@ class TestFailureReasonClassification:def test_classification(self, description: str, exc: BaseException, expected: str) -> None:- assert _failure_reason(exc) == expected, description+ assert _failure_reason(exc, _raised_by(exc)) == expected, descriptiondef test_every_expected_value_is_one_the_catalogue_accepts(self) -> None:"""`_failure_reason` and `bridge_connected.failure_reason` share one@@ -219,12 +246,15 @@ class TestSlackAuthCodesAreExhaustiveOverNothingElse:"code", ["missing_scope", "channel_not_found", "internal_error", "fatal_error"])def test_a_non_auth_code_is_platform_error(self, code: str) -> None:- assert _failure_reason(_slack_error(code)) == "platform_error"+ assert _failure_reason(_slack_error(code), SlackAdapter) == "platform_error"def test_a_response_with_no_error_key_does_not_crash(self) -> None:"""Defensive: a malformed or unexpected response body must degrade tothe safe default rather than raising out of the classifier itself."""- assert _failure_reason(SlackApiError("boom", {"ok": False})) == "platform_error"+ assert (+ _failure_reason(SlackApiError("boom", {"ok": False}), SlackAdapter)+ == "platform_error"+ )def test_a_response_that_is_not_a_mapping_at_all_does_not_crash(self) -> None:"""The case that actually bites.@@ -248,7 +278,10 @@ class TestSlackAuthCodesAreExhaustiveOverNothingElse:status = 502assert (- _failure_reason(SlackApiError("boom", _NotAMapping())) # type: ignore[arg-type]+ _failure_reason(+ SlackApiError("boom", _NotAMapping()), # type: ignore[arg-type]+ SlackAdapter,+ )== "platform_error")@@ -266,10 +299,16 @@ class TestSlackAuthCodesAreExhaustiveOverNothingElse:status_code=502,)- assert _failure_reason(SlackApiError("boom", response)) == "platform_error"+ assert (+ _failure_reason(SlackApiError("boom", response), SlackAdapter)+ == "platform_error"+ )def test_a_response_of_none_does_not_crash(self) -> None:- assert _failure_reason(SlackApiError("boom", None)) == "platform_error" # type: ignore[arg-type]+ assert (+ _failure_reason(SlackApiError("boom", None), SlackAdapter)+ == "platform_error"+ ) # type: ignore[arg-type]class TestTheTransportFailuresThatHaveNoLibraryName:@@ -299,7 +338,7 @@ class TestTheTransportFailuresThatHaveNoLibraryName:],)def test_it_reports_network(self, description: str, exc: Exception) -> None:- assert _failure_reason(exc) == "network", description+ assert _failure_reason(exc, _raised_by(exc)) == "network", descriptionclass TestABodyThatIsNotJsonIsNotTheOperatorsConfig:@@ -310,6 +349,35 @@ class TestABodyThatIsNotJsonIsNotTheOperatorsConfig:def test_an_unparseable_mattermost_body_is_the_platform(self) -> None:assert (- _failure_reason(RequestsJSONDecodeError("not json", "<html>", 0))+ _failure_reason(+ RequestsJSONDecodeError("not json", "<html>", 0), MattermostAdapter+ )== "platform_error")+++class TestTheAdapterOwnsItsPlatformsExceptions:+ """The shared classifier knows no platform SDK: what one means is the+ knowledge of the adapter that raises it."""++ def test_a_platform_error_with_no_adapter_to_read_it_is_unknown(self) -> None:+ assert _failure_reason(_slack_error("invalid_auth"), None) == "unknown"++ def test_another_platforms_adapter_does_not_read_it(self) -> None:+ assert _failure_reason(_slack_error("invalid_auth"), TeamsAdapter) == "unknown"++ def test_the_shared_rules_still_apply_without_an_adapter(self) -> None:+ assert _failure_reason(BridgeCredentialError("no"), None) == "auth_failed"+ assert _failure_reason(httpx.ConnectError("no route"), None) == "network"+ assert _failure_reason(BridgeOperationError("no"), None) == "platform_error"+ assert _failure_reason(ValueError("bad"), None) == "config_invalid"++ def test_an_adapter_classifier_that_raises_does_not_replace_the_failure(+ self,+ ) -> None:+ class _Broken(TeamsAdapter):+ @classmethod+ def classify_failure(cls, exc: BaseException) -> None:+ raise RuntimeError("the classifier itself is broken")++ assert _failure_reason(BridgeOperationError("no"), _Broken) == "platform_error"diff --git a/core/tests/switch_core/telemetry/test_catalogue.py b/core/tests/switch_core/telemetry/test_catalogue.pyindex 950f19b4a..9f2e9269f 100644--- a/core/tests/switch_core/telemetry/test_catalogue.py+++ b/core/tests/switch_core/telemetry/test_catalogue.py@@ -15,6 +15,7 @@ from switch_core.telemetry.catalogue import (CATALOGUE,EVENT_NAME_PREFIX,TelemetryCatalogueError,+ event_spec,validate,wire_name,)@@ -56,7 +57,7 @@ def _one_valid_value(spec: object) -> object:def _valid_payload(event: str) -> dict[str, object]:- return {name: _one_valid_value(spec) for name, spec in CATALOGUE[event].items()}+ return {name: _one_valid_value(spec) for name, spec in event_spec(event).items()}class TestNothingIdentifyingCanBeSent:@@ -69,7 +70,7 @@ class TestNothingIdentifyingCanBeSent:"""offenders = {f"{event}.{name}"- for event, spec in CATALOGUE.items()+ for event, spec in ((e, event_spec(e)) for e in CATALOGUE)for name in specif name in FORBIDDEN_PROPERTIES}@@ -166,7 +167,7 @@ class TestNaming:def test_every_property_is_snake_case(self) -> None:offenders = [f"{event}.{name}"- for event, spec in CATALOGUE.items()+ for event, spec in ((e, event_spec(e)) for e in CATALOGUE)for name in specif not name.replace("_", "").isalnum() or name != name.lower()]diff --git a/core/tests/switch_core/telemetry/test_preconfigured_connectors.py b/core/tests/switch_core/telemetry/test_preconfigured_connectors.pyindex 201591263..57ba674af 100644--- a/core/tests/switch_core/telemetry/test_preconfigured_connectors.py+++ b/core/tests/switch_core/telemetry/test_preconfigured_connectors.py@@ -294,6 +294,6 @@ class TestRegisteringRecordsTheFlag:assert row.preconfigured is preconfigured[configured] = await _events(service, sink, "connector_configured")assert configured == {- "bridge_platform": "none",+ "bridge_platform": "recording","is_preconfigured": preconfigured,}diff --git a/core/tests/switch_core/telemetry/test_relay_attribute_cap.py b/core/tests/switch_core/telemetry/test_relay_attribute_cap.pyindex 34ca456cd..7231f4d9e 100644--- a/core/tests/switch_core/telemetry/test_relay_attribute_cap.py+++ b/core/tests/switch_core/telemetry/test_relay_attribute_cap.py@@ -17,7 +17,13 @@ import httpximport pytestfrom switch_core.observability.otlp import OtlpClient-from switch_core.telemetry.catalogue import BOOLEAN, CATALOGUE, NUMBER, PropertyType+from switch_core.telemetry.catalogue import (+ BOOLEAN,+ CATALOGUE,+ NUMBER,+ PropertyType,+ event_spec,+)from switch_core.telemetry.service import TelemetryServicefrom switch_core.telemetry.sink import OtlpRelaySink, TelemetryRecord@@ -78,7 +84,7 @@ async def _attributes_on_the_wire(telemetry_environment="prod",telemetry_internal=False,)- service.emit(event, **{key: value(kind) for key, kind in CATALOGUE[event].items()})+ service.emit(event, **{key: value(kind) for key, kind in event_spec(event).items()})await service.aclose()body: dict[str, Any] = {}diff --git a/core/tests/switch_core/telemetry/test_snapshot.py b/core/tests/switch_core/telemetry/test_snapshot.pyindex 79396eee1..f76ed9276 100644--- a/core/tests/switch_core/telemetry/test_snapshot.py+++ b/core/tests/switch_core/telemetry/test_snapshot.py@@ -30,6 +30,7 @@ from switch_core.db.models import (User,)from switch_core.messages.recorded_types import MEMBERSHIP_EVENT_TYPE+from switch_core.telemetry.catalogue import event_specfrom switch_core.telemetry.snapshot import (SPOKEN_EVENT_TYPES,UsageCounts,@@ -1166,10 +1167,8 @@ class TestTheDerivedProperties:assert properties[f"connector_{platform}_count"] == 0def test_the_properties_match_the_catalogue_exactly(self) -> None:- from switch_core.telemetry.catalogue import CATALOGUE-properties = UsageCounts().as_event_properties(session_live_count=3)- assert set(properties) == set(CATALOGUE["usage_snapshot"])+ assert set(properties) == set(event_spec("usage_snapshot") or {})class TestNormalising:@@ -1182,10 +1181,12 @@ class TestNormalising:assert normalise_channel_type(None) == "none"assert normalise_channel_type("something-new") == "none"- def test_an_unknown_platform_becomes_none(self) -> None:+ def test_an_unregistered_platform_is_unknown_and_no_bridge_is_none(self) -> None:+ """`none` is reserved for a room with no bridge; a bridge on a platform+ this build has not registered is still a bridge."""assert normalise_platform("slack") == "slack"assert normalise_platform(None) == "none"- assert normalise_platform("irc") == "none"+ assert normalise_platform("irc") == "unknown"def test_a_runtime_switch_does_not_know_becomes_other(self) -> None:assert normalise_known_agent_type({"known_agent_type": "codex"}) == "codex"diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex 0ec3363a9..fabbeacbc 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -93,7 +93,7 @@ id, no IP field, no Switch identity.| `agent_type` | the AI provider, from a fixed registry: `claude`, `codex`, `gemini`, `cursor`, `copilot`, `opencode`, `grok`, `devin`, `qwen`, `droid`, `amp`, `goose`, `cline`, `continue`, `mistral`, `kiro`, `junie`, … and `unknown`. **Never an agent's name.** || `location` | `local`, `remote`, `unknown`. **Never a path, directory or project name.** || `server_kind` | `local`, `remote_managed`, `external`. **Never a server name or URL.** |-| `bridge_platform` | `slack`, `mattermost`, `discord`, `teams`, `telegram`, `other`, `unknown`. **Never a workspace or channel name.** |+| `bridge_platform` | A platform key the server lists as one of its registered platforms (`slack`, `mattermost`, `discord`, `teams`, `telegram`, and any platform added since), else `other`, or `unknown` when it cannot be read. Always a short lowercase key. **Never a workspace or channel name.** || `entry_point` | `command_palette`, `sidebar`, `server_page`, `onboarding`, `agent_page`, `session_list`, `room_row`, `unknown` || `target` | `local`, `remote`, `unknown` |diff --git a/docs/contributing/add-a-messaging-platform.md b/docs/contributing/add-a-messaging-platform.mdnew file mode 100644index 000000000..074fd3649--- /dev/null+++ b/docs/contributing/add-a-messaging-platform.md@@ -0,0 +1,234 @@+# Add a messaging platform++A messaging platform (Slack, Teams, Telegram, …) connects to Switch through a+**collaboration bridge**. Adding one takes three things and nothing else:++1. **An adapter folder**: `core/switch_core/bridges/collaboration/<key>/`+2. **One registration line** in `core/switch_core/bridges/collaboration/platforms.py`+3. **A docs page**: `docs/messaging-platforms/<key>.md`++You don't edit Console, telemetry, the session contract or the gateway. They+all read what your adapter declares about itself. If you find yourself editing+one of them for your platform, stop and ask in the PR: it means something is+still hardcoded and should be fixed once for everyone.++`core/tests/switch_core/bridges/collaboration/dummy_platform/` is a complete+minimal example of both kinds of platform (one that dials out, one that+receives webhooks). Read it alongside this page.++## 1. Pick a key++The key identifies your platform everywhere: a bridge's `type`, a telemetry+value, the surface recorded on an answered approval card. It must be 2-32+characters long, use only lowercase letters, digits and underscores, and start+with a letter. Examples: `google_chat`, `whatsapp`, `email`. Registration+refuses anything else.++## 2. The adapter folder++```+core/switch_core/bridges/collaboration/<key>/+ __init__.py+ adapter.py # the adapter and its connection config+ icon.svg # the platform's logo+```++### The connection config++A pydantic model that subclasses `BridgeConnectionConfig`. Its fields *are* the+connect form: Console builds the form from this model's JSON schema, so the+field titles, descriptions and defaults are what an operator sees.++- Console masks a field whose name contains `token`, `password`, `secret`,+ `api_key`, `private_key` or `credential`. For any other secret field, add+ `Field(json_schema_extra={"format": "password"})`.+- Hide fields that shouldn't appear on the form with `SkipJsonSchema[...]`.+- Validate early. A config the adapter can't use should fail here, not at+ start.++### The adapter++Subclass `PlatformAdapter` (`bridges/collaboration/adapter.py`). The lifecycle+builds it as `YourAdapter(config=<your validated config>)`.++**Declare who you are.** All of these are class attributes:++| Attribute | Required | What it does |+|---|---|---|+| `display_name` | yes | How a person names the platform ("Microsoft Teams"). Console labels it with this, and cards say an answer came "from" it. Registration refuses an adapter without one. |+| `docs_slug` | no | The page under the published messaging-apps docs. Leave it `None` until the page is published there; Console then links to the docs index. |+| `icon.svg` | no | Shipped in your folder and served to Console, which draws it as an image. Without one Console uses a generic icon. Rename it with `icon_file` if you must. |++**Implement the basics.** These are abstract and every platform must provide+them:++- `start(on_message, on_command, on_agent_joined, on_user_joined, on_app_joined)`+ and `stop()`: connect, and hand inbound events to those callbacks.+- `send_message`, `update_message`, `delete_message`, `send_typing`: post as an+ agent, edit, delete and show typing.+- `create_channel`, `get_channel_type`, `add_agents_to_channel`,+ `add_users_to_channel`, `get_channel_agent_names`: channels and membership.+- `create_agent_identity`, `remove_agent_identity`: give an agent its own name+ and avatar on the platform, where the platform allows it.+- `translate_inbound` and `_render_outbound`: convert between the platform's+ markup and Switch Markdown.++**Everything else has a working default.** Admin messages, approval and+question cards, attachments, reactions, deeplinks and directory search all fall+back to plain text, or say clearly that they're unsupported. Override one only+when the platform can do better. Read the docstring of each method before+overriding it: many spell out guarantees the callers rely on.++**Switch off what the platform can't do.** Capability flags are class+attributes, so Switch and Console can answer before a connection exists:++| Flag | Default | Set it to False when |+|---|---|---|+| `supports_channel_creation` | True | the bot can't create a chat (Telegram) |+| `supports_directory_search` | True | the bot can only see people who have spoken to it |+| `renders_custom_url_schemes` | True | the platform only linkifies http(s) |+| `draws_session_activity` | False | set it to True only if you implement the rich session cards |++There are more flags (reactions, mentions, recovery). Each one is documented+where it is declared.++**Say what your failures mean.** When a bridge fails, telemetry reports one of+`auth_failed`, `network`, `platform_error`, `config_invalid` or `unknown`.+There are two ways to get this right:++- Raise `BridgeCredentialError` when the platform rejects the credentials, and+ `BridgeOperationError` when it refuses an operation. Both are classified for+ you.+- Or override `classify_failure(exc)` to map your SDK's own exceptions, and+ return `None` for anything that isn't yours.++Never classify by matching words in an exception's message or class name.++**Check credentials before saving.** Override `verify_credentials(config)` to+make a cheap authenticated call and raise `BridgeCredentialError` with the+platform's explanation. Without it, a wrong token looks like success and fails+hours later. If your config contains URLs that Switch itself calls, also+override `outbound_urls(config)` so the deployment's outbound policy can check+them.++**Links must be https.** `channel_deeplink` and `home_deeplink` must return+https URLs. Console opens only http(s) links for platforms it has no+special handling for.++## 3. Receiving events over webhooks (optional)++Some platforms can't keep a connection open to Switch: email, SMS, WhatsApp,+Google Chat. Instead they call an address for every event. To support that:++1. Set `receives_webhooks = True`.+2. Implement `verify_webhook(request)`. Check the request against **this+ connection's own secret**, from your config: an HMAC header over+ `request.body`, a signed token, or a token in the query string for a GET+ address check. Raise `WebhookAuthenticityError` if it doesn't prove itself.+ Don't read or log the body before this passes.+3. Implement `parse_webhook(request)`. It returns an `InboundWebhook`:+ - Set `external_event_id` to the platform's delivery id. That is what makes+ a retried delivery recognisable, so it's handled once.+ - For a request that is the platform checking the address (a challenge to+ echo back), set `handshake` to the text to answer with, and nothing is+ dispatched.+ - Set `answers_inline=False`. Events are acknowledged first and handled+ after; an event that expects its answer in the HTTP response (as a Teams+ card press does) isn't supported on a connection's own address yet.+ - Raise `WebhookPayloadError` for a body you can't read.+ - No I/O here.+4. Implement `dispatch_event(envelope_type, payload)`. It runs in the+ background, after the platform has been answered. Turn the payload into+ `InboundMessage` etc. and call the callbacks you were given in `start`.++Each connection then receives events at:++```+https://<MESSAGING_PUBLIC_URL>/messaging/bridges/<bridge id>/events+```++Switch shows that address on the connection, for the operator to paste into+the platform's settings.++Some platforms take the address through their API rather than a settings page+(Telegram's `setWebhook`, for example). The adapter is given the address+before `start` as `self.webhook_url` (`set_webhook_url`), so it can register+the address itself. That value is `None` when the deployment has no+`MESSAGING_PUBLIC_URL`; raise `BridgeOperationError` from `start` in that case,+because no event could ever arrive. Both GET and POST reach your adapter. Switch answers+immediately and hands the event over in the background, so a slow agent turn+never makes the platform time out and retry.++### Exposing it over public HTTPS++The platform calls that address from the internet, so the deployment needs:++- `MESSAGING_PUBLIC_URL` set to the public origin (scheme and host, no path,+ must be https). This is the same setting the one-click Slack app uses.+ Without it, the connection shows no address.+- The `/messaging` path prefix routed to switch-core (port 8000) on that host,+ with a browser-trusted certificate. If you already route it for the Slack+ app, you're done; see `deploy/remote/helm/switch/samples/ingress.example.yaml`.+- For local development, a tunnel works: `cloudflared tunnel --url+ http://localhost:8000` or `ngrok http 8000`. Set `MESSAGING_PUBLIC_URL` to the+ https URL it prints.++Status codes are answered for the platform's retry logic: 200 when handled,+401 for a bad signature, 400 for an unreadable body, 404 for an address with no+webhook bridge behind it, and 503 (retry later) while the bridge is stopped.++## 4. Register it++Add one line to `PLATFORMS` in+`core/switch_core/bridges/collaboration/platforms.py`:++```python+PlatformRegistration("google_chat", GoogleChatAdapter, GoogleChatConnectionConfig),+```++That publishes your platform to the gateway's platform list (and so to+Console's connect form, labels and icons), to telemetry, and to the session+renderers.++## 5. Tests++Put them in `core/tests/switch_core/bridges/collaboration/test_<key>_*.py`. At a+minimum:++- **Config**: valid configs parse; each invalid one is refused with a clear+ message.+- **Inbound**: a representative platform payload becomes the right+ `InboundMessage` (channel, sender, text, thread, attachments), and your own+ bot's messages are ignored.+- **Outbound**: `send_message`, `update_message` and `delete_message` make the+ right platform calls, with markup rendered by `_render_outbound`.+- **Failures**: `classify_failure` maps your SDK's real exception types+ (construct the real classes, don't guess them).+- **Webhooks**, if you receive them: a correctly signed request is accepted,+ one signed with another secret is refused, a malformed body is refused, a+ retried delivery carries the same `external_event_id`, and the address check+ echoes its challenge.++Mock the platform's HTTP API at the transport level, not the adapter's own+methods. `test_platform_self_contained.py` shows how to drive the webhook+route end to end.++## 6. The docs page++Write `docs/messaging-platforms/<key>.md` for the operator connecting it:++- what to create on the platform side (app, bot, token), step by step+- which permissions or scopes it needs, and why+- what each connection field means+- for webhook platforms: where to paste the address, and the HTTPS requirement+ above+- what doesn't work on this platform (the capability flags you turned off)++Once the page is published on the docs site, set `docs_slug` to its slug.++## Opening the PR++Fill in the **Adding or changing a messaging platform** section of the pull+request template: your adapter's test summary and a short video of the+platform working. [Adding support for a new messaging platform](new-messaging-platform.md)+lists exactly what the video has to show.diff --git a/docs/contributing/new-messaging-platform.md b/docs/contributing/new-messaging-platform.mdnew file mode 100644index 000000000..b3aea4782--- /dev/null+++ b/docs/contributing/new-messaging-platform.md@@ -0,0 +1,78 @@+# Adding support for a new messaging platform++This page is the short version: what to do, in order, and what your pull+request has to show. The technical details are in+[Add a messaging platform](add-a-messaging-platform.md).++## Before you start++- **Find out how the platform delivers messages.** Either Switch connects to+ it and is handed messages on that connection (a socket, long polling), or the+ platform calls a web address for every message (a webhook). Both work; the+ webhook kind also needs Switch reachable from the internet over https, and+ for testing a tunnel such as ngrok is enough.+- **Have a test account on the platform** where you can create a bot or app+ and add it to a chat. You'll need it to test.++## 1. Write the code++Follow [Add a messaging platform](add-a-messaging-platform.md). You add:++- a folder with the adapter, its connection settings and its logo;+- one line in `core/switch_core/bridges/collaboration/platforms.py`;+- a docs page, `docs/messaging-platforms/<key>.md`.++You shouldn't need to change anything else: Switch Console, telemetry and the+server learn the platform's name, logo and abilities from your adapter. If you+do change something else, say why in your pull request.++## 2. Run the automatic tests++From the repository root:++```bash+just check && just typecheck+uv run --project core pytest core/tests/switch_core/bridges/collaboration/test_<your-platform>_*.py+```++Your tests mock the platform, so they're quick and free. The whole suite also+runs on your pull request. Copy the summary your tests print at the end; you'll+paste it into your pull request.++## 3. Try it for real++The tests can't talk to the real platform. So run Switch from your branch+(`just up`, then `just run`; see [CONTRIBUTING](../../CONTRIBUTING.md#development-setup)),+point Switch Console at it, connect your platform with your test account, and+record your screen while you do this:++1. Open **Connect a messaging app** and show your platform in the list with its+ own name and logo.+2. Fill in its connect form and connect it.+3. Webhook platforms only: copy the address shown once it's connected, and+ paste it into the platform's settings.+4. Create a room on it, or add the bot to a chat, and have an agent post a+ message. Show it arriving on the platform.+5. Send a message on the platform and show it reaching the room, with the agent+ replying.+6. Get the agent to ask for approval (for example, to run a shell command),+ answer the card on the platform, and show Switch recording that it was+ answered from your platform.++Keep the video short; a couple of minutes is plenty. If the platform can't do+one of these (say, it has no buttons for approval cards), show what happens+instead and say so in the pull request.++## 4. Open the pull request++The pull request template's **Adding or changing a messaging platform**+section asks for:++- **the adapter test summary** from step 2;+- **the video** from step 3;+- three checks: nothing changed outside your platform's folder, its line and+ its docs page; what the platform can't do is declared; the docs page is+ written.++Fill in all of it. We review a new platform from those, so a pull request+without them waits.diff --git a/docs/messaging-platforms/README.md b/docs/messaging-platforms/README.mdnew file mode 100644index 000000000..0c970dc5d--- /dev/null+++ b/docs/messaging-platforms/README.md@@ -0,0 +1,12 @@+# Messaging platform pages++One page per platform added through+[Add a messaging platform](../contributing/add-a-messaging-platform.md), named+`<key>.md` after the platform's key. Each one tells an operator how to connect+the platform: what to create on the platform side, the permissions it needs,+what each connection field means and what the platform can't do.++The platforms Switch shipped with are documented on the published docs site,+under [Deploy → Messaging apps](https://docs.flintai.dev/flintai/switch/deploy/messaging-apps).+A page here moves there once it's published, and the adapter's `docs_slug` is+then set so Console links to it.diff --git a/docs/old/telemetry-events.md b/docs/old/telemetry-events.mdindex c360674b8..ed5b8c12b 100644--- a/docs/old/telemetry-events.md+++ b/docs/old/telemetry-events.md@@ -366,11 +366,7 @@ never invisible.| `agent_opencode_count` | number | || `agent_other_count` | number | including agents with no known runtime || `session_live_count` | number | connections open at snapshot time |-| `connector_slack_count` | number | **configured** bridges by platform |-| `connector_mattermost_count` | number | |-| `connector_discord_count` | number | |-| `connector_teams_count` | number | |-| `connector_telegram_count` | number | |+| `connector_<platform>_count` | number | **configured** bridges by platform: one property per platform this build registers (`connector_slack_count`, `connector_teams_count`, …), so a new platform adds its own || `connector_configured_count` | number | configured, whether or not connected || `message_count_1d` | number | messages in 24h || `message_from_human_1d` | number | of those, sent by humans |@@ -521,7 +517,7 @@ when Switch is first told about the bridge.| Property | Type ||---|---|| `channel_type` | `channel_public` \| `channel_private` \| `direct` \| `none` |-| `bridge_platform` | platform, or `none` for internal-only |+| `bridge_platform` | platform, or `none` for internal-only, or `unknown` for a bridge whose platform is not registered in this build || `agent_count` | number || `human_count` | number || `has_instructions` | boolean |