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(switchdash): connect a messaging app to a server in-app (CHOO-1784)
Louis Amaudruzc869cbb88d7e
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.tsindex 655b2c2d2..9d0c10cb0 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts@@ -21,6 +21,8 @@ import type {AddServerParams,AgentDefaults,AgentVerifyResult,+ CreateBridgeParams,+ CreateBridgeResult,CreateRoomParams,CreateRoomResult,PasswordLoginParams,@@ -30,6 +32,7 @@ import type {RemoteAgentRoom,RemoteAgentSummary,RemoteBridge,+ RemoteBridgeType,RemoteExternalUser,RemoteRoomGroup,RemoteRoomRole,@@ -43,6 +46,7 @@ import type {} from '@shared/core/switch-servers/switch-servers';import { createRPCController } from '@shared/lib/ipc/rpc';import { type LoginError, oidcLogin, passwordLogin } from './auth';+import { createBridgeOnServer } from './create-bridge';import { createRoomOnServer } from './create-room';import {addRoomAgents,@@ -54,6 +58,7 @@ import {fetchAllExternalUsers,fetchAuthConfig,fetchBridges,+ fetchBridgeTypes,fetchMe,fetchRoomAgentIds,fetchRoomGroups,@@ -198,6 +203,27 @@ export const switchServersController = createRPCController({listRemoteBridges: async (serverId: string): Promise<RemoteBridge[]> =>fetchBridges(await requireReachableServer(serverId)),+ listRemoteBridgeTypes: async (serverId: string): Promise<RemoteBridgeType[]> =>+ fetchBridgeTypes(await requireReachableServer(serverId)),++ /**+ * Attach a collaboration bridge to the chosen server (CHOO-1784).+ *+ * `params.connectionConfig` carries platform credentials. They cross the IPC+ * boundary once, on the way out, and are never written to switchdash's disk+ * or returned to the renderer — the server stores them. Keep it that way: do+ * not log `params` here.+ */+ createBridge: async (params: CreateBridgeParams): Promise<CreateBridgeResult> => {+ const server = await requireReachableServer(params.serverId);+ return createBridgeOnServer(server, {+ bridgeType: params.bridgeType,+ displayName: params.displayName,+ connectionConfig: params.connectionConfig,+ setAsDefault: params.setAsDefault,+ });+ },+/*** Create a room on the chosen server, owned by the signed-in user. Room* provisioning stays server-side (`POST /gateway/rooms`); this only mapsdiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-bridge.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-bridge.test.tsnew file mode 100644index 000000000..861a8caf8--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-bridge.test.ts@@ -0,0 +1,268 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const getSessionCookie = vi.hoisted(() => vi.fn());+const refreshSession = vi.hoisted(() => vi.fn());+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());++vi.mock('./servers-store', () => ({ getSessionCookie }));+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));++const { createBridgeOnServer } = await import('./create-bridge');+const { fetchBridgeTypes } = await import('./gateway-client');++const SERVER = {+ id: 'srv-1',+ name: 'S',+ gatewayUrl: 'https://switch.example.com',+ managed: false,+} as never;++const PARAMS = {+ bridgeType: 'slack',+ displayName: 'Acme Slack',+ connectionConfig: {+ bot_token: 'xoxb-secret-value',+ app_token: 'xapp-secret-value',+ workspace_id: 'T123',+ },+ setAsDefault: false,+};++/** A far-from-expiry JWT, so no renewal path is exercised here. */+function validJwt(): string {+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');+ return `${header}.${payload}.sig`;+}++function response(status: number, body: unknown): Response {+ const text = typeof body === 'string' ? body : JSON.stringify(body);+ return {+ status,+ ok: status >= 200 && status < 300,+ json: async () => (typeof body === 'string' ? {} : body),+ headers: { getSetCookie: () => [] },+ text: async () => text,+ } as unknown as Response;+}++const CREATED = {+ bridge_id: 'bridge-1',+ bridge_type: 'slack',+ display_name: 'Acme Slack',+ status: 'active',+ is_default: false,+};++const fetchMock = vi.fn();++describe('createBridgeOnServer', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(validJwt());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('returns the registered bridge on success', async () => {+ fetchMock.mockResolvedValue(response(200, CREATED));++ await expect(createBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({+ kind: 'created',+ bridge: {+ id: 'bridge-1',+ type: 'slack',+ displayName: 'Acme Slack',+ status: 'active',+ isDefault: false,+ },+ });+ });++ it('sends the credentials in the gateway\'s snake_case shape', async () => {+ fetchMock.mockResolvedValue(response(200, CREATED));++ await createBridgeOnServer(SERVER, { ...PARAMS, setAsDefault: true });++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://switch.example.com/gateway/collaborations');+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({+ bridge_type: 'slack',+ display_name: 'Acme Slack',+ connection_config: PARAMS.connectionConfig,+ set_as_default: true,+ });+ });++ it('maps a rejected session onto unauthenticated so the caller prompts a sign-in', async () => {+ fetchMock.mockResolvedValue(response(401, 'Token expired'));++ await expect(createBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({+ kind: 'unauthenticated',+ });+ });++ it('reports a non-admin as forbidden, not as a bad form entry', async () => {+ // Registering a bridge is admin-only. Editing the credentials cannot fix+ // this, so it must not be presented as a validation failure.+ fetchMock.mockResolvedValue(response(403, { detail: 'Admin access required' }));++ await expect(createBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({ kind: 'forbidden' });+ });++ it("reports rejected credentials as invalid, in the gateway's words", async () => {+ fetchMock.mockResolvedValue(response(422, { detail: 'Field required: workspace_id' }));++ await expect(createBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({+ kind: 'invalid',+ message: 'Field required: workspace_id',+ });+ });++ it('surfaces an unreachable gateway rather than failing silently', async () => {+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));++ await expect(createBridgeOnServer(SERVER, PARAMS)).resolves.toMatchObject({ kind: 'error' });+ });++ it('rethrows a server fault rather than flattening it into a form error', async () => {+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));++ await expect(createBridgeOnServer(SERVER, PARAMS)).rejects.toMatchObject({ status: 500 });+ });++ it('never puts a credential in the error it raises', async () => {+ // The failure path is where a token is most likely to escape into a log:+ // GatewayError must quote the response body only, never the request.+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));++ await expect(createBridgeOnServer(SERVER, PARAMS)).rejects.toSatisfy((cause: Error) => {+ const text = `${cause.message} ${JSON.stringify(cause)}`;+ return !text.includes('xoxb-secret-value') && !text.includes('xapp-secret-value');+ });+ });+});++describe('fetchBridgeTypes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(validJwt());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('flattens the config schema into ordered fields, marking the required ones', async () => {+ fetchMock.mockResolvedValue(+ response(200, [+ {+ key: 'slack',+ config_schema: {+ properties: {+ bot_token: { title: 'Bot Token', type: 'string', description: 'The xoxb token.' },+ app_token: { title: 'App Token', type: 'string' },+ workspace_id: { title: 'Workspace Id', type: 'string' },+ },+ required: ['bot_token', 'app_token', 'workspace_id'],+ },+ },+ ])+ );++ const [slack] = await fetchBridgeTypes(SERVER);++ expect(slack.key).toBe('slack');+ // Field order follows the Pydantic model, which the setup docs mirror.+ expect(slack.fields.map((f) => f.key)).toEqual(['bot_token', 'app_token', 'workspace_id']);+ expect(slack.fields[0]).toEqual({+ key: 'bot_token',+ label: 'Bot Token',+ description: 'The xoxb token.',+ required: true,+ secret: true,+ });+ });++ it('marks a field optional when the schema does not require it', async () => {+ fetchMock.mockResolvedValue(+ response(200, [+ {+ key: 'mattermost',+ config_schema: {+ properties: {+ url: { title: 'Url', type: 'string' },+ admin_password: { title: 'Admin Password', type: 'string' },+ public_url: { anyOf: [{ type: 'string' }, { type: 'null' }] },+ },+ required: ['url', 'admin_password'],+ },+ },+ ])+ );++ const [mm] = await fetchBridgeTypes(SERVER);+ const byKey = Object.fromEntries(mm.fields.map((f) => [f.key, f]));++ expect(byKey.url).toMatchObject({ required: true, secret: false });+ expect(byKey.admin_password).toMatchObject({ required: true, secret: true });+ expect(byKey.public_url).toMatchObject({ required: false, secret: false });+ // No `title` in the schema — fall back to a humanised key rather than+ // showing the raw snake_case name.+ expect(byKey.public_url.label).toBe('Public Url');+ });++ it('masks a private key, which a bare api_key heuristic would miss', async () => {+ // Teams' Graph encryption key is as sensitive as a token but matches+ // neither `token` nor `api_key`.+ fetchMock.mockResolvedValue(+ response(200, [+ {+ key: 'teams',+ config_schema: {+ properties: {+ app_id: { title: 'App Id', type: 'string' },+ encryption_private_key: { anyOf: [{ type: 'string' }, { type: 'null' }] },+ },+ required: ['app_id'],+ },+ },+ ])+ );++ const [teams] = await fetchBridgeTypes(SERVER);+ const byKey = Object.fromEntries(teams.fields.map((f) => [f.key, f]));++ expect(byKey.app_id.secret).toBe(false);+ expect(byKey.encryption_private_key.secret).toBe(true);+ });++ it('honours an explicit password format over the name heuristic', async () => {+ fetchMock.mockResolvedValue(+ response(200, [+ {+ key: 'custom',+ config_schema: {+ properties: { handshake: { title: 'Handshake', type: 'string', format: 'password' } },+ required: ['handshake'],+ },+ },+ ])+ );++ const [custom] = await fetchBridgeTypes(SERVER);+ expect(custom.fields[0].secret).toBe(true);+ });++ it('tolerates a type with no fields rather than throwing', async () => {+ fetchMock.mockResolvedValue(response(200, [{ key: 'stub', config_schema: {} }]));++ await expect(fetchBridgeTypes(SERVER)).resolves.toEqual([{ key: 'stub', fields: [] }]);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-bridge.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-bridge.tsnew file mode 100644index 000000000..faf834dde--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/create-bridge.ts@@ -0,0 +1,44 @@+import { createBridge, GatewayError } from '@main/core/switch-servers/gateway-client';+import type {+ CreateBridgeParams,+ CreateBridgeResult,+ SwitchServer,+} from '@shared/core/switch-servers/switch-servers';++/**+ * Attach a collaboration bridge to `server` and map recoverable gateway+ * failures onto a typed {@link CreateBridgeResult}, so the modal can name what+ * went wrong instead of surfacing a raw status line.+ *+ * Unmapped failures still throw: an unexpected 500 is a bug, not a form error.+ *+ * Nothing here logs `params.connectionConfig`, and nothing returns it. The+ * credentials exist in this process only for the duration of the call —+ * switchdash never persists them; the server is where they live.+ */+export async function createBridgeOnServer(+ server: SwitchServer,+ params: Omit<CreateBridgeParams, 'serverId'>+): Promise<CreateBridgeResult> {+ try {+ const bridge = await createBridge(server, {+ bridgeType: params.bridgeType,+ displayName: params.displayName,+ connectionConfig: params.connectionConfig,+ setAsDefault: params.setAsDefault,+ });+ return { kind: 'created', bridge };+ } catch (cause) {+ if (cause instanceof GatewayError) {+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };+ // Registering a bridge is admin-only. A non-admin cannot fix this by+ // editing the form, so it is not a validation failure.+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };+ if (cause.kind === 'http' && (cause.status === 400 || cause.status === 422)) {+ return { kind: 'invalid', message: cause.detail ?? cause.message };+ }+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };+ }+ throw cause;+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.tsindex a1855b789..f866bb8a2 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts@@ -1,9 +1,11 @@import type { KnownAgentType } from '@main/core/agents/known-agent-type';import type {AddressingPolicy,+ BridgeConfigField,RemoteAgentRoom,RemoteAgentSummary,RemoteBridge,+ RemoteBridgeType,RemoteExternalUser,RemoteRoomGroup,RemoteRoomRole,@@ -494,6 +496,106 @@ export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]}));}+/** Field names that hold a credential and must be masked on input. Mirrors the+ * operator dashboard's `isSecretField`, widened to catch `*_private_key` (the+ * Teams bridge's Graph encryption key), which its bare `api_key` alternation+ * misses. */+const SECRET_FIELD_RE = /token|password|secret|api[_-]?key|private[_-]?key|credential/i;++/** JSON Schema as Pydantic's `model_json_schema()` emits it for a bridge config. */+type BridgeConfigSchema = {+ properties?: Record<string, { title?: string; description?: string; format?: string }>;+ required?: string[];+};++function humanizeFieldKey(key: string): string {+ return key.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());+}++function toConfigFields(schema: BridgeConfigSchema): BridgeConfigField[] {+ const required = new Set(schema.required ?? []);+ // Object key order follows the Pydantic model's field order, which puts the+ // required credentials before the optional tuning knobs — worth preserving,+ // so the form reads the way the platform's setup docs do.+ return Object.entries(schema.properties ?? {}).map(([key, prop]) => ({+ key,+ label: prop.title ?? humanizeFieldKey(key),+ description: prop.description ?? null,+ required: required.has(key),+ secret: prop.format === 'password' || SECRET_FIELD_RE.test(key),+ }));+}++/**+ * The bridge types a server can register, with the credential fields each needs+ * (`GET /collaborations/types`).+ *+ * The field list is the server's to define — switch-core derives it from the+ * adapter's own config model — so the attach form is generated from this rather+ * than hard-coded per platform. A server running a newer switch-core that adds+ * a bridge type, or a field to an existing one, works without an app release.+ *+ * Every schema-visible field is a string today (the sole int, the Teams listen+ * port, is `SkipJsonSchema`), so values are collected as strings and the server+ * coerces.+ */+export async function fetchBridgeTypes(server: SwitchServer): Promise<RemoteBridgeType[]> {+ const res = await gatewayFetch(server, '/collaborations/types', { authenticated: true });+ const json = (await res.json()) as Array<{+ key: string;+ config_schema: BridgeConfigSchema;+ }>;+ return json.map((t) => ({ key: t.key, fields: toConfigFields(t.config_schema ?? {}) }));+}++/**+ * Register a collaboration bridge on `server` (admin-only+ * `POST /collaborations`), optionally making it the default for new rooms.+ *+ * The server validates the credentials against the adapter's config model,+ * mints the bridge's Matrix client, persists it and **starts the adapter+ * immediately** — there is no stack restart and no config file to write, so+ * live sessions and connected agents are unaffected.+ *+ * `connectionConfig` holds platform credentials. Do not log it, do not return+ * it to the renderer, and do not fold it into an error message: `GatewayError`+ * quotes the *response* body only, never the request.+ */+export async function createBridge(+ server: SwitchServer,+ params: {+ bridgeType: string;+ displayName: string;+ connectionConfig: Record<string, string>;+ setAsDefault: boolean;+ }+): Promise<RemoteBridge> {+ const res = await gatewayFetch(server, '/collaborations', {+ authenticated: true,+ method: 'POST',+ body: {+ bridge_type: params.bridgeType,+ display_name: params.displayName,+ connection_config: params.connectionConfig,+ set_as_default: params.setAsDefault,+ },+ });+ const b = (await res.json()) as {+ bridge_id: string;+ bridge_type: string;+ display_name: string;+ status: string;+ is_default?: boolean;+ };+ return {+ id: b.bridge_id,+ type: b.bridge_type,+ displayName: b.display_name,+ status: b.status,+ isDefault: b.is_default ?? false,+ };+}+/*** Union of external (bridged human) users across every bridge on the server* (`GET /collaborations`, then each bridge's `/users`). The addressing policy'sdiff --git a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.tsindex efdd033e1..5217787f8 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts+++ b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts@@ -8,6 +8,7 @@ import { RenameSessionModal } from '@renderer/features/sessions/rename-session-mimport { AddAgentsToRoomModal } from '@renderer/features/switch-rooms/AddAgentsToRoomModal';import { AddServerModal } from '@renderer/features/switch-servers/AddServerModal';import { AssignServerModal } from '@renderer/features/switch-servers/assign-server-modal';+import { ConnectMessagingAppModal } from '@renderer/features/switch-servers/ConnectMessagingAppModal';import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomModal';import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServerModal';import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';@@ -63,6 +64,10 @@ export const modalRegistry = {}),deleteServerModal: createModal(DeleteServerModal, { size: 'sm' }),createRoomModal: createModal(CreateRoomModal, { size: 'md', dismissOnOutsideClick: false }),+ connectMessagingAppModal: createModal(ConnectMessagingAppModal, {+ size: 'md',+ dismissOnOutsideClick: false,+ }),addAgentsToRoomModal: createModal(AddAgentsToRoomModal, {size: 'sm',dismissOnOutsideClick: false,diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsxnew file mode 100644index 000000000..6e6e0ee7f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx@@ -0,0 +1,290 @@+import { useQuery } from '@tanstack/react-query';+import { observer } from 'mobx-react-lite';+import { useCallback, useMemo, useState } from 'react';+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { rpc } from '@renderer/lib/ipc';+import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { Checkbox } from '@renderer/lib/ui/checkbox';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Field, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';+import type { CreateBridgeResult } from '@shared/core/switch-servers/switch-servers';+import { switchServersStore } from './switch-servers-store';++type ConnectMessagingAppModalArgs = {+ /** Attach to this server instead of the active one. */+ serverId?: string;+};++type Props = BaseModalProps<{ bridgeId: string }> & ConnectMessagingAppModalArgs;++/** Platform names as their own docs write them, so the picker matches what the+ * user just read while creating the bot. Unknown keys (a bridge type added by a+ * newer switch-core) fall back to the raw key rather than being hidden. */+const PLATFORM_LABELS: Record<string, string> = {+ slack: 'Slack',+ mattermost: 'Mattermost',+ discord: 'Discord',+ teams: 'Microsoft Teams',+};++function platformLabel(key: string): string {+ return PLATFORM_LABELS[key] ?? key;+}++export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModal({+ serverId: overrideServerId,+ onSuccess,+ onClose,+}: Props) {+ const { setCloseGuard } = useModalContext();++ const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';+ const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;+ const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';++ const [typeKey, setTypeKey] = useState<string | null>(null);+ const [displayName, setDisplayName] = useState('');+ // Credential values. Renderer-local and never persisted: this state dies with+ // the modal, and the only thing that reads it is the submit call.+ const [config, setConfig] = useState<Record<string, string>>({});+ const [setAsDefault, setSetAsDefault] = useState(false);+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const typesQuery = useQuery({+ queryKey: ['remote-bridge-types', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridgeTypes(serverId),+ enabled: !!serverId,+ });++ const types = useMemo(() => typesQuery.data ?? [], [typesQuery.data]);+ const selectedType = types.find((t) => t.key === typeKey) ?? null;++ const handleTypeChange = useCallback((next: string | null) => {+ // Switching platform drops whatever was typed for the previous one — those+ // fields do not exist on the new type, and carrying a stale token forward+ // would silently submit a credential the user thinks they replaced.+ setTypeKey(next);+ setConfig({});+ setError(null);+ }, []);++ const trimmedName = displayName.trim();+ const missingRequired = (selectedType?.fields ?? []).some(+ (f) => f.required && !(config[f.key] ?? '').trim()+ );+ const canSubmit =+ !!serverId && isAdmin && !!selectedType && !!trimmedName && !missingRequired && !isSubmitting;++ const handleSubmit = useCallback(async () => {+ if (!canSubmit || !selectedType) return;+ setIsSubmitting(true);+ setCloseGuard(true);+ setError(null);++ try {+ // Send only the fields this type declares, trimmed. A value left over in+ // state from a field that is no longer rendered must not ride along.+ const connectionConfig: Record<string, string> = {};+ for (const field of selectedType.fields) {+ const value = (config[field.key] ?? '').trim();+ if (value) connectionConfig[field.key] = value;+ }++ const result = await rpc.switchServers.createBridge({+ serverId,+ bridgeType: selectedType.key,+ displayName: trimmedName,+ connectionConfig,+ setAsDefault,+ });++ if (result.kind !== 'created') {+ setError(messageFor(result));+ return;+ }+ onSuccess({ bridgeId: result.bridge.id });+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setIsSubmitting(false);+ setCloseGuard(false);+ }+ }, [+ canSubmit,+ selectedType,+ serverId,+ trimmedName,+ config,+ setAsDefault,+ onSuccess,+ setCloseGuard,+ ]);++ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Connect a messaging app{server ? ` to ${server.name}` : ''}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ <div className="flex w-full flex-col gap-5">+ {!server && (+ <p className="text-destructive text-xs">+ No Switch server is selected. Choose a server in the sidebar first.+ </p>+ )}++ {server && !isAdmin && (+ <p className="text-destructive text-xs">+ Connecting a messaging app requires an admin account on this server. You are signed in+ without admin rights, so the server would reject this.+ </p>+ )}++ <Field>+ <FieldLabel>Messaging app</FieldLabel>+ <Select+ value={typeKey ?? ''}+ onValueChange={(next) => handleTypeChange(next ?? null)}+ disabled={typesQuery.isLoading || types.length === 0 || !isAdmin}+ >+ <SelectTrigger>+ <SelectValue placeholder={typesQuery.isLoading ? 'Loading…' : 'Choose a platform'}>+ {selectedType ? platformLabel(selectedType.key) : undefined}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {types.map((type) => (+ <SelectItem key={type.key} value={type.key}>+ <span className="flex items-center gap-2">+ {hasBridgeIcon(type.key) && <BridgeIcon bridgeType={type.key} size={16} />}+ {platformLabel(type.key)}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {typesQuery.isError && (+ <p className="text-destructive mt-1 text-xs">+ Could not load the available messaging apps: {errorText(typesQuery.error)}+ </p>+ )}+ </Field>++ {selectedType && (+ <>+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ autoFocus+ placeholder={`e.g. ${platformLabel(selectedType.key)}`}+ value={displayName}+ onChange={(e) => {+ setDisplayName(e.target.value);+ setError(null);+ }}+ />+ <p className="mt-1 text-xs text-foreground-muted">+ How this connection is labelled in switchdash when you pick it for a room.+ </p>+ </Field>++ {selectedType.fields.map((field) => (+ <Field key={field.key}>+ <FieldLabel>+ {field.label}+ {!field.required && (+ <span className="ml-1 font-normal text-foreground-muted">(optional)</span>+ )}+ </FieldLabel>+ <Input+ // Masked for credentials, so a token is not left readable on+ // screen while the user checks the rest of the form.+ type={field.secret ? 'password' : 'text'}+ autoComplete={field.secret ? 'new-password' : 'off'}+ spellCheck={false}+ value={config[field.key] ?? ''}+ onChange={(e) => {+ const { value } = e.target;+ setConfig((prev) => ({ ...prev, [field.key]: value }));+ setError(null);+ }}+ />+ {field.description && (+ <p className="mt-1 text-xs text-foreground-muted">{field.description}</p>+ )}+ </Field>+ ))}++ <label className="group/field flex cursor-pointer items-start gap-2.5">+ <Checkbox+ checked={setAsDefault}+ onCheckedChange={(checked) => setSetAsDefault(checked === true)}+ className="mt-0.5"+ />+ <span className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">Use for new rooms by default</span>+ <span className="text-xs text-foreground-muted">+ Rooms created without naming a messaging app will land here. Replaces the+ server’s current default; existing rooms are unaffected.+ </span>+ </span>+ </label>++ <p className="text-xs text-foreground-muted">+ Credentials are sent to {server?.name ?? 'the server'} and stored there. switchdash+ does not keep a copy. The connection starts immediately — no restart, and running+ sessions are unaffected.+ </p>+ </>+ )}++ {error && <p className="text-destructive text-xs">{error}</p>}+ </div>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={isSubmitting}>+ Cancel+ </Button>+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>+ {isSubmitting ? 'Connecting…' : 'Connect'}+ </ConfirmButton>+ </DialogFooter>+ </>+ );+});++function errorText(cause: unknown): string {+ return cause instanceof Error ? cause.message : String(cause);+}++/** Turn a failed attach into something the user can act on. */+function messageFor(result: Exclude<CreateBridgeResult, { kind: 'created' }>): string {+ switch (result.kind) {+ case 'unauthenticated':+ return 'Your session for this server expired. Sign in again, then retry.';+ case 'forbidden':+ return 'Connecting a messaging app requires an admin account on this server.';+ case 'invalid':+ // The gateway validated the credentials against the platform's own config+ // model, so its wording is more specific than anything we could invent.+ return `The server rejected these details: ${result.message}`;+ case 'error':+ return result.message;+ }+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsxnew file mode 100644index 000000000..663976466--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -0,0 +1,104 @@+import { useQueryClient, useQuery } from '@tanstack/react-query';+import { MessageSquare, Plus } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { rpc } from '@renderer/lib/ipc';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { switchRoomsStore } from './switch-rooms-store';+import { switchServersStore } from './switch-servers-store';++/**+ * The messaging apps bridged to a server, and — for an admin — the way to+ * connect another (CHOO-1784).+ *+ * Listing is offered on every server type, not just managed ones: a bridge is+ * registered through the server's own admin API, so there is nothing+ * switchdash has to own locally for this to work. Attaching is gated on the+ * signed-in user being an admin, because the endpoint is.+ */+export const MessagingAppsCard = observer(function MessagingAppsCard({+ serverId,+ className,+}: {+ serverId: string;+ className?: string;+}) {+ const queryClient = useQueryClient();+ const showConnectMessagingApp = useShowModal('connectMessagingAppModal');+ const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';++ const bridgesQuery = useQuery({+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ enabled: !!serverId,+ });++ const bridges = bridgesQuery.data ?? [];++ return (+ <div className={className}>+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <h3 className="text-sm font-medium text-foreground">Messaging apps</h3>+ {bridgesQuery.isLoading && <Spinner className="size-3.5" />}+ </div>+ {isAdmin && (+ <Button+ variant="outline"+ size="sm"+ onClick={() =>+ showConnectMessagingApp({+ serverId,+ onSuccess: () => {+ // Refresh the bridge list everywhere it is consumed — this+ // card and the room-creation picker share the query key.+ void queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });+ void switchRoomsStore.refreshAll();+ },+ })+ }+ >+ <Plus className="size-4" />+ Connect+ </Button>+ )}+ </div>++ {bridgesQuery.isError ? (+ <p className="text-destructive mt-3 text-xs">+ Could not load messaging apps:{' '}+ {bridgesQuery.error instanceof Error+ ? bridgesQuery.error.message+ : String(bridgesQuery.error)}+ </p>+ ) : bridges.length === 0 && !bridgesQuery.isLoading ? (+ <p className="mt-3 text-xs text-foreground-muted">+ {isAdmin+ ? 'No messaging app is connected, so rooms created here would be unreachable. Connect one to get started.'+ : 'No messaging app is connected. An admin on this server can connect one.'}+ </p>+ ) : (+ <ul className="mt-3 space-y-2">+ {bridges.map((bridge) => (+ <li key={bridge.id} className="flex items-center gap-2 text-sm">+ {hasBridgeIcon(bridge.type) ? (+ <BridgeIcon bridgeType={bridge.type} size={16} />+ ) : (+ <MessageSquare className="size-4 text-foreground-muted" />+ )}+ <span className="min-w-0 flex-1 truncate text-foreground">{bridge.displayName}</span>+ {bridge.isDefault && <Badge variant="secondary">Default</Badge>}+ {/* Surfaced only when it is NOT active: a bridge that is down+ cannot back a new room, and the room-creation picker silently+ omits it, so this is where that becomes visible. */}+ {bridge.status !== 'active' && <Badge variant="destructive">{bridge.status}</Badge>}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsxindex 65a002681..2d115f3b1 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx@@ -24,6 +24,7 @@ import { Spinner } from '@renderer/lib/ui/spinner';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { localServerStore } from './local-server-store';import { LocalServerControls } from './LocalServerControls';+import { MessagingAppsCard } from './MessagingAppsCard';import { remoteServerStore } from './remote-server-store';import { RemoteServerControls } from './RemoteServerControls';import { switchServersStore } from './switch-servers-store';@@ -230,9 +231,11 @@ const ServerMainPanel = observer(function ServerMainPanel() {{!connected && <LoginPanel serverId={serverId} />}+ {connected && <MessagingAppsCard serverId={serverId} className={card} />}+<div className={`${card} space-y-3`}><p className="text-sm text-foreground-muted">- Configure resources, messaging apps, API keys and users in the full admin interface.+ Configure resources, API keys and users in the full admin interface.</p><Buttonvariant="outline"diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.tsindex 721f88a47..1e96ac6ce 100644--- a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -196,6 +196,68 @@ export type RemoteBridge = {isDefault: boolean;};+/**+ * One credential field a bridge type needs, projected from the JSON Schema the+ * gateway derives from the adapter's Pydantic config model.+ *+ * The schema is the server's to define, not switchdash's: a Slack bridge needs+ * different fields from a Discord one, and a switch-core release can add a+ * field without an app release. So the attach form is generated from this+ * rather than hand-written per platform.+ */+export type BridgeConfigField = {+ key: string;+ label: string;+ description: string | null;+ required: boolean;+ /** Render masked and keep out of logs. Set from the schema's+ * `format: "password"` hint, falling back to a name heuristic. */+ secret: boolean;+};++/** A bridge type registered on a server, with the fields needed to attach one+ * (mirrors the gateway `BridgeTypeInfo`, with its raw JSON Schema flattened+ * into an ordered field list). */+export type RemoteBridgeType = {+ /** Platform key (`slack`, `mattermost`, …). */+ key: string;+ fields: BridgeConfigField[];+};++/**+ * Parameters for attaching a collaboration bridge to a server from inside+ * switchdash (CHOO-1784).+ *+ * `connectionConfig` carries platform credentials — a Slack bot token, a+ * Discord bot token, a Mattermost admin password. It is main-process-only: it+ * goes straight to the server over HTTPS and is never persisted by switchdash,+ * never logged, and never sent back to the renderer.+ */+export type CreateBridgeParams = {+ serverId: string;+ bridgeType: string;+ displayName: string;+ connectionConfig: Record<string, string>;+ /** Make this the bridge new rooms land on when none is named. */+ setAsDefault: boolean;+};++/**+ * Outcome of attaching a bridge. As with room creation, recoverable gateway+ * failures become variants the modal can say out loud rather than a raw throw.+ *+ * `forbidden` is its own case because it is not a fault the user can fix by+ * editing the form: registering a bridge is admin-only, so a non-admin needs+ * telling that rather than a validation error.+ */+export type CreateBridgeResult =+ | { kind: 'created'; bridge: RemoteBridge }+ | { kind: 'unauthenticated' }+ | { kind: 'forbidden' }+ /** The server rejected the credentials or the config shape (400/422). */+ | { kind: 'invalid'; message: string }+ | { kind: 'error'; message: string };+/** A bridged (external) human identity on a server. The `users` dimension of an* addressing policy keys off these ids. */export type RemoteExternalUser = {