AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): close the loop on chat-platform account linking (#13999)
Bentlyf6b98c5a2094
diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py b/autogpt_platform/backend/backend/api/features/platform_linking/registry.pyindex 4879df1adc..c76bba0a60 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/registry.py@@ -19,6 +19,16 @@ from backend.util.settings import Settings# oauth module — which pulls in the Slack SDK + Prisma — into this metadata file)._SLACK_INSTALL_PATH = "/api/copilot-webhooks/slack/install"+# The platform's own word for a server: Slack has workspaces, Telegram+# groups, Teams teams. Declared once so every surface (settings page, link+# confirmation, bot copy) reads natively instead of saying "server".+_SERVER_NOUNS = {+ "DISCORD": "server",+ "SLACK": "workspace",+ "TELEGRAM": "group",+}+_DEFAULT_SERVER_NOUN = "server"+class PlatformMeta(BaseModel):"""Static + runtime metadata for one chat-bot platform."""@@ -28,6 +38,7 @@ class PlatformMeta(BaseModel):platform: str # canonical key, matches PlatformLinkInfo.platform (uppercase)display_name: stricon: str # filename under /public/integrations/<icon>+ server_noun: str # see _SERVER_NOUNSenabled: booladd_bot_url: str | None # null when the platform has no invite URL we can build@@ -42,12 +53,23 @@ def enabled_platforms() -> list[PlatformMeta]:return [platform for platform in all_platforms if platform.enabled]+def server_noun_for(platform: str) -> str:+ """The platform's word for a server, for surfaces that only know its key.++ Reads the map rather than the metas: building those hits config getters+ and URL builders, which is a lot of work for a constant string. Unknown+ platforms get the safe generic wording.+ """+ return _SERVER_NOUNS.get(platform.upper(), _DEFAULT_SERVER_NOUN)++def _discord_meta() -> PlatformMeta:enabled = bool(discord_config.get_bot_token())return PlatformMeta(platform="DISCORD",display_name="Discord",icon="discord.png",+ server_noun=_SERVER_NOUNS["DISCORD"],enabled=enabled,add_bot_url=_discord_invite_url() if enabled else None,)@@ -67,6 +89,7 @@ def _slack_meta() -> PlatformMeta:platform="SLACK",display_name="Slack",icon="slack.png",+ server_noun=_SERVER_NOUNS["SLACK"],enabled=enabled,add_bot_url=_slack_install_url() if (enabled and oauth_ready) else None,)@@ -84,6 +107,7 @@ def _telegram_meta() -> PlatformMeta:platform="TELEGRAM",display_name="Telegram",icon="telegram.png",+ server_noun=_SERVER_NOUNS["TELEGRAM"],enabled=enabled,add_bot_url=(f"https://t.me/{username}?startgroup=true"diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/routes.py b/autogpt_platform/backend/backend/api/features/platform_linking/routes.pyindex b583752e32..82223e3da6 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/routes.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/routes.py@@ -7,15 +7,19 @@ from autogpt_libs import authfrom fastapi import APIRouter, HTTPException, Path, Securityfrom pydantic import BaseModel, Field+from backend.copilot.bot.adapters.slack import oauth as slack_oauth+from backend.copilot.bot.adapters.slack import pending as slack_pendingfrom backend.copilot.bot.adapters.telegram import config as telegram_configfrom backend.copilot.bot.adapters.telegram.login import verify_login-from backend.data.db_accessors import platform_linking_db+from backend.data.db_accessors import bot_installs_db, platform_linking_dbfrom backend.platform_linking.models import (BotPlatformInfo,ConfirmLinkResponse,ConfirmUserLinkResponse,DeleteLinkResponse,LinkTokenInfoResponse,+ PendingInstallInfo,+ Platform,PlatformLinkInfo,PlatformUserLinkInfo,)@@ -81,9 +85,11 @@ def _translate(exc: Exception) -> HTTPException:)async def get_link_token_info_route(token: TokenPath) -> LinkTokenInfoResponse:try:- return await platform_linking_db().get_link_token_info(token)+ info = await platform_linking_db().get_link_token_info(token)except (NotFoundError, LinkTokenExpiredError) as exc:raise _translate(exc) from exc+ info.server_noun = registry.server_noun_for(info.platform)+ return info@router.post(@@ -98,7 +104,7 @@ async def confirm_link_token(body: ConfirmLinkRequest | None = None,) -> ConfirmLinkResponse:try:- return await platform_linking_db().confirm_server_link(+ response = await platform_linking_db().confirm_server_link(token, user_id, verified_platform_user_id=_verified_platform_user(body))except (@@ -109,6 +115,10 @@ async def confirm_link_token(LinkAlreadyExistsError,) as exc:raise _translate(exc) from exc+ response.return_url = await _slack_return_url_for_team(+ response.platform, response.platform_server_id+ )+ return response@router.post(@@ -123,7 +133,7 @@ async def confirm_user_link_token(body: ConfirmLinkRequest | None = None,) -> ConfirmUserLinkResponse:try:- return await platform_linking_db().confirm_user_link(+ response = await platform_linking_db().confirm_user_link(token, user_id, verified_platform_user_id=_verified_platform_user(body))except (@@ -134,6 +144,22 @@ async def confirm_user_link_token(LinkAlreadyExistsError,) as exc:raise _translate(exc) from exc+ # The DM link completes the closed-loop journey: hand back a deep link to+ # the bot chat so the success page can return the user where they came+ # from. Slack's comes from the pending-install marker (retired here);+ # Telegram's is just the bot's public t.me address.+ if response.platform == Platform.SLACK.value:+ marker = await slack_pending.get_pending(user_id)+ if marker and marker.app_id:+ response.return_url = slack_pending.bot_dm_url(+ marker.app_id, marker.team_id+ )+ await slack_pending.clear_pending(user_id)+ elif response.platform == Platform.TELEGRAM.value:+ username = telegram_config.get_bot_username().lstrip("@")+ if username:+ response.return_url = f"https://t.me/{username}"+ return response@router.get(@@ -184,14 +210,59 @@ async def list_bot_platforms(platform=meta.platform,display_name=meta.display_name,icon=meta.icon,- add_bot_url=meta.add_bot_url,+ server_noun=meta.server_noun,+ add_bot_url=_user_bound_install_url(+ meta.platform, meta.add_bot_url, user_id+ ),dm_link=dm_by_platform.get(meta.platform),server_links=servers_by_platform.get(meta.platform, []),+ pending_install=await _pending_install(+ meta.platform, user_id, dm_by_platform.get(meta.platform)+ ),)for meta in registry.enabled_platforms()]+async def _slack_return_url_for_team(platform: str, team_id: str) -> str | None:+ """Deep link into the bot's DM for a just-linked Slack workspace."""+ if platform != Platform.SLACK.value:+ return None+ install = await bot_installs_db().get_bot_install(Platform.SLACK, team_id)+ if install is None or not install.app_id:+ return None+ return slack_pending.bot_dm_url(install.app_id, team_id)+++def _user_bound_install_url(+ platform: str, add_bot_url: str | None, user_id: str+) -> str | None:+ """Attach the signed user param so the install can be attributed back.++ Only Slack's install flow round-trips our backend; other platforms'+ invite URLs go straight to the platform and are returned untouched.+ """+ if platform != Platform.SLACK.value or not add_bot_url:+ return add_bot_url+ return f"{add_bot_url}?u={slack_oauth.make_install_user_param(user_id)}"+++async def _pending_install(+ platform: str, user_id: str, dm_link: PlatformUserLinkInfo | None+) -> PendingInstallInfo | None:+ """The caller's not-yet-linked install, if any. Linking the DM completes+ the journey, so an existing DM link clears the pending state."""+ if platform != Platform.SLACK.value or dm_link is not None:+ return None+ marker = await slack_pending.get_pending(user_id)+ if marker is None or not marker.app_id:+ return None+ return PendingInstallInfo(+ server_name=marker.team_name,+ open_bot_url=slack_pending.bot_dm_url(marker.app_id, marker.team_id),+ )++@router.delete("/links/{link_id}",response_model=DeleteLinkResponse,diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py b/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.pyindex 3315beb4e9..b43611021e 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py@@ -7,7 +7,12 @@ import pytestfrom fastapi import HTTPExceptionfrom backend.api.features.platform_linking.registry import PlatformMeta-from backend.platform_linking.models import PlatformLinkInfo, PlatformUserLinkInfo+from backend.platform_linking.models import (+ ConfirmLinkResponse,+ ConfirmUserLinkResponse,+ PlatformLinkInfo,+ PlatformUserLinkInfo,+)from backend.util.exceptions import (LinkAlreadyExistsError,LinkFlowMismatchError,@@ -25,6 +30,13 @@ def _db_mock(**method_configs):return db+def _installs_mock(install):+ """Mock of the bot-installs accessor, resolving to the given install."""+ installs = MagicMock()+ installs.get_bot_install = AsyncMock(return_value=install)+ return installs++def _discord_meta(*, enabled: bool = True, add_bot_url: str | None = "https://invite") -> PlatformMeta:@@ -32,6 +44,7 @@ def _discord_meta(platform="DISCORD",display_name="Discord",icon="discord.png",+ server_noun="server",enabled=enabled,add_bot_url=add_bot_url,)@@ -498,3 +511,220 @@ class TestTelegramLoginVerification:with pytest.raises(HTTPException) as exc:await confirm_user_link_token("tok", "user-1", body=None)assert exc.value.status_code == 403+++def _slack_meta() -> PlatformMeta:+ return PlatformMeta(+ platform="SLACK",+ display_name="Slack",+ icon="slack.png",+ server_noun="workspace",+ enabled=True,+ add_bot_url="https://b.example/api/copilot-webhooks/slack/install",+ )+++_R = "backend.api.features.platform_linking.routes"+++class TestClosedLoopSlackFlow:+ @pytest.mark.asyncio+ async def test_slack_install_url_is_user_bound(self):+ from backend.api.features.platform_linking.routes import list_bot_platforms++ db = _db_mock(+ list_user_links=AsyncMock(return_value=[]),+ list_server_links=AsyncMock(return_value=[]),+ )+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(+ f"{_R}.registry.enabled_platforms",+ return_value=[_slack_meta()],+ ),+ patch(+ f"{_R}.slack_oauth.make_install_user_param",+ return_value="u1.1.sig",+ ),+ patch(f"{_R}.slack_pending.get_pending", new=AsyncMock(return_value=None)),+ ):+ result = await list_bot_platforms(user_id="u1")++ assert result[0].add_bot_url == (+ "https://b.example/api/copilot-webhooks/slack/install?u=u1.1.sig"+ )+ assert result[0].pending_install is None++ @pytest.mark.asyncio+ async def test_pending_install_surfaces_until_dm_linked(self):+ from backend.api.features.platform_linking.routes import list_bot_platforms+ from backend.copilot.bot.adapters.slack.pending import PendingSlackInstall++ db = _db_mock(+ list_user_links=AsyncMock(return_value=[]),+ list_server_links=AsyncMock(return_value=[]),+ )+ marker = PendingSlackInstall(team_id="T1", team_name="eek", app_id="A1")+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(+ f"{_R}.registry.enabled_platforms",+ return_value=[_slack_meta()],+ ),+ patch(+ f"{_R}.slack_pending.get_pending", new=AsyncMock(return_value=marker)+ ),+ ):+ result = await list_bot_platforms(user_id="u1")++ pending = result[0].pending_install+ assert pending is not None+ assert pending.server_name == "eek"+ assert pending.open_bot_url == "https://slack.com/app_redirect?app=A1&team=T1"++ @pytest.mark.asyncio+ async def test_user_confirm_returns_deep_link_and_clears_marker(self):+ from backend.api.features.platform_linking.routes import confirm_user_link_token+ from backend.copilot.bot.adapters.slack.pending import PendingSlackInstall++ db = _db_mock(+ confirm_user_link=AsyncMock(+ return_value=ConfirmUserLinkResponse(+ success=True, platform="SLACK", platform_user_id="U1"+ )+ )+ )+ marker = PendingSlackInstall(team_id="T1", team_name="eek", app_id="A1")+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(+ f"{_R}.slack_pending.get_pending", new=AsyncMock(return_value=marker)+ ),+ patch(f"{_R}.slack_pending.clear_pending", new=AsyncMock()) as cleared,+ ):+ response = await confirm_user_link_token("tok", "u1", body=None)++ assert response.return_url == "https://slack.com/app_redirect?app=A1&team=T1"+ cleared.assert_awaited_once_with("u1")++ @pytest.mark.asyncio+ async def test_server_confirm_returns_deep_link_from_install(self):+ from backend.api.features.platform_linking.routes import confirm_link_token++ db = _db_mock(+ confirm_server_link=AsyncMock(+ return_value=ConfirmLinkResponse(+ success=True,+ platform="SLACK",+ platform_server_id="T1",+ server_name="eek",+ )+ )+ )+ install = MagicMock()+ install.app_id = "A1"+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(+ f"{_R}.bot_installs_db",+ return_value=_installs_mock(install),+ ),+ ):+ response = await confirm_link_token("tok", "u1", body=None)++ assert response.return_url == "https://slack.com/app_redirect?app=A1&team=T1"++ @pytest.mark.asyncio+ @pytest.mark.parametrize("install", [None, "no-app-id"])+ async def test_server_confirm_has_no_deep_link_without_a_usable_install(+ self, install+ ):+ from backend.api.features.platform_linking.routes import confirm_link_token++ db = _db_mock(+ confirm_server_link=AsyncMock(+ return_value=ConfirmLinkResponse(+ success=True,+ platform="SLACK",+ platform_server_id="T1",+ server_name="eek",+ )+ )+ )+ if install == "no-app-id":+ install = MagicMock()+ install.app_id = None+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(f"{_R}.bot_installs_db", return_value=_installs_mock(install)),+ ):+ response = await confirm_link_token("tok", "u1", body=None)++ # No app id means no deep link we can build; the link itself still stands.+ assert response.success is True+ assert response.return_url is None++ @pytest.mark.asyncio+ async def test_user_confirm_without_a_marker_still_clears_and_returns_no_link(self):+ from backend.api.features.platform_linking.routes import confirm_user_link_token++ db = _db_mock(+ confirm_user_link=AsyncMock(+ return_value=ConfirmUserLinkResponse(+ success=True, platform="SLACK", platform_user_id="U1"+ )+ )+ )+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(f"{_R}.slack_pending.get_pending", new=AsyncMock(return_value=None)),+ patch(f"{_R}.slack_pending.clear_pending", new=AsyncMock()) as cleared,+ ):+ response = await confirm_user_link_token("tok", "u1", body=None)++ assert response.return_url is None+ # Clearing is unconditional: a marker may exist even when this call+ # could not read one back.+ cleared.assert_awaited_once_with("u1")++ @pytest.mark.asyncio+ async def test_non_slack_platforms_are_untouched(self):+ from backend.api.features.platform_linking.routes import list_bot_platforms++ db = _db_mock(+ list_user_links=AsyncMock(return_value=[]),+ list_server_links=AsyncMock(return_value=[]),+ )+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(+ f"{_R}.registry.enabled_platforms",+ return_value=[_discord_meta()],+ ),+ ):+ result = await list_bot_platforms(user_id="u1")++ assert result[0].add_bot_url == "https://invite"+ assert result[0].pending_install is None++ @pytest.mark.asyncio+ async def test_telegram_user_confirm_returns_tme_link(self):+ from backend.api.features.platform_linking.routes import confirm_user_link_token++ db = _db_mock(+ confirm_user_link=AsyncMock(+ return_value=ConfirmUserLinkResponse(+ success=True, platform="TELEGRAM", platform_user_id="tg-1"+ )+ )+ )+ with (+ patch(f"{_R}.platform_linking_db", return_value=db),+ patch(+ f"{_R}.telegram_config.get_bot_username",+ return_value="AutoGPTBot",+ ),+ ):+ response = await confirm_user_link_token("tok", "u1", body=None)++ assert response.return_url == "https://t.me/AutoGPTBot"diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.pyindex fa927f933d..81bba67836 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py@@ -19,6 +19,7 @@ from urllib.parse import urlencodefrom fastapi import FastAPI, Request, Responsefrom fastapi.responses import PlainTextResponse, RedirectResponse+from pydantic import BaseModelfrom slack_sdk.web.async_client import AsyncWebClientfrom backend.data.bot_analytics import record_guild_joined@@ -27,6 +28,7 @@ from backend.platform_linking.models import BotGuildInput, Platformfrom backend.util.settings import Settingsfrom . import config+from .pending import PendingSlackInstall, bot_dm_url, mark_pendinglogger = logging.getLogger(__name__)@@ -52,6 +54,11 @@ _SCOPES = (_STATE_TTL_SECONDS = 600+# ``u`` params are minted when the Bots page renders, and the page may sit+# open a while before the user clicks — allow much longer than the OAuth+# round-trip itself.+_USER_PARAM_TTL_SECONDS = 24 * 3600+def is_enabled() -> bool:"""The install flow needs OAuth app credentials; single-workspace mode@@ -79,13 +86,18 @@ def _redirect_uri() -> str:return f"{base}{CALLBACK_PATH}"-async def _handle_install() -> Response:+async def _handle_install(request: Request) -> Response:+ # ``u`` is an HMAC-signed platform user id minted by the authenticated+ # Bots settings route. Folding it into the OAuth state is what lets the+ # callback attribute the install to an account; the public marketing-page+ # button has no ``u`` and installs anonymously.+ user_id = _verify_user_param(request.query_params.get("u", ""))params = urlencode({"client_id": config.get_client_id(),"scope": ",".join(_SCOPES),"redirect_uri": _redirect_uri(),- "state": _make_state(),+ "state": _make_state(user_id),})return RedirectResponse(@@ -101,7 +113,8 @@ async def _handle_callback(return _done(ok=False, detail=error)state = request.query_params.get("state", "")code = request.query_params.get("code", "")- if not _verify_state(state):+ user_id = _verify_state(state)+ if user_id is None: # "" is a valid anonymous install; None is a bad state.return PlainTextResponse("invalid or expired state", status_code=400)if not code:return PlainTextResponse("missing code", status_code=400)@@ -116,33 +129,100 @@ async def _handle_callback(logger.warning("Slack oauth.v2.access failed: %s", resp.get("error"))return _done(ok=False, detail=resp.get("error") or "exchange failed")- token = resp.get("access_token") or ""team = resp.get("team") or {}- team_id = team.get("id") or ""- if not token or not team_id:+ install = _Install(+ team_id=team.get("id") or "",+ team_name=team.get("name"),+ token=resp.get("access_token") or "",+ app_id=resp.get("app_id") or "",+ bot_user_id=resp.get("bot_user_id"),+ )+ if not install.token or not install.team_id:return _done(ok=False, detail="incomplete install response")+ await _store_install(install)+ if on_installed is not None:+ on_installed(install.team_id)+ if user_id:+ await _mark_install_pending(user_id, install)+ return _post_install_response(install)+++class _Install(BaseModel):+ """The fields we need out of an oauth.v2.access response."""++ team_id: str+ team_name: str | None+ token: str+ app_id: str+ bot_user_id: str | None+++async def _store_install(install: _Install) -> None:await upsert_bot_install(platform=Platform.SLACK,- team_id=team_id,- bot_token=token,- bot_user_id=resp.get("bot_user_id"),- app_id=resp.get("app_id"),- name=team.get("name"),+ team_id=install.team_id,+ bot_token=install.token,+ bot_user_id=install.bot_user_id,+ app_id=install.app_id or None,+ name=install.team_name,)- if on_installed is not None:- on_installed(team_id)try:await record_guild_joined(BotGuildInput(- platform=Platform.SLACK, server_id=team_id, name=team.get("name")+ platform=Platform.SLACK,+ server_id=install.team_id,+ name=install.team_name,))except Exception:logger.warning(- "Failed to record BotGuild for Slack install %s", team_id, exc_info=True+ "Failed to record BotGuild for Slack install %s",+ install.team_id,+ exc_info=True,+ )+++async def _mark_install_pending(user_id: str, install: _Install) -> None:+ """Flag the install as awaiting the user's DM, so the Bots page can say so."""+ await mark_pending(+ user_id,+ PendingSlackInstall(+ team_id=install.team_id,+ team_name=install.team_name,+ app_id=install.app_id or None,+ ),+ )+++def _post_install_response(install: _Install) -> Response:+ if not install.app_id:+ return _done(ok=True, detail=install.team_name or install.team_id)+ # Our own page rather than Slack's: it opens the bot DM via the desktop+ # deep link and then returns the tab to the Bots settings page, so the+ # install doesn't strand a dead browser tab.+ return RedirectResponse(+ _installed_page_url(+ team_id=install.team_id,+ app_id=install.app_id,+ bot_user_id=install.bot_user_id,)- return _done(ok=True, detail=team.get("name") or team_id)+ or bot_dm_url(install.app_id, install.team_id),+ status_code=302,+ )+++def _installed_page_url(+ *, team_id: str, app_id: str, bot_user_id: str | None+) -> str | None:+ """Our post-install handoff page, or None when no frontend is configured."""+ base = (Settings().config.frontend_base_url or "").rstrip("/")+ if not base:+ return None+ params = {"team": team_id, "app": app_id}+ if bot_user_id:+ params["bot"] = bot_user_id+ return f"{base}/link/slack/installed?{urlencode(params)}"def _done(*, ok: bool, detail: str) -> Response:@@ -160,24 +240,58 @@ def _done(*, ok: bool, detail: str) -> Response:return PlainTextResponse(f"Slack install failed: {detail}", status_code=400)-def _make_state() -> str:+def make_install_user_param(user_id: str) -> str:+ """Signed ``u`` value the authenticated Bots route appends to the install+ URL, so the unauthenticated OAuth flow can attribute the install to an+ account without trusting the query string."""+ payload = f"{user_id}.{int(time.time())}"+ return f"{payload}.{_sign(payload)}"+++def _verify_user_param(value: str) -> str:+ """Return the user id from a valid ``u`` param, else "" (anonymous)."""+ try:+ user_id, ts, sig = value.rsplit(".", 2)+ except ValueError:+ return ""+ payload = f"{user_id}.{ts}"+ if not hmac.compare_digest(sig, _sign(payload)):+ return ""+ try:+ if (int(time.time()) - int(ts)) > _USER_PARAM_TTL_SECONDS:+ return ""+ except ValueError:+ return ""+ return user_id+++def _make_state(user_id: str = "") -> str:nonce = secrets.token_urlsafe(24)- payload = f"{nonce}.{int(time.time())}"+ payload = f"{nonce}.{int(time.time())}.{user_id}"return f"{payload}.{_sign(payload)}"-def _verify_state(state: str) -> bool:+def _verify_state(state: str) -> str | None:+ """Return the embedded user id ("" for anonymous installs), or None when+ the state is forged or expired."""try:- nonce, ts, sig = state.rsplit(".", 2)+ payload, sig = state.rsplit(".", 1)except ValueError:- return False- payload = f"{nonce}.{ts}"+ return Noneif not hmac.compare_digest(sig, _sign(payload)):- return False+ return None+ # Split off the two fixed leading fields, not on every dot: the user id+ # is last and a dotted one would otherwise fail attribution.+ try:+ _nonce, ts, user_id = payload.split(".", 2)+ except ValueError:+ return Nonetry:- return (int(time.time()) - int(ts)) <= _STATE_TTL_SECONDS+ if (int(time.time()) - int(ts)) > _STATE_TTL_SECONDS:+ return Noneexcept ValueError:- return False+ return None+ return user_iddef _sign(payload: str) -> str:diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth_test.pyindex b2c0a0af5c..4eb18b86a0 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth_test.py@@ -2,6 +2,7 @@import timefrom unittest.mock import AsyncMock, MagicMock, patch+from urllib.parse import parse_qs, urlparseimport pytest@@ -37,17 +38,43 @@ def test_is_enabled_requires_both_credentials():def test_state_roundtrip_and_tamper_rejected():with patch(f"{_O}.config.get_client_secret", return_value="csecret"):state = oauth._make_state()- assert oauth._verify_state(state) is True- assert oauth._verify_state(state + "x") is False- assert oauth._verify_state("garbage") is False+ assert oauth._verify_state(state) == "" # anonymous install+ assert oauth._verify_state(state + "x") is None+ assert oauth._verify_state("garbage") is None+++def test_state_carries_the_installing_user():+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ state = oauth._make_state("user-123")+ assert oauth._verify_state(state) == "user-123"+++def test_state_survives_a_user_id_containing_dots():+ # The user id is the last field, so parsing has to stop after the two+ # fixed ones or a dotted id silently loses its tail.+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ state = oauth._make_state("user.with.dots")+ assert oauth._verify_state(state) == "user.with.dots"def test_expired_state_rejected():with patch(f"{_O}.config.get_client_secret", return_value="csecret"):old_ts = int(time.time()) - oauth._STATE_TTL_SECONDS - 5- payload = f"nonce.{old_ts}"+ payload = f"nonce.{old_ts}.user-123"stale = f"{payload}.{oauth._sign(payload)}"- assert oauth._verify_state(stale) is False+ assert oauth._verify_state(stale) is None+++def test_user_param_roundtrip_tamper_and_expiry():+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ param = oauth.make_install_user_param("user-123")+ assert oauth._verify_user_param(param) == "user-123"+ assert oauth._verify_user_param(param + "x") == ""+ assert oauth._verify_user_param("") == ""+ old_ts = int(time.time()) - oauth._USER_PARAM_TTL_SECONDS - 5+ payload = f"user-123.{old_ts}"+ stale = f"{payload}.{oauth._sign(payload)}"+ assert oauth._verify_user_param(stale) == ""@pytest.mark.asyncio@@ -62,7 +89,7 @@ async def test_callback_exchanges_code_and_stores_install():patch(f"{_O}.Settings") as settings,):settings.return_value.config.platform_base_url = "https://b.example"- settings.return_value.config.frontend_base_url = ""+ settings.return_value.config.frontend_base_url = "https://f.example"web_client.return_value.oauth_v2_access = AsyncMock(return_value={"ok": True,@@ -82,7 +109,105 @@ async def test_callback_exchanges_code_and_stores_install():assert kwargs["bot_token"] == "xoxb-workspace"assert kwargs["bot_user_id"] == "UBOT"roster.assert_awaited_once()- assert resp.status_code == 200 # plain success page (no frontend URL configured)+ # Success hands off to our own page, which opens the bot DM and returns+ # the tab to settings — never a dead-end browser tab.+ assert resp.status_code == 302+ assert resp.headers["location"] == (+ "https://f.example/link/slack/installed?team=T1&app=A1&bot=UBOT"+ )+++async def test_callback_with_user_state_records_pending_install():+ cid, secret = _creds()+ with (+ cid,+ secret,+ patch(f"{_O}.AsyncWebClient") as web_client,+ patch(f"{_O}.upsert_bot_install", new=AsyncMock()),+ patch(f"{_O}.record_guild_joined", new=AsyncMock()),+ patch(f"{_O}.mark_pending", new=AsyncMock()) as pending,+ patch(f"{_O}.Settings") as settings,+ ):+ settings.return_value.config.frontend_base_url = "https://f.example"+ web_client.return_value.oauth_v2_access = AsyncMock(+ return_value={+ "ok": True,+ "access_token": "xoxb-workspace",+ "team": {"id": "T1", "name": "Acme"},+ "bot_user_id": "UBOT",+ "app_id": "A1",+ }+ )+ resp = await oauth._handle_callback(+ _req({"state": oauth._make_state("user-123"), "code": "auth-code"})+ )+ pending.assert_awaited_once()+ user_id, install = pending.await_args.args+ assert user_id == "user-123"+ assert install.team_id == "T1"+ assert install.team_name == "Acme"+ assert install.app_id == "A1"+ # Pin the target: without Settings patched both branches return 302 and+ # the assertion passes either way.+ assert resp.status_code == 302+ assert resp.headers["location"] == (+ "https://f.example/link/slack/installed?team=T1&app=A1&bot=UBOT"+ )+++async def test_callback_without_app_id_falls_back_to_settings_page():+ cid, secret = _creds()+ with (+ cid,+ secret,+ patch(f"{_O}.AsyncWebClient") as web_client,+ patch(f"{_O}.upsert_bot_install", new=AsyncMock()),+ patch(f"{_O}.record_guild_joined", new=AsyncMock()),+ patch(f"{_O}.Settings") as settings,+ ):+ settings.return_value.config.frontend_base_url = "https://f.example"+ web_client.return_value.oauth_v2_access = AsyncMock(+ return_value={+ "ok": True,+ "access_token": "xoxb-workspace",+ "team": {"id": "T1", "name": "Acme"},+ "bot_user_id": "UBOT",+ }+ )+ resp = await oauth._handle_callback(+ _req({"state": oauth._make_state(), "code": "auth-code"})+ )+ assert resp.status_code == 302+ assert (+ resp.headers["location"] == "https://f.example/settings/bots?slack_installed=1"+ )+++async def test_install_folds_a_verified_user_param_into_the_state():+ cid, secret = _creds()+ with cid, secret, patch(f"{_O}.Settings") as settings:+ settings.return_value.config.platform_base_url = "https://b.example"+ param = oauth.make_install_user_param("user-123")+ resp = await oauth._handle_install(_req({"u": param}))+ location = resp.headers["location"]+ state = parse_qs(urlparse(location).query)["state"][0]+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ assert oauth._verify_state(state) == "user-123"+++async def test_install_ignores_a_forged_user_param():+ cid, secret = _creds()+ with cid, secret, patch(f"{_O}.Settings") as settings:+ settings.return_value.config.platform_base_url = "https://b.example"+ resp = await oauth._handle_install(_req({"u": "user-666.123.badsig"}))+ location = resp.headers["location"]+ state = parse_qs(urlparse(location).query)["state"][0]+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ assert oauth._verify_state(state) == ""@pytest.mark.asyncio@@ -128,3 +253,33 @@ async def test_callback_handles_user_denied():settings.return_value.config.frontend_base_url = ""resp = await oauth._handle_callback(_req({"error": "access_denied"}))assert resp.status_code == 400+++async def test_callback_falls_back_to_slack_redirect_without_a_frontend_url():+ # Self-hosted deployments may run the API without our frontend; the Slack+ # redirect still gets the user to the bot rather than a blank page.+ cid, secret = _creds()+ with (+ cid,+ secret,+ patch(f"{_O}.AsyncWebClient") as web_client,+ patch(f"{_O}.upsert_bot_install", new=AsyncMock()),+ patch(f"{_O}.record_guild_joined", new=AsyncMock()),+ patch(f"{_O}.Settings") as settings,+ ):+ settings.return_value.config.frontend_base_url = ""+ web_client.return_value.oauth_v2_access = AsyncMock(+ return_value={+ "ok": True,+ "access_token": "xoxb-workspace",+ "team": {"id": "T1", "name": "Acme"},+ "bot_user_id": "UBOT",+ "app_id": "A1",+ }+ )+ resp = await oauth._handle_callback(+ _req({"state": oauth._make_state(), "code": "auth-code"})+ )+ assert resp.status_code == 302+ assert resp.headers["location"] == "https://slack.com/app_redirect?app=A1&team=T1"diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/pending.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/pending.pynew file mode 100644index 0000000000..fdaa7b4283--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/pending.py@@ -0,0 +1,66 @@+"""Pending-install markers: who installed a workspace before linking a DM.++The closed-loop install flow needs the Bots settings page to say "you added+the bot to workspace X — one step left" before any account link exists. The+OAuth install is the only moment that ties a platform user to a workspace, so+the callback drops a short-lived marker here and the settings/confirm routes+read it back. Redis with a TTL: this is journey state, not a record.+"""++import json+import logging++from pydantic import BaseModel, ValidationError++from backend.data.redis_client import get_redis_async++logger = logging.getLogger(__name__)++_TTL_SECONDS = 7 * 24 * 3600+++class PendingSlackInstall(BaseModel):+ team_id: str+ team_name: str | None = None+ app_id: str | None = None+++def bot_dm_url(app_id: str, team_id: str) -> str:+ """Deep link that lands the user in the bot's DM in the Slack client."""+ return f"https://slack.com/app_redirect?app={app_id}&team={team_id}"+++def _key(user_id: str) -> str:+ return f"copilot:bot:slack:pending-install:{user_id}"+++async def mark_pending(user_id: str, install: PendingSlackInstall) -> None:+ """Best-effort: losing the marker degrades UX, never the flow."""+ try:+ redis = await get_redis_async()+ await redis.set(_key(user_id), install.model_dump_json(), ex=_TTL_SECONDS)+ except Exception:+ logger.warning("Could not record pending Slack install", exc_info=True)+++async def get_pending(user_id: str) -> PendingSlackInstall | None:+ try:+ redis = await get_redis_async()+ raw = await redis.get(_key(user_id))+ except Exception:+ logger.warning("Could not read pending Slack install", exc_info=True)+ return None+ if not raw:+ return None+ try:+ return PendingSlackInstall.model_validate_json(raw)+ except (ValidationError, json.JSONDecodeError):+ return None+++async def clear_pending(user_id: str) -> None:+ try:+ redis = await get_redis_async()+ await redis.delete(_key(user_id))+ except Exception:+ logger.warning("Could not clear pending Slack install", exc_info=True)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/pending_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/pending_test.pynew file mode 100644index 0000000000..241ce5f477--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/pending_test.py@@ -0,0 +1,105 @@+"""Tests for the Slack pending-install marker."""++from unittest.mock import AsyncMock, patch++import pytest++from backend.copilot.bot.adapters.slack import pending++_P = "backend.copilot.bot.adapters.slack.pending"+++class _FakeRedis:+ """Enough of the Redis surface to round-trip one key."""++ def __init__(self):+ self.store: dict[str, str] = {}++ async def set(self, key: str, value: str, ex: int | None = None):+ self.store[key] = value+ self.ex = ex++ async def get(self, key: str):+ return self.store.get(key)++ async def delete(self, key: str):+ self.store.pop(key, None)+++def _redis(client):+ return patch(f"{_P}.get_redis_async", AsyncMock(return_value=client))+++async def test_marker_round_trips_through_redis():+ client = _FakeRedis()+ install = pending.PendingSlackInstall(team_id="T1", team_name="Acme", app_id="A1")+ with _redis(client):+ await pending.mark_pending("user-1", install)+ loaded = await pending.get_pending("user-1")++ assert loaded == install+ # The key is what the settings route reads back; a rename would silently+ # strand every in-flight install.+ assert "copilot:bot:slack:pending-install:user-1" in client.store+ assert client.ex == pending._TTL_SECONDS+++async def test_marker_is_scoped_to_one_user():+ client = _FakeRedis()+ with _redis(client):+ await pending.mark_pending("user-1", pending.PendingSlackInstall(team_id="T1"))+ assert await pending.get_pending("user-2") is None+++async def test_clearing_removes_the_marker():+ client = _FakeRedis()+ with _redis(client):+ await pending.mark_pending("user-1", pending.PendingSlackInstall(team_id="T1"))+ await pending.clear_pending("user-1")+ assert await pending.get_pending("user-1") is None+++async def test_missing_marker_reads_as_none():+ with _redis(_FakeRedis()):+ assert await pending.get_pending("nobody") is None+++async def test_a_redis_outage_never_breaks_the_install_flow():+ # The marker is a UX hint; Redis being down must not fail the OAuth+ # callback or the settings page.+ down = AsyncMock(side_effect=RuntimeError("redis is down"))+ with patch(f"{_P}.get_redis_async", down):+ await pending.mark_pending("user-1", pending.PendingSlackInstall(team_id="T1"))+ await pending.clear_pending("user-1")+ assert await pending.get_pending("user-1") is None+++async def test_a_read_failure_reads_as_none():+ client = _FakeRedis()+ client.get = AsyncMock(side_effect=RuntimeError("connection reset"))+ with _redis(client):+ assert await pending.get_pending("user-1") is None+++async def test_unreadable_payloads_read_as_none():+ client = _FakeRedis()+ with _redis(client):+ client.store[pending._key("user-1")] = "not json"+ assert await pending.get_pending("user-1") is None+ # Valid JSON, wrong shape: team_id is required.+ client.store[pending._key("user-1")] = '{"team_name": "Acme"}'+ assert await pending.get_pending("user-1") is None+++def test_bot_dm_url_points_at_the_app_in_that_workspace():+ assert (+ pending.bot_dm_url("A1", "T1")+ == "https://slack.com/app_redirect?app=A1&team=T1"+ )diff --git a/autogpt_platform/backend/backend/platform_linking/models.py b/autogpt_platform/backend/backend/platform_linking/models.pyindex c6d383a2f1..2a0f43f717 100644--- a/autogpt_platform/backend/backend/platform_linking/models.py+++ b/autogpt_platform/backend/backend/platform_linking/models.py@@ -184,6 +184,9 @@ class LinkTokenInfoResponse(BaseModel):platform: strlink_type: LinkTypeserver_name: str | None = None+ # See BotPlatformInfo.server_noun — the confirmation page uses it so it+ # never offers to connect "this Slack server".+ server_noun: str = "server"class ResolveResponse(BaseModel):@@ -207,6 +210,17 @@ class PlatformUserLinkInfo(BaseModel):linked_at: datetime+class PendingInstallInfo(BaseModel):+ """The caller added the bot to a server but hasn't linked an account yet.++ ``open_bot_url`` deep-links into the bot's chat on the platform, where the+ next step (the bot's Link Account prompt) is waiting.+ """++ server_name: str | None = None+ open_bot_url: str++class BotPlatformInfo(BaseModel):"""A bot platform enabled on this deployment plus the caller's links to it.@@ -217,9 +231,15 @@ class BotPlatformInfo(BaseModel):platform: strdisplay_name: stricon: str+ # The platform's own word for a server ("workspace", "group", "team"), so+ # the UI never calls a Slack workspace a server.+ server_noun: str = "server"add_bot_url: str | None = Nonedm_link: PlatformUserLinkInfo | None = Noneserver_links: list[PlatformLinkInfo] = Field(default_factory=list)+ # Set while an install by this user awaits its account link (currently+ # only Slack can know this — its install flow round-trips our backend).+ pending_install: PendingInstallInfo | None = Noneclass ConfirmLinkResponse(BaseModel):@@ -228,6 +248,8 @@ class ConfirmLinkResponse(BaseModel):platform: strplatform_server_id: strserver_name: str | None+ # Deep link back to the bot chat the flow started from, when derivable.+ return_url: str | None = Noneclass ConfirmUserLinkResponse(BaseModel):@@ -235,6 +257,7 @@ class ConfirmUserLinkResponse(BaseModel):link_type: LinkType = LinkType.USERplatform: strplatform_user_id: str+ return_url: str | None = Noneclass DeleteLinkResponse(BaseModel):diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsxindex dccb8a6860..757b24a06b 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx@@ -159,6 +159,98 @@ describe("PlatformLinkPage", () => {expect(screen.getByText(/builders guild/i)).toBeDefined();});+ test("offers a way back into the chat client when confirm returns one", async () => {+ setRoute("token-123", "slack");+ server.use(+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({+ platform: "SLACK",+ link_type: LinkType.USER,+ server_name: null,+ }),+ getPostPlatformLinkingConfirmAUserLinkTokenUserMustBeAuthenticatedMockHandler200(+ {+ success: true,+ link_type: LinkType.USER,+ platform: "SLACK",+ platform_user_id: "U1",+ return_url: "https://slack.com/app_redirect?app=A1&team=T1",+ },+ ),+ );++ render(<PlatformLinkPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: /connect my slack dms/i }),+ );++ const back = await screen.findByRole("link", { name: /return to slack/i });+ expect(back.getAttribute("href")).toBe(+ "https://slack.com/app_redirect?app=A1&team=T1",+ );+ expect(screen.getByText(/try it now/i)).toBeDefined();+ });++ test("keeps the DM-only hint off a server link", async () => {+ setRoute("token-123", "slack");+ server.use(+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({+ platform: "SLACK",+ link_type: LinkType.SERVER,+ server_name: "Acme",+ server_noun: "workspace",+ }),+ getPostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticatedMockHandler200(+ {+ success: true,+ link_type: LinkType.SERVER,+ platform: "SLACK",+ platform_server_id: "T1",+ server_name: "Acme",+ return_url: "https://slack.com/app_redirect?app=A1&team=T1",+ },+ ),+ );++ render(<PlatformLinkPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: /connect slack to autogpt/i }),+ );++ await screen.findByRole("link", { name: /return to slack/i });+ // The whole workspace is linked; telling them to DM the bot is a mixed+ // message on this path.+ expect(screen.queryByText(/try it now/i)).toBeNull();+ });++ test("names the server type the way the platform does", async () => {+ setRoute("token-123", "slack");+ server.use(+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({+ platform: "SLACK",+ link_type: LinkType.SERVER,+ server_name: "Acme",+ server_noun: "workspace",+ }),+ getPostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticatedMockHandler200(+ {+ success: true,+ link_type: LinkType.SERVER,+ platform: "SLACK",+ platform_server_id: "T1",+ server_name: "Acme",+ },+ ),+ );++ render(<PlatformLinkPage />);++ fireEvent.click(+ await screen.findByRole("button", { name: /connect slack to autogpt/i }),+ );++ expect(await screen.findByText(/everyone in the workspace/i)).toBeDefined();+ });+test("falls back to a generic title when the server has no name", async () => {server.use(getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsxindex 2eb3189295..6c705633c7 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx@@ -8,6 +8,7 @@ interface Props {linkType: LinkType;platform: string;serverName: string | null;+ serverNoun: string;userEmail: string | null;isLinking: boolean;onLink: () => void;@@ -18,37 +19,39 @@ export function ReadyView({linkType,platform,serverName,+ serverNoun,userEmail,isLinking,onLink,onSwitchAccount,}: Props) {const forUser = isUserLink(linkType);- const title = buildTitle({ forUser, platform, serverName });+ const title = buildTitle({ forUser, platform, serverName, serverNoun });const contextLabel = forUser? `your ${platform} DMs`- : (serverName ?? `this ${platform} server`);+ : (serverName ?? `this ${platform} ${serverNoun}`);return (- <AuthCard title={title}>+ <AuthCard title={title} className="max-w-[38rem] gap-6 p-8"><div className="flex w-full flex-col items-center gap-6">- <div className="w-full rounded-xl bg-muted p-5 text-left">+ <div className="w-full rounded-xl bg-muted px-6 py-5 text-left"><Text variant="body-medium" className="font-medium">What happens when you confirm:</Text>{forUser ? (- <ul className="mt-3 space-y-2 text-sm text-muted-foreground">+ <ul className="mt-4 space-y-2.5 text-sm leading-relaxed text-muted-foreground"><li>{contextLabel} will be linked to your AutoGPT account</li><li>DMs with the bot run as your own private AutoGPT chat</li><li>All usage from those DMs is billed to your account</li></ul>) : (- <ul className="mt-3 space-y-2 text-sm text-muted-foreground">+ <ul className="mt-4 space-y-2.5 text-sm leading-relaxed text-muted-foreground"><li>{contextLabel} will be connected to your AutoGPT account</li>- <li>Anyone in the server can give AutoGPT tasks</li>+ <li>Anyone in the {serverNoun} can give AutoGPT tasks</li><li>- Server conversations are shared — for private 1:1 work, DM the- bot and link your own AutoGPT account+ Conversations in a shared {serverNoun} are visible to everyone+ there — for private 1:1 work, DM the bot and link your own+ AutoGPT account</li><li>Uses the tools and integrations connected to your AutoGPT@@ -58,8 +61,11 @@ export function ReadyView({)}</div>- <div className="w-full rounded-xl border border-border bg-muted p-4">- <Text variant="small" className="text-muted-foreground">+ <div className="w-full rounded-xl border border-border bg-muted px-5 py-4">+ <Text+ variant="small"+ className="leading-relaxed text-muted-foreground"+ >Usage from {contextLabel} is billed to your AutoGPT account. You canunlink at any time in Settings → Bots.</Text>@@ -69,7 +75,7 @@ export function ReadyView({onClick={onLink}loading={isLinking}disabled={isLinking}- className="w-full"+ className="w-full sm:w-auto sm:min-w-[16rem]">{forUser? `Connect my ${platform} DMs`@@ -100,8 +106,9 @@ function buildTitle(args: {forUser: boolean;platform: string;serverName: string | null;+ serverNoun: string;}): string {if (args.forUser) return `Link your ${args.platform} DMs`;if (args.serverName) return `Set up AutoGPT for ${args.serverName}`;- return `Set up AutoGPT for this ${args.platform} server`;+ return `Set up AutoGPT for this ${args.platform} ${args.serverNoun}`;}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsxindex 14efcd43d5..370a0ad6f0 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx@@ -1,27 +1,39 @@+import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { AuthCard } from "@/components/auth/AuthCard";import { LinkType } from "@/app/api/__generated__/models/linkType";import { isUserLink } from "../helpers";-import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";+import {+ ArrowTurnBackwardIcon,+ CheckmarkCircle02Icon,+} from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";interface Props {linkType: LinkType;platform: string;serverName: string | null;+ serverNoun: string;+ returnUrl: string | null;}-export function SuccessView({ linkType, platform, serverName }: Props) {+export function SuccessView({+ linkType,+ platform,+ serverName,+ serverNoun,+ returnUrl,+}: Props) {const forUser = isUserLink(linkType);const label =forUser || !serverName ? `your ${platform} account` : serverName;const detail = forUser? `You can now chat with AutoGPT in your ${platform} DMs.`- : `Everyone in the server can start using AutoGPT right away.`;+ : `Everyone in the ${serverNoun} can start using AutoGPT right away.`;return (- <AuthCard title="AutoGPT is ready!">- <div className="flex w-full flex-col items-center gap-6">+ <AuthCard title="AutoGPT is ready!" className="max-w-[38rem] gap-6 p-8">+ <div className="flex w-full flex-col items-center gap-7"><div className="flex h-16 w-16 items-center justify-center rounded-full bg-green-100"><Iconicon={CheckmarkCircle02Icon}@@ -29,17 +41,47 @@ export function SuccessView({ linkType, platform, serverName }: Props) {className="text-green-600"/></div>- <Text- variant="body-medium"- className="text-center text-muted-foreground"- >- <strong>{label}</strong> is now connected to your AutoGPT account.- <br />- {detail}- </Text>- <Text variant="small" className="text-center text-muted-foreground">- You can close this page and go back to your chat.- </Text>++ <div className="w-full rounded-xl bg-muted px-6 py-5 text-center">+ <Text variant="body-medium" className="text-muted-foreground">+ <strong>{label}</strong> is now connected to your AutoGPT account.+ <br />+ {detail}+ </Text>+ {returnUrl && forUser ? (+ <Text variant="small" className="mt-3 block text-muted-foreground">+ Try it now — “research a topic”, “build me an+ agent”, or “draft a doc”.+ </Text>+ ) : null}+ </div>++ <div className="flex w-full flex-col items-stretch gap-3 sm:flex-row sm:justify-center sm:gap-4">+ {returnUrl ? (+ <Button+ as="NextLink"+ href={returnUrl}+ size="small"+ leftIcon={<Icon icon={ArrowTurnBackwardIcon} size={16} />}+ >+ Return to {platform}+ </Button>+ ) : null}+ <Button+ as="NextLink"+ href="/settings/bots"+ variant="outline"+ size="small"+ >+ Manage bots+ </Button>+ </div>++ {returnUrl ? null : (+ <Text variant="small" className="text-center text-muted-foreground">+ You can close this page and go back to your chat.+ </Text>+ )}</div></AuthCard>);diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/page.tsxindex 0333ab58b9..cdde7dc002 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/page.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/page.tsx@@ -26,6 +26,7 @@ export default function PlatformLinkPage() {linkType={page.viewData.linkType}platform={page.viewData.platform}serverName={page.viewData.serverName}+ serverNoun={page.viewData.serverNoun}userEmail={page.userEmail}isLinking={false}onLink={page.handleLink}@@ -38,6 +39,7 @@ export default function PlatformLinkPage() {linkType={page.viewData.linkType}platform={page.viewData.platform}serverName={page.viewData.serverName}+ serverNoun={page.viewData.serverNoun}userEmail={page.userEmail}isLinkingonLink={page.handleLink}@@ -50,6 +52,8 @@ export default function PlatformLinkPage() {linkType={page.successData.linkType}platform={page.successData.platform}serverName={page.successData.serverName}+ serverNoun={page.successData.serverNoun}+ returnUrl={page.successData.returnUrl}/>)}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.tsindex e939dc5aaf..fde9957086 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts@@ -28,6 +28,7 @@ interface ViewData {linkType: LinkType;platform: string;serverName: string | null;+ serverNoun: string;}export function usePlatformLinkingPage() {@@ -97,6 +98,7 @@ export function usePlatformLinkingPage() {successData: buildSuccessData({confirmResponse,fallbackPlatform: platformFromUrl,+ serverNoun: info?.server_noun ?? "server",}),errorMessage: buildErrorMessage({hasToken: Boolean(token),@@ -131,7 +133,12 @@ function resolveStatus(args: {function buildViewData(args: {info:- | { link_type: LinkType; platform: string; server_name?: string | null }+ | {+ link_type: LinkType;+ platform: string;+ server_name?: string | null;+ server_noun?: string;+ }| undefined;platformFromUrl: string;}): ViewData | null {@@ -141,13 +148,15 @@ function buildViewData(args: {platform:getPlatformDisplayName(args.info.platform) || args.platformFromUrl,serverName: args.info.server_name ?? null,+ serverNoun: args.info.server_noun ?? "server",};}function buildSuccessData(args: {confirmResponse: ConfirmLinkResponse | ConfirmUserLinkResponse | undefined;fallbackPlatform: string;-}): (ViewData & { platform: string }) | null {+ serverNoun: string;+}): (ViewData & { platform: string; returnUrl: string | null }) | null {if (!args.confirmResponse) return null;const serverName ="server_name" in args.confirmResponse@@ -159,6 +168,9 @@ function buildSuccessData(args: {getPlatformDisplayName(args.confirmResponse.platform) ||args.fallbackPlatform,serverName,+ // From the token info — the confirm response carries no noun.+ serverNoun: args.serverNoun,+ returnUrl: args.confirmResponse.return_url ?? null,};}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/__tests__/page.test.tsxnew file mode 100644index 0000000000..450e952cf1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/__tests__/page.test.tsx@@ -0,0 +1,81 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++import { fireEvent, render, screen } from "@/tests/integrations/test-utils";+import SlackInstalledPage from "../page";++const mockUseSearchParams = vi.hoisted(() => vi.fn());+const mockReplace = vi.hoisted(() => vi.fn());++vi.mock("next/navigation", () => ({+ usePathname: () => "/link/slack/installed",+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+ replace: mockReplace,+ }),+ useSearchParams: mockUseSearchParams,+}));++function setParams(params: Record<string, string>) {+ mockUseSearchParams.mockReturnValue(new URLSearchParams(params));+}++beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers({ shouldAdvanceTime: true });+ setParams({ team: "T1", app: "A1", bot: "UBOT" });+ Object.defineProperty(window, "location", {+ configurable: true,+ value: { href: "http://localhost/link/slack/installed" },+ });+});++afterEach(() => {+ vi.useRealTimers();+});++describe("SlackInstalledPage", () => {+ test("opens the bot DM and then returns to the bots settings page", () => {+ render(<SlackInstalledPage />);++ expect(window.location.href).toBe("slack://user?team=T1&id=UBOT");+ expect(mockReplace).not.toHaveBeenCalled();++ vi.advanceTimersByTime(2000);++ expect(mockReplace).toHaveBeenCalledWith("/settings/bots");+ });++ test("still returns to settings when Slack gave us no bot user", () => {+ setParams({ team: "T1", app: "A1" });++ render(<SlackInstalledPage />);++ // No deep link to follow, so the page must not strand the user here.+ expect(window.location.href).toBe("http://localhost/link/slack/installed");+ vi.advanceTimersByTime(2000);+ expect(mockReplace).toHaveBeenCalledWith("/settings/bots");+ });++ test("offers a browser fallback for people without the Slack app", () => {+ render(<SlackInstalledPage />);++ expect(+ screen+ .getByRole("link", { name: /open slack in browser/i })+ .getAttribute("href"),+ ).toBe("https://slack.com/app_redirect?app=A1&team=T1");+ });++ test("retries the deep link when the user asks", () => {+ render(<SlackInstalledPage />);+ window.location.href = "http://localhost/link/slack/installed";++ fireEvent.click(screen.getByRole("button", { name: /^open slack$/i }));++ expect(window.location.href).toBe("slack://user?team=T1&id=UBOT");+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/page.tsxnew file mode 100644index 0000000000..e752396711--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/page.tsx@@ -0,0 +1,47 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { AuthCard } from "@/components/auth/AuthCard";+import { useSlackInstalledHandoff } from "./useSlackInstalledHandoff";++export default function SlackInstalledPage() {+ const { openSlackHref, openSlack } = useSlackInstalledHandoff();++ return (+ <div className="flex h-full min-h-[85vh] flex-col items-center justify-center py-10">+ <AuthCard title="Slack connected" className="max-w-[38rem] gap-6 p-8">+ <div className="flex w-full flex-col items-center gap-7">+ <div className="w-full rounded-xl bg-muted px-6 py-5 text-center">+ {/* The page navigates on its own, so announce it rather than+ letting a screen reader land somewhere unexplained. */}+ <Text+ variant="body-medium"+ className="text-muted-foreground"+ role="status"+ aria-live="polite"+ >+ Opening Slack so you can finish linking your account.+ <br />+ You'll be taken back to your bot settings in a moment.+ </Text>+ </div>++ <div className="flex w-full flex-col items-stretch gap-3 sm:flex-row sm:justify-center sm:gap-4">+ <Button size="small" onClick={openSlack}>+ Open Slack+ </Button>+ <Button+ as="NextLink"+ href={openSlackHref}+ variant="outline"+ size="small"+ >+ Open Slack in browser+ </Button>+ </div>+ </div>+ </AuthCard>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/useSlackInstalledHandoff.ts b/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/useSlackInstalledHandoff.tsnew file mode 100644index 0000000000..cd2cb6fcd3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/slack/installed/useSlackInstalledHandoff.ts@@ -0,0 +1,38 @@+import { useRouter, useSearchParams } from "next/navigation";+import { useEffect } from "react";++// Long enough for the browser to hand the deep link to the Slack app, short+// enough that nobody sits looking at a handoff screen.+const RETURN_DELAY_MS = 1200;++export function useSlackInstalledHandoff() {+ const router = useRouter();+ const searchParams = useSearchParams();+ const team = searchParams.get("team") ?? "";+ const app = searchParams.get("app") ?? "";+ const bot = searchParams.get("bot") ?? "";++ // The desktop scheme opens the bot DM without navigating this tab, so we+ // stay in control and can send the user back to their settings. The https+ // form is the fallback for anyone without the Slack app.+ const deepLink = bot+ ? `slack://user?team=${encodeURIComponent(team)}&id=${encodeURIComponent(bot)}`+ : "";+ const openSlackHref = `https://slack.com/app_redirect?app=${encodeURIComponent(app)}&team=${encodeURIComponent(team)}`;++ function openSlack() {+ if (deepLink) window.location.href = deepLink;+ else window.open(openSlackHref, "_blank", "noopener,noreferrer");+ }++ useEffect(() => {+ if (deepLink) window.location.href = deepLink;+ const timer = window.setTimeout(+ () => router.replace("/settings/bots"),+ RETURN_DELAY_MS,+ );+ return () => window.clearTimeout(timer);+ }, [deepLink, router]);++ return { openSlackHref, openSlack };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsxindex e905a1dec6..7a76863d34 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx@@ -95,6 +95,78 @@ describe("SettingsBotsPage", () => {);});+ test("takes over the card with a finish-in-Slack prompt while an install is pending", async () => {+ server.use(+ getListBotPlatformsMockHandler([+ slackPlatform({+ add_bot_url:+ "https://backend.example/api/copilot-webhooks/slack/install",+ pending_install: {+ server_name: "Acme",+ open_bot_url: "https://slack.com/app_redirect?app=A1&team=T1",+ },+ }),+ ]),+ );++ render(<SettingsBotsPage />);++ expect(await screen.findByText(/pending — finish in slack/i)).toBeDefined();+ const open = screen.getByRole("link", { name: /open autogpt in slack/i });+ expect(open.getAttribute("href")).toBe(+ "https://slack.com/app_redirect?app=A1&team=T1",+ );+ // Alongside, not instead of: a pending marker lasts up to 7 days and must+ // not lock someone out of installing to a second workspace.+ expect(+ screen.getByRole("link", { name: /add bot to slack/i }),+ ).toBeDefined();+ });++ test("refetches when the user comes back to the tab", async () => {+ let calls = 0;+ server.use(+ getListBotPlatformsMockHandler(() => {+ calls += 1;+ return [slackPlatform()];+ }),+ );++ render(<SettingsBotsPage />);+ await screen.findByRole("heading", { name: /slack/i });+ const afterMount = calls;++ fireEvent(window, new Event("focus"));+ await waitFor(() => expect(calls).toBeGreaterThan(afterMount));++ // Hidden tabs are not a return: the install round-trip ends with the user+ // looking at this page, not at a background one.+ const settled = calls;+ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ value: "hidden",+ });+ fireEvent(document, new Event("visibilitychange"));+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(calls).toBe(settled);+ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ value: "visible",+ });+ });++ test("names Slack's server type a workspace", async () => {+ server.use(+ getListBotPlatformsMockHandler([+ slackPlatform({ server_noun: "workspace" }),+ ]),+ );++ render(<SettingsBotsPage />);++ expect(await screen.findByText(/linked workspaces/i)).toBeDefined();+ });+test("shows the 'no bots enabled' empty state when no platforms are configured", async () => {server.use(getListBotPlatformsMockHandler([]));@@ -145,7 +217,7 @@ describe("SettingsBotsPage", () => {).toBeDefined();});- test("shows a 'Bot not in server' indicator when the server name is missing", async () => {+ test("flags a link whose name we don't have, without claiming the bot is gone", async () => {server.use(getListBotPlatformsMockHandler([discordPlatform({@@ -166,7 +238,10 @@ describe("SettingsBotsPage", () => {render(<SettingsBotsPage />);expect(await screen.findByText("1126875755960336515")).toBeDefined();- expect(screen.getByText(/bot not in server/i)).toBeDefined();+ // A missing name means exactly that — it is not evidence the bot was+ // removed, so the row must not say so.+ expect(screen.getByText(/name unavailable/i)).toBeDefined();+ expect(screen.queryByText(/not in server/i)).toBeNull();});test("clicking unlink on a linked server fires the API and the row is gone after refetch", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsxindex aabf8be671..a418d9477d 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsx@@ -1,6 +1,7 @@"use client";import Image from "next/image";+import { Badge } from "@/components/atoms/Badge/Badge";import { Button } from "@/components/atoms/Button/Button";import { Card } from "@/components/atoms/Card/Card";import { Text } from "@/components/atoms/Text/Text";@@ -9,7 +10,7 @@ import type { BotPlatformInfo } from "@/app/api/__generated__/models/botPlatformimport { BotCardDmTile } from "./BotCardDmTile";import { BotCardServerList } from "./BotCardServerList";import { useBotCard } from "./useBotCard";-import { PlusSignIcon } from "@hugeicons/core-free-icons";+import { ArrowUpRight01Icon, PlusSignIcon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";type Props = {@@ -19,6 +20,9 @@ type Props = {export function BotCard({ platform }: Props) {const { isPending, unlinkServerLink, unlinkDmLink } = useBotCard();const serverLinks = platform.server_links ?? [];+ const pendingInstall = platform.pending_install ?? null;+ // Optional in the generated client (it has a server-side default).+ const serverNoun = platform.server_noun ?? "server";return (<Card className="flex flex-col gap-5 p-5">@@ -34,20 +38,43 @@ export function BotCard({ platform }: Props) {<Text variant="large-medium" as="h2" className="text-textBlack">{platform.display_name}</Text>+ {pendingInstall ? (+ <Badge variant="info" size="small">+ Pending — finish in {platform.display_name}+ </Badge>+ ) : null}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {pendingInstall ? (+ <Button+ as="NextLink"+ href={pendingInstall.open_bot_url}+ target="_blank"+ rel="noopener noreferrer"+ variant="primary"+ size="small"+ rightIcon={<Icon icon={ArrowUpRight01Icon} size={16} />}+ >+ Open AutoGPT in {platform.display_name}+ </Button>+ ) : null}+ {/* Kept alongside the pending action, not replaced by it: adding the+ bot to a second {serverNoun} is a normal thing to want while the+ first install is still waiting on its DM. */}+ {platform.add_bot_url ? (+ // Same tab on purpose: the install round-trip ends by returning here,+ // so a new tab would just strand the user on a dead page.+ <Button+ as="NextLink"+ href={platform.add_bot_url}+ variant={pendingInstall ? "outline" : "primary"}+ size="small"+ leftIcon={<Icon icon={PlusSignIcon} size={16} />}+ >+ Add bot to {platform.display_name}+ </Button>+ ) : null}</div>- {platform.add_bot_url ? (- <Button- as="NextLink"- href={platform.add_bot_url}- target="_blank"- rel="noopener noreferrer"- variant="primary"- size="small"- leftIcon={<Icon icon={PlusSignIcon} size={16} />}- >- Add bot to {platform.display_name}- </Button>- ) : null}</header><section className="flex flex-col gap-2">@@ -60,7 +87,9 @@ export function BotCard({ platform }: Props) {</Text><BotCardDmTileplatformName={platform.display_name}+ serverNoun={serverNoun}dmLink={platform.dm_link ?? null}+ pendingServerName={pendingInstall?.server_name ?? null}isPending={isPending}onUnlink={unlinkDmLink}/>@@ -72,10 +101,11 @@ export function BotCard({ platform }: Props) {as="span"className="uppercase tracking-wide text-zinc-500">- Linked servers+ Linked {serverNoun}s</Text><BotCardServerListplatformName={platform.display_name}+ serverNoun={serverNoun}serverLinks={serverLinks}isPending={isPending}onUnlink={unlinkServerLink}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardDmTile.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardDmTile.tsxindex bacff50a19..cbc514621f 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardDmTile.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardDmTile.tsx@@ -10,23 +10,31 @@ import { Icon } from "@/components/atoms/Icon/Icon";type Props = {platformName: string;+ serverNoun: string;dmLink: PlatformUserLinkInfo | null;+ pendingServerName?: string | null;isPending: (linkId: string) => boolean;onUnlink: (linkId: string) => void;};export function BotCardDmTile({platformName,+ serverNoun,dmLink,+ pendingServerName,isPending,onUnlink,}: Props) {const title = dmLink? (dmLink.platform_username ?? `User ${dmLink.platform_user_id}`)- : `DM the bot on ${platformName} to link`;+ : pendingServerName+ ? `${capitalize(serverNoun)} “${pendingServerName}” connected — one step left`+ : `DM the bot on ${platformName} to link`;const subtitle = dmLink? "Your DM channel is linked to this account."- : "Send the bot a direct message to start the link flow.";+ : pendingServerName+ ? `DM the bot in ${platformName} and tap Link Account to connect your DMs.`+ : "Send the bot a direct message to start the link flow.";return (<div className="flex items-center justify-between gap-3 rounded-large border border-zinc-200 px-4 py-3">@@ -64,3 +72,7 @@ export function BotCardDmTile({</div>);}++function capitalize(value: string) {+ return value.charAt(0).toUpperCase() + value.slice(1);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsxindex 55eb86df76..cfeceb28b1 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx@@ -15,6 +15,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";type Props = {platformName: string;+ serverNoun: string;serverLinks: PlatformLinkInfo[];isPending: (linkId: string) => boolean;onUnlink: (linkId: string) => void;@@ -22,6 +23,7 @@ type Props = {export function BotCardServerList({platformName,+ serverNoun,serverLinks,isPending,onUnlink,@@ -30,8 +32,8 @@ export function BotCardServerList({return (<div className="rounded-large border border-dashed border-zinc-200 px-4 py-3"><Text variant="small" as="span" className="text-zinc-500">- No servers linked yet. Use "Add bot to {platformName}" to- invite the bot — already added it? Run <code>/setup</code> there to+ No {serverNoun}s linked yet. Use "Add bot to {platformName}"{" "}+ to invite the bot — already added it? Run <code>/setup</code> there tofinish connecting.</Text></div>@@ -45,6 +47,7 @@ export function BotCardServerList({key={link.id}link={link}platformName={platformName}+ serverNoun={serverNoun}isPending={isPending(link.id)}onUnlink={() => onUnlink(link.id)}/>@@ -56,6 +59,7 @@ export function BotCardServerList({type RowProps = {link: PlatformLinkInfo;platformName: string;+ serverNoun: string;isPending: boolean;onUnlink: () => void;};@@ -63,6 +67,7 @@ type RowProps = {function BotCardServerRow({link,platformName,+ serverNoun,isPending,onUnlink,}: RowProps) {@@ -89,13 +94,12 @@ function BotCardServerRow({<Tooltip><TooltipTrigger asChild><span className="inline-flex items-center gap-1 text-xs text-amber-600">- <Icon icon={AlertCircleIcon} size={14} /> Bot not in server+ <Icon icon={AlertCircleIcon} size={14} /> Name unavailable</span></TooltipTrigger><TooltipContent>- {platformName} can't see this server, so we can't- resolve its name. Re-invite the bot, or unlink to remove this- row.+ {platformName} didn't give us a name for this {serverNoun}.+ It stays linked and usable; unlink to remove this row.</TooltipContent></Tooltip>) : (diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/useBotsList.ts b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/useBotsList.tsindex 19e6eaeea0..d7b38c0328 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/useBotsList.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/useBotsList.ts@@ -1,11 +1,35 @@import { useListBotPlatforms } from "@/app/api/__generated__/endpoints/platform-linking/platform-linking";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useEffect } from "react";export function useBotsList() {const { data, isLoading, isSuccess, isError, error, refetch } =useListBotPlatforms({- query: { retry: false },+ query: {+ retry: false,+ // Links are made outside the app, so the global 60s staleTime would+ // serve cache to someone returning from exactly that round-trip.+ staleTime: 0,+ // The listeners below cover coming back; this would double it up.+ refetchOnWindowFocus: false,+ refetchOnMount: "always",+ },});++ // Both events are needed: tab switches fire visibilitychange, while+ // alt-tabbing back from the desktop app fires focus on a still-visible tab.+ useEffect(() => {+ function refetchIfVisible() {+ if (document.visibilityState === "visible") refetch();+ }++ window.addEventListener("focus", refetchIfVisible);+ document.addEventListener("visibilitychange", refetchIfVisible);+ return () => {+ window.removeEventListener("focus", refetchIfVisible);+ document.removeEventListener("visibilitychange", refetchIfVisible);+ };+ }, [refetch]);const visibility = useGetFlag(Flag.COPILOT_BOT_PLATFORMS);const allPlatforms = data?.status === 200 ? data.data : [];diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 8e916982c8..ff873f533b 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15264,6 +15264,11 @@"platform": { "type": "string", "title": "Platform" },"display_name": { "type": "string", "title": "Display Name" },"icon": { "type": "string", "title": "Icon" },+ "server_noun": {+ "type": "string",+ "title": "Server Noun",+ "default": "server"+ },"add_bot_url": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Add Bot Url"@@ -15278,6 +15283,12 @@"items": { "$ref": "#/components/schemas/PlatformLinkInfo" },"type": "array","title": "Server Links"+ },+ "pending_install": {+ "anyOf": [+ { "$ref": "#/components/schemas/PendingInstallInfo" },+ { "type": "null" }+ ]}},"type": "object",@@ -15957,6 +15968,10 @@"server_name": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Server Name"+ },+ "return_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Return Url"}},"type": "object",@@ -15976,7 +15991,11 @@"default": "USER"},"platform": { "type": "string", "title": "Platform" },- "platform_user_id": { "type": "string", "title": "Platform User Id" }+ "platform_user_id": { "type": "string", "title": "Platform User Id" },+ "return_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Return Url"+ }},"type": "object","required": ["success", "platform", "platform_user_id"],@@ -20126,6 +20145,11 @@"server_name": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Server Name"+ },+ "server_noun": {+ "type": "string",+ "title": "Server Noun",+ "default": "server"}},"type": "object",@@ -21508,6 +21532,19 @@"title": "PendingHumanReviewModel","description": "Response model for pending human review data.\n\nRepresents a human review request that is awaiting user action.\nContains all necessary information for a user to review and approve\nor reject data from a Human-in-the-Loop block execution.\n\nAttributes:\n id: Unique identifier for the review record\n user_id: ID of the user who must perform the review\n node_exec_id: ID of the node execution that created this review\n node_id: ID of the node definition (for grouping reviews from same node)\n graph_exec_id: ID of the graph execution containing the node\n graph_id: ID of the graph template being executed\n graph_version: Version number of the graph template\n payload: The actual data payload awaiting review\n instructions: Instructions or message for the reviewer\n editable: Whether the reviewer can edit the data\n status: Current review status (WAITING, APPROVED, or REJECTED)\n review_message: Optional message from the reviewer\n created_at: Timestamp when review was created\n updated_at: Timestamp when review was last modified\n reviewed_at: Timestamp when review was completed (if applicable)"},+ "PendingInstallInfo": {+ "properties": {+ "server_name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Server Name"+ },+ "open_bot_url": { "type": "string", "title": "Open Bot Url" }+ },+ "type": "object",+ "required": ["open_bot_url"],+ "title": "PendingInstallInfo",+ "description": "The caller added the bot to a server but hasn't linked an account yet.\n\n``open_bot_url`` deep-links into the bot's chat on the platform, where the\nnext step (the bot's Link Account prompt) is waiting."+ },"PhaseUsage": {"properties": {"phase": {diff --git a/autogpt_platform/frontend/src/components/auth/AuthCard.tsx b/autogpt_platform/frontend/src/components/auth/AuthCard.tsxindex 8c3d013e47..6d41faf7be 100644--- a/autogpt_platform/frontend/src/components/auth/AuthCard.tsx+++ b/autogpt_platform/frontend/src/components/auth/AuthCard.tsx@@ -40,9 +40,14 @@ interface Props {className?: string;}-export function AuthCard({ children, title }: Props) {+export function AuthCard({ children, title, className }: Props) {return (- <Card className="mx-auto flex min-h-[40vh] w-full max-w-[32rem] flex-col items-center justify-center gap-8">+ <Card+ className={cn(+ "mx-auto flex min-h-[40vh] w-full max-w-[32rem] flex-col items-center justify-center gap-8",+ className,+ )}+ ><Text variant="h3" as="h2" className="mb-3">{title}</Text>