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(discord): Discord bridge polish — deeplink redirect, room icon, outbound images (CHOO-1588) (#41)
Christian McDermott866c7907737d
diff --git a/.env.example b/.env.exampleindex 2c2fed003..0d0ae7a81 100644--- a/.env.example+++ b/.env.example@@ -46,6 +46,11 @@ GATEWAY_ADMIN_PASSWORD=admin# ── Frontend ─────────────────────────────────────────────────────────────────FRONTEND_BASE_URL=http://localhost:5173+# Public origin of the gateway HTTP API (used to build the switchdash:// deeplink+# HTTP redirect so "Open in SwitchDash" is clickable on Discord and other+# http-only platforms). Leave unset to post the raw switchdash:// deeplink.+# GATEWAY_PUBLIC_URL=http://localhost:8000+# ── Mattermost (local dev) ───────────────────────────────────────────────────MATTERMOST_ADMIN_USER=adminMATTERMOST_ADMIN_PASSWORD=admin1234diff --git a/.github/renovate-security/jira_client.py b/.github/renovate-security/jira_client.pyindex ad32ed890..04b5d58ff 100644--- a/.github/renovate-security/jira_client.py+++ b/.github/renovate-security/jira_client.py@@ -24,7 +24,6 @@ import osimport urllib.errorimport urllib.parseimport urllib.request-from typing import OptionalDEFAULT_BASE = "https://sandboxquantum.atlassian.net"# Vulnerabilities are tracked in the VULNMGMT project. Both search and create@@ -51,7 +50,7 @@ class JiraClient:self._auth = base64.b64encode(f"{email}:{token}".encode()).decode()@classmethod- def from_env(cls) -> Optional["JiraClient"]:+ def from_env(cls) -> JiraClient | None:email = os.environ.get("SBT_MACHINE_USER_EMAIL")token = os.environ.get("SBT_MACHINE_USER_JIRA_TOKEN")# `or DEFAULT_BASE` (not a get default): the workflow sets@@ -63,9 +62,7 @@ class JiraClient:return Nonereturn cls(base, email, token)- def _request(- self, method: str, path: str, body: Optional[dict] = None- ) -> Optional[dict]:+ def _request(self, method: str, path: str, body: dict | None = None) -> dict | None:url = f"{self.base}{path}"data = json.dumps(body).encode() if body is not None else Nonereq = urllib.request.Request(url, data=data, method=method)@@ -114,11 +111,11 @@ class JiraClient:self,summary: str,description: str,- labels: Optional[list[str]] = None,+ labels: list[str] | None = None,project: str = CREATE_PROJECT,issue_type: str = "Task",- epic_key: Optional[str] = None,- ) -> Optional[JiraIssue]:+ epic_key: str | None = None,+ ) -> JiraIssue | None:# REST v3 requires an ADF description.fields = {"project": {"key": project},@@ -141,7 +138,7 @@ class JiraClient:id=str(data.get("id") or ""),)- def resolve_key(self, id_or_key: str) -> Optional[str]:+ def resolve_key(self, id_or_key: str) -> str | None:"""Current key for an issue id/key. After VULNMGMT automation MOVES a createdissue to its BU project, the numeric id still resolves but returns the NEW key(e.g. QNV-7011). Used to stamp the real key into the PR body / close marker."""@@ -152,13 +149,13 @@ class JiraClient:return data.get("key")return None- def myself(self) -> Optional[dict]:+ def myself(self) -> dict | None:"""The account this token authenticates as (email, displayName, accountId) —so permissions can be granted to the RIGHT account."""data = self._request("GET", "/rest/api/3/myself")return data if isinstance(data, dict) else None- def find_account_id(self, query: str) -> Optional[str]:+ def find_account_id(self, query: str) -> str | None:"""Best-effort accountId lookup for a user by email or display name, so'assign to aisim' works from a human-readable identifier. Returns None ifthe account can't be resolved (user search is permission-gated)."""@@ -256,8 +253,8 @@ class JiraClient:def set_assignee(self,key: str,- account_id: Optional[str] = None,- name: Optional[str] = None,+ account_id: str | None = None,+ name: str | None = None,) -> bool:"""Assign an issue (e.g. to the aisim account). Jira Cloud wants anaccountId; Server/DC wants a name/username. Try accountId first, then name.@@ -280,7 +277,7 @@ class JiraClient:)return data.get("transitions", []) if isinstance(data, dict) else []- def close_issue(self, key: str, comment: Optional[str] = None) -> bool:+ def close_issue(self, key: str, comment: str | None = None) -> bool:"""Transition an issue to a Done-category status (optionally commentingfirst). Picks the transition whose target status is in the 'done' category,else one named like Done/Closed/Resolved. Best-effort."""@@ -317,7 +314,7 @@ class JiraClient:)return data is not None- def find_field_id(self, name_substr: str) -> Optional[str]:+ def find_field_id(self, name_substr: str) -> str | None:"""Best-effort: id of the first field whose name contains `name_substr`(case-insensitive), e.g. 'business unit' -> 'customfield_12345'. Lets theBU field be auto-discovered without hardcoding its custom-field id."""@@ -345,7 +342,7 @@ class JiraClient:return Truereturn False- def field_value(self, key: str, field_id: str) -> Optional[str]:+ def field_value(self, key: str, field_id: str) -> str | None:"""Read a field's current value as a plain string (for verify-after-set).Unwraps the single-select ``{"value"/"name": ...}`` shape. Returns None if thefield is unset or unreadable. GETs follow the redirect Jira serves when andiff --git a/.github/renovate-security/renovate_jira.py b/.github/renovate-security/renovate_jira.pyindex 9238baa76..fd873125e 100644--- a/.github/renovate-security/renovate_jira.py+++ b/.github/renovate-security/renovate_jira.py@@ -30,7 +30,6 @@ import osimport sysimport timefrom pathlib import Path-from typing import Optionalimport jira_client@@ -106,7 +105,7 @@ def _read_files_arg(files_arg: str) -> list[str]:def _tracking_section(- created: Optional[jira_client.JiraIssue],+ created: jira_client.JiraIssue | None,linked: list[jira_client.JiraIssue],assigned: bool,) -> str:@@ -248,12 +247,14 @@ def reconcile(args) -> int:# project so we link an existing ticket instead of opening a duplicate.terms = [t for t in [eco_label, Path(project_dir).name] if t]jql = jira_client.build_search_jql(- terms, repo=repo_name, projects=_dedup_projects(client, create_project),+ terms,+ repo=repo_name,+ projects=_dedup_projects(client, create_project),path=project_dir,)linked = client.search(jql) if project_dir else []- created: Optional[jira_client.JiraIssue] = None+ created: jira_client.JiraIssue | None = Noneassigned = Falseif not linked and not args.no_create:issue_type = os.environ.get("JIRA_ISSUE_TYPE") or ""@@ -497,7 +498,7 @@ def close_jira(keys_arg: str) -> int:return 0-def main(argv: Optional[list[str]] = None) -> int:+def main(argv: list[str] | None = None) -> int:ap = argparse.ArgumentParser(description=__doc__)ap.add_argument("--reconcile", action="store_true", help="create/link a ticket for a PR"diff --git a/.github/renovate-security/trivy_scan.py b/.github/renovate-security/trivy_scan.pyindex 691d41043..518ad469b 100644--- a/.github/renovate-security/trivy_scan.py+++ b/.github/renovate-security/trivy_scan.py@@ -36,8 +36,8 @@ import jsonimport reimport subprocess # noqa: S404 - we invoke the trivy CLI with a fixed argv (no shell)import sys+from collections.abc import Callablefrom pathlib import Path-from typing import Callable, Optional# Container image refs we never scan: templated (resolved at build time, not a real# image), the empty "scratch" base, and private registries that need auth (mirrors the@@ -143,7 +143,7 @@ def base_images(text: str, skip_prefixes: tuple[str, ...]) -> list[str]:def images_by_dir(repo_root: Path,skip_prefixes: tuple[str, ...] = _DEFAULT_SKIP_PREFIXES,- only_dirs: Optional[set[str]] = None,+ only_dirs: set[str] | None = None,) -> dict[str, list[str]]:"""Map ``dir -> [base image refs]`` across every Dockerfile. ``dir`` is theDockerfile's parent (repo-relative), matching Renovate's ``packageFileDir`` grouping@@ -167,10 +167,10 @@ def images_by_dir(# --------------------------------------------------------------------------- ## Trivy boundary# --------------------------------------------------------------------------- #-TrivyRunner = Callable[[list[str]], Optional[str]]+TrivyRunner = Callable[[list[str]], str | None]-def _run_trivy(argv: list[str]) -> Optional[str]:+def _run_trivy(argv: list[str]) -> str | None:"""Invoke the trivy CLI with a fixed argv (no shell) and return stdout, or None onfailure. Trivy exits non-zero when it finds vulns with --exit-code set; we never setit here (detection is non-blocking), so a non-zero code is a real error."""@@ -314,7 +314,7 @@ def scan_config(min_severity: str = "high",trivy_bin: str = "trivy",runner: TrivyRunner = _run_trivy,- only_dirs: Optional[set[str]] = None,+ only_dirs: set[str] | None = None,) -> list[Finding]:target = repo_root / tf_subdirif not target.exists():@@ -431,7 +431,7 @@ def _render_body(directory: str, findings: list[Finding], engine: str) -> str:def build_report_groups(- findings: list[Finding], engine: str, scanned_dirs: Optional[list[str]] = None+ findings: list[Finding], engine: str, scanned_dirs: list[str] | None = None) -> list[dict]:"""One report group per directory, for the ticket layer + job summary. When``scanned_dirs`` is given, dirs that were scanned but produced no findings are@@ -511,7 +511,7 @@ def _load_findings_json(path: str) -> list[Finding]:]-def main(argv: Optional[list[str]] = None) -> int:+def main(argv: list[str] | None = None) -> int:ap = argparse.ArgumentParser(description=__doc__)ap.add_argument("--mode", choices=["image", "config"], required=True)ap.add_argument("--repo-root", type=Path, default=None)diff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 1d7de9aba..87cfdb9f3 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -8,6 +8,7 @@ from fastapi.responses import JSONResponsefrom switch_core.bridges.agent.api.handlers import router as api_routerfrom switch_core.bridges.agent.auth import BearerAuthMiddleware+from switch_core.bridges.agent.deeplink import router as deeplink_routerfrom switch_core.bridges.agent.dependencies import init_dependenciesfrom switch_core.bridges.agent.mcp import create_mcp_appfrom switch_core.bridges.agent.protocol.event_queue import EventQueue@@ -120,6 +121,7 @@ def create_agent_bridge_app(return JSONResponse(status_code=422, content={"detail": exc.errors()})app.include_router(api_router, prefix="/agents", tags=["api"])+ app.include_router(deeplink_router, tags=["deeplink"])app.state.config = configdiff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.pyindex 95583bc6d..33f6136bd 100644--- a/core/switch_core/bridges/agent/auth.py+++ b/core/switch_core/bridges/agent/auth.py@@ -27,6 +27,9 @@ PUBLIC_PATH_PREFIXES: tuple[str, ...] = ("/oauth","/collab","/gateway",+ # Public switchdash:// deeplink HTTP redirect — followed by whoever clicks+ # the "Open in SwitchDash" link in an external channel, so no bearer token.+ "/deeplink",)diff --git a/core/switch_core/bridges/agent/deeplink.py b/core/switch_core/bridges/agent/deeplink.pynew file mode 100644index 000000000..48c982c7f--- /dev/null+++ b/core/switch_core/bridges/agent/deeplink.py@@ -0,0 +1,24 @@+from __future__ import annotations++from fastapi import APIRouter, Request+from fastapi.responses import RedirectResponse++from switch_core.deeplinks import gateway_query_to_switchdash++router = APIRouter()++[email protected]("/deeplink/session")+async def redirect_session_deeplink(request: Request) -> RedirectResponse:+ """302-redirect to the `switchdash://session?…` deeplink.++ Platforms that only linkify http(s) (Discord, …) can't render the raw+ custom-scheme deeplink, so the bridge posts this https URL instead and the+ click lands here. The incoming query string is carried across verbatim; the+ scheme and host of the target are fixed constants, so this cannot be coerced+ into an open redirect. Public by design — the link is followed by whoever+ clicks it in the external channel, and it serves no data beyond the redirect+ (its `/deeplink` prefix is in the Bearer middleware's public allowlist).+ """+ target = gateway_query_to_switchdash(request.url.query)+ return RedirectResponse(url=target, status_code=302)diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex 3c18f089b..7c308a2fc 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -66,6 +66,7 @@ from switch_core.db.stores.agent_runtime_state_store import (from switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.deeplinks import switchdash_to_gatewayfrom switch_core.events import (LlmCallReport as MatrixLlmCallReport,)@@ -979,7 +980,20 @@ class ProtocolService:`detail` is a short activity line for the running turn (e.g. "Editingfoo.py"); like `thread_id` it is transient and rides the event only —the bridge surfaces it in place on the live working message.++ The `switchdash://` deeplink is rewritten to a gateway HTTP redirect when+ `GATEWAY_PUBLIC_URL` is configured, so the "Open in SwitchDash" link is+ clickable on platforms that only linkify http(s) (Discord). The rewritten+ link is what gets persisted and emitted, so both the bridged status+ message and the `!status` command surface a clickable link. When unset,+ the raw `switchdash://` deeplink is left untouched (today's behavior)."""+ if deeplink_url is not None and self.config.gateway_public_url:+ deeplink_url = (+ switchdash_to_gateway(deeplink_url, self.config.gateway_public_url)+ or deeplink_url+ )+room = await self.require_room_member(agent_id, room_id)async with self.session_factory() as session:agent = await self.agent_store.get(session, agent_id)diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 1275bf97c..29525bb15 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import ioimport loggingimport refrom collections import OrderedDict@@ -236,6 +237,104 @@ class DiscordAdapter(CollaborationAdapter):)return None+ async def send_attachment(+ self,+ channel_id: str,+ sender_name: str,+ filename: str,+ mimetype: str,+ data: bytes,+ caption: str | None = None,+ thread_root_id: str | None = None,+ ) -> str | None:+ """Relay a file into a Discord channel under the agent's identity.++ Unlike Slack/Mattermost, a Discord webhook post carries both a+ per-message username/avatar override AND a file, so the attachment+ renders under the agent's name and icon exactly like a normal message+ (with the image preview intact — embeds are not suppressed). DM+ ("lobby") channels have no webhook, so the file posts as the bot with+ the agent name inlined, mirroring send_message. Falls back to the base+ text notice on failure so the attachment is never silently dropped.+ """+ try:+ target = await self._get_channel(int(channel_id))+ except Exception:+ logger.exception("Cannot resolve Discord channel %s", channel_id)+ return await super().send_attachment(+ channel_id,+ sender_name,+ filename,+ mimetype,+ data,+ caption,+ thread_root_id,+ )++ body = self.translate_outbound(caption) if caption else ""++ if self._channel_type_of(target) == "lobby":+ content = f"**{sender_name}**: {body}" if body else f"**{sender_name}**"+ try:+ msg = await target.send(+ content, file=discord.File(io.BytesIO(data), filename=filename)+ )+ return f"{msg.channel.id}:{msg.id}"+ except discord.HTTPException:+ logger.exception(+ "Failed to send Discord DM attachment in %s", channel_id+ )+ return await super().send_attachment(+ channel_id,+ sender_name,+ filename,+ mimetype,+ data,+ caption,+ thread_root_id,+ )++ thread: Any = None+ if thread_root_id:+ try:+ thread = await self._ensure_thread(int(channel_id), thread_root_id)+ except Exception:+ logger.exception(+ "Failed to resolve Discord thread for root %s — posting attachment at channel root",+ thread_root_id,+ )++ try:+ webhook = await self._get_webhook(int(channel_id))+ kwargs: dict[str, Any] = {}+ if thread is not None:+ kwargs["thread"] = thread+ sent: Any = await webhook.send(+ content=body,+ username=sender_name,+ avatar_url=self._get_agent_icon(sender_name),+ file=discord.File(io.BytesIO(data), filename=filename),+ wait=True,+ **kwargs,+ )+ return f"{sent.channel.id}:{sent.id}"+ except discord.HTTPException as e:+ logger.error(+ "Failed to send attachment '%s' to Discord channel %s: %s",+ filename,+ channel_id,+ e,+ )+ return await super().send_attachment(+ channel_id,+ sender_name,+ filename,+ mimetype,+ data,+ caption,+ thread_root_id,+ )+async def admin_message(self,channel_id: str,diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 8e118bd0a..59a66e708 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -1,3 +1,5 @@+from urllib.parse import urlsplit+from pydantic import model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict@@ -56,6 +58,15 @@ class SwitchConfig(BaseSettings):frontend_base_url: str | None = None+ # Public origin (scheme + host, no path) of the Switch API — the same host+ # switchdash reports as its `server`, e.g. https://switch-api.<tailnet>.ts.net.+ # Distinct from `frontend_base_url`, which is the operator UI. Powers the+ # `switchdash://` deeplink HTTP redirect (`/deeplink/session`, served on the+ # agent-bridge app) so the "Open in SwitchDash" link is clickable on platforms+ # that only linkify http(s) (Discord, and any future http-only bridge). When+ # unset, the raw `switchdash://` deeplink is posted as-is.+ gateway_public_url: str | None = None+# Upper bound on a single attachment an agent may post to a room (and that# a collaboration bridge will relay out). Uploads over this raise instead# of being truncated or silently dropped.@@ -90,6 +101,21 @@ class SwitchConfig(BaseSettings):)return self+ @model_validator(mode="after")+ def _validate_gateway_public_url(self) -> "SwitchConfig":+ # The deeplink redirect is registered at the gateway root (`/deeplink/+ # session`), so a public URL carrying a path prefix would build links+ # that 404. Reject it at startup rather than fail silently at click time.+ if self.gateway_public_url:+ parts = urlsplit(self.gateway_public_url)+ if not parts.scheme or not parts.netloc or parts.path not in ("", "/"):+ raise ValueError(+ "GATEWAY_PUBLIC_URL must be a scheme + host only "+ "(e.g. https://gateway.example), with no path, "+ f"got {self.gateway_public_url!r}."+ )+ return self+@model_validator(mode="after")def _validate_gateway_oidc(self) -> "SwitchConfig":required = (diff --git a/core/switch_core/deeplinks.py b/core/switch_core/deeplinks.pynew file mode 100644index 000000000..7c45fcd1c--- /dev/null+++ b/core/switch_core/deeplinks.py@@ -0,0 +1,48 @@+from __future__ import annotations++from urllib.parse import urlsplit++# Scheme + host of the switchdash session deeplink switchdash reports with its+# runtime state, e.g. `switchdash://session?server=…&agent=…&room=…&session=…`.+# urlsplit maps the part after `://` and before `?` to `netloc`, so a session+# deeplink is `scheme == "switchdash"` and `netloc == "session"`.+_DEEPLINK_SCHEME = "switchdash"+_DEEPLINK_HOST = "session"++# Gateway path that 302-redirects to the reconstructed `switchdash://` deeplink.+# Kept here so the route and the rewrite agree on a single source of truth.+DEEPLINK_REDIRECT_PATH = "/deeplink/session"+++def switchdash_to_gateway(deeplink_url: str, gateway_public_url: str) -> str | None:+ """Rewrite a `switchdash://session?…` deeplink into a gateway HTTP redirect.++ Platforms like Discord only linkify http(s), so the raw custom-scheme+ deeplink renders as plain text. The gateway serves an HTTP endpoint+ (`DEEPLINK_REDIRECT_PATH`) that 302-redirects to the deeplink; posting that+ https URL makes the "Open in SwitchDash" link clickable everywhere.++ The query string is carried across verbatim (server/agent/room/session and+ any future params). Returns None when `deeplink_url` is not a switchdash+ session deeplink, so callers leave unrecognised links untouched.+ """+ parts = urlsplit(deeplink_url)+ if parts.scheme != _DEEPLINK_SCHEME or parts.netloc != _DEEPLINK_HOST:+ return None+ # Only the query is carried across — switchdash session deeplinks never carry+ # a fragment, so there is nothing to preserve there.+ base = gateway_public_url.rstrip("/")+ query = f"?{parts.query}" if parts.query else ""+ return f"{base}{DEEPLINK_REDIRECT_PATH}{query}"+++def gateway_query_to_switchdash(query: str) -> str:+ """Reconstruct the `switchdash://session?…` deeplink the redirect targets.++ The inverse of `switchdash_to_gateway`: the redirect endpoint hands the+ incoming query string here to build the Location it 302s to. Scheme and host+ are fixed constants, so the endpoint can never be coerced into redirecting to+ an arbitrary target.+ """+ suffix = f"?{query}" if query else ""+ return f"{_DEEPLINK_SCHEME}://{_DEEPLINK_HOST}{suffix}"diff --git a/core/tests/switch_core/bridges/agent/test_deeplink_route.py b/core/tests/switch_core/bridges/agent/test_deeplink_route.pynew file mode 100644index 000000000..4b2d87c7d--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_deeplink_route.py@@ -0,0 +1,68 @@+from __future__ import annotations++from fastapi import FastAPI+from fastapi.testclient import TestClient++from switch_core.bridges.agent.auth import BearerAuthMiddleware, _is_public_path+from switch_core.bridges.agent.deeplink import router+++def _client() -> TestClient:+ app = FastAPI()+ app.include_router(router)+ return TestClient(app, follow_redirects=False)+++def _client_with_auth() -> TestClient:+ """The route behind the real Bearer middleware, as it runs on the+ agent-bridge app — reproducing the no-token click from an external channel."""+ app = FastAPI()+ app.include_router(router)+ app.add_middleware(+ BearerAuthMiddleware,+ agent_store=None, # type: ignore[arg-type]+ api_key_store=None, # type: ignore[arg-type]+ session_factory=None, # type: ignore[arg-type]+ )+ return TestClient(app, follow_redirects=False)+++class TestDeeplinkRedirect:+ def test_302_redirects_to_switchdash_deeplink(self) -> None:+ resp = _client().get(+ "/deeplink/session",+ params={"server": "https://s", "agent": "a", "room": "r", "session": "x"},+ )+ assert resp.status_code == 302+ location = resp.headers["location"]+ assert location.startswith("switchdash://session?")+ assert "room=r" in location+ assert "agent=a" in location++ def test_no_query_redirects_to_bare_deeplink(self) -> None:+ resp = _client().get("/deeplink/session")+ assert resp.status_code == 302+ assert resp.headers["location"] == "switchdash://session"+++class TestDeeplinkIsPublic:+ """The redirect must bypass the agent-bridge Bearer auth — it is clicked+ from an external channel with no token (the 401 CHOO-1588 originally hit)."""++ def test_deeplink_session_path_is_public(self) -> None:+ assert _is_public_path("/deeplink/session") is True++ def test_deeplink_prefix_is_public(self) -> None:+ assert _is_public_path("/deeplink") is True++ def test_unrelated_path_is_not_public(self) -> None:+ assert _is_public_path("/agents/x") is False++ def test_redirect_works_through_bearer_middleware_without_token(self) -> None:+ # The exact CHOO-1588 regression: a no-token click returned 401+ # "Missing or invalid Authorization header" before /deeplink was public.+ resp = _client_with_auth().get(+ "/deeplink/session", params={"server": "https://s", "room": "r"}+ )+ assert resp.status_code == 302+ assert resp.headers["location"].startswith("switchdash://session?")diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.pyindex b286b51f9..b1693585f 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py@@ -525,6 +525,128 @@ def test_send_message_to_dm_falls_back_to_bot_post() -> None:assert ref == f"{dm.id}:501"+# ── Outbound attachments ─────────────────────────────────────────────────────+++def test_send_attachment_posts_via_webhook_with_agent_identity() -> None:+ adapter = _adapter()+ channel = _FakeChannel()+ adapter._client = _FakeClient({CHANNEL_ID: channel})+ webhook = _FakeWebhook()+ adapter._webhooks[CHANNEL_ID] = webhook++ ref = _run(+ adapter.send_attachment(+ str(CHANNEL_ID),+ "my-agent",+ "shot.png",+ "image/png",+ b"PNGDATA",+ caption="look **here**",+ )+ )++ assert len(webhook.sent) == 1+ call = webhook.sent[0]+ assert call["content"] == "look **here**"+ assert call["username"] == "my-agent"+ assert "my-agent" in call["avatar_url"]+ assert isinstance(call["file"], discord.File)+ assert call["file"].filename == "shot.png"+ # Image previews must render, so embeds are NOT suppressed for attachments.+ assert "suppress_embeds" not in call+ assert "thread" not in call+ assert ref == f"{CHANNEL_ID}:901"+++def test_send_attachment_without_caption_sends_empty_content() -> None:+ adapter = _adapter()+ channel = _FakeChannel()+ adapter._client = _FakeClient({CHANNEL_ID: channel})+ webhook = _FakeWebhook()+ adapter._webhooks[CHANNEL_ID] = webhook++ _run(+ adapter.send_attachment(+ str(CHANNEL_ID), "my-agent", "shot.png", "image/png", b"PNGDATA"+ )+ )++ assert webhook.sent[0]["content"] == ""+ assert webhook.sent[0]["file"].filename == "shot.png"+++def test_send_attachment_into_thread() -> None:+ adapter = _adapter()+ channel = _FakeChannel()+ thread = _FakeThread(parent=channel, thread_id=4000)+ adapter._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})+ webhook = _FakeWebhook()+ adapter._webhooks[CHANNEL_ID] = webhook++ ref = _run(+ adapter.send_attachment(+ str(CHANNEL_ID),+ "my-agent",+ "shot.png",+ "image/png",+ b"PNGDATA",+ thread_root_id=f"{CHANNEL_ID}:4000",+ )+ )++ assert webhook.sent[0]["thread"] is thread+ assert ref == "4000:901"+++def test_send_attachment_to_dm_posts_file_as_bot() -> None:+ adapter = _adapter()+ dm = _FakeDMChannel()+ adapter._client = _FakeClient({dm.id: dm})++ ref = _run(+ adapter.send_attachment(+ str(dm.id), "my-agent", "shot.png", "image/png", b"PNGDATA", caption="hi"+ )+ )++ assert dm.sent[0]["content"] == "**my-agent**: hi"+ assert dm.sent[0]["file"].filename == "shot.png"+ assert ref == f"{dm.id}:501"+++def test_send_attachment_falls_back_to_text_note_on_http_error() -> None:+ class _FileRejectingWebhook(_FakeWebhook):+ async def send(self, **kwargs: Any) -> Any:+ if "file" in kwargs:+ raise discord.HTTPException(_FakeResponse(), "upload failed")+ return await super().send(**kwargs)++ adapter = _adapter()+ channel = _FakeChannel()+ adapter._client = _FakeClient({CHANNEL_ID: channel})+ webhook = _FileRejectingWebhook()+ adapter._webhooks[CHANNEL_ID] = webhook++ ref = _run(+ adapter.send_attachment(+ str(CHANNEL_ID),+ "my-agent",+ "shot.png",+ "image/png",+ b"PNGDATA",+ caption="a picture",+ )+ )++ # Base fallback posts a disclosed text note (no file) via send_message.+ text_posts = [c for c in webhook.sent if "file" not in c]+ assert len(text_posts) == 1+ assert "shot.png" in text_posts[0]["content"]+ assert "a picture" in text_posts[0]["content"]+ assert ref == f"{CHANNEL_ID}:901"++def test_admin_message_posts_as_bot_not_webhook() -> None:adapter = _adapter()channel = _FakeChannel()diff --git a/core/tests/switch_core/test_config_gateway_public_url.py b/core/tests/switch_core/test_config_gateway_public_url.pynew file mode 100644index 000000000..5583d568b--- /dev/null+++ b/core/tests/switch_core/test_config_gateway_public_url.py@@ -0,0 +1,45 @@+import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ matrix_server="http://tuwunel:8008",+ matrix_server_name="switch.local",+ matrix_admin_user="admin",+ matrix_admin_password="pw",+ matrix_registration_shared_secret="secret",+ agent_registration_token="token",+ jwt_secret_key="jwt",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++def test_unset_gateway_public_url_is_allowed() -> None:+ assert _config().gateway_public_url is None+++ "url",+ ["https://gateway.example", "https://gateway.example/", "http://localhost:8000"],+)+def test_scheme_and_host_only_url_is_accepted(url: str) -> None:+ assert _config(gateway_public_url=url).gateway_public_url == url+++ "url",+ ["https://gateway.example/api", "gateway.example", "/deeplink", "https://"],+)+def test_url_with_path_or_missing_host_raises(url: str) -> None:+ with pytest.raises(ValueError, match="GATEWAY_PUBLIC_URL"):+ _config(gateway_public_url=url)diff --git a/core/tests/switch_core/test_deeplinks.py b/core/tests/switch_core/test_deeplinks.pynew file mode 100644index 000000000..9721da038--- /dev/null+++ b/core/tests/switch_core/test_deeplinks.py@@ -0,0 +1,53 @@+from __future__ import annotations++from switch_core.deeplinks import (+ DEEPLINK_REDIRECT_PATH,+ gateway_query_to_switchdash,+ switchdash_to_gateway,+)++_DEEPLINK = "switchdash://session?server=https%3A%2F%2Fs&agent=a&room=r&session=x"+++class TestSwitchdashToGateway:+ def test_rewrites_session_deeplink_to_gateway_redirect(self) -> None:+ result = switchdash_to_gateway(_DEEPLINK, "https://gw.example")+ assert result == (+ "https://gw.example/deeplink/session"+ "?server=https%3A%2F%2Fs&agent=a&room=r&session=x"+ )++ def test_strips_trailing_slash_on_base(self) -> None:+ result = switchdash_to_gateway(_DEEPLINK, "https://gw.example/")+ assert result is not None+ assert result.startswith("https://gw.example/deeplink/session?")++ def test_deeplink_without_query_has_no_question_mark(self) -> None:+ result = switchdash_to_gateway("switchdash://session", "https://gw.example")+ assert result == "https://gw.example/deeplink/session"++ def test_non_switchdash_scheme_returns_none(self) -> None:+ assert (+ switchdash_to_gateway("https://elsewhere/x", "https://gw.example") is None+ )++ def test_wrong_host_returns_none(self) -> None:+ assert (+ switchdash_to_gateway("switchdash://other?a=b", "https://gw.example")+ is None+ )+++class TestGatewayQueryToSwitchdash:+ def test_reconstructs_deeplink_from_query(self) -> None:+ query = "server=https%3A%2F%2Fs&agent=a&room=r&session=x"+ assert gateway_query_to_switchdash(query) == f"switchdash://session?{query}"++ def test_empty_query_has_no_question_mark(self) -> None:+ assert gateway_query_to_switchdash("") == "switchdash://session"++ def test_round_trip(self) -> None:+ gateway = switchdash_to_gateway(_DEEPLINK, "https://gw.example")+ assert gateway is not None+ query = gateway.split(DEEPLINK_REDIRECT_PATH + "?", 1)[1]+ assert gateway_query_to_switchdash(query) == _DEEPLINKdiff --git a/dash/apps/switchdash-desktop/src/assets/images/bridges/discord.svg b/dash/apps/switchdash-desktop/src/assets/images/bridges/discord.svgnew file mode 100644index 000000000..ef9e17e5a--- /dev/null+++ b/dash/apps/switchdash-desktop/src/assets/images/bridges/discord.svg@@ -0,0 +1,3 @@+<svg width="127" height="127" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <path fill="#5865F2" d="M20.317 4.3698a19.7913 19.7913 0 0 0-4.8851-1.5152.0741.0741 0 0 0-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 0 0-.0785-.037 19.7363 19.7363 0 0 0-4.8852 1.515.0699.0699 0 0 0-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 0 0 .0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 0 0 .0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 0 0-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 0 1-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 0 1 .0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 0 1 .0785.0095c.1202.099.246.198.3728.2924a.077.077 0 0 1-.0066.1276 12.2986 12.2986 0 0 1-1.873.8914.0766.0766 0 0 0-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 0 0 .0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 0 0 .0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 0 0-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189z"/>+</svg>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsxindex 5b7cdc5bf..1aa974a97 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx@@ -6,6 +6,7 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-serimport { events } from '@renderer/lib/ipc';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';import { sessionDeeplinkChannel } from '@shared/core/switch-rooms/switchRoomEvents';+import { pickDeeplinkTarget } from './session-deeplink-resolve';import { switchRoomsStore as roomConnectionsStore } from './switch-rooms-store';/**@@ -58,9 +59,11 @@ export function SessionDeeplinkListener(): null {void agentsStore.load();return events.on(sessionDeeplinkChannel, ({ agentId, roomId, server, sessionId }) => {void (async () => {- // Prefer the shared session id (resolves on any client); fall back- // to room matching for older links that didn't carry it.- const match = (sessionId ? findSessionById(sessionId) : null) ?? findSessionForRoom(roomId);+ const match = pickDeeplinkTarget(+ sessionId,+ () => findSessionById(sessionId),+ () => findSessionForRoom(roomId)+ );if (!match) {console.warn('[deeplink] no local session for deeplink', {sessionId,@@ -73,6 +76,13 @@ export function SessionDeeplinkListener(): null {// Scope the sidebar to the session's server first; otherwise its location// is filtered out of the server-scoped tree and the reveal has nothing// to expand.+ console.info('[deeplink] navigating to session', {+ linkSessionId: sessionId,+ matchedSessionId: match.sessionId,+ matchedVia: sessionId ? 'session-id' : 'room',+ locationId: match.locationId,+ roomId,+ });if (!agentsStore.loaded) await agentsStore.load();const serverId = agentsStore.serverIdForLocation(match.locationId);if (serverId) await switchServersStore.setActive(serverId);diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-resolve.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-resolve.test.tsnew file mode 100644index 000000000..9ec394eac--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-resolve.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it, vi } from 'vitest';+import { pickDeeplinkTarget } from './session-deeplink-resolve';++type Match = { locationId: string; sessionId: string };++const byId: Match = { locationId: 'loc-by-id', sessionId: 's-1' };+const byRoom: Match = { locationId: 'loc-by-room', sessionId: 's-other' };++describe('pickDeeplinkTarget', () => {+ it('uses the exact session-id match when a session id is present', () => {+ expect(+ pickDeeplinkTarget(+ 's-1',+ () => byId,+ () => byRoom+ )+ ).toBe(byId);+ });++ it('does NOT fall back to a room match when the session id is unresolved', () => {+ // The CHOO-1588 wrong-chat bug: a present-but-unresolved session id must+ // return null, not a different session that merely shares the room.+ expect(+ pickDeeplinkTarget(+ 's-1',+ () => null,+ () => byRoom+ )+ ).toBeNull();+ });++ it('does not even run the room resolver when a session id is present', () => {+ const resolveByRoom = vi.fn(() => byRoom);+ pickDeeplinkTarget('s-1', () => byId, resolveByRoom);+ expect(resolveByRoom).not.toHaveBeenCalled();+ });++ it('falls back to room matching for older links with no session id', () => {+ expect(+ pickDeeplinkTarget(+ '',+ () => byId,+ () => byRoom+ )+ ).toBe(byRoom);+ });+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-resolve.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-resolve.tsnew file mode 100644index 000000000..dba158f1b--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-resolve.ts@@ -0,0 +1,14 @@+/**+ * Choose the session a deeplink targets. A session id resolves the exact+ * session on any client, so when one is present we use ONLY the id match — never+ * a room-based guess, which would open a different session that merely shares the+ * room (the wrong chat, CHOO-1588). Older links that carried no session id fall+ * back to room matching. Resolvers are lazy so the unused one isn't run.+ */+export function pickDeeplinkTarget<T>(+ sessionId: string,+ resolveById: () => T | null,+ resolveByRoom: () => T | null+): T | null {+ return sessionId ? resolveById() : resolveByRoom();+}diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex f836b7922..18f28434a 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -110,6 +110,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/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex 65557ea49..4d0a80f62 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -240,6 +240,10 @@ Include with `nindent 12`.- name: FRONTEND_BASE_URLvalue: {{ .Values.switchCore.frontendBaseUrl | quote }}{{- end }}+{{- if .Values.switchCore.gatewayPublicUrl }}+- name: GATEWAY_PUBLIC_URL+ value: {{ .Values.switchCore.gatewayPublicUrl | quote }}+{{- end }}{{- end }}{{/*diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex f195a0c39..6ae1e461f 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -88,6 +88,11 @@ switchCore:logLevel: INFO# Public base URL the gateway is served on (used for links / OIDC redirects).frontendBaseUrl: ""+ # Public origin (scheme + host, no path) of the gateway HTTP API itself, used+ # to build the switchdash:// deeplink HTTP redirect so the "Open in SwitchDash"+ # link is clickable on Discord and other http-only platforms. Leave empty to+ # post the raw switchdash:// deeplink.+ gatewayPublicUrl: ""# Set the Secure flag on the switch_auth session cookie. True here because the# gateway is served over HTTPS (ALB / Tailscale); keep false only for plain-HTTP# local dev.