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): open a messaging app's workspace from the server page (CHOO-1784)
Louis Amaudruz7c99e465dd5c
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex a922f6873..02c6643a6 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -271,6 +271,17 @@ class CollaborationAdapter(ABC):server + team + channel name."""return None+ async def home_deeplink(self) -> str | None:+ """Link that opens this bridge's *workspace* — the Slack workspace, the+ Discord guild, the Mattermost team — rather than one channel within it.+ None when the platform has no such link or it cannot be built.++ The bridge-level counterpart to :meth:`channel_deeplink`, for offering+ "open the messaging app" next to the bridge itself. Built from the+ connection config, which never leaves the server; only the resulting+ URL is exposed."""+ return None+@abstractmethodasync def get_channel_type(self, channel_id: str) -> ChannelType: ...diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 4189cf63e..11480d548 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -551,6 +551,13 @@ class DiscordAdapter(CollaborationAdapter):return Nonereturn f"https://discord.com/channels/{self._config.guild_id}/{external_channel_id}"+ async def home_deeplink(self) -> str | None:+ """`https://discord.com/channels/<guild>` — the guild's canonical link,+ which the desktop app claims, same as `channel_deeplink`."""+ if not self._config.guild_id:+ return None+ return f"https://discord.com/channels/{self._config.guild_id}"+async def get_channel_type(self, channel_id: str) -> ChannelType:target = await self._get_channel(int(channel_id))return self._channel_type_of(target)diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex c09ab128d..9c66546ef 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -673,6 +673,21 @@ class MattermostAdapter(CollaborationAdapter):host = re.sub(r"^https?://", "", base_url).rstrip("/")return f"mattermost://{host}/{self._config.team_name}/channels/{name}"+ async def home_deeplink(self) -> str | None:+ """`mattermost://<host>/<team>` — the team's home in the desktop app.++ Uses `public_url` when set, for the same reason `channel_deeplink`+ does: `url` may be an address only Switch can reach. For the bundled+ deployment neither is reachable from a user's machine (`url` is the+ in-compose `http://mattermost:8065` and `public_url` is unset), so a+ client that knows where it published Mattermost should prefer its own+ origin over this."""+ base_url = self._config.public_url or self._config.url+ if not base_url or not self._config.team_name:+ return None+ host = re.sub(r"^https?://", "", base_url).rstrip("/")+ return f"mattermost://{host}/{self._config.team_name}"+async def add_agents_to_channel(self, channel_id: str, agent_names: list[str]) -> None:diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 4f8ee5fda..c9e4cbf3e 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -595,6 +595,13 @@ class SlackAdapter(CollaborationAdapter):f"slack://channel?team={self._config.workspace_id}&id={external_channel_id}")+ async def home_deeplink(self) -> str | None:+ """`slack://open?team=<workspace>` — opens this workspace in the Slack+ desktop app, matching the scheme `channel_deeplink` already uses."""+ if not self._config.workspace_id:+ return None+ return f"slack://open?team={self._config.workspace_id}"+async def get_channel_type(self, channel_id: str) -> ChannelType:if not self._web_client:raise RuntimeError("Slack client not connected")diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex 8c9fb3b04..d66e3e4e3 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -665,6 +665,18 @@ class TeamsAdapter(CollaborationAdapter):f"?groupId={team_id}&tenantId={self._config.tenant_id}")+ async def home_deeplink(self) -> str | None:+ """`https://teams.microsoft.com/?tenantId=<tenant>` — opens Teams on the+ right tenant.++ Deliberately the tenant root rather than a team link: the+ `/l/team/{id}/conversations` form keys off the General channel's thread+ id, not the team id, and this adapter does not hold that. A link that+ reliably lands in the correct tenant beats one that may 404."""+ if not self._config.tenant_id:+ return None+ return f"https://teams.microsoft.com/?tenantId={self._config.tenant_id}"+async def add_agents_to_channel(self, channel_id: str, agent_names: list[str]) -> None:diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex d7e4ea6ac..f03b1b5e7 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)-from switch_core.db.models import User+from switch_core.db.models import CollaborationBridge, Userfrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_store import RoomStore@@ -37,6 +37,48 @@ logger = logging.getLogger(__name__)router = APIRouter()+async def _home_url(+ bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService+) -> str | None:+ """Link that opens the bridge's workspace in its messaging app, built by+ the live adapter. None when the bridge is not running or the platform has+ no such link — the same "offer it only when it works" rule the per-room+ channel deeplink follows."""+ adapter = collab_lifecycle.get_adapter(bridge_id)+ if adapter is None:+ return None+ try:+ return await adapter.home_deeplink()+ except Exception:+ logger.warning(+ "Failed to build home deeplink for bridge %s", bridge_id, exc_info=True+ )+ return None+++async def _detail(+ bridge: CollaborationBridge,+ *,+ room_count: int,+ collab_lifecycle: CollaborationBridgeLifecycleService,+ is_default: bool | None = None,+) -> BridgeDetail:+ """One place every response shape is built, so a new field cannot reach+ some endpoints and miss others. `is_default` overrides the stored value for+ a caller that just changed it in the same request."""+ return BridgeDetail(+ bridge_id=bridge.id,+ bridge_type=bridge.type,+ display_name=bridge.display_name,+ status=bridge.status,+ agent_greetings_enabled=bridge.agent_greetings_enabled,+ is_default=bridge.is_default if is_default is None else is_default,+ room_count=room_count,+ created_at=str(bridge.created_at),+ home_url=await _home_url(bridge.id, collab_lifecycle),+ )++@router.get("/types")async def list_bridge_types(collab_lifecycle: Annotated[@@ -83,15 +125,8 @@ async def create_bridge(await session.commit()is_default = True- return BridgeDetail(- bridge_id=bridge.id,- bridge_type=bridge.type,- display_name=bridge.display_name,- status=bridge.status,- agent_greetings_enabled=bridge.agent_greetings_enabled,- is_default=is_default,- room_count=0,- created_at=str(bridge.created_at),+ return await _detail(+ bridge, room_count=0, collab_lifecycle=collab_lifecycle, is_default=is_default)@@ -101,6 +136,9 @@ async def set_default_bridge(session: Annotated[AsyncSession, Depends(get_session)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],room_store: Annotated[RoomStore, Depends(get_room_store)],+ collab_lifecycle: Annotated[+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)+ ],_user: Annotated[User, Depends(require_admin)],) -> BridgeDetail:"""Nominate a bridge as the instance default, demoting the previous one."""@@ -111,15 +149,8 @@ async def set_default_bridge(await session.commit()rooms = await room_store.get_by_bridge(session, bridge_id)- return BridgeDetail(- bridge_id=bridge.id,- bridge_type=bridge.type,- display_name=bridge.display_name,- status=bridge.status,- agent_greetings_enabled=bridge.agent_greetings_enabled,- is_default=bridge.is_default,- room_count=len(rooms),- created_at=str(bridge.created_at),+ return await _detail(+ bridge, room_count=len(rooms), collab_lifecycle=collab_lifecycle)@@ -128,6 +159,9 @@ async def list_bridges(session: Annotated[AsyncSession, Depends(get_session)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],room_store: Annotated[RoomStore, Depends(get_room_store)],+ collab_lifecycle: Annotated[+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)+ ],_user: Annotated[User, Depends(get_current_user)],) -> list[BridgeDetail]:bridges = await bridge_store.get_all(session)@@ -136,15 +170,8 @@ async def list_bridges(for bridge in bridges:rooms = await room_store.get_by_bridge(session, bridge.id)details.append(- BridgeDetail(- bridge_id=bridge.id,- bridge_type=bridge.type,- display_name=bridge.display_name,- status=bridge.status,- agent_greetings_enabled=bridge.agent_greetings_enabled,- is_default=bridge.is_default,- room_count=len(rooms),- created_at=str(bridge.created_at),+ await _detail(+ bridge, room_count=len(rooms), collab_lifecycle=collab_lifecycle))@@ -158,6 +185,9 @@ async def update_bridge(session: Annotated[AsyncSession, Depends(get_session)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],room_store: Annotated[RoomStore, Depends(get_room_store)],+ collab_lifecycle: Annotated[+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)+ ],# Admin-only for the same reason as registering one: a bridge is an unowned,# workspace-wide integration, so there is no owner to scope mutation to._user: Annotated[User, Depends(require_admin)],@@ -171,15 +201,8 @@ async def update_bridge()await session.commit()rooms = await room_store.get_by_bridge(session, bridge_id)- return BridgeDetail(- bridge_id=bridge.id,- bridge_type=bridge.type,- display_name=bridge.display_name,- status=bridge.status,- agent_greetings_enabled=bridge.agent_greetings_enabled,- is_default=bridge.is_default,- room_count=len(rooms),- created_at=str(bridge.created_at),+ return await _detail(+ bridge, room_count=len(rooms), collab_lifecycle=collab_lifecycle)diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 130ac70c4..cf2de62a3 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -416,6 +416,11 @@ class BridgeDetail(BaseModel):is_default: boolroom_count: intcreated_at: str+ # Link that opens this bridge's workspace in its messaging app, built by+ # the live adapter. None when the bridge is not running, or the platform+ # offers no such link. Never carries a credential — only ids that the+ # platform already puts in its own URLs.+ home_url: str | None = Noneclass BridgeUpdateRequest(BaseModel):diff --git a/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py b/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.pynew file mode 100644index 000000000..94fe16901--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py@@ -0,0 +1,127 @@+"""Workspace-level ("open the messaging app") links, one per adapter.++These are pure functions of the connection config — no client, no network — so+they are tested together rather than scattered across each platform's+provisioning suite.++The property that matters beyond the exact strings: a home link must never+carry a credential. It is derived from a config that also holds bot tokens and+admin passwords, and it is served to any authenticated user by+`GET /gateway/collaborations`, so that is asserted for every platform.+"""++from __future__ import annotations++import asyncio+from typing import Any++from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++BOT_TOKEN = "xoxb-do-not-leak-this"+ADMIN_PASSWORD = "do-not-leak-this-either"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++def _slack() -> SlackAdapter:+ return SlackAdapter(+ config=SlackConnectionConfig(+ bot_token=BOT_TOKEN, app_token="xapp-secret", workspace_id="T0ABCDEF"+ )+ )+++def _discord() -> DiscordAdapter:+ return DiscordAdapter(+ config=DiscordConnectionConfig(bot_token=BOT_TOKEN, guild_id="900")+ )+++def _mattermost(**overrides: Any) -> MattermostAdapter:+ config = {+ "url": "http://mattermost:8065",+ "admin_user": "admin",+ "admin_password": ADMIN_PASSWORD,+ "team_name": "switch",+ **overrides,+ }+ return MattermostAdapter(config=MattermostConnectionConfig(**config))+++def _teams() -> TeamsAdapter:+ return TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="app-1",+ app_password=ADMIN_PASSWORD,+ tenant_id="tenant-9",+ team_id="team-3",+ public_base_url="https://switch.example.com",+ client_state="state",+ )+ )+++def test_slack_home_opens_the_workspace() -> None:+ assert _run(_slack().home_deeplink()) == "slack://open?team=T0ABCDEF"+++def test_discord_home_opens_the_guild() -> None:+ assert _run(_discord().home_deeplink()) == "https://discord.com/channels/900"+++def test_teams_home_opens_the_tenant() -> None:+ # Deliberately the tenant root, not a team link: the `/l/team/` form needs+ # the General channel's thread id, which this adapter does not hold.+ assert (+ _run(_teams().home_deeplink())+ == "https://teams.microsoft.com/?tenantId=tenant-9"+ )+++def test_mattermost_home_opens_the_team() -> None:+ assert _run(_mattermost().home_deeplink()) == "mattermost://mattermost:8065/switch"+++def test_mattermost_home_prefers_the_public_url() -> None:+ # `url` is the address Switch reaches Mattermost on, which may be private.+ # The link is for the user's machine, so the public one wins when set.+ adapter = _mattermost(public_url="https://chat.example.com/")++ assert _run(adapter.home_deeplink()) == "mattermost://chat.example.com/switch"+++def test_base_adapter_offers_no_home_link() -> None:+ # A platform that has not implemented one must return None rather than+ # inherit something wrong — the caller hides the action instead.+ assert _run(CollaborationAdapter.home_deeplink(object())) is None # type: ignore[arg-type]+++def test_no_home_link_carries_a_credential() -> None:+ for adapter in (_slack(), _discord(), _mattermost(), _teams()):+ link = _run(adapter.home_deeplink())+ assert link is not None+ assert BOT_TOKEN not in link+ assert ADMIN_PASSWORD not in link+ assert "xapp-" not in linkdiff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/constants.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/constants.tsindex 76385f312..9310c42a3 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/constants.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/constants.ts@@ -62,3 +62,8 @@ export const LOCAL_SERVER_ADMIN_EMAIL = '[email protected]';* stack is never exposed to the LAN (the standalone compose defaults to all* interfaces for repo users who may want remote access). */export const LOCAL_SERVER_BIND_ADDR = '127.0.0.1';++/** Mattermost team the stack's seeder creates (MATTERMOST_TEAM_NAME). Named+ * rather than inlined because it is also what a link into the bundled+ * Mattermost has to path through — the two must not drift. */+export const LOCAL_SERVER_MATTERMOST_TEAM = 'switch';diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/env-file.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/env-file.tsindex 1cf8ad14d..90acbe83d 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/env-file.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/env-file.ts@@ -1,4 +1,8 @@-import { LOCAL_SERVER_ADMIN_EMAIL, LOCAL_SERVER_BIND_ADDR } from './constants';+import {+ LOCAL_SERVER_ADMIN_EMAIL,+ LOCAL_SERVER_BIND_ADDR,+ LOCAL_SERVER_MATTERMOST_TEAM,+} from './constants';import type { LocalServerPorts } from './free-port';import type { LocalServerSecrets } from './secret-values';@@ -54,7 +58,7 @@ export function buildEnvFile(params: LocalServerEnvParams): string {'','MATTERMOST_ADMIN_USER=admin',`MATTERMOST_ADMIN_PASSWORD=${secrets.mattermostAdminPassword}`,- 'MATTERMOST_TEAM_NAME=switch',+ `MATTERMOST_TEAM_NAME=${LOCAL_SERVER_MATTERMOST_TEAM}`,'MATTERMOST_USER=user',`MATTERMOST_USER_PASSWORD=${secrets.mattermostUserPassword}`,'',diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-embed.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-embed.tsindex 5482759b4..fce0e299e 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-embed.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-embed.ts@@ -1,9 +1,5 @@import { session as electronSession } from 'electron';-import {- managedServerSecretsKey,- managedServerStateDir,-} from '@main/core/managed-switch-server/host/host-for-server';-import { readPersistedPorts } from '@main/core/managed-switch-server/ports';+import { managedServerSecretsKey } from '@main/core/managed-switch-server/host/host-for-server';import { loadOrCreateSecrets } from '@main/core/managed-switch-server/secrets';import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';@@ -13,30 +9,11 @@ import {mattermostPartition,type RoomEmbed,} from '@shared/core/switch-rooms/room-embed';+import { mattermostOriginFor } from './mattermost-origin';const MATTERMOST_AUTH_COOKIE = 'MMAUTHTOKEN';const MATTERMOST_USER = 'user';-/**- * Where this server's Mattermost is reachable from the desktop, or null when we- * don't run it. Only managed servers publish Mattermost on a port we chose and- * hold credentials for; an external server's Mattermost (if any) is somebody- * else's deployment.- */-async function mattermostOriginFor(serverId: string): Promise<string | null> {- const server = await getServer(serverId);- if (!server?.managed) return null;-- const ports = await readPersistedPorts({ stateDir: managedServerStateDir(server) });- if (!ports) return null;-- // Remote-managed stacks publish onto the SSH host's loopback and are reached- // through the same forwarded ports the gateway URL already uses, so the- // gateway's hostname is the right one to pair with the Mattermost port.- const gatewayHost = new URL(server.gatewayUrl).hostname;- return `http://${gatewayHost}:${ports.mattermost}`;-}-/*** Log the shared `user` account into Mattermost so the webview's partition* holds a live session.diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-origin.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-origin.tsnew file mode 100644index 000000000..b4fb38497--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-origin.ts@@ -0,0 +1,23 @@+import { managedServerStateDir } from '@main/core/managed-switch-server/host/host-for-server';+import { readPersistedPorts } from '@main/core/managed-switch-server/ports';+import { getServer } from '@main/core/switch-servers/servers-store';++/**+ * Where this server's Mattermost is reachable from the desktop, or null when we+ * don't run it. Only managed servers publish Mattermost on a port we chose and+ * hold credentials for; an external server's Mattermost (if any) is somebody+ * else's deployment.+ */+export async function mattermostOriginFor(serverId: string): Promise<string | null> {+ const server = await getServer(serverId);+ if (!server?.managed) return null;++ const ports = await readPersistedPorts({ stateDir: managedServerStateDir(server) });+ if (!ports) return null;++ // Remote-managed stacks publish onto the SSH host's loopback and are reached+ // through the same forwarded ports the gateway URL already uses, so the+ // gateway's hostname is the right one to pair with the Mattermost port.+ const gatewayHost = new URL(server.gatewayUrl).hostname;+ return `http://${gatewayHost}:${ports.mattermost}`;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/bridge-home-url.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/bridge-home-url.test.tsnew file mode 100644index 000000000..9d6737359--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/bridge-home-url.test.ts@@ -0,0 +1,88 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { RemoteBridge, SwitchServer } from '@shared/core/switch-servers/switch-servers';++const mattermostOriginFor = vi.hoisted(() => vi.fn());+vi.mock('@main/core/switch-rooms/mattermost-origin', () => ({ mattermostOriginFor }));++const { withResolvedHomeUrls } = await import('./bridge-home-url');++const MANAGED = { id: 'srv-1', managed: true } as SwitchServer;+const EXTERNAL = { id: 'srv-2', managed: false } as SwitchServer;++function bridge(overrides: Partial<RemoteBridge>): RemoteBridge {+ return {+ id: 'b1',+ type: 'mattermost',+ displayName: 'Mattermost',+ status: 'active',+ isDefault: true,+ homeUrl: null,+ ...overrides,+ };+}++describe('withResolvedHomeUrls', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mattermostOriginFor.mockResolvedValue('http://127.0.0.1:8065');+ });++ it("uses switchdash's own origin for a managed stack's Mattermost", async () => {+ // The gateway reports the in-compose address, which resolves to nothing on+ // the user's machine. switchdash published the port, so it knows better.+ const [resolved] = await withResolvedHomeUrls(MANAGED, [+ bridge({ homeUrl: 'mattermost://mattermost:8065/switch' }),+ ]);++ expect(resolved.homeUrl).toBe('http://127.0.0.1:8065/switch');+ });++ it('supplies a link even when the server offers none', async () => {+ // The gateway only gained `home_url` after the currently pinned+ // switch-core, so a managed stack returns null until the pin bumps. The+ // bundled Mattermost still opens, because nothing here needed its answer.+ const [resolved] = await withResolvedHomeUrls(MANAGED, [bridge({ homeUrl: null })]);++ expect(resolved.homeUrl).toBe('http://127.0.0.1:8065/switch');+ });++ it('leaves other platforms on the server-built link', async () => {+ // Slack, Discord and Teams are public platforms — the gateway's URL is+ // correct everywhere, and switchdash has nothing better to offer.+ const resolved = await withResolvedHomeUrls(MANAGED, [+ bridge({ id: 'b2', type: 'slack', homeUrl: 'slack://open?team=T1' }),+ bridge({ id: 'b3', type: 'discord', homeUrl: null }),+ ]);++ expect(resolved[0].homeUrl).toBe('slack://open?team=T1');+ expect(resolved[1].homeUrl).toBeNull();+ });++ it('leaves a non-managed server untouched', async () => {+ // Somebody else's Mattermost: we neither run it nor know where it is+ // published, so the server's own answer is the only one available.+ const [resolved] = await withResolvedHomeUrls(EXTERNAL, [+ bridge({ homeUrl: 'mattermost://chat.example.com/switch' }),+ ]);++ expect(resolved.homeUrl).toBe('mattermost://chat.example.com/switch');+ expect(mattermostOriginFor).not.toHaveBeenCalled();+ });++ it('keeps the server link when the stack is not running', async () => {+ // No persisted ports (stack never started) means no origin to substitute.+ mattermostOriginFor.mockResolvedValue(null);++ const [resolved] = await withResolvedHomeUrls(MANAGED, [+ bridge({ homeUrl: 'mattermost://mattermost:8065/switch' }),+ ]);++ expect(resolved.homeUrl).toBe('mattermost://mattermost:8065/switch');+ });++ it('does not probe the stack when no Mattermost bridge is attached', async () => {+ await withResolvedHomeUrls(MANAGED, [bridge({ type: 'slack', homeUrl: null })]);++ expect(mattermostOriginFor).not.toHaveBeenCalled();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/bridge-home-url.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/bridge-home-url.tsnew file mode 100644index 000000000..3d0e77058--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/bridge-home-url.ts@@ -0,0 +1,36 @@+import { LOCAL_SERVER_MATTERMOST_TEAM } from '@main/core/managed-switch-server/constants';+import { mattermostOriginFor } from '@main/core/switch-rooms/mattermost-origin';+import type { RemoteBridge, SwitchServer } from '@shared/core/switch-servers/switch-servers';++/**+ * Resolve the link that opens each bridge's workspace, preferring one+ * switchdash can reach over one the server merely knows about.+ *+ * The gateway builds `home_url` from the bridge's connection config, which is+ * right for Slack, Discord and Teams — public platforms whose URLs are the+ * same everywhere. It is *wrong* for a managed stack's bundled Mattermost: the+ * configured `url` is the in-compose `http://mattermost:8065`, unreachable from+ * the user's machine, and `public_url` is unset because the deployment does not+ * know which port switchdash published it on. switchdash does know, so it+ * substitutes its own origin.+ *+ * That substitution is also why the action works before the gateway gains the+ * field at all: for the common case — a managed server's bundled Mattermost —+ * nothing here depends on the server's answer.+ */+export async function withResolvedHomeUrls(+ server: SwitchServer,+ bridges: RemoteBridge[]+): Promise<RemoteBridge[]> {+ if (!server.managed || !bridges.some((b) => b.type === 'mattermost')) {+ return bridges;+ }++ const origin = await mattermostOriginFor(server.id);+ if (!origin) return bridges;++ const localTeamUrl = `${origin}/${LOCAL_SERVER_MATTERMOST_TEAM}`;+ return bridges.map((bridge) =>+ bridge.type === 'mattermost' ? { ...bridge, homeUrl: localTeamUrl } : bridge+ );+}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 9d0c10cb0..f5e01161a 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@@ -46,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 { withResolvedHomeUrls } from './bridge-home-url';import { createBridgeOnServer } from './create-bridge';import { createRoomOnServer } from './create-room';import {@@ -200,8 +201,10 @@ export const switchServersController = createRPCController({listRemoteRooms: async (serverId: string): Promise<RemoteRoomSummary[]> =>fetchRooms(await requireServer(serverId)),- listRemoteBridges: async (serverId: string): Promise<RemoteBridge[]> =>- fetchBridges(await requireReachableServer(serverId)),+ listRemoteBridges: async (serverId: string): Promise<RemoteBridge[]> => {+ const server = await requireReachableServer(serverId);+ return withResolvedHomeUrls(server, await fetchBridges(server));+ },listRemoteBridgeTypes: async (serverId: string): Promise<RemoteBridgeType[]> =>fetchBridgeTypes(await requireReachableServer(serverId)),diff --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.tsindex 01be5e104..7680abbd8 100644--- 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.ts@@ -79,6 +79,7 @@ describe('createBridgeOnServer', () => {displayName: 'Acme Slack',status: 'active',isDefault: false,+ homeUrl: null,},});});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.tsindex f4f6e8a02..add094dae 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -233,7 +233,9 @@ describe('room creation', () => {vi.unstubAllGlobals();});- it('maps the bridge list, defaulting is_default to false when absent', async () => {+ it('maps the bridge list, defaulting is_default and home_url when absent', async () => {+ // `home_url` post-dates the pinned switch-core, so a current server omits+ // it entirely — that has to read as "no link", not undefined.fetchMock.mockResolvedValue(jsonResponse([{@@ -242,6 +244,7 @@ describe('room creation', () => {display_name: 'Mattermost',status: 'active',is_default: true,+ home_url: 'mattermost://chat.example.com/switch',},{ bridge_id: 'b2', bridge_type: 'slack', display_name: 'Slack', status: 'stopped' },]) as never@@ -254,8 +257,16 @@ describe('room creation', () => {displayName: 'Mattermost',status: 'active',isDefault: true,+ homeUrl: 'mattermost://chat.example.com/switch',+ },+ {+ id: 'b2',+ type: 'slack',+ displayName: 'Slack',+ status: 'stopped',+ isDefault: false,+ homeUrl: null,},- { id: 'b2', type: 'slack', displayName: 'Slack', status: 'stopped', isDefault: false },]);});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 f866bb8a2..dafe6de3c 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@@ -486,6 +486,7 @@ export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]display_name: string;status: string;is_default?: boolean;+ home_url?: string | null;}>;return json.map((b) => ({id: b.bridge_id,@@ -493,6 +494,7 @@ export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]displayName: b.display_name,status: b.status,isDefault: b.is_default ?? false,+ homeUrl: b.home_url ?? null,}));}@@ -586,6 +588,7 @@ export async function createBridge(display_name: string;status: string;is_default?: boolean;+ home_url?: string | null;};return {id: b.bridge_id,@@ -593,6 +596,7 @@ export async function createBridge(displayName: b.display_name,status: b.status,isDefault: b.is_default ?? false,+ homeUrl: b.home_url ?? null,};}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.tsxindex 663976466..2fa4be62f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -1,7 +1,8 @@import { useQueryClient, useQuery } from '@tanstack/react-query';-import { MessageSquare, Plus } from 'lucide-react';+import { ExternalLink, MessageSquare, Plus } from 'lucide-react';import { observer } from 'mobx-react-lite';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { rpc } from '@renderer/lib/ipc';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { Badge } from '@renderer/lib/ui/badge';@@ -90,6 +91,20 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({<MessageSquare className="size-4 text-foreground-muted" />)}<span className="min-w-0 flex-1 truncate text-foreground">{bridge.displayName}</span>+ {/* Offered only when the link resolves — an older server, or a+ bridge that is down, reports none, and a button that cannot+ do anything is worse than no button. */}+ {bridge.homeUrl && (+ <Button+ variant="ghost"+ size="sm"+ aria-label={`Open ${bridgePlatformLabel(bridge.type)}`}+ onClick={() => void rpc.app.openExternal(bridge.homeUrl as string)}+ >+ <ExternalLink className="size-3.5" />+ Open+ </Button>+ )}{bridge.isDefault && <Badge variant="secondary">Default</Badge>}{/* Surfaced only when it is NOT active: a bridge that is downcannot back a new room, and the room-creation picker silentlydiff --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 1e96ac6ce..0fc155df6 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@@ -194,6 +194,13 @@ export type RemoteBridge = {status: string;/** The bridge used when a room is created without naming one. */isDefault: boolean;+ /**+ * Link that opens this bridge's workspace in its messaging app, from the+ * gateway's live adapter. Null when the bridge is not running, the platform+ * offers no such link, or the server predates the field — so treat its+ * absence as "no action to offer", not as an error.+ */+ homeUrl: string | null;};/**