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: standalone built-in chat UI — default bridge + inline room view (CHOO-1674) (#84)
Louis Amaudruze45e4d13c603
diff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.jsonindex d6e00b0f3..dff01da86 100644--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json@@ -1,5 +1,5 @@{"name": "switch-connector",- "version": "0.1.15",+ "version": "0.2.0","description": "Connect Claude Code to a Switch platform instance as a participating agent"-}\ No newline at end of file+}diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.mdindex 1635b7015..055114cb8 100644--- a/connectors/claude-code-plugin/skills/switch/SKILL.md+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md@@ -231,12 +231,16 @@ available to any agent — the responsibility for using them well stillapplies.- **`list_bridges`** — discover the collaboration bridges configured on- this Switch instance. Returns `{id, type, display_name, status}` per- bridge. Only `status == "active"` bridges are usable for new rooms.+ this Switch instance. Returns `{id, type, display_name, status,+ is_default}` per bridge. Only `status == "active"` bridges are usable+ for new rooms. `is_default` marks the bridge `create_room` uses when no+ `bridge_id` is given (at most one per instance).- **`create_room`** — provision a new room. Required: `name`,`description`, `agent_names`. Optional but commonly used: `bridge_id`,- `channel_type` (`"channel_public"`, `"channel_private"`, or `"direct"`- for a 1:1 DM — see "DM rooms" below), `user_names`, `instructions`,+ `internal_only` (opt out of the default bridge — see "Prefer bridged+ rooms" below), `channel_type` (`"channel_public"`, `"channel_private"`,+ or `"direct"` for a 1:1 DM — see "DM rooms" below), `user_names`,+ `instructions`,`reference_ids`, `package_ids`, `linked_rooms`, `join_event_listeners`(subset of `agent_names` that should receive `room_join` events in theroom — off by default). Returns@@ -307,26 +311,33 @@ applies.### Prefer bridged rooms — and let the user pick the bridge-The point of Switch is collaboration between agents and humans. **Default-to creating bridged rooms** (rooms attached to a Slack / Mattermost-channel via a `bridge_id`) so humans on those platforms can participate.-Only create an internal-only room (omitting `bridge_id`) when the user-has explicitly said the room should not bridge anywhere — e.g. "just a-scratch room for agents to coordinate."+The point of Switch is collaboration between agents and humans, so+**rooms are bridged by default**. Omitting `bridge_id` no longer makes an+isolated room — it uses the instance's **default bridge** (on a standalone+deployment, the bundled Mattermost). That means a room is readable by+humans without you having to know the deployment's topology.++To create a room with **no** external channel, pass `internal_only=True`.+Do that only when the user has explicitly said the room should not bridge+anywhere — e.g. "just a scratch room for agents to coordinate."**Do not guess a `bridge_id`.** Workflow when the user asks you tocreate a room:1. Call `list_bridges`.-2. Show the user the active bridges (display name + type) and ask which- one to use (or whether to skip bridging entirely).+2. Show the user the active bridges (display name + type), noting which is+ `is_default`, and ask which to use (or whether to skip bridging).3. Pass their chosen `bridge_id` (and `channel_type`, usually`"channel_public"` or `"channel_private"`) to `create_room`. Omit- both if they chose internal-only.+ `bridge_id` to accept the default; pass `internal_only=True` if they+ want no channel at all.++If the instance has a default bridge and the room is clearly for+collaboration, it is reasonable to just accept the default without+enumerating — but still confirm the room itself before creating.-If exactly one active bridge exists and the room is clearly for-collaboration, it is reasonable to propose using it without enumerating-— but still confirm before creating.+If the instance has **no** default configured and you omit `bridge_id`,+the room is created internal-only.### DM rooms (1:1 with a user)@@ -552,7 +563,8 @@ tell whether a holder is reachable in this room right now.- `list_bridges` — before creating a room, to discover the availablecollaboration bridges and ask the user which one to use.- `create_room` — provision a new room. Confirm name, members, and- bridge choice with the user before calling. Prefer bridged rooms.+ bridge choice with the user before calling. Rooms use the default+ bridge unless you pass `bridge_id` or `internal_only`.- `invite_agent_to_room` — add another agent to an existing room byname.- `list_all_rooms` / `get_room_detail` — enumerate every room on thediff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex 8157c3348..edeb6bafb 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -1050,6 +1050,7 @@ async def create_room(user_names=req.user_names,channel_type=req.channel_type,bridge_id=req.bridge_id,+ internal_only=req.internal_only,admin_mode=req.admin_mode,security_config=req.security_config,instructions=req.instructions,diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.pyindex 831c7874c..1e7a7b1c3 100644--- a/core/switch_core/bridges/agent/api/schemas.py+++ b/core/switch_core/bridges/agent/api/schemas.py@@ -342,9 +342,11 @@ class CreateModerationRoomRequest(BaseModel):include_subagents_for: list[str] | None = Noneuser_names: list[str] | None = Nonechannel_type: Literal["channel_public", "channel_private"] | None = None- # Bridge is optional — omit to create an internal-only room (no- # external collaboration channel).+ # Bridge is optional — omit to use the instance's default bridge.bridge_id: str | None = None+ # Opt out of the instance default bridge: create a room with no external+ # channel. Ignored when bridge_id is set.+ internal_only: bool = Falseadmin_mode: bool = Falsesecurity_config: dict[str, Any] | None = Noneinstructions: str | None = Nonediff --git a/core/switch_core/bridges/agent/mcp/server.py b/core/switch_core/bridges/agent/mcp/server.pyindex 8a037ebbd..5a91bd129 100644--- a/core/switch_core/bridges/agent/mcp/server.py+++ b/core/switch_core/bridges/agent/mcp/server.py@@ -837,6 +837,7 @@ async def create_room(user_names: list[str] | None = None,channel_type: str | None = None,bridge_id: str | None = None,+ internal_only: bool = False,admin_mode: bool = False,security_config: dict[str, Any] | None = None,instructions: str | None = None,@@ -853,10 +854,15 @@ async def create_room() -> dict[str, Any]:"""Create a new Switch room.- Prefer bridged rooms (pass `bridge_id`) for collaboration with humans on- Slack/Mattermost. Omit `bridge_id` only when you explicitly want an- internal-only room with no external channel. Call `list_bridges` to- discover bridge ids and present the choice to the user.+ Rooms are bridged by default: omitting `bridge_id` uses the instance's+ default bridge (on a standalone deployment, the bundled Mattermost), so the+ room is readable by humans without the caller knowing the deployment's+ topology. Pass `bridge_id` to choose a specific bridge — call+ `list_bridges` to discover ids and present the choice to the user. Pass+ `internal_only=True` for an agent-only room with no external channel.++ If the instance has no default bridge configured and you omit `bridge_id`,+ the room is created internal-only.Args:name: Display name for the room.@@ -873,7 +879,9 @@ async def create_room(as a private channel with that user invited; the user must alreadybe known to Switch on the bridge (creation fails otherwise).bridge_id: Optional id of the collaboration bridge backing this room.- Omit for an internal-only room (no external channel).+ Omit to use the instance's default bridge.+ internal_only: Create a room with no external channel, opting out of+ the default bridge. Ignored when `bridge_id` is set.admin_mode: When true, the room is created in administrative mode.security_config: Optional dict overriding default protection checks.instructions: Room-specific system prompt / guidance shown to agents@@ -931,6 +939,7 @@ async def create_room(user_names=user_names,channel_type=channel_type,bridge_id=bridge_id,+ internal_only=internal_only,admin_mode=admin_mode,security_config=security_config,instructions=instructions,@@ -1239,9 +1248,10 @@ async def list_bridges() -> list[dict[str, Any]]:the list to the user and let them choose, rather than guessing.Returns:- List of `{id, type, display_name, status}` dicts. Only `status`- == "active" bridges are usable for new rooms; others are shown for- context.+ List of `{id, type, display_name, status, is_default}` dicts. Only+ `status` == "active" bridges are usable for new rooms; others are+ shown for context. `is_default` marks the bridge that `create_room`+ uses when no `bridge_id` is given (at most one)."""protocol = _get_protocol()return await protocol.list_bridges()diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex 7a1dec1a9..42df19ba9 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -1663,6 +1663,7 @@ class ProtocolService:"type": b.type,"display_name": b.display_name,"status": b.status,+ "is_default": b.is_default,}for b in bridges]@@ -1676,6 +1677,7 @@ class ProtocolService:user_names: list[str] | None,channel_type: str | None,bridge_id: str | None,+ internal_only: bool = False,admin_mode: bool = False,security_config: dict[str, Any] | None = None,instructions: str | None = None,@@ -1725,6 +1727,7 @@ class ProtocolService:user_names=user_names,channel_type=channel_type, # type: ignore[arg-type]bridge_id=bridge_id,+ internal_only=internal_only,admin_mode=admin_mode,protection_config=security_config,instructions=instructions,diff --git a/core/switch_core/bridges/collaboration/api.py b/core/switch_core/bridges/collaboration/api.pyindex 528b968b6..2aaa7609d 100644--- a/core/switch_core/bridges/collaboration/api.py+++ b/core/switch_core/bridges/collaboration/api.py@@ -23,11 +23,16 @@ class OnboardBridgeRequest(BaseModel):bridge_type: strdisplay_name: strconnection_config: dict[str, Any]+ # Nominate this bridge as the one new rooms land on when none is named.+ # Set by the bundled-Mattermost setup so a standalone deployment bridges+ # rooms out of the box.+ set_as_default: bool = Falseclass OnboardBridgeResponse(BaseModel):bridge_id: strstatus: str+ is_default: boolclass BridgeInfo(BaseModel):@@ -35,6 +40,7 @@ class BridgeInfo(BaseModel):bridge_type: strdisplay_name: strstatus: str+ is_default: bool@router.post("")@@ -43,6 +49,8 @@ async def onboard_bridge(collab_lifecycle: Annotated[CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)],+ session: Annotated[AsyncSession, Depends(get_session)],+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],) -> OnboardBridgeResponse:try:bridge = await collab_lifecycle.register(@@ -55,7 +63,15 @@ async def onboard_bridge(except RuntimeError as e:raise HTTPException(status_code=502, detail=str(e))- return OnboardBridgeResponse(bridge_id=bridge.id, status=bridge.status)+ is_default = bridge.is_default+ if req.set_as_default:+ await bridge_store.set_default(session, bridge.id)+ await session.commit()+ is_default = True++ return OnboardBridgeResponse(+ bridge_id=bridge.id, status=bridge.status, is_default=is_default+ )@router.get("")@@ -70,6 +86,7 @@ async def list_bridges(bridge_type=b.type,display_name=b.display_name,status=b.status,+ is_default=b.is_default,)for b in bridges]@@ -90,6 +107,29 @@ async def get_bridge(bridge_type=bridge.type,display_name=bridge.display_name,status=bridge.status,+ is_default=bridge.is_default,+ )++[email protected]("/{bridge_id}/default")+async def set_default_bridge(+ bridge_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],+) -> BridgeInfo:+ """Nominate a bridge as the instance default, demoting the previous one."""+ try:+ bridge = await bridge_store.set_default(session, bridge_id)+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e))+ await session.commit()++ return BridgeInfo(+ bridge_id=bridge.id,+ bridge_type=bridge.type,+ display_name=bridge.display_name,+ status=bridge.status,+ is_default=bridge.is_default,)diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex e4ac1af33..06df5d550 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -42,6 +42,12 @@ class MattermostConnectionConfig(BridgeConnectionConfig):# address). Used for the channel deeplink so the link works in the user's# desktop client. Falls back to `url` when unset.public_url: str | None = None+ # Human account to add to every channel this bridge creates. A bundled+ # Mattermost has exactly one human, and a room created by an agent names no+ # users — without this they would never be a member of a private channel and+ # could not read the room at all. Unset for bridges where membership is+ # managed on the platform.+ default_member: str | None = Noneclass MattermostAdapter(CollaborationAdapter):@@ -523,8 +529,31 @@ class MattermostAdapter(CollaborationAdapter):)channel_id = channel["id"]+ await self._add_default_member(channel_id)return channel_id+ async def _add_default_member(self, channel_id: str) -> None:+ """Add the deployment's human account to a channel we just created.++ Public channels would let them join by navigating, but private ones+ would not — and a room created by an agent names no users, so nothing+ else would ever add them. Best-effort and loudly logged: the channel and+ room already exist by this point, so failing here should not undo them,+ but it does mean a human cannot see the room.+ """+ member = self._config.default_member+ if not member:+ return+ try:+ await self.add_users_to_channel(channel_id, [member], [])+ except Exception:+ logger.exception(+ "Failed to add default member '%s' to Mattermost channel %s — "+ "the room exists but no human is in its channel",+ member,+ channel_id,+ )+async def get_channel_type(self, channel_id: str) -> ChannelType:if not self._admin_driver or not self._main_loop:raise RuntimeError("Mattermost client not connected")diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 43c4b1f7e..d697d6d76 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -498,10 +498,25 @@ class CollaborationBridge(Base):agent_greetings_enabled: Mapped[bool] = mapped_column(Boolean, server_default="true", nullable=False)+ # The bridge new rooms land on when no bridge is named. At most one row may+ # be true; the partial unique index below is what actually enforces that,+ # so concurrent writers cannot produce two defaults.+ is_default: Mapped[bool] = mapped_column(+ Boolean, server_default="false", nullable=False+ )created_at: Mapped[str] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)+ __table_args__ = (+ Index(+ "ix_collaboration_bridges_single_default",+ "is_default",+ unique=True,+ postgresql_where=text("is_default"),+ ),+ )+# ── Server-Side Connectors ────────────────────────────────────────────────────diff --git a/core/switch_core/db/stores/collaboration_bridge_store.py b/core/switch_core/db/stores/collaboration_bridge_store.pyindex 4094b2c6a..1fd8d0732 100644--- a/core/switch_core/db/stores/collaboration_bridge_store.py+++ b/core/switch_core/db/stores/collaboration_bridge_store.py@@ -27,6 +27,36 @@ class CollaborationBridgeStore:)return list(result.scalars().all())+ async def get_default(self, session: AsyncSession) -> CollaborationBridge | None:+ """The bridge new rooms land on when none is named, or None when the+ instance has not nominated one."""+ result = await session.execute(+ select(CollaborationBridge).where(CollaborationBridge.is_default.is_(True))+ )+ return result.scalars().one_or_none()++ async def set_default(+ self, session: AsyncSession, bridge_id: str+ ) -> CollaborationBridge:+ """Nominate ``bridge_id`` as the instance default, demoting whichever+ bridge held it before. The demotion is flushed first because a partial+ unique index enforces a single default — writing the new one while the+ old is still set would collide."""+ bridge = await session.get(CollaborationBridge, bridge_id)+ if bridge is None:+ raise ValueError(f"Bridge not found: {bridge_id}")++ current = await self.get_default(session)+ if current is not None and current.id == bridge_id:+ return bridge+ if current is not None:+ current.is_default = False+ await session.flush()++ bridge.is_default = True+ await session.flush()+ return bridge+async def update_status(self, session: AsyncSession, bridge_id: str, status: str) -> None:diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 2f63cea1c..779e12ca2 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -81,6 +81,7 @@ async def create_bridge(display_name=bridge.display_name,status=bridge.status,agent_greetings_enabled=bridge.agent_greetings_enabled,+ is_default=bridge.is_default,room_count=0,created_at=str(bridge.created_at),)@@ -105,6 +106,7 @@ async def list_bridges(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),)@@ -137,6 +139,7 @@ async def update_bridge(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),)diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex abbe529fe..fb392f954 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -332,6 +332,7 @@ async def create_room(join_event_listeners=req.join_event_listeners,user_names=req.user_names,bridge_id=req.bridge_id,+ internal_only=req.internal_only,external_channel_id=req.external_channel_id,group_id=req.group_id,created_by=user.id,diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 7fd815c73..7e5fed3aa 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -96,6 +96,9 @@ class RoomCreateRequest(BaseModel):join_event_listeners: list[str] | None = Noneuser_names: list[str] | None = Nonebridge_id: str | None = None+ # Opt out of the instance default bridge: create a room with no external+ # channel. Ignored when bridge_id is set.+ internal_only: bool = Falseexternal_channel_id: str | None = Nonegroup_id: str | None = Noneread_visibility: str = "public"@@ -410,6 +413,7 @@ class BridgeDetail(BaseModel):display_name: strstatus: stragent_greetings_enabled: bool+ is_default: boolroom_count: intcreated_at: strdiff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 1545b13e9..7bf123919 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -244,6 +244,7 @@ async def run() -> None:agent_store=agent_store,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle,+ collab_bridge_store=bridge_store,resource_service=resource_service,session_factory=session_factory,)diff --git a/core/switch_core/migrations/versions/a1b2c3d4e5f6_default_collaboration_bridge.py b/core/switch_core/migrations/versions/a1b2c3d4e5f6_default_collaboration_bridge.pynew file mode 100644index 000000000..bede6e035--- /dev/null+++ b/core/switch_core/migrations/versions/a1b2c3d4e5f6_default_collaboration_bridge.py@@ -0,0 +1,58 @@+"""default collaboration bridge (CHOO-1674)++Adds ``is_default`` to ``collaboration_bridges`` so a Switch instance can name+the bridge that new rooms land on when no bridge is given. This is what makes a+standalone deployment usable out of the box: the bundled Mattermost becomes the+default, so every room has a place humans can read it, and internal-only+becomes an explicit opt-out rather than the accident of omitting a field.++A partial unique index enforces "at most one default" in the database rather+than in application code, so two concurrent writers cannot both win.++Existing instances are left without a default on purpose — adopting one is+``setup.py``'s job (it knows which bridge is the bundled one), and silently+promoting an arbitrary existing bridge here could start routing rooms to a+Slack workspace the operator never nominated.++Revision ID: a1b2c3d4e5f6+Revises: d5e6f7a8b9c0+Create Date: 2026-07-28 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers, used by Alembic.+revision: str = "a1b2c3d4e5f6"+down_revision: str | None = "d5e6f7a8b9c0"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_INDEX_NAME = "ix_collaboration_bridges_single_default"+++def upgrade() -> None:+ op.add_column(+ "collaboration_bridges",+ sa.Column(+ "is_default",+ sa.Boolean(),+ server_default=sa.text("false"),+ nullable=False,+ ),+ )+ op.create_index(+ _INDEX_NAME,+ "collaboration_bridges",+ ["is_default"],+ unique=True,+ postgresql_where=sa.text("is_default"),+ )+++def downgrade() -> None:+ op.drop_index(_INDEX_NAME, table_name="collaboration_bridges")+ op.drop_column("collaboration_bridges", "is_default")diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex c4454e9cd..ba4a9f32a 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -13,6 +13,7 @@ from switch_core.bridges.resource.service import ResourceServicefrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.db.models import Room, RoomGroup, RoomRolefrom switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.matrix_admin import MatrixAdmin@@ -53,6 +54,11 @@ class RoomCreateConfig(BaseModel):user_names: list[str] | None = Nonechannel_type: ChannelType | None = Nonebridge_id: str | None = None+ # Opt out of the instance default bridge and create a room with no external+ # channel. Only meaningful when ``bridge_id`` is unset: omitting the bridge+ # now means "use the default", so making a room agent-only has to be said+ # rather than implied.+ internal_only: bool = Falseexternal_channel_id: str | None = Noneinstructions: str | None = Noneprotection_config: dict[str, object] | None = None@@ -107,6 +113,7 @@ class RoomService:agent_store: AgentStore,client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,+ collab_bridge_store: CollaborationBridgeStore,resource_service: ResourceService,session_factory: async_sessionmaker[AsyncSession],) -> None:@@ -115,6 +122,7 @@ class RoomService:self._agent_store = agent_storeself._client_lifecycle = client_lifecycleself._collab_lifecycle = collab_lifecycle+ self._collab_bridge_store = collab_bridge_storeself._resource_service = resource_serviceself._session_factory = session_factory@@ -280,6 +288,39 @@ class RoomService:await session.commit()return failures+ async def _resolve_bridge_id(self, config: RoomCreateConfig) -> str | None:+ """Pick the bridge for a new room: the one named, else the instance+ default, else none.++ A standalone Switch always ships a bridge (the bundled Mattermost), so+ defaulting to it means every room has somewhere humans can read it+ without the caller having to know the deployment's topology. Callers+ that genuinely want an agent-only room pass ``internal_only``.++ A default that is configured but not currently running is reported+ rather than skipped — silently creating an unbridged room would look+ identical to success and only surface much later as a room nobody can+ see.+ """+ if config.bridge_id:+ return config.bridge_id+ if config.internal_only:+ return None++ async with self._session_factory() as session:+ default = await self._collab_bridge_store.get_default(session)+ if default is None:+ return None++ if self._collab_lifecycle.get(default.id) is None:+ raise ValueError(+ f"Default bridge '{default.display_name}' ({default.id}) is not "+ "running, so the room cannot be bridged. Start the bridge, name "+ "a different bridge_id, or pass internal_only to create an "+ "agent-only room."+ )+ return default.id+async def create_room(self, config: RoomCreateConfig) -> RoomCreateResult:await self._validate_attachments(config)# Validate the group up front so a bad id fails before we provision a@@ -292,11 +333,12 @@ class RoomService:join_event_listeners = await self._resolve_join_event_listeners(config)channel_type = config.channel_typeexternal_channel_id = config.external_channel_id+ bridge_id = await self._resolve_bridge_id(config)bridge_core = None- if config.bridge_id:- bridge_core = self._collab_lifecycle.get(config.bridge_id)+ if bridge_id:+ bridge_core = self._collab_lifecycle.get(bridge_id)if bridge_core is None:- raise ValueError(f"Bridge not running: {config.bridge_id}")+ raise ValueError(f"Bridge not running: {bridge_id}")if bridge_core and external_channel_id is not None and channel_type is None:channel_type = await bridge_core.adapter.get_channel_type(@@ -355,7 +397,7 @@ class RoomService:name=config.name,description=config.description,channel_type=channel_type,- bridge_id=config.bridge_id,+ bridge_id=bridge_id,external_channel_id=external_channel_id,admin_mode=config.admin_mode,instructions=config.instructions,diff --git a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.pyindex ac9ff34f8..b54b8fa65 100644--- a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py+++ b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py@@ -67,3 +67,86 @@ async def test_set_agent_greetings_enabled_unknown_bridge_raises(async with session_factory() as session:with pytest.raises(ValueError):await store.set_agent_greetings_enabled(session, "does-not-exist", False)+++async def test_no_default_bridge_until_one_is_nominated(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)++ assert await store.get_default(session) is None+ bridge = await store.get(session, bridge_id)+ assert bridge is not None+ assert bridge.is_default is False+++async def test_set_default_persists(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)+ await store.set_default(session, bridge_id)+ await session.commit()++ async with session_factory() as session:+ default = await store.get_default(session)+ assert default is not None+ assert default.id == bridge_id+++async def test_nominating_a_new_default_demotes_the_previous_one(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Only one bridge may be default — promoting a second must demote the+ first rather than trip the partial unique index."""+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ first = await _make_bridge(session)+ second = await _make_bridge(session)++ await store.set_default(session, first)+ await store.set_default(session, second)+ await session.commit()++ async with session_factory() as session:+ default = await store.get_default(session)+ assert default is not None+ assert default.id == second++ demoted = await store.get(session, first)+ assert demoted is not None+ assert demoted.is_default is False+++async def test_set_default_is_idempotent(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)++ await store.set_default(session, bridge_id)+ await store.set_default(session, bridge_id)+ await session.commit()++ async with session_factory() as session:+ default = await store.get_default(session)+ assert default is not None+ assert default.id == bridge_id+++async def test_set_default_unknown_bridge_raises(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ with pytest.raises(ValueError):+ await store.set_default(session, "does-not-exist")diff --git a/core/uv.lock b/core/uv.lockindex ac1bff945..3c66c3702 100644--- a/core/uv.lock+++ b/core/uv.lock@@ -2433,7 +2433,7 @@ wheels = [[[package]]name = "switch-core"-version = "0.6.0"+version = "0.8.1"source = { editable = "." }dependencies = [{ name = "aiohttp" },diff --git a/dash/apps/switchdash-desktop/electron.vite.config.ts b/dash/apps/switchdash-desktop/electron.vite.config.tsindex 3c6183350..a44337fe4 100644--- a/dash/apps/switchdash-desktop/electron.vite.config.ts+++ b/dash/apps/switchdash-desktop/electron.vite.config.ts@@ -29,6 +29,18 @@ export default defineConfig({'@root': resolve('.'),},},+ build: {+ rollupOptions: {+ input: {+ // The app's own preload, attached to the main window.+ index: resolve('src/preload/index.ts'),+ // Guest preload for the embedded Mattermost webview. Built as a+ // separate entry so it can be attached per-webview rather than to+ // the app window.+ 'mattermost-guest': resolve('src/preload/mattermost-guest.ts'),+ },+ },+ },},renderer: {root: 'src/renderer',diff --git a/dash/apps/switchdash-desktop/package.json b/dash/apps/switchdash-desktop/package.jsonindex d8424c993..5952ed024 100644--- a/dash/apps/switchdash-desktop/package.json+++ b/dash/apps/switchdash-desktop/package.json@@ -31,6 +31,7 @@"build": "electron-vite build && pnpm run build:sidecar","build:main": "electron-vite build --filter main","build:sidecar": "node scripts/build-sidecar.mjs",+ "sync:compose": "node scripts/sync-standalone-compose.mjs","build:renderer": "electron-vite build --filter renderer","package": "pnpm run build && electron-builder --config electron-builder.config.ts","package:mac": "pnpm run build && electron-builder --mac --config electron-builder.config.ts",diff --git a/dash/apps/switchdash-desktop/scripts/sync-standalone-compose.mjs b/dash/apps/switchdash-desktop/scripts/sync-standalone-compose.mjsindex e94f5878c..c6895dfe4 100644--- a/dash/apps/switchdash-desktop/scripts/sync-standalone-compose.mjs+++ b/dash/apps/switchdash-desktop/scripts/sync-standalone-compose.mjs@@ -6,23 +6,37 @@** Copies deploy/local/standalone-docker-compose.yml (the file the switch-release* workflow publishes to GHCR as `standalone-compose:<version>`) into- * src/main/core/local-switch-server/resources/, re-adding the "bundled copy"+ * src/main/core/managed-switch-server/resources/, re-adding the "bundled copy"* header. Run this when bumping COMPATIBLE_SWITCH_VERSION so the bundled compose* stays in lockstep with the pinned switch-core release. It reads the repo file* directly rather than pulling the OCI artifact so it works offline and before a* release exists; the two are identical by construction.*/-import { readFileSync, writeFileSync } from 'node:fs';+import { existsSync, readFileSync, writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';const here = dirname(fileURLToPath(import.meta.url));const repoRoot = resolve(here, '../../../..');const source = resolve(repoRoot, 'deploy/local/standalone-docker-compose.yml');-const dest = resolve(- here,- '../src/main/core/local-switch-server/resources/standalone-docker-compose.pinned.yml'-);+const destDir = resolve(here, '../src/main/core/managed-switch-server/resources');+const dest = resolve(destDir, 'standalone-docker-compose.pinned.yml');++// Name the module rename explicitly: this script pointed at the old+// `local-switch-server` path long after it was renamed, so it silently never+// ran and the bundled compose drifted from source.+for (const [label, path] of [+ ['source compose', source],+ ['destination directory', destDir],+]) {+ if (!existsSync(path)) {+ console.error(+ `sync-standalone-compose: ${label} not found at ${path}\n` ++ 'If a module was renamed, update this script to match.'+ );+ process.exit(1);+ }+}const header = `# BUNDLED COPY — do not hand-edit. This is the standalone compose published to# GHCR as \`standalone-compose:<version>\` by the switch-release workflow, pinneddiff --git a/dash/apps/switchdash-desktop/src/main/app/window.ts b/dash/apps/switchdash-desktop/src/main/app/window.tsindex f5f7d3008..76941c59c 100644--- a/dash/apps/switchdash-desktop/src/main/app/window.ts+++ b/dash/apps/switchdash-desktop/src/main/app/window.ts@@ -1,7 +1,8 @@import { join } from 'node:path';import { BrowserWindow } from 'electron';import appIcon from '@/assets/images/switchdash/switchdash_logo.png?asset';-import { registerExternalLinkHandlers } from '@main/utils/externalLinks';+import { log } from '@main/lib/logger';+import { registerExternalLinkHandlers, registerGuestLinkHandlers } from '@main/utils/externalLinks';import { PRODUCT_NAME } from '@shared/app-identity';import { APP_ORIGIN } from './protocol';@@ -23,6 +24,10 @@ export function createMainWindow(): BrowserWindow {sandbox: false,// __dirname resolves to out/main/ at runtime; preload is at out/preload/index.mjspreload: join(__dirname, '../preload/index.mjs'),+ // Enables the embedded room view's <webview> (CHOO-1674). Guests are+ // constrained in the will-attach-webview handler below, which is what+ // actually keeps this from widening the app's attack surface.+ webviewTag: true,},...(process.platform === 'darwin'? {@@ -43,6 +48,8 @@ export function createMainWindow(): BrowserWindow {// Route external links to the user’s default browserregisterExternalLinkHandlers(mainWindow, import.meta.env.DEV);+ constrainEmbeddedWebviews(mainWindow);+// Show when readymainWindow.once('ready-to-show', () => {mainWindow?.show();@@ -62,6 +69,41 @@ export function createMainWindow(): BrowserWindow {return mainWindow;}+/**+ * Strip privileges from any `<webview>` the renderer attaches.+ *+ * `webviewTag: true` lets renderer markup ask for a guest with whatever+ * webPreferences it likes, so the renderer is no longer the only thing that has+ * to be trusted — the embedded page is too. Rather than trusting the tag's+ * attributes, we overwrite the dangerous ones here, and allow only the guest+ * preload the app ships. Anything else is dropped.+ */+function constrainEmbeddedWebviews(window: BrowserWindow): void {+ const guestPreload = join(__dirname, '../preload/mattermost-guest.mjs');++ window.webContents.on('will-attach-webview', (event, webPreferences, params) => {+ // Never honour a preload named in markup — pin it to the one we ship.+ webPreferences.preload = guestPreload;+ webPreferences.nodeIntegration = false;+ webPreferences.contextIsolation = true;++ // Only ever embed real web content. A file:// or custom-scheme guest would+ // be running local content with a preload attached, which is not something+ // this feature needs.+ const protocol = params.src ? new URL(params.src).protocol : null;+ if (protocol !== 'http:' && protocol !== 'https:') {+ log.warn('Blocked webview attach for non-http source', { src: params.src });+ event.preventDefault();+ }+ });++ // A guest inherits none of the window's link handling, so wire it up as each+ // one attaches — otherwise every link in a message is silently inert.+ window.webContents.on('did-attach-webview', (_event, guest) => {+ registerGuestLinkHandlers(guest);+ });+}+export function getMainWindow(): BrowserWindow | null {return mainWindow;}diff --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 8da6e71d7..76385f312 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@@ -1,3 +1,5 @@+import { USER_DATA_DIR_NAME } from '@shared/app-identity';+/*** Fixed coordinates for the managed local stack. These mirror the ports and* hosts baked into the bundled standalone compose (resources/…pinned.yml): the@@ -5,14 +7,27 @@* switchdash addresses the resulting server.*/-/** `docker compose --project-name` for the managed stack on this machine, so its- * containers and volumes are isolated and discoverable across app restarts. */-export const LOCAL_SERVER_PROJECT_NAME = 'switchdash-local';+/**+ * `docker compose --project-name` for the managed stack on this machine, so its+ * containers and volumes are isolated and discoverable across app restarts.+ *+ * Scoped per build. Each build keeps its generated stack secrets in its own+ * userData dir (see USER_DATA_DIR_NAME), but Postgres only honours+ * POSTGRES_PASSWORD when it initialises a fresh volume — so builds sharing one+ * project name share `pgdata` and every build except the one that created it+ * fails authentication. They also fight over the containers themselves,+ * recreating each other's stack on start. Stable keeps the original name so+ * existing installs stay attached to the stack they already have.+ */+export const LOCAL_SERVER_PROJECT_NAME =+ USER_DATA_DIR_NAME === 'switchdash' ? 'switchdash-local' : `${USER_DATA_DIR_NAME}-local`;/** `docker compose --project-name` for a managed stack on a remote host. Each- * remote host runs its own Docker daemon, so a single fixed name is enough to- * isolate + rediscover the stack there. */-export const REMOTE_SERVER_PROJECT_NAME = 'switchdash-remote';+ * remote host runs its own Docker daemon, so one name per build is enough to+ * isolate + rediscover the stack there — per build for the same reason as+ * {@link LOCAL_SERVER_PROJECT_NAME}, since two builds can target one host. */+export const REMOTE_SERVER_PROJECT_NAME =+ USER_DATA_DIR_NAME === 'switchdash' ? 'switchdash-remote' : `${USER_DATA_DIR_NAME}-remote`;/** File names of the compose file and generated `.env` inside the host working* dir. Kept relative so `docker compose -f <name>` resolves against the workingdiff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/host-for-server.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/host-for-server.tsindex 106cb171e..c26c12e11 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/host-for-server.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/host-for-server.ts@@ -1,5 +1,6 @@import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { remoteSecretsKey } from './remote-identity';+import { localServerDir, remoteServerStateDir } from '../paths';+import { hostSlug, remoteSecretsKey } from './remote-identity';/** Local host's fixed secrets-store key. */const LOCAL_SECRETS_KEY = 'local-switch-server:secrets';@@ -18,3 +19,16 @@ export function managedServerSecretsKey(server: SwitchServer): string {}return LOCAL_SECRETS_KEY;}++/**+ * The on-disk state directory holding a managed server's persisted port+ * choice. Like {@link managedServerSecretsKey}, this exists so a caller that+ * only needs to read state does not have to construct a {@link ServerHost} —+ * which for a remote server would open an SSH connection.+ */+export function managedServerStateDir(server: SwitchServer): string {+ if (server.managementKind === 'remote' && server.sshHost) {+ return remoteServerStateDir(hostSlug(server.sshHost));+ }+ return localServerDir();+}diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/ports.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/ports.tsindex c31dd4357..3536958c1 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/ports.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/ports.ts@@ -3,11 +3,15 @@ import { dirname, join } from 'node:path';import { isPorts, type LocalServerPorts } from './free-port';import type { ServerHost } from './host/types';-function portsFilePath(host: ServerHost): string {+/** Reading the persisted choice only needs the state directory — not a live+ * host — so these take the narrowest shape that works. */+type HostStateDir = Pick<ServerHost, 'stateDir'>;++function portsFilePath(host: HostStateDir): string {return join(host.stateDir, 'ports.json');}-async function loadPersisted(host: ServerHost): Promise<LocalServerPorts | null> {+async function loadPersisted(host: HostStateDir): Promise<LocalServerPorts | null> {try {const parsed: unknown = JSON.parse(await readFile(portsFilePath(host), 'utf8'));return isPorts(parsed) ? parsed : null;@@ -41,7 +45,7 @@ export async function resolvePorts(host: ServerHost): Promise<LocalServerPorts>* Used at boot to re-establish a remote forward only when we know the ports the* running containers are actually bound to (picking fresh here would forward to* the wrong ports). */-export function readPersistedPorts(host: ServerHost): Promise<LocalServerPorts | null> {+export function readPersistedPorts(host: HostStateDir): Promise<LocalServerPorts | null> {return loadPersisted(host);}diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex 4f21aab08..7829a1830 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -52,9 +52,21 @@ services:PGPASSWORD: ${DB_PASSWORD}entrypoint: >sh -c "- until pg_isready -h postgres -U ${DB_USER}; do sleep 1; done- psql -h postgres -U ${DB_USER} -tc \"SELECT 1 FROM pg_database WHERE datname='mattermost'\" | grep -q 1 ||- psql -h postgres -U ${DB_USER} -c 'CREATE DATABASE mattermost;'+ i=0+ until psql -h postgres -U ${DB_USER} -d postgres -c 'SELECT 1' >/dev/null 2>&1; do+ i=$$((i+1))+ if [ $$i -ge 30 ]; then+ echo 'init-db: could not connect to postgres as ${DB_USER} after 30 tries.' >&2+ echo 'Last attempt:' >&2+ psql -h postgres -U ${DB_USER} -d postgres -c 'SELECT 1' >&2+ echo 'A stale pgdata volume keeps the password it was first created with,' >&2+ echo 'so a regenerated DB_PASSWORD will fail here. Recreate the stack to reset it.' >&2+ exit 1+ fi+ sleep 1+ done+ psql -h postgres -U ${DB_USER} -d postgres -tc \"SELECT 1 FROM pg_database WHERE datname='mattermost'\" | grep -q 1 ||+ psql -h postgres -U ${DB_USER} -d postgres -c 'CREATE DATABASE mattermost;'"depends_on:postgres:@@ -75,7 +87,13 @@ services:TUWUNEL_MAX_REQUEST_SIZE: "20000000"mattermost:- image: mattermost/mattermost-team-edition:latest+ # Pinned rather than `latest`: switchdash embeds this Mattermost's web UI+ # and depends on its DOM structure, so an unattended upgrade could break+ # the embedded room view on a `docker compose pull` no one initiated.+ image: mattermost/mattermost-team-edition:11.9.0+ # Mattermost publishes team-edition for amd64 only, so an Apple Silicon or+ # other arm64 host fails the pull outright without this. Runs emulated.+ platform: linux/amd64profiles: ["collab"]ports:- "${SWITCH_BIND_ADDR:-0.0.0.0}:${MATTERMOST_HOST_PORT:-8065}:8065"@@ -86,6 +104,14 @@ services:MM_SQLSETTINGS_DATASOURCE: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/mattermost?sslmode=disableMM_SERVICESETTINGS_SITEURL: http://localhost:${MATTERMOST_HOST_PORT:-8065}MM_SERVICESETTINGS_ENABLELOCALMODE: "true"+ # The first-run onboarding checklist opens a modal over a dimmed page,+ # which in the embedded room view is chrome the user cannot meaningfully+ # act on and has to dismiss per account.+ MM_SERVICESETTINGS_ENABLEONBOARDINGFLOW: "false"+ # Agents post `switchdash://session?…` deeplinks so a human can jump from+ # a message to the session behind it. Mattermost only turns known schemes+ # into links, so without this they render as unclickable plain text.+ MM_DISPLAYSETTINGS_CUSTOMURLSCHEMES: switchdashMM_SERVICESETTINGS_ENABLEBOTACCOUNTCREATION: "true"MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS: "true"# Lets the bridge hard-delete (permanent=true) an agent's transient@@ -93,6 +119,11 @@ services:# leave a "(message deleted)" tombstone. Requires Mattermost >= v10.2.MM_SERVICESETTINGS_ENABLEAPIPOSTDELETION: "true"MM_TEAMSETTINGS_ENABLEOPENSERVER: "true"+ # Neither plugin is usable in a bundled Switch deployment: Copilot has no+ # configured provider and throws a 404 looking up its bot on every page+ # load, and Calls ships a WebRTC service nothing here can reach.+ MM_PLUGINSETTINGS_PLUGINSTATES: |+ {"mattermost-ai":{"Enable":false},"com.mattermost.calls":{"Enable":false}}depends_on:init-db:condition: service_completed_successfully@@ -117,6 +148,7 @@ services:GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}FRONTEND_BASE_URL: ${FRONTEND_BASE_URL}+ GATEWAY_PUBLIC_URL: ${GATEWAY_PUBLIC_URL:-}depends_on:postgres:condition: service_healthydiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.tsindex 6038270ce..9923347e4 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/controller.ts@@ -1,7 +1,23 @@+import type { MattermostTheme } from '@shared/core/switch-rooms/mattermost-theme';+import type { RoomEmbed } from '@shared/core/switch-rooms/room-embed';import type { SessionRoomConnection } from '@shared/core/switch-rooms/switch-rooms';import { createRPCController } from '@shared/lib/ipc/rpc';+import { resolveChannelEmbed } from './mattermost-embed';import { switchRoomService } from './switch-room-service';export const switchRoomsController = createRPCController({getConnections: (): SessionRoomConnection[] => switchRoomService.getConnections(),++ /**+ * Decide how a room's conversation should be shown, and prepare whatever+ * that needs (a logged-in Mattermost partition, for the inline case). Called+ * by the room view before rendering, and again on retry — a failure here is+ * usually a Mattermost that has not finished starting.+ */+ resolveRoomEmbed: (params: {+ serverId: string;+ bridgeType: string | null;+ externalChannelUrl: string | null;+ theme: MattermostTheme | null;+ }): Promise<RoomEmbed> => resolveChannelEmbed(params),});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.tsnew file mode 100644index 000000000..5482759b4--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/mattermost-embed.ts@@ -0,0 +1,218 @@+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 { loadOrCreateSecrets } from '@main/core/managed-switch-server/secrets';+import { getServer } from '@main/core/switch-servers/servers-store';+import { log } from '@main/lib/logger';+import type { MattermostTheme } from '@shared/core/switch-rooms/mattermost-theme';+import {+ channelUrlFromDeeplink,+ mattermostPartition,+ type RoomEmbed,+} from '@shared/core/switch-rooms/room-embed';++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.+ *+ * Two things make this work, both verified against a real Mattermost 11.9.0+ * rather than reasoned about:+ *+ * 1. `X-Requested-With: XMLHttpRequest` is REQUIRED. Without it Mattermost+ * answers 200 and returns a `Token` header but sets no cookies at all —+ * cookie auth is deliberately granted only to XHR-style requests, since a+ * cookie is what a cross-site form post could abuse. Its own web app always+ * sends this header.+ * 2. The request must go through the partition's own session, which is where+ * Electron then stores the response's cookies. A plain `net.fetch` puts+ * them in the default session instead, out of the webview's reach.+ *+ * Mattermost marks only MMAUTHTOKEN HttpOnly; its web app reads MMUSERID and+ * MMCSRF from `document.cookie` to decide it is signed in, so all three must+ * land with their original flags. Letting the net stack store them keeps that+ * automatic.+ *+ * Throws on failure; an embed that silently renders a login page is worse than+ * a stated error.+ */+async function installMattermostSession(origin: string, serverId: string): Promise<string> {+ const server = await getServer(serverId);+ if (!server?.managed) throw new Error('Not a managed server');++ const secrets = await loadOrCreateSecrets({ secretsKey: managedServerSecretsKey(server) });++ const partition = mattermostPartition(serverId);+ const partitionSession = electronSession.fromPartition(partition);++ const response = await partitionSession.fetch(`${origin}/api/v4/users/login`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-Requested-With': 'XMLHttpRequest',+ },+ credentials: 'include',+ body: JSON.stringify({+ login_id: MATTERMOST_USER,+ password: secrets.mattermostUserPassword,+ }),+ });++ if (!response.ok) {+ throw new Error(+ `Mattermost login failed (${response.status}). The bundled chat may still be starting.`+ );+ }++ await partitionSession.cookies.flushStore();++ // Assert against the jar the webview reads, not the response — that is the+ // state the embed actually depends on.+ const stored = await partitionSession.cookies.get({ url: origin });+ const names = stored.map((c) => c.name);+ if (!names.includes(MATTERMOST_AUTH_COOKIE)) {+ throw new Error(+ `Mattermost login returned ${response.status} but the webview partition has no ` ++ `${MATTERMOST_AUTH_COOKIE} (cookies present: ${names.join(', ') || 'none'}).`+ );+ }++ return partition;+}++/**+ * Apply switchdash's palette to the Mattermost account the embed signs in as.+ *+ * Mattermost stores this as a per-user preference, so it themes itself rather+ * than us overriding its stylesheet from the guest preload — menus, hovers and+ * code blocks stay coherent instead of half-converted.+ *+ * Best-effort: a room that renders in Mattermost's default colours is a+ * cosmetic problem, not a reason to fall back to the deeplink. Logged rather+ * than swallowed.+ */+async function applyMattermostTheme(+ origin: string,+ partition: string,+ theme: MattermostTheme+): Promise<void> {+ const partitionSession = electronSession.fromPartition(partition);+ const request = (path: string, init?: { method?: string; body?: string }) =>+ partitionSession.fetch(`${origin}${path}`, {+ credentials: 'include',+ ...init,+ headers: {+ 'Content-Type': 'application/json',+ // Same requirement as the login: Mattermost rejects cookie-authenticated+ // writes that do not look like XHR.+ 'X-Requested-With': 'XMLHttpRequest',+ },+ });++ try {+ const meResponse = await request('/api/v4/users/me');+ if (!meResponse.ok) throw new Error(`GET /users/me returned ${meResponse.status}`);+ const { id } = (await meResponse.json()) as { id: string };++ // The preference value is a JSON *string*, not an object.+ const saved = await request(`/api/v4/users/${id}/preferences`, {+ method: 'PUT',+ body: JSON.stringify([+ { user_id: id, category: 'theme', name: '', value: JSON.stringify(theme) },+ ]),+ });+ if (!saved.ok) throw new Error(`PUT /preferences returned ${saved.status}`);+ } catch (cause) {+ log.warn('Could not apply the switchdash theme to Mattermost; using its defaults', {+ reason: cause instanceof Error ? cause.message : String(cause),+ });+ }+}++/**+ * Decide how to show a room's conversation, and prepare whatever that choice+ * needs (a logged-in partition, for the inline case).+ *+ * Every failure resolves to `external` or `unavailable` with a reason rather+ * than throwing: a room that cannot be embedded should degrade to its deeplink+ * with the cause on screen, not blank the pane.+ */+export async function resolveChannelEmbed(params: {+ serverId: string;+ bridgeType: string | null;+ externalChannelUrl: string | null;+ theme: MattermostTheme | null;+}): Promise<RoomEmbed> {+ const { serverId, bridgeType, externalChannelUrl, theme } = params;++ if (!bridgeType) {+ return {+ kind: 'unavailable',+ reason: 'This room has no chat channel — it was created as an agent-only room.',+ };+ }++ if (bridgeType !== 'mattermost') {+ if (externalChannelUrl) {+ return { kind: 'external', url: externalChannelUrl, platform: bridgeType };+ }+ return {+ kind: 'unavailable',+ reason: `This room is bridged to ${bridgeType}, which cannot be shown inside switchdash.`,+ };+ }++ const origin = await mattermostOriginFor(serverId);+ if (!origin || !externalChannelUrl) {+ if (externalChannelUrl) {+ return { kind: 'external', url: externalChannelUrl, platform: bridgeType };+ }+ return {+ kind: 'unavailable',+ reason: 'No Mattermost channel is linked to this room yet.',+ };+ }++ const url = channelUrlFromDeeplink(externalChannelUrl, origin);+ if (!url) {+ return { kind: 'external', url: externalChannelUrl, platform: bridgeType };+ }++ try {+ const partition = await installMattermostSession(origin, serverId);+ if (theme) await applyMattermostTheme(origin, partition, theme);+ return { kind: 'inline', url, partition, chromeless: true };+ } catch (cause) {+ const reason = cause instanceof Error ? cause.message : String(cause);+ log.warn('Could not prepare inline Mattermost session; offering the deeplink instead', {+ serverId,+ reason,+ });+ return { kind: 'external', url: externalChannelUrl, platform: bridgeType };+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/utils/externalLinks.ts b/dash/apps/switchdash-desktop/src/main/utils/externalLinks.tsindex c56d9ac67..2b5fbe598 100644--- a/dash/apps/switchdash-desktop/src/main/utils/externalLinks.ts+++ b/dash/apps/switchdash-desktop/src/main/utils/externalLinks.ts@@ -1,4 +1,5 @@-import { shell, type BrowserWindow } from 'electron';+import { shell, type BrowserWindow, type WebContents } from 'electron';+import { DEEPLINK_SCHEME, handleDeeplinkUrl } from '@main/app/deeplinks';import { getMainWindow } from '@main/app/window';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';@@ -22,6 +23,68 @@ function requestExternalLinkOpen(url: string) {});}+/**+ * Link handling for an embedded `<webview>` guest (the room view's Mattermost).+ *+ * A guest gets none of the main window's handlers, and Electron's default for+ * an unhandled `window.open` is to deny it — so every external link in a+ * message silently did nothing when clicked. Mattermost renders those as+ * `target="_blank"`, which is `window.open`.+ *+ * Three destinations, in order of specificity:+ *+ * - our own `switchdash://` deeplinks, which agents post into rooms so a human+ * can jump to the session behind a message. Handled in-process rather than+ * handed to the OS: the app is already running and is the registered+ * handler, so a round trip through the shell would at best come back to us.+ * - the guest's own origin, which moves the pane rather than opening a window.+ * - anything else http(s), which belongs in the user's browser.+ */+export function registerGuestLinkHandlers(guest: WebContents) {+ const guestOrigin = (): string | null => {+ try {+ return new URL(guest.getURL()).origin;+ } catch {+ return null;+ }+ };++ const isSameOrigin = (url: string): boolean => {+ const origin = guestOrigin();+ return origin !== null && (url === origin || url.startsWith(`${origin}/`));+ };++ // Never let the guest spawn a window: it would be chrome-less, unmanaged and+ // outside the room pane. Every case below therefore denies, having routed the+ // URL somewhere useful first.+ const route = (url: string): void => {+ if (url.startsWith(`${DEEPLINK_SCHEME}://`)) {+ handleDeeplinkUrl(url);+ return;+ }+ if (isSameOrigin(url)) {+ void guest.loadURL(url);+ return;+ }+ if (/^https?:\/\//i.test(url)) {+ requestExternalLinkOpen(url);+ return;+ }+ log.warn('Blocked link with an unsupported scheme from the embedded room view', { url });+ };++ guest.setWindowOpenHandler(({ url }) => {+ route(url);+ return { action: 'deny' };+ });++ guest.on('will-navigate', (event, url) => {+ if (isSameOrigin(url)) return;+ event.preventDefault();+ route(url);+ });+}+export function registerExternalLinkHandlers(win: BrowserWindow, isDev: boolean) {const wc = win.webContents;diff --git a/dash/apps/switchdash-desktop/src/preload/mattermost-guest.ts b/dash/apps/switchdash-desktop/src/preload/mattermost-guest.tsnew file mode 100644index 000000000..c6d9d1bb7--- /dev/null+++ b/dash/apps/switchdash-desktop/src/preload/mattermost-guest.ts@@ -0,0 +1,140 @@+/**+ * Guest preload for the embedded Mattermost channel view (CHOO-1674).+ *+ * Runs inside the `<webview>` before any page script. Two jobs, both of which+ * have to happen before first paint:+ *+ * 1. Suppress the "Where would you like to view this?" desktop-vs-browser+ * interstitial. Mattermost records that choice in localStorage; writing it+ * up front means the channel loads directly instead of behind a gate the+ * user would have to dismiss on every navigation.+ *+ * 2. Hide the global header and sidebars, so the pane shows the channel and+ * nothing else. We inject CSS rather than using Mattermost's `/_popout/`+ * route because that route requires the desktop app's `window.opener`+ * token handshake, which an embedded webview cannot supply (verified in+ * Phase 0 — under an Electron UA the popout bounces to a login page).+ *+ * The sidebars are hidden, not unmounted, so they keep their global keyboard+ * shortcuts. Those would silently navigate a sidebar the user cannot see, so+ * we swallow them.+ */++// Mattermost's landing page records the user's choice under this key and skips+// the interstitial when it is already set.+const LANDING_PAGE_SEEN_KEY = '__landingPageSeen__';++const CHROMELESS_CSS = `+ #global-header,+ .team-sidebar,+ #SidebarContainer,+ .app-bar,+ .announcement-bar,+ .global-classification-banner,+ .sidebar--right--width-holder {+ display: none !important;+ }++ /* The centre column is a named grid track with a min width, and+ .main-wrapper's margin is gated on :has(.team-sidebar) — which still+ matches while the sidebar is merely hidden. Zero it so the channel fills+ the pane instead of sitting behind a phantom gutter. */+ .main-wrapper {+ margin-left: 0 !important;+ border-left: none !important;+ }++ #channel_view {+ min-width: 0 !important;+ }++ /* Workspace-administration affordances that do not belong in an embedded+ room: the reader is a switchdash user looking at one conversation, and+ acting on any of these would take them somewhere the pane cannot show.+ Add to this list as more surface: each entry is one Mattermost control. */++ /* "Invite others to the workspace", in the channel intro. */+ #introTextInvite {+ display: none !important;+ }+`;++function suppressLandingInterstitial(): void {+ try {+ window.localStorage.setItem(LANDING_PAGE_SEEN_KEY, 'true');+ } catch {+ // Storage can be unavailable before the origin is committed; the+ // interstitial is a nuisance, not a failure, so carry on either way.+ }+}++/**+ * Run `attach` as soon as `<html>` exists.+ *+ * A preload runs before the parser has produced anything: `document` is there+ * but `document.documentElement` is still null (measured against Mattermost+ * 11.9.0 — `readyState: "loading"`, documentElement/head/body all null). So the+ * style element has nowhere to go yet, and appending unconditionally throws.+ * Waiting for DOMContentLoaded instead would risk painting the full chrome+ * first, so watch for the root element and attach the instant it appears.+ */+function whenDocumentElement(attach: () => void): void {+ if (document.documentElement) {+ attach();+ return;+ }+ new MutationObserver((_records, observer) => {+ if (document.documentElement) {+ observer.disconnect();+ attach();+ }+ }).observe(document, { childList: true });+}++function injectChromelessCss(): void {+ whenDocumentElement(() => {+ const style = document.createElement('style');+ style.setAttribute('data-switchdash', 'chromeless');+ style.textContent = CHROMELESS_CSS;+ document.documentElement.appendChild(style);+ });+}++/**+ * Mattermost binds these to window at the document level. With the sidebars+ * hidden they would move the user somewhere invisible, so stop them before+ * Mattermost's own listeners see them.+ */+function swallowHiddenSidebarShortcuts(): void {+ window.addEventListener(+ 'keydown',+ (event) => {+ const mod = event.ctrlKey || event.metaKey;+ const navigatesHiddenSidebar =+ (event.altKey && ['ArrowUp', 'ArrowDown'].includes(event.key)) ||+ (mod && event.shiftKey && ['K', 'k', 'A', 'a'].includes(event.key));+ if (navigatesHiddenSidebar) {+ event.stopImmediatePropagation();+ event.preventDefault();+ }+ },+ { capture: true }+ );+}++// Independently, so one failing step cannot take the others with it — a+// throw in the CSS injection previously left the shortcut guard unregistered+// too, which made a styling bug look like a keyboard bug as well.+for (const step of [+ suppressLandingInterstitial,+ injectChromelessCss,+ swallowHiddenSidebarShortcuts,+]) {+ try {+ step();+ } catch (cause) {+ // Nothing here is load-bearing enough to justify blanking the pane, but a+ // silent partial failure is what cost us the last round of debugging.+ console.error(`switchdash guest preload: ${step.name} failed`, cause);+ }+}diff --git a/dash/apps/switchdash-desktop/src/renderer/app/view-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/view-registry.tsindex 9dc2dc8ea..e930ababa 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/view-registry.ts+++ b/dash/apps/switchdash-desktop/src/renderer/app/view-registry.ts@@ -3,6 +3,7 @@ import { homeView } from '@renderer/app/home-view';import { locationView } from '@renderer/features/locations/view';import { sessionView } from '@renderer/features/sessions/view';import { settingsView } from '@renderer/features/settings/settings-view';+import { roomView } from '@renderer/features/switch-rooms/view';import { serverView } from '@renderer/features/switch-servers/view';import type { CommandProvider } from '@renderer/lib/commands/types';import { appState } from '@renderer/lib/stores/app-state';@@ -14,6 +15,7 @@ export const views = {home: homeView,location: locationView,session: sessionView,+ room: roomView,settings: settingsView,server: serverView,// oxlint-disable-next-line typescript/no-explicit-anydiff --git a/dash/apps/switchdash-desktop/src/renderer/app/workspace.tsx b/dash/apps/switchdash-desktop/src/renderer/app/workspace.tsxindex a3d7a861e..217f4ec9e 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/workspace.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/app/workspace.tsx@@ -1,4 +1,5 @@import { LeftSidebar } from '@renderer/features/sidebar/left-sidebar';+import { RoomEmbedLayer } from '@renderer/features/switch-rooms/room-embed-layer';import { CommandShortcutBinder } from '@renderer/lib/commands/command-shortcut-binder';import { AppKeyboardShortcuts } from '@renderer/lib/components/app-keyboard-shortcuts';import { MonacoKeyboardBridge } from '@renderer/lib/components/monaco-keyboard-bridge';@@ -27,6 +28,7 @@ export function Workspace() {<WorkspaceViewContent /></WrapView>}+ persistentLayer={<RoomEmbedLayer />}/><Toaster /></>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex 4ba6923dc..8822ac0b6 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -14,7 +14,9 @@ import { SidebarSessionItem } from './session-item';import {groupByRoom,openRoomInGateway,+ openRoomView,openRoomInMessagingApp,+ isRoomViewActive,RoomRow,roomLabel,} from './sidebar-room-grouping';@@ -123,6 +125,8 @@ const AgentSessions = observer(function AgentSessions({depth={depth}bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}+ onSelect={roomKey === UNASSIGNED_ROOM_KEY ? null : () => openRoomView(roomKey)}+ isActive={isRoomViewActive(roomKey)}onOpenGateway={() => openRoomInGateway(roomKey)}onOpenChannel={switchRoomsStore.roomChannelUrl(roomKey)@@ -205,6 +209,8 @@ const RoomFocusedTree = observer(function RoomFocusedTree() {depth={0}bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}+ onSelect={roomKey === UNASSIGNED_ROOM_KEY ? null : () => openRoomView(roomKey)}+ isActive={isRoomViewActive(roomKey)}onOpenGateway={() => openRoomInGateway(roomKey)}onOpenChannel={switchRoomsStore.roomChannelUrl(roomKey)diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex 3b8f9cda1..8a8c2f911 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -4,6 +4,7 @@ import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/swiimport { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { rpc } from '@renderer/lib/ipc';+import { appState } from '@renderer/lib/stores/app-state';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { cn } from '@renderer/utils/utils';import { SidebarItemMiniButton, SidebarMenuRow } from './sidebar-primitives';@@ -26,6 +27,28 @@ export function openRoomInGateway(roomKey: string): void {if (url) void rpc.app.openExternal(url);}+/** Show a room's conversation in the main panel (no-op for Unassigned, which+ * is a bucket rather than a real room). */+export function openRoomView(roomKey: string): void {+ if (roomKey === UNASSIGNED_ROOM_KEY) return;+ appState.navigation.navigate('room', { roomId: roomKey });+}++/**+ * Whether a room row is the one currently open in the main panel, so it can+ * carry the same selected styling as an agent or session row.+ *+ * Read from the navigation store rather than the `useParams` hook because the+ * room rows are produced inside `.map()` callbacks, where a hook cannot be+ * called. Observers re-render on navigation either way.+ */+export function isRoomViewActive(roomKey: string): boolean {+ if (roomKey === UNASSIGNED_ROOM_KEY) return false;+ if (appState.navigation.currentViewId !== 'room') return false;+ const params = appState.navigation.viewParamsStore.room;+ return (params as { roomId?: string } | undefined)?.roomId === roomKey;+}+/*** Open a room's bridged channel in the messaging app's desktop client (Slack,* Mattermost) via the native deeplink the gateway built. No-op when the room@@ -67,6 +90,8 @@ export function RoomRow({onToggle,onOpenGateway,onOpenChannel = null,+ onSelect = null,+ isActive = false,depth = 0,bridgeType = null,}: {@@ -75,6 +100,11 @@ export function RoomRow({expanded: boolean;onToggle: () => void;onOpenGateway: () => void;+ /** Open the room's conversation in the main panel. Null for rows that have+ * no room behind them (Unassigned), which stay expand-only. */+ onSelect?: (() => void) | null;+ /** True when this room's conversation is the view currently open. */+ isActive?: boolean;/** Open the room's channel in the messaging app, or null when there is no* native deeplink (room not bridged / link unknown). */onOpenChannel?: (() => void) | null;@@ -87,9 +117,10 @@ export function RoomRow({return (<SidebarMenuRowclassName="group/room flex h-8 items-center gap-1 px-1"+ isActive={isActive}style={depthIndent(depth)}onMouseDown={(e) => e.preventDefault()}- onClick={onToggle}+ onClick={onSelect ?? onToggle}><SidebarItemMiniButtontype="button"diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsxnew file mode 100644index 000000000..7847f1054--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx@@ -0,0 +1,249 @@+import { ExternalLink, Loader2, MessagesSquare, RefreshCw } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useCallback, useEffect, useRef, useState } from 'react';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { useTheme } from '@renderer/lib/hooks/useTheme';+import { rpc } from '@renderer/lib/ipc';+import { appState } from '@renderer/lib/stores/app-state';+import { Button } from '@renderer/lib/ui/button';+import { cn } from '@renderer/utils/utils';+import type { RoomEmbed } from '@shared/core/switch-rooms/room-embed';+import { currentMattermostTheme } from './theme-tokens';+import { WEBVIEW_ALLOW_POPUPS } from './webview-attrs';++/**+ * How many rooms keep a live `<webview>` once visited. Each one is a real+ * renderer process, so this trades memory for instant switching; beyond a+ * handful the cost stops being worth it and the oldest is dropped.+ */+const MAX_LIVE_EMBEDS = 4;++type EmbedState =+ | { phase: 'resolving' }+ | { phase: 'ready'; embed: RoomEmbed }+ | { phase: 'error'; message: string };++function RoomNotice({+ icon,+ title,+ detail,+ action,+}: {+ icon: React.ReactNode;+ title: string;+ detail?: string;+ action?: React.ReactNode;+}) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center">+ <div className="text-foreground-passive">{icon}</div>+ <p className="text-sm font-medium text-foreground">{title}</p>+ {detail && <p className="max-w-md text-xs text-foreground-muted">{detail}</p>}+ {action}+ </div>+ );+}++/**+ * Persistent host for room conversations.+ *+ * This lives above the view switch rather than inside the room view's+ * MainPanel, because a `<webview>` reloads from scratch whenever it is+ * unmounted OR re-parented — so navigating to a session and back used to+ * re-download and re-render the whole Mattermost client. Keeping the element+ * mounted and toggling visibility is the only way to make that instant.+ *+ * Rooms visited earlier stay mounted (bounded by MAX_LIVE_EMBEDS) so switching+ * between two rooms is instant in both directions.+ */+export const RoomEmbedLayer = observer(function RoomEmbedLayer() {+ const { effectiveTheme } = useTheme();+ const isRoomView = appState.navigation.currentViewId === 'room';+ const activeRoomId =+ (appState.navigation.viewParamsStore.room as { roomId?: string } | undefined)?.roomId ?? null;++ const [states, setStates] = useState<Map<string, EmbedState>>(new Map());+ // Visit order, oldest first — drives eviction.+ const orderRef = useRef<string[]>([]);+ // Which rooms have been resolved (or are in flight). Held in a ref so the+ // effect below can consult it without depending on `states`, which it also+ // writes — that dependency would re-run it on every resolution.+ const startedRef = useRef(new Set<string>());++ const resolve = useCallback(+ async (roomId: string) => {+ startedRef.current.add(roomId);+ setStates((prev) => new Map(prev).set(roomId, { phase: 'resolving' }));++ const serverId = switchRoomsStore.roomServerId(roomId);+ if (!serverId) {+ setStates((prev) =>+ new Map(prev).set(roomId, {+ phase: 'error',+ message: 'This room’s server is still loading. Try again in a moment.',+ })+ );+ return;+ }++ try {+ const embed = await rpc.switchRooms.resolveRoomEmbed({+ serverId,+ bridgeType: switchRoomsStore.roomBridgeTypeById(roomId),+ externalChannelUrl: switchRoomsStore.roomChannelUrl(roomId),+ theme: currentMattermostTheme(effectiveTheme),+ });+ setStates((prev) => new Map(prev).set(roomId, { phase: 'ready', embed }));+ } catch (cause) {+ setStates((prev) =>+ new Map(prev).set(roomId, {+ phase: 'error',+ message: cause instanceof Error ? cause.message : String(cause),+ })+ );+ }+ },+ [effectiveTheme]+ );++ // Resolve a room the first time it is opened, and evict the oldest beyond the+ // cap. Rooms already resolved are left alone — that is the whole point.+ useEffect(() => {+ if (!activeRoomId) return;++ orderRef.current = [...orderRef.current.filter((id) => id !== activeRoomId), activeRoomId];+ const evicted = orderRef.current.slice(0, -MAX_LIVE_EMBEDS);+ orderRef.current = orderRef.current.slice(-MAX_LIVE_EMBEDS);++ if (evicted.length) {+ for (const id of evicted) startedRef.current.delete(id);+ setStates((prev) => {+ const next = new Map(prev);+ for (const id of evicted) next.delete(id);+ return next;+ });+ }++ if (!startedRef.current.has(activeRoomId)) void resolve(activeRoomId);+ }, [activeRoomId, resolve]);++ /*+ * A theme switch needs the guest reloaded, not just re-pushed.+ *+ * Mattermost reads the theme preference when its client boots and renders it+ * into `:root` custom properties. Changing the preference underneath a page+ * that is already running does not restyle it, and overriding those+ * properties from the preload only half works — measured against 11.9.0, the+ * channel background follows but its text colour does not, which would leave+ * dark text on a dark pane.+ *+ * So push the new preference and reload. Since the theme is part of each+ * webview's key, that happens by remount. Backgrounded rooms are dropped+ * rather than reloaded in place: they would all reload at once for something+ * the user cannot see, and re-resolving on next open is cheaper.+ */+ const themeRef = useRef(effectiveTheme);+ useEffect(() => {+ if (themeRef.current === effectiveTheme) return;+ themeRef.current = effectiveTheme;++ startedRef.current = new Set(activeRoomId ? [activeRoomId] : []);+ orderRef.current = activeRoomId ? [activeRoomId] : [];+ setStates(new Map());++ if (activeRoomId) void resolve(activeRoomId);+ }, [effectiveTheme, activeRoomId, resolve]);++ // Never unmount, even off a room view: returning null here would destroy+ // every live <webview> and reload Mattermost on the way back, which is the+ // exact cost this layer exists to avoid. Hide the whole layer instead —+ // display:none keeps the guests running and takes the layer out of both+ // layout and hit-testing, so the view underneath behaves normally.+ const visible = isRoomView && activeRoomId !== null;+ const active = activeRoomId ? states.get(activeRoomId) : undefined;++ return (+ <div+ className={cn(+ 'absolute inset-x-0 top-10 bottom-0 overflow-hidden rounded-b-[10px] bg-background',+ visible ? 'block' : 'hidden'+ )}+ >+ {visible && (active?.phase === 'resolving' || active === undefined) ? (+ <RoomNotice+ icon={<Loader2 className="size-5 animate-spin" />}+ title="Opening conversation…"+ />+ ) : null}++ {visible && active?.phase === 'error' ? (+ <RoomNotice+ icon={<MessagesSquare className="size-6" />}+ title="Couldn’t open this conversation"+ detail={active.message}+ action={+ <Button+ variant="outline"+ size="sm"+ onClick={() => activeRoomId && void resolve(activeRoomId)}+ >+ <RefreshCw className="size-3" />+ Retry+ </Button>+ }+ />+ ) : null}++ {visible && active?.phase === 'ready' && active.embed.kind === 'unavailable' ? (+ <RoomNotice icon={<MessagesSquare className="size-6" />} title={active.embed.reason} />+ ) : null}++ {visible && active?.phase === 'ready' && active.embed.kind === 'external' ? (+ <RoomNotice+ icon={<MessagesSquare className="size-6" />}+ title={`This room lives in ${capitalise(active.embed.platform)}`}+ detail="Conversations on external platforms open in their own app."+ action={+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ const embed = active.embed;+ if (embed.kind === 'external') void rpc.app.openExternal(embed.url);+ }}+ >+ <ExternalLink className="size-3" />+ Open in {capitalise(active.embed.platform)}+ </Button>+ }+ />+ ) : null}++ {/* Every inline room stays mounted; only the active one is visible.+ Unmounting or moving these would reload Mattermost. */}+ {[...states.entries()].map(([roomId, state]) =>+ state.phase === 'ready' && state.embed.kind === 'inline' ? (+ <webview+ // The theme is part of the identity: Mattermost only picks up a+ // theme change at boot, so a switch has to remount the guest.+ key={`${state.embed.partition}:${state.embed.url}:${effectiveTheme}`}+ src={state.embed.url}+ partition={state.embed.partition}+ // Required for links to work at all: Mattermost renders external+ // links as target="_blank", and without this the guest's popups are+ // blocked outright — they never reach the window-open handler, so+ // clicking a link does nothing. No window is actually created; the+ // handler in the main process denies every request and routes+ // http(s) to the user's browser instead.+ {...WEBVIEW_ALLOW_POPUPS}+ className={cn('h-full w-full', roomId === activeRoomId ? 'flex' : 'hidden')}+ />+ ) : null+ )}+ </div>+ );+});++function capitalise(value: string): string {+ return value.charAt(0).toUpperCase() + value.slice(1);+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/theme-tokens.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/theme-tokens.tsnew file mode 100644index 000000000..833bcd70f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/theme-tokens.ts@@ -0,0 +1,72 @@+import {+ cssColorToHex,+ mattermostThemeFromTokens,+ type MattermostTheme,+ type ThemeTokens,+} from '@shared/core/switch-rooms/mattermost-theme';++/** Which CSS custom property backs each token the Mattermost theme needs. */+const TOKEN_VARIABLES: Record<keyof ThemeTokens, string> = {+ background: '--background',+ backgroundElevated: '--background-2',+ backgroundSecondary: '--background-secondary',+ foreground: '--foreground',+ foregroundMuted: '--foreground-muted',+ border: '--border',+ accent: '--primary-button-border',+ accentStrong: '--selection',+ buttonBg: '--primary-button-background',+ buttonColor: '--primary-button-foreground',+ destructive: '--foreground-destructive',+ warning: '--status-in-progress',+ success: '--status-in-review',+};++/**+ * Resolve the app's live palette to hex.+ *+ * Reading the custom properties directly would hand back their raw text —+ * `var()` chains, or keywords like `white` — so instead each one is applied to+ * an offscreen probe and read back as a computed colour, which the browser has+ * already resolved to a concrete colour function. That also means this follows+ * a theme switch automatically rather than duplicating the palette in TS.+ *+ * Returns null if any token fails to resolve: a partial theme would leave+ * Mattermost with a mix of our colours and its defaults, which looks worse+ * than leaving it alone.+ */+export function readThemeTokens(): ThemeTokens | null {+ if (typeof document === 'undefined') return null;++ const probe = document.createElement('div');+ probe.style.position = 'absolute';+ probe.style.visibility = 'hidden';+ probe.style.pointerEvents = 'none';+ document.body.appendChild(probe);++ try {+ const resolved: Partial<Record<keyof ThemeTokens, string>> = {};+ for (const [token, variable] of Object.entries(TOKEN_VARIABLES) as [+ keyof ThemeTokens,+ string,+ ][]) {+ probe.style.color = '';+ probe.style.color = `var(${variable})`;+ const hex = cssColorToHex(getComputedStyle(probe).color);+ if (!hex) return null;+ resolved[token] = hex;+ }+ return resolved as ThemeTokens;+ } finally {+ probe.remove();+ }+}++/** The app's current palette as a Mattermost theme, or null if unavailable. */+export function currentMattermostTheme(+ effectiveTheme: 'emlight' | 'emdark'+): MattermostTheme | null {+ const tokens = readThemeTokens();+ if (!tokens) return null;+ return mattermostThemeFromTokens(tokens, effectiveTheme === 'emdark' ? 'dark' : 'light');+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/view.tsxnew file mode 100644index 000000000..f75acea92--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/view.tsx@@ -0,0 +1,47 @@+import { observer } from 'mobx-react-lite';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';+import { useParams } from '@renderer/lib/layout/navigation-provider';++const RoomTitlebar = observer(function RoomTitlebar() {+ const { params } = useParams('room');+ const name = switchRoomsStore.roomNameById(params.roomId);+ const serverName = switchRoomsStore.roomServerName(params.roomId);++ return (+ <Titlebar+ leftSlot={+ <div className="flex items-center gap-1 px-2 text-sm text-foreground-muted">+ {serverName && (+ <>+ <span className="max-w-40 truncate text-sm text-foreground-passive">+ {serverName}+ </span>+ <span className="text-sm text-foreground-passive">/</span>+ </>+ )}+ <span className="max-w-56 truncate">{name ?? 'Room'}</span>+ </div>+ }+ />+ );+});++export const roomView = {+ WrapView: ({ children }: { children: React.ReactNode; roomId: string }) => <>{children}</>,+ TitlebarSlot: RoomTitlebar,+ // The conversation itself is drawn by RoomEmbedLayer, which is mounted above+ // the view switch so its <webview> survives navigating away and back.+ MainPanel: () => null,+ canActivate: (params: unknown): GuardResult => {+ const roomId =+ typeof params === 'object' && params !== null+ ? (params as { roomId?: unknown }).roomId+ : undefined;+ if (typeof roomId !== 'string') {+ return { ok: false, redirect: 'home' };+ }+ return { ok: true };+ },+} satisfies ViewDefinition<{ roomId: string }>;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/webview-attrs.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/webview-attrs.tsnew file mode 100644index 000000000..908ad87a2--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/webview-attrs.ts@@ -0,0 +1,17 @@+/**+ * `allowpopups` for the embedded room `<webview>`.+ *+ * Spread rather than written as a JSX prop for two reasons, both load-bearing:+ *+ * - React's own typing declares `allowpopups` as a boolean, but React does+ * NOT emit an attribute for `allowpopups={true}` on this element — the+ * attribute is simply absent, which Electron reads as popups blocked. It+ * has to reach the DOM as a string.+ * - Setting it later via a ref is too late: the guest attaches when the+ * element enters the DOM, and its popup policy is fixed at that point.+ *+ * Without the attribute, Electron blocks the guest's popups before they reach+ * the window-open handler, so every external link in a message silently does+ * nothing. Covered by webview-allowpopups.test.tsx.+ */+export const WEBVIEW_ALLOW_POPUPS: Record<string, string> = { allowpopups: 'true' };diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 91fd9f12b..7b89000db 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -55,6 +55,20 @@ export class SwitchRoomsStore {return this.channelUrlByRoom.get(roomId) ?? null;}+ /** Id of the server a room belongs to, or null if not yet loaded. The room+ * view needs it to resolve that server's Mattermost session. */+ roomServerId(roomId: string): string | null {+ return this.roomServerById.get(roomId) ?? null;+ }++ /** Display name of the server a room belongs to, for the room titlebar's+ * breadcrumb. Null while rooms are still loading. */+ roomServerName(roomId: string): string | null {+ const serverId = this.roomServerById.get(roomId);+ if (!serverId) return null;+ return switchServersStore.servers.find((s) => s.id === serverId)?.name ?? null;+ }+/*** URL of a room's detail page in the gateway web app, or null if the room's* owning server isn't known yet (names/servers are loaded by loadRoomNames).diff --git a/dash/apps/switchdash-desktop/src/renderer/globals.d.ts b/dash/apps/switchdash-desktop/src/renderer/globals.d.tsindex ec5ccabbc..c5f4f5c8e 100644--- a/dash/apps/switchdash-desktop/src/renderer/globals.d.ts+++ b/dash/apps/switchdash-desktop/src/renderer/globals.d.ts@@ -2,6 +2,27 @@ declare module 'react-syntax-highlighter';declare module 'react-syntax-highlighter/dist/esm/styles/prism';declare global {+ namespace React {+ namespace JSX {+ interface IntrinsicElements {+ /**+ * Electron's `<webview>` tag, used by the embedded room view. React+ * has no built-in typing for it, and only the attributes we actually+ * set are declared — adding one means adding it here first.+ */+ webview: React.DetailedHTMLProps<+ React.HTMLAttributes<HTMLElement> & {+ src?: string;+ partition?: string;+ preload?: string;+ useragent?: string;+ },+ HTMLElement+ >;+ }+ }+ }+interface Window {electronAPI: {invoke: (channel: string, ...args: unknown[]) => Promise<unknown>;diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/layout/workspace-layout.tsx b/dash/apps/switchdash-desktop/src/renderer/lib/layout/workspace-layout.tsxindex caac08b5c..9d15af018 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/layout/workspace-layout.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/lib/layout/workspace-layout.tsx@@ -12,9 +12,21 @@ const MAIN_PANEL_MIN_SIZE = '30%';interface WorkspaceLayoutProps {leftSidebar: ReactNode;mainContent: ReactNode;+ /**+ * Content overlaid on the main panel that must survive view changes.+ *+ * Rendered here rather than inside a view because the per-view subtree is+ * remounted on navigation, and the embedded room `<webview>` reloads its+ * whole client whenever it is unmounted or re-parented.+ */+ persistentLayer?: ReactNode;}-export function WorkspaceLayout({ leftSidebar, mainContent }: WorkspaceLayoutProps) {+export function WorkspaceLayout({+ leftSidebar,+ mainContent,+ persistentLayer = null,+}: WorkspaceLayoutProps) {const { leftPanelRef, handleDragging, syncLeftOpenFromPanel, isLeftOpen } =useWorkspaceLayoutContext();const { defaultLayout, onLayoutChanged } = useDefaultLayout({@@ -55,7 +67,10 @@ export function WorkspaceLayout({ leftSidebar, mainContent }: WorkspaceLayoutPro)}/><ResizablePanel id="workspace-main" minSize={MAIN_PANEL_MIN_SIZE}>- {mainContent}+ <div className="relative h-full w-full">+ {mainContent}+ {persistentLayer}+ </div></ResizablePanel></ResizablePanelGroup>);diff --git a/dash/apps/switchdash-desktop/src/renderer/tests/browser/webview-allowpopups.test.tsx b/dash/apps/switchdash-desktop/src/renderer/tests/browser/webview-allowpopups.test.tsxnew file mode 100644index 000000000..a4ccdf7de--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/tests/browser/webview-allowpopups.test.tsx@@ -0,0 +1,56 @@+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+/**+ * The embedded room view depends on React actually emitting `allowpopups` onto+ * the `<webview>` tag.+ *+ * Without that attribute Electron blocks the guest's popups outright — they+ * never reach the window-open handler in the main process — and every external+ * link in a Mattermost message silently does nothing when clicked. It is one+ * attribute on a non-standard element that React has no built-in knowledge of,+ * so it is exactly the kind of thing a React or typing upgrade could quietly+ * drop.+ */+import { WEBVIEW_ALLOW_POPUPS } from '@renderer/features/switch-rooms/webview-attrs';++let container: HTMLDivElement | null = null;++afterEach(() => {+ container?.remove();+ container = null;+});++describe('<webview allowpopups>', () => {+ it('renders the attribute onto the DOM element', async () => {+ container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(+ <webview src="http://127.0.0.1:1/x" partition="persist:test" {...WEBVIEW_ALLOW_POPUPS} />+ );+ });++ const el = container.querySelector('webview');+ expect(el).not.toBeNull();+ expect(el?.hasAttribute('allowpopups')).toBe(true);++ await act(async () => root.unmount());+ });++ it('omits the attribute when not asked for, so the default stays restrictive', async () => {+ container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(<webview src="http://127.0.0.1:1/x" partition="persist:test" />);+ });++ expect(container.querySelector('webview')?.hasAttribute('allowpopups')).toBe(false);++ await act(async () => root.unmount());+ });+});diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.tsindex 72a7ffc42..4e3ddf1dd 100644--- a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts@@ -12,4 +12,4 @@ export const RELEASE_REPO_OWNER = 'sandbox-quantum';export const RELEASE_REPO_NAME = 'switch';// Keep in sync with COMPATIBLE_SWITCH_VERSION in ./app-identity.ts.-export const COMPATIBLE_SWITCH_VERSION = '0.3.0';+export const COMPATIBLE_SWITCH_VERSION = '0.8.1';diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.tsindex f0e322810..b075e4f5c 100644--- a/dash/apps/switchdash-desktop/src/shared/app-identity.ts+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.ts@@ -27,4 +27,4 @@ export const RELEASE_REPO_NAME = 'switch';// artifact. Bump it in lockstep with the bundled compose// (src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml)// so a switchdash release pins a known-good switch-core stack.-export const COMPATIBLE_SWITCH_VERSION = '0.3.0';+export const COMPATIBLE_SWITCH_VERSION = '0.8.1';diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/mattermost-theme.test.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/mattermost-theme.test.tsnew file mode 100644index 000000000..b98647171--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/mattermost-theme.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest';+import { cssColorToHex, displayP3ToHex, mattermostThemeFromTokens } from './mattermost-theme';++describe('displayP3ToHex', () => {+ it('maps the endpoints exactly', () => {+ expect(displayP3ToHex(0, 0, 0)).toBe('#000000');+ expect(displayP3ToHex(1, 1, 1)).toBe('#ffffff');+ });++ it('leaves greys untouched, since the conversion rows sum to 1', () => {+ // switchdash's neutral scale is achromatic, so this is the property that+ // lets the palette survive the gamut change unchanged.+ expect(displayP3ToHex(0.067, 0.067, 0.067)).toBe('#111111');+ expect(displayP3ToHex(0.988, 0.988, 0.988)).toBe('#fcfcfc');+ });++ it('actually moves a saturated colour, rather than passing it through', () => {+ // jade-9 (dark). A naive read would give #51a085; P3 is the wider gamut, so+ // the sRGB equivalent has to be more saturated to look the same.+ const converted = displayP3ToHex(0.319, 0.63, 0.521);+ expect(converted).not.toBe('#51a085');+ expect(converted).toMatch(/^#[0-9a-f]{6}$/);+ });++ it('clips out-of-gamut colours instead of producing garbage', () => {+ // Pure P3 red is outside sRGB; every channel must still be a valid byte.+ expect(displayP3ToHex(1, 0, 0)).toMatch(/^#[0-9a-f]{6}$/);+ expect(displayP3ToHex(1, 0, 0).startsWith('#ff')).toBe(true);+ });+});++describe('cssColorToHex', () => {+ it('parses the color(display-p3 ...) form the palette computes to', () => {+ expect(cssColorToHex('color(display-p3 0.067 0.067 0.067)')).toBe('#111111');+ });++ it('parses rgb(), which is what keyword tokens like `white` resolve to', () => {+ expect(cssColorToHex('rgb(255, 255, 255)')).toBe('#ffffff');+ expect(cssColorToHex('rgba(17, 17, 17, 1)')).toBe('#111111');+ });++ it('accepts space-separated rgb', () => {+ expect(cssColorToHex('rgb(0 128 255)')).toBe('#0080ff');+ });++ it('passes hex through, expanding shorthand', () => {+ expect(cssColorToHex('#AABBCC')).toBe('#aabbcc');+ expect(cssColorToHex('#abc')).toBe('#aabbcc');+ });++ it('returns null for anything it does not understand, rather than guessing', () => {+ expect(cssColorToHex('color-mix(in srgb, red, blue)')).toBeNull();+ expect(cssColorToHex('')).toBeNull();+ expect(cssColorToHex('transparent')).toBeNull();+ });+});++describe('mattermostThemeFromTokens', () => {+ const tokens = {+ background: '#111111',+ backgroundElevated: '#222222',+ backgroundSecondary: '#191919',+ foreground: '#eeeeee',+ foregroundMuted: '#b4b4b4',+ border: '#3a3a3a',+ accent: '#51a085',+ accentStrong: '#66d4a7',+ buttonBg: '#1d3a2e',+ buttonColor: '#bbeed6',+ destructive: '#e5484d',+ warning: '#f5a524',+ success: '#30a46c',+ };++ it('marks the theme custom, or Mattermost ignores the colours', () => {+ expect(mattermostThemeFromTokens(tokens, 'dark').type).toBe('custom');+ });++ it('drives the channel surface from the app background', () => {+ const theme = mattermostThemeFromTokens(tokens, 'dark');+ expect(theme.centerChannelBg).toBe('#111111');+ expect(theme.centerChannelColor).toBe('#eeeeee');+ });++ it('picks a code theme per mode, since that key is a name not a colour', () => {+ expect(mattermostThemeFromTokens(tokens, 'dark').codeTheme).toBe('monokai');+ expect(mattermostThemeFromTokens(tokens, 'light').codeTheme).toBe('github');+ });++ it('emits only strings, which is all the preferences API accepts', () => {+ const theme = mattermostThemeFromTokens(tokens, 'dark');+ for (const value of Object.values(theme)) expect(typeof value).toBe('string');+ });+});diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/mattermost-theme.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/mattermost-theme.tsnew file mode 100644index 000000000..4cb3d8020--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/mattermost-theme.ts@@ -0,0 +1,161 @@+/**+ * Build a Mattermost theme from switchdash's own design tokens, so the embedded+ * room view matches the app instead of sitting in it as a bright rectangle.+ *+ * Mattermost accepts a fully custom theme as a per-user preference, which is+ * better than overriding its stylesheet from the guest preload: it themes+ * itself, so hovers, menus, code blocks and states we never enumerated stay+ * coherent rather than half-converted.+ */++/** The subset of Mattermost theme keys that matter once the chrome is hidden. */+export type MattermostTheme = Record<string, string>;++/** sRGB transfer function, and its inverse. */+function gammaExpand(c: number): number {+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+}++function gammaEncode(c: number): number {+ return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;+}++/**+ * Linear Display-P3 to linear sRGB (D65, no chromatic adaptation needed since+ * both use the same white point).+ *+ * Each row sums to 1, so achromatic colours are unchanged — which is why+ * switchdash's greys convert to the same hex either way, and only the accent+ * colours actually move.+ */+const P3_TO_SRGB = [+ [1.2249401762805, -0.2249401762805, 0.0],+ [-0.0420569547775, 1.0420569547775, 0.0],+ [-0.0196376254397, -0.0786361771772, 1.0982738026169],+] as const;++function clamp01(n: number): number {+ return n < 0 ? 0 : n > 1 ? 1 : n;+}++function toHexPair(unit: number): string {+ return Math.round(clamp01(unit) * 255)+ .toString(16)+ .padStart(2, '0');+}++/**+ * Convert a Display-P3 triple (0–1 components) to an sRGB hex string.+ *+ * P3 is the wider gamut, so saturated colours can land outside sRGB and are+ * clipped per channel. That is a visible but unavoidable approximation on an+ * sRGB surface, and it only affects the accent colours.+ */+export function displayP3ToHex(r: number, g: number, b: number): string {+ const linear = [gammaExpand(r), gammaExpand(g), gammaExpand(b)];+ const out = P3_TO_SRGB.map((row) =>+ gammaEncode(clamp01(row[0] * linear[0] + row[1] * linear[1] + row[2] * linear[2]))+ );+ return `#${out.map(toHexPair).join('')}`;+}++/**+ * Normalise a computed CSS colour to hex.+ *+ * Reading these off a probe element rather than the custom property itself+ * means the browser has already resolved `var()` chains and keywords, so the+ * input is always a concrete colour function — but which one depends on the+ * token (`color(display-p3 …)` for the palette, `rgb(…)` for plain keywords+ * like `white`).+ *+ * Returns null for anything unrecognised, so a caller can drop that key rather+ * than emit a broken theme.+ */+export function cssColorToHex(value: string): string | null {+ const input = value.trim();++ const p3 = /^color\(\s*display-p3\s+([\d.eE+-]+)\s+([\d.eE+-]+)\s+([\d.eE+-]+)/.exec(input);+ if (p3) {+ return displayP3ToHex(Number(p3[1]), Number(p3[2]), Number(p3[3]));+ }++ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(input);+ if (rgb) {+ const parts = [rgb[1], rgb[2], rgb[3]].map((n) => toHexPair(Number(n) / 255));+ return `#${parts.join('')}`;+ }++ if (/^#[0-9a-f]{6}$/i.test(input)) return input.toLowerCase();+ if (/^#[0-9a-f]{3}$/i.test(input)) {+ const [, a, b, c] = input.toLowerCase();+ return `#${a}${a}${b}${b}${c}${c}`;+ }++ return null;+}++/**+ * switchdash tokens the theme is built from, already resolved to hex. Kept as+ * an explicit shape so the renderer's collection and this mapping cannot drift+ * apart silently.+ */+export type ThemeTokens = {+ background: string;+ backgroundElevated: string;+ backgroundSecondary: string;+ foreground: string;+ foregroundMuted: string;+ border: string;+ accent: string;+ accentStrong: string;+ buttonBg: string;+ buttonColor: string;+ destructive: string;+ warning: string;+ success: string;+};++/**+ * Map switchdash tokens onto Mattermost's theme keys.+ *+ * Sidebar keys are still set even though the sidebars are hidden: Mattermost+ * reuses those colours in menus and popovers that remain visible.+ */+export function mattermostThemeFromTokens(+ tokens: ThemeTokens,+ mode: 'light' | 'dark'+): MattermostTheme {+ return {+ type: 'custom',++ sidebarBg: tokens.backgroundSecondary,+ sidebarText: tokens.foreground,+ sidebarUnreadText: tokens.foreground,+ sidebarTextHoverBg: tokens.backgroundElevated,+ sidebarTextActiveBorder: tokens.accent,+ sidebarTextActiveColor: tokens.foreground,+ sidebarHeaderBg: tokens.backgroundSecondary,+ sidebarHeaderTextColor: tokens.foreground,++ centerChannelBg: tokens.background,+ centerChannelColor: tokens.foreground,+ newMessageSeparator: tokens.accent,+ linkColor: tokens.accentStrong,++ buttonBg: tokens.buttonBg,+ buttonColor: tokens.buttonColor,++ mentionBg: tokens.accent,+ mentionColor: tokens.background,+ mentionHighlightBg: tokens.backgroundElevated,+ mentionHighlightLink: tokens.accentStrong,++ errorTextColor: tokens.destructive,+ onlineIndicator: tokens.success,+ awayIndicator: tokens.warning,+ dndIndicator: tokens.destructive,++ // Mattermost only accepts its own named code themes, not colours.+ codeTheme: mode === 'dark' ? 'monokai' : 'github',+ };+}diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/room-embed.test.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/room-embed.test.tsnew file mode 100644index 000000000..e1cb9f9b8--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/room-embed.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';+import { channelUrlFromDeeplink, mattermostPartition } from './room-embed';++describe('channelUrlFromDeeplink', () => {+ it('rewrites a Mattermost deeplink onto the origin we serve it from', () => {+ expect(+ channelUrlFromDeeplink(+ 'mattermost://localhost:8065/switch/channels/town-square',+ 'http://127.0.0.1:51002'+ )+ ).toBe('http://127.0.0.1:51002/switch/channels/town-square');+ });++ it('keeps channel names containing dashes intact', () => {+ // Bridged channels are named after the room, so double dashes are common+ // and were an early suspect for the blank-page bug.+ expect(+ channelUrlFromDeeplink(+ 'mattermost://localhost:8065/switch/channels/mattermost--off-topic',+ 'http://127.0.0.1:8065'+ )+ ).toBe('http://127.0.0.1:8065/switch/channels/mattermost--off-topic');+ });++ it('tolerates a trailing slash on the origin', () => {+ expect(+ channelUrlFromDeeplink('mattermost://host/switch/channels/x', 'http://127.0.0.1:8065/')+ ).toBe('http://127.0.0.1:8065/switch/channels/x');+ });++ it('returns null for a non-Mattermost deeplink rather than mangling it', () => {+ expect(channelUrlFromDeeplink('slack://channel?id=C123', 'http://127.0.0.1:8065')).toBeNull();+ });++ it('returns null when the deeplink names no channel path', () => {+ expect(channelUrlFromDeeplink('mattermost://localhost:8065', 'http://x')).toBeNull();+ });+});++describe('mattermostPartition', () => {+ it('is per-server, so two servers cannot share a session', () => {+ expect(mattermostPartition('a')).not.toBe(mattermostPartition('b'));+ });++ it('is persistent, so the session survives a pane remount', () => {+ expect(mattermostPartition('a').startsWith('persist:')).toBe(true);+ });+});diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/room-embed.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/room-embed.tsnew file mode 100644index 000000000..d4cbe326e--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/room-embed.ts@@ -0,0 +1,60 @@+/**+ * How a room's conversation can be shown inside switchdash.+ *+ * This is the seam CHOO-1674's Phase 0 was run to settle. Mattermost's+ * `/_popout/` route looked like the supported way to embed a single channel,+ * but it turns out to require the desktop app's `window.opener` token+ * handshake — under an Electron user agent the web app ignores our session+ * cookie and bounces to a login page. So we load the ordinary channel URL and+ * hide the surrounding chrome ourselves.+ *+ * Keeping the decision behind one resolved value means swapping strategies+ * later touches this module and nothing else.+ */++export type RoomEmbed =+ /**+ * Render the channel inline in a `<webview>`. `partition` already has the+ * Mattermost session cookie installed; `chromeless` asks the guest preload+ * to hide the global header and sidebars.+ */+ | {+ kind: 'inline';+ url: string;+ partition: string;+ chromeless: true;+ }+ /**+ * The room is bridged somewhere we cannot embed (Slack, or a Mattermost we+ * hold no credentials for). Offer the deeplink instead of pretending.+ */+ | { kind: 'external'; url: string; platform: string }+ /** Nothing to show, with a reason worth surfacing rather than a blank pane. */+ | { kind: 'unavailable'; reason: string };++/**+ * Mattermost deeplinks are `mattermost://<host>/<team>/channels/<name>`, which+ * a webview cannot load. Rewrite one onto the http(s) origin we actually serve+ * Mattermost from, preserving the team/channel path.+ *+ * Returns null rather than throwing: a malformed or non-Mattermost link is a+ * reason to fall back to the deeplink, not to fail the whole room view.+ */+export function channelUrlFromDeeplink(deeplink: string, mattermostOrigin: string): string | null {+ if (!deeplink.startsWith('mattermost://')) return null;+ try {+ // `new URL` on a custom scheme parses the authority as the host, so the+ // team/channel path is preserved verbatim after it.+ const parsed = new URL(deeplink);+ const path = parsed.pathname.replace(/^\/+/, '');+ if (!path) return null;+ return `${mattermostOrigin.replace(/\/+$/, '')}/${path}`;+ } catch {+ return null;+ }+}++/** Per-server partition, so each server's Mattermost session stays isolated. */+export function mattermostPartition(serverId: string): string {+ return `persist:switch-mattermost:${serverId}`;+}diff --git a/deploy/local/docker-compose.yml b/deploy/local/docker-compose.ymlindex ef0403e54..bd6e90021 100644--- a/deploy/local/docker-compose.yml+++ b/deploy/local/docker-compose.yml@@ -64,6 +64,13 @@ services:# leave a "(message deleted)" tombstone. Requires Mattermost >= v10.2.MM_SERVICESETTINGS_ENABLEAPIPOSTDELETION: "true"MM_TEAMSETTINGS_ENABLEOPENSERVER: "true"+ # Both of these exist for switchdash's embedded room view (CHOO-1674):+ # the onboarding checklist opens a modal over a dimmed page inside the+ # pane, and Mattermost only turns known schemes into links, so without+ # the second the `switchdash://session?…` deeplinks agents post render as+ # unclickable text. Kept in step with the standalone compose.+ MM_SERVICESETTINGS_ENABLEONBOARDINGFLOW: "false"+ MM_DISPLAYSETTINGS_CUSTOMURLSCHEMES: switchdashdepends_on:init-db:condition: service_completed_successfullydiff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 18f28434a..d715a9f27 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -45,9 +45,21 @@ services:PGPASSWORD: ${DB_PASSWORD}entrypoint: >sh -c "- until pg_isready -h postgres -U ${DB_USER}; do sleep 1; done- psql -h postgres -U ${DB_USER} -tc \"SELECT 1 FROM pg_database WHERE datname='mattermost'\" | grep -q 1 ||- psql -h postgres -U ${DB_USER} -c 'CREATE DATABASE mattermost;'+ i=0+ until psql -h postgres -U ${DB_USER} -d postgres -c 'SELECT 1' >/dev/null 2>&1; do+ i=$$((i+1))+ if [ $$i -ge 30 ]; then+ echo 'init-db: could not connect to postgres as ${DB_USER} after 30 tries.' >&2+ echo 'Last attempt:' >&2+ psql -h postgres -U ${DB_USER} -d postgres -c 'SELECT 1' >&2+ echo 'A stale pgdata volume keeps the password it was first created with,' >&2+ echo 'so a regenerated DB_PASSWORD will fail here. Recreate the stack to reset it.' >&2+ exit 1+ fi+ sleep 1+ done+ psql -h postgres -U ${DB_USER} -d postgres -tc \"SELECT 1 FROM pg_database WHERE datname='mattermost'\" | grep -q 1 ||+ psql -h postgres -U ${DB_USER} -d postgres -c 'CREATE DATABASE mattermost;'"depends_on:postgres:@@ -68,7 +80,13 @@ services:TUWUNEL_MAX_REQUEST_SIZE: "20000000"mattermost:- image: mattermost/mattermost-team-edition:latest+ # Pinned rather than `latest`: switchdash embeds this Mattermost's web UI+ # and depends on its DOM structure, so an unattended upgrade could break+ # the embedded room view on a `docker compose pull` no one initiated.+ image: mattermost/mattermost-team-edition:11.9.0+ # Mattermost publishes team-edition for amd64 only, so an Apple Silicon or+ # other arm64 host fails the pull outright without this. Runs emulated.+ platform: linux/amd64profiles: ["collab"]ports:- "${SWITCH_BIND_ADDR:-0.0.0.0}:${MATTERMOST_HOST_PORT:-8065}:8065"@@ -79,6 +97,14 @@ services:MM_SQLSETTINGS_DATASOURCE: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/mattermost?sslmode=disableMM_SERVICESETTINGS_SITEURL: http://localhost:${MATTERMOST_HOST_PORT:-8065}MM_SERVICESETTINGS_ENABLELOCALMODE: "true"+ # The first-run onboarding checklist opens a modal over a dimmed page,+ # which in the embedded room view is chrome the user cannot meaningfully+ # act on and has to dismiss per account.+ MM_SERVICESETTINGS_ENABLEONBOARDINGFLOW: "false"+ # Agents post `switchdash://session?…` deeplinks so a human can jump from+ # a message to the session behind it. Mattermost only turns known schemes+ # into links, so without this they render as unclickable plain text.+ MM_DISPLAYSETTINGS_CUSTOMURLSCHEMES: switchdashMM_SERVICESETTINGS_ENABLEBOTACCOUNTCREATION: "true"MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS: "true"# Lets the bridge hard-delete (permanent=true) an agent's transient@@ -86,6 +112,11 @@ services:# leave a "(message deleted)" tombstone. Requires Mattermost >= v10.2.MM_SERVICESETTINGS_ENABLEAPIPOSTDELETION: "true"MM_TEAMSETTINGS_ENABLEOPENSERVER: "true"+ # Neither plugin is usable in a bundled Switch deployment: Copilot has no+ # configured provider and throws a 404 looking up its bot on every page+ # load, and Calls ships a WebRTC service nothing here can reach.+ MM_PLUGINSETTINGS_PLUGINSTATES: |+ {"mattermost-ai":{"Enable":false},"com.mattermost.calls":{"Enable":false}}depends_on:init-db:condition: service_completed_successfullydiff --git a/deploy/remote/helm/switch/templates/mattermost/deployment.yaml b/deploy/remote/helm/switch/templates/mattermost/deployment.yamlindex 4efe30455..983829e3a 100644--- a/deploy/remote/helm/switch/templates/mattermost/deployment.yaml+++ b/deploy/remote/helm/switch/templates/mattermost/deployment.yaml@@ -58,6 +58,13 @@ spec:value: "true"- name: MM_TEAMSETTINGS_ENABLEOPENSERVERvalue: "true"+ # For switchdash's embedded room view (CHOO-1674): suppress the+ # onboarding modal, and linkify the `switchdash://` deeplinks+ # agents post. Kept in step with the standalone compose.+ - name: MM_SERVICESETTINGS_ENABLEONBOARDINGFLOW+ value: "false"+ - name: MM_DISPLAYSETTINGS_CUSTOMURLSCHEMES+ value: "switchdash"- name: MM_TEAMSETTINGS_MAXUSERSPERTEAMvalue: {{ .Values.mattermost.maxUsersPerTeam | default 1000 | quote }}readinessProbe:diff --git a/deploy/shared_resources/setup.py b/deploy/shared_resources/setup.pyindex aaf85f53d..71b029254 100644--- a/deploy/shared_resources/setup.py+++ b/deploy/shared_resources/setup.py@@ -171,7 +171,16 @@ def register_bridge() -> None:bridges = resp.json()for bridge in bridges:if bridge.get("bridge_type") == "mattermost":- print(f"Mattermost bridge already registered: {bridge['bridge_id']}")+ bridge_id = bridge["bridge_id"]+ print(f"Mattermost bridge already registered: {bridge_id}")+ # Adopt the default on an instance that predates it, so an+ # existing deployment gains the invariant on its next setup run+ # rather than only new ones.+ if not any(b.get("is_default") for b in bridges):+ client.post(+ f"/collab/bridges/{bridge_id}/default"+ ).raise_for_status()+ print(f"Set Mattermost bridge as default: {bridge_id}")client.close()return@@ -181,6 +190,11 @@ def register_bridge() -> None:"admin_user": MATTERMOST_ADMIN_USER,"admin_password": MATTERMOST_ADMIN_PASSWORD,"team_name": MATTERMOST_TEAM_NAME,+ # The bundled deployment's single human. Added to every channel this+ # bridge creates so they can read rooms that agents created without+ # naming any users — including private ones, which they could not+ # otherwise join.+ "default_member": MATTERMOST_USER,}if MATTERMOST_PUBLIC_URL:connection_config["public_url"] = MATTERMOST_PUBLIC_URL@@ -190,11 +204,14 @@ def register_bridge() -> None:"bridge_type": "mattermost","display_name": "Mattermost","connection_config": connection_config,+ # The bundled Mattermost is the deployment's own chat, so it is+ # what rooms should bridge to when the caller names nothing.+ "set_as_default": True,},)resp.raise_for_status()data = resp.json()- print(f"Registered Mattermost bridge: {data['bridge_id']}")+ print(f"Registered Mattermost bridge: {data['bridge_id']} (default)")client.close()