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
feat(telegram): the distributed Telegram app (#583)
Laasya Bangaloree474f496d60e
diff --git a/.env.example b/.env.exampleindex 80bb4119a..edd70dd9a 100644--- a/.env.example+++ b/.env.example@@ -265,6 +265,16 @@ FRONTEND_BASE_URL=http://localhost:5173# them apart.# TEAMS_APP_NAME=+# The distributed Telegram app — one bot per deployment whose groups a customer+# claims with a link, not the self-registered bot whose token an operator pastes+# in (TELEGRAM_SETUP.md). Set both or neither, with MESSAGING_PUBLIC_URL on port+# 443, 80, 88 or 8443. The webhook secret is 32-256 characters of A-Z a-z 0-9 _ -+# and is what proves an update came from Telegram (openssl rand -hex 32). Turn Group Privacy off in+# BotFather before the bot joins any chat. See+# docs/old/bridges/TELEGRAM_DISTRIBUTED_APP.md.+# TELEGRAM_APP_BOT_TOKEN=+# TELEGRAM_APP_WEBHOOK_SECRET=+# ── Mattermost (local dev) ───────────────────────────────────────────────────MATTERMOST_ADMIN_USER=adminMATTERMOST_ADMIN_PASSWORD=diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.tsindex a8307f66b..59c7acb38 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts@@ -122,6 +122,11 @@ describe('buildEnvFile', () => {'DISCORD_APP_CLIENT_SECRET','DISCORD_APP_BOT_TOKEN','DISCORD_APP_APPLICATION_ID',+ // Telegram's distributed bot is deployment config too, and Telegram+ // delivers its updates to a webhook on MESSAGING_PUBLIC_URL, which a+ // loopback stack cannot offer (see above).+ 'TELEGRAM_APP_BOT_TOKEN',+ 'TELEGRAM_APP_WEBHOOK_SECRET',// Agent management is off unless a server opts in, and the compose file// defaults it off. A managed stack does not opt in yet: the pinned// switch-core release predates it, and turning it on also needs adiff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex 999015dd1..a4497b725 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -259,6 +259,8 @@ services:# below: `${VAR:-}` would hand them an empty string, which fails boot.DISCORD_APP_MESSAGE_CONTENT:DISCORD_APP_MEMBERS:+ TELEGRAM_APP_BOT_TOKEN: ${TELEGRAM_APP_BOT_TOKEN:-}+ TELEGRAM_APP_WEBHOOK_SECRET: ${TELEGRAM_APP_WEBHOOK_SECRET:-}# Observability and log format. Forwarded because this service names# every variable it passes, so without them here, setting any of these# in `.env` does nothing and the Helm chart is the only way to turndiff --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 5844dcdaa..fcd850bfe 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@@ -22,6 +22,7 @@ function bridge(overrides: Partial<RemoteBridge>): RemoteBridge {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: 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 077b2d4bc..c41e82e98 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@@ -99,6 +99,7 @@ describe('createBridgeOnServer', () => {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: null,},});});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.tsindex 3df7fdee5..ee7b0da10 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts@@ -236,3 +236,92 @@ describe('bridgeInstallState', () => {await expect(bridgeInstallState(SERVER, 'b1')).rejects.toMatchObject({ status: 500 });});});++describe('disconnecting a Telegram connection', () => {+ const CHAT = { ...INSTALL, platform: 'telegram', external_workspace_id: '-1001' };++ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(validJwt());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('disconnects every chat, then deletes the connection', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, {+ installs: [+ { ...CHAT, id: 'chat-1' },+ { ...CHAT, id: 'chat-2', external_workspace_id: '-1002' },+ { ...CHAT, id: 'chat-gone', ended_at: '2026-02-01T00:00:00Z' },+ ],+ });+ }+ if (url.includes('/messaging-apps/installs/') || url.includes('/collaborations/b1')) {+ return response(200, {});+ }+ throw new Error(`unexpected request: ${url}`);+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'deleted' });++ const urls = fetchMock.mock.calls.map((call) => call[0] as string);+ expect(urls).toEqual([+ 'https://switch.example.com/gateway/messaging-apps/installs',+ 'https://switch.example.com/gateway/messaging-apps/installs/chat-1',+ 'https://switch.example.com/gateway/messaging-apps/installs/chat-2',+ 'https://switch.example.com/gateway/collaborations/b1',+ ]);+ });++ it('carries on past a chat someone else already disconnected', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, {+ installs: [+ { ...CHAT, id: 'chat-1' },+ { ...CHAT, id: 'chat-2' },+ ],+ });+ }+ if (url.endsWith('/messaging-apps/installs/chat-1')) {+ return response(404, { detail: 'Install not found' });+ }+ if (url.includes('/messaging-apps/installs/') || url.includes('/collaborations/b1')) {+ return response(200, {});+ }+ throw new Error(`unexpected request: ${url}`);+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'deleted' });+ });++ it('stops at a chat the bot cannot leave, leaving the connection in place', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, {+ installs: [+ { ...CHAT, id: 'chat-1' },+ { ...CHAT, id: 'chat-2' },+ ],+ });+ }+ if (url.endsWith('/messaging-apps/installs/chat-1')) {+ return response(502, { detail: 'Telegram refused to let the bot leave chat -1001.' });+ }+ throw new Error(`unexpected request: ${url}`);+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({+ kind: 'error',+ message: 'Telegram refused to let the bot leave chat -1001.',+ });++ const urls = fetchMock.mock.calls.map((call) => call[0] as string);+ expect(urls.some((u) => u.includes('chat-2') || u.includes('/collaborations/'))).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.tsindex df0ca6572..23c9d8e57 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.ts@@ -22,6 +22,13 @@ import type {* bridge with no such install (every bridge registered with pasted-in* credentials) is deleted the ordinary way.*+ * A Telegram connection is the exception: each chat connected through it is+ * an install of its own, and ending one only takes that chat away — the+ * connection outlives its chats. So every chat is ended in turn, and then the+ * connection itself is deleted, which the server allows once no chat uses it.+ * A chat that will not let go stops it there, with the connection and the+ * chats not yet reached still in place; disconnecting again carries on.+ ** The installs list is read with the same 404-tolerance as everywhere else a* server might predate a route: an older server has no installs to find, so* this falls back to the ordinary delete rather than failing.@@ -31,10 +38,17 @@ export async function disconnectBridgeOnServer(bridgeId: string): Promise<DeleteBridgeResult> {try {- const active = await activeInstallFor(server, bridgeId);+ const installs = await activeInstallsFor(server, bridgeId);+ const active = installs[0];if (!active) {return await deleteBridge(server, bridgeId);}+ if (CHAT_PLATFORMS.has(active.platform)) {+ for (const chat of installs) {+ await endChat(server, chat.id);+ }+ return await deleteBridge(server, bridgeId);+ }await deleteMessagingAppInstall(server, active.id);return { kind: 'deleted' };} catch (cause) {@@ -54,16 +68,35 @@ export async function bridgeInstallState(bridgeId: string): Promise<BridgeInstallState> {try {- return (await activeInstallFor(server, bridgeId)) ? 'installed' : 'not-installed';+ return (await activeInstallsFor(server, bridgeId)).length > 0 ? 'installed' : 'not-installed';} catch (cause) {if (resultFor(cause)) return 'unknown';throw cause;}}-async function activeInstallFor(server: SwitchServer, bridgeId: string) {+/**+ * Platforms whose installs are chats sharing one connection, rather than one+ * install per connection. Only the Switch Telegram app's connection has+ * installs at all; an organisation's own Telegram bot has none, and is+ * deleted the ordinary way.+ */+const CHAT_PLATFORMS = new Set(['telegram']);++async function activeInstallsFor(server: SwitchServer, bridgeId: string) {const installs = await fetchMessagingAppInstalls(server);- return installs.find((i) => i.bridgeId === bridgeId && i.endedAt === null) ?? null;+ return installs.filter((i) => i.bridgeId === bridgeId && i.endedAt === null);+}++/** End one chat's install; one already ended, by someone else in the+ * meantime, is as good as ended here. */+async function endChat(server: SwitchServer, installId: string): Promise<void> {+ try {+ await deleteMessagingAppInstall(server, installId);+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'http' && cause.status === 404) return;+ throw cause;+ }}function resultFor(cause: unknown): DeleteBridgeResult | null {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 444b3f108..ced56d932 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@@ -60,9 +60,12 @@ const {acceptInvitation,acceptPendingInvitation,addBridgeTeam,+ beginChatClaim,beginMessagingAppInstall,deleteMessagingAppInstall,- fetchInstallablePlatforms,+ disconnectChat,+ fetchConnectedChats,+ fetchMessagingApps,fetchPendingInvitations,fetchJoinableWorkspaces,fetchBridgeTeams,@@ -470,6 +473,7 @@ describe('room creation', () => {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: null,},{id: 'b2',@@ -486,6 +490,7 @@ describe('room creation', () => {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: null,},]);});@@ -512,6 +517,23 @@ describe('room creation', () => {});});+ it('carries why a connection binds no chat by id', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse([+ {+ bridge_id: 'b1',+ bridge_type: 'telegram',+ display_name: 'Telegram',+ status: 'active',+ channel_ids_refused: 'Rooms come from connecting a chat.',+ },+ ]) as never+ );++ const [bridge] = await fetchBridges(SERVER);+ expect(bridge.channelIdsRefused).toBe('Rooms come from connecting a chat.');+ });+it('reads the effective answer as the platform ceiling ANDed with the operator switch', async () => {fetchMock.mockResolvedValue(jsonResponse([@@ -1631,25 +1653,42 @@ describe("installing the deployment's own messaging app", () => {vi.unstubAllGlobals();});- it('lists the platforms the deployment has an app for', async () => {- fetchMock.mockResolvedValue(jsonResponse({ platforms: ['slack'] }) as never);+ it('lists the platforms the deployment has an app for, of both kinds', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ platforms: ['slack'],+ claimable: [{ platform: 'telegram', connected: true, can_add_chat: true }],+ }) as never+ );- await expect(fetchInstallablePlatforms(SERVER)).resolves.toEqual(['slack']);+ await expect(fetchMessagingApps(SERVER)).resolves.toEqual({+ installable: ['slack'],+ claimable: [{ platform: 'telegram', connected: true, canAddChat: true }],+ });expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe('https://switch.example.com/gateway/messaging-apps');});+ it('reads a server from before claim-based apps as offering none', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ platforms: ['slack'] }) as never);++ await expect(fetchMessagingApps(SERVER)).resolves.toEqual({+ installable: ['slack'],+ claimable: [],+ });+ });+it('reads a server without the route as having no app to install', async () => {fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);- await expect(fetchInstallablePlatforms(SERVER)).resolves.toEqual([]);+ await expect(fetchMessagingApps(SERVER)).resolves.toEqual({ installable: [], claimable: [] });});it('raises on any other failure', async () => {fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Forbidden"}') as never);- await expect(fetchInstallablePlatforms(SERVER)).rejects.toMatchObject({ status: 403 });+ await expect(fetchMessagingApps(SERVER)).rejects.toMatchObject({ status: 403 });});it('starts an install and returns the consent URL', async () => {@@ -1670,6 +1709,81 @@ describe("installing the deployment's own messaging app", () => {await expect(beginMessagingAppInstall(SERVER, 'slack')).rejects.toMatchObject({ status: 501 });});++ it('starts connecting a chat and returns its link, code and bot handle', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ url: 'https://t.me/example_bot?startgroup=abc',+ code: 'abc',+ bot_handle: '@example_bot',+ }) as never+ );++ await expect(beginChatClaim(SERVER, 'telegram')).resolves.toEqual({+ url: 'https://t.me/example_bot?startgroup=abc',+ code: 'abc',+ botHandle: '@example_bot',+ });+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://switch.example.com/gateway/messaging-apps/telegram/claim');+ expect(init.method).toBe('POST');+ });++ it('raises when the server refuses the claim', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(403, '{"detail":"Only an admin can connect the first chat"}') as never+ );++ await expect(beginChatClaim(SERVER, 'telegram')).rejects.toMatchObject({ status: 403 });+ });++ it('lists the chats still connected to one connection', async () => {+ const install = {+ bridge_id: 'b-tg',+ external_workspace_id: '-1001',+ name: 'Ops',+ status: 'active',+ scopes: '',+ installed_at: '2026-09-01T10:00:00Z',+ ended_at: null,+ };+ fetchMock.mockResolvedValue(+ jsonResponse({+ installs: [+ { ...install, id: 'i-1' },+ { ...install, id: 'i-2', name: null, external_workspace_id: '-1002' },+ { ...install, id: 'i-3', status: 'disconnected' },+ { ...install, id: 'i-4', bridge_id: 'b-other' },+ ],+ }) as never+ );++ await expect(fetchConnectedChats(SERVER, 'b-tg')).resolves.toEqual([+ { id: 'i-1', name: 'Ops', externalId: '-1001', connectedAt: '2026-09-01T10:00:00Z' },+ { id: 'i-2', name: null, externalId: '-1002', connectedAt: '2026-09-01T10:00:00Z' },+ ]);+ expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/messaging-apps/installs'+ );+ });++ it('disconnects a chat by its install', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ id: 'i-1', status: 'disconnected' }) as never);++ await disconnectChat(SERVER, 'i-1');++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://switch.example.com/gateway/messaging-apps/installs/i-1');+ expect(init.method).toBe('DELETE');+ });++ it('raises with the reason when the bot could not leave the chat', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(502, '{"detail":"Telegram would not let the bot leave; try again"}') as never+ );++ await expect(disconnectChat(SERVER, 'i-1')).rejects.toMatchObject({ status: 502 });+ });});describe('invitations addressed to the signed-in account', () => {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 f67e7610c..775e5d37d 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@@ -35,9 +35,12 @@ import type {AddTeamsTeamResult,BridgeConfigField,BridgeDirectoryUser,+ ChatClaim,+ ConnectedChat,DeleteBridgeResult,LinkedIdentity,MessagingAppInstall,+ MessagingApps,RemoteAgentRoom,RemoteAgentSummary,RemoteBridge,@@ -1163,6 +1166,7 @@ type BridgeJson = {// bridge behaved before either existed.attention?: string | null;team_placement_supported?: boolean;+ channel_ids_refused?: string | null;};function mapBridge(b: BridgeJson): RemoteBridge {@@ -1180,6 +1184,7 @@ function mapBridge(b: BridgeJson): RemoteBridge {directorySearchSupported: b.directory_search_supported ?? true,attention: b.attention ?? null,teamPlacementSupported: b.team_placement_supported ?? false,+ channelIdsRefused: b.channel_ids_refused ?? null,};}@@ -1196,24 +1201,94 @@ export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]}/**- * The messaging platforms this deployment has its own app for, which a- * workspace can install with the platform's OAuth consent screen instead of- * registering an app and pasting its tokens. Empty on a deployment that- * registered none.+ * What this deployment's own messaging apps offer the signed-in user: the+ * platforms a workspace admin can install with the platform's OAuth consent+ * screen instead of registering an app and pasting its tokens, and the ones+ * whose chats are connected one at a time with a link or code. Both empty on+ * a deployment that registered no app.*- * A 404 is a server from before the route existed; it has no app to install- * either, so it answers empty rather than failing the connect dialog.+ * A 404 is a server from before the route existed, and a missing `claimable`+ * one from before claim-based apps; either has nothing of that kind to offer,+ * so it answers empty rather than failing the connect dialog.*/-export async function fetchInstallablePlatforms(server: SwitchServer): Promise<string[]> {+export async function fetchMessagingApps(server: SwitchServer): Promise<MessagingApps> {let res: Response;try {res = await gatewayFetch(server, '/messaging-apps', { authenticated: true });} catch (cause) {- if (cause instanceof GatewayError && cause.status === 404) return [];+ if (cause instanceof GatewayError && cause.status === 404) {+ return { installable: [], claimable: [] };+ }throw cause;}- const json = (await res.json()) as { platforms: string[] };- return json.platforms;+ const json = (await res.json()) as {+ platforms: string[];+ claimable?: { platform: string; connected: boolean; can_add_chat: boolean }[];+ };+ return {+ installable: json.platforms,+ claimable: (json.claimable ?? []).map((c) => ({+ platform: c.platform,+ connected: c.connected,+ canAddChat: c.can_add_chat,+ })),+ };+}++/**+ * Start connecting a chat to the deployment's claim-based app for `platform`,+ * in the workspace the session is bound to. Nothing comes back when the chat+ * connects: the claim lands in the chat, and the server creates its room.+ */+export async function beginChatClaim(server: SwitchServer, platform: string): Promise<ChatClaim> {+ const res = await gatewayFetch(server, `/messaging-apps/${encodeURIComponent(platform)}/claim`, {+ authenticated: true,+ method: 'POST',+ });+ const json = (await res.json()) as { url: string; code: string; bot_handle: string };+ return { url: json.url, code: json.code, botHandle: json.bot_handle };+}++/**+ * The chats connected to a claim-based connection, from the server's list of+ * this workspace's installs. Ended ones are left out: they are history, and+ * nothing here can be done to them.+ */+export async function fetchConnectedChats(+ server: SwitchServer,+ bridgeId: string+): Promise<ConnectedChat[]> {+ const res = await gatewayFetch(server, '/messaging-apps/installs', { authenticated: true });+ const json = (await res.json()) as {+ installs: {+ id: string;+ bridge_id: string | null;+ external_workspace_id: string;+ name: string | null;+ status: string;+ installed_at: string;+ }[];+ };+ return json.installs+ .filter((i) => i.bridge_id === bridgeId && i.status === 'active')+ .map((i) => ({+ id: i.id,+ name: i.name,+ externalId: i.external_workspace_id,+ connectedAt: i.installed_at,+ }));+}++/**+ * Disconnect one chat: the bot leaves it and its room stays, bridged to+ * nothing. Raises with the server's reason when it refuses, including when+ * the platform would not let the bot leave, which changes nothing.+ */+export async function disconnectChat(server: SwitchServer, installId: string): Promise<void> {+ await gatewayFetch(server, `/messaging-apps/installs/${encodeURIComponent(installId)}`, {+ authenticated: true,+ method: 'DELETE',+ });}/**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 644157b36..be9b5ebe6 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@@ -91,6 +91,7 @@ describe('updateBridgeOnServer', () => {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: null,},});});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsindex 740d4c7e9..7f7832c1d 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts@@ -10,11 +10,13 @@ import {addBridgeTeam,addRoomAgents,agentExistsOnServer,+ beginChatClaim,changeTemplateRun,createRoomFromTemplate,createTemplate,deleteRoom,deleteTemplate,+ disconnectChat,exportRoomYaml,fetchAddressingPolicy,fetchAgentManagementAccess,@@ -25,7 +27,8 @@ import {fetchBridgeTeams,beginMessagingAppInstall,fetchBridgeTypes,- fetchInstallablePlatforms,+ fetchConnectedChats,+ fetchMessagingApps,fetchMyIdentities,fetchRoomAgentIds,fetchRoomDetail,@@ -80,7 +83,9 @@ import type {AgentIconBackfill,AgentVerifyResult,BridgeDirectorySearchResult,+ ChatClaim,ClaimIdentityParams,+ ConnectedChat,ClaimIdentityResult,CreateBridgeParams,CreateBridgeResult,@@ -89,6 +94,7 @@ import type {DeleteBridgeParams,DeleteBridgeResult,LinkedIdentity,+ MessagingApps,RemoteAgentRoom,RemoteAgentSummary,RemoteBridge,@@ -283,8 +289,8 @@ export const workspacesController = createRPCController({listBridgeTypes: (workspaceId: string): Promise<RemoteBridgeType[]> =>withReachableWorkspaceSession(workspaceId, fetchBridgeTypes),- listInstallablePlatforms: (workspaceId: string): Promise<string[]> =>- withReachableWorkspaceSession(workspaceId, fetchInstallablePlatforms),+ listMessagingApps: (workspaceId: string): Promise<MessagingApps> =>+ withReachableWorkspaceSession(workspaceId, fetchMessagingApps),/** Returns the platform's consent URL for the renderer to open in the browser. */beginMessagingAppInstall: (params: { workspaceId: string; platform: string }): Promise<string> =>@@ -292,6 +298,26 @@ export const workspacesController = createRPCController({beginMessagingAppInstall(server, params.platform)),+ /** A one-time link and code that connect a chat; the chat itself is where it lands. */+ beginChatClaim: (params: { workspaceId: string; platform: string }): Promise<ChatClaim> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ beginChatClaim(server, params.platform)+ ),++ listConnectedChats: (params: {+ workspaceId: string;+ bridgeId: string;+ }): Promise<ConnectedChat[]> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ fetchConnectedChats(server, params.bridgeId)+ ),++ /** Open to members: a chat is a room, and rooms are members'. */+ disconnectChat: (params: { workspaceId: string; installId: string }): Promise<void> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ disconnectChat(server, params.installId)+ ),+/*** Attach a collaboration bridge to the chosen workspace (CHOO-1784).*diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex a863fc155..756210f42 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -15,6 +15,7 @@ import { AddServerModal } from '@renderer/features/switch-servers/AddServerModalimport { AssignServerModal } from '@renderer/features/switch-servers/assign-server-modal';import { BundledChatSignInModal } from '@renderer/features/switch-servers/BundledChatSignIn';import { ClaimIdentityModal } from '@renderer/features/switch-servers/ClaimIdentityModal';+import { ConnectChatModal } from '@renderer/features/switch-servers/ConnectChatModal';import { ConnectionsModal } from '@renderer/features/switch-servers/ConnectionsModal';import { ConnectMessagingAppModal } from '@renderer/features/switch-servers/ConnectMessagingAppModal';import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomModal';@@ -94,6 +95,7 @@ export const modalRegistry = {size: 'md',dismissOnOutsideClick: false,}),+ connectChatModal: createModal(ConnectChatModal, { size: 'md' }),connectionsModal: createModal(ConnectionsModal, { size: 'md' }),claimIdentityModal: createModal(ClaimIdentityModal, {size: 'md',diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectChatModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectChatModal.tsxnew file mode 100644index 000000000..7dfba9750--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectChatModal.tsx@@ -0,0 +1,72 @@+import { useQuery } from '@tanstack/react-query';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useOnUnmount } from '@renderer/lib/hooks/use-on-unmount';+import { rpc } from '@renderer/lib/ipc';+import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Spinner } from '@renderer/lib/ui/spinner';+import { ChatClaimDetails } from './ConnectChatPanel';++type ConnectChatModalArgs = {+ workspaceId: string;+ platform: string;+ /** Run however the dialog goes away. The chat's room is made in the chat,+ * on no signal Switch Console receives, so this is when to look for it. */+ onClosed: () => void;+};++type Props = BaseModalProps<void> & ConnectChatModalArgs;++/**+ * Connect one more chat to a connection that already exists, from its row in+ * Messaging apps. Open to members as well as admins: once a workspace has the+ * connection, a chat is a room, and rooms are members'.+ *+ * The claim is minted when the dialog opens and never again while it stays+ * open — each one is a new code, and a refetch on focus would quietly swap the+ * one the user is halfway through pasting.+ *+ * Goes through the modal registry because it is opened from the row's+ * dropdown, which unmounts anything rendered inside it as it closes.+ */+export function ConnectChatModal({ workspaceId, platform, onClosed, onClose }: Props) {+ const label = bridgePlatformLabel(platform);+ useOnUnmount(onClosed);+ const claimQuery = useQuery({+ queryKey: ['chat-claim', workspaceId, platform],+ queryFn: () => rpc.workspaces.beginChatClaim({ workspaceId, platform }),+ staleTime: Infinity,+ gcTime: 0,+ retry: false,+ refetchOnWindowFocus: false,+ });++ return (+ <>+ <DialogHeader>+ <DialogTitle>Add to {label}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ {claimQuery.isLoading && <Spinner className="size-4" />}+ {claimQuery.isError && (+ <p className="text-xs text-destructive">+ {failureText(claimQuery.error, `Could not start connecting a ${label} chat.`)}+ </p>+ )}+ {claimQuery.data && <ChatClaimDetails platform={platform} claim={claimQuery.data} />}+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose}>+ Close+ </Button>+ </DialogFooter>+ </>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectChatPanel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectChatPanel.tsxnew file mode 100644index 000000000..24b14c37c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectChatPanel.tsx@@ -0,0 +1,197 @@+import { useQuery } from '@tanstack/react-query';+import { Check, Copy, ExternalLink, Loader2 } from 'lucide-react';+import { useCallback, useEffect, useState } from 'react';+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 { rpc } from '@renderer/lib/ipc';+import { openExternalUrl } from '@renderer/lib/open-external';+import { Button } from '@renderer/lib/ui/button';+import type { ChatClaim, ClaimablePlatform } from '@shared/core/switch-servers/switch-servers';+import { INSTALL_POLL_INTERVAL_MS } from './InstallMessagingAppPanel';++type ConnectedBridge = { bridgeId: string; displayName: string };++type Phase =+ | { kind: 'idle' }+ | { kind: 'starting' }+ | { kind: 'shown'; claim: ChatClaim; knownBridgeIds: ReadonlySet<string> | null };++type Props = {+ workspaceId: string;+ claimable: ClaimablePlatform;+ /** Called once the link and code are on screen. */+ onShown: () => void;+ /** Called once the workspace's first chat has created its connection. */+ onConnected: (bridge: ConnectedBridge) => void;+};++/**+ * Connect a chat to the deployment's claim-based app for a platform (the+ * Switch Telegram app), from the Connect a messaging app dialog.+ *+ * The claim lands in the chat, not here, so nothing comes back when it works.+ * A workspace's first chat is the exception: it creates the connection, so the+ * panel notes which bridges existed before and hands over the new one, the way+ * an OAuth install does. Later chats only add rooms to a connection that is+ * already there, and the details stay up until the dialog is closed.+ */+export function ConnectChatPanel({ workspaceId, claimable, onShown, onConnected }: Props) {+ const { platform } = claimable;+ const label = bridgePlatformLabel(platform);+ const [phase, setPhase] = useState<Phase>({ kind: 'idle' });+ const [error, setError] = useState<string | null>(null);++ const watching = phase.kind === 'shown' && phase.knownBridgeIds !== null;+ const bridgesQuery = useQuery({+ queryKey: ['messaging-app-claim-wait', workspaceId, platform],+ queryFn: () => rpc.workspaces.listBridges(workspaceId),+ enabled: watching,+ refetchInterval: watching ? INSTALL_POLL_INTERVAL_MS : false,+ gcTime: 0,+ });++ useEffect(() => {+ if (phase.kind !== 'shown' || phase.knownBridgeIds === null || !bridgesQuery.data) return;+ const known = phase.knownBridgeIds;+ const created = bridgesQuery.data.find((b) => b.type === platform && !known.has(b.id));+ if (created) onConnected({ bridgeId: created.id, displayName: created.displayName });+ }, [phase, bridgesQuery.data, platform, onConnected]);++ const start = async () => {+ setPhase({ kind: 'starting' });+ setError(null);+ try {+ const before = claimable.connected ? null : await rpc.workspaces.listBridges(workspaceId);+ const claim = await rpc.workspaces.beginChatClaim({ workspaceId, platform });+ setPhase({+ kind: 'shown',+ claim,+ knownBridgeIds: before === null ? null : new Set(before.map((b) => b.id)),+ });+ onShown();+ } catch (cause) {+ setPhase({ kind: 'idle' });+ setError(failureText(cause, `Could not start connecting a ${label} chat.`));+ }+ };++ if (phase.kind === 'shown') {+ return (+ <div className="flex flex-col gap-2">+ <ChatClaimDetails platform={platform} claim={phase.claim} />+ {watching && (+ <p className="flex items-center gap-2 text-xs text-foreground-muted">+ <Loader2 className="size-3.5 animate-spin" />+ This connection appears here as soon as the first chat is connected.+ </p>+ )}+ {watching && bridgesQuery.isError && (+ <p className="text-xs text-destructive">+ {failureText(+ bridgesQuery.error,+ `Could not check whether ${label} is connected yet; still trying`+ )}+ </p>+ )}+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-foreground-muted">+ Connects a {label} group or channel to this Switch server’s own {label} app. Each chat gets+ a room; there are no tokens to copy.+ </p>+ <Button className="w-fit" onClick={() => void start()} disabled={phase.kind === 'starting'}>+ {hasBridgeIcon(platform) && <BridgeIcon bridgeType={platform} size={16} />}+ {phase.kind === 'starting' ? 'Getting a link…' : `Add to ${label}`}+ </Button>+ {error && <p className="text-xs text-destructive">{error}</p>}+ </div>+ );+}++/**+ * How to use a claim: a link for a group, and the bot's handle and a command+ * for a channel. A channel carries nothing when a bot is added to it, so its+ * admin adds the bot by hand and posts the code; the handle is shown whole+ * because Telegram's search does not find a bot by part of it. The expiry is+ * said here because a link that quietly stopped working looks exactly like one+ * that never did.+ */+export function ChatClaimDetails({ platform, claim }: { platform: string; claim: ChatClaim }) {+ const label = bridgePlatformLabel(platform);+ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1.5">+ <Button+ className="w-fit"+ onClick={() => void openExternalUrl(claim.url, `Could not open ${label}`)}+ >+ <ExternalLink className="size-4" />+ Add to a {label} group+ </Button>+ <p className="text-xs text-foreground-muted">+ Pick a group and confirm. The bot joins and asks which Switch organisation the group is+ for; when a group admin chooses Connect, Switch creates the group’s room.+ </p>+ </div>++ <div className="flex flex-col gap-1.5 text-xs">+ <p>+ For a channel, open its Administrators, choose Add Admin, and search for the bot by its+ full username:+ </p>+ <CopyableValue value={claim.botHandle} label="the bot’s username" />+ <p>+ Keep its permission to post, save, then post this in the channel and choose Connect when+ the bot asks:+ </p>+ <CopyableValue value={`/connect ${claim.code}`} label="the command" />+ <p className="text-foreground-muted">+ Agents can always post to the channel. For posts in the channel to reach agents, turn on+ Sign Messages and Show Authors’ Profiles in its settings, and post as yourself rather than+ as the channel.+ </p>+ </div>++ <p className="rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">+ The link and the code work once, for ten minutes. Anyone who has them in that time can ask+ to connect a chat to this workspace, so share them only with people who should.+ </p>+ </div>+ );+}++function CopyableValue({ value, label }: { value: string; label: string }) {+ const [copied, setCopied] = useState(false);++ const copy = useCallback(() => {+ void navigator.clipboard.writeText(value).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ });+ }, [value]);++ return (+ <div className="flex items-center gap-2">+ <code className="min-w-0 truncate rounded bg-background-quaternary-1 px-2 py-1 font-mono text-xs text-foreground">+ {value}+ </code>+ <button+ type="button"+ onClick={copy}+ aria-label={copied ? `Copied ${label}` : `Copy ${label}`}+ className="shrink-0 rounded p-1 text-foreground-passive hover:bg-background-2 hover:text-foreground"+ >+ {copied ? (+ <Check className="size-3.5 text-foreground-success" />+ ) : (+ <Copy className="size-3.5" />+ )}+ </button>+ </div>+ );+}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 507a77d81..9c9b66f83 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@@ -6,6 +6,7 @@ import { workspacesStore } from '@renderer/features/workspaces/workspaces-store'import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel, bridgeSetupDocsUrl } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';+import { useOnUnmount } from '@renderer/lib/hooks/use-on-unmount';import { rpc } from '@renderer/lib/ipc';import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';import { openExternalUrl } from '@renderer/lib/open-external';@@ -29,6 +30,7 @@ import {} from '@renderer/lib/ui/select';import { cn } from '@renderer/utils/utils';import type { CreateBridgeResult } from '@shared/core/switch-servers/switch-servers';+import { ConnectChatPanel } from './ConnectChatPanel';import { InstallMessagingAppPanel } from './InstallMessagingAppPanel';import { switchServersStore } from './switch-servers-store';import { administersWorkspaceInScope } from './workspace-admin';@@ -36,6 +38,10 @@ import { administersWorkspaceInScope } from './workspace-admin';type ConnectMessagingAppModalArgs = {/** Attach to this server instead of the active one. */serverId?: string;+ /** Run however the dialog goes away. A chat connected from it after the+ * first lands on no signal Switch Console receives, so this is when to+ * look for it. */+ onClosed: () => void;};/** What the caller needs to decide what to do next. `directorySearchSupported`@@ -52,9 +58,11 @@ type Props = BaseModalProps<ConnectedApp> & ConnectMessagingAppModalArgs;export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModal({serverId: overrideServerId,+ onClosed,onSuccess,onClose,}: Props) {+ useOnUnmount(onClosed);const { setCloseGuard } = useModalContext();const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';@@ -85,13 +93,18 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod// Asked only of someone who may install: the route refuses everyone else, and// for them the dialog already says why nothing here will work.const installableQuery = useQuery({- queryKey: ['installable-messaging-apps', workspaceId],- queryFn: () => rpc.workspaces.listInstallablePlatforms(workspaceId as string),+ queryKey: ['messaging-apps', workspaceId],+ queryFn: () => rpc.workspaces.listMessagingApps(workspaceId as string),enabled: workspaceId !== null && isAdmin,});- const installable = installableQuery.data ?? [];+ const installable = installableQuery.data?.installable ?? [];+ const claimable = (installableQuery.data?.claimable ?? []).filter((c) => c.canAddChat);const [useOwnApp, setUseOwnApp] = useState(false);- const offerInstall = installable.length > 0 && !useOwnApp;+ // The platform whose link and code are on screen. From then on the dialog is+ // about that one chat: the other apps are a different errand, and for a+ // workspace that already has the connection, closing is how it ends.+ const [claimingPlatform, setClaimingPlatform] = useState<string | null>(null);+ const offerInstall = (installable.length > 0 || claimable.length > 0) && !useOwnApp;const showForm = !offerInstall && !(isAdmin && installableQuery.isLoading);const types = useMemo(() => typesQuery.data ?? [], [typesQuery.data]);@@ -214,7 +227,11 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModreturn (<><DialogHeader showCloseButton={false}>- <DialogTitle>Connect a messaging app{server ? ` to ${server.name}` : ''}</DialogTitle>+ <DialogTitle>+ {claimingPlatform !== null+ ? `Add to ${bridgePlatformLabel(claimingPlatform)}`+ : `Connect a messaging app${server ? ` to ${server.name}` : ''}`}+ </DialogTitle></DialogHeader><DialogContentArea className="pt-0"><div className="flex w-full flex-col gap-5">@@ -246,21 +263,35 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod{offerInstall && workspaceId !== null && (<>- {installable.map((platform) => (- <InstallMessagingAppPanel- key={platform}- workspaceId={workspaceId}- platform={platform}- onInstalled={(bridge) => handleInstalled(platform, bridge)}- />- ))}- <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>+ {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>+ )}</>)}@@ -428,7 +459,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod</DialogContentArea><DialogFooter><Button variant="outline" onClick={onClose} disabled={isSubmitting}>- Cancel+ {claimingPlatform !== null ? 'Close' : 'Cancel'}</Button>{showForm && (<ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectedChatsList.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectedChatsList.tsxnew file mode 100644index 000000000..6608414c0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectedChatsList.tsx@@ -0,0 +1,103 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { RelativeTime } from '@renderer/lib/ui/relative-time';+import { Spinner } from '@renderer/lib/ui/spinner';+import type { ConnectedChat } from '@shared/core/switch-servers/switch-servers';++/**+ * The chats under a connection whose chats are connected one at a time (the+ * Switch Telegram app). A Slack workspace or Discord server is a connection of+ * its own, and so a row of its own; these share one connection, so they are+ * listed under it.+ *+ * Anyone may disconnect one, not only an admin: a chat is a room, and rooms+ * are members'. The connection stays when the last one goes.+ */+export function ConnectedChatsList({+ workspaceId,+ bridgeId,+ platformLabel,+ onDisconnected,+}: {+ workspaceId: string;+ bridgeId: string;+ platformLabel: string;+ onDisconnected: () => void;+}) {+ const queryClient = useQueryClient();+ const showConfirm = useShowModal('confirmActionModal');+ const [disconnectingId, setDisconnectingId] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ const chatsQuery = useQuery({+ queryKey: ['connected-chats', workspaceId, bridgeId],+ queryFn: () => rpc.workspaces.listConnectedChats({ workspaceId, bridgeId }),+ });++ const disconnect = async (chat: ConnectedChat) => {+ setDisconnectingId(chat.id);+ setError(null);+ try {+ await rpc.workspaces.disconnectChat({ workspaceId, installId: chat.id });+ await queryClient.invalidateQueries({ queryKey: ['connected-chats', workspaceId] });+ onDisconnected();+ } catch (cause) {+ setError(failureText(cause, `Could not disconnect ${chatName(chat)}.`));+ } finally {+ setDisconnectingId(null);+ }+ };++ const confirmDisconnect = (chat: ConnectedChat) =>+ showConfirm({+ title: `Disconnect ${chatName(chat)}?`,+ description: `The bot leaves the chat. Its room stays in Switch, with nothing bridging it to ${platformLabel}.`,+ confirmLabel: 'Disconnect',+ onSuccess: () => void disconnect(chat),+ });++ const chats = chatsQuery.data ?? [];++ return (+ <div className="flex flex-col pb-1 pl-8">+ {chatsQuery.isLoading && <Spinner className="size-3.5" />}+ {chatsQuery.isError && (+ <p className="text-xs text-destructive">+ {failureText(chatsQuery.error, 'Could not load the chats connected here.')}+ </p>+ )}+ {chatsQuery.isSuccess && chats.length === 0 && (+ <p className="text-xs text-foreground-muted">No chats connected.</p>+ )}+ {chats.map((chat) => (+ <div key={chat.id} className="flex items-center gap-2 py-0.5 text-xs">+ <span+ className={`min-w-0 flex-1 truncate text-foreground ${chat.name === null ? 'font-mono' : ''}`}+ title={chat.externalId}+ >+ {chatName(chat)}+ </span>+ <RelativeTime value={chat.connectedAt} className="shrink-0 text-foreground-muted" />+ <Button+ variant="ghost"+ size="xs"+ className="shrink-0"+ disabled={disconnectingId !== null}+ onClick={() => confirmDisconnect(chat)}+ >+ {disconnectingId === chat.id ? 'Disconnecting…' : 'Disconnect'}+ </Button>+ </div>+ ))}+ {error !== null && <p className="text-xs text-destructive">{error}</p>}+ </div>+ );+}++function chatName(chat: ConnectedChat): string {+ return chat.name ?? chat.externalId;+}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 63807ac12..d495b5701 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@@ -8,13 +8,14 @@ import {MessageSquare,MoreVertical,Plus,+ PlusCircle,Trash2,TriangleAlert,Unlink,Users,} from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect, useMemo, useState } from 'react';+import { Fragment, useEffect, useMemo, useState } from 'react';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';@@ -38,6 +39,7 @@ import { Spinner } from '@renderer/lib/ui/spinner';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { log } from '@renderer/utils/logger';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';+import { ConnectedChatsList } from './ConnectedChatsList';import { orderBridges } from './messaging-apps-order';import {hasUnlinkedMessagingApp,@@ -94,6 +96,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const showConnectMessagingApp = useShowModal('connectMessagingAppModal');const showClaimIdentity = useShowModal('claimIdentityModal');const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');+ const showConnectChat = useShowModal('connectChatModal');const workspaceId = workspacesStore.idOnServerInScope(serverId);const isAdmin = administersWorkspaceInScope(serverId);// Only a stack Switch Console runs has a chat whose credentials it generated and@@ -108,6 +111,19 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const bridges = useMemo(() => orderBridges(bridgesQuery.data ?? []), [bridgesQuery.data]);+ // Which platforms the signed-in user may connect another chat on. Asked only+ // once there is a connection whose chats arrive that way, which also keeps+ // the question off servers that predate it.+ const hasClaimedChats = bridges.some((b) => b.channelIdsRefused !== null);+ const messagingAppsQuery = useQuery({+ queryKey: ['messaging-apps', workspaceId],+ queryFn: () => rpc.workspaces.listMessagingApps(workspaceId as string),+ enabled: workspaceId !== null && hasClaimedChats,+ });+ const chatPlatforms = new Set(+ (messagingAppsQuery.data?.claimable ?? []).filter((c) => c.canAddChat).map((c) => c.platform)+ );+const {identities,error: identitiesError,@@ -155,6 +171,14 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const [savingBridgeId, setSavingBridgeId] = useState<string | null>(null);const [toggleError, setToggleError] = useState<string | null>(null);+ // A chat connected from either dialog lands in the chat, on no signal+ // Switch Console receives, so the sidebar and the chat list are looked at+ // again when the dialog goes away rather than waited on.+ const refreshChats = () => {+ void switchRoomsStore.refreshRoomState();+ void queryClient.invalidateQueries({ queryKey: ['connected-chats', workspaceId] });+ };+const handleToggleChannelCreation = async (bridge: RemoteBridge, enabled: boolean) => {if (workspaceId === null) return;setSavingBridgeId(bridge.id);@@ -209,6 +233,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({onClick={() =>showConnectMessagingApp({serverId,+ onClosed: refreshChats,onSuccess: ({ bridgeId, displayName, directorySearchSupported }) => {// Refresh the bridge list everywhere it is consumed — this// card and the room-creation picker share the query key.@@ -287,46 +312,76 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({) : (<div className="mt-2 flex flex-col">{bridges.map((bridge) => (- <MessagingAppRow- key={bridge.id}- workspaceId={workspaceId}- serverId={serverId}- bridge={bridge}- /* Nothing is drawn in the identity column until the list+ <Fragment key={bridge.id}>+ <MessagingAppRow+ workspaceId={workspaceId}+ serverId={serverId}+ bridge={bridge}+ /* Nothing is drawn in the identity column until the listarrives: "not linked" and "not known yet" look identical,and offering to link an account the user already has is themore confusing of the two. */- identities={identities}- currentUserId={currentUserId}- onReleased={refreshIdentities}- showBundledSignIn={isManaged && bridge.type === 'mattermost'}- isAdmin={isAdmin}- savingChannelCreation={savingBridgeId === bridge.id}- onToggleChannelCreation={(enabled) =>- void handleToggleChannelCreation(bridge, enabled)- }- onDisconnect={() => {- if (workspaceId === null) return;- showDisconnectMessagingApp({- workspaceId,- bridgeId: bridge.id,- bridgeDisplayName: bridge.displayName,- bridgeType: bridge.type,- onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: ['remote-bridges', workspaceId],- });- // The rooms on that bridge went with it, so the sidebar- // is stale in a way the bridge list alone does not- // repair.- void switchRoomsStore.refreshRoomState();- },- });- }}- />+ identities={identities}+ currentUserId={currentUserId}+ onReleased={refreshIdentities}+ showBundledSignIn={isManaged && bridge.type === 'mattermost'}+ isAdmin={isAdmin}+ savingChannelCreation={savingBridgeId === bridge.id}+ onToggleChannelCreation={(enabled) =>+ void handleToggleChannelCreation(bridge, enabled)+ }+ onConnectChat={+ bridge.channelIdsRefused !== null &&+ chatPlatforms.has(bridge.type) &&+ workspaceId !== null+ ? () =>+ showConnectChat({+ workspaceId,+ platform: bridge.type,+ onClosed: refreshChats,+ })+ : null+ }+ onDisconnect={() => {+ if (workspaceId === null) return;+ showDisconnectMessagingApp({+ workspaceId,+ bridgeId: bridge.id,+ bridgeDisplayName: bridge.displayName,+ bridgeType: bridge.type,+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: ['remote-bridges', workspaceId],+ });+ // The rooms on that bridge went with it, so the sidebar+ // is stale in a way the bridge list alone does not+ // repair.+ void switchRoomsStore.refreshRoomState();+ },+ });+ }}+ />+ {bridge.channelIdsRefused !== null && workspaceId !== null && (+ <ConnectedChatsList+ workspaceId={workspaceId}+ bridgeId={bridge.id}+ platformLabel={bridgePlatformLabel(bridge.type)}+ // The chat's room stays but is bridged to nothing now.+ onDisconnected={() => void switchRoomsStore.refreshRoomState()}+ />+ )}+ </Fragment>))}</div>)}+ {messagingAppsQuery.isError && (+ <p className="mt-2 text-xs text-destructive">+ {failureText(+ messagingAppsQuery.error,+ 'Could not check whether you can add chats here, so adding one is not offered.'+ )}+ </p>+ )}{toggleError && <p className="mt-2 text-xs text-destructive">{toggleError}</p>}</div>);@@ -353,6 +408,7 @@ export function MessagingAppRow({isAdmin,savingChannelCreation,onToggleChannelCreation,+ onConnectChat,onDisconnect,}: {/** Null while this install has not resolved the server's workspace; the@@ -369,6 +425,9 @@ export function MessagingAppRow({isAdmin: boolean;savingChannelCreation: boolean;onToggleChannelCreation: (enabled: boolean) => void;+ /** Set on a connection whose chats are connected one at a time, for a user+ * the server lets add one — members too, unlike every other change here. */+ onConnectChat: (() => void) | null;onDisconnect: () => void;}) {const showClaimIdentity = useShowModal('claimIdentityModal');@@ -548,6 +607,16 @@ export function MessagingAppRow({</DropdownMenuItem>)}+ {onConnectChat !== null && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={onConnectChat}>+ <PlusCircle className="size-4" />+ Add to {platform}…+ </DropdownMenuItem>+ </>+ )}+<DropdownMenuSeparator />{/* "Off" and "this platform has no such thing" are different claims,and an unticked box makes them look the same (CHOO-2137). Adiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.test.tsindex 720f861db..f7c94b2d0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.test.ts@@ -41,4 +41,17 @@ describe('disconnectMessagingAppParagraphs', () => {expect(text).toContain('deletes every Switch room');}});++ it('says every Telegram chat goes, keeping its room, and then the connection', () => {+ const text = disconnectMessagingAppParagraphs({+ bridgeDisplayName: 'Telegram',+ bridgeType: 'telegram',+ installState: 'installed',+ }).join(' ');++ expect(text).toContain('Every chat connected through Telegram is disconnected');+ expect(text).toContain('internal-only');+ expect(text).toContain('connection itself is removed');+ expect(text).not.toContain('deletes every Switch room');+ });});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.tsindex 3220573e8..2927c3073 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.ts@@ -15,6 +15,10 @@ import type { BridgeInstallState } from '@shared/core/switch-servers/switch-serv* organisation and leaves its teams, while removing the app from the* organisation entirely stays a Microsoft admin's job.*+ * A Switch Telegram app connection holds many chats, each an install of its+ * own; disconnecting it ends every chat, keeping each chat's room, and then+ * removes the connection.+ ** Until the install state is known, the strongest warning is shown: saying* rooms are kept when they are about to be deleted is the mistake that cannot* be taken back.@@ -27,6 +31,12 @@ export function disconnectMessagingAppParagraphs(params: {const { bridgeDisplayName, bridgeType, installState } = params;if (installState === 'installed') {const kept = `The Switch rooms bridged to ${bridgeDisplayName} are not deleted — they become internal-only, reachable only from inside Switch.`;+ if (bridgeType === 'telegram') {+ return [+ `Every chat connected through ${bridgeDisplayName} is disconnected: the bot leaves each one, and each chat’s Switch room is kept as an internal-only room, reachable only from inside Switch. Then the connection itself is removed, which turns Telegram off for this workspace.`,+ 'To stop a single chat instead, disconnect it from the list of chats under this connection.',+ ];+ }if (bridgeType === 'teams') {return [`Switch stops listening in this Microsoft organisation and leaves every team it was added to. ${kept}`,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 4e0a4b765..019ee592b 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@@ -15,6 +15,7 @@ function bridge(id: string, displayName: string): RemoteBridge {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: 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 73f74e731..08083e14a 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@@ -21,6 +21,7 @@ function bridge(id: string, displayName: string): RemoteBridge {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: null,};}@@ -177,7 +178,7 @@ describe('what is said instead, where the link step is withheld', () => {expect(note).toContain('Telegram louis');// Be seen first, link second — the part that cannot be guessed.- expect(note).toContain('send a message');+ expect(note).toContain('Send a message in a connected group');expect(note).toContain('link your account');});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.tsindex 722e2f41e..f21d50eef 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts@@ -88,6 +88,9 @@ export function shouldOfferIdentityLinkOnConnect(app: {* never coming, and nothing says linking is still owed. This is the ordering* they cannot infer: be seen first, link second.*+ * Only a chat connected to Switch counts — the bot stores nothing it hears+ * anywhere else.+ ** Null where the directory can be searched, because there the ordinary flow* asks at the moment it is offering to act.*/@@ -96,5 +99,5 @@ export function identityLinkOrderingNote(app: {directorySearchSupported: boolean;}): string | null {if (app.directorySearchSupported) return null;- return `${app.displayName} has no directory of users to search, so Switch does not know you there yet. Add the bot to a chat and send a message in it — you can then link your account from this app’s menu, once you are someone Switch has seen.`;+ return `${app.displayName} has no directory of users to search, so Switch knows only people who have written in a chat connected to it. Send a message in a connected group, then link your account from this app’s menu.`;}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-on-unmount.ts b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-on-unmount.tsnew file mode 100644index 000000000..744b83156--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-on-unmount.ts@@ -0,0 +1,17 @@+import { useEffect, useRef } from 'react';++/**+ * Run `callback` when the component unmounts, with the latest one it was given.+ *+ * For work that has to happen however a component goes away. A registry+ * dialog is the case in point: the registry runs its `onClose` only for a+ * Close button the dialog draws, while X, Escape and a click outside close it+ * directly, and all four unmount it.+ */+export function useOnUnmount(callback: () => void): void {+ const latest = useRef(callback);+ useEffect(() => {+ latest.current = callback;+ });+ useEffect(() => () => latest.current(), []);+}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-messaging-app-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-messaging-app-modal.test.tsxindex 8f1be9d6e..6862f8387 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-messaging-app-modal.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-messaging-app-modal.test.tsx@@ -5,6 +5,9 @@* installing it — the consent screen opens in the browser and the dialog* watches for the connection it creates — and keeps the paste-your-tokens* form one click away. Where it has none, the form is all there is.+ *+ * A claim-based app (Telegram) is offered alongside: its link and code are+ * shown here, and a workspace's first chat is watched for like an install.*/import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { act } from 'react';@@ -12,8 +15,9 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const listBridgeTypes = vi.hoisted(() => vi.fn());-const listInstallablePlatforms = vi.hoisted(() => vi.fn());+const listMessagingApps = vi.hoisted(() => vi.fn());const beginMessagingAppInstall = vi.hoisted(() => vi.fn());+const beginChatClaim = vi.hoisted(() => vi.fn());const listBridges = vi.hoisted(() => vi.fn());const createBridge = vi.hoisted(() => vi.fn());const openExternalUrl = vi.hoisted(() => vi.fn());@@ -30,8 +34,9 @@ vi.mock('@renderer/lib/ipc', () => ({rpc: {workspaces: {listBridgeTypes,- listInstallablePlatforms,+ listMessagingApps,beginMessagingAppInstall,+ beginChatClaim,listBridges,createBridge,},@@ -77,8 +82,13 @@ beforeEach(() => {.mockResolvedValue([{ key: 'slack', fields: [], channelCreationSupported: true, directorySearchSupported: true },]);- listInstallablePlatforms.mockReset().mockResolvedValue(['slack']);+ listMessagingApps.mockReset().mockResolvedValue({ installable: ['slack'], claimable: [] });beginMessagingAppInstall.mockReset().mockResolvedValue('https://slack.example/oauth?state=s');+ beginChatClaim.mockReset().mockResolvedValue({+ url: 'https://t.me/example_bot?startgroup=abc',+ code: 'abc',+ botHandle: '@example_bot',+ });listBridges.mockReset().mockResolvedValue([bridge('b-old', 'slack')]);createBridge.mockReset();openExternalUrl.mockReset().mockResolvedValue(true);@@ -102,7 +112,7 @@ async function render(): Promise<HTMLElement> {root!.render(<QueryClientProvider client={client}><Dialog open onOpenChange={() => {}}>- <ConnectMessagingAppModal onSuccess={onSuccess} onClose={onClose} />+ <ConnectMessagingAppModal onSuccess={onSuccess} onClose={onClose} onClosed={() => {}} /></Dialog></QueryClientProvider>)@@ -203,7 +213,7 @@ describe('the connect-messaging-app dialog', () => {});it('shows only the token form when the server has no app of its own', async () => {- listInstallablePlatforms.mockResolvedValue([]);+ listMessagingApps.mockResolvedValue({ installable: [], claimable: [] });const el = await render();expect(el.textContent).toContain('Choose a platform');@@ -211,10 +221,111 @@ describe('the connect-messaging-app dialog', () => {});it('falls back to the token form, and says why, when the check fails', async () => {- listInstallablePlatforms.mockRejectedValue(new Error('boom'));+ listMessagingApps.mockRejectedValue(new Error('boom'));const el = await render();expect(el.textContent).toContain('Could not check which messaging apps');expect(el.textContent).toContain('Choose a platform');});});++describe('connecting a Telegram chat from the dialog', () => {+ function telegram(connected: boolean, canAddChat = true) {+ return {+ installable: [],+ claimable: [{ platform: 'telegram', connected, canAddChat }],+ };+ }++ it('is offered for a claim-based app, with no token form', async () => {+ listMessagingApps.mockResolvedValue(telegram(false));+ const el = await render();++ expect(findButton(el, 'Add to Telegram')).toBeDefined();+ expect(el.textContent).not.toContain('Choose a platform');+ });++ it('is not offered when the server says this user may not add a chat', async () => {+ listMessagingApps.mockResolvedValue(telegram(false, false));+ const el = await render();++ expect(findButton(el, 'Add to Telegram')).toBeUndefined();+ expect(el.textContent).toContain('Choose a platform');+ });++ it('shows the link, bot handle and command, and hands back the first chat’s connection', async () => {+ listMessagingApps.mockResolvedValue(telegram(false));+ const el = await render();+ listBridges+ .mockResolvedValueOnce([bridge('b-old', 'slack')])+ .mockResolvedValue([bridge('b-old', 'slack'), bridge('b-tg', 'telegram')]);++ await act(async () => button(el, 'Add to Telegram').click());+ await settle();++ expect(beginChatClaim).toHaveBeenCalledWith({ workspaceId: 'ws-1', platform: 'telegram' });+ expect(el.textContent).toContain('@example_bot');+ expect(el.textContent).toContain('/connect abc');+ expect(el.textContent).toContain('work once, for ten minutes');+ expect(onSuccess).toHaveBeenCalledWith({+ bridgeId: 'b-tg',+ displayName: 'telegram b-tg',+ directorySearchSupported: true,+ });+ });++ it('leaves only that chat on screen once its link is shown', async () => {+ listMessagingApps.mockResolvedValue({+ installable: ['slack'],+ claimable: [{ platform: 'telegram', connected: true, canAddChat: true }],+ });+ const el = await render();+ expect(findButton(el, 'Add to Slack')).toBeDefined();++ await act(async () => button(el, 'Add to Telegram').click());+ await settle();++ expect(findButton(el, 'Add to Slack')).toBeUndefined();+ expect(findButton(el, 'Use your own app instead')).toBeUndefined();+ expect(el.textContent).toContain('Add to Telegram');+ expect(findButton(el, 'Close')).toBeDefined();+ });++ it('opens the group link in the browser', async () => {+ listMessagingApps.mockResolvedValue(telegram(true));+ const el = await render();++ await act(async () => button(el, 'Add to Telegram').click());+ await settle();+ await act(async () => button(el, 'Add to a Telegram group').click());++ expect(openExternalUrl).toHaveBeenCalledWith(+ 'https://t.me/example_bot?startgroup=abc',+ 'Could not open Telegram'+ );+ });++ it('does not wait for a connection once the workspace has one', async () => {+ listMessagingApps.mockResolvedValue(telegram(true));+ const el = await render();++ await act(async () => button(el, 'Add to Telegram').click());+ await settle();++ expect(el.textContent).toContain('/connect abc');+ expect(listBridges).not.toHaveBeenCalled();+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it('says so when the claim could not be started', async () => {+ listMessagingApps.mockResolvedValue(telegram(true));+ beginChatClaim.mockRejectedValue(new Error('claim refused'));+ const el = await render();++ await act(async () => button(el, 'Add to Telegram').click());+ await settle();++ expect(el.textContent).toContain('Could not start connecting a Telegram chat');+ expect(findButton(el, 'Add to Telegram')).toBeDefined();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/connected-chats-list.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/connected-chats-list.test.tsxnew file mode 100644index 000000000..177a52fd5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/connected-chats-list.test.tsx@@ -0,0 +1,157 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ConnectedChat } from '@shared/core/switch-servers/switch-servers';++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++const state = vi.hoisted(() => ({+ chats: [] as ConnectedChat[],+ listConnectedChats: vi.fn(),+ disconnectChat: vi.fn(),+ confirmations: [] as { title: string; description: string; onSuccess: () => void }[],+}));++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ workspaces: {+ listConnectedChats: state.listConnectedChats,+ disconnectChat: state.disconnectChat,+ },+ },+}));++// The confirmation is the shared registry dialog; what matters here is what+// it is asked and what happens once it is confirmed.+vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useShowModal: () => (args: { title: string; description: string; onSuccess: () => void }) =>+ state.confirmations.push(args),+}));++/**+ * The chats under the Switch Telegram app's connection. A Slack workspace or a+ * Discord server is a connection of its own, and so a row of its own; these+ * share one connection, so they are listed under it, each with a way out.+ */+import { ConnectedChatsList } from '@renderer/features/switch-servers/ConnectedChatsList';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ state.chats = [+ { id: 'i-1', name: 'Ops', externalId: '-1001', connectedAt: '2026-09-01T10:00:00Z' },+ { id: 'i-2', name: null, externalId: '-1002', connectedAt: '2026-09-01T10:00:00Z' },+ ];+ state.confirmations = [];+ state.listConnectedChats.mockReset().mockImplementation(async () => state.chats);+ state.disconnectChat.mockReset().mockResolvedValue(undefined);+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function settle(): Promise<void> {+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());+}++async function render(onDisconnected: () => void = () => {}): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <ConnectedChatsList+ workspaceId="ws-1"+ bridgeId="b-tg"+ platformLabel="Telegram"+ onDisconnected={onDisconnected}+ />+ </QueryClientProvider>+ )+ );+ await settle();+ return container;+}++function disconnectButtons(el: HTMLElement): HTMLButtonElement[] {+ return [...el.querySelectorAll('button')].filter((b) => b.textContent?.trim() === 'Disconnect');+}++describe('the list', () => {+ it('names each chat, by its chat id when it has no name', async () => {+ const el = await render();++ expect(state.listConnectedChats).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ bridgeId: 'b-tg',+ });+ expect(el.textContent).toContain('Ops');+ expect(el.textContent).toContain('-1002');+ expect(disconnectButtons(el)).toHaveLength(2);+ });++ it('says so when no chat is connected', async () => {+ state.chats = [];++ const el = await render();++ expect(el.textContent).toContain('No chats connected.');+ });+});++describe('disconnecting', () => {+ it('asks first, saying the room stays', async () => {+ const el = await render();++ await act(async () => disconnectButtons(el)[0].click());++ expect(state.confirmations).toHaveLength(1);+ expect(state.confirmations[0].title).toBe('Disconnect Ops?');+ expect(state.confirmations[0].description).toContain('Its room stays in Switch');+ expect(state.disconnectChat).not.toHaveBeenCalled();+ });++ it('disconnects that chat once confirmed, and refreshes', async () => {+ const onDisconnected = vi.fn();+ const el = await render(onDisconnected);+ await act(async () => disconnectButtons(el)[0].click());+ state.chats = [state.chats[1]];++ await act(async () => state.confirmations[0].onSuccess());+ await settle();++ expect(state.disconnectChat).toHaveBeenCalledWith({ workspaceId: 'ws-1', installId: 'i-1' });+ expect(onDisconnected).toHaveBeenCalledOnce();+ expect(el.textContent).not.toContain('Ops');+ });++ it('says why when the server refuses', async () => {+ state.disconnectChat.mockRejectedValue(+ new Error('Telegram did not let the bot leave; disconnect again to retry.')+ );+ const onDisconnected = vi.fn();+ const el = await render(onDisconnected);+ await act(async () => disconnectButtons(el)[0].click());++ await act(async () => state.confirmations[0].onSuccess());+ await settle();++ expect(el.textContent).toContain('Could not disconnect Ops.');+ expect(el.textContent).toContain('Telegram did not let the bot leave');+ expect(onDisconnected).not.toHaveBeenCalled();+ });+});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 817e759a0..65234683a 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@@ -71,6 +71,7 @@ function bridge(patch: Partial<RemoteBridge> = {}): RemoteBridge {directorySearchSupported: true,attention: null,teamPlacementSupported: false,+ channelIdsRefused: null,...patch,};}@@ -90,6 +91,7 @@ function row(bridge?: RemoteBridge;identities?: LinkedIdentity[] | null;isAdmin?: boolean;+ onConnectChat?: (() => void) | null;onDisconnect?: () => void;} = {}) {@@ -105,6 +107,7 @@ function row(isAdmin={overrides.isAdmin ?? false}savingChannelCreation={false}onToggleChannelCreation={() => {}}+ onConnectChat={overrides.onConnectChat ?? null}onDisconnect={overrides.onDisconnect ?? (() => {})}/>);@@ -242,6 +245,26 @@ describe('the row menu', () => {expect(onDisconnect).toHaveBeenCalledTimes(1);});++ it('offers connecting a chat, to a member too, where the card allows it', async () => {+ const onConnectChat = vi.fn();+ const telegram = bridge({ id: 'b-tg', type: 'telegram', displayName: 'Telegram' });+ const el = await render(row({ bridge: telegram, isAdmin: false, onConnectChat }));+ expect(await openMenu(el)).toContain('Add to Telegram…');++ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (i) => i.textContent?.trim() === 'Add to Telegram…'+ );+ await act(async () => item!.click());++ expect(onConnectChat).toHaveBeenCalledTimes(1);+ });++ it('offers no chat to connect otherwise', async () => {+ const el = await render(row({ isAdmin: true }));++ expect(await openMenu(el)).not.toContain('Add to Slack…');+ });});/**diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex d627e927c..e7f406aed 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@@ -376,6 +376,61 @@ export type RemoteBridge = {* False for every other bridge, and for a server predating the field.*/teamPlacementSupported: boolean;+ /**+ * Why no existing chat can be bound to a room by its id on this connection,+ * or null when one can. The server sets it for a connection whose chats+ * arrive only by being connected with a link or code (the Switch Telegram+ * app), which is also what marks the connection that adding a chat adds to.+ * Null on a server predating the field.+ */+ channelIdsRefused: string | null;+};++/**+ * A platform whose chats are connected one at a time with a link or code from+ * Switch, rather than installed with a consent screen: the Switch Telegram+ * app. `canAddChat` is the server's answer for the signed-in user — an admin+ * connects a workspace's first chat, which creates its connection, and anyone+ * connects more after that.+ */+export type ClaimablePlatform = {+ platform: string;+ /** The workspace already has this platform's connection. */+ connected: boolean;+ canAddChat: boolean;+};++/** What the server's own messaging apps offer the signed-in user. */+export type MessagingApps = {+ /** Platforms installed with a consent screen. Empty for anyone but an admin. */+ installable: string[];+ claimable: ClaimablePlatform[];+};++/**+ * A one-time way to connect a chat: a link that adds the bot to a group and+ * connects it, the bare code a channel admin posts as `/connect <code>`, and+ * the bot's handle to search for when adding it to a channel. Both work once,+ * for ten minutes.+ */+export type ChatClaim = {+ url: string;+ code: string;+ botHandle: string;+};++/**+ * One chat connected to a claim-based connection. Each is a room, and any+ * member may disconnect one; the connection stays when its last chat goes.+ */+export type ConnectedChat = {+ /** The install's id, which is what disconnecting it names. */+ id: string;+ /** The chat's room name, or null when it has none. */+ name: string | null;+ /** The platform's id for the chat, shown when it has no name. */+ externalId: string;+ connectedAt: string;};/**diff --git a/core/pyproject.toml b/core/pyproject.tomlindex 63e3b4142..b1240c371 100644--- a/core/pyproject.toml+++ b/core/pyproject.toml@@ -92,6 +92,7 @@ markers = ["integration: boots real Postgres + Tuwunel via testcontainers (slow; excluded from the default run — use `just test-integration`)","benchmark: boots real Postgres and serves the agent bridge on a socket to measure it (slow, and reports numbers rather than asserting them; excluded from the default run — use `just bench`)","no_ambient_tenant: opt out of session_factory's default tenant-zero binding, for tests asserting what is or is not bound",+ "collaboration_bridges: build the integration harness with the real collaboration bridge lifecycle rather than the no-bridges stand-in",][tool.mypy]diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex b06394c63..e6a993415 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -1223,8 +1223,10 @@ class PlatformAdapter(ABC):than showing an empty picker that looks broken."""raise NotImplementedError(- f"{self.platform_name} has no searchable user directory — on this "- "platform someone must send a message before Switch knows them"+ f"{self.platform_name} has no searchable user directory, so this "+ "lists only people who have written in a chat connected to Switch. "+ "If you are not listed, send a message in a connected group, then "+ "search again")async def channel_deeplink(self, external_channel_id: str) -> str | None:@@ -1316,6 +1318,16 @@ class PlatformAdapter(ABC):"""return None+ def channel_ids_refused(self) -> str | None:+ """Why this bridge binds no existing channel by id at all, or None.++ For a bridge whose chats reach it only one way, so the dashboard can+ say so where a room is created rather than offer a choice that fails.+ Plain text, and the one wording: a bridge that answers here refuses+ with it too.+ """+ return None+@abstractmethodasync def get_channel_type(self, channel_id: str) -> ChannelType: ...diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.pyindex 47e7f04ce..c61643d31 100644--- a/core/switch_core/bridges/collaboration/install.py+++ b/core/switch_core/bridges/collaboration/install.py@@ -33,7 +33,7 @@ not registered an app cannot half-offer installs.from __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import Mapping+from collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclassfrom typing import Any, ClassVar, Literal@@ -98,6 +98,15 @@ class MessagingInstallError(RuntimeError):"""+class ClaimantMayNotConnect(RuntimeError):+ """The person who posted a claim may not connect the chat it was posted in.++ Holding a valid code says who in Switch asked; it says nothing about who+ may decide for the chat. A claim connects everything said there to a+ tenant, so the platform's own say over the chat has to agree as well.+ """++class WebhookAuthenticityError(RuntimeError):"""An inbound webhook did not prove it came from the platform.@@ -229,6 +238,82 @@ class InstallGrant:platform_data: Mapping[str, object]+@dataclass(frozen=True)+class InstallClaim:+ """A platform event that asks for its workspace to be installed.++ The counterpart of a completed OAuth callback for a platform that has none.+ Telegram cannot redirect a browser anywhere; what it can do is post the+ state it was handed into the chat the bot was just added to, so the+ install arrives as an ordinary webhook event instead of a callback.++ `grant` is what that event amounts to, in the shape the rest of the install+ already takes. `workspace_name` names the bridge when this claim is the one+ that creates it, so for a platform whose bridge serves many workspaces it+ should name the connection rather than the one chat that happened to come+ first.++ `claimant` is the platform's id for whoever posted the claim, which is what+ `require_claimant_may_connect` asks the platform about. A message posted as+ the chat itself (a channel's post, an anonymous group admin's) names the+ chat.+ """++ token: str+ grant: InstallGrant+ claimant: str+++#: Why a claim was refused, as a person trying to connect a chat needs to hear+#: it. `expired` covers a link already used too: the store cannot tell the two+#: apart, and neither is fixed differently — both want a fresh link.+ClaimRefusal = Literal[+ "expired", "unrecognised", "already_connected", "not_permitted", "not_chat_admin"+]+++@dataclass(frozen=True)+class ClaimProposal:+ """What a claim would connect its chat to, for the chat's admins to check.++ The claim-based counterpart of OAuth's confirmation page. A link can be+ forwarded to anyone, so whoever used it may not be whoever asked for it,+ and nothing is connected until an admin of the chat has seen which Switch+ organisation it is for and chosen Connect. `requested_by` is a name, not+ the email the page shows: everyone in the chat sees this.+ """++ organisation: str+ requested_by: str+++ClaimDecision = Literal["connect", "cancel"]+++@dataclass(frozen=True)+class ClaimAnswer:+ """An answer to a proposal, from the chat it was posted in.++ `claim.claimant` is whoever answered, which is who must be an admin of the+ chat. `press` is the platform's own record of the answer, handed back to+ the installer to close it.+ """++ claim: InstallClaim+ decision: ClaimDecision+ press: Mapping[str, object]+++#: How an answer ended: connected, cancelled, or refused for a claim's reason.+ClaimOutcome = Literal["connected", "cancelled"] | ClaimRefusal+++#: Which state token an installer's platform can carry. `v1` for a platform+#: that hands the state back through a redirect; `compact` for one whose only+#: carrier is short (see `install_state`).+StateFormat = Literal["v1", "compact"]++class MessagingAppInstaller(ABC):"""The install half of one platform, holding that platform's app credentials.@@ -249,6 +334,24 @@ class MessagingAppInstaller(ABC):#: and its webhook URLs simply do not exist.webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]]+ state_format: ClassVar[StateFormat] = "v1"++ #: Whether a workspace is installed by a claim posted in it rather than by+ #: an OAuth round trip. A claim-based platform shares one bridge per tenant+ #: across every chat claimed, so one chat is a room rather than a+ #: connection: after an admin connects the first, members may connect and+ #: disconnect chats. The bridge outlives its chats, and only an admin+ #: removes it, by deleting it.+ installs_by_claim: ClassVar[bool] = False++ #: Whether events from workspaces nobody has installed are routine here.+ #: Off for a platform whose app is only ever in workspaces that installed+ #: it, so such an event is worth a warning each time. On for one whose app+ #: can sit in chats nobody claimed and hear everything said there, where a+ #: warning per event would bury the drops that are real losses; those are+ #: counted instead.+ expects_unowned_events: ClassVar[bool] = False+@abstractmethoddef authorize_url(self, *, state: str, redirect_uri: str) -> str:"""Where to send the browser to begin an install.@@ -418,7 +521,9 @@ class MessagingAppInstaller(ABC):The counterpart of `revoke` for a platform with no per-install token,called only when the install's bridge is not running to do it itself- (`PlatformAdapter.withdraw`). A no-op where there is nothing on+ (`PlatformAdapter.withdraw`) — or, for a platform that `installs_by_claim`,+ always, since its bridge serves the tenant's other workspaces and is not+ removed with this one. A no-op where there is nothing onthe platform to undo. Best effort: raise `MessagingInstallError` tosay what was left behind, and the disconnect is refused so it can betried again.@@ -435,6 +540,130 @@ class MessagingAppInstaller(ABC):"""return f"{self.platform} reported: {error}."+ def claim_of_event(self, payload: Mapping[str, object]) -> InstallClaim | None:+ """The install this event asks for, or `None` if it asks for none.++ Only a platform with no OAuth leg overrides this; for the rest an+ install arrives at the callback and never as an event. A claim+ installs nothing by itself: it is proposed to the chat, and an admin's+ answer (:meth:`answer_of_event`) is what connects it.++ Asked before the event is resolved, because the workspace it names is+ by definition not installed yet and resolving it would drop the one+ event that could change that. Pure, like :meth:`workspace_of_event`:+ the token is verified and redeemed by the install service, not here.+ """+ return None++ def answer_of_event(self, payload: Mapping[str, object]) -> ClaimAnswer | None:+ """The answer this event gives to a proposal, or `None` if it is none.++ Pure, like :meth:`claim_of_event`, and asked before the event is+ resolved for the same reason.+ """+ return None++ async def require_claimant_may_connect(self, claim: InstallClaim) -> None:+ """Refuse a claim posted by someone who may not decide for its chat.++ Asked before the claim's code is spent, so a refused attempt leaves it+ for someone who may. Raise :class:`ClaimantMayNotConnect` to refuse,+ and :class:`MessagingInstallError` when the platform could not be+ asked, which the platform retries. A no-op for a platform that installs+ by OAuth, whose own consent screen already asked.+ """+ return None++ def migration_of_event(+ self, payload: Mapping[str, object]+ ) -> tuple[str, str] | None:+ """`(old id, new id)` if this event says its workspace changed id.++ Telegram reissues a chat's id when a group becomes a supergroup. The+ install row is keyed by that id and has to follow it, or the chat's+ events stop resolving to anyone. Pure, like `workspace_of_event`,+ which for such an event answers the *old* id so it still resolves.+ """+ return None++ async def on_claim_proposed(+ self, *, claim: InstallClaim, proposal: ClaimProposal+ ) -> None:+ """Ask the chat a claim came from whether to connect it.++ Runs after the platform has been answered. A claim-based platform must+ override this, since without it nobody is asked and nothing connects.+ """+ raise MessagingInstallError(+ f"{self.platform} is not installed by claiming a chat, so there is "+ "no chat to ask"+ )++ async def on_claim_answered(+ self, *, answer: ClaimAnswer, outcome: ClaimOutcome+ ) -> None:+ """Close an answer: say how it ended, where it was given.++ Runs after the platform has been answered. Must say nothing about+ which tenant holds a chat that is already connected.+ """+ return None++ async def on_claim_refused(+ self, *, claim: InstallClaim, reason: ClaimRefusal+ ) -> None:+ """Tell the chat a claim came from why it was not connected.++ Runs after the platform has been answered. Without it the person who+ tapped the link sees nothing happen, which reads as Switch being broken+ rather than as a link that ran out. Must say nothing about which tenant+ holds a chat that is already connected.+ """+ return None++ async def on_unowned_event(+ self,+ *,+ workspace_id: str,+ payload: Mapping[str, object],+ still_unowned: Callable[[], Awaitable[bool]],+ ) -> None:+ """React to an authentic event from a workspace nobody holds.++ Runs after the platform has been answered. Nothing about the event may+ be stored; what a platform may do is say something back in the chat —+ how to connect it, or that a direct message reaches no one.+ `still_unowned` re-asks, for a reply worth delaying until a claim that+ may be in flight has had its chance.+ """+ return None++ def bot_handle(self) -> str:+ """The name a person searches for to add the bot to a chat by hand.++ Shown beside the claim link, for a chat the link cannot reach. Only a+ claim-based platform is asked; any other has no bot to add by hand.+ """+ raise MessagingInstallError(+ f"{self.platform} is not installed by claiming a chat, so it has no "+ "bot to add by hand"+ )++ def shared_connection(self) -> object | None:+ """The deployment-level connection this platform's bridges run on, if any.++ `None` for a platform whose bridges each hold their own credential.+ A platform with one app-wide bot returns what its bridges attach to,+ and the install service hands it to a bridge the first time it+ delivers that bridge an event — which is how a bridge registered after+ boot gets one.++ Raise :class:`MessagingInstallError` if it exists but cannot be used+ yet; the event is then refused as retryable rather than delivered to a+ bridge that could not act on it.+ """+ return None+@abstractmethoddef connection_config(self, grant: InstallGrant) -> dict[str, object]:"""Render a grant as the connection config this platform's adapter takes.diff --git a/core/switch_core/bridges/collaboration/install_routes.py b/core/switch_core/bridges/collaboration/install_routes.pyindex 0664b48fe..0f659316e 100644--- a/core/switch_core/bridges/collaboration/install_routes.py+++ b/core/switch_core/bridges/collaboration/install_routes.py@@ -36,7 +36,13 @@ from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponsefrom switch_core.bridges.collaboration.install import (PUBLIC_PATH_PREFIX,+ ClaimAnswer,+ ClaimantMayNotConnect,+ ClaimOutcome,+ ClaimProposal,+ ClaimRefusal,InboundWebhook,+ InstallClaim,MessagingInstallError,WebhookAuthenticityError,WebhookEndpoint,@@ -48,6 +54,8 @@ from switch_core.bridges.collaboration.install_confirmation import (InstallTicketError,)from switch_core.bridges.collaboration.install_service import (+ InstallClaimNotPermitted,+ InstallClaimRepeated,InstallPlatformMismatch,MessagingInstallService,PendingInstall,@@ -55,12 +63,15 @@ from switch_core.bridges.collaboration.install_service import (WebhookBridgeUnavailable,WebhookTarget,WebhookWorkspaceUnknown,+ WebhookWorkspaceUnowned,)from switch_core.bridges.collaboration.install_state import InstallStateErrorfrom switch_core.db.stores.messaging_install_store import (MessagingInstallClaimedError,MessagingInstallStateError,)+from switch_core.observability.catalogue import MESSAGING_EVENTS_IGNORED+from switch_core.observability.metrics import metricslogger = logging.getLogger(__name__)@@ -339,6 +350,152 @@ def create_messaging_install_router(target.tenant_id,)+ async def _propose(+ platform: str, claim: InstallClaim, background: BackgroundTasks+ ) -> None:+ """Ask the chat a claim came from whether to connect it, or say why not.++ A claim connects nothing by itself, and a refused claim is not a+ refused event. The event is resolved next either way, and that is right+ in every case: a claim posted in a chat this tenant already holds+ reaches it as any message does; a chat another tenant holds resolves to+ them, exactly as it would have without the claim; and one nobody holds+ is dropped as any unowned workspace is.++ Asking and saying why are the installer's, after the platform has been+ answered. A claim in a chat its own tenant already holds is not a+ refusal and says nothing.+ """+ reason: ClaimRefusal+ refusal: Exception+ try:+ proposal = await service.propose(platform=platform, claim=claim)+ except InstallClaimRepeated as repeated:+ logger.info("Ignored a %s claim: %s", platform, repeated)+ return+ except InstallStateError as failure:+ reason, refusal = "unrecognised", failure+ except MessagingInstallStateError as failure:+ reason, refusal = "expired", failure+ except MessagingInstallClaimedError as failure:+ reason, refusal = "already_connected", failure+ except InstallClaimNotPermitted as failure:+ reason, refusal = "not_permitted", failure+ except ClaimantMayNotConnect as failure:+ reason, refusal = "not_chat_admin", failure+ else:+ background.add_task(_proposed, platform, claim, proposal)+ return+ logger.warning(+ "Refused a claim of %s workspace %s: %s",+ platform,+ claim.grant.external_workspace_id,+ refusal,+ )+ background.add_task(_claim_refused, platform, claim, reason)++ async def _answer_claim(+ platform: str, answer: ClaimAnswer, background: BackgroundTasks+ ) -> bool:+ """Connect or decline what an admin of the chat answered; True if connected.++ Whoever answered must be an admin of the chat, and the answer must+ come from the chat the claim was put to; the state, burnt when it was+ put, is decided once. An answer repeated after it connected the chat+ is the platform retrying, and is closed as connected again rather than+ refused.+ """+ outcome: ClaimOutcome+ refusal: Exception | None = None+ try:+ if answer.decision == "connect":+ await service.connect(platform=platform, claim=answer.claim)+ outcome = "connected"+ else:+ await service.decline(platform=platform, claim=answer.claim)+ outcome = "cancelled"+ except InstallClaimRepeated as repeated:+ logger.info("Ignored a repeated %s answer: %s", platform, repeated)+ outcome = "connected"+ except InstallStateError as failure:+ outcome, refusal = "unrecognised", failure+ except MessagingInstallStateError as failure:+ outcome, refusal = "expired", failure+ except MessagingInstallClaimedError as failure:+ outcome, refusal = "already_connected", failure+ except InstallClaimNotPermitted as failure:+ outcome, refusal = "not_permitted", failure+ except ClaimantMayNotConnect as failure:+ outcome, refusal = "not_chat_admin", failure+ if refusal is not None:+ logger.warning(+ "Refused an answer to a claim of %s workspace %s: %s",+ platform,+ answer.claim.grant.external_workspace_id,+ refusal,+ )+ background.add_task(_answered, platform, answer, outcome)+ return outcome == "connected"++ async def _proposed(+ platform: str, claim: InstallClaim, proposal: ClaimProposal+ ) -> None:+ """Let the installer ask the chat; logged, never raised."""+ try:+ await service.installer(platform).on_claim_proposed(+ claim=claim, proposal=proposal+ )+ except Exception:+ logger.exception(+ "Failed to ask %s workspace %s to confirm its claim",+ platform,+ claim.grant.external_workspace_id,+ )++ async def _answered(+ platform: str, answer: ClaimAnswer, outcome: ClaimOutcome+ ) -> None:+ """Let the installer close an answer; logged, never raised."""+ try:+ await service.installer(platform).on_claim_answered(+ answer=answer, outcome=outcome+ )+ except Exception:+ logger.exception(+ "Failed to tell %s workspace %s how its answer ended (%s)",+ platform,+ answer.claim.grant.external_workspace_id,+ outcome,+ )++ async def _claim_refused(+ platform: str, claim: InstallClaim, reason: ClaimRefusal+ ) -> None:+ """Let the installer explain a refused claim; logged, never raised."""+ try:+ await service.installer(platform).on_claim_refused(+ claim=claim, reason=reason+ )+ except Exception:+ logger.exception(+ "Failed to tell %s workspace %s why its claim was refused",+ platform,+ claim.grant.external_workspace_id,+ )++ async def _unowned(platform: str, workspace_id: str, event: InboundWebhook) -> None:+ """Let the installer answer an unowned event; logged, never raised."""+ try:+ await service.unowned(+ platform=platform, workspace_id=workspace_id, event=event+ )+ except Exception:+ logger.exception(+ "Failed to answer a %s event from unowned workspace %s",+ platform,+ workspace_id,+ )+async def _end_install(platform: str, revocation: Revocation) -> None:"""Act on the platform's news after it has been acknowledged.@@ -476,11 +633,20 @@ def create_messaging_install_router(# each lookup is two database reads before the platform is answered.resolved: dict[str, WebhookTarget | Exception] = {}- async def resolve(event: InboundWebhook) -> WebhookTarget:+ async def resolve(+ event: InboundWebhook, *, wait_for_start: bool+ ) -> WebhookTarget:workspace_id = service.workspace_of(platform=platform, event=event)- if workspace_id not in resolved:+ # Waiting looks again whatever is cached: it is asked for by an+ # event that may itself have just installed the workspace.+ if wait_for_start or workspace_id not in resolved:+ lookup = (+ service.resolve_started+ if wait_for_start+ else service.resolve_by_workspace+ )try:- resolved[workspace_id] = await service.resolve_by_workspace(+ resolved[workspace_id] = await lookup(platform=platform, workspace_id=workspace_id)except (WebhookWorkspaceUnknown, WebhookBridgeUnavailable) as failure:@@ -515,7 +681,28 @@ def create_messaging_install_router(handled += 1continue- target = await resolve(event)+ # Before resolving too: the workspace a claim names is not+ # installed yet. Checked before answering, so a refusal+ # Telegram could not be asked about is retried rather than+ # lost.+ claim = service.claim_of(platform=platform, event=event)+ if claim is not None:+ await _propose(platform, claim, background)++ # An answer is the install's, and goes on to be delivered only+ # when it connected its chat: then it is the event that creates+ # the room.+ answer = service.answer_of(platform=platform, event=event)+ if answer is not None and not await _answer_claim(+ platform, answer, background+ ):+ handled += 1+ continue++ target = await resolve(event, wait_for_start=answer is not None)+ await service.follow_migration(+ platform=platform, event=event, target=target+ )except WebhookPayloadError as failure:# Skipped rather than answered: on an endpoint every workspace# shares, one unreadable item in a batch must not take the rest@@ -525,6 +712,22 @@ def create_messaging_install_router()unreadable += 1continue+ except WebhookWorkspaceUnowned as failure:+ # A 200, for the reason given below. Where the app routinely+ # sits in chats nobody claimed, a warning per event would bury+ # the drops that are real losses, so those are counted instead+ # and each real loss is reported where its cause is known.+ if service.note_unowned(+ platform=platform, workspace_id=failure.workspace_id+ ):+ metrics().increment(+ MESSAGING_EVENTS_IGNORED,+ {"platform": platform, "reason": "unowned"},+ )+ else:+ logger.warning("Dropped a %s event: %s", platform, failure)+ background.add_task(_unowned, platform, failure.workspace_id, event)+ continueexcept WebhookWorkspaceUnknown as failure:# A 200 for an event that reached nobody, which is the one place# this file answers something other than what happened. The app@@ -535,6 +738,14 @@ def create_messaging_install_router(# visible.logger.warning("Dropped a %s event: %s", platform, failure)continue+ except MessagingInstallError as failure:+ # The installer cannot read this event yet — Telegram's, before+ # its bot has said who it is. Transient, so counted with the+ # undeliverable: the platform retries a request nothing in+ # which was delivered.+ logger.error("Could not read a %s event yet: %s", platform, failure)+ unavailable += 1+ continueexcept WebhookBridgeUnavailable as failure:logger.error("Could not deliver a %s event: %s", platform, failure)unavailable += 1diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.pyindex 3e967f7b4..dbd990040 100644--- a/core/switch_core/bridges/collaboration/install_service.py+++ b/core/switch_core/bridges/collaboration/install_service.py@@ -56,16 +56,26 @@ workspace it has already been thrown out of.from __future__ import annotations+import asyncioimport logging+import time+from collections import OrderedDictfrom collections.abc import Mappingfrom dataclasses import dataclass-from typing import Any+from typing import Any, Protocol+from sqlalchemy import textfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.adapter import (+ PlatformAdapter,+ SupportsSharedConnection,+)from switch_core.bridges.collaboration.install import (+ ClaimAnswer,+ ClaimProposal,InboundWebhook,+ InstallClaim,InstallGrant,MessagingAppInstaller,MessagingInstallerRegistry,@@ -83,7 +93,9 @@ from switch_core.bridges.collaboration.install_confirmation import (from switch_core.bridges.collaboration.install_state import (InstallState,mint,+ mint_compact,verify,+ verify_compact,)from switch_core.bridges.collaboration.lifecycle_service import (BridgeClaimConflict,@@ -94,7 +106,13 @@ from switch_core.bridges.collaboration.models import (BridgeStartRefused,)from switch_core.db.audit import AuditAction, record_audit_event-from switch_core.db.models import MessagingInstall, Tenant, User+from switch_core.db.models import (+ MessagingInstall,+ MessagingInstallState,+ Room,+ Tenant,+ User,+)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.messaging_event_store import MessagingEventReceiptStorefrom switch_core.db.stores.messaging_install_store import (@@ -102,8 +120,10 @@ from switch_core.db.stores.messaging_install_store import (INSTALL_DISCONNECTED,INSTALL_REVOKED,MessagingInstallClaimedError,+ MessagingInstallStateError,MessagingInstallStore,)+from switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import tenant_of_messaging_installfrom switch_core.keys import Keyringfrom switch_core.tenant_context import no_tenant, tenant_scope@@ -123,6 +143,41 @@ class WebhookWorkspaceUnknown(RuntimeError):"""+class WebhookWorkspaceUnowned(WebhookWorkspaceUnknown):+ """No tenant holds the workspace at all — the routine case of the two.++ Split from the scoped re-read missing, which is a lookup disagreeing with+ itself and always worth a warning. This one is an app sitting in a+ workspace nobody installed it into, which on some platforms is most of+ what it hears.+ """++ def __init__(self, message: str, *, workspace_id: str) -> None:+ super().__init__(message)+ self.workspace_id = workspace_id+++class RoomDetacher(Protocol):+ """Detaches the one room a bridge holds for a workspace that is leaving it."""++ async def unlink_bridge_channel(+ self, bridge_id: str, external_channel_id: str+ ) -> None: ...+++#: How long an unowned workspace's drops are remembered, and how many+#: workspaces at most. Long enough to span a migration's two notices; bounded+#: because an app sitting in unclaimed chats sees an open-ended set of them.+_RECENT_DROP_TTL = 300.0+_RECENT_DROPS_MAX = 1000++#: How long an event carrying a claim waits for its bridge to start before the+#: platform is told to retry. The claim is the event that provisions the chat's+#: room, and a bridge still starting has nothing to provision it with.+_BRIDGE_START_WAIT = 2.0+_BRIDGE_START_POLL = 0.05++class WebhookBridgeUnavailable(RuntimeError):"""The workspace resolves to a tenant, and nothing is running to take it.@@ -140,6 +195,21 @@ class Revocation:reason: str+@dataclass(frozen=True)+class ClaimLink:+ """What a person needs to claim a chat: the link, and the bare code.++ The link adds the bot to a group and claims it in one step. A channel has+ no such link — Telegram carries no state when a bot is added to one — so+ the code is posted there by hand, as `/connect <code>`, after adding the+ bot by its handle.+ """++ url: str+ code: str+ bot_handle: str++@dataclass(frozen=True)class WebhookTarget:"""Where one verified event goes: a tenant, a bridge, and its live adapter.@@ -182,6 +252,27 @@ class InstallPlatformMismatch(RuntimeError):"""+class InstallClaimNotPermitted(RuntimeError):+ """The person who minted a claim may not make the install it would make.++ Connecting a further chat to a tenant's existing connection is a member's+ action — a chat is a room, and rooms are members' — but the first claim+ creates the connection itself, which is an admin's. Checked when the claim+ is redeemed and not only when it was minted, because whether a connection+ exists can change in the ten minutes between the two.+ """+++class InstallClaimRepeated(RuntimeError):+ """A claim arrived again after it had already connected its workspace.++ The platform re-sends an event it thinks went unanswered, and the retried+ claim finds its state burnt. Told apart from a claim that genuinely came+ too late, because answering a retry with "that link has expired" in a chat+ it has just connected would be telling the person something false.+ """++class MessagingInstallService:def __init__(self,@@ -191,16 +282,32 @@ class MessagingInstallService:receipts: MessagingEventReceiptStore,installers: MessagingInstallerRegistry,lifecycle: CollaborationBridgeLifecycleService,+ # Defaulted because only a claim-based platform asks either: who may+ # turn it on, and which room a chat that leaves takes with it. A+ # deployment, or a test, with none of those platforms passes neither.+ users: UserStore = UserStore(),+ rooms: RoomDetacher | None = None,public_origin: str,keyring: Keyring,) -> None:self._session_factory = session_factoryself._store = store+ self._users = users+ self._rooms = rooms+ # (platform, workspace id) -> (events dropped, when the last was), in+ # order of that last drop. Ids and counts only: nothing an unowned+ # workspace said is kept.+ self._recent_drops: OrderedDict[tuple[str, str], tuple[int, float]] = (+ OrderedDict()+ )self._receipts = receiptsself._installers = installersself._lifecycle = lifecycleself._public_origin = public_originself._keyring = keyring+ # Burnt claim states awaiting an answer: state id -> (chat, when). See+ # `propose`.+ self._proposals: dict[str, tuple[str, float]] = {}def _redirect_uri(self, platform: str) -> str:"""Where the platform sends the browser back to.@@ -226,20 +333,56 @@ class MessagingInstallService:tenant they are authenticated for and there is no parameter throughwhich they could name another."""+ installer = self._installers.get(platform)+ token = await self._mint_state(session, platform=platform, user_id=user_id)+ return installer.authorize_url(+ state=token, redirect_uri=self._redirect_uri(platform)+ )++ async def begin_claim(+ self, session: AsyncSession, *, platform: str, user_id: str+ ) -> ClaimLink:+ """`begin`, for a platform installed by claim: the link and its code."""+ installer = self._installers.get(platform)+ token = await self._mint_state(session, platform=platform, user_id=user_id)+ return ClaimLink(+ url=installer.authorize_url(+ state=token, redirect_uri=self._redirect_uri(platform)+ ),+ code=token,+ bot_handle=installer.bot_handle(),+ )++ async def _mint_state(+ self, session: AsyncSession, *, platform: str, user_id: str+ ) -> str:installer = self._installers.get(platform)state = await self._store.start_install(session, platform=platform, user_id=user_id)- token = mint(- InstallState(- tenant_id=state.tenant_id, state_id=state.id, platform=platform- ),- keyring=self._keyring,+ signed = InstallState(+ tenant_id=state.tenant_id, state_id=state.id, platform=platform)- return installer.authorize_url(- state=token, redirect_uri=self._redirect_uri(platform)+ if installer.state_format == "compact":+ return mint_compact(signed, keyring=self._keyring)+ return mint(signed, keyring=self._keyring)++ async def platform_connected(self, session: AsyncSession, *, platform: str) -> bool:+ """Whether the bound tenant already has a bridge for a claim-based platform.++ The line between an admin's action and a member's: connecting a chat+ while there is none creates the tenant's connection; every other chat+ is a room.+ """+ return (+ await self._store.bridge_for_platform(session, platform=platform)+ is not None)+ async def install_platform(self, session: AsyncSession, *, install_id: str) -> str:+ """Which platform one of the bound tenant's installs belongs to, or raise."""+ return (await self._store.get(session, install_id=install_id)).platform+async def complete(self, *, platform: str, code: str, state_token: str) -> PendingInstall:@@ -258,13 +401,7 @@ class MessagingInstallService:)with tenant_scope(state.tenant_id):- async with tenant_session(- self._session_factory, state.tenant_id- ) as session:- burnt = await self._store.redeem_state(- session, state_id=state.state_id, platform=platform- )- await session.commit()+ burnt = await self._burn(state)grant = await installer.redeem(code=code, redirect_uri=self._redirect_uri(platform)@@ -359,14 +496,7 @@ class MessagingInstallService:session,platform=platform,external_workspace_id=grant.external_workspace_id,- # A grant with no token is a platform whose credential is- # deployment-level (Discord), not per-install; there is- # nothing to encrypt and the column is nullable for it.- encrypted_bot_token=(- self._keyring.encrypt(grant.bot_token)- if grant.bot_token is not None- else None- ),+ encrypted_bot_token=self._encrypted_token(grant),scopes=grant.scopes,platform_data=grant.platform_data,user_id=decided.created_by_user_id,@@ -613,6 +743,318 @@ class MessagingInstallService:"only what it was installed into.")+ async def propose(self, *, platform: str, claim: InstallClaim) -> ClaimProposal:+ """Spend a claim's state on asking its chat, and say what it would connect.++ The claim-based counterpart of `complete`: verify, then burn the state+ and commit before anything else, so a code seen in the chat — in the+ claim itself, or behind the proposal's buttons — is dead from here on.+ The burnt state is then held for this one chat, and only an answer from+ it can decide it (see `connect`). Held in memory: the app runs on one+ pod, and a restart costs an unanswered proposal, whose answer is then+ refused as expired.++ Everything `connect` would refuse is refused here first, so a chat is+ only asked about a claim that can still succeed.+ """+ installer = self._installers.get(platform)+ state = verify_compact(claim.token, platform=platform, keyring=self._keyring)+ await installer.require_claimant_may_connect(claim)+ chat_id = claim.grant.external_workspace_id++ with tenant_scope(state.tenant_id):+ holder = await tenant_of_messaging_install(+ self._session_factory, platform, chat_id+ )+ if holder == state.tenant_id:+ raise InstallClaimRepeated(+ f"the {platform} workspace {chat_id} is already connected to "+ "this organisation"+ )+ if holder is not None:+ raise MessagingInstallClaimedError(+ f"the {platform} workspace {chat_id} is already connected to Switch"+ )+ try:+ burnt = await self._burn(state)+ except MessagingInstallStateError:+ if self._proposed_chat(state.state_id) == chat_id:+ raise InstallClaimRepeated(+ f"the {platform} workspace {chat_id} was already asked "+ "about this claim"+ ) from None+ raise+ self._proposals[state.state_id] = (chat_id, time.monotonic())++ async with tenant_session(+ self._session_factory, state.tenant_id+ ) as session:+ if (+ await self._store.bridge_for_platform(session, platform=platform)+ is None+ ):+ await self._require_admin(session, burnt, platform)+ tenant = await session.get(Tenant, state.tenant_id)+ requester = await session.get(User, burnt.created_by_user_id)+ if tenant is None or requester is None:+ raise RuntimeError(+ f"install state {state.state_id} names a tenant or user "+ "that no longer exists"+ )+ return ClaimProposal(+ organisation=tenant.name, requested_by=requester.name+ )++ async def decline(self, *, platform: str, claim: InstallClaim) -> None:+ """An admin of the chat chose Cancel: decide the state, connect nothing."""+ installer = self._installers.get(platform)+ state = verify_compact(claim.token, platform=platform, keyring=self._keyring)+ with tenant_scope(state.tenant_id):+ await self._decide(installer, state, claim)+ logger.info(+ "Declined a %s claim of workspace %s for tenant %s",+ platform,+ claim.grant.external_workspace_id,+ state.tenant_id,+ )++ async def connect(self, *, platform: str, claim: InstallClaim) -> MessagingInstall:+ """An admin of the chat chose Connect: install the workspace it names.++ The counterpart of `confirm`. There is no code to exchange — the event+ is the grant — and what differs after that is the bridge.++ **A claim-based platform shares one bridge per tenant.** Identities are+ held per bridge, so a bridge per chat would have every person link+ themselves again in every chat. The first chat registers the bridge+ and each later one attaches to it.++ That makes the first connection a race: two landing together would each+ find no bridge and each register one. So the lookup, the insert, the+ registration and the attachment happen inside one transaction holding+ an advisory lock on the tenant and platform, and a second one waits+ and then finds the bridge the first one made. Holding the transaction+ across registration has a second benefit: a registration that fails+ rolls the install back with it, rather than leaving a workspace claimed+ by a tenant with no bridge to deliver its events to.+ """+ installer = self._installers.get(platform)+ state = verify_compact(claim.token, platform=platform, keyring=self._keyring)+ chat_id = claim.grant.external_workspace_id++ with tenant_scope(state.tenant_id):+ if (+ await tenant_of_messaging_install(+ self._session_factory, platform, chat_id+ )+ == state.tenant_id+ ):+ raise InstallClaimRepeated(+ f"the {platform} workspace {chat_id} was already connected by "+ "this claim"+ )+ decided = await self._decide(installer, state, claim)++ async with tenant_session(+ self._session_factory, state.tenant_id+ ) as session:+ await self._lock_platform(session, state.tenant_id, platform)+ bridge_id = await self._store.bridge_for_platform(+ session, platform=platform+ )+ if bridge_id is None:+ await self._require_admin(session, decided, platform)++ install = await self._store.record_install(+ session,+ platform=platform,+ external_workspace_id=chat_id,+ encrypted_bot_token=self._encrypted_token(claim.grant),+ scopes=claim.grant.scopes,+ platform_data=claim.grant.platform_data,+ user_id=decided.created_by_user_id,+ )++ if bridge_id is None:+ bridge = await self._lifecycle.register(+ bridge_type=platform,+ display_name=claim.grant.workspace_name,+ connection_config=installer.connection_config(claim.grant),+ channel_creation_enabled=False,+ # Someone here connected a chat, as with an OAuth install.+ preconfigured=False,+ )+ bridge_id = bridge.id++ attached = await self._store.attach_bridge(+ session, install_id=install.id, bridge_id=bridge_id+ )+ await record_audit_event(+ session,+ tenant_id=state.tenant_id,+ actor_user_id=decided.created_by_user_id,+ action=AuditAction.MESSAGING_INSTALL_CONNECTED,+ target_type="messaging_install",+ target_id=install.id,+ details={+ "platform": platform,+ "external_workspace_id": chat_id,+ "workspace_name": claim.grant.workspace_name,+ "bridge_id": bridge_id,+ "scopes": claim.grant.scopes,+ "claimed_by": claim.claimant,+ },+ )+ await session.commit()++ logger.info(+ "Connected %s workspace %s for tenant %s on bridge %s",+ platform,+ chat_id,+ state.tenant_id,+ bridge_id,+ )+ return attached++ def _proposed_chat(self, state_id: str) -> str | None:+ """The chat a burnt state was proposed in, while it can be answered."""+ held = self._proposals.get(state_id)+ if held is None:+ return None+ chat_id, proposed_at = held+ if time.monotonic() - proposed_at > CONFIRM_TTL.total_seconds():+ del self._proposals[state_id]+ return None+ return chat_id++ async def _decide(+ self,+ installer: MessagingAppInstaller,+ state: InstallState,+ claim: InstallClaim,+ ) -> MessagingInstallState:+ """Take an answer to a proposal, once, from an admin of its own chat.++ Refused as expired when the state was proposed in another chat, or not+ proposed at all here: a code copied out of one chat cannot be answered+ from another. Who answered is checked before the state is decided, so+ a refused press leaves the proposal for an admin to answer.+ """+ if self._proposed_chat(state.state_id) != claim.grant.external_workspace_id:+ raise MessagingInstallStateError(+ "this claim was not proposed in this chat, or its proposal has "+ "expired. Start again from Switch."+ )+ await installer.require_claimant_may_connect(claim)+ async with tenant_session(self._session_factory, state.tenant_id) as session:+ decided = await self._store.decide_state(+ session,+ state_id=state.state_id,+ platform=state.platform,+ window=CONFIRM_TTL,+ )+ await session.commit()+ self._proposals.pop(state.state_id, None)+ return decided++ @staticmethod+ async def _lock_platform(+ session: AsyncSession, tenant_id: str, platform: str+ ) -> None:+ """Serialise the changes to which installs share a tenant's bridge.++ Held by a first claim across looking up and registering the bridge.+ """+ await session.execute(+ text("SELECT pg_advisory_xact_lock(hashtext(:key))"),+ {"key": f"messaging-install-claim:{tenant_id}:{platform}"},+ )++ async def _release_bridge(+ self, *, platform: str, bridge_id: str, workspace_id: str+ ) -> None:+ """Remove the bridge an install built, or detach one chat's room.++ A bridge built for one install goes with it, which is every OAuth+ install. A claim-based platform's bridge is the tenant's connection+ rather than any chat's, and outlives the last of them until an admin+ deletes it: a chat ending detaches only its own room, whoever ended it.+ """+ if self._installers.get(platform).installs_by_claim:+ if self._rooms is None:+ raise RuntimeError(+ f"{platform} is installed by claim, so ending one of its "+ "installs detaches a room, and this install service was "+ "built with nothing to detach it with"+ )+ await self._rooms.unlink_bridge_channel(bridge_id, workspace_id)+ return+ await self._lifecycle.remove(bridge_id)++ async def resolve_started(+ self, *, platform: str, workspace_id: str+ ) -> WebhookTarget:+ """`resolve_by_workspace`, waiting for a bridge still starting.++ For a connecting answer. The admin's Connect is the event that+ provisions its chat's room, and a bridge is launched before it is+ started: its adapter is given the callbacks that provision anything in+ the bridge's own task, a few reads after launch, and until then it is+ refused as unavailable. That gap is open when the press has just+ registered the bridge, when Telegram retries it while the bridge is+ still coming up, and when it lands on a bridge that is restarting.++ Only a connecting answer waits; every other event is refused straight+ away. Past the wait the platform is told to retry, and the retry — a+ repeated answer, since the install is committed — waits again.+ """+ deadline = time.monotonic() + _BRIDGE_START_WAIT+ while True:+ try:+ return await self.resolve_by_workspace(+ platform=platform, workspace_id=workspace_id+ )+ except WebhookBridgeUnavailable:+ if time.monotonic() >= deadline:+ raise+ await asyncio.sleep(_BRIDGE_START_POLL)++ async def _burn(self, state: InstallState) -> MessagingInstallState:+ """Redeem a verified state, and commit, before anything else happens.++ Shared by both ways an install completes, and in its own transaction+ for the reason the module docstring gives: a replay must fail even if+ everything after this does.+ """+ async with tenant_session(self._session_factory, state.tenant_id) as session:+ burnt = await self._store.redeem_state(+ session, state_id=state.state_id, platform=state.platform+ )+ await session.commit()+ return burnt++ def _encrypted_token(self, grant: InstallGrant) -> str | None:+ """The grant's credential as stored, or `None` if it carries none.++ A grant with no token is a platform whose credential is+ deployment-level (Discord, Telegram), not per-install; there is nothing+ to encrypt and the column is nullable for it.+ """+ if grant.bot_token is None:+ return None+ return self._keyring.encrypt(grant.bot_token)++ async def _require_admin(+ self, session: AsyncSession, burnt: MessagingInstallState, platform: str+ ) -> None:+ user = await session.get(User, burnt.created_by_user_id)+ if user is None or not await self._users.administers(session, user):+ raise InstallClaimNotPermitted(+ f"connecting the first {platform} chat turns {platform} on for "+ "this organisation, which only an admin can do. Ask an admin to "+ "connect it, or to connect any chat first."+ )+async def list_installs(self, session: AsyncSession) -> list[MessagingInstall]:"""The bound tenant's installs, for the operator's own list.@@ -621,6 +1063,34 @@ class MessagingInstallService:"""return await self._store.list_for_tenant(session)+ async def install_names(self, session: AsyncSession) -> dict[str, str]:+ """What a person calls each of the bound tenant's installs that still+ has a name, by install id.++ A claimed chat is a room, so it is called what its room is called. An+ OAuth install is its own bridge, named for the workspace it came from.+ An ended install has let go of both and is left to be shown by its id.+ """+ names: dict[str, str] = {}+ for install_id, platform, room, bridge in await self._store.names_for_tenant(+ session+ ):+ name = room if self._installs_by_claim(platform) else bridge+ if name:+ names[install_id] = name+ return names++ async def chat_rooms(self, session: AsyncSession) -> dict[str, Room]:+ """The room each of the bound tenant's claimed chats still has, by+ install id. An ended chat has let go of its room and is absent."""+ return await self._store.rooms_for_tenant(session)++ def _installs_by_claim(self, platform: str) -> bool:+ try:+ return self._installers.get(platform).installs_by_claim+ except MessagingInstallError:+ return False+# ── Ending an install ────────────────────────────────────────────────────async def disconnect(self, *, tenant_id: str, install_id: str) -> MessagingInstall:@@ -631,8 +1101,8 @@ class MessagingInstallService:`app_uninstalled` ended a second earlier, and that is not an error toshow them.- **Removing the bridge detaches every room that used it**, which become- internal-only. That is the honest consequence of disconnecting a+ **Removing an OAuth install's bridge detaches every room that used+ it**, which become internal-only; a claimed chat detaches only its own. That is the honest consequence of disconnecting amessaging app and it is not softened here — but it is the reason thisis an explicit action with a confirmation in front of it rather thansomething inferred.@@ -659,11 +1129,16 @@ class MessagingInstallService:installer = self._installers.get(platform)if token is not None:await installer.revoke(bot_token=self._keyring.decrypt(token))- elif bridge_id is None or not self._lifecycle.is_connected(bridge_id):+ elif (+ installer.installs_by_claim+ or bridge_id is None+ or not self._lifecycle.is_connected(bridge_id)+ ):# A tokenless install has nothing to revoke, and a connected# bridge lets go of the platform itself as it is removed. One# that is not running, or still starting, cannot, so the- # installer does it.+ # installer does it. So does a claimed chat, whose bridge is+ # the tenant's and is not removed with it.await installer.release(external_workspace_id=workspace_id)async with tenant_session(self._session_factory, tenant_id) as session:@@ -673,7 +1148,9 @@ class MessagingInstallService:await session.commit()if bridge_id is not None:- await self._lifecycle.remove(bridge_id)+ await self._release_bridge(+ platform=platform, bridge_id=bridge_id, workspace_id=workspace_id+ )logger.info("Disconnected %s workspace %s for tenant %s",@@ -737,7 +1214,9 @@ class MessagingInstallService:await session.commit()if bridge_id is not None:- await self._lifecycle.remove(bridge_id)+ await self._release_bridge(+ platform=platform, bridge_id=bridge_id, workspace_id=workspace_id+ )logger.warning("Ended the install of %s workspace %s for tenant %s: %s",@@ -837,6 +1316,19 @@ class MessagingInstallService:workspace_id=installer.workspace_of_event(event.payload), reason=reason)+ def claim_of(self, *, platform: str, event: InboundWebhook) -> InstallClaim | None:+ """Whether this event asks for its workspace to be installed.++ Asked before `resolve` for the mirror of the reason `revocation` is:+ the workspace a claim names is not installed yet, so resolving it first+ would drop the one event that could install it.+ """+ return self._installers.get(platform).claim_of_event(event.payload)++ def answer_of(self, *, platform: str, event: InboundWebhook) -> ClaimAnswer | None:+ """Whether this event answers a proposal; asked before `resolve` too."""+ return self._installers.get(platform).answer_of_event(event.payload)+async def resolve(self, *, platform: str, event: InboundWebhook) -> WebhookTarget:"""Turn a webhook event's workspace into the bridge entitled to it."""return await self.resolve_by_workspace(@@ -873,9 +1365,10 @@ class MessagingInstallService:self._session_factory, platform, workspace_id)if tenant_id is None:- raise WebhookWorkspaceUnknown(+ raise WebhookWorkspaceUnowned(f"no tenant has installed Switch into {platform} workspace "- f"{workspace_id}"+ f"{workspace_id}",+ workspace_id=workspace_id,)async with tenant_session(self._session_factory, tenant_id) as session:@@ -899,6 +1392,14 @@ class MessagingInstallService:f"bridge {install.bridge_id}, which serves {platform} workspace "f"{workspace_id}, is not running")+ # Normally attached already, as it started. This covers one that+ # started before the platform's shared connection was up and that the+ # walk on connect did not reach. Here rather than at dispatch so a+ # connection that is not ready is refused while the platform can still+ # be told to retry.+ connection = self._installers.get(platform).shared_connection()+ if connection is not None and isinstance(adapter, SupportsSharedConnection):+ adapter.attach_shared_connection(connection)return WebhookTarget(tenant_id=tenant_id,platform=platform,@@ -906,6 +1407,94 @@ class MessagingInstallService:adapter=adapter,)+ async def follow_migration(+ self, *, platform: str, event: InboundWebhook, target: WebhookTarget+ ) -> None:+ """Move the install to its workspace's new id, if the event says so.++ After `resolve`, which found the tenant by the old id, and before the+ event is delivered, whose handler moves the room the same way. Awaited+ rather than deferred: until the row moves, every event from the new id+ resolves to nobody and is dropped.++ Messages from the new id that were dropped before this ran are lost;+ the recently-dropped list is how that is said rather than guessed.+ """+ migration = self._installers.get(platform).migration_of_event(event.payload)+ if migration is None:+ return+ old_id, new_id = migration+ with tenant_scope(target.tenant_id):+ async with tenant_session(+ self._session_factory, target.tenant_id+ ) as session:+ moved = await self._store.move_workspace(+ session,+ platform=platform,+ from_workspace_id=old_id,+ to_workspace_id=new_id,+ )+ await session.commit()+ if moved is None:+ return+ logger.info(+ "The %s install of workspace %s followed it to %s (tenant %s)",+ platform,+ old_id,+ new_id,+ target.tenant_id,+ )+ dropped = self._recent_drops.pop((platform, new_id), None)+ if dropped is not None:+ logger.error(+ "%d %s event(s) from workspace %s were dropped as unowned before "+ "its install followed it from %s; they are lost",+ dropped[0],+ platform,+ new_id,+ old_id,+ )++ def note_unowned(self, *, platform: str, workspace_id: str) -> bool:+ """Remember an unowned drop, and say whether it is routine here.++ Remembered as an id and a count for a few minutes, so a migration can+ tell whether it lost anything; see `follow_migration`. Routine or not+ is the installer's `expects_unowned_events`, and decides whether the+ route warns or only counts.+ """+ now = time.monotonic()+ while self._recent_drops:+ _, (_, last_seen) = next(iter(self._recent_drops.items()))+ if now - last_seen < _RECENT_DROP_TTL:+ break+ self._recent_drops.popitem(last=False)+ key = (platform, workspace_id)+ count, _ = self._recent_drops.pop(key, (0, now))+ self._recent_drops[key] = (count + 1, now)+ if len(self._recent_drops) > _RECENT_DROPS_MAX:+ self._recent_drops.popitem(last=False)+ return self._installers.get(platform).expects_unowned_events++ async def unowned(+ self, *, platform: str, workspace_id: str, event: InboundWebhook+ ) -> None:+ """Let the installer answer an unowned event, after the platform has been."""++ async def still_unowned() -> bool:+ return (+ await tenant_of_messaging_install(+ self._session_factory, platform, workspace_id+ )+ is None+ )++ await self._installers.get(platform).on_unowned_event(+ workspace_id=workspace_id,+ payload=event.payload,+ still_unowned=still_unowned,+ )+async def deliver(self, target: WebhookTarget, event: InboundWebhook) -> None:"""Hand a resolved event to the bridge, at most once.diff --git a/core/switch_core/bridges/collaboration/install_state.py b/core/switch_core/bridges/collaboration/install_state.pyindex 9f2d4693b..c76d8e402 100644--- a/core/switch_core/bridges/collaboration/install_state.py+++ b/core/switch_core/bridges/collaboration/install_state.py@@ -32,6 +32,16 @@ derived rather than reused: a token minted here must never be mistakable for asession JWT, or for whatever the next thing to want a signature turns out tobe. Verification accepts any key in the keyring, and while `JWT_SECRET_KEY` isstill set, a state minted with it before `SECRET_KEYS` existed.++**A second, compact form exists for platforms with no redirect.** Telegram has+no consent screen to carry a state through; the only thing that rides along+with adding its bot to a group is a deep-link start parameter of at most 64+characters from `[A-Za-z0-9_-]`, and the form above is about 150. The compact+form carries the same two ids as raw UUID bytes and a truncated MAC, and says+nothing about the platform: that is implied by the key, which is derived per+platform, so a token minted for one platform is simply unsigned to another.+Ninety-six bits of MAC is ample for a token that is also single use and dead+in ten minutes."""from __future__ import annotations@@ -40,6 +50,7 @@ import base64import hashlibimport hmacimport json+import uuidfrom dataclasses import dataclassfrom switch_core.keys import Keyring, Purpose@@ -50,6 +61,13 @@ _LEGACY_KEY_INFO = b"switch/messaging-install-state/v1"_PREFIX = "v1."+#: The compact form's counterparts. Its key info is completed by the platform+#: name — see `_compact_signing_key`.+_COMPACT_KEY_INFO = b"switch/messaging-install-claim/c1/"+_COMPACT_PREFIX = "c1"+_COMPACT_MAC_BYTES = 12+_COMPACT_BODY_BYTES = 32+class InstallStateError(RuntimeError):"""A state parameter was absent, malformed, or not signed by us.@@ -145,3 +163,60 @@ def verify(token: str, *, keyring: Keyring) -> InstallState:)except (ValueError, KeyError, TypeError):raise InstallStateError("install state is malformed") from None+++def _compact_signing_key(key: bytes, platform: str) -> bytes:+ return hmac.new(key, _COMPACT_KEY_INFO + platform.encode(), hashlib.sha256).digest()+++def _compact_mac(key: bytes, platform: str, body: bytes) -> bytes:+ return hmac.new(_compact_signing_key(key, platform), body, hashlib.sha256).digest()[+ :_COMPACT_MAC_BYTES+ ]+++def mint_compact(state: InstallState, *, keyring: Keyring) -> str:+ """Sign a state short enough to ride in a 64-character deep link.++ Both ids must be UUIDs, which every tenant and state row is in production.+ Anything else is a programming error rather than a state to mint, and+ raises `ValueError` instead of producing a token that could not round-trip.+ """+ body = uuid.UUID(state.tenant_id).bytes + uuid.UUID(state.state_id).bytes+ mac = _compact_mac(keyring.derive(Purpose.INSTALL_STATE), state.platform, body)+ return f"{_COMPACT_PREFIX}{_b64(body + mac)}"+++def verify_compact(token: str, *, platform: str, keyring: Keyring) -> InstallState:+ """Recover a compact state minted for `platform`, or raise.++ The platform is an argument rather than a field because the token does not+ carry one: the caller says which platform it is listening as, and a token+ minted for any other fails the MAC like a forgery would.++ Any key in the keyring verifies, as for the full form. `JWT_SECRET_KEY`+ does not: no compact state was ever minted with it.+ """+ if not token.startswith(_COMPACT_PREFIX):+ raise InstallStateError("install state is not a state this deployment minted")++ try:+ raw = _unb64(token[len(_COMPACT_PREFIX) :])+ except ValueError:+ raise InstallStateError("install state is malformed") from None+ if len(raw) != _COMPACT_BODY_BYTES + _COMPACT_MAC_BYTES:+ raise InstallStateError("install state is malformed")++ body, mac = raw[:_COMPACT_BODY_BYTES], raw[_COMPACT_BODY_BYTES:]+ matches = False+ for key in keyring.verification_keys(Purpose.INSTALL_STATE):+ expected = _compact_mac(key, platform, body)+ matches = hmac.compare_digest(mac, expected) or matches+ if not matches:+ raise InstallStateError("install state was not signed by this deployment")++ return InstallState(+ tenant_id=str(uuid.UUID(bytes=body[:16])),+ state_id=str(uuid.UUID(bytes=body[16:])),+ platform=platform,+ )diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 227438ca0..47301ee52 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -388,6 +388,9 @@ class CollaborationBridgeLifecycleService:# registration refuses a second claim, but rows predating that check# still start.self._running_workspaces: dict[str, str] = {}+ # Resources the deployment itself holds and no bridge may, with who+ # holds them — the distributed Telegram app's bot, for one.+ self._reserved_resources: dict[str, str] = {}# Started and not deliberately stopped. A crash removes a bridge from# `_bridges` and leaves it here, which is what makes "configured but no# longer running" answerable.@@ -701,6 +704,15 @@ class CollaborationBridgeLifecycleService:except Exception:logger.exception("Failed to start bridge %s", bridge.id)+ def reserve_resource(self, resource: str, holder: str) -> None:+ """Keep a resource the deployment itself uses away from every bridge.++ The distributed Telegram app's bot is the case: its updates go to the+ webhook, and a self-registered bridge polling the same bot would fail+ against it — or, if it got there first, take every tenant's updates.+ """+ self._reserved_resources[resource] = holder+async def reject_claim_conflict(self,bridge_type: str,@@ -726,6 +738,16 @@ class CollaborationBridgeLifecycleService:wanted_workspace = adapter_cls.claimed_workspace(connection_config)if wanted_resource is None and wanted_workspace is None:return+ holder = (+ None+ if wanted_resource is None+ else self._reserved_resources.get(wanted_resource)+ )+ if holder is not None:+ raise BridgeClaimConflict(+ f"{wanted_resource} is this deployment's own {holder} and cannot "+ "also be connected as a bridge. Use a bot of your own."+ )# Captured before the loop below rebinds per tenant. This method is# only ever reached from an authenticated request or an install the@@ -1018,6 +1040,13 @@ class CollaborationBridgeLifecycleService:# the bind error one of them causes. Say which bridge holds it# instead.wanted = adapter_cls.exclusive_resource(bridge.connection_config or {})+ if wanted is not None and wanted in self._reserved_resources:+ raise ValueError(+ f"Cannot start bridge {bridge_id} ({bridge.type}): {wanted} "+ f"is this deployment's own "+ f"{self._reserved_resources[wanted]}. Give the bridge a bot "+ "of its own."+ )if wanted is not None:for other_id, held in self._held_resources.items():if held == wanted and other_id != bridge_id:diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex 92bd2d9fc..0a0d3ea9a 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -9,10 +9,11 @@ from collections import OrderedDictfrom collections.abc import Awaitable, Callable, Coroutinefrom contextvars import ContextVarfrom dataclasses import replace-from typing import Any, ClassVar, NamedTuple+from typing import Any, ClassVar, Literal, NamedTuple+from pydantic import ConfigDict, model_validator+from pydantic.json_schema import SkipJsonSchemafrom telegram import (- BotCommand,ForceReply,InlineKeyboardButton,InlineKeyboardMarkup,@@ -34,10 +35,11 @@ from telegram.error import ()from telegram.ext import Application, ApplicationBuilder, TypeHandler-from switch_core.bridges.agent.commands import COMMANDS, COMMANDS_BY_NAME, CommandArg+from switch_core.bridges.agent.commands import COMMANDS_BY_NAME, CommandArgfrom switch_core.bridges.collaboration.adapter import (ActivityMark,ActivityMarkRefused,+ ChannelNotBindable,PlatformAdapter,RemovalFailed,RequestCard,@@ -78,10 +80,19 @@ from switch_core.bridges.collaboration.session.renderers.neutral import (render_request,turn_status,)+from switch_core.bridges.collaboration.telegram.app_client import (+ TelegramAppClient,+ bot_id_of,+ bot_resource,+)from switch_core.bridges.collaboration.telegram.chunking import (MAX_MESSAGE,chunk_message,)+from switch_core.bridges.collaboration.telegram.commands import command_menu+from switch_core.bridges.collaboration.telegram.install import is_connect_press+from switch_core.observability.catalogue import BRIDGE_THROTTLE_HELD+from switch_core.observability.metrics import metricsfrom switch_core.room_wide_mention import (CODE_AND_URLS,defuse_mass_mention_words_in_prose,@@ -251,12 +262,6 @@ _COMMAND_PREFIXES = ("!", "/")# worth saying in the chat and in the logs._INSTALL_PAYLOAD = "switch"-# Telegram will only register a command spelled in these characters, and caps a-# description at 256. A name it rejects is left out of the menu rather than-# taking the whole call down.-_TELEGRAM_COMMAND_RE = re.compile(r"[a-z0-9_-]{1,32}")-_MAX_COMMAND_DESCRIPTION = 256-# Supergroup and channel ids are the internal id with a -100 prefix; t.me/c/# links carry the internal id alone._SUPERGROUP_PREFIX = "-100"@@ -437,8 +442,55 @@ class _ThreadRoot(NamedTuple):class TelegramConnectionConfig(BridgeConnectionConfig):- bot_token: str- bot_username: str+ # Still required on the registration form, which only ever creates a+ # self-registered bridge. The model allows them absent because the install+ # flow writes shared bridges without them; the validator below is what+ # decides, so the form cannot drift from it.+ model_config = ConfigDict(+ json_schema_extra={"required": ["bot_token", "bot_username"]}+ )++ #: Optional because they depend on `event_delivery`, which the validator+ #: below enforces: a self-registered bridge polls with its own bot; a+ #: distributed one runs on the deployment's shared bot and carries neither.+ bot_token: str | None = None+ bot_username: str | None = None+ #: How this bridge's updates reach it, decided by which bot the chat was+ #: connected to rather than by anyone's preference.+ #:+ #: `own_connection` is the self-registered bot: Switch polls Telegram with+ #: the token above. `shared` is the distributed app: the bridge polls+ #: nothing, is handed the one deployment bot, and receives its updates+ #: from the webhook route.+ #:+ #: Hidden from the registration form, which only ever reaches the+ #: self-registered case; the shared value is written by the install flow.+ event_delivery: SkipJsonSchema[Literal["own_connection", "shared"]] = (+ "own_connection"+ )++ @model_validator(mode="after")+ def _credentials_match_delivery(self) -> TelegramConnectionConfig:+ """Refuse the half-states that look configured and cannot work.++ A self-registered bridge with no token polls nothing and receives+ nothing. A shared bridge carrying one holds a credential for a bot it+ does not own, and polling with it would take the shared bot's updates+ away from every tenant.+ """+ if self.event_delivery == "own_connection" and not (+ self.bot_token and self.bot_username+ ):+ raise ValueError(+ "bot_token and bot_username are required: without them Switch "+ "cannot poll Telegram and this bridge would receive nothing."+ )+ if self.event_delivery == "shared" and (self.bot_token or self.bot_username):+ raise ValueError(+ "a shared-delivery Telegram bridge carries no bot_token or "+ "bot_username; the distributed app's bot is deployment config."+ )+ return selfclass TelegramAdapter(PlatformAdapter):@@ -516,7 +568,13 @@ class TelegramAdapter(PlatformAdapter):self._app: Application | None = None # type: ignore[type-arg]self._bot: Any = Noneself._bot_user_id: int = 0- self._bot_username = config.bot_username.lstrip("@")+ self._bot_username = (config.bot_username or "").lstrip("@")+ # A shared bridge polls nothing and is handed the deployment's bot by+ # `attach_shared_connection`; until then it neither sends nor receives.+ self._shared = config.event_delivery == "shared"+ # Fired on that attach, so the start-time work that needed the bot+ # (agent identities) can run. Set by BridgeCore.+ self._on_attached: Callable[[], None] | None = Noneself._seen_ids: OrderedDict[tuple[str, int], None] = OrderedDict()self._seen_ids_max = 1000# Telegram user id ↔ username caches, for rendering outbound mentions of@@ -588,6 +646,14 @@ class TelegramAdapter(PlatformAdapter):self._on_user_joined = on_user_joinedself._on_app_joined = on_app_joined+ if self._shared:+ # No polling and no command menu: the shared bot's updates arrive+ # through `dispatch_event`, and its menu is published once for the+ # deployment. Inert until `attach_shared_connection`.+ logger.info("Telegram bridge registered on the shared app bot; awaiting it")+ return++ assert self._config.bot_token is not None # guaranteed by the validatorapp = ApplicationBuilder().token(self._config.bot_token).build()app.add_handler(TypeHandler(Update, self._make_on_update()))self._app = app@@ -639,24 +705,14 @@ class TelegramAdapter(PlatformAdapter):async def _publish_command_menu(self) -> None:"""Publish the in-room command set so Telegram offers it as you type.- Telegram only accepts `[a-z0-9_]` in a registered command, so the- hyphenated names are published in their underscore spelling —- `/invite_agent` — and `_parse_command` accepts either. Without this the- commands still work when typed in full, but nothing suggests them, and- a `/` menu that lists none implies the bot has none.+ Without this the commands still work when typed in full, but nothing+ suggests them, and a `/` menu that lists none implies the bot has none.A failure here is logged and left non-fatal, as Discord's sync is: thebridge is fully usable without the menu, and losing it is a far betteroutcome than refusing to start."""- menu = [- BotCommand(- command=command.name.replace("-", "_"),- description=command.description[:_MAX_COMMAND_DESCRIPTION],- )- for command in COMMANDS- if not command.hidden and _TELEGRAM_COMMAND_RE.fullmatch(command.name)- ]+ menu = command_menu()try:await self._require_bot().set_my_commands(menu)except Exception:@@ -882,7 +938,9 @@ class TelegramAdapter(PlatformAdapter):The link is withheld from a bot BotFather has barred from groups,because Telegram answers that by opening a chat with the bot too."""- if not self._bot_username or not self._can_join_groups:+ if self._shared or not self._bot_username or not self._can_join_groups:+ # A shared bridge's link is a signed claim from the install flow;+ # this unsigned one would add the bot to a chat nobody owns.return []return [BridgeInstallLink(@@ -942,6 +1000,69 @@ class TelegramAdapter(PlatformAdapter):self._bot = Nonelogger.info("Telegram adapter stopped")+ @classmethod+ def exclusive_resource(cls, connection_config: dict[str, object]) -> str | None:+ """The bot a self-registered bridge polls, which only one poller can use.++ Telegram hands each update to a single `getUpdates` caller, so two+ bridges on one token split a chat's messages between them at random.+ Declaring the bot here refuses the second at registration.++ A shared bridge declares nothing: every tenant's shared bridge runs on+ the one app bot by design, and none of them polls it.+ """+ config = TelegramConnectionConfig.model_validate(connection_config)+ if config.event_delivery == "shared" or config.bot_token is None:+ return None+ return bot_resource(bot_id_of(config.bot_token))++ def set_on_attached(self, callback: Callable[[], None]) -> None:+ self._on_attached = callback++ def attach_shared_connection(self, connection: Any) -> None:+ """Hand a shared bridge the deployment's bot, once.++ Called as a bridge starts once the bot is up, when the bot comes up+ for bridges started before it, and on each update delivered to a+ bridge, as a backstop. Everything the self-registered+ bridge learns from its own `getMe` is read from the shared client+ instead, and the rate-limit cooldown is the client's rather than this+ bridge's, because Telegram meters the bot and not the tenant.++ A no-op on a self-registered bridge and on one already attached. Any+ other connection type is a wiring mistake and raises rather than being+ read as if it were a Telegram bot.+ """+ if not self._shared or self._bot is not None:+ return+ if not isinstance(connection, TelegramAppClient):+ raise TypeError(+ f"a Telegram bridge was handed a {type(connection).__name__}, "+ "not the Telegram app client"+ )+ self._bot = connection.bot+ self._bot_user_id = int(connection.bot_id)+ self._bot_username = connection.bot_username+ self._privacy_mode_disabled = connection.privacy_mode_disabled+ self._can_join_groups = connection.can_join_groups+ self._rich_update_cooldown = connection.cooldown+ if self._on_attached is not None:+ self._on_attached()++ async def dispatch_event(+ self, *, envelope_type: str, payload: dict[str, Any]+ ) -> None:+ """Handle one update the webhook route resolved to this bridge.++ The same handling a polled update gets, from the same `Update` object,+ so the two delivery paths cannot drift in what they do with one.+ """+ if not self._shared:+ await super().dispatch_event(envelope_type=envelope_type, payload=payload)+ return+ update = Update.de_json(payload, self._require_bot())+ await self._handle_update(update)+def _require_bot(self) -> Any:if self._bot is None:raise RuntimeError("Telegram bot not connected")@@ -1822,6 +1943,11 @@ class TelegramAdapter(PlatformAdapter):"""remaining = self._rich_update_cooldown.remaining()if remaining > 0:+ metrics().observe(+ BRIDGE_THROTTLE_HELD,+ {"platform": "telegram", "delivery": self._config.event_delivery},+ remaining,+ )raise RichContentThrottled(retry_after=remaining, text=text)def _pace_publication(@@ -2036,6 +2162,27 @@ class TelegramAdapter(PlatformAdapter):return Nonereturn f"https://t.me/{self._bot_username}"+ def channel_ids_refused(self) -> str | None:+ """Every id, on the shared bot: a chat joins it only by being claimed.++ The shared bot is in every organisation's chats, and nothing it can+ ask Telegram says whose a chat is — only a claim does, and a claimed+ chat is given its room by the claim. A self-registered bot is the+ organisation's own and reaches only chats someone added it to.+ """+ if not self._shared:+ return None+ return (+ "Rooms on the Switch Telegram app come from connecting a chat: use "+ "Add to Telegram on the Telegram card under Installed apps, and the "+ "chat gets its room. A chat cannot be linked to a room by its id."+ )++ async def require_bindable_channel(self, channel_id: str) -> None:+ refusal = self.channel_ids_refused()+ if refusal is not None:+ raise ChannelNotBindable(refusal)+async def get_channel_type(self, channel_id: str) -> ChannelType:bot = self._require_bot()chat = await bot.get_chat(self._chat_id(channel_id))@@ -2283,7 +2430,17 @@ class TelegramAdapter(PlatformAdapter):message = getattr(query, "message", None)chat = getattr(message, "chat", None)user = getattr(query, "from_user", None)- dispatch = _press_action(str(getattr(query, "data", "") or ""))+ data = str(getattr(query, "data", "") or "")+ if is_connect_press(data) and chat is not None:+ # The install route connected the chat on this press and closes+ # it itself; what is left here is the join.+ await self._provision_claimed(+ str(chat.id),+ self._channel_type_of(chat),+ getattr(chat, "title", None),+ )+ return+ dispatch = _press_action(data)if dispatch is None or chat is None or user is None:await self._answer_callback(query_id, None)return@@ -2443,8 +2600,18 @@ class TelegramAdapter(PlatformAdapter):returnif author is None:- # Channel posts are authored by the channel, not a person; there is- # no sender to attribute them to.+ # A channel post names a person only when the channel shows its+ # authors' profiles, and then it arrives with a sender and is+ # bridged below. Otherwise it is the channel's, with no sender to+ # attribute it to. The one exception is the `/connect` that claimed+ # the channel for a shared bridge, which is its join.+ if self._shared:+ await self._absorb_claim(+ str(getattr(message, "text", None) or ""),+ chat_id,+ channel_type,+ channel_name,+ )returnusername = self._display_name(author)@@ -2457,6 +2624,10 @@ class TelegramAdapter(PlatformAdapter):root_id = self._root_id_of(message)message_ref = f"{chat_id}:{message.message_id}"+ if self._shared and await self._absorb_claim(+ content.strip(), chat_id, channel_type, channel_name+ ):+ returnif await self._handle_start(content.strip(), chat_id, channel_type):return@@ -2651,8 +2822,9 @@ class TelegramAdapter(PlatformAdapter):nothing.A bare `/start` in a 1:1 chat is left alone — it is how a person opens- a conversation with the bot, and swallowing it would leave the DM- unbridged until they typed again.+ a conversation with the bot, and swallowing it would leave them without+ the reply that says direct messages reach no agent. A DM is never+ bridged either way.Only groups reach this at all. A channel add sends no `/start` — thestart parameter is group-only — and a channel post has no sender, so it@@ -2677,6 +2849,65 @@ class TelegramAdapter(PlatformAdapter):await self.announce_visibility(chat_id)return True+ async def _absorb_claim(+ self,+ text: str,+ chat_id: str,+ channel_type: ChannelType,+ channel_name: str | None,+ ) -> bool:+ """Take a claim posted in a chat this bridge already holds as a join.++ A claim no longer connects a chat; an admin's Connect does, and that+ press is what provisions the room (`_provision_claimed`). A claim+ reaches a bridge only when it is posted in a chat the bridge already+ holds, and provisioning is idempotent, so this changes nothing there+ but keeps the claim from being relayed as a message.+ """+ parsed = self._parse_command(text)+ if (+ parsed is None+ or parsed[0] not in ("start", "connect")+ or not parsed[1]+ or channel_type == "lobby"+ ):+ return False+ await self._provision_claimed(chat_id, channel_type, channel_name)+ return True++ async def _provision_claimed(+ self, chat_id: str, channel_type: ChannelType, channel_name: str | None+ ) -> None:+ """Do the add's work for a chat the shared bot was connected to.++ On the shared bot the bot's own add arrives while the chat still+ belongs to nobody, so it is dropped before any bridge sees it, and the+ room it would have provisioned is not there. The first update the+ chat's tenant receives is the Connect press that connected it, so it+ provisions the room instead, then says what the bot can see. The press+ was checked and the claim redeemed by the install route before it was+ delivered here.+ """+ if channel_type == "lobby":+ return+ if self._on_app_joined is None:+ # Taking the press without provisioning would lose the chat's room+ # for good. The install route holds a connecting press until its+ # bridge has started, so reaching here means that wait was+ # bypassed.+ raise RuntimeError(+ f"Telegram chat {chat_id} was connected on a bridge that has not "+ "started, so its room cannot be provisioned"+ )+ await self._on_app_joined(+ InboundAppJoin(+ channel_id=chat_id,+ channel_type=channel_type,+ channel_name=channel_name,+ )+ )+ await self.announce_visibility(chat_id)+@staticmethoddef _missing_argument(name: str) -> CommandArg | None:"""The first required argument of `name`, or None if it takes none.diff --git a/core/switch_core/bridges/collaboration/telegram/app_client.py b/core/switch_core/bridges/collaboration/telegram/app_client.pynew file mode 100644index 000000000..000929a4b--- /dev/null+++ b/core/switch_core/bridges/collaboration/telegram/app_client.py@@ -0,0 +1,264 @@+"""The deployment's own Telegram bot, shared by every tenant.++The distributed Telegram app (`docs/old/bridges/TELEGRAM_DISTRIBUTED_APP.md`)+is one bot per deployment. Its token is deployment config, never stored against+an install, and everything that is per bot rather than per tenant lives here:+who the bot is (`getMe`), where Telegram delivers its updates (`setWebhook`),+the command menu (`setMyCommands`), and the rate-limit cooldown.++**The cooldown is one for the deployment, not one per tenant.** Telegram meters+the bot, and one bot serves every tenant here, so a 429 earned in one tenant's+chat is a 429 for all of them. Each tenant's adapter holds back against this+one rather than a cooldown of its own that would not know.++A bot has exactly one delivery channel. Setting a webhook makes `getUpdates`+fail, so this bot is never polled — not by this process and not by a+self-registered bridge someone pasted the same token into.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable, Callable++import telegram++from switch_core.bridges.collaboration.cooldown import Cooldown+from switch_core.bridges.collaboration.install import MessagingInstallError+from switch_core.bridges.collaboration.telegram.commands import command_menu++logger = logging.getLogger(__name__)++#: The updates Telegram is asked to deliver. The same set the self-registered+#: adapter polls for; a test holds the two together.+ALLOWED_UPDATES: tuple[str, ...] = (+ "message",+ "channel_post",+ "my_chat_member",+ "callback_query",+)++_INITIAL_RETRY_DELAY = 5.0+_MAX_RETRY_DELAY = 300.0++#: How often Telegram is asked how delivery to the webhook is going.+_DELIVERY_CHECK_INTERVAL = 300.0+#: Updates Telegram may hold for us before a growing queue is worth saying.+_PENDING_WORTH_REPORTING = 50+++class TelegramAppNotReady(MessagingInstallError):+ """The shared bot has not yet told us who it is.++ Its username comes from `getMe`, which runs in the background at boot so an+ unreachable Telegram cannot hold up a deployment serving other platforms.+ Until it answers there is no link to hand out and no way to tell a command+ addressed to this bot from one addressed to another bot in the same chat.+ """+++def bot_id_of(token: str) -> str:+ """The bot's numeric id, which is the part of its token before the colon.++ Read from the token rather than `getMe` because it is needed where no call+ can be made — comparing a token someone pasted into a self-registered+ bridge against this one.+ """+ bot_id, separator, _ = token.partition(":")+ if not separator or not bot_id.isdigit():+ raise ValueError("a Telegram bot token is shaped <bot id>:<secret>")+ return bot_id+++def bot_resource(bot_id: str) -> str:+ """The exclusive resource a Telegram bot is, as bridges and the app name it.++ One place, so the self-registered bridge's claim on a bot and the app's+ reservation of its own cannot drift into two spellings that never collide.+ """+ return f"Telegram bot {bot_id}"+++class TelegramAppClient:+ def __init__(+ self,+ *,+ bot: telegram.Bot,+ webhook_url: str,+ webhook_secret: str,+ on_connected: Callable[[TelegramAppClient], Awaitable[None]],+ ) -> None:+ self._bot = bot+ self._on_connected = on_connected+ self._webhook_url = webhook_url+ self._webhook_secret = webhook_secret+ self._username: str | None = None+ self.bot_id = bot_id_of(bot.token)+ self.privacy_mode_disabled = False+ self.can_join_groups = True+ self.cooldown = Cooldown(+ "Telegram",+ "message updates",+ "bot",+ "Every card it draws is frozen until then, in every chat of every "+ "organisation it serves.",+ )++ @property+ def bot(self) -> telegram.Bot:+ return self._bot++ @property+ def bot_username(self) -> str:+ self.require_ready()+ assert self._username is not None+ return self._username++ @property+ def is_live(self) -> bool:+ """Whether `start` has succeeded, which is what a bridge needs of it.++ Set as the last step of `start`, with no await between it and the+ walk `on_connected` makes over the running bridges.+ """+ return self._username is not None++ def require_ready(self) -> None:+ if self._username is None:+ raise TelegramAppNotReady(+ "the Switch Telegram bot has not connected yet, so there is no "+ "link to offer. Try again shortly; the server log says why if "+ "it keeps failing."+ )++ async def start(self) -> None:+ """Learn who the bot is, then point Telegram's delivery at us.++ `setWebhook` runs on every start rather than once at registration, so+ the URL, the secret and the update types always match this build's+ config — rotating the secret is a redeploy, not a manual call.+ """+ await self._bot.initialize()+ me = await self._bot.get_me()+ if not me.username:+ raise MessagingInstallError(+ f"Telegram reports no username for bot {me.id}, and every link "+ "to it is built from one"+ )+ await self._bot.set_webhook(+ url=self._webhook_url,+ secret_token=self._webhook_secret,+ allowed_updates=list(ALLOWED_UPDATES),+ )+ self.privacy_mode_disabled = bool(me.can_read_all_group_messages)+ self.can_join_groups = bool(me.can_join_groups)+ if not self.privacy_mode_disabled:+ logger.error(+ "Group Privacy is on for the Telegram app @%s, so it sees only "+ "commands and mentions in every chat it joins from now on. Turn "+ "it off in BotFather (/mybots -> Bot Settings -> Group Privacy); "+ "chats joined before the change keep the old setting until the "+ "bot is removed and added back",+ me.username,+ )+ await self._publish_command_menu()+ self._username = me.username+ logger.info(+ "Telegram app @%s is receiving updates at %s",+ self._username,+ self._webhook_url,+ )++ async def _publish_command_menu(self) -> None:+ """Publish the `/` menu, once for the bot rather than once per tenant.++ Non-fatal like the self-registered bridge's: commands work typed in+ full without it, and a missing menu is a far better outcome than an app+ that offers no links because a cosmetic call failed.+ """+ menu = command_menu()+ try:+ await self._bot.set_my_commands(menu)+ except Exception:+ logger.exception(+ "Could not publish the Telegram app's command menu; commands "+ "still work when typed, but are not suggested"+ )+ return+ logger.info("Published %d Telegram commands", len(menu))++ async def start_with_retry(self) -> None:+ """`start`, retried with backoff, as a supervised background task.++ A configured-but-unreachable Telegram must never block or fail a boot+ that serves every other platform. Until this succeeds the app offers no+ links, and updates Telegram already holds for us wait on its side. On+ success `on_connected` hands the bot to the bridges already running.+ """+ delay = _INITIAL_RETRY_DELAY+ while True:+ try:+ await self.start()+ break+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.exception(+ "The Telegram app failed to start; it offers no links until "+ "it does. Retrying in %.0fs",+ delay,+ )+ await asyncio.sleep(delay)+ delay = min(delay * 2, _MAX_RETRY_DELAY)+ await self._on_connected(self)++ async def check_delivery(+ self, previous: telegram.WebhookInfo | None+ ) -> telegram.WebhookInfo:+ """Ask Telegram how its deliveries to us are going, and say if badly.++ The only view there is of what Telegram has given up on. Our own route+ logs every refusal it makes, but not a delivery that never arrived, and+ not the retries Telegram is still holding: a new delivery error, or a+ queue growing past a handful, is Telegram telling us events are late+ or will be lost.+ """+ info = await self._bot.get_webhook_info()+ if info.last_error_date and (+ previous is None or info.last_error_date != previous.last_error_date+ ):+ logger.warning(+ "Telegram reports failing to deliver to the webhook: %s",+ info.last_error_message,+ )+ if info.pending_update_count >= _PENDING_WORTH_REPORTING and (+ previous is None+ or info.pending_update_count > previous.pending_update_count+ ):+ logger.warning(+ "Telegram is holding %d updates it has not yet delivered to the "+ "webhook; replies are late, and updates it gives up on are lost",+ info.pending_update_count,+ )+ return info++ async def watch_delivery(self) -> None:+ """`check_delivery` for the life of the process, after a start."""+ previous: telegram.WebhookInfo | None = None+ while True:+ await asyncio.sleep(_DELIVERY_CHECK_INTERVAL)+ try:+ previous = await self.check_delivery(previous)+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.exception("Could not ask Telegram how webhook delivery is going")++ async def stop(self) -> None:+ """Release the HTTP client. The webhook stays set on purpose.++ Deleting it would make Telegram discard what it would otherwise hold+ and retry while this process restarts.+ """+ await self._bot.shutdown()diff --git a/core/switch_core/bridges/collaboration/telegram/commands.py b/core/switch_core/bridges/collaboration/telegram/commands.pynew file mode 100644index 000000000..ddcce34a1--- /dev/null+++ b/core/switch_core/bridges/collaboration/telegram/commands.py@@ -0,0 +1,36 @@+"""The in-room command set, as Telegram's `/` menu publishes it.++Its own module because two things publish it: a self-registered bridge for its+own bot, and the distributed app's client for the one bot every tenant shares.+"""++from __future__ import annotations++import re++from telegram import BotCommand++from switch_core.bridges.agent.commands import COMMANDS++# Telegram will only register a command spelled in these characters, and caps a+# description at 256. A name it rejects is left out of the menu rather than+# taking the whole call down.+_TELEGRAM_COMMAND_RE = re.compile(r"[a-z0-9_-]{1,32}")+_MAX_COMMAND_DESCRIPTION = 256+++def command_menu() -> list[BotCommand]:+ """Every visible command, hyphens spelled as underscores.++ Telegram only accepts `[a-z0-9_]` in a registered command, so the+ hyphenated names are published in their underscore spelling —+ `/invite_agent` — and the adapter's command parser accepts either.+ """+ return [+ BotCommand(+ command=command.name.replace("-", "_"),+ description=command.description[:_MAX_COMMAND_DESCRIPTION],+ )+ for command in COMMANDS+ if not command.hidden and _TELEGRAM_COMMAND_RE.fullmatch(command.name)+ ]diff --git a/core/switch_core/bridges/collaboration/telegram/install.py b/core/switch_core/bridges/collaboration/telegram/install.pynew file mode 100644index 000000000..564250073--- /dev/null+++ b/core/switch_core/bridges/collaboration/telegram/install.py@@ -0,0 +1,592 @@+"""Installing the distributed Telegram app into a customer's chats.++The counterpart to `TELEGRAM_SETUP.md`'s self-registered bot, and a different+bot from it. See `docs/old/bridges/TELEGRAM_DISTRIBUTED_APP.md` for the design.++Telegram has no OAuth, so the install half of `MessagingAppInstaller` is mostly+absent here. What stands in for it is a **claim**: the link Switch hands out is+`t.me/<bot>?startgroup=<state>`, and adding the bot through it makes Telegram+post `/start@<bot> <state>` into the chat. A channel sends no `/start`, so a+channel admin posts `/connect <state>` instead. Either arrives as an ordinary+webhook event, and `claim_of_event` is what reads it.++The webhook half is Telegram's own and simpler than Slack's: no body signature,+only a secret Telegram echoes back in a header, which `setWebhook` gave it.+"""++from __future__ import annotations++import asyncio+import hmac+import json+import logging+from collections.abc import Awaitable, Callable, Mapping+from typing import Any, ClassVar++from telegram import InlineKeyboardButton, InlineKeyboardMarkup+from telegram.error import BadRequest, Forbidden, TelegramError++from switch_core.bridges.collaboration.install import (+ ClaimAnswer,+ ClaimantMayNotConnect,+ ClaimDecision,+ ClaimOutcome,+ ClaimProposal,+ ClaimRefusal,+ InboundWebhook,+ InstallClaim,+ InstallGrant,+ MessagingAppInstaller,+ MessagingInstallError,+ WebhookAuthenticityError,+ WebhookEndpoint,+ WebhookPayloadError,+)+from switch_core.bridges.collaboration.telegram.app_client import TelegramAppClient++logger = logging.getLogger(__name__)++#: The header Telegram carries `setWebhook`'s `secret_token` back in.+SECRET_TOKEN_HEADER = "X-Telegram-Bot-Api-Secret-Token"++#: The commands that carry a claim: Telegram's own handshake for a group added+#: through the link, and the one a channel admin types.+_CLAIM_COMMANDS = frozenset({"start", "connect"})++#: The name the tenant's one Telegram bridge is registered under.+_BRIDGE_NAME = "Telegram"++#: What Telegram says, refusing `leaveChat`, when the bot is already out of+#: the chat. Other refusals leave it in, so only these count as having left.+_ALREADY_OUT = ("chat not found", "not a member", "was kicked")++_REMOVED_STATUSES = frozenset({"left", "kicked"})+_PRESENT_STATUSES = frozenset({"member", "administrator"})+#: Who may connect a group: the people Telegram lets decide for it.+_ADMIN_STATUSES = frozenset({"creator", "administrator"})+#: Chats the bot being added to is never answered in.+_UNANSWERED_ADDS = frozenset({"private", "channel"})++#: How long an unclaimed add waits before saying so. Adding the bot through a+#: Switch link sends the add and the claim a moment apart, possibly delivered+#: out of order; the notice is only for an add no claim follows.+UNCLAIMED_NOTICE_GRACE = 10.0++UNCLAIMED_NOTICE = (+ "This chat isn't connected to Switch, so nothing said here reaches an "+ "agent. To connect it, add the bot with the link from Switch, or post "+ "/connect followed by a code from Switch."+)++#: What a refused claim is told, per reason. Nothing here names the tenant that+#: holds an already-connected chat, or says one exists beyond "connected".+CLAIM_REFUSED: dict[ClaimRefusal, str] = {+ "expired": (+ "That link or code has expired or was already used. Get a new one from "+ "Switch and try again."+ ),+ "unrecognised": (+ "That isn't a code from this Switch. Get a new link or code from "+ "Switch and try again."+ ),+ "already_connected": (+ "This chat is already connected to Switch. To connect it somewhere "+ "else, disconnect it in Switch first."+ ),+ "not_permitted": (+ "Only an admin can connect the first chat to Switch. Ask an admin to "+ "connect one, then try again."+ ),+ "not_chat_admin": (+ "Only an admin of this group can connect it to Switch. Ask a group "+ "admin to add the bot with your link, or to post the /connect code."+ ),+}++#: The prefixes of a proposal's two buttons, each followed by `:<state>`. One+#: letter each, because Telegram allows 64 bytes of callback data and the+#: compact state is 61 characters. Distinct from the bridge's own (`sw`, `sx`),+#: so neither reads the other's presses.+CONNECT_PREFIX = "c"+CANCEL_PREFIX = "x"+_DECISIONS: dict[str, ClaimDecision] = {+ CONNECT_PREFIX: "connect",+ CANCEL_PREFIX: "cancel",+}++#: What a proposal says. Plain text: the organisation's name is the tenant's+#: to choose and is not escaped for markup.+PROPOSAL = (+ "Connect this chat to Switch?\n\n"+ "Organisation: {organisation}\n"+ "Requested by: {requested_by}\n\n"+ "An admin of this chat needs to choose. If you don't recognise the "+ "organisation or the person, choose Cancel."+)++#: What a proposal is edited to once answered.+ANSWERED: dict[ClaimOutcome, str] = {+ "connected": "Connected to Switch.",+ "cancelled": "Not connected to Switch. The bot is leaving this chat.",+ "expired": CLAIM_REFUSED["expired"],+ "unrecognised": CLAIM_REFUSED["unrecognised"],+ "already_connected": CLAIM_REFUSED["already_connected"],+ "not_permitted": CLAIM_REFUSED["not_permitted"],+ "not_chat_admin": CLAIM_REFUSED["not_chat_admin"],+}++#: The alert a press from someone who is not an admin gets. The proposal stays+#: for an admin to answer.+NOT_AN_ADMIN_ALERT = "Only an admin of this chat can choose."++DIRECT_MESSAGE_REPLY = (+ "👋 Direct messages to this bot aren't routed to anyone. Connect a group "+ "or channel from Switch, then mention an agent there."+)+++def _as_dict(value: object) -> dict[str, Any] | None:+ return value if isinstance(value, dict) else None+++def _message_of(payload: Mapping[str, object]) -> dict[str, Any] | None:+ """The message an update carries, if it carries one.++ A group's message and a channel's post are the same object under two keys;+ a button press carries the message the button was on.+ """+ for key in ("message", "channel_post"):+ message = _as_dict(payload.get(key))+ if message is not None:+ return message+ callback = _as_dict(payload.get("callback_query"))+ if callback is not None:+ return _as_dict(callback.get("message"))+ return None+++def _claimant_of(message: dict[str, Any], chat: dict[str, Any]) -> str | None:+ """Who posted `message`: the chat itself for a channel or an anonymous admin."""+ if chat.get("type") == "channel":+ return str(chat["id"])+ sender = _as_dict(message.get("sender_chat")) or _as_dict(message.get("from"))+ if sender is None or sender.get("id") is None:+ return None+ return str(sender["id"])+++def is_connect_press(data: str) -> bool:+ """Whether a button press is a proposal's Connect, which the bridge the+ chat now belongs to receives as its join."""+ prefix, separator, token = data.partition(":")+ return prefix == CONNECT_PREFIX and bool(separator) and bool(token)+++def _grant_for(chat: dict[str, Any]) -> InstallGrant:+ return InstallGrant(+ external_workspace_id=str(chat["id"]),+ workspace_name=_BRIDGE_NAME,+ bot_token=None,+ scopes="",+ platform_data={},+ )+++def _chat_of(payload: Mapping[str, object]) -> dict[str, Any] | None:+ member = _as_dict(payload.get("my_chat_member"))+ if member is not None:+ return _as_dict(member.get("chat"))+ message = _message_of(payload)+ return _as_dict(message.get("chat")) if message is not None else None+++class TelegramAppInstaller(MessagingAppInstaller):+ platform: ClassVar[str] = "telegram"+ # Every update goes to the one URL `setWebhook` names.+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]] = frozenset({"events"})+ state_format = "compact"+ installs_by_claim = True+ # With Group Privacy off the bot hears everything in every chat it is in,+ # claimed or not.+ expects_unowned_events = True++ def __init__(self, *, client: TelegramAppClient, webhook_secret: str) -> None:+ self._client = client+ self._webhook_secret = webhook_secret.encode()+ # Chats with a proposal waiting for an answer, which are unowned but+ # not to be told so. In memory: the app runs on one pod, and a restart+ # only risks a needless notice.+ self._proposed: set[str] = set()++ def authorize_url(self, *, state: str, redirect_uri: str) -> str:+ """The link that adds the bot to a group and claims it.++ `redirect_uri` is unused: nothing redirects. Telegram opens the chat+ picker, adds the bot, and posts the state into the chat it was added to.+ """+ return f"https://t.me/{self._client.bot_username}?startgroup={state}"++ def bot_handle(self) -> str:+ """`@username`, typed in full: Telegram's search does not find a bot+ by part of its username."""+ return f"@{self._client.bot_username}"++ async def redeem(self, *, code: str, redirect_uri: str) -> InstallGrant:+ raise MessagingInstallError(+ "Telegram has no OAuth leg; a Telegram install is claimed from a chat"+ )++ async def revoke(self, *, bot_token: str) -> None:+ raise MessagingInstallError(+ "a Telegram install holds no token of its own to revoke"+ )++ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:+ """Compare the echoed secret, in constant time.++ The whole of Telegram's authenticity story: it signs nothing, so a post+ without the secret is indistinguishable from anyone who found the URL.+ """+ presented = next(+ (+ value+ for name, value in headers.items()+ if name.lower() == SECRET_TOKEN_HEADER.lower()+ ),+ None,+ )+ if presented is None:+ raise WebhookAuthenticityError("the Telegram secret-token header is absent")+ if not hmac.compare_digest(presented.encode(), self._webhook_secret):+ raise WebhookAuthenticityError("the Telegram secret token does not match")++ def parse_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:+ """One update. `update_id` is what receipts deduplicate retries by.++ Telegram says nothing about how often it has retried, so the attempt+ count is always zero; a retry is still caught by its `update_id`.+ """+ if endpoint != "events":+ raise WebhookPayloadError(+ f"Telegram delivers every update to /events, not /{endpoint}"+ )+ try:+ payload = json.loads(body)+ except ValueError as exc:+ raise WebhookPayloadError("a Telegram update is not JSON") from exc+ if not isinstance(payload, dict) or not isinstance(+ payload.get("update_id"), int+ ):+ raise WebhookPayloadError("a Telegram update carries no update_id")+ return [+ InboundWebhook(+ envelope_type=endpoint,+ payload=payload,+ handshake=None,+ external_event_id=str(payload["update_id"]),+ delivery_attempt=0,+ answers_inline=False,+ )+ ]++ def workspace_of_event(self, payload: Mapping[str, object]) -> str:+ """The chat an update belongs to.++ For the first message of a chat that has just become a supergroup,+ that is the chat it *was*. Its new id is owned by nobody until the+ install row follows it, and the old id is how the event finds the+ tenant that has to do the following.+ """+ message = _message_of(payload)+ if message is not None and message.get("migrate_from_chat_id") is not None:+ return str(message["migrate_from_chat_id"])+ chat = _chat_of(payload)+ if chat is None or chat.get("id") is None:+ raise WebhookPayloadError("a Telegram update names no chat")+ return str(chat["id"])++ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:+ """The bot leaving or being removed from a chat ends that chat's install.++ `my_chat_member` is only ever about the bot itself, so its new status is+ the whole answer.+ """+ member = _as_dict(payload.get("my_chat_member"))+ if member is None:+ return None+ status = (_as_dict(member.get("new_chat_member")) or {}).get("status")+ if status not in _REMOVED_STATUSES:+ return None+ return f"the bot was removed from the chat ({status})"++ def claim_of_event(self, payload: Mapping[str, object]) -> InstallClaim | None:+ """`/start <state>` or `/connect <state>` in a group or channel.++ A private chat never claims anything: it has no tenant to belong to,+ and account linking by DM is a separate, deferred feature. A command+ addressed to a different bot — `/start@otherbot …`, which a bot with+ privacy off also sees — is not ours to read.++ The claimant is whoever posted it. A channel's posts, and an anonymous+ admin's messages in a group, are posted as the chat itself, so they+ name the chat; only its admins can post that way.+ """+ message = _message_of(payload)+ if message is None:+ return None+ chat = _as_dict(message.get("chat"))+ if chat is None or chat.get("type") == "private" or chat.get("id") is None:+ return None+ text = message.get("text")+ if not isinstance(text, str) or not text.startswith("/"):+ return None++ parts = text.split()+ if len(parts) != 2:+ return None+ command, _, addressee = parts[0][1:].partition("@")+ if command not in _CLAIM_COMMANDS:+ return None+ if addressee and addressee.lower() != self._client.bot_username.lower():+ return None+ claimant = _claimant_of(message, chat)+ if claimant is None:+ return None++ return InstallClaim(token=parts[1], grant=_grant_for(chat), claimant=claimant)++ def answer_of_event(self, payload: Mapping[str, object]) -> ClaimAnswer | None:+ """A press of a proposal's Connect or Cancel.++ Who answered is who pressed, which Telegram fills in and the button+ cannot: the state in it says what is being answered, never by whom.+ """+ press = _as_dict(payload.get("callback_query"))+ if press is None:+ return None+ data = press.get("data")+ if not isinstance(data, str):+ return None+ prefix, separator, token = data.partition(":")+ decision = _DECISIONS.get(prefix)+ if decision is None or not separator or not token:+ return None+ chat = _as_dict((_as_dict(press.get("message")) or {}).get("chat"))+ presser = _as_dict(press.get("from"))+ if (+ chat is None+ or chat.get("type") == "private"+ or chat.get("id") is None+ or presser is None+ or presser.get("id") is None+ ):+ return None+ return ClaimAnswer(+ claim=InstallClaim(+ token=token, grant=_grant_for(chat), claimant=str(presser["id"])+ ),+ decision=decision,+ press=press,+ )++ async def require_claimant_may_connect(self, claim: InstallClaim) -> None:+ """Refuse a claim unless a creator or admin of the chat posted it.++ Telegram checks nothing here: `/start <code>` and `/connect <code>` are+ ordinary messages anyone in the group can send, and the link's chat+ picker offers every group where the person may add members. Telegram+ refusing the lookup, as it does for an id that is no one in the chat,+ is a refusal too; any other failure is raised to be retried, never let+ through unchecked.+ """+ chat_id = claim.grant.external_workspace_id+ if claim.claimant == chat_id:+ return+ try:+ member = await self._client.bot.get_chat_member(+ chat_id=int(chat_id), user_id=int(claim.claimant)+ )+ except (BadRequest, Forbidden) as refused:+ raise ClaimantMayNotConnect(+ f"Telegram would not say whether {claim.claimant} is an admin of "+ f"chat {chat_id}: {refused}"+ ) from refused+ except TelegramError as failure:+ raise MessagingInstallError(+ f"Could not ask Telegram whether {claim.claimant} is an admin of "+ f"chat {chat_id}: {failure}"+ ) from failure+ if member.status not in _ADMIN_STATUSES:+ raise ClaimantMayNotConnect(+ f"{claim.claimant} is a {member.status} of chat {chat_id}, not "+ "one of its admins"+ )++ async def release(self, *, external_workspace_id: str) -> None:+ """Leave the chat. There is no per-install token to revoke instead.++ A chat the bot is already out of answers with a refusal saying so,+ which is the outcome wanted. Any other failure, a refusal included,+ leaves the bot in the chat and is raised so the disconnect fails and+ can be tried again.+ """+ try:+ await self._client.bot.leave_chat(chat_id=int(external_workspace_id))+ except (BadRequest, Forbidden) as refused:+ if not any(phrase in str(refused).lower() for phrase in _ALREADY_OUT):+ raise MessagingInstallError(+ f"Telegram refused to let the bot leave chat "+ f"{external_workspace_id}: {refused}. It is still in the "+ "chat; disconnect again to retry."+ ) from refused+ logger.warning(+ "The Telegram app was already out of chat %s: %s",+ external_workspace_id,+ refused,+ )+ except TelegramError as failure:+ raise MessagingInstallError(+ f"Telegram did not let the bot leave chat {external_workspace_id}: "+ f"{failure}. It is still in the chat; disconnect again to retry."+ ) from failure++ def migration_of_event(+ self, payload: Mapping[str, object]+ ) -> tuple[str, str] | None:+ """Read either of the two notices Telegram sends for a supergroup."""+ message = _message_of(payload)+ if message is None:+ return None+ chat = _as_dict(message.get("chat")) or {}+ if message.get("migrate_to_chat_id") is not None:+ return str(chat.get("id")), str(message["migrate_to_chat_id"])+ if message.get("migrate_from_chat_id") is not None:+ return str(message["migrate_from_chat_id"]), str(chat.get("id"))+ return None++ async def on_claim_refused(+ self, *, claim: InstallClaim, reason: ClaimRefusal+ ) -> None:+ await self._client.bot.send_message(+ chat_id=int(claim.grant.external_workspace_id),+ text=CLAIM_REFUSED[reason],+ )++ async def on_claim_proposed(+ self, *, claim: InstallClaim, proposal: ClaimProposal+ ) -> None:+ """Post the proposal, with Connect and Cancel, in the chat."""+ chat_id = claim.grant.external_workspace_id+ self._proposed.add(chat_id)+ await self._client.bot.send_message(+ chat_id=int(chat_id),+ text=PROPOSAL.format(+ organisation=proposal.organisation,+ requested_by=proposal.requested_by,+ ),+ reply_markup=InlineKeyboardMarkup(+ [+ [+ InlineKeyboardButton(+ "Connect", callback_data=f"{CONNECT_PREFIX}:{claim.token}"+ ),+ InlineKeyboardButton(+ "Cancel", callback_data=f"{CANCEL_PREFIX}:{claim.token}"+ ),+ ]+ ]+ ),+ )++ async def on_claim_answered(+ self, *, answer: ClaimAnswer, outcome: ClaimOutcome+ ) -> None:+ """Close the press, and the proposal unless someone else must answer it.++ A press from someone who is not an admin leaves the proposal for one+ who is, and only the presser hears why. Every other outcome replaces+ the proposal with how it ended, so its buttons cannot be pressed again,+ and a cancelled one takes the bot out of the chat.+ """+ chat_id = answer.claim.grant.external_workspace_id+ query_id = str(answer.press.get("id") or "")+ if outcome == "not_chat_admin":+ await self._client.bot.answer_callback_query(+ callback_query_id=query_id, text=NOT_AN_ADMIN_ALERT, show_alert=True+ )+ return+ self._proposed.discard(chat_id)+ await self._client.bot.answer_callback_query(callback_query_id=query_id)+ message = _as_dict(answer.press.get("message")) or {}+ if message.get("message_id") is not None:+ await self._client.bot.edit_message_text(+ chat_id=int(chat_id),+ message_id=int(message["message_id"]),+ text=ANSWERED[outcome],+ )+ if outcome == "cancelled":+ await self.release(external_workspace_id=chat_id)++ async def on_unowned_event(+ self,+ *,+ workspace_id: str,+ payload: Mapping[str, object],+ still_unowned: Callable[[], Awaitable[bool]],+ ) -> None:+ """Say how to connect an unclaimed chat, or that DMs reach no one.++ The bot being added to a group is answered once, after the grace+ period, and only if no claim has landed by then. A channel is not+ answered: every channel is added unclaimed, because its code can only+ be posted once the bot is in, and a notice there would reach every+ subscriber. A direct message is answered each time, as the+ self-registered bridge answers one. Everything else from an unowned+ chat gets no answer: the bot stays, and stays quiet.+ """+ member = _as_dict(payload.get("my_chat_member"))+ if member is not None:+ chat = _as_dict(member.get("chat")) or {}+ status = (_as_dict(member.get("new_chat_member")) or {}).get("status")+ if status not in _PRESENT_STATUSES or chat.get("type") in _UNANSWERED_ADDS:+ return+ await asyncio.sleep(UNCLAIMED_NOTICE_GRACE)+ if workspace_id not in self._proposed and await still_unowned():+ await self._client.bot.send_message(+ chat_id=int(workspace_id), text=UNCLAIMED_NOTICE+ )+ return++ message = _as_dict(payload.get("message"))+ sent_in = _as_dict(message.get("chat")) if message is not None else None+ if sent_in is not None and sent_in.get("type") == "private":+ await self._client.bot.send_message(+ chat_id=int(workspace_id), text=DIRECT_MESSAGE_REPLY+ )++ def shared_connection(self) -> TelegramAppClient:+ """The shared bot, once it has said who it is.++ Handed to a bridge before its first update is dispatched, so a bridge+ created by a claim at runtime has a bot to answer with.+ """+ self._client.require_ready()+ return self._client++ def connection_config(self, grant: InstallGrant) -> dict[str, object]:+ """No token and no username: both come from the shared bot."""+ return {"event_delivery": "shared"}diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 0262071ce..b71d8f57c 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -523,6 +523,16 @@ class SwitchConfig(BaseSettings):# them — would otherwise see several apps of the same name.teams_app_name: str = "Agent Switch"+ # The distributed Telegram app (`TELEGRAM_DISTRIBUTED_APP.md`): one bot per+ # deployment whose groups a customer claims with a link, as opposed to the+ # self-registered bot whose token an operator pastes in. Two values: the+ # bot's token, which like Discord's is deployment config rather than per+ # install, and the secret Telegram echoes back on every webhook, which is+ # the whole of what proves an update came from Telegram. Setting both is+ # what enables it; setting one is a startup error.+ telegram_app_bot_token: str | None = None+ telegram_app_webhook_secret: str | None = None+# Public origin (scheme + host, no path) that a messaging platform reaches# Switch on: the base of the OAuth redirect and of the three event URLs# under `/messaging`, and the one registered with the app.@@ -1373,6 +1383,55 @@ class SwitchConfig(BaseSettings):)return self+ @model_validator(mode="after")+ def _validate_telegram_app(self) -> "SwitchConfig":+ required = (self.telegram_app_bot_token, self.telegram_app_webhook_secret)+ set_count = sum(1 for value in required if value)+ if 0 < set_count < len(required):+ raise ValueError(+ "Partial distributed Telegram app config: set both "+ "TELEGRAM_APP_BOT_TOKEN and TELEGRAM_APP_WEBHOOK_SECRET, or "+ "neither."+ )+ if not set_count:+ return self+ assert self.telegram_app_bot_token is not None+ assert self.telegram_app_webhook_secret is not None+ if not re.fullmatch(r"\d+:[A-Za-z0-9_-]+", self.telegram_app_bot_token):+ raise ValueError(+ "TELEGRAM_APP_BOT_TOKEN is not shaped like a Telegram bot token "+ "(<bot id>:<secret>, as BotFather issues it)."+ )+ # Telegram's own rule for `secret_token`. Checked here because+ # `setWebhook` would refuse it in a background task at boot, where the+ # failure reads as Telegram being unreachable rather than as this.+ if not re.fullmatch(r"[A-Za-z0-9_-]{1,256}", self.telegram_app_webhook_secret):+ raise ValueError(+ "TELEGRAM_APP_WEBHOOK_SECRET must be at most 256 characters of "+ "A-Z, a-z, 0-9, _ and -, which is all Telegram accepts."+ )+ # Ours: the same floor as every other secret this deployment chooses,+ # since it is the whole of what proves an update came from Telegram.+ if len(self.telegram_app_webhook_secret) < 32:+ raise ValueError(+ "TELEGRAM_APP_WEBHOOK_SECRET must be at least 32 characters, got "+ f"{len(self.telegram_app_webhook_secret)}. `openssl rand -hex 32` "+ "makes one."+ )+ if not self.messaging_public_url:+ raise ValueError(+ "A distributed Telegram app is configured but "+ "MESSAGING_PUBLIC_URL is not. Telegram delivers every update "+ "to a webhook built from it."+ )+ port = urlsplit(self.messaging_public_url).port+ if port not in (None, 443, 80, 88, 8443):+ raise ValueError(+ "Telegram delivers webhooks only to ports 443, 80, 88 and 8443, "+ f"and MESSAGING_PUBLIC_URL names port {port}."+ )+ return self+@propertydef gateway_oidc_enabled(self) -> bool:return bool(diff --git a/core/switch_core/db/stores/messaging_install_store.py b/core/switch_core/db/stores/messaging_install_store.pyindex 19c5091a4..e3046c7b3 100644--- a/core/switch_core/db/stores/messaging_install_store.py+++ b/core/switch_core/db/stores/messaging_install_store.py@@ -3,13 +3,15 @@ from __future__ import annotationsfrom collections.abc import Mappingfrom datetime import UTC, datetime, timedelta-from sqlalchemy import select, update+from sqlalchemy import and_, select, updatefrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.db.models import (+ CollaborationBridge,MessagingInstall,MessagingInstallState,+ Room,require_tenant_id,)@@ -23,7 +25,7 @@ STATE_TTL = timedelta(minutes=10)#: covers, so it is also the answer to "who holds this workspace".INSTALL_ACTIVE = "active"-#: Ended here, by someone who decided to. The bridge is gone with it.+#: Ended here, by someone who decided to.INSTALL_DISCONNECTED = "disconnected"#: Ended there: the platform told us the app was removed or its token killed.@@ -230,21 +232,159 @@ class MessagingInstallStore:) -> MessagingInstall | None:"""The live install a bridge was built for, if it was built for one.+ For a bridge with one install, which is every OAuth install's. A+ claim-based platform's bridge serves many and answers with the first;+ `list_for_bridge` has all of them.+ """+ installs = await self.list_for_bridge(session, bridge_id=bridge_id)+ return installs[0] if installs else None++ async def names_for_tenant(+ self, session: AsyncSession+ ) -> list[tuple[str, str, str | None, str | None]]:+ """`(install id, platform, room name, bridge name)` for every install.++ The room is the one bridged to the install's own workspace id, which+ only a chat claimed as a room has; the bridge is the one the install+ still points at. An ended install has let go of both, so both are+ `None`. Which of the two a person calls the install is the caller's.+ """+ result = await session.execute(+ select(+ MessagingInstall.id,+ MessagingInstall.platform,+ Room.name,+ CollaborationBridge.display_name,+ )+ .outerjoin(+ Room,+ and_(+ Room.bridge_id == MessagingInstall.bridge_id,+ Room.external_channel_id == MessagingInstall.external_workspace_id,+ ),+ )+ .outerjoin(+ CollaborationBridge,+ CollaborationBridge.id == MessagingInstall.bridge_id,+ )+ )+ return [(row[0], row[1], row[2], row[3]) for row in result.all()]++ async def rooms_for_tenant(self, session: AsyncSession) -> dict[str, Room]:+ """The room bridged to each install's own workspace id, by install id.++ The same pairing `names_for_tenant` names: only a chat claimed as a+ room has one, and only while the install still points at its bridge.+ Read for who may see and disconnect a chat, which is whoever may read+ and write its room.+ """+ result = await session.execute(+ select(MessagingInstall.id, Room).join(+ Room,+ and_(+ Room.bridge_id == MessagingInstall.bridge_id,+ Room.external_channel_id == MessagingInstall.external_workspace_id,+ ),+ )+ )+ return {row[0]: row[1] for row in result.all()}++ async def list_for_bridge(+ self, session: AsyncSession, *, bridge_id: str+ ) -> list[MessagingInstall]:+ """The live installs a bridge serves, if it was built for any.+Asked from the other direction than the rest of this store, and bysomething that does not otherwise know installs exist: the bridgedelete endpoint, which has to refuse rather than tear down a bridgewhose credential is a token nobody here has revoked.+ A list because a bridge may serve many: a Slack install has a bridge+ of its own, but every Telegram chat a tenant claims is served by the+ tenant's one Telegram bridge.+Live installs only. An ended one has already released its pointer, so arow matching here is always a bridge that is still somebody's install."""result = await session.execute(- select(MessagingInstall).where(+ select(MessagingInstall)+ .where(MessagingInstall.bridge_id == bridge_id,MessagingInstall.status == INSTALL_ACTIVE,)+ .order_by(MessagingInstall.installed_at, MessagingInstall.id))- return result.scalars().one_or_none()+ return list(result.scalars())++ async def bridge_for_platform(+ self, session: AsyncSession, *, platform: str+ ) -> str | None:+ """The bridge the bound tenant's claimed chats of `platform` share.++ Only meaningful for a platform whose installs share one bridge per+ tenant — one claimed by event rather than by OAuth. Read from the+ bridge rather than from its installs, because it outlives its chats:+ it is the tenant's connection, and stays until an admin deletes it.+ `None` means there is none, so the next claim creates it.++ A self-registered bridge of the same platform polls its own bot and+ says so in its config, so `event_delivery` is what tells the two apart.+ It is read here rather than in the query because the config is+ encrypted at rest.++ Two distinct bridges is a broken invariant rather than a choice to make+ here: routing a new chat to either would split one tenant's identities+ across two bridges without anyone having decided to.+ """+ result = await session.execute(+ select(CollaborationBridge).where(CollaborationBridge.type == platform)+ )+ bridge_ids = [+ bridge.id+ for bridge in result.scalars()+ if (bridge.connection_config or {}).get("event_delivery") == "shared"+ ]+ if len(bridge_ids) > 1:+ raise RuntimeError(+ f"this organisation has {len(bridge_ids)} shared {platform} "+ f"bridges ({', '.join(sorted(bridge_ids))}); it must have one"+ )+ return bridge_ids[0] if bridge_ids else None++ async def move_workspace(+ self,+ session: AsyncSession,+ *,+ platform: str,+ from_workspace_id: str,+ to_workspace_id: str,+ ) -> MessagingInstall | None:+ """Re-key the bound tenant's live install when its workspace changes id.++ `None` when there is nothing at the old id, which is the ordinary+ second half of a migration the platform announces twice: whichever+ notice arrives second finds the row already moved.++ The new id is still subject to the workspace uniqueness index, so a+ new id somebody else holds fails here rather than producing a+ workspace with two owners.+ """+ install = await self.get_for_workspace(+ session, platform=platform, external_workspace_id=from_workspace_id+ )+ if install is None:+ return None+ install.external_workspace_id = to_workspace_id+ try:+ await session.flush()+ except IntegrityError as exc:+ if "uq_messaging_installs_workspace" not in str(exc.orig):+ raise+ raise MessagingInstallClaimedError(+ f"the {platform} workspace {from_workspace_id} became "+ f"{to_workspace_id}, which another install already holds"+ ) from exc+ return installasync def get(self, session: AsyncSession, *, install_id: str) -> MessagingInstall:"""One of the bound tenant's installs, by id, or raise."""@@ -318,6 +458,20 @@ class MessagingInstallStore:await session.flush()return install+ async def list_active(+ self, session: AsyncSession, *, platform: str+ ) -> list[MessagingInstall]:+ """The bound tenant's live installs of one platform, oldest first."""+ result = await session.execute(+ select(MessagingInstall)+ .where(+ MessagingInstall.platform == platform,+ MessagingInstall.status == INSTALL_ACTIVE,+ )+ .order_by(MessagingInstall.installed_at, MessagingInstall.id)+ )+ return list(result.scalars())+async def end(self, session: AsyncSession, *, install_id: str, status: str) -> MessagingInstall:@@ -353,9 +507,9 @@ class MessagingInstallStore:# the dump. Keeping the row is the record; keeping the secret is not# part of it.install.encrypted_bot_token = None- # And the pointer goes with it, because the bridge is about to. The- # foreign key has no `ON DELETE`, so a row still naming the bridge is- # what would refuse its deletion.+ # And the pointer goes with it: an ended install no longer uses the+ # bridge, and the foreign key has no `ON DELETE`, so a row still naming+ # it is what would refuse the bridge's deletion.install.bridge_id = Noneawait session.flush()return installdiff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex d9576df80..5960ccfa6 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -29,6 +29,7 @@ from switch_core.db.audit import AuditAction, record_audit_eventfrom switch_core.db.models import (CollaborationBridge,ExternalUser,+ MessagingInstall,User,require_tenant_id,)@@ -148,6 +149,69 @@ def _places_app_in_teams(return adapter is not None and adapter.places_app_in_teams+#: What each platform calls the place its app is installed into, and how it+#: is named to a person.+_INSTALL_PLACES: dict[str, tuple[str, str]] = {+ "slack": ("Slack", "workspace"),+ "discord": ("Discord", "server"),+ "teams": ("Microsoft Teams", "organisation"),+ "telegram": ("Telegram", "chat"),+}+++def _installed_refusal(installs: list[MessagingInstall]) -> str:+ """Why a bridge live installs still use cannot be deleted, and what to do.++ Said in what disconnecting does on the platform, which differs for each:+ only Slack has a token to revoke, Discord's bot stays in the server, and a+ Telegram chat leaves its connection behind to be deleted here afterwards.+ Keyed by the platform's name rather than asked of its installer, which is+ gone on a deployment whose app credentials were removed — exactly when the+ installs left behind still have to protect their bridges.+ """+ platform = installs[0].platform+ label, noun = _INSTALL_PLACES.get(platform, (platform, "workspace"))+ where = (+ f"{label} {noun} {installs[0].external_workspace_id}"+ if len(installs) == 1+ else f"{len(installs)} {label} {noun}s"+ )+ them = "it" if len(installs) == 1 else "them"+ if platform == "telegram":+ return (+ f"The Switch bot is still in {where} through this connection. "+ f"Disconnect {them} under Installed apps first, then delete the "+ "connection here."+ )+ if platform == "discord":+ return (+ f"This connection was created by adding the Switch bot to {where}. "+ f"Disconnect {them} under Installed apps instead: that stops Switch "+ "using the server and removes this connection. The bot stays in the "+ "server until you remove it in Discord."+ )+ if platform == "slack":+ effect = "revokes Switch's token at Slack and removes this connection"+ elif platform == "teams":+ effect = "takes the app out of every team and removes this connection"+ else:+ effect = "removes this connection"+ return (+ f"This connection was created by installing the Switch app into "+ f"{where}. Disconnect {them} under Installed apps instead: that "+ f"{effect}."+ )+++def _channel_ids_refused(+ bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService+) -> str | None:+ """Why the bridge binds no channel by id. None when it is not running,+ where binding is refused anyway for want of a bridge to bind to."""+ adapter = collab_lifecycle.get_adapter(bridge_id)+ return None if adapter is None else adapter.channel_ids_refused()++async def _detail(bridge: CollaborationBridge,*,@@ -175,6 +239,7 @@ async def _detail(bridge.type),channel_creation_enabled=bridge.channel_creation_enabled,+ channel_ids_refused=_channel_ids_refused(bridge.id, collab_lifecycle),directory_search_supported=collab_lifecycle.supports_directory_search(bridge.type),@@ -676,10 +741,7 @@ async def _require_directory_account(except NotImplementedError as e:raise HTTPException(status_code=501,- detail=(- f"{e} — so this account cannot be linked before it has been "- "seen. Send one message in the workspace, then link it."- ),+ detail=f"{e}. This account cannot be linked until Switch has seen it.",) from eexcept DirectorySearchBusy as e:raise _search_busy(e) from e@@ -895,18 +957,9 @@ async def delete_bridge(# real foreign key — so this delete would destroy every room on the bridge# and *then* be refused by Postgres, leaving the bridge running, the rooms# gone and a live credential nobody has revoked.- install = await install_store.get_for_bridge(session, bridge_id=bridge_id)- if install is not None:- raise HTTPException(- status_code=409,- detail=(- f"This connection was created by installing the Switch app into "- f"{install.platform} workspace {install.external_workspace_id}, so "- "it cannot be deleted here — the app would stay installed and its "- "token would stay valid. Disconnect the app instead, which revokes "- "the token at the platform and then removes this connection."- ),- )+ installs = await install_store.list_for_bridge(session, bridge_id=bridge_id)+ if installs:+ raise HTTPException(status_code=409, detail=_installed_refusal(installs))rooms = await room_store.get_by_bridge(session, bridge_id)tenant_id = bridge.tenant_iddiff --git a/core/switch_core/gateway/messaging_installs.py b/core/switch_core/gateway/messaging_installs.pyindex e2341a206..bce1f9e5c 100644--- a/core/switch_core/gateway/messaging_installs.py+++ b/core/switch_core/gateway/messaging_installs.py@@ -5,6 +5,18 @@ begin in a top-level browser window on the platform's own domain, and aredirect from an XHR the operator's dashboard made would be followed by theXHR, not by the window. Handing the URL back and letting the page navigate isthe shape that works.++**Who may act depends on how the platform installs.** An OAuth install creates+a connection, and connections are a tenant admin's. A claim-based platform+(Telegram) shares one connection per organisation across every chat claimed, so+one chat is a room: an admin connects the first, which turns the platform on,+and after that members connect chats, and see and disconnect the ones whose+room they may read and write — every chat, until someone makes its room+private. Turning it off again is deleting that connection, which is an+admin's. Every check for an OAuth+platform is the tenant-admin check `require_tenant_admin` makes, read here as+`get_tenant_is_admin` so a route that serves both kinds of platform can tell+them apart."""from __future__ import annotations@@ -17,12 +29,13 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core.authz import Action, Principal, canfrom switch_core.bridges.collaboration.install import MessagingInstallErrorfrom switch_core.bridges.collaboration.install_service import MessagingInstallServicefrom switch_core.db.audit import AuditAction, record_audit_event-from switch_core.db.models import User, require_tenant_id+from switch_core.db.models import MessagingInstall, Room, User, require_tenant_idfrom switch_core.db.stores.messaging_install_store import MessagingInstallNotFound-from switch_core.gateway.auth import require_tenant_admin+from switch_core.gateway.auth import get_current_user, get_tenant_is_adminfrom switch_core.gateway.dependencies import get_install_service, get_sessionlogger = logging.getLogger(__name__)@@ -34,8 +47,32 @@ class InstallStart(BaseModel):authorize_url: str+class ClaimablePlatform(BaseModel):+ """A claim-based platform, and what this caller may do with it.++ Computed here because the split between an admin's action and a member's+ depends on whether the organisation has a connection yet.+ """++ platform: str+ # The organisation already has a connection, so a chat is a room.+ connected: bool+ can_add_chat: bool++class InstallablePlatforms(BaseModel):+ # OAuth platforms, offered to a tenant admin only.platforms: list[str]+ claimable: list[ClaimablePlatform]+++class ClaimStart(BaseModel):+ """A link that adds the bot to a group and claims it, its bare code, and+ the bot's handle for adding it to a channel by hand."""++ url: str+ code: str+ bot_handle: strclass InstalledApp(BaseModel):@@ -51,6 +88,10 @@ class InstalledApp(BaseModel):id: strplatform: strexternal_workspace_id: str+ # What a person calls it — a chat's room, or the workspace an OAuth+ # install came from — while it still has one. An ended install is shown by+ # its id.+ name: str | Nonestatus: strscopes: strbridge_id: str | None@@ -84,23 +125,102 @@ def _require_installs(return service+def _require_tenant_admin(is_admin: bool) -> None:+ if not is_admin:+ raise HTTPException(status_code=403, detail="Tenant admin access required")+++def _by_claim(service: MessagingInstallService, platform: str) -> bool:+ try:+ return service.installer(platform).installs_by_claim+ except MessagingInstallError as failure:+ raise HTTPException(status_code=404, detail=str(failure)) from failure++@router.get("")async def installable_platforms(+ session: Annotated[AsyncSession, Depends(get_session)],service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- _user: Annotated[User, Depends(require_tenant_admin)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> InstallablePlatforms:+ if service is None:+ return InstallablePlatforms(platforms=[], claimable=[])+ oauth = [p for p in service.platforms() if not _by_claim(service, p)]+ claimable = []+ for platform in service.platforms():+ if not _by_claim(service, platform):+ continue+ connected = await service.platform_connected(session, platform=platform)+ claimable.append(+ ClaimablePlatform(+ platform=platform,+ connected=connected,+ can_add_chat=connected or is_admin,+ )+ )return InstallablePlatforms(- platforms=[] if service is None else service.platforms()+ platforms=oauth if is_admin else [], claimable=claimable)[email protected]("/{platform}/claim")+async def begin_claim(+ platform: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ service: Annotated[MessagingInstallService | None, Depends(get_install_service)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+) -> ClaimStart:+ """A link that connects a chat by adding the bot to it, and its code.++ Checked here as well as when the claim is redeemed, so a member told they+ cannot turn the platform on hears it now rather than from the bot. The+ redemption check is the one that holds: whether a connection exists can+ change in the ten minutes between the two.+ """+ installs = _require_installs(service)+ if not _by_claim(installs, platform):+ raise HTTPException(+ status_code=404, detail=f"{platform} is not installed by claiming a chat"+ )+ if not is_admin and not await installs.platform_connected(+ session, platform=platform+ ):+ raise HTTPException(+ status_code=403,+ detail=(+ f"Connecting the first {platform} chat turns {platform} on for "+ "this organisation, which only an admin can do."+ ),+ )+ try:+ link = await installs.begin_claim(session, platform=platform, user_id=user.id)+ except MessagingInstallError as failure:+ # The shared bot has not connected yet, so there is no link to offer.+ raise HTTPException(status_code=503, detail=str(failure)) from failure+ await record_audit_event(+ session,+ tenant_id=require_tenant_id(),+ actor_user_id=user.id,+ action=AuditAction.MESSAGING_INSTALL_STARTED,+ target_type="messaging_install",+ target_id=None,+ details={"platform": platform},+ )+ await session.commit()+ logger.info("Started a %s claim for user %s", platform, user.id)+ return ClaimStart(url=link.url, code=link.code, bot_handle=link.bot_handle)++@router.post("/{platform}/install")async def begin_install(platform: str,session: Annotated[AsyncSession, Depends(get_session)],service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> InstallStart:+ _require_tenant_admin(is_admin)try:authorize_url = await _require_installs(service).begin(session, platform=platform, user_id=user.id@@ -126,7 +246,8 @@ async def begin_install(async def list_installs(session: Annotated[AsyncSession, Depends(get_session)],service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- _user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> InstalledApps:"""This organisation's installs, ended ones included.@@ -137,20 +258,60 @@ async def list_installs("""if service is None:return InstalledApps(installs=[])+ # A member sees the chats of claim-based platforms, which are rooms, and+ # not the OAuth workspaces, which are an admin's. Only the chats whose room+ # they may read: a private room's chat would otherwise name it to them.+ names = await service.install_names(session)+ rooms = await service.chat_rooms(session)+ principal = Principal(user.id, is_admin)return InstalledApps(installs=[- InstalledApp.model_validate(install, from_attributes=True)+ _installed(install, names.get(install.id))for install in await service.list_installs(session)+ if is_admin+ or (+ _installs_by_claim_or_gone(service, install.platform)+ and _room_allows(principal, "read", rooms.get(install.id))+ )])+def _room_allows(principal: Principal, action: Action, room: Room | None) -> bool:+ """Whether a chat's room lets `principal` act on it; a chat with no room+ left (an ended one) has nothing private to show."""+ return room is None or can(principal, action, room)+++def _installed(install: MessagingInstall, name: str | None) -> InstalledApp:+ return InstalledApp(+ id=install.id,+ platform=install.platform,+ external_workspace_id=install.external_workspace_id,+ name=name,+ status=install.status,+ scopes=install.scopes,+ bridge_id=install.bridge_id,+ installed_at=install.installed_at,+ ended_at=install.ended_at,+ )+++def _installs_by_claim_or_gone(service: MessagingInstallService, platform: str) -> bool:+ """Whether a platform is claim-based; False once its installer is gone."""+ try:+ return service.installer(platform).installs_by_claim+ except MessagingInstallError:+ return False++@router.delete("/installs/{install_id}")async def disconnect_install(install_id: str,session: Annotated[AsyncSession, Depends(get_session)],service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> InstalledApp:"""End an install: revoke the credential, remove the bridge, free the workspace.@@ -162,10 +323,36 @@ async def disconnect_install(the disconnect in the audit log.**Rooms that used the bridge become internal-only**, which is why this is a- delete an operator has to ask for rather than anything inferred.+ delete an admin has to ask for rather than anything inferred. One chat+ of a claim-based platform is a room, and whoever may write to that room+ may disconnect it, the same as moving the room onto another bridge."""+ installs = _require_installs(service)+ try:+ platform = await installs.install_platform(session, install_id=install_id)+ except MessagingInstallNotFound as missing:+ raise HTTPException(status_code=404, detail=str(missing)) from missing+ if not _installs_by_claim_or_gone(installs, platform):+ _require_tenant_admin(is_admin)+ else:+ room = (await installs.chat_rooms(session)).get(install_id)+ if room is None:+ # Nobody's room covers it any more, so it is the tenant's to decide.+ if not is_admin:+ raise HTTPException(+ status_code=403,+ detail="Only an admin can disconnect a chat whose room is gone.",+ )+ elif not can(Principal(user.id, is_admin), "write", room):+ raise HTTPException(+ status_code=403,+ detail=(+ "Only someone who can change this chat's room in Switch, its "+ "owner or an admin, can disconnect it."+ ),+ )try:- ended = await _require_installs(service).disconnect(+ ended = await installs.disconnect(tenant_id=require_tenant_id(), install_id=install_id)except MessagingInstallNotFound as missing:@@ -190,4 +377,5 @@ async def disconnect_install()await session.commit()logger.info("User %s disconnected messaging install %s", user.id, install_id)- return InstalledApp.model_validate(ended, from_attributes=True)+ # Ended, so it has let go of whatever it was called.+ return _installed(ended, None)diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 671cc7ad1..fc61335ea 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -533,6 +533,10 @@ class BridgeDetail(BaseModel):# switch you can flip, the second a disabled switch with a reason.channel_creation_supported: bool = Truechannel_creation_enabled: bool = True+ # Why no existing channel can be bound to a room by id on this connection,+ # or None when one can. Set for a connection whose chats arrive only one+ # way, so the room form can say so instead of offering the choice.+ channel_ids_refused: str | None = None# Whether the platform has a user directory Switch can search. False where# the only people Switch can name are those who have spoken to it, which# makes "pick yourself from the directory" an empty list on a connectiondiff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 53f39ef78..cb9217a59 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -12,6 +12,7 @@ from functools import partialfrom pathlib import Pathimport httpx+import telegramimport uvicornfrom alembic import command as alembic_commandfrom alembic.config import Config as AlembicConfig@@ -50,7 +51,7 @@ from switch_core.bridges.agent.server_connectors.opencode.connector import (OpenCodeConnectionConfig,OpenCodeConnector,)-from switch_core.bridges.collaboration.adapter import SupportsSharedConnection+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,DiscordConnectionConfig,@@ -58,7 +59,11 @@ from switch_core.bridges.collaboration.discord.adapter import (from switch_core.bridges.collaboration.discord.connection import DiscordConnectionfrom switch_core.bridges.collaboration.discord.gateway import DiscordGatewayClientfrom switch_core.bridges.collaboration.discord.install import DiscordAppInstaller-from switch_core.bridges.collaboration.install import MessagingInstallerRegistry+from switch_core.bridges.collaboration.install import (+ MessagingInstallerRegistry,+ events_path,+ public_url,+)from switch_core.bridges.collaboration.install_routes import (create_messaging_install_router,)@@ -88,6 +93,11 @@ from 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 TelegramAppInstallerfrom switch_core.bridges.resource.service import ResourceServicefrom switch_core.clients.actor import Actor, AgentActor, HumanActor, SystemActorfrom switch_core.clients.agent_consumer import AgentConsumer@@ -792,6 +802,45 @@ async def run(config: SwitchConfig) -> None:teams_app = _distributed_teams_app(config, installers, collab_lifecycle)+ async def _attach_shared_telegram_bridges(client: TelegramAppClient) -> None:+ # The bridges that started before the bot was up; each one starting+ # after is attached as it starts, by `_attach_to_telegram_if_live`.+ for adapter in collab_lifecycle.iter_adapters():+ if isinstance(adapter, TelegramAdapter):+ adapter.attach_shared_connection(client)++ telegram_app: TelegramAppClient | None = None+ if config.telegram_app_bot_token:+ assert config.telegram_app_webhook_secret is not None+ assert config.messaging_public_url is not None+ telegram_app = TelegramAppClient(+ bot=telegram.Bot(config.telegram_app_bot_token),+ webhook_url=public_url(+ config.messaging_public_url, events_path("telegram")+ ),+ webhook_secret=config.telegram_app_webhook_secret,+ on_connected=_attach_shared_telegram_bridges,+ )+ collab_lifecycle.reserve_resource(+ bot_resource(telegram_app.bot_id), "Telegram app bot"+ )+ shared_bot = telegram_app++ def _attach_to_telegram_if_live(adapter: PlatformAdapter) -> None:+ # Not before the bot is up, for the reason the Discord client+ # gives: the bridge would start against a bot it cannot use, and+ # the attach on connect would then be a no-op.+ if shared_bot.is_live and isinstance(adapter, TelegramAdapter):+ adapter.attach_shared_connection(shared_bot)++ collab_lifecycle.add_bridge_starting_listener(_attach_to_telegram_if_live)+ installers.register(+ TelegramAppInstaller(+ client=telegram_app,+ webhook_secret=config.telegram_app_webhook_secret,+ )+ )+install_service: MessagingInstallService | None = Noneif installers.platforms():assert config.messaging_public_url is not None@@ -801,6 +850,8 @@ async def run(config: SwitchConfig) -> None:receipts=MessagingEventReceiptStore(),installers=installers,lifecycle=collab_lifecycle,+ users=user_store,+ rooms=room_service,public_origin=config.messaging_public_url,keyring=config.keyring,)@@ -1013,11 +1064,12 @@ async def run(config: SwitchConfig) -> None:async def _attach_shared_discord_bridges(connection: DiscordConnection,) -> None:- # Runs once the socket is up: hand it to every already-running bridge- # that rides a shared connection. Platform-agnostic — narrowed by- # capability, not by knowing which platform that is.+ # Runs once the socket is up: hand it to every already-running+ # Discord bridge. Narrowed to Discord's adapter and not only to the+ # capability, because Telegram's shared bridges have it too and+ # must be handed Telegram's bot, not this socket.for adapter in collab_lifecycle.iter_adapters():- if isinstance(adapter, SupportsSharedConnection):+ if isinstance(adapter, DiscordAdapter):adapter.attach_shared_connection(connection)discord_gateway = DiscordGatewayClient(@@ -1032,6 +1084,20 @@ async def run(config: SwitchConfig) -> None:discord_gateway.start_with_retry(), name="discord-gateway-start")+ # The shared Telegram bot: `getMe`, then `setWebhook`. In the background+ # for the reason the Discord connection is — an unreachable Telegram must+ # not hold up a boot serving everything else.+ telegram_app_task: asyncio.Task[None] | None = None+ if telegram_app is not None:++ async def _run_telegram_app(client: TelegramAppClient) -> None:+ await client.start_with_retry()+ await client.watch_delivery()++ telegram_app_task = asyncio.create_task(+ _run_telegram_app(telegram_app), name="telegram-app"+ )+# Backfill room membership: system clients (e.g. the admin client) added# after a room was created, and any agent whose invite did not land. The# just-started clients accept the invites on their first sync.@@ -1069,6 +1135,8 @@ async def run(config: SwitchConfig) -> None:discord_gateway,discord_gateway_task,teams_app,+ telegram_app,+ telegram_app_task,)),)@@ -1552,6 +1620,10 @@ async def _shutdown(discord_gateway: DiscordGatewayClient | None,discord_gateway_task: asyncio.Task[None] | None,teams_app: TeamsSharedApp | None,+ # Defaulted so a caller with no Telegram app, as the shutdown-order tests+ # are, need not name it; `run` always passes both.+ telegram_app: TelegramAppClient | None = None,+ telegram_app_task: asyncio.Task[None] | None = None,) -> None:logger.info("Shutting down...")# Before uvicorn closes the sockets, so the controllers' are recorded as@@ -1573,6 +1645,15 @@ async def _shutdown(# After the bridges, which borrow its HTTP client until they stop.if teams_app is not None:await teams_app.aclose()++ if telegram_app_task is not None:+ telegram_app_task.cancel()+ try:+ await telegram_app_task+ except asyncio.CancelledError:+ pass+ if telegram_app is not None:+ await telegram_app.stop()await client_lifecycle.stop_all()await provisioning.close()diff --git a/core/switch_core/observability/catalogue.py b/core/switch_core/observability/catalogue.pyindex 85c19df77..c416b39a7 100644--- a/core/switch_core/observability/catalogue.py+++ b/core/switch_core/observability/catalogue.py@@ -364,6 +364,32 @@ BRIDGE_CALL_DURATION = _spec("platform","kind",)+BRIDGE_THROTTLE_HELD = _spec(+ "switch.bridge.throttle.held",+ "histogram",+ "s",+ "How long a publication was held back by a platform rate limit, recorded "+ "each time one is refused for it. `delivery` separates a bot one tenant "+ "owns from a shared app bot, where one tenant's burst holds back every "+ "other tenant's — a rising `shared` reading is what says per-tenant "+ "fairness has started to matter.",+ "platform",+ "delivery",+ bounds=(1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),+)++# ── Messaging app installs ───────────────────────────────────────────────────+MESSAGING_EVENTS_IGNORED = _spec(+ "switch.messaging.events_ignored",+ "sum",+ "{event}",+ "Authentic webhook events from a workspace nobody installed the app into, "+ "on a platform where that is routine — a shared bot sitting in chats "+ "nobody claimed. Counted rather than logged so that the drops which are "+ "real losses, each reported where its cause is known, are not buried.",+ "platform",+ "reason",+)# ── Agent protocol ───────────────────────────────────────────────────────────# The agent-side counterpart to the delivery counters above. An event that@@ -574,6 +600,8 @@ CATALOGUE: dict[str, MetricSpec] = {BRIDGE_ERRORS,BRIDGES_RUNNING,BRIDGE_CALL_DURATION,+ BRIDGE_THROTTLE_HELD,+ MESSAGING_EVENTS_IGNORED,AGENT_EVENTS_DROPPED,AGENT_BUFFER_SCANNED,AGENT_BUFFER_SCAN_DURATION,diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex cdb385892..a0ee2d0d3 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -1238,6 +1238,32 @@ class RoomService:logger.info("Unlinked bridge from room %s", room_id)+ async def unlink_bridge_channel(+ self, bridge_id: str, external_channel_id: str+ ) -> None:+ """Detach the one room a bridge holds for an external channel.++ For a bridge that serves many installs and loses one: the rest of its+ rooms stay bridged, and this one becomes internal-only, as every room+ does when a whole bridge goes. A channel with no room — never+ provisioned, or already deleted — has nothing to detach.++ Reads under the tenant bound by the caller, like the rest of this+ service's unscoped sessions.+ """+ async with self._session_factory() as session:+ room = await self._room_store.get_by_external_channel(+ session, bridge_id, external_channel_id+ )+ if room is None:+ logger.info(+ "Bridge %s holds no room for channel %s; nothing to detach",+ bridge_id,+ external_channel_id,+ )+ return+ await self.unlink_bridge_from_room(room.id)+async def change_bridge(self,room_id: str,diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex 22fb9e274..6db331f83 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -46,6 +46,9 @@ from switch_core.bridges.agent.protocol.types import (RegistrationResult,TaskProtocolConfig,)+from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)from switch_core.bridges.resource.service import ResourceServicefrom switch_core.clients.actor import Actor, AgentActor, HumanActorfrom switch_core.clients.agent_consumer import AgentConsumer@@ -63,6 +66,7 @@ from switch_core.db.runtime_role import grant_runtime_role, verify_restricted_rofrom switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStorefrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.document_store import DocumentStore@@ -85,6 +89,8 @@ from switch_core.messages.notify import MessageListenerfrom switch_core.provisioning import Provisioningfrom switch_core.provisioning.postgres import PostgresProvisioningfrom switch_core.room_service import RoomService+from switch_core.session_activity.listener import AgentSessionActivityListener+from switch_core.session_activity.service import AgentSessionActivityServicefrom switch_core.telemetry.messages import MessageTelemetryfrom switch_core.telemetry.service import TelemetryServicefrom switch_core.telemetry.sink import NullSink@@ -262,8 +268,12 @@ class Harness:event_buffer: EventBuffer,owner_id: str,session_factory: object,+ collab_lifecycle: object,) -> None:self.protocol = protocol+ # The real lifecycle under the `collaboration_bridges` marker, the+ # no-bridges stand-in otherwise.+ self.collab_lifecycle = collab_lifecycleself.room_service = room_serviceself.client_lifecycle = client_lifecycleself.room_store = room_store@@ -491,7 +501,9 @@ async def session_env(switch_stack: StackInfo) -> AsyncIterator[SessionEnv]:@pytest_asyncio.fixture(loop_scope="session")-async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:+async def harness(+ session_env: SessionEnv, request: pytest.FixtureRequest+) -> AsyncIterator[Harness]:# Truncation is DDL-adjacent and crosses every tenant, so it runs as# the owner. Nothing the application does goes through this engine.await _truncate_all(session_env.owner_engine)@@ -533,7 +545,13 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:# events and client registrations never leak across tests.event_buffer = EventBuffer(sequence_base=0)connections = AgentConnectionRegistry()- collab_lifecycle = _NoBridges()+ collab_lifecycle: object = _NoBridges()+ real_bridges = (+ request.node.get_closest_marker("collaboration_bridges") is not None+ )+ session_activity_listener = AgentSessionActivityListener(+ lambda: create_unpooled_engine(config)+ )# The transport's wake-up path: rows are announced over LISTEN/NOTIFY, so# nothing is delivered to a client until this connection is up.@@ -631,6 +649,25 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:tenants_isolated=True,)+ if real_bridges:+ collab_lifecycle = CollaborationBridgeLifecycleService(+ bridge_store=session_env.bridge_store,+ external_user_store=session_env.external_user_store,+ bridge_message_map_store=BridgeMessageMapStore(),+ room_store=session_env.room_store,+ agent_store=session_env.agent_store,+ client_store=session_env.client_store,+ client_lifecycle=client_lifecycle,+ room_service=None, # type: ignore[arg-type] # set below+ provisioning=provisioning,+ session_factory=session_factory,+ config=config,+ client_factory=client_factory,+ session_activity_listener=session_activity_listener,+ session_activity_service=AgentSessionActivityService(session_factory),+ connections=connections,+ )+room_service = RoomService(provisioning=provisioning,room_store=session_env.room_store,@@ -642,6 +679,8 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:session_factory=session_factory,room_cache=room_cache,)+ if isinstance(collab_lifecycle, CollaborationBridgeLifecycleService):+ collab_lifecycle._room_service = room_serviceprotocol = AgentCore(agent_store=session_env.agent_store,@@ -676,10 +715,13 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:event_buffer=event_buffer,owner_id=owner_id,session_factory=session_factory,+ collab_lifecycle=collab_lifecycle,)try:yield hfinally:+ if isinstance(collab_lifecycle, CollaborationBridgeLifecycleService):+ await collab_lifecycle.stop_all()# Stop the agents' receive loops before the next test truncates, so none# is mid-query against a table being cleared.await client_lifecycle.stop_all()diff --git a/core/tests/integration/test_telegram_isolation_e2e.py b/core/tests/integration/test_telegram_isolation_e2e.pynew file mode 100644index 000000000..e9e2262d6--- /dev/null+++ b/core/tests/integration/test_telegram_isolation_e2e.py@@ -0,0 +1,467 @@+"""Two organisations on the one shared Telegram bot, and nothing crossing.++The distributed Telegram app is one bot serving every organisation, so its+isolation rests on routing each update by the chat it came from and on+row-level security below that — not on anything Telegram separates. This drives+the genuine path end to end: the webhook route, the real installer, the claim+against Postgres under the restricted role, the real bridge lifecycle, the+shared-delivery adapter and `CollaborationCore`, down to the rows a bridged message+writes. Only Telegram itself is faked.++What it asserts is what the design's isolation argument promises: each chat's+messages reach its own organisation's room and appear nowhere in the other's —+not in its messages, its receipts or its seen users — the same Telegram user+in both is two people, one per organisation; a chat nobody claimed and a+direct message leave no row at all and no trace of what they said; and a lookup+that answers the wrong organisation is a miss rather than a cross-tenant read.+"""++from __future__ import annotations++import asyncio+import uuid+from collections.abc import Awaitable, Callable+from typing import Any++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy import select++from switch_core.bridges.collaboration import install_service as install_service_module+from switch_core.bridges.collaboration.install import MessagingInstallerRegistry+from switch_core.bridges.collaboration.install_routes import (+ create_messaging_install_router,+)+from switch_core.bridges.collaboration.install_service import MessagingInstallService+from switch_core.bridges.collaboration.telegram.adapter import (+ TelegramAdapter,+ TelegramConnectionConfig,+)+from switch_core.bridges.collaboration.telegram.app_client import TelegramAppClient+from switch_core.bridges.collaboration.telegram.install import (+ DIRECT_MESSAGE_REPLY,+ SECRET_TOKEN_HEADER,+ TelegramAppInstaller,+)+from switch_core.db.models import (+ TENANT_ZERO_ID,+ ExternalUser,+ Message,+ MessagingEventReceipt,+ Room,+ Tenant,+ TenantMember,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.messaging_event_store import MessagingEventReceiptStore+from switch_core.db.stores.messaging_install_store import MessagingInstallStore+from switch_core.db.stores.user_store import UserStore+from switch_core.room_service import RoomCreateConfig+from switch_core.tenant_context import tenant_scope+from tests.conftest import TEST_KEYRING+from tests.integration.conftest import Harness+from tests.switch_core.bridges.collaboration.test_telegram_adapter import _FakeBot++pytestmark = [+ pytest.mark.integration,+ pytest.mark.collaboration_bridges,+ pytest.mark.asyncio(loop_scope="session"),+]++_ORIGIN = "https://switch.example"+_SECRET = "placeholder-webhook-secret"+_BOT_ID = 555000+_USERNAME = "switch_app_bot"+_ADA = {"id": 4242, "is_bot": False, "first_name": "Ada", "username": "ada"}+++class _Me:+ id = _BOT_ID+ username = _USERNAME+ can_read_all_group_messages = True+ can_join_groups = True+++class _AppBot(_FakeBot):+ """The adapter tests' fake Telegram, plus what the shared client asks of it."""++ token = f"{_BOT_ID}:placeholder-token"++ async def initialize(self) -> None:+ return None++ async def get_me(self) -> _Me:+ return _Me()++ async def set_webhook(self, **kwargs: Any) -> bool:+ return True++ async def shutdown(self) -> None:+ return None+++class _World:+ """One deployment's shared bot, its install service and its webhook."""++ def __init__(self, harness: Harness, bot: _AppBot, client: httpx.AsyncClient):+ self.harness = harness+ self.bot = bot+ self.client = client+ self._update_id = 0++ async def post(self, **update: Any) -> int:+ self._update_id += 1+ response = await self.client.post(+ "/messaging/telegram/events",+ json={"update_id": self._update_id, **update},+ headers={SECRET_TOKEN_HEADER: _SECRET},+ )+ return response.status_code++ @property+ def last_update_id(self) -> int:+ return self._update_id+++async def _world(harness: Harness) -> tuple[_World, MessagingInstallService]:+ lifecycle: Any = harness.collab_lifecycle+ lifecycle.register_adapter("telegram", TelegramAdapter, TelegramConnectionConfig)++ async def attach(client: TelegramAppClient) -> None:+ for adapter in lifecycle.iter_adapters():+ if isinstance(adapter, TelegramAdapter):+ adapter.attach_shared_connection(client)++ bot = _AppBot()+ app_client = TelegramAppClient(+ bot=bot, # type: ignore[arg-type]+ webhook_url=f"{_ORIGIN}/messaging/telegram/events",+ webhook_secret=_SECRET,+ on_connected=attach,+ )+ await app_client.start()+ installers = MessagingInstallerRegistry()+ installers.register(TelegramAppInstaller(client=app_client, webhook_secret=_SECRET))+ service = MessagingInstallService(+ session_factory=harness.session_factory, # type: ignore[arg-type]+ store=MessagingInstallStore(),+ receipts=MessagingEventReceiptStore(),+ installers=installers,+ lifecycle=lifecycle,+ users=UserStore(),+ rooms=harness.room_service,+ public_origin=_ORIGIN,+ keyring=TEST_KEYRING,+ )+ app = FastAPI()+ app.include_router(create_messaging_install_router(service))+ client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url=_ORIGIN)+ return _World(harness, bot, client), service+++async def _organisation(harness: Harness) -> tuple[str, str]:+ """A tenant with one admin, created the way onboarding creates one.++ The tenant row is written by a session bound to its own id, which is the+ one binding `tenants`' policy accepts (see `create_tenant`).+ """+ factory: Any = harness.session_factory+ tenant_id = str(uuid.uuid4())+ suffix = tenant_id[:8]+ async with factory() as session:+ admin = User(+ name=f"admin-{suffix}", email=f"admin-{suffix}@example.test", role="user"+ )+ session.add(admin)+ await session.commit()+ admin_id = admin.id+ with tenant_scope(tenant_id):+ async with tenant_session(factory, tenant_id) as session:+ session.add(+ Tenant(id=tenant_id, slug=f"org-{suffix}", name=f"Org {suffix}")+ )+ await session.flush()+ session.add(+ TenantMember(tenant_id=tenant_id, user_id=admin_id, role="admin")+ )+ await session.commit()+ return tenant_id, admin_id+++async def _claim_code(+ harness: Harness, service: MessagingInstallService, tenant_id: str, admin_id: str+) -> str:+ factory: Any = harness.session_factory+ with tenant_scope(tenant_id):+ async with tenant_session(factory, tenant_id) as session:+ link = await service.begin_claim(+ session, platform="telegram", user_id=admin_id+ )+ await session.commit()+ return link.code+++def _group(chat_id: int, title: str) -> dict[str, Any]:+ return {"id": chat_id, "type": "supergroup", "title": title}+++def _message(+ chat: dict[str, Any], text: str, sender: dict[str, Any] = _ADA+) -> dict[str, Any]:+ return {+ "message_id": abs(hash(text)) % 100000,+ "date": 0,+ "chat": chat,+ "from": sender,+ "text": text,+ }+++async def _eventually(+ check: Callable[[], Awaitable[bool]], what: str, timeout: float = 15.0+) -> None:+ deadline = asyncio.get_running_loop().time() + timeout+ while asyncio.get_running_loop().time() < deadline:+ if await check():+ return+ await asyncio.sleep(0.1)+ raise AssertionError(f"timed out waiting for {what}")+++async def _scoped(harness: Harness, tenant_id: str, query: Any) -> list[Any]:+ factory: Any = harness.session_factory+ with tenant_scope(tenant_id):+ async with tenant_session(factory, tenant_id) as session:+ return list((await session.execute(query)).scalars())+++async def _bodies(harness: Harness, tenant_id: str) -> list[str]:+ return [+ body+ for body in await _scoped(harness, tenant_id, select(Message.body))+ if body is not None+ ]+++async def _connect(+ world: _World,+ service: MessagingInstallService,+ tenant_id: str,+ admin_id: str,+ chat: dict[str, Any],+) -> None:+ code = await _claim_code(world.harness, service, tenant_id, admin_id)+ # The bot being added arrives first, while the chat still belongs to nobody.+ await world.post(+ my_chat_member={+ "chat": chat,+ "from": _ADA,+ "date": 0,+ "old_chat_member": {+ "status": "left",+ "user": {"id": _BOT_ID, "is_bot": True, "first_name": "Switch"},+ },+ "new_chat_member": {+ "status": "member",+ "user": {"id": _BOT_ID, "is_bot": True, "first_name": "Switch"},+ },+ }+ )+ # Then the claim, which only asks; then an admin's Connect. Telegram+ # retries a 503 — a bridge still starting — so this does too, as Telegram+ # would.+ assert await world.post(message=_message(chat, f"/start@{_USERNAME} {code}")) == 200+ for _ in range(10):+ status = await world.post(+ callback_query={+ "id": f"press-{chat['id']}",+ "chat_instance": "1",+ "from": _ADA,+ "data": f"c:{code}",+ "message": _message(chat, "Connect this chat to Switch?"),+ }+ )+ if status == 200:+ break+ await asyncio.sleep(0.2)++ async def has_room() -> bool:+ rooms = await _scoped(+ world.harness,+ tenant_id,+ select(Room).where(Room.external_channel_id == str(chat["id"])),+ )+ return len(rooms) == 1++ await _eventually(has_room, f"the room for chat {chat['id']}")+++async def test_two_organisations_share_the_bot_and_nothing_else(+ harness: Harness, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ world, service = await _world(harness)+ tenant_a, admin_a = await _organisation(harness)+ tenant_b, admin_b = await _organisation(harness)+ chat_a, chat_b = _group(-1001111, "Acme"), _group(-1002222, "Globex")++ await _connect(world, service, tenant_a, admin_a, chat_a)+ await _connect(world, service, tenant_b, admin_b, chat_b)++ # ── Each chat's messages reach its own organisation, and only it ──────────+ await world.post(message=_message(chat_a, "hello from acme"))+ await world.post(message=_message(chat_b, "hello from globex"))++ async def both_arrived() -> bool:+ return "hello from acme" in await _bodies(+ harness, tenant_a+ ) and "hello from globex" in await _bodies(harness, tenant_b)++ await _eventually(both_arrived, "both messages to be bridged")+ assert "hello from globex" not in await _bodies(harness, tenant_a)+ assert "hello from acme" not in await _bodies(harness, tenant_b)++ a_rooms = await _scoped(harness, tenant_a, select(Room.external_channel_id))+ b_rooms = await _scoped(harness, tenant_b, select(Room.external_channel_id))+ assert str(chat_b["id"]) not in a_rooms+ assert str(chat_a["id"]) not in b_rooms++ # ── Receipts are kept by the organisation that received the update ───────+ a_receipts = set(+ await _scoped(+ harness, tenant_a, select(MessagingEventReceipt.external_event_id)+ )+ )+ b_receipts = set(+ await _scoped(+ harness, tenant_b, select(MessagingEventReceipt.external_event_id)+ )+ )+ assert a_receipts and b_receipts+ assert not a_receipts & b_receipts++ # ── One Telegram user in both chats is two people, one per organisation ──+ a_ada = await _scoped(+ harness,+ tenant_a,+ select(ExternalUser).where(ExternalUser.external_user_id == "4242"),+ )+ b_ada = await _scoped(+ harness,+ tenant_b,+ select(ExternalUser).where(ExternalUser.external_user_id == "4242"),+ )+ assert len(a_ada) == 1 and len(b_ada) == 1+ assert a_ada[0].bridge_id != b_ada[0].bridge_id+ assert a_ada[0].client_id != b_ada[0].client_id++ # ── A chat nobody claimed, and a direct message, leave no trace ──────────+ receipts_before = a_receipts | b_receipts+ with caplog.at_level("DEBUG"):+ assert (+ await world.post(+ message=_message(_group(-1003333, "Nobody"), "unclaimed secret")+ )+ == 200+ )+ assert (+ await world.post(+ message=_message(+ {"id": 4242, "type": "private", "first_name": "Ada"}, "dm secret"+ )+ )+ == 200+ )+ for tenant in (tenant_a, tenant_b, TENANT_ZERO_ID):+ bodies = await _bodies(harness, tenant)+ assert "unclaimed secret" not in bodies and "dm secret" not in bodies+ receipts_after = set(+ await _scoped(+ harness, tenant_a, select(MessagingEventReceipt.external_event_id)+ )+ ) | set(+ await _scoped(+ harness, tenant_b, select(MessagingEventReceipt.external_event_id)+ )+ )+ assert receipts_after == receipts_before+ assert "unclaimed secret" not in caplog.text+ assert "dm secret" not in caplog.text+ assert {"chat_id": 4242, "text": DIRECT_MESSAGE_REPLY} in [+ {"chat_id": m["chat_id"], "text": m["text"]} for m in world.bot.messages+ ]++ # ── A lookup that answers the wrong organisation is a miss ───────────────+ async def wrong(*_: Any) -> str:+ return tenant_b++ monkeypatch.setattr(install_service_module, "tenant_of_messaging_install", wrong)+ assert await world.post(message=_message(chat_a, "misrouted")) == 200+ await asyncio.sleep(0.5)+ assert "misrouted" not in await _bodies(harness, tenant_a)+ assert "misrouted" not in await _bodies(harness, tenant_b)++ await world.client.aclose()+++async def test_a_room_cannot_be_bound_to_another_organisations_chat(+ harness: Harness,+) -> None:+ """Binding a room to a chat by id decides where its agents' messages are+ posted, and the shared bot is in every organisation's chats — so the bot+ being able to see a chat says nothing about whose it is. A room bound to a+ chat another organisation claimed would post into it as the shared bot."""+ world, service = await _world(harness)+ tenant_a, admin_a = await _organisation(harness)+ tenant_b, admin_b = await _organisation(harness)+ chat_a, chat_b = _group(-1004444, "Acme"), _group(-1005555, "Globex")+ await _connect(world, service, tenant_a, admin_a, chat_a)+ await _connect(world, service, tenant_b, admin_b, chat_b)+ (bridge_a,) = await _scoped(+ harness,+ tenant_a,+ select(Room.bridge_id).where(Room.external_channel_id == str(chat_a["id"])),+ )+ sent_before = len(world.bot.messages)++ with tenant_scope(tenant_a), pytest.raises(ValueError):+ await harness.room_service.create_room(+ RoomCreateConfig(+ name="intruder",+ description="",+ bridge_id=bridge_a,+ external_channel_id=str(chat_b["id"]),+ created_by=admin_a,+ owner_id=admin_a,+ )+ )++ assert str(chat_b["id"]) not in await _scoped(+ harness, tenant_a, select(Room.external_channel_id)+ )++ # Nor moved onto the bridge bound to it, which is the other way a room+ # takes a chat id from whoever asks.+ with tenant_scope(tenant_a):+ internal = await harness.room_service.create_room(+ RoomCreateConfig(+ name="internal",+ description="",+ internal_only=True,+ created_by=admin_a,+ owner_id=admin_a,+ )+ )+ with pytest.raises(ValueError):+ await harness.room_service.change_bridge(+ internal.room.id,+ bridge_id=bridge_a,+ external_channel_id=str(chat_b["id"]),+ )++ assert str(chat_b["id"]) not in await _scoped(+ harness, tenant_a, select(Room.external_channel_id)+ )+ assert world.bot.messages[sent_before:] == []+ await world.client.aclose()diff --git a/core/tests/switch_core/bridges/collaboration/test_install_claim.py b/core/tests/switch_core/bridges/collaboration/test_install_claim.pynew file mode 100644index 000000000..33e02a5ad--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_install_claim.py@@ -0,0 +1,1541 @@+"""Installing a workspace from an event, for a platform with no OAuth leg.++Telegram cannot redirect a browser, so its install arrives as a webhook event+carrying a compact signed state. What is only visible here is what differs from+the OAuth install: every claim of one tenant lands on one shared bridge, the+first claim is an admin's and later ones a member's, and two first claims at+once still make one bridge.++Postgres is real because row-level security, the unique index and the advisory+lock are all part of the argument, and a mock has none of them.+"""++from __future__ import annotations++import asyncio+import json+import time+import uuid+from collections.abc import Mapping+from typing import Any, ClassVar+from urllib.parse import parse_qs, urlparse++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy import select+from sqlalchemy.ext.asyncio import async_sessionmaker++from switch_core.bridges.collaboration import install_service as install_service_module+from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.install import (+ ClaimAnswer,+ ClaimantMayNotConnect,+ ClaimProposal,+ InboundWebhook,+ InstallClaim,+ InstallGrant,+ MessagingAppInstaller,+ MessagingInstallerRegistry,+ MessagingInstallError,+ WebhookEndpoint,+)+from switch_core.bridges.collaboration.install_routes import (+ create_messaging_install_router,+)+from switch_core.bridges.collaboration.install_service import (+ InstallClaimNotPermitted,+ MessagingInstallService,+)+from switch_core.bridges.collaboration.install_state import (+ InstallState,+ InstallStateError,+ mint_compact,+)+from switch_core.db.models import (+ AuditEvent,+ Client,+ CollaborationBridge,+ MessagingInstall,+ Tenant,+ TenantMember,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.messaging_event_store import MessagingEventReceiptStore+from switch_core.db.stores.messaging_install_store import (+ INSTALL_ACTIVE,+ MessagingInstallClaimedError,+ MessagingInstallStateError,+ MessagingInstallStore,+)+from switch_core.db.stores.user_store import UserStore+from switch_core.keys import Keyring+from switch_core.observability.catalogue import MESSAGING_EVENTS_IGNORED+from switch_core.observability.metrics import MetricsRegistry, install, uninstall+from switch_core.tenant_context import tenant_scope+from tests.conftest import RLSHarness+from tests.switch_core.bridges.collaboration.test_install_webhook import (+ _RecordingAdapter,+)++pytestmark = pytest.mark.no_ambient_tenant++_KEYRING = Keyring.parse("test:" + "t" * 40, legacy_secret=None)+_ORIGIN = "https://switch.example"+_PLATFORM = "telegram"+++class _ClaimInstaller(MessagingAppInstaller):+ """A platform whose installs arrive as events, the way Telegram's do.++ The payload is a stand-in rather than Telegram's shape: `chat` names the+ workspace and `claim`, when present, carries the token.+ """++ platform: ClassVar[str] = _PLATFORM+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]] = frozenset({"events"})+ state_format = "compact"+ installs_by_claim = True+ expects_unowned_events = True++ def __init__(self) -> None:+ self.connection: object | None = None+ self.not_ready = False+ self.released: list[str] = []+ self.release_error: Exception | None = None+ self.unowned: list[tuple[str, bool]] = []+ self.refused: list[tuple[str, str]] = []+ self.proposed: list[tuple[str, ClaimProposal]] = []+ self.answered: list[tuple[str, str]] = []+ self.claimant_check: Exception | None = None++ async def require_claimant_may_connect(self, claim: InstallClaim) -> None:+ if self.claimant_check is not None:+ raise self.claimant_check++ async def on_claim_refused(self, *, claim: InstallClaim, reason: Any) -> None:+ self.refused.append((claim.grant.external_workspace_id, reason))++ async def on_claim_proposed(+ self, *, claim: InstallClaim, proposal: ClaimProposal+ ) -> None:+ self.proposed.append((claim.grant.external_workspace_id, proposal))++ async def on_claim_answered(self, *, answer: ClaimAnswer, outcome: Any) -> None:+ self.answered.append((answer.claim.grant.external_workspace_id, outcome))++ async def release(self, *, external_workspace_id: str) -> None:+ if self.release_error is not None:+ raise self.release_error+ self.released.append(external_workspace_id)++ def migration_of_event(+ self, payload: Mapping[str, object]+ ) -> tuple[str, str] | None:+ moved = payload.get("migrate")+ if not isinstance(moved, list):+ return None+ return str(moved[0]), str(moved[1])++ async def on_unowned_event(+ self,+ *,+ workspace_id: str,+ payload: Mapping[str, object],+ still_unowned: Any,+ ) -> None:+ self.unowned.append((workspace_id, await still_unowned()))++ def shared_connection(self) -> object | None:+ if self.not_ready:+ raise MessagingInstallError("the shared bot has not connected yet")+ return self.connection++ def authorize_url(self, *, state: str, redirect_uri: str) -> str:+ return f"https://t.me/switch_bot?startgroup={state}"++ async def redeem(self, *, code: str, redirect_uri: str) -> InstallGrant:+ raise AssertionError("a claim-based platform has no code to redeem")++ async def revoke(self, *, bot_token: str) -> None:+ raise AssertionError("a claim-based install holds no token to revoke")++ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:+ return None++ def parse_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:+ return [+ InboundWebhook(+ envelope_type=endpoint,+ payload=json.loads(body),+ handshake=None,+ external_event_id=None,+ delivery_attempt=0,+ answers_inline=False,+ )+ ]++ def workspace_of_event(self, payload: Mapping[str, object]) -> str:+ return str(payload["chat"])++ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:+ return None++ def claim_of_event(self, payload: Mapping[str, object]) -> InstallClaim | None:+ token = payload.get("claim")+ if not isinstance(token, str):+ return None+ return InstallClaim(+ token=token, grant=_grant(str(payload["chat"])), claimant="42"+ )++ def answer_of_event(self, payload: Mapping[str, object]) -> ClaimAnswer | None:+ token = payload.get("answer")+ if not isinstance(token, str):+ return None+ return ClaimAnswer(+ claim=InstallClaim(+ token=token, grant=_grant(str(payload["chat"])), claimant="42"+ ),+ decision="cancel" if payload.get("decision") == "cancel" else "connect",+ press={},+ )++ def connection_config(self, grant: InstallGrant) -> dict[str, object]:+ return {"event_delivery": "shared"}+++def _connect(chat_id: str, token: str) -> dict[str, Any]:+ """An admin's Connect on the proposal a claim with `token` posted."""+ return {"chat": chat_id, "answer": token, "decision": "connect"}+++def _grant(chat_id: str) -> InstallGrant:+ return InstallGrant(+ external_workspace_id=chat_id,+ workspace_name="Telegram",+ bot_token=None,+ scopes="",+ platform_data={},+ )+++class _AttachableAdapter(_RecordingAdapter):+ """A bridge that runs on its platform's shared connection."""++ def __init__(self) -> None:+ super().__init__()+ self.attached: list[object] = []++ def attach_shared_connection(self, connection: object) -> None:+ self.attached.append(connection)++ def set_on_attached(self, callback: Any) -> None:+ return None+++class _FakeLifecycle:+ """Registers real rows, on a plain session like the real lifecycle.++ The real `register` opens its own session and lets the tenant bound around+ the call decide where the row lands, and it does so while `claim` is still+ holding its transaction open — so a fake that wrote nothing, or wrote+ through the caller's session, would not exercise the part that matters.+ """++ def __init__(self, factory: async_sessionmaker, suffix: str) -> None:+ self._factory = factory+ self._suffix = suffix+ self.registered: list[dict[str, object]] = []+ self.adapters: dict[str, PlatformAdapter] = {}+ self.fail_next: Exception | None = None+ self.removed: list[str] = []++ async def register(self, **kwargs: object) -> CollaborationBridge:+ if self.fail_next is not None:+ failure, self.fail_next = self.fail_next, None+ raise failure+ self.registered.append(kwargs)+ async with self._factory() as session:+ client = Client(+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:{self._suffix}",+ display_name=str(kwargs["display_name"]),+ type="collaboration_bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type=str(kwargs["bridge_type"]),+ display_name=str(kwargs["display_name"]),+ connection_config=dict(kwargs["connection_config"]), # type: ignore[call-overload]+ client_id=client.id,+ status="active",+ )+ session.add(bridge)+ await session.flush()+ bridge_id = bridge.id+ await session.commit()+ self.adapters[bridge_id] = _AttachableAdapter()+ return CollaborationBridge(id=bridge_id)++ def get_adapter(self, bridge_id: str) -> PlatformAdapter | None:+ return self.adapters.get(bridge_id)++ def is_connected(self, bridge_id: str) -> bool:+ """Every bridge here is started the moment it exists."""+ return bridge_id in self.adapters++ async def remove(self, bridge_id: str) -> None:+ """Delete the row, on a plain session like the real one."""+ self.removed.append(bridge_id)+ self.adapters.pop(bridge_id, None)+ async with self._factory() as session:+ bridge = await session.get(CollaborationBridge, bridge_id)+ if bridge is not None:+ await session.delete(bridge)+ await session.commit()+++class _RecordingRooms:+ def __init__(self) -> None:+ self.detached: list[tuple[str, str]] = []++ async def unlink_bridge_channel(+ self, bridge_id: str, external_channel_id: str+ ) -> None:+ self.detached.append((bridge_id, external_channel_id))+++class _Fixture:+ def __init__(self) -> None:+ self.tenant_a: str = ""+ self.tenant_b: str = ""+ self.admin_a: str = ""+ self.member_a: str = ""+ self.admin_b: str = ""+ self.suffix: str = ""+ self.lifecycle: _FakeLifecycle+ self.installer: _ClaimInstaller+ self.rooms: _RecordingRooms+ self.service: MessagingInstallService+++async def _fixture(harness: RLSHarness) -> _Fixture:+ fixture = _Fixture()+ fixture.suffix = uuid.uuid4().hex[:8]+ # UUIDs, as every tenant is in production: the compact token carries them+ # as raw bytes.+ fixture.tenant_a = str(uuid.uuid4())+ fixture.tenant_b = str(uuid.uuid4())++ async with harness.owner() as session:+ for tenant_id in (fixture.tenant_a, fixture.tenant_b):+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ users = {}+ for label in ("admin-a", "member-a", "admin-b"):+ user = User(+ name=label, email=f"{label}-{fixture.suffix}@example.test", role="user"+ )+ session.add(user)+ users[label] = user+ await session.flush()+ for label, tenant_id, role in (+ ("admin-a", fixture.tenant_a, "admin"),+ ("member-a", fixture.tenant_a, "member"),+ ("admin-b", fixture.tenant_b, "admin"),+ ):+ session.add(+ TenantMember(tenant_id=tenant_id, user_id=users[label].id, role=role)+ )+ fixture.admin_a = users["admin-a"].id+ fixture.member_a = users["member-a"].id+ fixture.admin_b = users["admin-b"].id+ await session.commit()++ fixture.lifecycle = _FakeLifecycle(harness.restricted, fixture.suffix)+ fixture.rooms = _RecordingRooms()+ installers = MessagingInstallerRegistry()+ fixture.installer = _ClaimInstaller()+ installers.register(fixture.installer)+ fixture.service = MessagingInstallService(+ session_factory=harness.restricted,+ store=MessagingInstallStore(),+ receipts=MessagingEventReceiptStore(),+ installers=installers,+ lifecycle=fixture.lifecycle, # type: ignore[arg-type]+ users=UserStore(),+ rooms=fixture.rooms,+ public_origin=_ORIGIN,+ keyring=_KEYRING,+ )+ return fixture+++async def _link(+ factory: async_sessionmaker, fixture: _Fixture, tenant_id: str, user_id: str+) -> str:+ """Start a claim as `user_id` in `tenant_id` and return the token it minted."""+ async with tenant_session(factory, tenant_id) as session:+ url = await fixture.service.begin(session, platform=_PLATFORM, user_id=user_id)+ await session.commit()+ return parse_qs(urlparse(url).query)["startgroup"][0]+++async def _ask(fixture: _Fixture, token: str, chat_id: str) -> ClaimProposal:+ """Put a claim to its chat, as posting it there does."""+ return await fixture.service.propose(+ platform=_PLATFORM,+ claim=InstallClaim(token=token, grant=_grant(chat_id), claimant="42"),+ )+++async def _claim(fixture: _Fixture, token: str, chat_id: str) -> MessagingInstall:+ """Put a claim to its chat and connect it, as an admin choosing Connect."""+ await _ask(fixture, token, chat_id)+ return await fixture.service.connect(+ platform=_PLATFORM,+ claim=InstallClaim(token=token, grant=_grant(chat_id), claimant="42"),+ )+++async def _active_installs(harness: RLSHarness) -> list[MessagingInstall]:+ async with harness.owner() as session:+ rows = await session.execute(+ select(MessagingInstall).where(+ MessagingInstall.platform == _PLATFORM,+ MessagingInstall.status == INSTALL_ACTIVE,+ )+ )+ return list(rows.scalars())+++class TestNames:+ async def test_a_chat_is_named_by_its_room_never_by_the_shared_bridge(+ self, rls_harness: RLSHarness+ ) -> None:+ """Every chat shares the tenant's one bridge, so its name would call+ each of them the same thing; a chat whose room is not there yet has no+ name rather than the bridge's."""+ fixture = await _fixture(rls_harness)+ await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ assert await fixture.service.install_names(session) == {}++ async def test_an_install_whose_app_is_gone_is_still_listed(+ self, rls_harness: RLSHarness+ ) -> None:+ """A deployment can hold installs of a platform it no longer has an+ app for; naming them must not fail the whole list."""+ fixture = await _fixture(rls_harness)+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ await MessagingInstallStore().record_install(+ session,+ platform="slack",+ external_workspace_id="T-gone",+ encrypted_bot_token=None,+ scopes="",+ platform_data={},+ user_id=fixture.admin_a,+ )+ await session.commit()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ assert await fixture.service.install_names(session) == {}+++class TestTheLink:+ async def test_the_token_fits_a_telegram_deep_link(+ self, rls_harness: RLSHarness+ ) -> None:+ """At most 64 characters of `[A-Za-z0-9_-]`, or Telegram drops it."""+ fixture = await _fixture(rls_harness)++ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ assert len(token) <= 64+ assert all(c.isalnum() or c in "-_" for c in token)+++class TestOneBridgePerTenant:+ async def test_the_first_claim_creates_the_bridge(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ install = await _claim(fixture, token, "-1001")++ assert install.tenant_id == fixture.tenant_a+ assert install.external_workspace_id == "-1001"+ assert install.encrypted_bot_token is None+ assert install.installed_by_user_id == fixture.admin_a+ assert len(fixture.lifecycle.registered) == 1+ assert fixture.lifecycle.registered[0]["channel_creation_enabled"] is False+ assert install.bridge_id is not None++ async def test_a_claim_is_recorded_in_the_audit_log(+ self, rls_harness: RLSHarness+ ) -> None:+ """As an OAuth install is, naming who asked for the link and which+ account on the platform used it."""+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ install = await _claim(fixture, token, "-1001")++ async with rls_harness.owner() as session:+ rows = await session.execute(+ select(AuditEvent).where(AuditEvent.tenant_id == fixture.tenant_a)+ )+ (event,) = rows.scalars()+ assert event.action == "messaging_install.connected"+ assert event.actor_user_id == fixture.admin_a+ assert event.target_id == install.id+ assert event.details["external_workspace_id"] == "-1001"+ assert event.details["claimed_by"] == "42"++ async def test_later_claims_share_it(self, rls_harness: RLSHarness) -> None:+ """The reason for the design: identities are per bridge, so a bridge+ per chat would have everyone link themselves again in every chat."""+ fixture = await _fixture(rls_harness)+ first = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )++ second = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1002",+ )++ assert len(fixture.lifecycle.registered) == 1+ assert second.bridge_id == first.bridge_id++ async def test_another_tenant_gets_its_own(self, rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ a = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )++ b = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_b, fixture.admin_b+ ),+ "-2001",+ )++ assert b.tenant_id == fixture.tenant_b+ assert b.bridge_id != a.bridge_id++ async def test_a_self_registered_bridge_is_not_the_shared_one(+ self, rls_harness: RLSHarness+ ) -> None:+ """An organisation may also register its own bot, which polls for+ itself; a claim must not land its chat on that bridge."""+ fixture = await _fixture(rls_harness)+ with tenant_scope(fixture.tenant_a):+ own = await fixture.lifecycle.register(+ bridge_type=_PLATFORM,+ display_name="Our own bot",+ connection_config={"event_delivery": "own_connection"},+ channel_creation_enabled=False,+ )++ install = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )++ assert install.bridge_id != own.id+ assert len(fixture.lifecycle.registered) == 2++ async def test_two_first_claims_at_once_make_one_bridge(+ self, rls_harness: RLSHarness+ ) -> None:+ """The race the advisory lock exists for. Without it both claims find+ no bridge, both register one, and the tenant's chats are split across+ two bridges nobody chose."""+ fixture = await _fixture(rls_harness)+ tokens = [+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ for _ in range(2)+ ]++ first, second = await asyncio.gather(+ _claim(fixture, tokens[0], "-1001"), _claim(fixture, tokens[1], "-1002")+ )++ assert len(fixture.lifecycle.registered) == 1+ assert first.bridge_id == second.bridge_id++ async def test_a_failed_registration_leaves_the_chat_unclaimed(+ self, rls_harness: RLSHarness+ ) -> None:+ """Rather than claimed by a tenant with no bridge, which would refuse+ every later claim and answer every event with a retryable failure."""+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.fail_next = RuntimeError("the platform said no")++ with pytest.raises(RuntimeError, match="the platform said no"):+ await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )++ assert await _active_installs(rls_harness) == []+ retried = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ assert retried.bridge_id is not None+++class TestWhoMayClaim:+ async def test_a_member_cannot_turn_the_platform_on(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.member_a+ )++ with pytest.raises(InstallClaimNotPermitted):+ await _claim(fixture, token, "-1001")++ assert fixture.lifecycle.registered == []+ assert await _active_installs(rls_harness) == []++ async def test_a_member_can_add_a_chat_once_it_is_on(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ first = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )++ added = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.member_a+ ),+ "-1002",+ )++ assert added.bridge_id == first.bridge_id+ assert added.installed_by_user_id == fixture.member_a++ async def test_a_member_can_add_a_chat_when_none_is_left(+ self, rls_harness: RLSHarness+ ) -> None:+ """The connection outlives its chats, so it is still on."""+ fixture = await _fixture(rls_harness)+ first = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=first.id+ )++ added = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.member_a+ ),+ "-1002",+ )++ assert added.bridge_id == first.bridge_id+ assert len(fixture.lifecycle.registered) == 1++ async def test_a_member_cannot_turn_it_back_on_once_deleted(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ first = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=first.id+ )+ assert first.bridge_id is not None+ with tenant_scope(fixture.tenant_a):+ await fixture.lifecycle.remove(first.bridge_id)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.member_a+ )++ with pytest.raises(InstallClaimNotPermitted):+ await _claim(fixture, token, "-1002")+++class TestWhatAClaimWillNotDo:+ async def test_a_replayed_claim_is_refused(self, rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ await _claim(fixture, token, "-1001")++ with pytest.raises(MessagingInstallStateError):+ await _claim(fixture, token, "-1002")++ async def test_a_chat_another_tenant_holds_is_refused(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )++ with pytest.raises(MessagingInstallClaimedError):+ await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_b, fixture.admin_b+ ),+ "-1001",+ )++ installs = await _active_installs(rls_harness)+ assert [install.tenant_id for install in installs] == [fixture.tenant_a]++ async def test_a_token_minted_for_another_platform_is_refused(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = mint_compact(+ InstallState(+ tenant_id=fixture.tenant_a,+ state_id=str(uuid.uuid4()),+ platform="discord",+ ),+ keyring=_KEYRING,+ )++ with pytest.raises(InstallStateError):+ await _claim(fixture, token, "-1001")+++class TestProposals:+ """A chat is only asked about a claim that could still connect it."""++ async def test_it_names_the_organisation_and_who_asked(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ proposal = await fixture.service.propose(+ platform=_PLATFORM,+ claim=InstallClaim(token=token, grant=_grant("-1001"), claimant="42"),+ )++ assert proposal == ClaimProposal(+ organisation=fixture.tenant_a, requested_by="admin-a"+ )++ async def test_a_used_link_is_not_proposed(self, rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ await _claim(fixture, token, "-1001")++ with pytest.raises(MessagingInstallStateError):+ await fixture.service.propose(+ platform=_PLATFORM,+ claim=InstallClaim(token=token, grant=_grant("-1002"), claimant="42"),+ )++ async def test_a_chat_another_tenant_holds_is_not_proposed(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_b, fixture.admin_b+ )++ with pytest.raises(MessagingInstallClaimedError):+ await fixture.service.propose(+ platform=_PLATFORM,+ claim=InstallClaim(token=token, grant=_grant("-1001"), claimant="42"),+ )++ async def test_turning_it_on_is_not_proposed_from_a_members_link(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.member_a+ )++ with pytest.raises(InstallClaimNotPermitted):+ await fixture.service.propose(+ platform=_PLATFORM,+ claim=InstallClaim(token=token, grant=_grant("-1001"), claimant="42"),+ )+++class TestTheRoute:+ """A claim arrives as an ordinary event and only asks; an admin's answer,+ another event, is what connects the chat, and is then delivered as one."""++ async def _client(self, fixture: _Fixture) -> httpx.AsyncClient:+ app = FastAPI()+ app.include_router(create_messaging_install_router(fixture.service))+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN+ )++ async def _post(self, client: httpx.AsyncClient, body: dict[str, Any]) -> int:+ response = await client.post(+ f"/messaging/{_PLATFORM}/events", content=json.dumps(body).encode()+ )+ return response.status_code++ async def test_a_claim_asks_and_connects_nothing(+ self, rls_harness: RLSHarness+ ) -> None:+ """A forwarded link reaches whoever it was forwarded to, so the chat is+ told which organisation, and who asked, before anything is spent."""+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ async with await self._client(fixture) as client:+ assert await self._post(client, {"chat": "-1001", "claim": token}) == 200++ assert await _active_installs(rls_harness) == []+ assert fixture.lifecycle.registered == []+ assert fixture.installer.proposed == [+ (+ "-1001",+ ClaimProposal(organisation=fixture.tenant_a, requested_by="admin-a"),+ )+ ]++ async def test_connect_installs_the_chat_and_is_delivered_to_it(+ self, rls_harness: RLSHarness+ ) -> None:+ """Delivered because Connect is also the event that creates the room:+ the add and the claim before it were dropped, the chat being unowned."""+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ body = _connect("-1001", token)++ async with await self._client(fixture) as client:+ assert await self._post(client, {"chat": "-1001", "claim": token}) == 200+ assert await self._post(client, body) == 200++ (install,) = await _active_installs(rls_harness)+ assert install.tenant_id == fixture.tenant_a+ adapter = fixture.lifecycle.adapters[install.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _RecordingAdapter)+ assert adapter.dispatched == [("events", body)]+ assert fixture.installer.answered == [("-1001", "connected")]++ async def test_cancel_connects_nothing_and_spends_the_link(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ async with await self._client(fixture) as client:+ assert await self._post(client, {"chat": "-1001", "claim": token}) == 200+ cancel = {"chat": "-1001", "answer": token, "decision": "cancel"}+ assert await self._post(client, cancel) == 200+ assert await self._post(client, _connect("-1001", token)) == 200++ assert await _active_installs(rls_harness) == []+ assert fixture.installer.answered == [+ ("-1001", "cancelled"),+ ("-1001", "expired"),+ ]++ async def test_a_claim_telegram_sends_twice_asks_once(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ async with await self._client(fixture) as client:+ for _ in range(2):+ assert (+ await self._post(client, {"chat": "-1001", "claim": token}) == 200+ )++ assert [chat for chat, _ in fixture.installer.proposed] == ["-1001"]+ assert fixture.installer.refused == []++ async def test_a_code_copied_into_another_chat_cannot_be_answered_there(+ self, rls_harness: RLSHarness+ ) -> None:+ """Anyone in the first chat saw the code. Putting it to the chat spent+ it, so it asks nothing elsewhere, and an answer naming it from another+ chat connects nothing."""+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )++ async with await self._client(fixture) as client:+ assert await self._post(client, {"chat": "-1001", "claim": token}) == 200+ assert await self._post(client, {"chat": "-1002", "claim": token}) == 200+ assert await self._post(client, _connect("-1002", token)) == 200++ assert await _active_installs(rls_harness) == []+ assert [chat for chat, _ in fixture.installer.proposed] == ["-1001"]+ assert fixture.installer.refused == [("-1002", "expired")]+ assert fixture.installer.answered == [("-1002", "expired")]++ async def test_an_answer_from_someone_not_an_admin_connects_nothing(+ self, rls_harness: RLSHarness+ ) -> None:+ """And leaves the link for an admin, who can still connect."""+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ async with await self._client(fixture) as client:+ assert await self._post(client, {"chat": "-1001", "claim": token}) == 200+ fixture.installer.claimant_check = ClaimantMayNotConnect("a member")+ assert await self._post(client, _connect("-1001", token)) == 200+ assert await _active_installs(rls_harness) == []+ fixture.installer.claimant_check = None+ assert await self._post(client, _connect("-1001", token)) == 200++ (install,) = await _active_installs(rls_harness)+ assert install.external_workspace_id == "-1001"+ assert fixture.installer.answered == [+ ("-1001", "not_chat_admin"),+ ("-1001", "connected"),+ ]++ async def test_a_refused_claim_in_an_unowned_chat_is_dropped(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)++ async with await self._client(fixture) as client:+ status = await self._post(client, {"chat": "-1001", "claim": "c1forged"})++ assert status == 200+ assert await _active_installs(rls_harness) == []+ assert fixture.lifecycle.registered == []++ async def test_a_refused_claim_in_an_owned_chat_still_reaches_its_owner(+ self, rls_harness: RLSHarness+ ) -> None:+ """Tenant B's token posted in tenant A's chat changes nothing about+ where that chat's events go."""+ fixture = await _fixture(rls_harness)+ owned = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ intruding = await _link(+ rls_harness.restricted, fixture, fixture.tenant_b, fixture.admin_b+ )+ body = {"chat": "-1001", "claim": intruding}++ async with await self._client(fixture) as client:+ assert await self._post(client, body) == 200++ installs = await _active_installs(rls_harness)+ assert [install.tenant_id for install in installs] == [fixture.tenant_a]+ adapter = fixture.lifecycle.adapters[owned.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _RecordingAdapter)+ assert adapter.dispatched == [("events", body)]+++class TestTheSharedConnection:+ """A bridge registered by a claim at runtime missed boot's attach, so its+ first delivered event is what hands it the platform's shared bot."""++ async def _client(self, fixture: _Fixture) -> httpx.AsyncClient:+ app = FastAPI()+ app.include_router(create_messaging_install_router(fixture.service))+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN+ )++ async def test_the_first_delivery_attaches_it(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ shared = object()+ fixture.installer.connection = shared+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ await _ask(fixture, token, "-1001")++ async with await self._client(fixture) as client:+ response = await client.post(+ f"/messaging/{_PLATFORM}/events",+ content=json.dumps(_connect("-1001", token)).encode(),+ )++ assert response.status_code == 200+ (install,) = await _active_installs(rls_harness)+ adapter = fixture.lifecycle.adapters[install.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _AttachableAdapter)+ assert adapter.attached == [shared]+ assert len(adapter.dispatched) == 1++ async def test_a_connection_not_ready_yet_is_retried_not_dropped(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ owned = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ fixture.installer.not_ready = True++ async with await self._client(fixture) as client:+ response = await client.post(+ f"/messaging/{_PLATFORM}/events",+ content=json.dumps({"chat": "-1001"}).encode(),+ )++ assert response.status_code == 503+ adapter = fixture.lifecycle.adapters[owned.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _AttachableAdapter)+ assert adapter.dispatched == []+++class TestEndingOneChat:+ """Every chat a tenant claimed shares its one bridge, which is the+ tenant's connection rather than any chat's: a chat leaving takes only its+ own room with it, even the last one, however it left."""++ async def _two_chats(+ self, harness: RLSHarness+ ) -> tuple[_Fixture, MessagingInstall, MessagingInstall]:+ fixture = await _fixture(harness)+ first = await _claim(+ fixture,+ await _link(harness.restricted, fixture, fixture.tenant_a, fixture.admin_a),+ "-1001",+ )+ second = await _claim(+ fixture,+ await _link(harness.restricted, fixture, fixture.tenant_a, fixture.admin_a),+ "-1002",+ )+ return fixture, first, second++ async def test_disconnecting_one_chat_detaches_only_its_room(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture, first, second = await self._two_chats(rls_harness)++ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=first.id+ )++ assert fixture.installer.released == ["-1001"]+ assert fixture.rooms.detached == [(first.bridge_id, "-1001")]+ assert fixture.lifecycle.removed == []+ (left,) = await _active_installs(rls_harness)+ assert left.id == second.id and left.bridge_id == first.bridge_id++ async def test_disconnecting_the_last_chat_keeps_the_bridge(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture, first, second = await self._two_chats(rls_harness)+ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=first.id+ )++ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=second.id+ )++ assert fixture.rooms.detached == [+ (first.bridge_id, "-1001"),+ (first.bridge_id, "-1002"),+ ]+ assert fixture.lifecycle.removed == []+ assert await _active_installs(rls_harness) == []+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ assert await fixture.service.platform_connected(session, platform=_PLATFORM)++ async def test_the_platform_removing_the_bot_ends_one_chat_the_same_way(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture, first, second = await self._two_chats(rls_harness)++ await fixture.service.revoked(+ platform=_PLATFORM, workspace_id="-1001", reason="kicked"+ )+ await fixture.service.revoked(+ platform=_PLATFORM, workspace_id="-1002", reason="kicked"+ )++ assert fixture.installer.released == []+ assert fixture.rooms.detached == [+ (first.bridge_id, "-1001"),+ (second.bridge_id, "-1002"),+ ]+ assert fixture.lifecycle.removed == []++ async def test_a_bot_that_could_not_leave_keeps_the_chat_connected(+ self, rls_harness: RLSHarness+ ) -> None:+ """Tell the platform first, then destroy things: a failure leaves the+ install as it was, to be disconnected again."""+ fixture, first, _ = await self._two_chats(rls_harness)+ fixture.installer.release_error = MessagingInstallError("still in the chat")++ with pytest.raises(MessagingInstallError):+ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=first.id+ )++ assert len(await _active_installs(rls_harness)) == 2+ assert fixture.rooms.detached == []+++class TestMigration:+ async def _owned(self, harness: RLSHarness) -> tuple[_Fixture, MessagingInstall]:+ fixture = await _fixture(harness)+ install = await _claim(+ fixture,+ await _link(harness.restricted, fixture, fixture.tenant_a, fixture.admin_a),+ "-55",+ )+ return fixture, install++ async def _post(self, fixture: _Fixture, body: dict[str, Any]) -> int:+ app = FastAPI()+ app.include_router(create_messaging_install_router(fixture.service))+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN+ ) as client:+ response = await client.post(+ f"/messaging/{_PLATFORM}/events", content=json.dumps(body).encode()+ )+ return response.status_code++ async def test_the_install_follows_its_chat_to_the_new_id(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture, install = await self._owned(rls_harness)++ assert (+ await self._post(fixture, {"chat": "-55", "migrate": ["-55", "-1009"]})+ == 200+ )++ (moved,) = await _active_installs(rls_harness)+ assert moved.id == install.id+ assert moved.external_workspace_id == "-1009"++ async def test_the_second_notice_finds_the_work_done(+ self, rls_harness: RLSHarness+ ) -> None:+ """Telegram announces the move from both chats; the second resolves by+ the old id, which is nobody's now, and is dropped."""+ fixture, _ = await self._owned(rls_harness)+ await self._post(fixture, {"chat": "-55", "migrate": ["-55", "-1009"]})++ assert (+ await self._post(fixture, {"chat": "-55", "migrate": ["-55", "-1009"]})+ == 200+ )++ (moved,) = await _active_installs(rls_harness)+ assert moved.external_workspace_id == "-1009"++ async def test_messages_lost_before_the_move_are_reported(+ self, rls_harness: RLSHarness, caplog: pytest.LogCaptureFixture+ ) -> None:+ fixture, _ = await self._owned(rls_harness)+ for _ in range(2):+ await self._post(fixture, {"chat": "-1009"})++ with caplog.at_level("ERROR"):+ await self._post(fixture, {"chat": "-55", "migrate": ["-55", "-1009"]})++ assert any(+ "2 telegram event(s) from workspace -1009" in record.getMessage()+ for record in caplog.records+ )+++class TestUnownedChats:+ async def test_they_are_counted_not_warned_about_and_answered(+ self, rls_harness: RLSHarness, caplog: pytest.LogCaptureFixture+ ) -> None:+ fixture = await _fixture(rls_harness)+ registry = MetricsRegistry()+ install(registry)+ try:+ app = FastAPI()+ app.include_router(create_messaging_install_router(fixture.service))+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN+ ) as client:+ with caplog.at_level("WARNING"):+ response = await client.post(+ f"/messaging/{_PLATFORM}/events",+ content=json.dumps(+ {"chat": "-7", "text": "something private"}+ ).encode(),+ )+ payloads = {p.name: p for p in registry.collect()}+ finally:+ uninstall()++ assert response.status_code == 200+ assert not any("Dropped" in r.getMessage() for r in caplog.records)+ assert "something private" not in caplog.text+ (point,) = payloads[MESSAGING_EVENTS_IGNORED.name].numbers+ assert point.attributes == {"platform": _PLATFORM, "reason": "unowned"}+ assert fixture.installer.unowned == [("-7", True)]+ assert await _active_installs(rls_harness) == []+++class TestRefusedClaims:+ """The person who tapped the link is told why nothing happened — except+ for a retry of a claim that worked, which is not a refusal at all."""++ async def _post(self, fixture: _Fixture, body: dict[str, Any]) -> int:+ app = FastAPI()+ app.include_router(create_messaging_install_router(fixture.service))+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN+ ) as client:+ response = await client.post(+ f"/messaging/{_PLATFORM}/events", content=json.dumps(body).encode()+ )+ return response.status_code++ async def test_a_code_this_deployment_did_not_mint(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ await self._post(fixture, {"chat": "-1001", "claim": "c1forged"})+ assert fixture.installer.refused == [("-1001", "unrecognised")]++ async def test_a_link_already_used_elsewhere(self, rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ await _claim(fixture, token, "-1001")++ await self._post(fixture, {"chat": "-1002", "claim": token})++ assert fixture.installer.refused == [("-1002", "expired")]++ async def test_a_retry_of_a_claim_that_worked_is_not_refused(+ self, rls_harness: RLSHarness+ ) -> None:+ """Telegram re-sends what it thinks went unanswered. Telling that chat+ its link expired, having just connected it, would be false."""+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ body = {"chat": "-1001", "claim": token}+ await self._post(fixture, body)++ assert await self._post(fixture, body) == 200++ assert fixture.installer.refused == []++ async def test_a_chat_another_tenant_holds(self, rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ intruding = await _link(+ rls_harness.restricted, fixture, fixture.tenant_b, fixture.admin_b+ )++ await self._post(fixture, {"chat": "-1001", "claim": intruding})++ assert fixture.installer.refused == [("-1001", "already_connected")]++ async def test_a_member_turning_the_platform_on(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.member_a+ )+ await self._post(fixture, {"chat": "-1001", "claim": token})+ assert fixture.installer.refused == [("-1001", "not_permitted")]++ async def test_someone_who_is_not_an_admin_of_the_chat(+ self, rls_harness: RLSHarness+ ) -> None:+ """Refused before the code is spent, so a group admin can still use it."""+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ fixture.installer.claimant_check = ClaimantMayNotConnect("a member")++ await self._post(fixture, {"chat": "-1001", "claim": token})++ assert fixture.installer.refused == [("-1001", "not_chat_admin")]+ fixture.installer.claimant_check = None+ await _claim(fixture, token, "-1001")+ assert len(await _active_installs(rls_harness)) == 1++ async def test_a_check_telegram_could_not_answer_is_retried(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ fixture.installer.claimant_check = MessagingInstallError("timed out")++ status = await self._post(fixture, {"chat": "-1001", "claim": token})++ assert status == 503+ assert fixture.installer.refused == []+ assert await _active_installs(rls_harness) == []+++class TestABridgeStillStarting:+ """A chat's first delivered event is the Connect that connected it,+ delivered moments after it launched the tenant's bridge — before the+ bridge has handed its adapter the callbacks that provision the chat's+ room. Delivered early, the room would never be made. So a connecting+ answer waits for its bridge to start — a first one, Telegram's retry of+ one, or one on a bridge that is restarting — and nothing else does."""++ async def _post(self, fixture: _Fixture, body: dict[str, Any]) -> int:+ app = FastAPI()+ app.include_router(create_messaging_install_router(fixture.service))+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN+ ) as client:+ response = await client.post(+ f"/messaging/{_PLATFORM}/events", content=json.dumps(body).encode()+ )+ return response.status_code++ async def test_an_event_waits_for_the_bridge_to_finish_starting(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ polls = {"left": 3}++ def is_connected(bridge_id: str) -> bool:+ polls["left"] -= 1+ return polls["left"] <= 0++ fixture.lifecycle.is_connected = is_connected # type: ignore[method-assign]+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ await _ask(fixture, token, "-1001")++ assert await self._post(fixture, _connect("-1001", token)) == 200++ (install,) = await _active_installs(rls_harness)+ adapter = fixture.lifecycle.adapters[install.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _AttachableAdapter)+ assert len(adapter.dispatched) == 1++ async def test_one_that_does_not_start_in_time_is_retried(+ self, rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(install_service_module, "_BRIDGE_START_WAIT", 0.2)+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.is_connected = lambda bridge_id: False # type: ignore[method-assign]+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ await _ask(fixture, token, "-1001")++ assert await self._post(fixture, _connect("-1001", token)) == 503++ (install,) = await _active_installs(rls_harness)+ adapter = fixture.lifecycle.adapters[install.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _AttachableAdapter)+ assert adapter.dispatched == []++ async def test_an_ordinary_event_does_not_wait(+ self, rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Only the answer that made the bridge waits. Every other event is+ refused at once for the platform to retry, as on every platform, and+ never handed to an adapter still starting."""+ fixture = await _fixture(rls_harness)+ owned = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ fixture.lifecycle.is_connected = lambda bridge_id: False # type: ignore[method-assign]++ started = time.monotonic()+ assert await self._post(fixture, {"chat": "-1001"}) == 503+ assert time.monotonic() - started < install_service_module._BRIDGE_START_WAIT++ adapter = fixture.lifecycle.adapters[owned.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _AttachableAdapter)+ assert adapter.dispatched == []++ async def test_a_retried_answer_waits_too(+ self, rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Telegram retries the press while the bridge is still coming up. The+ retry is a repeated answer, and it must wait as the first one did, or+ it reaches the half-started adapter and the room is lost."""+ monkeypatch.setattr(install_service_module, "_BRIDGE_START_WAIT", 0.2)+ fixture = await _fixture(rls_harness)+ started = {"yes": False}+ fixture.lifecycle.is_connected = lambda bridge_id: started["yes"] # type: ignore[method-assign]+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ body = _connect("-1001", token)+ await _ask(fixture, token, "-1001")++ assert await self._post(fixture, body) == 503+ assert await self._post(fixture, body) == 503+ (install,) = await _active_installs(rls_harness)+ adapter = fixture.lifecycle.adapters[install.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _AttachableAdapter)+ assert adapter.dispatched == []++ started["yes"] = True+ assert await self._post(fixture, body) == 200++ assert len(adapter.dispatched) == 1+ assert fixture.installer.refused == []++ async def test_an_answer_on_a_restarting_bridge_waits(+ self, rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """A tenant's second group connected while its bridge restarts: the+ bridge exists and resolves, and its adapter is not started yet."""+ monkeypatch.setattr(install_service_module, "_BRIDGE_START_WAIT", 0.2)+ fixture = await _fixture(rls_harness)+ first = await _claim(+ fixture,+ await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ ),+ "-1001",+ )+ started = {"yes": False}+ fixture.lifecycle.is_connected = lambda bridge_id: started["yes"] # type: ignore[method-assign]+ token = await _link(+ rls_harness.restricted, fixture, fixture.tenant_a, fixture.admin_a+ )+ body = _connect("-1002", token)+ await _ask(fixture, token, "-1002")++ assert await self._post(fixture, body) == 503+ adapter = fixture.lifecycle.adapters[first.bridge_id] # type: ignore[index]+ assert isinstance(adapter, _AttachableAdapter)+ assert adapter.dispatched == []++ started["yes"] = True+ assert await self._post(fixture, body) == 200++ assert [payload["chat"] for _, payload in adapter.dispatched] == ["-1002"]diff --git a/core/tests/switch_core/bridges/collaboration/test_install_service.py b/core/tests/switch_core/bridges/collaboration/test_install_service.pyindex a15a0d4b6..015c0f4b4 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_service.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py@@ -64,6 +64,7 @@ from switch_core.db.stores.messaging_install_store import (MessagingInstallStateError,MessagingInstallStore,)+from switch_core.db.stores.user_store import UserStorefrom switch_core.keys import Keyringfrom tests.conftest import RLSHarness@@ -158,6 +159,15 @@ class _FakeInstaller(MessagingAppInstaller):return {"bot_token": grant.bot_token, "workspace_id": grant.workspace_name}+class _NoRooms:+ """A Slack bridge has one install, so an ending never detaches one room."""++ async def unlink_bridge_channel(+ self, bridge_id: str, external_channel_id: str+ ) -> None:+ raise AssertionError("a one-install bridge is removed, not detached")++class _FakeLifecycle:"""Stands in for the bridge lifecycle, which starts real network clients.@@ -286,6 +296,8 @@ async def _fixture(harness: RLSHarness, *, tokenless: bool = False) -> _Fixture:receipts=MessagingEventReceiptStore(),installers=installers,lifecycle=fixture.lifecycle, # type: ignore[arg-type]+ users=UserStore(),+ rooms=_NoRooms(),public_origin=_ORIGIN,keyring=_KEYRING,)diff --git a/core/tests/switch_core/bridges/collaboration/test_install_state.py b/core/tests/switch_core/bridges/collaboration/test_install_state.pyindex bdb277899..4546d5b9e 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_state.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_state.py@@ -20,7 +20,9 @@ from switch_core.bridges.collaboration.install_state import (InstallState,InstallStateError,mint,+ mint_compact,verify,+ verify_compact,)from switch_core.keys import Keyring, Purpose@@ -154,3 +156,73 @@ class TestKeyChanges:def test_and_not_once_it_is_removed(self) -> None:with pytest.raises(InstallStateError, match="not signed"):verify(_legacy_token(_LEGACY), keyring=_KEYRING)+++class TestTheCompactForm:+ """The form a Telegram deep link can carry: 64 characters at most, from+ `[A-Za-z0-9_-]`, and bound to its platform by the key rather than a field."""++ _STATE = InstallState(+ tenant_id="3f1c2a8e-7b4d-4e0a-9c6f-1d2e3f4a5b6c",+ state_id="a0b1c2d3-e4f5-4a6b-8c7d-9e0f1a2b3c4d",+ platform="telegram",+ )++ def test_it_verifies_back_to_what_went_in(self) -> None:+ token = mint_compact(self._STATE, keyring=_KEYRING)+ assert (+ verify_compact(token, platform="telegram", keyring=_KEYRING) == self._STATE+ )++ def test_it_fits_a_telegram_start_parameter(self) -> None:+ token = mint_compact(self._STATE, keyring=_KEYRING)+ assert len(token) <= 64+ assert all(c.isalnum() or c in "-_" for c in token)++ def test_a_token_for_another_platform_is_refused(self) -> None:+ token = mint_compact(self._STATE, keyring=_KEYRING)+ with pytest.raises(InstallStateError):+ verify_compact(token, platform="discord", keyring=_KEYRING)++ def test_a_token_from_another_deployment_is_refused(self) -> None:+ token = mint_compact(+ self._STATE, keyring=Keyring.parse(f"k1:{'b' * 40}", legacy_secret=None)+ )+ with pytest.raises(InstallStateError):+ verify_compact(token, platform="telegram", keyring=_KEYRING)++ def test_an_edited_tenant_is_refused(self) -> None:+ token = mint_compact(self._STATE, keyring=_KEYRING)+ raw = bytearray(base64.urlsafe_b64decode(token.removeprefix("c1") + "=="))+ raw[0] ^= 0x01+ forged = "c1" + base64.urlsafe_b64encode(bytes(raw)).decode().rstrip("=")++ with pytest.raises(InstallStateError):+ verify_compact(forged, platform="telegram", keyring=_KEYRING)++ def test_a_truncated_token_is_refused(self) -> None:+ token = mint_compact(self._STATE, keyring=_KEYRING)+ with pytest.raises(InstallStateError):+ verify_compact(token[:-4], platform="telegram", keyring=_KEYRING)++ def test_the_two_forms_do_not_stand_in_for_each_other(self) -> None:+ v1 = mint(self._STATE, keyring=_KEYRING)+ compact = mint_compact(self._STATE, keyring=_KEYRING)++ with pytest.raises(InstallStateError):+ verify_compact(v1, platform="telegram", keyring=_KEYRING)+ with pytest.raises(InstallStateError):+ verify(compact, keyring=_KEYRING)++ def test_ids_that_are_not_uuids_cannot_be_minted(self) -> None:+ """A programming error, raised rather than minted into a token that+ would verify to different ids."""+ with pytest.raises(ValueError):+ mint_compact(_STATE, keyring=_KEYRING)++ def test_a_token_minted_before_a_rotation_still_verifies(self) -> None:+ rotated = Keyring.parse(f"k2:{'c' * 40},k1:{_MASTER}", legacy_secret=None)+ token = mint_compact(self._STATE, keyring=_KEYRING)+ assert (+ verify_compact(token, platform="telegram", keyring=rotated) == self._STATE+ )diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.pyindex 31fc399a8..028f5a02f 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py@@ -62,6 +62,7 @@ from switch_core.db.stores.messaging_event_store import (MessagingEventReceiptStore,)from switch_core.db.stores.messaging_install_store import MessagingInstallStore+from switch_core.db.stores.user_store import UserStorefrom switch_core.keys import Keyringfrom switch_core.tenant_context import current_tenant_idfrom tests.conftest import RLSHarness@@ -157,6 +158,15 @@ class _GatedAdapter(_SocketOnlyAdapter):await self.release.wait()+class _NoRooms:+ """A Slack bridge has one install, so an ending never detaches one room."""++ async def unlink_bridge_channel(+ self, bridge_id: str, external_channel_id: str+ ) -> None:+ raise AssertionError("a one-install bridge is removed, not detached")++class _FakeLifecycle:def __init__(self, factory: async_sessionmaker) -> None:self._factory = factory@@ -285,6 +295,8 @@ async def _fixture(harness: RLSHarness) -> _Fixture:receipts=MessagingEventReceiptStore(),installers=installers,lifecycle=fixture.lifecycle, # type: ignore[arg-type]+ users=UserStore(),+ rooms=_NoRooms(),public_origin=_ORIGIN,keyring=_KEYRING,)diff --git a/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py b/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.pyindex 79c9e0094..b8bb2969e 100644--- a/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py+++ b/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py@@ -25,6 +25,7 @@ from switch_core.bridges.collaboration.models import BridgeStartRefusedfrom switch_core.db.models import CollaborationBridgefrom switch_core.db.stores.messaging_event_store import MessagingEventReceiptStorefrom switch_core.db.stores.messaging_install_store import MessagingInstallStore+from switch_core.db.stores.user_store import UserStorefrom tests.conftest import RLSHarnessfrom .test_install_service import (@@ -34,6 +35,7 @@ from .test_install_service import (_FakeInstaller,_FakeLifecycle,_fixture,+ _NoRooms,)pytestmark = pytest.mark.no_ambient_tenant@@ -92,6 +94,8 @@ async def _shared_app(harness: RLSHarness) -> tuple[MessagingInstallService, _Idreceipts=MessagingEventReceiptStore(),installers=installers,lifecycle=lifecycle, # type: ignore[arg-type]+ users=UserStore(),+ rooms=_NoRooms(),public_origin=_ORIGIN,keyring=_KEYRING,)diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_app_lifecycle.py b/core/tests/switch_core/bridges/collaboration/test_telegram_app_lifecycle.pynew file mode 100644index 000000000..b007c88e8--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_app_lifecycle.py@@ -0,0 +1,687 @@+"""How a chat leaves the distributed Telegram app, and what guards its bot.++The Postgres half — one chat's room detached while the bridge stays, the last+chat taking the bridge with it, two leaving at once — is in+`test_install_claim.py`. This is the Telegram half: leaving a chat, reading a+supergroup's two migration notices, answering chats nobody claimed, asking+Telegram how delivery is going, and keeping the app's own bot out of every+self-registered bridge.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime+from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi import HTTPException+from telegram.error import BadRequest, Forbidden, TimedOut++from switch_core.bridges.collaboration.install import (+ ClaimantMayNotConnect,+ ClaimProposal,+ InstallClaim,+ InstallGrant,+ MessagingInstallError,+)+from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)+from switch_core.bridges.collaboration.telegram import install as install_module+from 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 (+ ANSWERED,+ CLAIM_REFUSED,+ DIRECT_MESSAGE_REPLY,+ NOT_AN_ADMIN_ALERT,+ UNCLAIMED_NOTICE,+ TelegramAppInstaller,+)+from switch_core.db.models import CollaborationBridge+from switch_core.gateway.collaborations import update_bridge+from switch_core.gateway.schemas import BridgeUpdateRequest++_SECRET = "placeholder-secret"+++@dataclass+class _Me:+ id: int = 123456+ username: str = "switch_app_bot"+ can_read_all_group_messages: bool = True+ can_join_groups: bool = True+++@dataclass+class _WebhookInfo:+ pending_update_count: int = 0+ last_error_date: datetime | None = None+ last_error_message: str | None = None+++@dataclass+class _Member:+ status: str+++@dataclass+class _Bot:+ token: str = "123456:placeholder-token"+ left: list[int] = field(default_factory=list)+ sent: list[dict[str, Any]] = field(default_factory=list)+ leave_error: Exception | None = None+ webhook_info: _WebhookInfo = field(default_factory=_WebhookInfo)+ member_status: str = "administrator"+ member_error: Exception | None = None+ members_asked: list[tuple[int, int]] = field(default_factory=list)+ answered: list[dict[str, Any]] = field(default_factory=list)+ edited: list[dict[str, Any]] = field(default_factory=list)++ async def initialize(self) -> None:+ return None++ async def get_me(self) -> _Me:+ return _Me()++ async def set_webhook(self, **kwargs: Any) -> bool:+ return True++ async def set_my_commands(self, commands: Any) -> bool:+ return True++ async def leave_chat(self, *, chat_id: int) -> bool:+ if self.leave_error is not None:+ raise self.leave_error+ self.left.append(chat_id)+ return True++ async def send_message(self, **kwargs: Any) -> None:+ self.sent.append(kwargs)++ async def answer_callback_query(self, **kwargs: Any) -> None:+ self.answered.append(kwargs)++ async def edit_message_text(self, **kwargs: Any) -> None:+ self.edited.append(kwargs)++ async def get_chat_member(self, *, chat_id: int, user_id: int) -> _Member:+ self.members_asked.append((chat_id, user_id))+ if self.member_error is not None:+ raise self.member_error+ return _Member(status=self.member_status)++ async def get_webhook_info(self) -> _WebhookInfo:+ return self.webhook_info+++async def _nothing(client: TelegramAppClient) -> None:+ return None+++async def _installer(bot: _Bot | None = None) -> tuple[TelegramAppInstaller, _Bot]:+ bot = bot or _Bot()+ client = TelegramAppClient(+ bot=bot, # type: ignore[arg-type]+ webhook_url="https://switch.example/messaging/telegram/events",+ webhook_secret=_SECRET,+ on_connected=_nothing,+ )+ await client.start()+ return TelegramAppInstaller(client=client, webhook_secret=_SECRET), bot+++class TestBeingUp:+ """A bridge starting once the bot is up is attached as it starts; one+ starting before is left for the walk `on_connected` makes, which must see+ the bot as up so a bridge starting during it is caught by one or the other."""++ async def test_not_before_start(self) -> None:+ client = TelegramAppClient(+ bot=_Bot(), # type: ignore[arg-type]+ webhook_url="https://switch.example/messaging/telegram/events",+ webhook_secret=_SECRET,+ on_connected=_nothing,+ )++ assert not client.is_live++ async def test_up_by_the_time_the_running_bridges_are_walked(self) -> None:+ seen: list[bool] = []++ async def on_connected(client: TelegramAppClient) -> None:+ seen.append(client.is_live)++ client = TelegramAppClient(+ bot=_Bot(), # type: ignore[arg-type]+ webhook_url="https://switch.example/messaging/telegram/events",+ webhook_secret=_SECRET,+ on_connected=on_connected,+ )+ await client.start_with_retry()++ assert seen == [True]+++class TestLeaving:+ async def test_disconnecting_makes_the_bot_leave(self) -> None:+ installer, bot = await _installer()+ await installer.release(external_workspace_id="-1001")+ assert bot.left == [-1001]++ @pytest.mark.parametrize(+ "gone",+ [+ BadRequest("Bad Request: chat not found"),+ Forbidden("Forbidden: bot was kicked from the group chat"),+ Forbidden("Forbidden: bot is not a member of the supergroup chat"),+ ],+ )+ async def test_a_chat_it_is_already_out_of_is_a_success(+ self, gone: Exception+ ) -> None:+ installer, bot = await _installer(_Bot(leave_error=gone))+ await installer.release(external_workspace_id="-1001")++ @pytest.mark.parametrize(+ "refused",+ [+ BadRequest("Bad Request: CHANNEL_PRIVATE"),+ Forbidden("Forbidden: bot can't initiate conversation with a user"),+ ],+ )+ async def test_any_other_refusal_keeps_the_disconnect_from_finishing(+ self, refused: Exception+ ) -> None:+ installer, _ = await _installer(_Bot(leave_error=refused))+ with pytest.raises(MessagingInstallError, match="still in the chat"):+ await installer.release(external_workspace_id="-1001")++ async def test_any_other_failure_keeps_the_disconnect_from_finishing(+ self,+ ) -> None:+ installer, _ = await _installer(_Bot(leave_error=TimedOut()))+ with pytest.raises(MessagingInstallError, match="still in the chat"):+ await installer.release(external_workspace_id="-1001")+++def _claim(claimant: str) -> InstallClaim:+ return InstallClaim(+ token="c1token",+ grant=InstallGrant(+ external_workspace_id="-1001",+ workspace_name="Telegram",+ bot_token=None,+ scopes="",+ platform_data={},+ ),+ claimant=claimant,+ )+++class TestWhoMayConnectAChat:+ """Only a chat's creator or admins may connect it: the code says who in+ Switch asked, not who may decide for the chat."""++ @pytest.mark.parametrize("status", ["creator", "administrator"])+ async def test_its_admins_may(self, status: str) -> None:+ installer, bot = await _installer(_Bot(member_status=status))+ await installer.require_claimant_may_connect(_claim("42"))+ assert bot.members_asked == [(-1001, 42)]++ @pytest.mark.parametrize("status", ["member", "restricted"])+ async def test_anyone_else_may_not(self, status: str) -> None:+ installer, _ = await _installer(_Bot(member_status=status))+ with pytest.raises(ClaimantMayNotConnect, match="not one of its admins"):+ await installer.require_claimant_may_connect(_claim("42"))++ async def test_a_post_as_the_chat_itself_needs_no_lookup(self) -> None:+ """A channel's post, or an anonymous admin's message."""+ installer, bot = await _installer(_Bot(member_status="member"))+ await installer.require_claimant_may_connect(_claim("-1001"))+ assert bot.members_asked == []++ async def test_someone_telegram_will_not_answer_for_is_refused(self) -> None:+ installer, _ = await _installer(+ _Bot(member_error=BadRequest("Bad Request: PARTICIPANT_ID_INVALID"))+ )+ with pytest.raises(ClaimantMayNotConnect):+ await installer.require_claimant_may_connect(_claim("777000"))++ async def test_a_lookup_that_fails_is_retried_not_let_through(self) -> None:+ installer, _ = await _installer(_Bot(member_error=TimedOut()))+ with pytest.raises(MessagingInstallError, match="Could not ask Telegram"):+ await installer.require_claimant_may_connect(_claim("42"))+++def _message(chat_id: int, **fields: Any) -> dict[str, Any]:+ return {+ "update_id": 1,+ "message": {"message_id": 1, "chat": {"id": chat_id, "type": "supergroup"}}+ | fields,+ }+++class TestMigration:+ async def test_the_notice_in_the_old_chat(self) -> None:+ installer, _ = await _installer()+ payload = _message(-55, migrate_to_chat_id=-1009)+ assert installer.migration_of_event(payload) == ("-55", "-1009")++ async def test_the_notice_in_the_new_chat(self) -> None:+ installer, _ = await _installer()+ payload = _message(-1009, migrate_from_chat_id=-55)+ assert installer.migration_of_event(payload) == ("-55", "-1009")++ async def test_an_ordinary_message_is_not_one(self) -> None:+ installer, _ = await _installer()+ assert installer.migration_of_event(_message(-55, text="hi")) is None+++def _added(chat_type: str = "supergroup", status: str = "member") -> dict[str, Any]:+ return {+ "update_id": 1,+ "my_chat_member": {+ "chat": {"id": -1001, "type": chat_type},+ "new_chat_member": {"status": status, "user": {"id": 123456}},+ },+ }+++async def _answer(+ installer: TelegramAppInstaller, payload: dict[str, Any], *, owned: bool+) -> None:+ async def still_unowned() -> bool:+ return not owned++ workspace = str(+ payload.get("my_chat_member", payload.get("message", {}))["chat"]["id"]+ ) # type: ignore[index]+ await installer.on_unowned_event(+ workspace_id=workspace, payload=payload, still_unowned=still_unowned+ )+++class TestUnclaimedChats:+ @pytest.fixture(autouse=True)+ def _no_grace(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(install_module, "UNCLAIMED_NOTICE_GRACE", 0.0)++ async def test_an_unclaimed_add_is_told_how_to_connect(self) -> None:+ installer, bot = await _installer()+ await _answer(installer, _added(), owned=False)+ assert bot.sent == [{"chat_id": -1001, "text": UNCLAIMED_NOTICE}]++ async def test_an_add_a_claim_followed_says_nothing(self) -> None:+ """The link sends the add and the claim a moment apart; the notice is+ only for an add no claim follows."""+ installer, bot = await _installer()+ await _answer(installer, _added(), owned=True)+ assert bot.sent == []++ async def test_a_channel_add_says_nothing(self) -> None:+ """A channel's code is posted after the bot is in, so every channel is+ added unclaimed, and a notice there reaches every subscriber."""+ installer, bot = await _installer()+ await _answer(+ installer, _added(chat_type="channel", status="administrator"), owned=False+ )+ assert bot.sent == []++ async def test_leaving_is_not_answered(self) -> None:+ installer, bot = await _installer()+ await _answer(installer, _added(status="left"), owned=False)+ assert bot.sent == []++ async def test_a_direct_message_is_told_it_reaches_no_one(self) -> None:+ installer, bot = await _installer()+ payload = {+ "update_id": 1,+ "message": {+ "message_id": 1,+ "chat": {"id": 42, "type": "private"},+ "text": "hi",+ },+ }+ await _answer(installer, payload, owned=False)+ assert bot.sent == [{"chat_id": 42, "text": DIRECT_MESSAGE_REPLY}]++ async def test_chatter_in_an_unclaimed_group_gets_no_answer(self) -> None:+ installer, bot = await _installer()+ await _answer(installer, _message(-1001, text="hello"), owned=False)+ assert bot.sent == []+++class TestDeliveryHealth:+ async def test_a_new_delivery_error_is_reported(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ bot = _Bot(+ webhook_info=_WebhookInfo(+ last_error_date=datetime(2026, 9, 28), last_error_message="timeout"+ )+ )+ installer, _ = await _installer(bot)+ client = installer.shared_connection()++ with caplog.at_level("WARNING"):+ seen = await client.check_delivery(None)+ await client.check_delivery(seen)++ assert [r.getMessage() for r in caplog.records].count(+ "Telegram reports failing to deliver to the webhook: timeout"+ ) == 1++ async def test_a_growing_backlog_is_reported(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ bot = _Bot(webhook_info=_WebhookInfo(pending_update_count=80))+ installer, _ = await _installer(bot)+ with caplog.at_level("WARNING"):+ await installer.shared_connection().check_delivery(None)+ assert "holding 80 updates" in caplog.text++ async def test_a_small_backlog_is_not(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ bot = _Bot(webhook_info=_WebhookInfo(pending_update_count=3))+ installer, _ = await _installer(bot)+ with caplog.at_level("WARNING"):+ await installer.shared_connection().check_delivery(None)+ assert caplog.text == ""+++def _lifecycle() -> CollaborationBridgeLifecycleService:+ config = MagicMock()+ config.collaboration_callback_host = "127.0.0.1"+ config.collaboration_callback_port = 0+ config.jwt_secret_key = "server-secret-for-tests"+ lifecycle = CollaborationBridgeLifecycleService(+ bridge_store=None, # type: ignore[arg-type]+ external_user_store=None, # type: ignore[arg-type]+ bridge_message_map_store=None, # type: ignore[arg-type]+ room_store=None, # type: ignore[arg-type]+ agent_store=None, # type: ignore[arg-type]+ client_store=None, # type: ignore[arg-type]+ client_lifecycle=None, # type: ignore[arg-type]+ room_service=None, # type: ignore[arg-type]+ provisioning=None, # type: ignore[arg-type]+ session_factory=None, # type: ignore[arg-type]+ config=config,+ client_factory=None, # type: ignore[arg-type]+ session_activity_listener=None, # type: ignore[arg-type]+ session_activity_service=None, # type: ignore[arg-type]+ connections=None, # type: ignore[arg-type]+ )+ lifecycle.register_adapter("telegram", TelegramAdapter, TelegramConnectionConfig)+ return lifecycle+++class TestTheBotAsAResource:+ def test_a_self_registered_bridge_holds_its_bot(self) -> None:+ """Two pollers on one bot split its updates at random."""+ held = TelegramAdapter.exclusive_resource(+ {"bot_token": "987:placeholder", "bot_username": "acme_bot"}+ )+ assert held == bot_resource("987")++ def test_a_shared_bridge_holds_nothing(self) -> None:+ """Every tenant's shared bridge runs on the one app bot by design."""+ assert TelegramAdapter.exclusive_resource({"event_delivery": "shared"}) is None++ async def test_the_app_bot_cannot_be_connected_as_a_bridge(self) -> None:+ """Its updates go to the webhook, and a tenant polling it would take+ every other tenant's."""+ lifecycle = _lifecycle()+ lifecycle.reserve_resource(bot_resource("123456"), "Telegram app bot")++ with pytest.raises(ValueError, match="this deployment's own Telegram app bot"):+ await lifecycle.reject_claim_conflict(+ "telegram",+ {"bot_token": "123456:placeholder", "bot_username": "switch_app_bot"},+ )+++class _BridgeStore:+ def __init__(self, bridge: CollaborationBridge) -> None:+ self.bridge = bridge++ async def get(self, session: Any, bridge_id: str) -> CollaborationBridge:+ return self.bridge+++class _Session:+ """The request's session; the route commits it before checking the edit."""++ async def commit(self) -> None:+ return None+++class TestEditingAConnection:+ async def _patch(+ self, lifecycle: Any, stored: dict[str, object], change: dict[str, object]+ ) -> None:+ bridge = CollaborationBridge(+ id="b1", type="telegram", display_name="Telegram", connection_config=stored+ )+ await update_bridge(+ "b1",+ BridgeUpdateRequest(connection_config=change),+ _Session(), # type: ignore[arg-type]+ _BridgeStore(bridge), # type: ignore[arg-type]+ None, # type: ignore[arg-type]+ lifecycle,+ None, # type: ignore[arg-type]+ )++ async def test_the_delivery_mode_cannot_be_changed(self) -> None:+ """It would turn an install into a bridge polling a bot of its own."""+ with pytest.raises(HTTPException) as refused:+ await self._patch(+ _lifecycle(),+ {"event_delivery": "shared"},+ {+ "event_delivery": "own_connection",+ "bot_token": "1:placeholder",+ "bot_username": "b",+ },+ )+ assert refused.value.status_code == 422++ async def test_the_app_bot_cannot_be_edited_in(self) -> None:+ lifecycle = _lifecycle()+ lifecycle.reserve_resource(bot_resource("123456"), "Telegram app bot")+ with pytest.raises(HTTPException) as refused:+ await self._patch(+ lifecycle,+ {+ "event_delivery": "own_connection",+ "bot_token": "987:placeholder",+ "bot_username": "acme_bot",+ },+ {"bot_token": "123456:placeholder"},+ )+ assert refused.value.status_code == 400+++class TestRefusedClaims:+ @pytest.mark.parametrize("reason", sorted(CLAIM_REFUSED))+ async def test_the_chat_is_told_why(self, reason: str) -> None:+ installer, bot = await _installer()+ claim = InstallClaim(+ token="c1token",+ grant=InstallGrant(+ external_workspace_id="-1001",+ workspace_name="Telegram",+ bot_token=None,+ scopes="",+ platform_data={},+ ),+ claimant="42",+ )++ await installer.on_claim_refused(claim=claim, reason=reason) # type: ignore[arg-type]++ assert bot.sent == [{"chat_id": -1001, "text": CLAIM_REFUSED[reason]}] # type: ignore[index]+++#: As long as a real compact state: `c1` and 44 bytes, base64 without padding.+_TOKEN = "c1" + "A" * 59+++def _proposal_claim() -> InstallClaim:+ return InstallClaim(+ token=_TOKEN,+ grant=InstallGrant(+ external_workspace_id="-1001",+ workspace_name="Telegram",+ bot_token=None,+ scopes="",+ platform_data={},+ ),+ claimant="42",+ )+++def _press(data: str, *, chat_type: str = "supergroup") -> dict[str, Any]:+ return {+ "update_id": 2,+ "callback_query": {+ "id": "press-1",+ "from": {"id": 7, "is_bot": False, "first_name": "Ada"},+ "data": data,+ "message": {+ "message_id": 55,+ "chat": {"id": -1001, "type": chat_type},+ },+ },+ }+++class TestAskingTheChat:+ """A claim is put to the chat it was posted in, naming the organisation and+ who asked, and connects nothing until one of the chat's admins answers."""++ async def test_it_names_the_organisation_and_who_asked(self) -> None:+ installer, bot = await _installer()++ await installer.on_claim_proposed(+ claim=_proposal_claim(),+ proposal=ClaimProposal(organisation="Acme", requested_by="Ada Lovelace"),+ )++ (sent,) = bot.sent+ assert sent["chat_id"] == -1001+ assert "Organisation: Acme" in sent["text"]+ assert "Requested by: Ada Lovelace" in sent["text"]+ (row,) = sent["reply_markup"].inline_keyboard+ assert [(b.text, b.callback_data) for b in row] == [+ ("Connect", f"c:{_TOKEN}"),+ ("Cancel", f"x:{_TOKEN}"),+ ]++ async def test_its_buttons_fit_telegrams_callback_data(self) -> None:+ installer, bot = await _installer()++ await installer.on_claim_proposed(+ claim=_proposal_claim(),+ proposal=ClaimProposal(organisation="Acme", requested_by="Ada"),+ )++ (row,) = bot.sent[0]["reply_markup"].inline_keyboard+ assert all(len(b.callback_data.encode()) <= 64 for b in row)++ async def test_an_add_waiting_on_an_answer_is_not_told_to_connect(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(install_module, "UNCLAIMED_NOTICE_GRACE", 0.0)+ installer, bot = await _installer()+ await installer.on_claim_proposed(+ claim=_proposal_claim(),+ proposal=ClaimProposal(organisation="Acme", requested_by="Ada"),+ )++ await _answer(installer, _added(), owned=False)++ assert len(bot.sent) == 1+++class TestAnswers:+ async def test_connect_and_cancel_are_read_with_who_pressed(self) -> None:+ installer, _ = await _installer()++ connect = installer.answer_of_event(_press(f"c:{_TOKEN}"))+ cancel = installer.answer_of_event(_press(f"x:{_TOKEN}"))++ assert connect is not None and cancel is not None+ assert (connect.decision, cancel.decision) == ("connect", "cancel")+ assert connect.claim.token == _TOKEN+ assert connect.claim.claimant == "7"+ assert connect.claim.grant.external_workspace_id == "-1001"++ @pytest.mark.parametrize("data", ["sw:token:1", "sx:turn", "c:", "connect"])+ def test_any_other_press_is_not_one(self, data: str) -> None:+ installer = TelegramAppInstaller(client=MagicMock(), webhook_secret=_SECRET)+ assert installer.answer_of_event(_press(data)) is None++ async def test_connected_closes_the_press_and_the_proposal(self) -> None:+ installer, bot = await _installer()+ answer = installer.answer_of_event(_press(f"c:{_TOKEN}"))+ assert answer is not None++ await installer.on_claim_answered(answer=answer, outcome="connected")++ assert bot.answered == [{"callback_query_id": "press-1"}]+ assert bot.edited == [+ {"chat_id": -1001, "message_id": 55, "text": ANSWERED["connected"]}+ ]+ assert bot.left == []++ async def test_cancelled_takes_the_bot_out(self) -> None:+ installer, bot = await _installer()+ answer = installer.answer_of_event(_press(f"x:{_TOKEN}"))+ assert answer is not None++ await installer.on_claim_answered(answer=answer, outcome="cancelled")++ assert bot.edited[0]["text"] == ANSWERED["cancelled"]+ assert bot.left == [-1001]++ async def test_a_press_from_someone_not_an_admin_leaves_the_proposal(+ self,+ ) -> None:+ """Only the presser hears why, and an admin can still answer."""+ installer, bot = await _installer()+ answer = installer.answer_of_event(_press(f"c:{_TOKEN}"))+ assert answer is not None++ await installer.on_claim_answered(answer=answer, outcome="not_chat_admin")++ assert bot.answered == [+ {+ "callback_query_id": "press-1",+ "text": NOT_AN_ADMIN_ALERT,+ "show_alert": True,+ }+ ]+ assert bot.edited == []++ async def test_a_link_that_ran_out_says_so_in_place_of_the_proposal(+ self,+ ) -> None:+ installer, bot = await _installer()+ answer = installer.answer_of_event(_press(f"c:{_TOKEN}"))+ assert answer is not None++ await installer.on_claim_answered(answer=answer, outcome="expired")++ assert bot.edited[0]["text"] == CLAIM_REFUSED["expired"]+ assert bot.left == []diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_distributed_app.py b/core/tests/switch_core/bridges/collaboration/test_telegram_distributed_app.pynew file mode 100644index 000000000..41710d26e--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_distributed_app.py@@ -0,0 +1,44 @@+"""The operator page and the code have to agree, so this compares them.++`docs/old/bridges/TELEGRAM_DISTRIBUTED_APP.md` shows the webhook Switch sets at+boot — the URL Telegram posts to and the updates it is asked for — so an+operator can check their ingress and read what the bot hears. Nothing at+runtime compares the page with what `setWebhook` is actually sent, and a page+that drifted would send someone routing the wrong path.++Parsed out of the markdown rather than kept in a fixture, because a fixture+would be a third copy.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++from switch_core.bridges.collaboration.install import events_path, public_url+from switch_core.bridges.collaboration.telegram.app_client import ALLOWED_UPDATES++_DOC = (+ Path(__file__).resolve().parents[5]+ / "docs"+ / "old"+ / "bridges"+ / "TELEGRAM_DISTRIBUTED_APP.md"+)+++def _webhook() -> dict:+ blocks = re.findall(r"```json\n(.*?)\n```", _DOC.read_text(), re.DOTALL)+ assert len(blocks) == 1, (+ f"expected exactly one json block in {_DOC.name}, found {len(blocks)}"+ )+ return json.loads(blocks[0])+++def test_the_page_names_the_url_switch_serves() -> None:+ assert _webhook()["url"] == public_url("https://HOST", events_path("telegram"))+++def test_the_page_names_the_updates_switch_asks_for() -> None:+ assert _webhook()["allowed_updates"] == list(ALLOWED_UPDATES)diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_installer.py b/core/tests/switch_core/bridges/collaboration/test_telegram_installer.pynew file mode 100644index 000000000..2b668ee80--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_installer.py@@ -0,0 +1,484 @@+"""The distributed Telegram app's installer, and the shared bot behind it.++Everything here reads an update Telegram posted, before any tenant is known,+so it is pure and needs no database. What matters is that the reading is+exact: which chat an update belongs to decides whose rooms it reaches, and a+claim read from the wrong message would attach a chat to a tenant nobody chose.+"""++from __future__ import annotations++import json+from dataclasses import dataclass, field+from typing import Any++import httpx+import pytest+from fastapi import FastAPI++from switch_core.bridges.collaboration.install import (+ MessagingInstallerRegistry,+ WebhookAuthenticityError,+ WebhookPayloadError,+)+from switch_core.bridges.collaboration.install_routes import (+ create_messaging_install_router,+)+from switch_core.bridges.collaboration.install_service import MessagingInstallService+from switch_core.bridges.collaboration.telegram.adapter import (+ _ALLOWED_UPDATES,+ TelegramConnectionConfig,+)+from switch_core.bridges.collaboration.telegram.app_client import (+ ALLOWED_UPDATES,+ TelegramAppClient,+ TelegramAppNotReady,+ bot_id_of,+)+from switch_core.bridges.collaboration.telegram.install import (+ SECRET_TOKEN_HEADER,+ TelegramAppInstaller,+)++_SECRET = "placeholder-secret"+_WEBHOOK_URL = "https://switch.example/messaging/telegram/events"+++@dataclass+class _Me:+ id: int+ username: str | None+ can_read_all_group_messages: bool = True+ can_join_groups: bool = True+++@dataclass+class _FakeBot:+ """Stands in for `telegram.Bot`, recording what the client asked of it."""++ token: str = "123456:placeholder-token"+ username: str | None = "switch_app_bot"+ webhooks: list[dict[str, Any]] = field(default_factory=list)+ menus: list[list[Any]] = field(default_factory=list)+ shut_down: bool = False++ async def initialize(self) -> None:+ return None++ async def get_me(self) -> _Me:+ return _Me(id=123456, username=self.username)++ async def set_webhook(self, **kwargs: Any) -> bool:+ self.webhooks.append(kwargs)+ return True++ async def set_my_commands(self, commands: Any) -> bool:+ self.menus.append(list(commands))+ return True++ async def shutdown(self) -> None:+ self.shut_down = True+++async def _nothing(client: TelegramAppClient) -> None:+ return None+++def _client(bot: _FakeBot | None = None) -> TelegramAppClient:+ return TelegramAppClient(+ bot=bot or _FakeBot(), # type: ignore[arg-type]+ webhook_url=_WEBHOOK_URL,+ webhook_secret=_SECRET,+ on_connected=_nothing,+ )+++async def _installer() -> TelegramAppInstaller:+ client = _client()+ await client.start()+ return TelegramAppInstaller(client=client, webhook_secret=_SECRET)+++def _group_message(text: str, *, chat_id: int = -1001, chat_type: str = "supergroup"):+ return {+ "update_id": 7,+ "message": {+ "message_id": 1,+ "chat": {"id": chat_id, "type": chat_type, "title": "Acme"},+ "from": {"id": 42, "is_bot": False, "first_name": "Ada"},+ "text": text,+ },+ }+++def _channel_post(text: str, *, chat_id: int = -1002):+ return {+ "update_id": 8,+ "channel_post": {+ "message_id": 1,+ "chat": {"id": chat_id, "type": "channel", "title": "News"},+ "text": text,+ },+ }+++def _membership(status: str, *, chat_id: int = -1001):+ return {+ "update_id": 9,+ "my_chat_member": {+ "chat": {"id": chat_id, "type": "supergroup"},+ "from": {"id": 42, "is_bot": False, "first_name": "Ada"},+ "old_chat_member": {"status": "member", "user": {"id": 123456}},+ "new_chat_member": {"status": status, "user": {"id": 123456}},+ },+ }+++class TestTheSharedBot:+ def test_the_bot_id_is_read_from_the_token(self) -> None:+ assert bot_id_of("123456:placeholder") == "123456"++ def test_a_token_without_an_id_is_refused(self) -> None:+ with pytest.raises(ValueError):+ bot_id_of("placeholder")++ async def test_it_has_no_username_until_it_has_asked(self) -> None:+ client = _client()+ with pytest.raises(TelegramAppNotReady):+ client.bot_username++ await client.start()++ assert client.bot_username == "switch_app_bot"++ async def test_start_points_telegram_at_the_webhook(self) -> None:+ """Every start, so the URL, secret and update types always match the+ running config — rotating the secret is a redeploy."""+ bot = _FakeBot()+ await _client(bot).start()++ assert bot.webhooks == [+ {+ "url": _WEBHOOK_URL,+ "secret_token": _SECRET,+ "allowed_updates": list(ALLOWED_UPDATES),+ }+ ]++ async def test_a_bot_with_no_username_does_not_start(self) -> None:+ """Every link is built from the username, so there is nothing to offer."""+ bot = _FakeBot(username=None)+ with pytest.raises(Exception, match="no username"):+ await _client(bot).start()+ assert bot.webhooks == []++ async def test_start_publishes_the_command_menu_once_for_every_tenant(+ self,+ ) -> None:+ bot = _FakeBot()+ await _client(bot).start()+ assert len(bot.menus) == 1 and bot.menus[0]++ async def test_bridges_already_running_are_handed_the_bot_once_it_is_up(+ self,+ ) -> None:+ connected: list[TelegramAppClient] = []++ async def on_connected(client: TelegramAppClient) -> None:+ connected.append(client)++ client = TelegramAppClient(+ bot=_FakeBot(), # type: ignore[arg-type]+ webhook_url=_WEBHOOK_URL,+ webhook_secret=_SECRET,+ on_connected=on_connected,+ )+ await client.start_with_retry()++ assert connected == [client]++ def test_it_asks_for_what_the_self_registered_bot_polls_for(self) -> None:+ """One adapter reads both, so they must be offered the same updates."""+ assert list(ALLOWED_UPDATES) == list(_ALLOWED_UPDATES)+++class TestAuthenticity:+ async def test_the_right_secret_is_accepted(self) -> None:+ installer = await _installer()+ await installer.verify_webhook(+ endpoint="events",+ query={},+ headers={SECRET_TOKEN_HEADER: _SECRET},+ body=b"{}",+ )++ async def test_the_header_name_is_case_insensitive(self) -> None:+ """Starlette hands the route lower-cased header names."""+ installer = await _installer()+ await installer.verify_webhook(+ endpoint="events",+ query={},+ headers={SECRET_TOKEN_HEADER.lower(): _SECRET},+ body=b"{}",+ )++ async def test_a_wrong_secret_is_refused(self) -> None:+ installer = await _installer()+ with pytest.raises(WebhookAuthenticityError):+ await installer.verify_webhook(+ endpoint="events",+ query={},+ headers={SECRET_TOKEN_HEADER: "not-it"},+ body=b"{}",+ )++ async def test_a_missing_secret_is_refused(self) -> None:+ installer = await _installer()+ with pytest.raises(WebhookAuthenticityError):+ await installer.verify_webhook(+ endpoint="events", query={}, headers={}, body=b"{}"+ )+++class TestParsing:+ async def test_the_update_id_is_what_retries_are_caught_by(self) -> None:+ installer = await _installer()+ [event] = installer.parse_webhook(+ endpoint="events",+ headers={},+ query={},+ body=json.dumps(_group_message("hello")).encode(),+ )+ assert event.external_event_id == "7"+ assert event.delivery_attempt == 0+ assert event.handshake is None++ async def test_an_update_without_an_id_is_refused(self) -> None:+ installer = await _installer()+ with pytest.raises(WebhookPayloadError):+ installer.parse_webhook(endpoint="events", headers={}, query={}, body=b"{}")++ async def test_a_body_that_is_not_json_is_refused(self) -> None:+ installer = await _installer()+ with pytest.raises(WebhookPayloadError):+ installer.parse_webhook(+ endpoint="events", headers={}, query={}, body=b"<html>"+ )++ async def test_only_the_events_endpoint_is_telegrams(self) -> None:+ installer = await _installer()+ body = json.dumps(_group_message("hello")).encode()+ with pytest.raises(WebhookPayloadError):+ installer.parse_webhook(+ endpoint="interactive", headers={}, query={}, body=body+ )+++class TestWhichChat:+ @pytest.mark.parametrize(+ ("payload", "chat"),+ [+ (_group_message("hi", chat_id=-1001), "-1001"),+ (_channel_post("hi", chat_id=-1002), "-1002"),+ (_membership("member", chat_id=-1003), "-1003"),+ (+ {+ "update_id": 1,+ "callback_query": {+ "id": "cb",+ "message": {"chat": {"id": -1004, "type": "group"}},+ },+ },+ "-1004",+ ),+ ],+ )+ async def test_each_update_type_names_its_chat(+ self, payload: dict[str, Any], chat: str+ ) -> None:+ installer = await _installer()+ assert installer.workspace_of_event(payload) == chat++ async def test_a_migrated_chat_is_routed_by_the_id_it_had(self) -> None:+ """The new id is owned by nobody until the install row follows it."""+ installer = await _installer()+ payload = _group_message("", chat_id=-1009)+ payload["message"]["migrate_from_chat_id"] = -55++ assert installer.workspace_of_event(payload) == "-55"++ async def test_an_update_with_no_chat_is_refused(self) -> None:+ installer = await _installer()+ with pytest.raises(WebhookPayloadError):+ installer.workspace_of_event({"update_id": 1, "poll": {}})+++class TestRevocation:+ @pytest.mark.parametrize("status", ["left", "kicked"])+ async def test_the_bot_leaving_ends_the_install(self, status: str) -> None:+ installer = await _installer()+ reason = installer.revocation_of_event(_membership(status))+ assert reason is not None and status in reason++ @pytest.mark.parametrize("status", ["member", "administrator", "restricted"])+ async def test_anything_else_does_not(self, status: str) -> None:+ installer = await _installer()+ assert installer.revocation_of_event(_membership(status)) is None++ async def test_an_ordinary_message_does_not(self) -> None:+ installer = await _installer()+ assert installer.revocation_of_event(_group_message("bye")) is None+++class TestClaims:+ async def test_the_handshake_from_the_link_is_a_claim(self) -> None:+ installer = await _installer()+ claim = installer.claim_of_event(+ _group_message("/start@switch_app_bot c1token", chat_id=-1001)+ )++ assert claim is not None+ assert claim.token == "c1token"+ assert claim.grant.external_workspace_id == "-1001"+ assert claim.grant.bot_token is None++ async def test_connect_in_a_channel_is_a_claim(self) -> None:+ installer = await _installer()+ claim = installer.claim_of_event(+ _channel_post("/connect c1token", chat_id=-1002)+ )++ assert claim is not None+ assert claim.grant.external_workspace_id == "-1002"++ async def test_the_claimant_is_who_posted_it(self) -> None:+ installer = await _installer()+ claim = installer.claim_of_event(_group_message("/connect c1token"))+ assert claim is not None+ assert claim.claimant == "42"++ async def test_a_post_as_the_chat_names_the_chat(self) -> None:+ """Only admins can post as the chat: a channel's posts, and an+ anonymous admin's messages in a group."""+ installer = await _installer()+ anonymous = _group_message("/connect c1token", chat_id=-1001)+ anonymous["message"]["sender_chat"] = {"id": -1001, "type": "supergroup"}++ channel = installer.claim_of_event(_channel_post("/connect c1", chat_id=-1002))+ group = installer.claim_of_event(anonymous)++ assert channel is not None and channel.claimant == "-1002"+ assert group is not None and group.claimant == "-1001"++ async def test_the_bot_name_is_matched_without_case(self) -> None:+ installer = await _installer()+ claim = installer.claim_of_event(+ _group_message("/start@Switch_App_Bot c1token")+ )+ assert claim is not None++ async def test_a_command_for_another_bot_is_not_ours(self) -> None:+ """With privacy off this bot sees other bots' commands too."""+ installer = await _installer()+ assert (+ installer.claim_of_event(_group_message("/start@other_bot c1token")) is None+ )++ async def test_a_private_chat_never_claims(self) -> None:+ installer = await _installer()+ message = _group_message("/start c1token", chat_id=42, chat_type="private")+ assert installer.claim_of_event(message) is None++ @pytest.mark.parametrize(+ "text", ["/start", "/connect", "/start a b", "/invite-agent c1token", "hello"]+ )+ async def test_other_text_is_not_a_claim(self, text: str) -> None:+ installer = await _installer()+ assert installer.claim_of_event(_group_message(text)) is None++ async def test_a_membership_change_is_not_a_claim(self) -> None:+ installer = await _installer()+ assert installer.claim_of_event(_membership("member")) is None+++class TestTheLink:+ async def test_it_adds_the_bot_to_a_group_with_the_state(self) -> None:+ installer = await _installer()+ url = installer.authorize_url(state="c1token", redirect_uri="unused")+ assert url == "https://t.me/switch_app_bot?startgroup=c1token"++ async def test_the_handle_is_the_whole_username(self) -> None:+ installer = await _installer()+ assert installer.bot_handle() == "@switch_app_bot"++ def test_there_is_no_link_before_the_bot_has_connected(self) -> None:+ installer = TelegramAppInstaller(client=_client(), webhook_secret=_SECRET)+ with pytest.raises(TelegramAppNotReady):+ installer.authorize_url(state="c1token", redirect_uri="unused")++ async def test_the_bridge_config_carries_no_credential(self) -> None:+ installer = await _installer()+ claim = installer.claim_of_event(_group_message("/start c1token"))+ assert claim is not None+ assert installer.connection_config(claim.grant) == {"event_delivery": "shared"}++ async def test_the_bridge_config_is_one_the_telegram_bridge_accepts(self) -> None:+ """Registration validates it against the adapter's config, and a claim+ whose config were refused there would roll back every time."""+ installer = await _installer()+ claim = installer.claim_of_event(_group_message("/start c1token"))+ assert claim is not None++ config = TelegramConnectionConfig.model_validate(+ installer.connection_config(claim.grant)+ )++ assert config.event_delivery == "shared"+++class TestTheRoute:+ """Only the paths that end before a tenant is resolved, so the service+ needs nothing behind it."""++ def _client_for(self, installer: TelegramAppInstaller) -> httpx.AsyncClient:+ installers = MessagingInstallerRegistry()+ installers.register(installer)+ service = MessagingInstallService(+ session_factory=None, # type: ignore[arg-type]+ store=None, # type: ignore[arg-type]+ receipts=None, # type: ignore[arg-type]+ installers=installers,+ lifecycle=None, # type: ignore[arg-type]+ users=None, # type: ignore[arg-type]+ rooms=None, # type: ignore[arg-type]+ public_origin="https://switch.example",+ keyring=None, # type: ignore[arg-type]+ )+ app = FastAPI()+ app.include_router(create_messaging_install_router(service))+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="https://switch.example"+ )++ async def test_a_post_without_the_secret_is_refused(self) -> None:+ async with self._client_for(await _installer()) as client:+ response = await client.post(+ "/messaging/telegram/events",+ content=json.dumps(_group_message("hello")).encode(),+ headers={SECRET_TOKEN_HEADER: "not-it"},+ )+ assert response.status_code == 401++ async def test_a_claim_before_the_bot_has_connected_is_retried(self) -> None:+ """A 503, so Telegram holds the claim and sends it again, rather than a+ claim dropped because the bot did not yet know its own name."""+ installer = TelegramAppInstaller(client=_client(), webhook_secret=_SECRET)+ async with self._client_for(installer) as client:+ response = await client.post(+ "/messaging/telegram/events",+ content=json.dumps(+ _group_message("/start@switch_app_bot c1token")+ ).encode(),+ headers={SECRET_TOKEN_HEADER: _SECRET},+ )+ assert response.status_code == 503diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_shared_delivery.py b/core/tests/switch_core/bridges/collaboration/test_telegram_shared_delivery.pynew file mode 100644index 000000000..0a0259b60--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_shared_delivery.py@@ -0,0 +1,396 @@+"""A Telegram bridge on the distributed app's shared bot.++Such a bridge polls nothing and holds no token: it is handed the deployment's+one bot, receives its updates from the webhook route, and waits out rate limits+against the one cooldown every tenant shares. The tests here are about what+differs from a self-registered bridge, and about the handful of places where+getting it wrong would reach another tenant: two bridges must share one+cooldown, and a bridge must never be handed anything but the Telegram bot.+"""++from __future__ import annotations++from typing import Any++import pytest+from pydantic import ValidationError+from telegram.error import RetryAfter++from switch_core.bridges.collaboration.adapter import (+ ChannelNotBindable,+ RichContentThrottled,+ WebhookDeliveryUnsupported,+)+from switch_core.bridges.collaboration.models import InboundAppJoin, InboundMessage+from switch_core.bridges.collaboration.telegram.adapter import (+ TelegramAdapter,+ TelegramConnectionConfig,+)+from switch_core.bridges.collaboration.telegram.app_client import TelegramAppClient+from switch_core.observability.catalogue import BRIDGE_THROTTLE_HELD+from switch_core.observability.metrics import MetricsRegistry, install, uninstall+from tests.switch_core.bridges.collaboration.test_telegram_adapter import (+ _FakeBot,+)++_BOT_ID = 777+_USERNAME = "switch_app_bot"+++class _Me:+ id = _BOT_ID+ username = _USERNAME+ can_read_all_group_messages = True+ can_join_groups = True+++class _SharedBot(_FakeBot):+ """The adapter tests' fake bot, plus what the shared client asks of it."""++ token = f"{_BOT_ID}:placeholder-token"++ async def initialize(self) -> None:+ return None++ async def get_me(self) -> _Me:+ return _Me()++ async def set_webhook(self, **kwargs: Any) -> bool:+ return True++ async def shutdown(self) -> None:+ return None+++async def _nothing(client: TelegramAppClient) -> None:+ return None+++async def _client() -> TelegramAppClient:+ client = TelegramAppClient(+ bot=_SharedBot(), # type: ignore[arg-type]+ webhook_url="https://switch.example/messaging/telegram/events",+ webhook_secret="placeholder-secret",+ on_connected=_nothing,+ )+ await client.start()+ return client+++def _shared_adapter() -> TelegramAdapter:+ return TelegramAdapter(+ config=TelegramConnectionConfig(event_delivery="shared"),+ )+++def _joins(adapter: TelegramAdapter) -> list[InboundAppJoin]:+ joined: list[InboundAppJoin] = []++ async def on_app_joined(join: InboundAppJoin) -> None:+ joined.append(join)++ adapter._on_app_joined = on_app_joined+ return joined+++class TestConfig:+ def test_a_shared_bridge_carries_no_credential(self) -> None:+ config = TelegramConnectionConfig(event_delivery="shared")+ assert config.bot_token is None and config.bot_username is None++ def test_a_shared_bridge_with_a_token_is_refused(self) -> None:+ """A credential for a bot it does not own, which polling would steal+ every tenant's updates with."""+ with pytest.raises(ValidationError, match="shared-delivery"):+ TelegramConnectionConfig(+ event_delivery="shared", bot_token="1:placeholder", bot_username="x"+ )++ def test_a_self_registered_bridge_without_a_token_is_refused(self) -> None:+ with pytest.raises(ValidationError, match="bot_token and bot_username"):+ TelegramConnectionConfig(bot_username="acme_bot")++ def test_a_self_registered_bridge_is_unchanged(self) -> None:+ config = TelegramConnectionConfig(bot_token="1:placeholder", bot_username="b")+ assert config.event_delivery == "own_connection"++ def test_the_delivery_mode_is_not_on_the_registration_form(self) -> None:+ assert (+ "event_delivery"+ not in TelegramConnectionConfig.model_json_schema()["properties"]+ )+++class TestAttaching:+ async def test_start_polls_nothing(self) -> None:+ adapter = _shared_adapter()+ await adapter.start(+ on_message=None, # type: ignore[arg-type]+ on_command=None, # type: ignore[arg-type]+ on_agent_joined=None, # type: ignore[arg-type]+ on_user_joined=None, # type: ignore[arg-type]+ on_app_joined=None, # type: ignore[arg-type]+ )+ assert adapter._app is None+ assert adapter._bot is None++ async def test_attaching_hands_it_the_shared_bot(self) -> None:+ client = await _client()+ adapter = _shared_adapter()++ adapter.attach_shared_connection(client)++ assert adapter._bot is client.bot+ assert adapter._bot_user_id == _BOT_ID+ assert adapter._bot_username == _USERNAME+ assert adapter._privacy_mode_disabled is True++ async def test_attaching_runs_the_deferred_start_work_once(self) -> None:+ client = await _client()+ adapter = _shared_adapter()+ fired: list[None] = []+ adapter.set_on_attached(lambda: fired.append(None))++ adapter.attach_shared_connection(client)+ adapter.attach_shared_connection(client)++ assert fired == [None]++ async def test_a_self_registered_bridge_is_never_attached(self) -> None:+ client = await _client()+ adapter = TelegramAdapter(+ config=TelegramConnectionConfig(bot_token="1:placeholder", bot_username="b")+ )++ adapter.attach_shared_connection(client)++ assert adapter._bot is None++ def test_anything_but_the_telegram_client_is_refused(self) -> None:+ """Discord's shared connection is attached through the same method."""+ adapter = _shared_adapter()+ with pytest.raises(TypeError, match="Telegram app client"):+ adapter.attach_shared_connection(object())++ async def test_a_shared_bridge_offers_no_unsigned_add_link(self) -> None:+ """It would add the bot to a chat that belongs to nobody."""+ adapter = _shared_adapter()+ adapter.attach_shared_connection(await _client())+ assert await adapter.install_links() == []+++class TestTheSharedCooldown:+ async def test_a_limit_earned_by_one_tenant_holds_back_another(self) -> None:+ """Telegram meters the bot, and every tenant's bridge is that bot."""+ client = await _client()+ first, second = _shared_adapter(), _shared_adapter()+ first.attach_shared_connection(client)+ second.attach_shared_connection(client)++ first._rich_failure(RetryAfter(30), "update", "text")++ with pytest.raises(RichContentThrottled):+ second._refuse_while_throttled("text")++ async def test_each_hold_back_is_measured(self) -> None:+ registry = MetricsRegistry()+ install(registry)+ try:+ adapter = _shared_adapter()+ adapter.attach_shared_connection(await _client())+ adapter._rich_failure(RetryAfter(30), "update", "text")+ with pytest.raises(RichContentThrottled):+ adapter._refuse_while_throttled("text")++ (payload,) = [+ p for p in registry.collect() if p.name == BRIDGE_THROTTLE_HELD.name+ ]+ finally:+ uninstall()+ (point,) = payload.histograms+ assert point.attributes == {"platform": "telegram", "delivery": "shared"}+ assert point.count == 1+++def _update(**body: Any) -> dict[str, Any]:+ return {"update_id": 1, **body}+++class TestDelivery:+ async def test_a_claim_in_a_group_is_its_join(self) -> None:+ """A claim reaching a bridge was posted in a chat it already holds;+ provisioning is idempotent, and the claim is not relayed as a message."""+ adapter = _shared_adapter()+ adapter.attach_shared_connection(await _client())+ joined = _joins(adapter)++ await adapter.dispatch_event(+ envelope_type="events",+ payload=_update(+ message={+ "message_id": 5,+ "date": 0,+ "chat": {"id": -1001, "type": "supergroup", "title": "Acme"},+ "from": {"id": 42, "is_bot": False, "first_name": "Ada"},+ "text": f"/start@{_USERNAME} c1token",+ }+ ),+ )++ assert [(j.channel_id, j.channel_name) for j in joined] == [("-1001", "Acme")]++ async def test_an_admins_connect_is_its_join(self) -> None:+ """The press that connected the chat is the first update its tenant+ receives. The install route closes the press, so the bridge does not."""+ client = await _client()+ adapter = _shared_adapter()+ adapter.attach_shared_connection(client)+ joined = _joins(adapter)++ await adapter.dispatch_event(+ envelope_type="events",+ payload=_update(+ callback_query={+ "id": "press-1",+ "chat_instance": "1",+ "from": {"id": 42, "is_bot": False, "first_name": "Ada"},+ "data": "c:c1token",+ "message": {+ "message_id": 8,+ "date": 0,+ "chat": {"id": -1001, "type": "supergroup", "title": "Acme"},+ "text": "Connect this chat to Switch?",+ },+ }+ ),+ )++ assert [(j.channel_id, j.channel_name) for j in joined] == [("-1001", "Acme")]+ assert client.bot.answers == [] # type: ignore[attr-defined]++ async def test_connect_in_a_channel_is_its_join(self) -> None:+ """A channel post has no sender and is otherwise dropped unread."""+ adapter = _shared_adapter()+ adapter.attach_shared_connection(await _client())+ joined = _joins(adapter)++ await adapter.dispatch_event(+ envelope_type="events",+ payload=_update(+ channel_post={+ "message_id": 6,+ "date": 0,+ "chat": {"id": -1002, "type": "channel", "title": "News"},+ "text": "/connect c1token",+ }+ ),+ )++ assert [(j.channel_id, j.channel_name) for j in joined] == [("-1002", "News")]++ async def test_an_ordinary_channel_post_is_still_dropped(self) -> None:+ adapter = _shared_adapter()+ adapter.attach_shared_connection(await _client())+ joined = _joins(adapter)++ await adapter.dispatch_event(+ envelope_type="events",+ payload=_update(+ channel_post={+ "message_id": 7,+ "date": 0,+ "chat": {"id": -1002, "type": "channel", "title": "News"},+ "text": "morning all",+ }+ ),+ )++ assert joined == []++ async def test_a_post_signed_with_its_authors_profile_is_bridged(self) -> None:+ """With Show Authors' Profiles on, a post carries its author as its+ sender, which is all a message needs to reach the room."""+ adapter = _shared_adapter()+ adapter.attach_shared_connection(await _client())+ seen: list[InboundMessage] = []++ async def on_message(message: InboundMessage) -> None:+ seen.append(message)++ adapter._on_message = on_message++ await adapter.dispatch_event(+ envelope_type="events",+ payload=_update(+ channel_post={+ "message_id": 8,+ "date": 0,+ "chat": {"id": -1002, "type": "channel", "title": "News"},+ "from": {"id": 42, "is_bot": False, "first_name": "Ada"},+ "author_signature": "Ada",+ "text": "morning all",+ }+ ),+ )++ assert [(m.channel_id, m.sender_id, m.content) for m in seen] == [+ ("-1002", "42", "morning all")+ ]++ async def test_a_self_registered_bridge_still_refuses_webhooks(self) -> None:+ adapter = TelegramAdapter(+ config=TelegramConnectionConfig(bot_token="1:placeholder", bot_username="b")+ )+ with pytest.raises(WebhookDeliveryUnsupported):+ await adapter.dispatch_event(envelope_type="events", payload=_update())++ async def test_an_unattached_shared_bridge_fails_loud(self) -> None:+ adapter = _shared_adapter()+ with pytest.raises(RuntimeError, match="not connected"):+ await adapter.dispatch_event(envelope_type="events", payload=_update())+++async def test_a_claim_on_a_bridge_that_never_started_fails_loud() -> None:+ """Absorbing it quietly would lose the chat's room: a claim arrives once."""+ adapter = _shared_adapter()+ adapter.attach_shared_connection(await _client())++ with pytest.raises(RuntimeError, match="has not started"):+ await adapter.dispatch_event(+ envelope_type="events",+ payload=_update(+ message={+ "message_id": 9,+ "date": 0,+ "chat": {"id": -1001, "type": "supergroup", "title": "Acme"},+ "from": {"id": 42, "is_bot": False, "first_name": "Ada"},+ "text": f"/start@{_USERNAME} c1token",+ }+ ),+ )+++# ── A chat joins the shared bot only by being claimed ────────────────────────+++async def test_the_shared_bot_binds_no_chat_by_id() -> None:+ """The shared bot is in every organisation's chats, and nothing Telegram+ says about a chat names its owner — only a claim does. The refusal says+ how a room does come about, and is the wording the room form shows."""+ adapter = _shared_adapter()++ with pytest.raises(ChannelNotBindable) as refused:+ await adapter.require_bindable_channel("-1001")++ assert "Add to Telegram" in str(refused.value)+ assert str(refused.value) == adapter.channel_ids_refused()+++async def test_an_organisations_own_bot_binds_a_chat_by_id() -> None:+ adapter = TelegramAdapter(+ config=TelegramConnectionConfig(bot_token="token", bot_username="own_bot")+ )++ await adapter.require_bindable_channel("-1001")++ assert adapter.channel_ids_refused() is Nonediff --git a/core/tests/switch_core/db/stores/test_messaging_install_store.py b/core/tests/switch_core/db/stores/test_messaging_install_store.pyindex 40671b86f..8fcdcc668 100644--- a/core/tests/switch_core/db/stores/test_messaging_install_store.py+++ b/core/tests/switch_core/db/stores/test_messaging_install_store.py@@ -16,7 +16,7 @@ from datetime import UTC, datetime, timedeltaimport pytestfrom sqlalchemy.ext.asyncio import async_sessionmaker-from switch_core.db.models import Tenant, User+from switch_core.db.models import Client, CollaborationBridge, Room, Tenant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.messaging_install_store import (INSTALL_DISCONNECTED,@@ -368,3 +368,94 @@ class TestRefreshingALiveInstall:await store.refresh(session, install_id=install_id, scopes="a b", platform_data={})+++class TestNames:+ async def test_each_install_is_named_by_its_room_and_its_bridge(+ self, rls_harness: RLSHarness+ ) -> None:+ """A chat bridged as a room carries the room's name; an install on a+ bridge carries the bridge's; one on no bridge, as an ended one is,+ carries neither; and another tenant's installs are not read at all."""+ fixture = await _two_tenants(rls_harness.owner)+ store = MessagingInstallStore()+ suffix = fixture.workspace++ async with rls_harness.owner() as session:+ client = Client(+ tenant_id=fixture.tenant_a,+ transport_user_id=f"@bridge-{suffix}:test",+ display_name="bridge",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ tenant_id=fixture.tenant_a,+ type="telegram",+ display_name="Telegram",+ status="active",+ connection_config={},+ client_id=client.id,+ )+ session.add(bridge)+ await session.flush()+ session.add(+ Room(+ tenant_id=fixture.tenant_a,+ transport_room_id=f"!news-{suffix}:test",+ name="Telegram: news",+ description="",+ bridge_id=bridge.id,+ external_channel_id="-1001",+ )+ )+ bridge_id = bridge.id+ await session.commit()++ ids: dict[str, str] = {}+ for tenant_id, chat in (+ (fixture.tenant_a, "-1001"),+ (fixture.tenant_a, "-1002"),+ (fixture.tenant_a, "-1003"),+ (fixture.tenant_b, "-2001"),+ ):+ async with tenant_session(rls_harness.restricted, tenant_id) as session:+ install = await store.record_install(+ session,+ platform="telegram",+ external_workspace_id=chat,+ encrypted_bot_token=None,+ scopes="",+ platform_data={},+ user_id=fixture.user_id,+ )+ if chat in ("-1001", "-1002"):+ await store.attach_bridge(+ session, install_id=install.id, bridge_id=bridge_id+ )+ ids[chat] = install.id+ await session.commit()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ names = {+ install_id: (room, bridge_name)+ for install_id, _, room, bridge_name in await store.names_for_tenant(+ session+ )+ }++ assert names == {+ ids["-1001"]: ("Telegram: news", "Telegram"),+ ids["-1002"]: (None, "Telegram"),+ ids["-1003"]: (None, None),+ }++ # The same pairing, as the room itself, for who may see and disconnect+ # the chat.+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ rooms = await store.rooms_for_tenant(session)++ assert {install_id: room.name for install_id, room in rooms.items()} == {+ ids["-1001"]: "Telegram: news"+ }diff --git a/core/tests/switch_core/gateway/test_bridge_delete_guard.py b/core/tests/switch_core/gateway/test_bridge_delete_guard.pyindex b9be2d859..ec1604710 100644--- a/core/tests/switch_core/gateway/test_bridge_delete_guard.py+++ b/core/tests/switch_core/gateway/test_bridge_delete_guard.py@@ -29,7 +29,7 @@ from switch_core.db.stores.messaging_install_store import (MessagingInstallStore,)from switch_core.db.stores.room_store import RoomStore-from switch_core.gateway.collaborations import delete_bridge+from switch_core.gateway.collaborations import _installed_refusal, delete_bridge_BRIDGE_STORE = CollaborationBridgeStore()_ROOM_STORE = RoomStore()@@ -189,7 +189,7 @@ async def test_the_refusal_names_the_workspace_to_disconnect(detail = str(excinfo.value.detail)assert workspace in detail- assert "slack" in detail+ assert "Slack workspace" in detailassert "Disconnect" in detail@@ -250,3 +250,59 @@ async def test_a_bridge_whose_install_already_ended_still_deletes()assert lifecycle.removed == [bridge_id]+++async def test_a_bridge_serving_several_installs_is_refused_for_all_of_them(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """A tenant's Telegram chats share one bridge, so the guard reads every+ live install behind it, not just the first."""+ async with session_factory() as session:+ admin = await _make_admin(session)+ bridge_id = await _make_bridge(session)+ for _ in range(2):+ await _make_install(+ session, bridge_id=bridge_id, status=INSTALL_ACTIVE, user_id=admin.id+ )+ await session.commit()++ lifecycle = _RecordingLifecycle()+ async with session_factory() as session:+ with pytest.raises(HTTPException) as excinfo:+ await delete_bridge(+ bridge_id,+ session,+ _BRIDGE_STORE,+ _ROOM_STORE,+ _RecordingRoomService(), # type: ignore[arg-type]+ _INSTALL_STORE,+ lifecycle, # type: ignore[arg-type]+ await _make_admin(session),+ )++ assert excinfo.value.status_code == 409+ assert "2 Slack workspaces" in str(excinfo.value.detail)+ assert lifecycle.removed == []+++ ("platform", "said", "unsaid"),+ [+ ("slack", "revokes Switch's token at Slack", "then delete"),+ ("discord", "remove it in Discord", "token"),+ ("teams", "out of every team", "token"),+ ("telegram", "then delete the connection here", "token"),+ ],+)+def test_the_refusal_says_what_disconnecting_does_on_each_platform(+ platform: str, said: str, unsaid: str+) -> None:+ """Only Slack has a token to revoke, and only a Telegram chat leaves its+ connection behind to be deleted here afterwards."""+ install = MessagingInstall(platform=platform, external_workspace_id="W1")++ refusal = _installed_refusal([install])++ assert "W1" in refusal+ assert said in refusal+ assert unsaid not in refusaldiff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.pyindex afac26745..855cd1b73 100644--- a/core/tests/switch_core/gateway/test_held_connections.py+++ b/core/tests/switch_core/gateway/test_held_connections.py@@ -147,6 +147,9 @@ class _Adapter:self._calls.record("platform channel deeplink")return None+ def channel_ids_refused(self) -> str | None:+ return None+class _CollabLifecycle:def __init__(self, calls: _Calls) -> None:diff --git a/core/tests/switch_core/gateway/test_messaging_install_routes.py b/core/tests/switch_core/gateway/test_messaging_install_routes.pynew file mode 100644index 000000000..cfb8ba844--- /dev/null+++ b/core/tests/switch_core/gateway/test_messaging_install_routes.py@@ -0,0 +1,338 @@+"""Who may do what with an installed messaging app.++An OAuth install creates a connection, which is the deployment operator's, and+every route keeps exactly the operator check it had. A claim-based platform+(Telegram) is different in one respect: one chat is a room, not a connection.+So an admin connects the first chat — which turns the platform on for the+organisation — and after that members connect and disconnect chats, while+removing all of them is an admin's again.++The routes are called directly with a fake service: the rules here are about+the caller, and the service's own behaviour is tested against Postgres+elsewhere.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from types import SimpleNamespace+from typing import Any++import pytest+from fastapi import HTTPException++from switch_core.bridges.collaboration.install import MessagingInstallError+from switch_core.bridges.collaboration.install_service import ClaimLink+from switch_core.db.models import User+from switch_core.gateway.messaging_installs import (+ begin_claim,+ begin_install,+ disconnect_install,+ installable_platforms,+ list_installs,+)+from switch_core.tenant_context import tenant_scope++_TENANT = "00000000-0000-0000-0000-00000000000a"+++def _install(install_id: str, platform: str) -> SimpleNamespace:+ return SimpleNamespace(+ id=install_id,+ tenant_id=_TENANT,+ platform=platform,+ external_workspace_id=f"ws-{install_id}",+ status="active",+ scopes="",+ bridge_id="b1",+ installed_at="2026-09-28T00:00:00Z",+ ended_at=None,+ )+++def _room(+ *, owner_id: str | None = None, read: str = "public", write: str = "public"+) -> SimpleNamespace:+ return SimpleNamespace(+ owner_id=owner_id, read_visibility=read, write_visibility=write+ )+++@dataclass+class _Service:+ connected: bool = False+ not_ready: bool = False+ installs: list[SimpleNamespace] = field(+ default_factory=lambda: [_install("s1", "slack"), _install("t1", "telegram")]+ )+ disconnected: list[str] = field(default_factory=list)+ rooms: dict[str, SimpleNamespace] = field(default_factory=lambda: {"t1": _room()})++ def platforms(self) -> list[str]:+ return ["slack", "telegram"]++ def installer(self, platform: str) -> Any:+ if platform not in self.platforms():+ raise MessagingInstallError(f"no {platform} app")+ return SimpleNamespace(installs_by_claim=platform == "telegram")++ async def platform_connected(self, session: Any, *, platform: str) -> bool:+ return self.connected++ async def begin_claim(+ self, session: Any, *, platform: str, user_id: str+ ) -> ClaimLink:+ if self.not_ready:+ raise MessagingInstallError("the bot has not connected yet")+ return ClaimLink(+ url="https://t.me/switch_app_bot?startgroup=c1code",+ code="c1code",+ bot_handle="@switch_app_bot",+ )++ async def begin(self, session: Any, *, platform: str, user_id: str) -> str:+ return f"https://{platform}.example/authorize"++ async def list_installs(self, session: Any) -> list[SimpleNamespace]:+ return self.installs++ async def install_names(self, session: Any) -> dict[str, str]:+ return {"t1": "Telegram: news"}++ async def chat_rooms(self, session: Any) -> dict[str, SimpleNamespace]:+ return self.rooms++ async def install_platform(self, session: Any, *, install_id: str) -> str:+ return next(i.platform for i in self.installs if i.id == install_id)++ async def disconnect(self, *, tenant_id: str, install_id: str) -> SimpleNamespace:+ self.disconnected.append(install_id)+ return next(i for i in self.installs if i.id == install_id)+++class _Session:+ """Collects what the routes add, which is only ever their audit events."""++ def __init__(self) -> None:+ self.added: list[Any] = []++ def add(self, row: Any) -> None:+ self.added.append(row)++ async def flush(self) -> None:+ return None++ async def commit(self) -> None:+ return None++ def audited(self) -> list[tuple[str, str | None]]:+ return [(event.action, event.target_id) for event in self.added]+++def _user(role: str = "user") -> User:+ return User(id=f"u-{role}", name=role, email=f"{role}@example.test", role=role)+++class TestWhatIsOffered:+ async def test_a_tenant_admin_sees_oauth_platforms_and_claimable_ones(self) -> None:+ offered = await installable_platforms(+ _Session(),+ _Service(connected=False),+ True, # type: ignore[arg-type]+ )+ assert offered.platforms == ["slack"]+ (telegram,) = offered.claimable+ assert telegram.can_add_chat++ async def test_a_member_is_offered_no_oauth_install(self) -> None:+ offered = await installable_platforms(+ _Session(),+ _Service(connected=True),+ False, # type: ignore[arg-type]+ )+ assert offered.platforms == []++ async def test_a_member_may_add_a_chat_once_it_is_connected(self) -> None:+ offered = await installable_platforms(+ _Session(),+ _Service(connected=True),+ False, # type: ignore[arg-type]+ )+ (telegram,) = offered.claimable+ assert telegram.can_add_chat++ async def test_a_member_may_not_turn_it_on(self) -> None:+ offered = await installable_platforms(+ _Session(),+ _Service(connected=False),+ False, # type: ignore[arg-type]+ )+ (telegram,) = offered.claimable+ assert not telegram.can_add_chat+++class TestClaimLinks:+ async def test_a_member_gets_a_link_once_it_is_connected(self) -> None:+ session = _Session()+ with tenant_scope(_TENANT):+ started = await begin_claim(+ "telegram",+ session, # type: ignore[arg-type]+ _Service(connected=True), # type: ignore[arg-type]+ _user(),+ False,+ )+ assert started.url.startswith("https://t.me/")+ assert started.code == "c1code"+ assert started.bot_handle == "@switch_app_bot"+ assert session.audited() == [("messaging_install.started", None)]++ async def test_a_member_cannot_turn_it_on(self) -> None:+ with pytest.raises(HTTPException) as refused:+ await begin_claim(+ "telegram",+ _Session(),+ _Service(connected=False),+ _user(),+ False, # type: ignore[arg-type]+ )+ assert refused.value.status_code == 403++ async def test_an_admin_can(self) -> None:+ with tenant_scope(_TENANT):+ started = await begin_claim(+ "telegram",+ _Session(), # type: ignore[arg-type]+ _Service(connected=False), # type: ignore[arg-type]+ _user(),+ True,+ )+ assert started.code == "c1code"++ async def test_an_oauth_platform_has_no_claim_link(self) -> None:+ with pytest.raises(HTTPException) as refused:+ await begin_claim(+ "slack",+ _Session(),+ _Service(),+ _user("admin"),+ True, # type: ignore[arg-type]+ )+ assert refused.value.status_code == 404++ async def test_no_link_before_the_bot_has_connected(self) -> None:+ with pytest.raises(HTTPException) as refused:+ await begin_claim(+ "telegram",+ _Session(), # type: ignore[arg-type]+ _Service(connected=True, not_ready=True), # type: ignore[arg-type]+ _user(),+ False,+ )+ assert refused.value.status_code == 503+++class TestOAuthIsATenantAdmins:+ async def test_a_member_cannot_start_an_oauth_install(self) -> None:+ with pytest.raises(HTTPException) as refused:+ await begin_install("slack", _Session(), _Service(), _user(), False) # type: ignore[arg-type]+ assert refused.value.status_code == 403++ async def test_a_tenant_admin_can(self) -> None:+ with tenant_scope(_TENANT):+ started = await begin_install(+ "slack",+ _Session(), # type: ignore[arg-type]+ _Service(), # type: ignore[arg-type]+ _user(),+ True,+ )+ assert started.authorize_url == "https://slack.example/authorize"++ async def test_a_member_cannot_disconnect_an_oauth_install(self) -> None:+ service = _Service()+ with tenant_scope(_TENANT), pytest.raises(HTTPException) as refused:+ await disconnect_install("s1", _Session(), service, _user(), False) # type: ignore[arg-type]+ assert refused.value.status_code == 403+ assert service.disconnected == []+++class TestChats:+ async def test_a_member_sees_only_the_chats(self) -> None:+ listed = await list_installs(_Session(), _Service(), _user(), False) # type: ignore[arg-type]+ assert [i.platform for i in listed.installs] == ["telegram"]++ async def test_a_tenant_admin_sees_everything(self) -> None:+ listed = await list_installs(_Session(), _Service(), _user(), True) # type: ignore[arg-type]+ assert [i.platform for i in listed.installs] == ["slack", "telegram"]++ async def test_each_is_listed_by_the_name_it_still_has(self) -> None:+ listed = await list_installs(_Session(), _Service(), _user(), True) # type: ignore[arg-type]+ assert [(i.id, i.name) for i in listed.installs] == [+ ("s1", None),+ ("t1", "Telegram: news"),+ ]++ async def test_a_member_disconnects_one_chat(self) -> None:+ service = _Service()+ session = _Session()+ with tenant_scope(_TENANT):+ await disconnect_install("t1", session, service, _user(), False) # type: ignore[arg-type]+ assert service.disconnected == ["t1"]+ assert session.audited() == [("messaging_install.disconnected", "t1")]+++class TestPrivateRooms:+ """A chat is a room, so a room made private takes its chat with it: a+ member who cannot read it does not see the chat, and one who cannot write+ to it cannot disconnect it — the check moving the room onto another bridge+ makes."""++ async def test_a_member_does_not_see_a_chat_whose_room_they_cannot_read(+ self,+ ) -> None:+ service = _Service(rooms={"t1": _room(read="private", write="private")})+ listed = await list_installs(_Session(), service, _user(), False) # type: ignore[arg-type]+ assert listed.installs == []++ async def test_its_owner_does(self) -> None:+ service = _Service(+ rooms={"t1": _room(owner_id="u-user", read="private", write="private")}+ )+ listed = await list_installs(_Session(), service, _user(), False) # type: ignore[arg-type]+ assert [i.id for i in listed.installs] == ["t1"]++ async def test_an_admin_does(self) -> None:+ service = _Service(rooms={"t1": _room(read="private", write="private")})+ listed = await list_installs(_Session(), service, _user(), True) # type: ignore[arg-type]+ assert "t1" in [i.id for i in listed.installs]++ async def test_a_member_cannot_disconnect_a_chat_whose_room_they_cannot_change(+ self,+ ) -> None:+ service = _Service(rooms={"t1": _room(write="private")})+ with tenant_scope(_TENANT), pytest.raises(HTTPException) as refused:+ await disconnect_install("t1", _Session(), service, _user(), False) # type: ignore[arg-type]+ assert refused.value.status_code == 403+ assert service.disconnected == []++ async def test_an_admin_can(self) -> None:+ service = _Service(rooms={"t1": _room(read="private", write="private")})+ with tenant_scope(_TENANT):+ await disconnect_install("t1", _Session(), service, _user(), True) # type: ignore[arg-type]+ assert service.disconnected == ["t1"]++ async def test_a_chat_whose_room_is_gone_is_not_a_members(self) -> None:+ """No room's permissions cover it any more, so the tenant's admins+ decide."""+ service = _Service(rooms={})+ with tenant_scope(_TENANT), pytest.raises(HTTPException) as refused:+ await disconnect_install("t1", _Session(), service, _user(), False) # type: ignore[arg-type]+ assert refused.value.status_code == 403+ assert service.disconnected == []++ async def test_an_admin_can_disconnect_a_chat_whose_room_is_gone(self) -> None:+ service = _Service(rooms={})+ with tenant_scope(_TENANT):+ await disconnect_install("t1", _Session(), service, _user(), True) # type: ignore[arg-type]+ assert service.disconnected == ["t1"]diff --git a/core/tests/switch_core/gateway/test_messaging_installs_authz.py b/core/tests/switch_core/gateway/test_messaging_installs_authz.pyindex c700b3cc0..9147e28f8 100644--- a/core/tests/switch_core/gateway/test_messaging_installs_authz.py+++ b/core/tests/switch_core/gateway/test_messaging_installs_authz.py@@ -5,6 +5,11 @@ may do it is that workspace's owner or admin — not only the deploymentoperator. On a server where people sign themselves up, the operator bit isheld by nobody who runs a workspace, so gating these routes on it would leavethe Slack button unreachable to exactly the people it is for.++A claim-based platform (Telegram) is the one refinement: its connection is an+admin's, but each chat on it is a room, which members connect and disconnect.+So the routes read the tenant-admin bit and decide per platform, and a member+listing installs sees those chats and no OAuth workspace."""from __future__ import annotations@@ -18,7 +23,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.db.models import Tenant, TenantMember, Userfrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway import dependencies as gw_deps-from switch_core.gateway.auth import create_jwt, require_admin, require_tenant_admin+from switch_core.gateway.auth import create_jwt, get_tenant_is_admin, require_adminfrom switch_core.gateway.messaging_installs import routerfrom switch_core.keys import Keyring@@ -35,12 +40,12 @@ def _dependency_calls(dependant: object) -> list[object]:return calls-def test_every_route_requires_a_tenant_admin_and_not_the_operator() -> None:+def test_every_route_asks_the_tenant_and_not_the_operator() -> None:routes = [route for route in router.routes if hasattr(route, "dependant")]- assert len(routes) == 4+ assert routesfor route in routes:calls = _dependency_calls(route.dependant) # type: ignore[attr-defined]- assert require_tenant_admin in calls, route.path # type: ignore[attr-defined]+ assert get_tenant_is_admin in calls, route.path # type: ignore[attr-defined]assert require_admin not in calls, route.path # type: ignore[attr-defined]@@ -104,9 +109,12 @@ class TestWhoMayManageInstalls:response = await _list_installs(session_factory, user_id, "wsadmin")assert response.status_code == 200, response.text- async def test_a_plain_member_may_not(+ async def test_a_plain_member_sees_the_list_without_any_workspace(self, session_factory: async_sessionmaker[AsyncSession]) -> None:+ """A member may list, for the chats they may disconnect; which installs+ they see is pinned in `test_messaging_install_routes.py`."""user_id = await _member(session_factory, name="plain", role="member")response = await _list_installs(session_factory, user_id, "plain")- assert response.status_code == 403+ assert response.status_code == 200, response.text+ assert response.json() == {"installs": []}diff --git a/core/tests/switch_core/test_config_telegram_app.py b/core/tests/switch_core/test_config_telegram_app.pynew file mode 100644index 000000000..fd9b9390b--- /dev/null+++ b/core/tests/switch_core/test_config_telegram_app.py@@ -0,0 +1,96 @@+"""Half-configuring the distributed Telegram app has to be a startup error.++The token without the secret is a bot that accepts any post to its webhook;+the secret without the token is nothing to receive for. And the values Telegram+itself would refuse — a malformed secret, a port it will not deliver to — are+refused here, where the message can say so, rather than in a background task+at boot where they would read as Telegram being unreachable.+"""++import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)++_APP = dict(+ telegram_app_bot_token="123456:placeholder-token",+ telegram_app_webhook_secret="placeholder-webhook-secret-0123456789",+)++_ORIGIN = "https://switch.example"+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++def test_setting_neither_is_the_ordinary_case() -> None:+ assert _config().telegram_app_bot_token is None+++def test_setting_both_with_a_public_origin_is_accepted() -> None:+ config = _config(**_APP, messaging_public_url=_ORIGIN)+ assert config.telegram_app_webhook_secret == _APP["telegram_app_webhook_secret"]++[email protected]("missing", sorted(_APP))+def test_setting_one_raises(missing: str) -> None:+ partial = {key: value for key, value in _APP.items() if key != missing}+ with pytest.raises(ValueError, match="Partial distributed Telegram app config"):+ _config(**partial, messaging_public_url=_ORIGIN)+++def test_an_app_with_no_public_origin_raises() -> None:+ with pytest.raises(ValueError, match="MESSAGING_PUBLIC_URL"):+ _config(**_APP)+++ "secret", ["has space" * 4, "has/slash" * 4, "x" * 257, "ümlaut" * 6]+)+def test_a_secret_telegram_would_refuse_raises(secret: str) -> None:+ with pytest.raises(ValueError, match="TELEGRAM_APP_WEBHOOK_SECRET"):+ _config(+ **{**_APP, "telegram_app_webhook_secret": secret},+ messaging_public_url=_ORIGIN,+ )+++def test_a_short_secret_raises() -> None:+ """Telegram would take one character; this deployment holds the secret to+ the same 32-character floor as the others it chooses."""+ with pytest.raises(ValueError, match="at least 32 characters"):+ _config(+ **{**_APP, "telegram_app_webhook_secret": "x" * 31},+ messaging_public_url=_ORIGIN,+ )+++def test_a_token_not_shaped_like_one_raises() -> None:+ with pytest.raises(ValueError, match="TELEGRAM_APP_BOT_TOKEN"):+ _config(+ **{**_APP, "telegram_app_bot_token": "not-a-token"},+ messaging_public_url=_ORIGIN,+ )++[email protected]("port", [443, 80, 88, 8443])+def test_the_ports_telegram_delivers_to_are_accepted(port: int) -> None:+ _config(**_APP, messaging_public_url=f"https://switch.example:{port}")+++def test_any_other_port_raises() -> None:+ with pytest.raises(ValueError, match="8443"):+ _config(**_APP, messaging_public_url="https://switch.example:8080")diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 1d3ccb57c..33aa71bb5 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -252,6 +252,8 @@ services:# below: `${VAR:-}` would hand them an empty string, which fails boot.DISCORD_APP_MESSAGE_CONTENT:DISCORD_APP_MEMBERS:+ TELEGRAM_APP_BOT_TOKEN: ${TELEGRAM_APP_BOT_TOKEN:-}+ TELEGRAM_APP_WEBHOOK_SECRET: ${TELEGRAM_APP_WEBHOOK_SECRET:-}# Observability and log format. Forwarded because this service names# every variable it passes, so without them here, setting any of these# in `.env` does nothing and the Helm chart is the only way to turndiff --git a/deploy/observability/README.md b/deploy/observability/README.mdindex 79c09f0be..7e9a1f003 100644--- a/deploy/observability/README.md+++ b/deploy/observability/README.md@@ -46,8 +46,8 @@ done**Histogram panels need two things, not one.** Request latency, delivery lag,database query duration, pool hold and wait time (`switch.db.pool.hold.duration`,-`switch.db.pool.wait.duration`), platform call duration, the agent buffer's-scan length and duration, and garbage-collection pauses+`switch.db.pool.wait.duration`), platform call duration, rate-limit hold-backs,+the agent buffer's scan length and duration, and garbage-collection pauses(`switch.runtime.gc_pause`) are OTLP histograms, and the`p95:`/`p99:` queries here assume the collector exports them to Datadog as*distributions*. Check the collector's@@ -60,7 +60,8 @@ on a distribution metric and are billed separately.** Enable them per metric inMetrics Summary, and add the tag each panel groups by to that metric'sconfigured tag set (`route` for requests, `operation` for database queries andthe agent buffer, `caller` for pool hold time but not wait time, `generation` for-garbage-collection pauses, `bridge` and `platform` for bridge calls), or+garbage-collection pauses, `bridge` and `platform` for bridge calls, `platform`+and `delivery` for rate-limit hold-backs), or`p95: … by {…}` returns nothing on a fresh account. Empty is the honest outcome either way; a panel is never silentlyswitched to a different statistic.diff --git a/deploy/observability/dashboard.json b/deploy/observability/dashboard.jsonindex a6e8245dd..7a6253a5a 100644--- a/deploy/observability/dashboard.json+++ b/deploy/observability/dashboard.json@@ -703,7 +703,26 @@"layout": {"x": 0,"y": 55,- "width": 12,+ "width": 6,+ "height": 4+ }+ },+ {+ "definition": {+ "type": "timeseries",+ "title": "Publications held back by a rate limit p95 (s) by platform and delivery \u2014 needs distribution mapping, see README",+ "show_legend": true,+ "requests": [+ {+ "q": "p95:switch.bridge.throttle.held{$env,$service} by {platform,delivery}",+ "display_type": "line"+ }+ ]+ },+ "layout": {+ "x": 6,+ "y": 55,+ "width": 6,"height": 4}},@@ -722,7 +741,26 @@"layout": {"x": 0,"y": 59,- "width": 12,+ "width": 6,+ "height": 4+ }+ },+ {+ "definition": {+ "type": "timeseries",+ "title": "Messaging events from unclaimed chats, by platform",+ "show_legend": true,+ "requests": [+ {+ "q": "sum:switch.messaging.events_ignored{$env,$service} by {platform,reason}.as_count()",+ "display_type": "bars"+ }+ ]+ },+ "layout": {+ "x": 6,+ "y": 59,+ "width": 6,"height": 4}},diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex bbf76bacb..81155e5f8 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -103,6 +103,9 @@ TEAMS_APP_NOTIFICATION_PRIVATE_KEY: {{ required "secrets.teamsAppNotificationPriTEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY: {{ .Values.secrets.teamsAppNotificationPreviousPrivateKey | b64enc | quote }}{{- end }}{{- end }}+{{- if .Values.switchCore.telegramApp.enabled }}+TELEGRAM_APP_BOT_TOKEN: {{ required "secrets.telegramAppBotToken is required when switchCore.telegramApp.enabled" .Values.secrets.telegramAppBotToken | b64enc | quote }}+TELEGRAM_APP_WEBHOOK_SECRET: {{ required "secrets.telegramAppWebhookSecret is required when switchCore.telegramApp.enabled" .Values.secrets.telegramAppWebhookSecret | b64enc | quote }}{{- end }}{{/*@@ -827,7 +830,7 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}- name: GATEWAY_PUBLIC_URLvalue: {{ .Values.switchCore.gatewayPublicUrl | quote }}{{- end }}-{{- if or .Values.switchCore.slackApp.enabled .Values.switchCore.discordApp.enabled .Values.switchCore.teamsApp.enabled }}+{{- if or .Values.switchCore.slackApp.enabled .Values.switchCore.discordApp.enabled .Values.switchCore.teamsApp.enabled .Values.switchCore.telegramApp.enabled }}- name: MESSAGING_PUBLIC_URLvalue: {{ required "switchCore.messagingPublicUrl is required when a distributed messaging app is enabled" (include "switch.messagingPublicUrl" .) | quote }}{{- end }}@@ -923,6 +926,18 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}key: TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY{{- end }}{{- end }}+{{- if .Values.switchCore.telegramApp.enabled }}+- name: TELEGRAM_APP_BOT_TOKEN+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TELEGRAM_APP_BOT_TOKEN+- name: TELEGRAM_APP_WEBHOOK_SECRET+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TELEGRAM_APP_WEBHOOK_SECRET+{{- end }}{{- end }}{{/*diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex f88ed9da2..c0d0c9f1e 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -163,6 +163,13 @@ secrets:teamsAppNotificationPrivateKey: ""teamsAppNotificationPreviousPrivateKey: ""+ # Distributed Telegram app (required when switchCore.telegramApp.enabled). The+ # bot token is deployment config shared by every tenant, like Discord's. The+ # webhook secret (32-256 characters of A-Z a-z 0-9 _ -) is the whole of what+ # proves an update came from Telegram.+ telegramAppBotToken: ""+ telegramAppWebhookSecret: ""+# ── Switch Core (FastAPI) ─────────────────────────────────────────────────────switchCore:# Existing Secret with github.json (client_id, client_secret, slug, origin).@@ -343,9 +350,9 @@ switchCore:# open anyone can own a workspace, so this keeps the relay from being used# to mail arbitrary addresses. Operators are exempt.emailsPerDayPerWorkspace: 50- # Public origin every distributed messaging app (Slack, Discord, Teams) is- # reached on — scheme + host, https, no path. Required when any of them is- # enabled, and add /messaging to ingress.agentApiPaths as well. Earlier+ # Public origin every distributed messaging app (Slack, Discord, Teams,+ # Telegram) is reached on — scheme + host, https, no path. Required when any+ # of them is enabled, and add /messaging to ingress.agentApiPaths as well. Earlier# releases took it per app (slackApp.messagingPublicUrl,# discordApp.messagingPublicUrl); those are still read when this is empty.messagingPublicUrl: ""@@ -418,6 +425,21 @@ switchCore:# can tell them apart. Set it before the first approval: Teams takes a# new name only with a newer app package.name: ""++ # The distributed Telegram app: one bot we register whose groups a customer+ # claims with a link from Switch, never seeing a token — as opposed to a+ # self-registered bot an operator pastes a token for. Off unless you have+ # registered such a bot, with Group Privacy turned off in BotFather before it+ # joined any chat.+ #+ # Telegram delivers every update as a webhook to+ # <switchCore.messagingPublicUrl>/messaging/telegram/events, so enabling it commits the+ # deployment to being reachable there on port 443, 80, 88 or 8443 — add+ # /messaging to ingress.agentApiPaths as well. The token and webhook secret+ # are supplied through secrets.telegramAppBotToken /+ # secrets.telegramAppWebhookSecret.+ telegramApp:+ enabled: false# Bearer-token resolution runs before every authenticated request and agents# beat continuously, so a successful resolution is memoised in process for# this many seconds. Only successes are cached — an unknown or revoked tokendiff --git a/docs/old/bridges/README.md b/docs/old/bridges/README.mdindex 63dd1e879..e7a658978 100644--- a/docs/old/bridges/README.md+++ b/docs/old/bridges/README.md@@ -29,6 +29,10 @@ Discord and Microsoft Teams have distributed apps too:[`TEAMS_DISTRIBUTED_APP.md`](TEAMS_DISTRIBUTED_APP.md), the second approved fora whole organisation by its Microsoft admin.+Telegram has one too: a single bot per deployment, receiving updates by webhook,+whose chats a customer connects with a link or code from Switch — see+[`TELEGRAM_DISTRIBUTED_APP.md`](TELEGRAM_DISTRIBUTED_APP.md).+## The onboarding model (same for every bridge)A bridge is an **unowned, workspace-wide integration** that holds platformdiff --git a/docs/old/bridges/TELEGRAM_DISTRIBUTED_APP.md b/docs/old/bridges/TELEGRAM_DISTRIBUTED_APP.mdnew file mode 100644index 000000000..b230692fc--- /dev/null+++ b/docs/old/bridges/TELEGRAM_DISTRIBUTED_APP.md@@ -0,0 +1,225 @@+# The distributed Telegram app++`TELEGRAM_SETUP.md` describes the bot **an operator registers for themselves**:+they create it in BotFather, paste its token into Switch, and add it to their+own chats. This page describes the other one — the bot **we** register once per+deployment, whose chats a customer connects with a link from Switch and which+never requires them to see a token.++They are two separate bots and they will both exist. Nothing here replaces the+other page.++A chat is connected to an organisation that **already exists**. Nothing done in+Telegram brings an organisation into being: every connection starts from a link+or code minted inside Switch by someone signed in to it.++## Why it cannot be the same bot++A self-registered bot is **polled**: Switch asks Telegram for its updates over+a connection it opens, so the deployment needs no inbound route. The shared bot+serves every organisation on the deployment, and Telegram gives a bot exactly+one delivery channel, so it is set up the other way round: Telegram posts every+update to a webhook on this deployment, and Switch works out which organisation+each belongs to from the chat it came from.++Two consequences follow, and both are enforced rather than advised:++- **The shared bot is never polled.** A webhook makes `getUpdates` fail, and a+ poller that got there first would take every organisation's updates. Its+ token is refused as a self-registered bridge, at registration, at start and+ on edit.+- **One bot is one credential for every organisation.** Its token lives in+ deployment secrets, never in the database or a connection's config, and is+ never shown to a customer. Treat it as the deployment's most sensitive+ messaging credential.++## Register the bot++1. In [@BotFather](https://t.me/BotFather), send `/newbot`, give it a display+ name and a username ending in `bot`, and save the token it replies with.+2. **Turn Group Privacy off before the bot joins any chat:** `/mybots` → the+ bot → **Bot Settings** → **Group Privacy** → **Turn off**. Telegram reads the+ setting when the bot joins a chat, so changing it later fixes no chat the+ bot is already in. Switch logs an error at boot if it is still on.+3. Leave **Allow Groups?** on (BotFather's default). A bot barred from groups+ cannot be added to one, and Telegram answers the link by opening a direct+ chat instead.++Set nothing else in BotFather. The command menu is published by Switch on+every start and would overwrite anything set there.++## Configure the deployment++| Variable | What it is |+| --- | --- |+| `TELEGRAM_APP_BOT_TOKEN` | The token BotFather issued, shaped `<bot id>:<secret>`. |+| `TELEGRAM_APP_WEBHOOK_SECRET` | A secret Telegram echoes back on every update, 32–256 characters of `A-Z a-z 0-9 _ -`. It is the whole of what proves an update came from Telegram. `openssl rand -hex 32` makes a good one. |+| `MESSAGING_PUBLIC_URL` | The origin Telegram posts to: `https`, scheme and host, no path, on port 443, 80, 88 or 8443 — the only ports Telegram delivers to. |++Set both `TELEGRAM_APP_*` values or neither; setting one is refused at startup,+as is a malformed token or secret, a missing origin, or a port Telegram will+not use. Setting them is the whole of turning the app on: there is no separate+switch.++With the Helm chart, set `switchCore.telegramApp.enabled` and+`switchCore.messagingPublicUrl` (the origin every distributed messaging app+shares), and supply the two secrets as+`secrets.telegramAppBotToken` and `secrets.telegramAppWebhookSecret`. The+standalone compose file forwards both variables from `.env`.++**Route `/messaging` to Switch from the internet** — in the chart, add it to+`ingress.agentApiPaths`. Telegram gives up on a URL it cannot reach or whose+certificate it cannot verify.++## What Switch tells Telegram at boot++On every start Switch asks Telegram who the bot is (`getMe`), then points its+delivery at this deployment with `setWebhook` and publishes the command menu+with `setMyCommands`. Doing it on every start keeps the URL, the secret and the+update types in step with the running config: rotating the secret is a+redeploy, not a manual call. The webhook it sets, with `HOST` standing for+`MESSAGING_PUBLIC_URL`'s host:++```json+{+ "url": "https://HOST/messaging/telegram/events",+ "allowed_updates": ["message", "channel_post", "my_chat_member", "callback_query"]+}+```++The start runs in the background and retries, so an unreachable Telegram never+holds up a deployment serving other platforms. Until it succeeds Switch offers+no links, and updates Telegram already holds wait on its side. The webhook is+left set on shutdown, so Telegram holds and retries updates across a restart.++## How a chat is connected++In the dashboard, **Installed apps** → the Telegram card → **Add to Telegram** shows a link+and a code. Both work once, for ten minutes. Switch Console shows the same: an+admin's **Connect** under Messaging apps offers **Add to Telegram**, and once+the workspace has its Telegram connection, anyone can use **Add to Telegram…**+in that connection's menu.++- **A group:** the link opens Telegram's chat picker. Adding the bot through it+ posts the code into the group.+- **A channel:** Telegram carries nothing when a bot is added to a channel, so+ add the bot as an administrator with permission to post — **Administrators**+ → **Add Admin**, searching for the full `@username` the dialog shows, since+ Telegram does not find a bot by part of it — then post `/connect <code>` in+ the channel.++Either way the code connects nothing yet. The bot asks in the chat, naming the+Switch organisation and the person who made the link, with **Connect** and+**Cancel**: a link can be forwarded to anyone, so whoever used it may not know+whose it is. Asking spends the code, so it cannot be copied out of the chat and+used elsewhere, and only a press in that chat answers it, within 15 minutes.+When an admin of the chat chooses Connect, Switch creates the chat's room and+the bot says what it can see. Cancel connects nothing and the bot leaves. A+press from anyone else gets a private notice, and the question stays for an+admin to answer. A restart of Switch forgets an unanswered question; its+buttons then say the code has expired.++ What agents say in the room is posted to the channel either way. Posts in+ the channel reach the room only when its **Sign Messages** and **Show+ Authors' Profiles** settings are both on and the admin posts as themselves:+ a post made as the channel names no one, and is not bridged.++Who may connect one:++- **In Telegram, only the chat's creator or an admin.** Whoever adds the bot+ through the link, or posts `/connect <code>`, must be one, and so must+ whoever chooses Connect or Cancel. Switch asks Telegram before spending the+ code, so if someone else tries, a group admin can still use the same link.+ In a channel only admins can post, and an anonymous admin's message counts+ as an admin's.+- **The first chat is an admin's.** It creates the organisation's Telegram+ connection, which is what turns Telegram on for it.+- **After that, any member** may connect more chats and disconnect any one of+ them, the last included. A chat is a room, and rooms are members'. A room+ made private takes its chat with it: a member who cannot read the room does+ not see the chat in the Telegram card, and one who cannot write to it cannot+ disconnect it. Its owner and admins still can. A chat whose room is gone,+ deleted or moved elsewhere, is left to admins to disconnect.+- **Turning Telegram off is an admin's**: it is deleting the connection, and+ connections are admins'.++Every chat an organisation connects shares its one connection, so a person+links their Telegram account once and is recognised in all of them.++When a connection does not happen, the bot says why in the chat: the link or+code has expired or was used, the code is not from this deployment, the chat is already+connected to Switch, only an admin can connect the first chat, or only an admin+of the group can connect it. It never says+which organisation holds a chat. A code posted in a chat its organisation already+holds is not answered.++A chat's room comes only from connecting it. The room form's **Use existing+channel** is off for the Telegram app, and a room cannot be moved onto it with+a chat id either: the bot is in every organisation's chats, so it could reach+one another organisation connected. A connected chat already has its room.++## What the bot does in chats nobody connected++The bot can be added to a group without a link — by anyone who finds it. It+then posts one message, ten seconds later and only if no connection has landed+in the meantime, saying the chat is not connected and how to connect it, and+after that it stays and says nothing. In a channel it posts nothing: a channel+is always added before its code is posted, and anything the bot said there+would reach every subscriber.++With Group Privacy off it still receives everything said there. **None of it is+stored, dispatched or logged.** Each such update is counted in+`switch.messaging.events_ignored` and dropped.++A direct message to the bot gets a reply saying direct messages reach no one,+as the self-registered bot's does.++## Disconnecting++- **A chat:** **Disconnect** on the chat's row in the Telegram card, or on+ its row under the Telegram connection in Switch Console. The bot leaves the+ chat and its room becomes internal-only; every other chat keeps working. If+ Telegram refuses to let the bot leave, nothing changes and the error says to+ try again.+- **Removing the bot in Telegram** ends that chat's connection the same way,+ from Telegram's side.+- **Telegram itself:** the organisation's Telegram connection stays when its+ last chat goes, however it went, so Telegram stays on and a member can+ connect a chat again. To turn it off, an admin disconnects any chats left+ and then deletes the Telegram connection from the list of connections. The+ delete is refused while any chat is still connected, since the bot would+ stay in it. Deleting the connection also forgets everyone's linked Telegram+ account; the next admin to connect a chat starts a new one.++## Rotating credentials++- **The bot token:** send `/revoke` to BotFather, put the new token in+ `TELEGRAM_APP_BOT_TOKEN`, and redeploy. Nothing stored needs changing, because+ nothing stored holds it.+- **The webhook secret:** change `TELEGRAM_APP_WEBHOOK_SECRET` and redeploy.+ The next start sets it on the webhook.++## Watching it++- **Delivery.** Every five minutes Switch asks Telegram how delivery to the+ webhook is going (`getWebhookInfo`) and logs a warning on a new delivery+ error, or when the backlog of updates Telegram is holding grows past 50. It+ is the only view of what Telegram has given up on.+- **Lost messages.** A supergroup's messages sent between its conversion and+ the connection following it to the new chat id are lost, and are logged as+ an error with their count.+- **Rate limits.** One bot serves every organisation, so a burst in one holds+ back the others. `switch.bridge.throttle.held` with `delivery=shared` shows+ how long publications are held back.+- **Unclaimed traffic.** `switch.messaging.events_ignored` counts updates from+ chats nobody connected.++## Left out on purpose++- **Linking a Telegram account by direct message.** People link themselves the+ way they do on the self-registered bot, once per organisation.+- **Bridging direct messages.** A direct message belongs to no organisation.+- **Fair sharing of the bot's send rate between organisations.** Deferred until+ the metric above says it is needed.+- **Leaving unclaimed chats automatically.** The bot stays, quiet, so a channel+ admin can post the code after adding it.diff --git a/docs/old/observability.md b/docs/old/observability.mdindex 4c019ad32..65702a9f5 100644--- a/docs/old/observability.md+++ b/docs/old/observability.md@@ -250,6 +250,14 @@ handled in a way that leaves no trace.- **`switch.bridge.errors`** — an inbound bridge failure is a message a personsent that nobody received; from the platform it is indistinguishable frombeing ignored.+- **`switch.bridge.throttle.held`** — how long a platform rate limit held a+ publication back. On a shared app bot one tenant's burst holds back every+ tenant, so a rising `delivery=shared` reading is the signal that per-tenant+ fairness is needed.+- **`switch.messaging.events_ignored`** — events from chats nobody claimed,+ on a platform where the app routinely sits in them (a shared Telegram bot+ with Group Privacy off). Counted instead of logged, so the drops that are+ real losses — a bridge down, a migration's window — keep their own errors.- **`switch.connectors.running`** — connectors start fire-and-forget, eachfailure logged and stepped over, so one that never came up is a dead agenthost nothing else reports.diff --git a/gateway/src/assets/bridges/discord.svg b/gateway/src/assets/bridges/discord.svgnew file mode 100644index 000000000..ef9e17e5a--- /dev/null+++ b/gateway/src/assets/bridges/discord.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/gateway/src/assets/bridges/slack.svg b/gateway/src/assets/bridges/slack.svgnew file mode 100644index 000000000..86f521f37--- /dev/null+++ b/gateway/src/assets/bridges/slack.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/gateway/src/assets/bridges/telegram.svg b/gateway/src/assets/bridges/telegram.svgnew file mode 100644index 000000000..480149bb5--- /dev/null+++ b/gateway/src/assets/bridges/telegram.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/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 6662f8e96..0e0fe8ed7 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -145,6 +145,9 @@ export interface BridgeDetail {// Whether this operator has allowed this connection to create channels.// Only meaningful when channel_creation_supported is true.channel_creation_enabled: boolean;+ // Why no existing channel can be linked by id on this connection, or null+ // when one can — the Switch Telegram app, whose chats come from connecting.+ channel_ids_refused?: string | null;room_count: number;created_at: string;// Empty for platforms whose app is installed through their own admin UI.@@ -1013,6 +1016,10 @@ export interface InstalledApp {id: string;platform: string;external_workspace_id: string;+ // What a person calls it — a chat's room, or the workspace an OAuth install+ // came from — while it still has one. Null once it has ended, and absent+ // from a server that predates it.+ name?: string | null;// "active", "disconnected" (ended here) or "revoked" (ended at the// platform). The last two are kept apart because an operator whose// connection stopped working needs to know which of the two it was.@@ -1024,9 +1031,32 @@ export interface InstalledApp {ended_at: string | null;}-export async function fetchInstallablePlatforms(): Promise<string[] | null> {- const res = await fetchJson<{ platforms: string[] }>("/messaging-apps");- return res === null ? null : res.platforms;+// A platform installed by claiming a chat (Telegram) rather than by OAuth, and+// what the signed-in person may do with it. Worked out by the server because+// the split — an admin connects the first chat, members the rest — depends on+// whether the organisation has a connection yet. `connected` outlives the+// chats: the connection stays until an admin deletes it.+export interface ClaimablePlatform {+ platform: string;+ connected: boolean;+ can_add_chat: boolean;+}++// The OAuth platforms, offered to a tenant admin only, as the list they have+// always been read as — with the claim-based platforms carried alongside, from+// the same response, rather than fetched a second time.+export type InstallablePlatforms = string[] & {+ claimable?: ClaimablePlatform[];+};++export async function fetchInstallablePlatforms(): Promise<InstallablePlatforms | null> {+ const res = await fetchJson<{+ platforms: string[];+ claimable?: ClaimablePlatform[];+ }>("/messaging-apps");+ return res === null+ ? null+ : Object.assign([...res.platforms], { claimable: res.claimable ?? [] });}export async function fetchInstalledApps(): Promise<InstalledApp[] | null> {@@ -1047,6 +1077,19 @@ export async function beginAppInstall(platform: string): Promise<string> {return res.authorize_url;}+// A link that adds the bot to a group and connects it, and the bare code a+// channel admin posts as `/connect <code>` instead, after adding the bot by+// `bot_handle`. The link and code work once, for ten minutes.+export interface ChatClaim {+ url: string;+ code: string;+ bot_handle: string;+}++export async function beginChatClaim(platform: string): Promise<ChatClaim> {+ return jsonRequest<ChatClaim>(`/messaging-apps/${platform}/claim`, "POST");+}+// Throwing, because 502 here means the platform refused to revoke, nothing was// destroyed, and trying again is the right next move — all of which is in the// message and none of which survives a boolean.diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.tsindex 17409042d..ee28d38e2 100644--- a/gateway/src/data/hooks.ts+++ b/gateway/src/data/hooks.ts@@ -13,6 +13,7 @@ import {type DocumentDetail,type DocumentSummary,type InboundLinkedRoomDetail,+ type InstallablePlatforms,type InstalledApp,type KnownAgentType,type LinkedRoomDetail,@@ -168,7 +169,7 @@ export function useAllExternalUsers(): UseQueryResult<ExternalUserSummary[]> {// Empty on every deployment that registered no app of its own, which is most// of them — the page reads that as "there is nothing to install here", not as// a failure.-export function useInstallablePlatforms(): UseQueryResult<string[]> {+export function useInstallablePlatforms(): UseQueryResult<InstallablePlatforms> {return useQuery(fetchInstallablePlatforms);}diff --git a/gateway/src/pages/collaborations/ClaimChatDialog.tsx b/gateway/src/pages/collaborations/ClaimChatDialog.tsxnew file mode 100644index 000000000..ba5a273ff--- /dev/null+++ b/gateway/src/pages/collaborations/ClaimChatDialog.tsx@@ -0,0 +1,154 @@+import ContentCopyOutlined from "@mui/icons-material/ContentCopyOutlined";+import OpenInNewOutlined from "@mui/icons-material/OpenInNewOutlined";+import {+ Alert,+ Box,+ Button,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ IconButton,+ Stack,+ Tooltip,+ Typography,+} from "@mui/material";+import { useState } from "react";+import type { ChatClaim } from "../../data/api";+import { MONO_SX, titleCase } from "../../theme/hootFormat";++interface Props {+ platform: string;+ /** The claim to show, or null when the dialog is closed. */+ claim: ChatClaim | null;+ onClose: () => void;+}++/** Connecting a chat to a claim-based platform (Telegram).+ *+ * Shown rather than navigated to, unlike an OAuth install: there is no+ * consent screen to send the browser to, only a link that opens the+ * platform's own chat picker, and a code for the one kind of chat the link+ * cannot reach. A channel carries no state when a bot is added to it, so its+ * admin adds the bot by its handle and then posts the code. The handle is+ * shown whole because Telegram's search does not find a bot by part of it.+ * The link and code work once, for ten minutes, which is said here because a+ * link that quietly stopped working looks exactly like one that never did. */+export default function ClaimChatDialog({ platform, claim, onClose }: Props) {+ const [copied, setCopied] = useState<string | null>(null);+ const command = claim ? `/connect ${claim.code}` : "";+ const handle = claim?.bot_handle ?? "";+ const name = titleCase(platform);++ const copy = async (text: string) => {+ await navigator.clipboard.writeText(text);+ setCopied(text);+ };++ const close = () => {+ setCopied(null);+ onClose();+ };++ return (+ <Dialog open={!!claim} onClose={close} maxWidth="sm" fullWidth>+ <DialogTitle>Add to {name}</DialogTitle>+ <DialogContent>+ <Stack spacing={2.5} sx={{ mt: 0.5 }}>+ <Stack spacing={1} alignItems="flex-start">+ <Button+ variant="contained"+ startIcon={<OpenInNewOutlined />}+ href={claim?.url ?? ""}+ target="_blank"+ rel="noreferrer noopener"+ >+ Add to a {name} group+ </Button>+ <Typography variant="body2" color="text.secondary">+ Pick a group and confirm. The bot joins and asks which Switch+ organisation the group is for; when a group admin chooses+ Connect, Switch creates the group's room.+ </Typography>+ </Stack>++ <Stack spacing={1}>+ <Typography variant="body2">+ For a channel, open its Administrators, choose Add Admin, and+ search for the bot by its full username:+ </Typography>+ <Copyable+ text={handle}+ label="Copy the bot's username"+ copied={copied}+ onCopy={copy}+ />+ <Typography variant="body2">+ Keep its permission to post, save, then post this in the+ channel and choose Connect when the bot asks:+ </Typography>+ <Copyable+ text={command}+ label="Copy the command"+ copied={copied}+ onCopy={copy}+ />+ <Typography variant="body2" color="text.secondary">+ Agents can always post to the channel. For posts in the channel to+ reach agents, turn on Sign Messages and Show Authors'+ Profiles in its settings, and post as yourself rather than as the+ channel.+ </Typography>+ </Stack>++ <Alert severity="info" variant="outlined">+ The link and the code work once, for ten minutes. Anyone who has+ them in that time can ask to connect a chat to this organisation,+ so share them only with people who should.+ </Alert>+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={close}>Close</Button>+ </DialogActions>+ </Dialog>+ );+}++function Copyable({+ text,+ label,+ copied,+ onCopy,+}: {+ text: string;+ label: string;+ copied: string | null;+ onCopy: (text: string) => void;+}) {+ return (+ <Stack direction="row" alignItems="center" spacing={1}>+ <Box+ component="code"+ sx={{+ ...MONO_SX,+ px: 1,+ py: 0.5,+ borderRadius: 1,+ bgcolor: "action.hover",+ }}+ >+ {text}+ </Box>+ <Tooltip title={copied === text ? "Copied" : "Copy"}>+ <IconButton+ size="small"+ onClick={() => onCopy(text)}+ aria-label={label}+ >+ <ContentCopyOutlined fontSize="small" />+ </IconButton>+ </Tooltip>+ </Stack>+ );+}diff --git a/gateway/src/pages/collaborations/CollaborationsPage.tsx b/gateway/src/pages/collaborations/CollaborationsPage.tsxindex c499546c0..8d1a57836 100644--- a/gateway/src/pages/collaborations/CollaborationsPage.tsx+++ b/gateway/src/pages/collaborations/CollaborationsPage.tsx@@ -11,7 +11,6 @@ import {Dialog,DialogActions,DialogContent,- DialogContentText,DialogTitle,IconButton,Stack,@@ -25,7 +24,6 @@ import DataTable from "../../components/DataTable";import {type BridgeDetail,beginAppInstall,- deleteBridge,updateBridge,} from "../../data/api";import { useAuth } from "../../data/AuthContext";@@ -33,6 +31,8 @@ import { useBridges, useInstallablePlatforms } from "../../data/hooks";import { formatDate, platformLabel, titleCase } from "../../theme/hootFormat";import AddToChatDialog from "./AddToChatDialog";import AttentionBanner from "./AttentionBanner";+import DeleteConnectionText from "./DeleteConnectionText";+import { deleteConnection, mayHoldChats } from "./deleteConnection";import InstalledAppsSection from "./InstalledAppsSection";import RegisterMessagingAppDialog from "./RegisterMessagingAppDialog";import TeamsPlacementDialog from "./TeamsPlacementDialog";@@ -58,13 +58,16 @@ export default function CollaborationsPage() {const [teamsTarget, setTeamsTarget] = useState<BridgeDetail | null>(null);const [approvingId, setApprovingId] = useState<string | null>(null);const [approveError, setApproveError] = useState<string | null>(null);+ // Bumped to reload the installed apps after deleting a connection+ // disconnected its chats.+ const [installsVersion, setInstallsVersion] = useState(0);const handleDelete = useCallback(async () => {if (!deleteTarget) return;setDeleting(true);setDeleteError(null);try {- await deleteBridge(deleteTarget.bridge_id);+ await deleteConnection(deleteTarget);setDeleteTarget(null);refetch();} catch (e) {@@ -74,6 +77,9 @@ export default function CollaborationsPage() {setDeleteError(e instanceof Error ? e.message : "Failed to delete");} finally {setDeleting(false);+ // Its chats were disconnected on the way, however far it got, so the+ // installed apps listed below are stale.+ if (mayHoldChats(deleteTarget)) setInstallsVersion((v) => v + 1);}}, [deleteTarget, refetch]);@@ -291,7 +297,11 @@ export default function CollaborationsPage() {<DataTable rows={rows} columns={columns} />)}- <InstalledAppsSection isAdmin={isAdmin} onConnectionsChanged={refetch} />+ <InstalledAppsSection+ key={installsVersion}+ isAdmin={isAdmin}+ onConnectionsChanged={refetch}+ /><RegisterMessagingAppDialogopen={registerOpen}@@ -320,12 +330,7 @@ export default function CollaborationsPage() {><DialogTitle>Delete collaboration bridge</DialogTitle><DialogContent>- <DialogContentText>- Are you sure you want to delete "{deleteTarget?.display_name}" (- {deleteTarget?.bridge_type})? This will also delete all{" "}- {deleteTarget?.room_count ?? 0} associated room- {deleteTarget?.room_count === 1 ? "" : "s"} and external users.- </DialogContentText>+ {deleteTarget && <DeleteConnectionText bridge={deleteTarget} />}{deleteError && (<Alert severity="error" sx={{ mt: 2 }}>{deleteError}diff --git a/gateway/src/pages/collaborations/DeleteConnectionText.tsx b/gateway/src/pages/collaborations/DeleteConnectionText.tsxnew file mode 100644index 000000000..2e040f20a--- /dev/null+++ b/gateway/src/pages/collaborations/DeleteConnectionText.tsx@@ -0,0 +1,72 @@+import { DialogContentText } from "@mui/material";+import { useEffect, useState } from "react";+import type { BridgeDetail } from "../../data/api";+import { connectedChats, mayHoldChats } from "./deleteConnection";++/**+ * What deleting a connection does, for its confirmation.+ *+ * Deleting takes every room on the connection with it — except on a Switch+ * Telegram app connection, whose chats are disconnected first and keep their+ * rooms. Which of the two applies is only known once its chats have been+ * counted, so until then this says it is checking rather than warn about the+ * wrong thing.+ */+export default function DeleteConnectionText({ bridge }: { bridge: BridgeDetail }) {+ const holdsChats = mayHoldChats(bridge);+ const [chats, setChats] = useState<number | null>(holdsChats ? null : 0);+ const [failed, setFailed] = useState(false);++ useEffect(() => {+ if (!holdsChats) return;+ let current = true;+ connectedChats(bridge)+ .then((found) => {+ if (current) setChats(found.length);+ })+ .catch(() => {+ if (current) setFailed(true);+ });+ return () => {+ current = false;+ };+ }, [bridge, holdsChats]);++ const rooms = (+ <>+ This will also delete all {bridge.room_count} associated room+ {bridge.room_count === 1 ? "" : "s"} and external users.+ </>+ );++ if (failed) {+ return (+ <DialogContentText>+ Could not check which chats are still connected through "+ {bridge.display_name}". Deleting it disconnects each of them+ first, keeping their rooms as internal-only rooms.+ </DialogContentText>+ );+ }+ if (chats === null) {+ return <DialogContentText>Checking which chats are still connected…</DialogContentText>;+ }+ if (chats === 0) {+ return (+ <DialogContentText>+ Are you sure you want to delete "{bridge.display_name}" (+ {bridge.bridge_type})? {rooms}+ </DialogContentText>+ );+ }+ return (+ <DialogContentText>+ {chats === 1 ? "1 chat is" : `${chats} chats are`} still connected through+ "{bridge.display_name}". Deleting it disconnects{" "}+ {chats === 1 ? "it" : "each of them"} first: the bot leaves, and the+ chat's room is kept as an internal-only room, reachable only from+ inside Switch. Then the connection is deleted, which turns Telegram off+ for this organisation.+ </DialogContentText>+ );+}diff --git a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx b/gateway/src/pages/collaborations/DisconnectAppDialog.tsxindex 4f54e8b23..bcb1d7b0d 100644--- a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx+++ b/gateway/src/pages/collaborations/DisconnectAppDialog.tsx@@ -35,15 +35,38 @@ import { platformLabel } from "../../theme/hootFormat";* whether the install has a token, but that field is not surfaced here. Any* platform not listed gets the default (revoking) copy. `noun` is what the* platform calls the place installed into — a Discord "server", not a- * "workspace".+ * "workspace". `rooms` is what happens to Switch's side: for most platforms+ * the whole connection goes, but a Telegram chat is one room on a connection+ * every other chat of the organisation keeps using.*/-const PLATFORM_COPY: Record<string, { noun: string; effect: string }> = {+interface Copy {+ noun: string;+ effect: string;+ rooms: string;+}++const CONNECTION_ROOMS = (noun: string) =>+ "Rooms that used this connection are kept, but become internal-only: they " ++ `stop mirroring to the ${noun}, and installing again creates a new ` ++ "connection rather than reattaching them.";++const PLATFORM_COPY: Record<string, Copy> = {discord: {noun: "server",effect:"Switch will stop mirroring messages to and from it. The bot stays in " +"the server until you remove it in Discord — disconnecting here does " +"not remove it.",+ rooms: CONNECTION_ROOMS("server"),+ },+ telegram: {+ noun: "chat",+ effect: "The bot leaves the chat, and Switch stops mirroring it.",+ rooms:+ "The chat's room is kept, but becomes internal-only, and connecting " ++ "the chat again creates a new room rather than reattaching it. Other " ++ "connected Telegram chats are not affected, and Telegram stays on for " ++ "this organisation even when this is its last chat.",},// The distributed Teams app holds no per-workspace token to revoke: one// install serves the whole Microsoft organisation, so disconnecting only@@ -57,15 +80,23 @@ const PLATFORM_COPY: Record<string, { noun: string; effect: string }> = {"the app itself: a Microsoft admin removes \"Agent Switch\" in the " +"Teams admin center, and the enterprise application in the Microsoft " +"Entra admin center, to take it out of the organisation entirely.",+ rooms: CONNECTION_ROOMS("organisation"),},};-const DEFAULT_COPY = {+const DEFAULT_COPY: Copy = {noun: "workspace",effect:"Switch's access token is revoked at the platform and the connection it " +"created is removed.",+ rooms: CONNECTION_ROOMS("workspace"),};+/** What `platform` calls the place an install goes into: a Discord server,+ * a Telegram chat, a Slack workspace. */+export function installNoun(platform: string): string {+ return (PLATFORM_COPY[platform] ?? DEFAULT_COPY).noun;+}+interface Props {install: InstalledApp | null;onClose: () => void;@@ -107,13 +138,10 @@ export default function DisconnectAppDialog({<DialogContent><DialogContentText>Disconnect Switch from the {platformLabel(install?.platform ?? "")}{" "}- {copy.noun} <b>{install?.external_workspace_id}</b>? {copy.effect}- </DialogContentText>- <DialogContentText sx={{ mt: 2 }}>- Rooms that used this connection are kept, but become internal-only:- they stop mirroring to the {copy.noun}, and installing again creates a- new connection rather than reattaching them.+ {copy.noun} <b>{install?.name ?? install?.external_workspace_id}</b>?{" "}+ {copy.effect}</DialogContentText>+ <DialogContentText sx={{ mt: 2 }}>{copy.rooms}</DialogContentText>{error && (<Alert severity="error" sx={{ mt: 2 }}>{error}diff --git a/gateway/src/pages/collaborations/InstalledAppsSection.tsx b/gateway/src/pages/collaborations/InstalledAppsSection.tsxindex 2bb4f1be9..c50440e3d 100644--- a/gateway/src/pages/collaborations/InstalledAppsSection.tsx+++ b/gateway/src/pages/collaborations/InstalledAppsSection.tsx@@ -1,22 +1,36 @@-import LinkOffOutlined from "@mui/icons-material/LinkOffOutlined";import {Alert,Box,Button,Chip,CircularProgress,- IconButton,+ Divider,+ Paper,Stack,Tooltip,Typography,} from "@mui/material";-import type { GridColDef } from "@mui/x-data-grid";import { useCallback, useMemo, useState } from "react";-import DataTable from "../../components/DataTable";-import { type InstalledApp, beginAppInstall } from "../../data/api";+import {+ type ChatClaim,+ type ClaimablePlatform,+ type InstalledApp,+ beginAppInstall,+ beginChatClaim,+} from "../../data/api";import { useInstallablePlatforms, useInstalledApps } from "../../data/hooks";-import { EM_DASH, MONO_SX, formatDate, platformLabel, titleCase } from "../../theme/hootFormat";-import DisconnectAppDialog from "./DisconnectAppDialog";+import {+ MONO_SX,+ formatDate,+ pluralize,+ platformLabel,+ titleCase,+} from "../../theme/hootFormat";+import discordIcon from "../../assets/bridges/discord.svg";+import slackIcon from "../../assets/bridges/slack.svg";+import telegramIcon from "../../assets/bridges/telegram.svg";+import ClaimChatDialog from "./ClaimChatDialog";+import DisconnectAppDialog, { installNoun } from "./DisconnectAppDialog";/*** The other way a connection comes into being. Registering an app means@@ -32,11 +46,27 @@ import DisconnectAppDialog from "./DisconnectAppDialog";* Renders nothing at all on a deployment that has no app of its own and has* never had one, which is most of them: an empty section explaining a feature* nobody here can use is worse than no section.+ *+ * One card per platform, each carrying its own actions, so the page does not+ * grow a row of buttons with every app. Installs are listed by name; ended+ * ones, which are history rather than state, are folded away.+ *+ * A claim-based platform (Telegram) is installed a chat at a time, and a chat+ * is a room rather than a connection. So its buttons are offered to whoever+ * the server says may use them — an admin to connect the first chat, anyone+ * after that — and any member may disconnect one of its chats, where every+ * OAuth action here is a tenant admin's. Its connection outlives its chats,+ * and is turned off by deleting it with the other connections.*/-type InstallRow = InstalledApp & { id: string };-const STATUS_COLOR: Record<string, "success" | "warning" | "default"> = {- active: "success",+// The platform's own logo on its Add button, as Switch Console shows it.+const PLATFORM_ICON: Record<string, string> = {+ discord: discordIcon,+ slack: slackIcon,+ telegram: telegramIcon,+};++const ENDED_COLOR: Record<string, "warning" | "default"> = {// Ended at the platform rather than here — somebody removed the app, or its// token was killed. Warned rather than greyed out, because unlike// "disconnected" it is news.@@ -55,14 +85,32 @@ export default function InstalledAppsSection({isAdmin,onConnectionsChanged,}: Props) {- const { data: platforms } = useInstallablePlatforms();+ const { data: offered, refetch: refetchOffered } = useInstallablePlatforms();const { data: installs, loading, refetch } = useInstalledApps();const [starting, setStarting] = useState<string | null>(null);+ const [claim, setClaim] = useState<{+ platform: string;+ claim: ChatClaim;+ } | null>(null);const [error, setError] = useState<string | null>(null);const [disconnectTarget, setDisconnectTarget] = useState<InstalledApp | null>(null,);+ const claimable = useMemo(() => offered?.claimable ?? [], [offered]);+ const installable = useMemo(() => (offered ? [...offered] : []), [offered]);+ const rows = useMemo(() => installs ?? [], [installs]);++ // Every platform this organisation can add to, or has anything recorded+ // for — a platform whose app was since removed still shows its history.+ const platforms = useMemo(() => {+ const seen = new Set<string>();+ for (const c of claimable) seen.add(c.platform);+ if (isAdmin) for (const p of installable) seen.add(p);+ for (const row of rows) seen.add(row.platform);+ return [...seen];+ }, [claimable, installable, rows, isAdmin]);+const handleInstall = useCallback(async (platform: string) => {setStarting(platform);setError(null);@@ -78,135 +126,49 @@ export default function InstalledAppsSection({}}, []);+ const handleClaim = useCallback(async (platform: string) => {+ setStarting(platform);+ setError(null);+ try {+ setClaim({ platform, claim: await beginChatClaim(platform) });+ } catch (e) {+ setError(+ e instanceof Error ? e.message : "Failed to start connecting a chat",+ );+ } finally {+ setStarting(null);+ }+ }, []);++ // A claim lands in the chat, not here, so the list is refreshed when the+ // dialog closes rather than waited on.+ const handleClaimClosed = useCallback(() => {+ setClaim(null);+ refetch();+ refetchOffered();+ onConnectionsChanged();+ }, [refetch, refetchOffered, onConnectionsChanged]);+const handleDisconnected = useCallback(() => {setDisconnectTarget(null);refetch();+ refetchOffered();onConnectionsChanged();- }, [refetch, onConnectionsChanged]);-- const columns = useMemo<GridColDef<InstallRow>[]>(- () => [- {- field: "platform",- headerName: "Platform",- width: 130,- renderCell: ({ value }) => (- <Chip label={platformLabel(String(value))} size="small" />- ),- },- {- field: "external_workspace_id",- headerName: "Workspace",- width: 170,- renderCell: ({ value }) => (- <Box component="span" sx={MONO_SX}>- {String(value)}- </Box>- ),- },- {- field: "status",- headerName: "Status",- width: 140,- renderCell: ({ value }) => (- <Chip- label={titleCase(String(value))}- size="small"- color={STATUS_COLOR[value as string] ?? "default"}- />- ),- },- {- field: "scopes",- headerName: "Scopes",- flex: 1,- minWidth: 180,- // Verbatim, and in full on hover: a scope string that means nothing- // here is still the answer to why the platform refused a call.- renderCell: ({ value }) => (- <Tooltip title={String(value)}>- <Box component="span" sx={MONO_SX}>- {String(value)}- </Box>- </Tooltip>- ),- },- {- field: "installed_at",- headerName: "Installed",- width: 130,- valueFormatter: (value) => formatDate(value as string),- },- {- field: "ended_at",- headerName: "Ended",- width: 130,- valueFormatter: (value) =>- value ? formatDate(value as string) : EM_DASH,- },- ...(isAdmin- ? [- {- field: "actions" as const,- headerName: "",- width: 70,- sortable: false,- filterable: false,- align: "right" as const,- renderCell: ({ row }: { row: InstallRow }) =>- row.status === "active" ? (- <Tooltip title="Disconnect this app">- <IconButton- size="small"- onClick={() => setDisconnectTarget(row)}- >- <LinkOffOutlined fontSize="small" />- </IconButton>- </Tooltip>- ) : null,- },- ]- : []),- ],- [isAdmin],- );+ }, [refetch, refetchOffered, onConnectionsChanged]);- const rows = useMemo<InstallRow[]>(() => installs ?? [], [installs]);-- const installable = platforms ?? [];- if (installable.length === 0 && rows.length === 0) return null;+ if (platforms.length === 0) {+ return null;+ }return (<Box mt={5}>- <Stack direction="row" alignItems="center" mb={1}>- <Typography variant="h5">Installed apps</Typography>- {isAdmin && (- <Stack direction="row" spacing={1} sx={{ ml: "auto" }}>- {installable.map((platform) => (- <Button- key={platform}- variant="contained"- disabled={starting !== null}- startIcon={- starting === platform ? (- <CircularProgress size={16} />- ) : undefined- }- onClick={() => handleInstall(platform)}- >- Add to {platformLabel(platform)}- </Button>- ))}- </Stack>- )}- </Stack>-+ <Typography variant="h5" mb={1}>+ Installed apps+ </Typography><Typography variant="body2" color="text.secondary" mb={2}>- Installing adds this Switch deployment's own app to your workspace.- Unlike a registered app, whose token is yours to rotate, an installed app- authenticates with credentials this deployment holds and you cannot see- or rotate. Removing it has to go through Disconnect rather than deleting- its connection.+ This deployment's own apps, using credentials only the deployment+ holds. Disconnect what an app is installed in here: a connection above+ cannot be deleted while an app is still installed through it.</Typography>{error && (@@ -217,12 +179,27 @@ export default function InstalledAppsSection({{loading ? (<CircularProgress />- ) : rows.length === 0 ? (- <Typography variant="body2" color="text.secondary">- No workspaces yet. Use the button above to install the app into one.- </Typography>) : (- <DataTable rows={rows} columns={columns} height={360} />+ <Stack spacing={2}>+ {platforms.map((platform) => {+ const claimed = claimable.find((c) => c.platform === platform);+ return (+ <PlatformCard+ key={platform}+ platform={platform}+ installs={rows.filter((row) => row.platform === platform)}+ claimable={claimed}+ canInstall={isAdmin && installable.includes(platform)}+ canDisconnect={isAdmin || claimed !== undefined}+ starting={starting}+ onAdd={() =>+ claimed ? handleClaim(platform) : handleInstall(platform)+ }+ onDisconnect={setDisconnectTarget}+ />+ );+ })}+ </Stack>)}<DisconnectAppDialog@@ -230,6 +207,188 @@ export default function InstalledAppsSection({onClose={() => setDisconnectTarget(null)}onDisconnected={handleDisconnected}/>+ <ClaimChatDialog+ platform={claim?.platform ?? ""}+ claim={claim?.claim ?? null}+ onClose={handleClaimClosed}+ /></Box>);}++interface CardProps {+ platform: string;+ installs: InstalledApp[];+ // Set for a claim-based platform, with what this caller may do on it.+ claimable: ClaimablePlatform | undefined;+ canInstall: boolean;+ canDisconnect: boolean;+ starting: string | null;+ onAdd: () => void;+ onDisconnect: (install: InstalledApp) => void;+}++function PlatformCard({+ platform,+ installs,+ claimable,+ canInstall,+ canDisconnect,+ starting,+ onAdd,+ onDisconnect,+}: CardProps) {+ const [showEnded, setShowEnded] = useState(false);+ const name = platformLabel(platform);+ const noun = installNoun(platform);+ const active = installs.filter((row) => row.status === "active");+ const ended = installs.filter((row) => row.status !== "active");+ const canAdd = claimable ? claimable.can_add_chat : canInstall;+ const icon = PLATFORM_ICON[platform];++ return (+ <Paper variant="outlined" sx={{ borderRadius: 2 }}>+ <Stack+ direction="row"+ alignItems="center"+ spacing={1}+ sx={{ px: 2, py: 1.5 }}+ >+ <Box sx={{ flexGrow: 1 }}>+ <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>+ {name}+ </Typography>+ <Typography variant="body2" color="text.secondary">+ {active.length > 0+ ? `${pluralize(active.length, noun)} connected`+ : claimable?.connected+ ? `No ${noun}s connected. The connection stays until an admin deletes it above.`+ : "Not connected"}+ </Typography>+ </Box>+ {canAdd && (+ <Button+ variant="contained"+ disabled={starting !== null}+ startIcon={+ starting === platform ? (+ <CircularProgress size={16} />+ ) : icon ? (+ <Box+ component="img"+ src={icon}+ alt=""+ sx={{ width: 16, height: 16 }}+ />+ ) : undefined+ }+ onClick={onAdd}+ >+ Add to {name}+ </Button>+ )}+ </Stack>++ {active.map((install) => (+ <InstallRow+ key={install.id}+ install={install}+ onDisconnect={canDisconnect ? () => onDisconnect(install) : undefined}+ />+ ))}++ {ended.length > 0 && (+ <>+ <Divider />+ <Box sx={{ px: 1, py: 0.5 }}>+ <Button+ size="small"+ onClick={() => setShowEnded((shown) => !shown)}+ >+ {showEnded ? "Hide ended" : `Show ${ended.length} ended`}+ </Button>+ </Box>+ {showEnded &&+ ended.map((install) => (+ <InstallRow key={install.id} install={install} />+ ))}+ </>+ )}+ </Paper>+ );+}++function InstallRow({+ install,+ onDisconnect,+}: {+ install: InstalledApp;+ onDisconnect?: () => void;+}) {+ const live = install.status === "active";+ return (+ <>+ <Divider />+ <Stack+ direction="row"+ alignItems="center"+ spacing={2}+ sx={{ px: 2, py: 1 }}+ >+ <Box sx={{ flexGrow: 1, minWidth: 0 }}>+ {/* The id is always a hover away: it is what the platform's own+ admin screens and Switch's logs call the install. */}+ <Tooltip+ title={install.external_workspace_id}+ placement="bottom-start"+ >+ <Typography+ variant="body2"+ noWrap+ sx={install.name ? undefined : MONO_SX}+ >+ {install.name ?? install.external_workspace_id}+ </Typography>+ </Tooltip>+ {install.scopes && (+ // Verbatim, and in full on hover: a scope string that means+ // nothing here is still the answer to why the platform refused a+ // call.+ <Tooltip title={install.scopes} placement="bottom-start">+ <Typography+ variant="caption"+ color="text.secondary"+ noWrap+ component="div"+ sx={MONO_SX}+ >+ {install.scopes}+ </Typography>+ </Tooltip>+ )}+ </Box>+ {!live && (+ <Chip+ label={titleCase(install.status)}+ size="small"+ color={ENDED_COLOR[install.status] ?? "default"}+ />+ )}+ <Typography+ variant="body2"+ color="text.secondary"+ sx={{ whiteSpace: "nowrap" }}+ >+ {live+ ? `Connected ${formatDate(install.installed_at)}`+ : `Ended ${formatDate(install.ended_at)}`}+ </Typography>+ {live && onDisconnect && (+ <Button size="small" color="error" onClick={onDisconnect}>+ Disconnect+ </Button>+ )}+ </Stack>+ </>+ );+}diff --git a/gateway/src/pages/collaborations/deleteConnection.test.tsx b/gateway/src/pages/collaborations/deleteConnection.test.tsxnew file mode 100644index 000000000..02b69117f--- /dev/null+++ b/gateway/src/pages/collaborations/deleteConnection.test.tsx@@ -0,0 +1,142 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { BridgeDetail, InstalledApp } from "../../data/api";+import DeleteConnectionText from "./DeleteConnectionText";+import { deleteConnection } from "./deleteConnection";++function bridge(overrides: Partial<BridgeDetail> = {}): BridgeDetail {+ return {+ bridge_id: "b1",+ bridge_type: "telegram",+ display_name: "Telegram",+ status: "active",+ room_count: 2,+ ...overrides,+ } as BridgeDetail;+}++function chat(id: string, overrides: Partial<InstalledApp> = {}): InstalledApp {+ return {+ id,+ platform: "telegram",+ external_workspace_id: `-100${id}`,+ status: "active",+ scopes: "",+ bridge_id: "b1",+ installed_at: "2026-01-01",+ ended_at: null,+ ...overrides,+ };+}++/** Answers each request from `routes` by method and path, and records it. */+function stubFetch(routes: Record<string, [number, unknown]>) {+ const calls: string[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string, init?: RequestInit) => {+ const key = `${init?.method ?? "GET"} ${String(url).replace("/gateway", "")}`;+ calls.push(key);+ const [status, body] = routes[key] ?? [500, { detail: `unexpected ${key}` }];+ return new Response(JSON.stringify(body), { status });+ }),+ );+ return calls;+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("deleteConnection", () => {+ it("disconnects every chat still connected, then deletes the connection", async () => {+ const calls = stubFetch({+ "GET /messaging-apps/installs": [+ 200,+ {+ installs: [+ chat("1"),+ chat("2"),+ chat("3", { status: "disconnected" }),+ chat("4", { bridge_id: "another" }),+ ],+ },+ ],+ "DELETE /messaging-apps/installs/1": [200, chat("1")],+ "DELETE /messaging-apps/installs/2": [200, chat("2")],+ "DELETE /collaborations/b1": [200, { ok: true }],+ });++ await deleteConnection(bridge());++ expect(calls).toEqual([+ "GET /messaging-apps/installs",+ "DELETE /messaging-apps/installs/1",+ "DELETE /messaging-apps/installs/2",+ "DELETE /collaborations/b1",+ ]);+ });++ it("carries on past a chat someone else already disconnected", async () => {+ const calls = stubFetch({+ "GET /messaging-apps/installs": [200, { installs: [chat("1"), chat("2")] }],+ "DELETE /messaging-apps/installs/1": [404, { detail: "Install not found" }],+ "DELETE /messaging-apps/installs/2": [200, chat("2")],+ "DELETE /collaborations/b1": [200, { ok: true }],+ });++ await deleteConnection(bridge());++ expect(calls).toContain("DELETE /collaborations/b1");+ });++ it("stops at a chat the bot cannot leave, leaving the connection in place", async () => {+ const calls = stubFetch({+ "GET /messaging-apps/installs": [200, { installs: [chat("1"), chat("2")] }],+ "DELETE /messaging-apps/installs/1": [+ 502,+ { detail: "Telegram refused to let the bot leave chat -1001." },+ ],+ });++ await expect(deleteConnection(bridge())).rejects.toThrow(+ "Telegram refused to let the bot leave chat -1001.",+ );+ expect(calls).not.toContain("DELETE /messaging-apps/installs/2");+ expect(calls).not.toContain("DELETE /collaborations/b1");+ });++ it("deletes any other connection directly, without reading installs", async () => {+ const calls = stubFetch({ "DELETE /collaborations/b1": [200, { ok: true }] });++ await deleteConnection(bridge({ bridge_type: "teams" }));++ expect(calls).toEqual(["DELETE /collaborations/b1"]);+ });+});++describe("DeleteConnectionText", () => {+ it("says a Telegram connection's chats are disconnected first and keep their rooms", async () => {+ stubFetch({+ "GET /messaging-apps/installs": [200, { installs: [chat("1"), chat("2")] }],+ });++ render(<DeleteConnectionText bridge={bridge()} />);++ const text = await screen.findByText(/2 chats are still connected/);+ expect(text.textContent).toContain("internal-only room");+ expect(text.textContent).not.toContain("delete all");+ });++ it("warns that rooms go with any other connection, without asking the server", () => {+ const calls = stubFetch({});++ render(<DeleteConnectionText bridge={bridge({ bridge_type: "slack", display_name: "Acme" })} />);++ expect(+ screen.getByText(/This will also delete all 2 associated rooms and external users/),+ ).toBeTruthy();+ expect(calls).toEqual([]);+ });+});diff --git a/gateway/src/pages/collaborations/deleteConnection.ts b/gateway/src/pages/collaborations/deleteConnection.tsnew file mode 100644index 000000000..b0b7a726a--- /dev/null+++ b/gateway/src/pages/collaborations/deleteConnection.ts@@ -0,0 +1,62 @@+import {+ ApiError,+ type BridgeDetail,+ type InstalledApp,+ deleteBridge,+ disconnectApp,+ fetchInstalledApps,+} from "../../data/api";++/**+ * Platforms whose app connection holds many chats, each an install of its+ * own, rather than one install per connection. Only the Switch Telegram app's+ * connection has installs; an organisation's own Telegram bot has none, and+ * is deleted as any other connection is.+ */+const CHAT_PLATFORMS = new Set(["telegram"]);++/** Whether `bridge` may hold chats that deleting it disconnects first. */+export function mayHoldChats(bridge: BridgeDetail): boolean {+ return CHAT_PLATFORMS.has(bridge.bridge_type);+}++/** The chats still connected through `bridge`; none for any connection but a+ * Switch Telegram app's. */+export async function connectedChats(+ bridge: BridgeDetail,+): Promise<InstalledApp[]> {+ if (!mayHoldChats(bridge)) return [];+ const installs = await fetchInstalledApps();+ if (installs === null) {+ throw new Error(+ "Could not read which chats are still connected, so nothing was deleted.",+ );+ }+ return installs.filter(+ (i) => i.bridge_id === bridge.bridge_id && i.status === "active",+ );+}++/**+ * Delete a connection, disconnecting every chat still connected through it+ * first.+ *+ * The server refuses to delete a connection a chat still uses, and ending a+ * chat leaves the connection behind, so a Telegram connection is emptied+ * before it is deleted: the bot leaves each chat, whose room is kept as an+ * internal-only room. A chat already ended elsewhere is skipped. One the bot+ * cannot leave stops it there, with the connection and the chats not yet+ * reached still in place; deleting again carries on. Every other connection+ * is deleted as it always was.+ */+export async function deleteConnection(bridge: BridgeDetail): Promise<void> {+ for (const chat of await connectedChats(bridge)) {+ try {+ await disconnectApp(chat.id);+ } catch (e) {+ if (e instanceof ApiError && e.status === 404) continue;+ throw e;+ }+ }+ await deleteBridge(bridge.bridge_id);+}diff --git a/gateway/src/pages/rooms/RoomCreateFormBody.tsx b/gateway/src/pages/rooms/RoomCreateFormBody.tsxindex 59601189d..80588828b 100644--- a/gateway/src/pages/rooms/RoomCreateFormBody.tsx+++ b/gateway/src/pages/rooms/RoomCreateFormBody.tsx@@ -77,6 +77,11 @@ export default function RoomCreateFormBody() {!!selectedBridge &&!(selectedBridge.channel_creation_supported && selectedBridge.channel_creation_enabled);+ // A connection whose chats arrive only one way takes no channel id either,+ // and says how its rooms come about instead.+ const existingChannelRefusal = selectedBridge?.channel_ids_refused ?? null;+ const noChannelSource = channelCreationBlocked && existingChannelRefusal !== null;+const channelCreationBlockedReason = useMemo(() => {if (!selectedBridge || !channelCreationBlocked) return null;if (!selectedBridge.channel_creation_supported) {@@ -88,10 +93,10 @@ export default function RoomCreateFormBody() {// If the user had "Create new channel" selected and then picks a bridge// that can't do that, flip the selection rather than leaving it invalid.useEffect(() => {- if (channelCreationBlocked && channelSource === "new") {+ if (channelCreationBlocked && !noChannelSource && channelSource === "new") {setChannelSource("existing");}- }, [channelCreationBlocked, channelSource]);+ }, [channelCreationBlocked, noChannelSource, channelSource]);const addRole = useCallback(() => setRoles((rs) => [...rs, { name: "", instructions: "", exclusive: false }]),@@ -134,11 +139,12 @@ export default function RoomCreateFormBody() {const canSubmit = useMemo(() => {if (!name.trim() || !description.trim()) return false;if (hasBridge) {+ if (noChannelSource) return false;if (channelSource === "existing" && !externalChannelId.trim()) return false;return true;}return agentIds.length >= 1;- }, [name, description, hasBridge, channelSource, externalChannelId, agentIds]);+ }, [name, description, hasBridge, noChannelSource, channelSource, externalChannelId, agentIds]);const handleSubmit = useCallback(async () => {if (!canSubmit) return;@@ -364,16 +370,17 @@ export default function RoomCreateFormBody() {value="existing"control={<Radio size="small" />}label="Use existing channel"+ disabled={existingChannelRefusal !== null}/></RadioGroup>- {channelCreationBlockedReason && (+ {(noChannelSource ? existingChannelRefusal : channelCreationBlockedReason) && (<Alert severity="info" variant="outlined">- {channelCreationBlockedReason}+ {noChannelSource ? existingChannelRefusal : channelCreationBlockedReason}</Alert>)}- {channelSource === "existing" ? (+ {noChannelSource ? null : channelSource === "existing" ? (<TextFieldlabel="External channel ID"value={externalChannelId}diff --git a/internal/slack-sdk-parity-plan.md b/internal/slack-sdk-parity-plan.mddeleted file mode 100644index 3bb1af085..000000000--- a/internal/slack-sdk-parity-plan.md+++ /dev/null@@ -1,135 +0,0 @@-# Compact SDK Slack parity--## Plan--1. Keep activity in the existing thread. The live status is a compact line with the ticking timer and a directly visible **Console app** link. Tool details remain expandable. The same status message shows the final runtime. The tool log stays second, ahead of request cards. No other cards contain Console links.-2. Keep each permission/question request as its own post. For requests initiated by a Slack message, rely on normal thread notifications. Both thread starters and participants normally follow replies. Do not query or override personal notification preferences. For requests without a threaded Slack initiator, use a linked recipient when available.-3. Update routine state in place. Publish one short thread alert for a turn/session failure that needs attention, with navigation available on the status line. Do not expose raw private SDK notices or tool output.-4. On explicit rejection of Block Kit formatting, retry with compact text in the same thread. Preserve typed request handles, stable recovery markers, and edits to the same message. Never retry an uncertain network outcome as a new post.-5. Run focused rendering, publication, and fallback tests. Record exact local and manual Slack test steps below when implementation is complete.--The initial parity change excluded legacy deletion and architectural refactoring. The follow-up cleanup is recorded below. Role restoration and reset/compact confirmation remain with the SDK developer.--## Research--Slack's [thread documentation](https://slack.com/help/articles/115000769927-Use-threads-to-organize-discussions) says channel/group-DM thread replies notify people who started the thread, replied, or were mentioned. Users can disable these notifications. Therefore an extra mention on every permission card duplicates default notification behaviour without reliably overriding user preferences.--The Console link is directly visible beside the timer. Tool details remain in the expandable plan; timer-only edits do not touch that message.--## Validation and manual test steps--Implementation is complete. Links are presentation metadata built from the configured public server URL and current SDK identifiers. Activity fallback text contains only the plan header, while the blocks retain expandable tool details. An attention message uses a durable slot per command, updates when the problem changes or clears, and does not repeatedly mention the recipient.--### Load the changes--1. Run the Console development build from this checkout. To test Console links against that development build, launch it from `console/` with `SWITCHDASH_REGISTER_DEEPLINK=1 pnpm dev`. This registers the development app as the handler for `switchdash://` links. Otherwise links open the installed Console app.-2. Open the local Switch server page in Console.-3. Enable **Build switch-core from this checkout**.-4. Click **Restart**. Wait for the server to run and the Slack bridge to reconnect. The page should say that switch-core was built from the checkout. These changes run in Switch core; they do not require replacing the SDK host or sidecar.-5. For a managed local server, Console already supplies `GATEWAY_PUBLIC_URL`. For a separately deployed server, set it to the same API address used for that server in Console, then rebuild/restart Switch core. When the setting is absent, the status omits the Console link.--Do not reset the agent to load these changes. Role restoration and reset/compact confirmation are separate upstream fixes.--### Check compact activity and Console navigation--1. Start a test Claude SDK session connected to the Slack room, with **Bypass permissions** disabled.-2. At the channel root, message the agent: `Use Bash to run pwd, then use Bash to run git status --short. Wait for any required approvals.`-3. Verify that activity appears in a thread under your message. There should be no activity broadcast back to the channel root.-4. While the agent is working or waiting, find the compact status line: `Working… 30s · Console app`. The link should stay visible as the timer updates. No expansion is required, and it is not a separate notification or button.-5. Click the link. Console should select the correct server, room, agent, and SDK session.-6. Expand the tool plan. Tool details should still be present, without repeated Console links. Timer-only updates should not redraw or collapse the separate tool log. Tool changes still update that log.-7. After the turn ends, verify that the first status message changes to **Worked for** with the final runtime and **Console app** link. The separate tool log must remain second and expandable; requests stay below it. No status deletion or replacement navigation post should occur. The eyes reaction is removed.-8. Repeat with an agent question before its first tool call. A small **No tool calls yet.** placeholder reserves the second position, then becomes the tool log. No permission or answer card should contain a Console link.--If provider policy allows those commands without asking, use an action already known to require approval in your test setup. Absence of a permission request from the provider is not a Slack rendering failure.--### Check permission posts and notifications--1. Trigger a permission request in the thread above.-2. Verify that it is a separate thread reply with working approval buttons. It should have no Console link, whether open or resolved.-3. Verify that the card contains no extra mention of you. With Slack's default thread notifications enabled, it should appear as a thread reply notification.-4. Approve the request. Verify that the same card changes to its settled state, without a second mention or duplicate request post.-5. Trigger another request and deny it. Confirm that its outcome appears on the same card.--A permission denial is a request outcome, not automatically a turn failure. Its crossed/denied icon is expected. A separate attention reply appears only if the turn fails or the active host/session becomes unavailable or faulted.--6. With a second Slack user, have user A post a root message, then have user B address the agent inside that thread. Trigger an approval. Neither user should get an extra explicit mention. Slack normally notifies both because A started the thread and B replied to it.-7. Check Slack's per-thread notification setting if notifications differ. Switch deliberately does not inspect or override users' muted threads, notification schedules, or device preferences.--For non-Slack origins or unthreaded requests, recipient mapping prefers the initiating person's linked account, then the linked agent owner in that room. Automated tests exercise this branch without requiring a second platform or synthetic production command.--### Exercise errors, retries, and rejected rich rendering--Run from the repository root:--```sh-core/.venv/bin/python -m pytest core/tests/switch_core/bridges/collaboration/test_session_compact_presentation.py core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py -v-```--These tests simulate Slack's explicit formatting rejection and check that one compact text post keeps the thread, request handle, identity, and recovery marker. They also verify that a fallback edit clears old buttons on the same message. Timeouts, rate limits, and authorization errors must not cause a second post.--For real database-backed notification and failure recovery tests on macOS Docker Desktop:--```sh-DOCKER_HOST="unix://${HOME}/.docker/run/docker.sock" TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock core/.venv/bin/python -m pytest core/tests/switch_core/sessions/test_session_presentation.py core/tests/switch_core/sessions/test_attention_durability.py -v-```--These use a temporary test database and simulated Slack responses. Expected behaviours:--- A failed turn or offline/faulted host produces one concise attention reply in the original thread.-- No raw private provider notice or tool output is copied into that reply.-- Repeated polling, lost acknowledgements, and bridge restarts do not duplicate the alert.-- When the host recovers, the same attention reply updates to remove the stale warning.-- Completed error receipts prevent old alerts being replayed.--No failure-injection switch was added to the production app. These deterministic tests cover failure paths that are hard to trigger reliably in a live workspace. The actual Slack expansion and notification behaviour still needs the manual checks above.--When finished testing links in the development app, run `pnpm run deeplink:reset` from `console/` to restore the installed app as the URL handler.--### Review and automated results--The working-tree review removed unused permission-card Console URL fields, URL construction, and URL parameters. It also removed the unused URL argument from attention replies. Notification recipients are now resolved only for initial open-request publication, since redraws never mention them. These changes preserve the tested Slack layout.--The combined regression suite passed **598 tests**:--```sh-DOCKER_HOST="unix://${HOME}/.docker/run/docker.sock" TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock core/.venv/bin/python -m pytest core/tests/switch_core/sessions core/tests/switch_core/bridges/collaboration/test_session*.py core/tests/switch_core/bridges/collaboration/test_slack_adapter.py core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py -q --tb=short-```--Mypy passed for all eight changed source files. Ruff and `git diff --check` passed. The tests cover stable message order, completion, restart recovery, uncertain delivery, notification recipients, and text fallback.--The user accepted the rendered layout and repeated the smoke test after the review cleanup. Existing completed threads are not rewritten.--The separate Console startup/session recovery workarounds and nginx DNS change remain untouched and outside the Slack commit scope. Other pre-existing internal notes also remain outside that scope. Platform expansion and the upstream reset/compact work remain separate follow-ups.--## Legacy rendering removal--After the user accepted SDK parity, the Slack native stream driver, runtime-state renderer, ownership and stream maps, legacy stop handler, and obsolete `agent_sessions` configuration field were removed. SDK activity still uses the same status and tool-log messages, request cards, Console link, delivery journal, and text fallback.--The shared adapter now declares SDK publication, separate tool-log layout, and activity-reaction capabilities. Slack enables these capabilities and disables legacy runtime-state rendering. Other platforms retain their current behaviour. The shared publisher no longer imports or checks the concrete Slack adapter class.--Slack explicitly ignores legacy runtime-state publication and repositioning, preventing the base renderer from posting duplicate indicators. Native stop events no longer dispatch commands; `!interrupt @agent-name` continues through global command routing. The separate explicit typing API is retained.--Tests for the retired output were removed. Shared Slack API fakes now live in `slack_fakes.py`, independent of legacy tests. Runtime-indicator race tests use Telegram, which still depends on that shared code. New checks cover ignored legacy events, retained reaction error handling, global interrupt routing, and adapter capability selection. Agent display-name tests now exercise SDK status publication.--Validation:--- All collaboration and SDK session tests passed: **1,626 tests**.-- The final focused identity, SDK-only Slack, and global-control run passed **130 tests**, including three newly added cases.-- Mypy passed for the four changed source files. Ruff and `git diff --check` passed.--Run the broad regression suite from the repository root:--```sh-DOCKER_HOST="unix://${HOME}/.docker/run/docker.sock" TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock core/.venv/bin/python -m pytest core/tests/switch_core/bridges/collaboration core/tests/switch_core/sessions -q --tb=short-```--### Smoke-test the removal--1. Rebuild and restart Switch core from this checkout using the Console server page.-2. Start a fresh Slack thread. Ask the agent to run a tool that needs approval, approve it, and let the turn finish.-3. Check that the timer and Console link remain first, the expandable tool log remains second, and request cards stay below without duplicate links. The final runtime must replace the top status in place.-4. Start a longer task and send `!interrupt @agent-name` in its thread. Check that work stops and the eyes reaction clears.-5. Click the Console link and confirm that it opens the correct session.--The user accepted the live smoke test and approved committing and pushing this cleanup. The separate Console and nginx changes remain untouched.