Skip to content

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(backend/copilot-bot): enforce subscription paywall + rate limits on bot turns (#13477)

Bently59f6ede8e020
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
index 919a78d2b6..74fef46c27 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
@@ -29,7 +29,9 @@ from backend.platform_linking.models import (
BotGuildInput,
CreateLinkTokenRequest,
CreateUserLinkTokenRequest,
+ EnsureSessionResult,
Platform,
+ TurnDenial,
WorkspaceArtifact,
WorkspaceUploadRequest,
WorkspaceUploadResult,
@@ -63,10 +65,23 @@ class BotStreamError(Exception):
self.error_kind = error_kind
+class ChatTurnDeniedError(Exception):
+ """The turn was refused before running (subscription paywall / rate limit).
+
+ Carries the :class:`TurnDenial` so the handler can show the user-facing
+ message and, when present, a CTA button (e.g. Subscribe / Upgrade).
+ """
+
+ def __init__(self, denial: TurnDenial):
+ super().__init__(denial.message)
+ self.denial = denial
+
+
__all__ = [
"BotBackend",
"BotStreamError",
"ChatSummary",
+ "ChatTurnDeniedError",
"DuplicateChatMessageError",
"LinkAlreadyExistsError",
"LinkTokenResult",
@@ -327,12 +342,14 @@ class BotBackend:
platform_user_id: str,
platform_server_id: str | None,
session_id: str | None,
- ) -> str:
+ ) -> EnsureSessionResult:
"""Resolve (or create) the copilot session for this conversation.
Called before uploading attachments so they land in the session folder
(``/sessions/<id>/``) where AutoPilot reads them — the same way the web
- UI uploads into an already-open session.
+ UI uploads into an already-open session. Carries a ``denial`` instead
+ of a session when the turn gate refuses the user, so the caller can
+ skip the upload entirely.
"""
return await self._client.ensure_chat_session(
platform=Platform(platform.upper()),
@@ -425,6 +442,10 @@ class BotBackend:
file_ids=file_ids or [],
)
)
+ if handle.denial is not None:
+ # Refused before running (paywall / rate limit) — no stream exists
+ # to subscribe to. Surface the denial for the handler to render.
+ raise ChatTurnDeniedError(handle.denial)
if on_session_id:
await on_session_id(handle.session_id)
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
index e85280fcf7..364f566a72 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
@@ -18,6 +18,7 @@ from backend.platform_linking.models import (
LinkTokenResponse,
Platform,
ResolveResponse,
+ TurnDenial,
WorkspaceUploadResult,
)
from backend.util.exceptions import (
@@ -30,6 +31,7 @@ from .adapters.base import InboundAttachment
from .bot_backend import (
BotBackend,
BotStreamError,
+ ChatTurnDeniedError,
_extract_setup_requirements,
_is_corrupted_setup_requirements,
)
@@ -514,3 +516,24 @@ class TestUploadWorkspaceFiles:
)
assert results == []
api._client.upload_workspace_file.assert_not_awaited()
+
+
+class TestStreamChatDenial:
+ @pytest.mark.asyncio
+ async def test_stream_chat_raises_chat_turn_denied_on_denial(self, api: BotBackend):
+ api._client.start_chat_turn = AsyncMock(
+ return_value=ChatTurnHandle(
+ session_id="",
+ turn_id="",
+ user_id="u1",
+ denial=TurnDenial(reason="paywalled", message="subscription required"),
+ )
+ )
+
+ with pytest.raises(ChatTurnDeniedError) as exc_info:
+ async for _ in api.stream_chat(
+ platform="discord", platform_user_id="pu1", message="hi"
+ ):
+ pass
+
+ assert exc_info.value.denial.reason == "paywalled"
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.py
index 126f0985a0..2f10db754b 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py
@@ -17,6 +17,7 @@ from backend.data.sharing.workspace_refs import (
WorkspaceArtifactLink,
extract_artifact_links,
)
+from backend.platform_linking.models import TurnDenial
from backend.util.exceptions import (
DuplicateChatMessageError,
LinkAlreadyExistsError,
@@ -31,7 +32,7 @@ from .adapters.base import (
MessageHistoryEntry,
PlatformAdapter,
)
-from .bot_backend import BotBackend, BotStreamError
+from .bot_backend import BotBackend, BotStreamError, ChatTurnDeniedError
from .config import SESSION_TTL
from .text import format_batch, split_at_boundary
@@ -89,30 +90,65 @@ class MessageHandler:
async def _resolve_session_for_attachments(
self, ctx: MessageContext, target_id: str
- ) -> str | None:
+ ) -> tuple[str | None, TurnDenial | None]:
"""Resolve (or create) the session this message's attachments upload
into, so they land where the turn will read them (``/sessions/<id>/``).
Serialised per target so concurrent attachment messages converge on one
- session instead of splitting the files. Returns None on failure — the
- caller then reports the files as un-attachable rather than uploading
- them somewhere AutoPilot can't see.
+ session instead of splitting the files. Returns ``(session_id, None)``
+ on success, ``(None, denial)`` when the turn gate refused the user
+ (the caller renders the denial and skips the upload + turn), and
+ ``(None, None)`` on failure — the caller then reports the files as
+ un-attachable rather than uploading them somewhere AutoPilot can't see.
"""
async with self._session_lock(target_id):
try:
- session_id = await self._api.ensure_session(
+ result = await self._api.ensure_session(
platform=ctx.platform,
platform_user_id=ctx.user_id,
platform_server_id=ctx.server_id,
session_id=await sessions.get_session(ctx.platform, target_id),
)
- await sessions.set_session(ctx.platform, target_id, session_id)
- return session_id
+ if result.denial is not None:
+ return None, result.denial
+ if result.session_id:
+ await sessions.set_session(
+ ctx.platform, target_id, result.session_id
+ )
+ return result.session_id, None
except Exception:
logger.exception(
"Failed to resolve session for uploads (user %s)", ctx.user_id
)
- return None
+ return None, None
+
+ async def _send_denial(
+ self,
+ ctx: MessageContext,
+ adapter: PlatformAdapter,
+ target_id: str,
+ denial: TurnDenial,
+ ) -> None:
+ """Render a turn denial: message plus CTA button when configured."""
+ logger.info("Turn denied (%s) for target %s", denial.reason, target_id)
+ self._api.track_event(
+ platform=ctx.platform,
+ event_type="turn_denied",
+ server_id=ctx.server_id,
+ channel_type=ctx.channel_type,
+ error_kind=denial.reason,
+ )
+ if denial.button_url and denial.button_label:
+ await adapter.send_link(
+ target_id,
+ denial.message,
+ link_label=denial.button_label,
+ link_url=denial.button_url,
+ )
+ else:
+ await adapter.send_message(
+ target_id, denial.message, mentionable_users=ctx.mentionable_users
+ )
async def handle(self, ctx: MessageContext, adapter: PlatformAdapter) -> None:
if not ctx.text.strip() and not ctx.attachments:
@@ -161,7 +197,15 @@ class MessageHandler:
file_ids: list[str]
upload_problems: list[tuple[str, str]]
if ctx.attachments:
- session_id = await self._resolve_session_for_attachments(ctx, target_id)
+ session_id, denial = await self._resolve_session_for_attachments(
+ ctx, target_id
+ )
+ if denial is not None:
+ # The turn gate refused the user before anything was uploaded —
+ # render the denial and stop; no file is scanned or stored and
+ # no turn runs.
+ await self._send_denial(ctx, adapter, target_id, denial)
+ return
if session_id is None:
# Without a session the files can't be made readable to
# AutoPilot, so report them as failed rather than uploading
@@ -611,6 +655,11 @@ class MessageHandler:
adapter, target_id, post, ctx, active_session_id
):
sent_any_content = True
+ except ChatTurnDeniedError as exc:
+ # Refused before running (paywall / rate limit). Show the message
+ # and, when present, a CTA button (Subscribe / Upgrade).
+ await self._send_denial(ctx, adapter, target_id, exc.denial)
+ return
except DuplicateChatMessageError:
# Another in-flight turn is already processing this exact message —
# stay quiet so the user doesn't get a double response.
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler_test.py b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
index bbccdc3205..a67aea6c92 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
@@ -6,7 +6,12 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from backend.platform_linking.models import WorkspaceArtifact, WorkspaceUploadResult
+from backend.platform_linking.models import (
+ EnsureSessionResult,
+ TurnDenial,
+ WorkspaceArtifact,
+ WorkspaceUploadResult,
+)
from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
from .adapters.base import (
@@ -16,7 +21,7 @@ from .adapters.base import (
MessageHistoryEntry,
ReferencedConversation,
)
-from .bot_backend import LinkTokenResult, ResolveResult
+from .bot_backend import ChatTurnDeniedError, LinkTokenResult, ResolveResult
from .handler import (
MAX_TURN_FILE_IDS,
MessageHandler,
@@ -86,7 +91,9 @@ def _api(*, server_linked: bool = True, user_linked: bool = True) -> MagicMock:
)
api.fetch_workspace_artifact = AsyncMock(return_value=None)
api.upload_workspace_files = AsyncMock(return_value=[])
- api.ensure_session = AsyncMock(return_value="session-ensured")
+ api.ensure_session = AsyncMock(
+ return_value=EnsureSessionResult(session_id="session-ensured")
+ )
async def _empty_stream(*args, **kwargs):
if False:
@@ -1040,6 +1047,36 @@ class TestAttachments:
assert "a.png" in adapter.send_message.await_args_list[0].args[1]
assert captured["file_ids"] == []
+ @pytest.mark.asyncio
+ async def test_denied_user_gets_denial_before_any_upload(self):
+ # The turn gate refuses the user during session resolution — the bot
+ # renders the denial (with CTA button) and stops: no AV scan, no
+ # storage write, no turn.
+ api, captured = self._upload_recording_api([])
+ api.ensure_session = AsyncMock(
+ return_value=EnsureSessionResult(
+ denial=TurnDenial(
+ reason="rate_limited",
+ message="You've reached your daily usage limit.",
+ button_label="Upgrade for higher limits",
+ button_url="https://app.example/settings/billing",
+ )
+ )
+ )
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ await handler.handle(self._dm_ctx("look", [("a.png", "image/png")]), adapter)
+
+ api.upload_workspace_files.assert_not_awaited()
+ adapter.send_link.assert_awaited_once()
+ assert (
+ adapter.send_link.await_args.kwargs["link_label"]
+ == "Upgrade for higher limits"
+ )
+ # No turn ran at all.
+ assert "file_ids" not in captured
+
def test_session_lock_is_stable_per_target(self):
# Concurrent attachment messages on the same target serialise on one
# lock (so they converge on one session); different targets don't block.
@@ -1265,3 +1302,63 @@ class TestAttachments:
assert "file_ids" not in captured
note = adapter.send_message.await_args_list[0].args[1]
assert "bad.exe" in note
+
+
+class TestTurnDenied:
+ @pytest.mark.asyncio
+ async def test_paywalled_turn_sends_subscribe_button(self):
+ api = _api()
+
+ async def denied_stream(*args, **kwargs):
+ raise ChatTurnDeniedError(
+ TurnDenial(
+ reason="paywalled",
+ message="AutoPilot needs an active subscription.",
+ button_label="Subscribe",
+ button_url="https://app.example/settings/billing",
+ )
+ )
+ yield "" # pragma: no cover
+
+ api.stream_chat = denied_stream
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ with patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ adapter.send_link.assert_awaited_once()
+ kwargs = adapter.send_link.await_args.kwargs
+ assert kwargs["link_url"] == "https://app.example/settings/billing"
+ assert kwargs["link_label"] == "Subscribe"
+ adapter.send_message.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_rate_limited_turn_sends_plain_message_when_no_button(self):
+ api = _api()
+ msg = "You've reached your daily usage limit. Resets in 5h 30m."
+
+ async def denied_stream(*args, **kwargs):
+ raise ChatTurnDeniedError(TurnDenial(reason="rate_limited", message=msg))
+ yield "" # pragma: no cover
+
+ api.stream_chat = denied_stream
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ with patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ adapter.send_message.assert_awaited_once()
+ assert msg in adapter.send_message.await_args.args[1]
+ adapter.send_link.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/platform_linking/chat.py b/autogpt_platform/backend/backend/platform_linking/chat.py
index e39748d9e5..e3427682b5 100644
--- a/autogpt_platform/backend/backend/platform_linking/chat.py
+++ b/autogpt_platform/backend/backend/platform_linking/chat.py
@@ -5,6 +5,7 @@ from uuid import uuid4
from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError
from backend.copilot import stream_registry
+from backend.copilot.config import ChatConfig
from backend.copilot.executor.utils import enqueue_copilot_turn
from backend.copilot.model import (
ChatMessage,
@@ -14,16 +15,26 @@ from backend.copilot.model import (
get_chat_session,
get_user_sessions,
)
+from backend.copilot.rate_limit import (
+ RateLimitExceeded,
+ RateLimitUnavailable,
+ check_rate_limit,
+ get_global_rate_limits,
+ is_user_paywalled,
+)
from backend.data.db_accessors import platform_linking_db, workspace_db
from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
+from backend.util.settings import Settings
from backend.util.workspace import WorkspaceManager
from .models import (
BotChatRequest,
ChatSessionSummary,
ChatTurnHandle,
+ EnsureSessionResult,
ListUserChatsResponse,
Platform,
+ TurnDenial,
WorkspaceUploadRequest,
WorkspaceUploadResult,
)
@@ -34,6 +45,100 @@ CHAT_TOOL_CALL_ID = "chat_stream"
CHAT_TOOL_NAME = "chat"
+def _billing_url() -> str | None:
+ """The platform billing page, or None when no frontend URL is configured
+ (Discord rejects relative URLs on link buttons, so callers fall back to a
+ plain-text message in that case)."""
+ base = Settings().config.frontend_base_url
+ return f"{base.rstrip('/')}/settings/billing" if base else None
+
+
+def _unavailable_denial() -> TurnDenial:
+ """The gate couldn't be evaluated (tier lookup or Redis unreachable). Fail
+ closed with a retry nudge rather than letting an unmetered turn through —
+ mirrors the web route's 503-on-lookup-failure behaviour."""
+ return TurnDenial(
+ reason="unavailable",
+ message="AutoPilot is temporarily unavailable — please try again in a moment.",
+ )
+
+
+async def _check_paywall(user_id: str) -> TurnDenial | None:
+ """Subscription paywall check — fail closed on lookup failure."""
+ try:
+ paywalled = await is_user_paywalled(user_id)
+ except Exception:
+ # Tier lookup blip (Supabase / LD). The web maps this to a 503; fail
+ # closed here too so a transient error can't bypass the paywall.
+ logger.warning(
+ "evaluate_turn_gate: paywall lookup failed for ...%s",
+ user_id[-8:],
+ exc_info=True,
+ )
+ return _unavailable_denial()
+ if not paywalled:
+ return None
+ billing = _billing_url()
+ return TurnDenial(
+ reason="paywalled",
+ message=(
+ "AutoPilot needs an active subscription. "
+ "Upgrade your plan to start chatting with it."
+ ),
+ button_label="Subscribe" if billing else None,
+ button_url=billing,
+ )
+
+
+async def _check_usage_limits(user_id: str) -> TurnDenial | None:
+ """Daily/weekly USD-cap check — fail closed on any lookup failure."""
+ cfg = ChatConfig()
+ try:
+ daily, weekly, _tier = await get_global_rate_limits(
+ user_id,
+ cfg.daily_cost_limit_microdollars,
+ cfg.weekly_cost_limit_microdollars,
+ )
+ await check_rate_limit(
+ user_id=user_id,
+ daily_cost_limit=daily,
+ weekly_cost_limit=weekly,
+ )
+ except RateLimitExceeded as exc:
+ # str(exc) already reads e.g. "You've reached your daily usage limit.
+ # Resets in 5h 30m." — exactly the window + countdown we want to show.
+ billing = _billing_url()
+ return TurnDenial(
+ reason="rate_limited",
+ message=str(exc),
+ button_label="Upgrade for higher limits" if billing else None,
+ button_url=billing,
+ )
+ except RateLimitUnavailable:
+ return _unavailable_denial()
+ except Exception:
+ # Same fail-closed treatment as the paywall lookup: an unexpected
+ # error (LD, config, Redis client) must not bypass the USD caps.
+ logger.warning(
+ "evaluate_turn_gate: rate limit check failed for ...%s",
+ user_id[-8:],
+ exc_info=True,
+ )
+ return _unavailable_denial()
+ return None
+
+
+async def evaluate_turn_gate(user_id: str) -> TurnDenial | None:
+ """Apply the same subscription paywall + usage rate limits as the web UI.
+
+ The bot enqueues turns directly into the executor, bypassing the
+ route-level paywall dependency and the dispatcher's rate-limit check, so
+ without this a NO_TIER / over-cap user would get unmetered free usage.
+ Returns a :class:`TurnDenial` to surface, or None when the turn may run.
+ """
+ return await _check_paywall(user_id) or await _check_usage_limits(user_id)
+
+
async def _resolve_owner(
platform: str, platform_server_id: str | None, platform_user_id: str
) -> str:
@@ -147,20 +252,34 @@ async def ensure_chat_session(
platform_user_id: str,
platform_server_id: str | None,
session_id: str | None,
-) -> str:
- """Resolve (or create) the session for a bot conversation, return its ID.
+) -> EnsureSessionResult:
+ """Resolve (or create) the session for a bot conversation.
Called before uploading attachments so they can be written into the
session folder — mirroring the web UI, which uploads into an already-open
session so files land at /sessions/<id>/ where AutoPilot reads them.
+
+ Evaluates the turn gate first: a capped/paywalled user gets the denial
+ back *before* any file is scanned or stored (the caller renders it and
+ skips the upload + turn). ``start_chat_turn`` re-checks the gate as the
+ authoritative enforcement point; this early check exists purely to spare
+ the wasted upload.
"""
owner_user_id = await _resolve_owner(
platform.value, platform_server_id, platform_user_id
)
+ denial = await evaluate_turn_gate(owner_user_id)
+ if denial is not None:
+ logger.info(
+ "Bot session request denied (%s) for user ...%s",
+ denial.reason,
+ owner_user_id[-8:],
+ )
+ return EnsureSessionResult(denial=denial)
session = await _resolve_or_create_session(
owner_user_id, session_id, platform.value.lower()
)
- return session.session_id
+ return EnsureSessionResult(session_id=session.session_id)
async def start_chat_turn(request: BotChatRequest) -> ChatTurnHandle:
@@ -170,6 +289,20 @@ async def start_chat_turn(request: BotChatRequest) -> ChatTurnHandle:
the full stream (Redis Streams, not pub/sub).
"""
owner_user_id = await resolve_chat_owner(request)
+
+ # Gate before touching the session / enqueue so a refused turn neither
+ # persists a message nor runs the LLM.
+ denial = await evaluate_turn_gate(owner_user_id)
+ if denial is not None:
+ logger.info(
+ "Bot chat turn denied (%s) for user ...%s",
+ denial.reason,
+ owner_user_id[-8:],
+ )
+ return ChatTurnHandle(
+ session_id="", turn_id="", user_id=owner_user_id, denial=denial
+ )
+
if request.file_ids and request.session_id:
# Attachment turn: the files were already uploaded into this session
# (ensure_chat_session ran first). It must still exist — silently
diff --git a/autogpt_platform/backend/backend/platform_linking/chat_test.py b/autogpt_platform/backend/backend/platform_linking/chat_test.py
index 958a34cccd..4678a111de 100644
--- a/autogpt_platform/backend/backend/platform_linking/chat_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/chat_test.py
@@ -6,15 +6,17 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError
+from backend.copilot.rate_limit import RateLimitExceeded, RateLimitUnavailable
from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
from .chat import (
ensure_chat_session,
+ evaluate_turn_gate,
list_user_chats,
start_chat_turn,
upload_workspace_file,
)
-from .models import BotChatRequest, Platform, WorkspaceUploadRequest
+from .models import BotChatRequest, Platform, TurnDenial, WorkspaceUploadRequest
def _request(**overrides) -> BotChatRequest:
@@ -28,6 +30,16 @@ def _request(**overrides) -> BotChatRequest:
class TestStartChatTurn:
+ @pytest.fixture(autouse=True)
+ def _allow_turn(self):
+ # The paywall/rate-limit gate is covered in TestEvaluateTurnGate; here
+ # default it to "allow" so these tests don't reach DB/Redis for it.
+ with patch(
+ "backend.platform_linking.chat.evaluate_turn_gate",
+ new=AsyncMock(return_value=None),
+ ):
+ yield
+
@pytest.mark.asyncio
async def test_no_user_link_raises_not_found(self):
db_mock = MagicMock()
@@ -380,6 +392,17 @@ class TestUploadWorkspaceFile:
class TestEnsureChatSession:
+ @pytest.fixture(autouse=True)
+ def _allow_turn(self):
+ # Gate behaviour is covered in TestEvaluateTurnGate and the dedicated
+ # denial test below; default to "allow" so the happy-path tests don't
+ # reach DB/Redis for it.
+ with patch(
+ "backend.platform_linking.chat.evaluate_turn_gate",
+ new=AsyncMock(return_value=None),
+ ):
+ yield
+
@pytest.mark.asyncio
async def test_reuses_valid_cached_session(self):
db = MagicMock()
@@ -394,9 +417,10 @@ class TestEnsureChatSession:
"backend.platform_linking.chat.create_chat_session", new=AsyncMock()
) as mock_create,
):
- sid = await ensure_chat_session(Platform.DISCORD, "pu1", None, "cached")
+ result = await ensure_chat_session(Platform.DISCORD, "pu1", None, "cached")
- assert sid == "cached"
+ assert result.session_id == "cached"
+ assert result.denial is None
mock_create.assert_not_awaited()
@pytest.mark.asyncio
@@ -410,11 +434,35 @@ class TestEnsureChatSession:
new=AsyncMock(return_value=MagicMock(session_id="fresh")),
) as mock_create,
):
- sid = await ensure_chat_session(Platform.DISCORD, "pu1", None, None)
+ result = await ensure_chat_session(Platform.DISCORD, "pu1", None, None)
- assert sid == "fresh"
+ assert result.session_id == "fresh"
assert mock_create.await_args.kwargs["source_platform"] == "discord"
+ @pytest.mark.asyncio
+ async def test_denied_user_gets_denial_and_no_session(self):
+ # A capped/paywalled user is refused BEFORE any session is created —
+ # the caller then skips the file upload entirely (nothing scanned or
+ # stored for a denied user).
+ db = MagicMock()
+ db.find_user_link_owner = AsyncMock(return_value="owner-1")
+ denial = TurnDenial(reason="rate_limited", message="limit reached")
+ with (
+ patch("backend.platform_linking.chat.platform_linking_db", return_value=db),
+ patch(
+ "backend.platform_linking.chat.evaluate_turn_gate",
+ new=AsyncMock(return_value=denial),
+ ),
+ patch(
+ "backend.platform_linking.chat.create_chat_session", new=AsyncMock()
+ ) as mock_create,
+ ):
+ result = await ensure_chat_session(Platform.DISCORD, "pu1", None, None)
+
+ assert result.session_id is None
+ assert result.denial == denial
+ mock_create.assert_not_awaited()
+
@pytest.mark.asyncio
async def test_unlinked_dm_raises_not_found(self):
db = MagicMock()
@@ -424,3 +472,93 @@ class TestEnsureChatSession:
):
with pytest.raises(NotFoundError):
await ensure_chat_session(Platform.DISCORD, "pu1", None, None)
+
+
+class TestEvaluateTurnGate:
+ _PATH = "backend.platform_linking.chat"
+
+ @pytest.mark.asyncio
+ async def test_paywalled_returns_denial_with_button(self):
+ with (
+ patch(f"{self._PATH}.is_user_paywalled", AsyncMock(return_value=True)),
+ patch(
+ f"{self._PATH}._billing_url",
+ return_value="https://app/settings/billing",
+ ),
+ ):
+ denial = await evaluate_turn_gate("user-1")
+
+ assert denial is not None
+ assert denial.reason == "paywalled"
+ assert denial.button_url == "https://app/settings/billing"
+ assert denial.button_label == "Subscribe"
+
+ @pytest.mark.asyncio
+ async def test_rate_limited_returns_window_and_reset_message(self):
+ from datetime import timedelta, timezone
+
+ resets_at = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
+ with (
+ patch(f"{self._PATH}.is_user_paywalled", AsyncMock(return_value=False)),
+ patch(
+ f"{self._PATH}.get_global_rate_limits",
+ AsyncMock(return_value=(100, 500, "BASIC")),
+ ),
+ patch(
+ f"{self._PATH}.check_rate_limit",
+ AsyncMock(side_effect=RateLimitExceeded("daily", resets_at)),
+ ),
+ ):
+ denial = await evaluate_turn_gate("user-1")
+
+ assert denial is not None
+ assert denial.reason == "rate_limited"
+ assert "daily usage limit" in denial.message
+ assert "Resets in" in denial.message
+
+ @pytest.mark.asyncio
+ async def test_rate_unavailable_returns_transient_message_no_button(self):
+ with (
+ patch(f"{self._PATH}.is_user_paywalled", AsyncMock(return_value=False)),
+ patch(
+ f"{self._PATH}.get_global_rate_limits",
+ AsyncMock(return_value=(100, 500, "BASIC")),
+ ),
+ patch(
+ f"{self._PATH}.check_rate_limit",
+ AsyncMock(side_effect=RateLimitUnavailable()),
+ ),
+ ):
+ denial = await evaluate_turn_gate("user-1")
+
+ assert denial is not None
+ assert denial.reason == "unavailable"
+ assert denial.button_url is None
+
+ @pytest.mark.asyncio
+ async def test_paywall_lookup_failure_fails_closed_as_unavailable(self):
+ # A transient tier-lookup error must NOT let the turn through unmetered;
+ # fail closed with a retry message (mirrors the web route's 503).
+ with patch(
+ f"{self._PATH}.is_user_paywalled",
+ AsyncMock(side_effect=RuntimeError("supabase down")),
+ ):
+ denial = await evaluate_turn_gate("user-1")
+
+ assert denial is not None
+ assert denial.reason == "unavailable"
+ assert denial.button_url is None
+
+ @pytest.mark.asyncio
+ async def test_within_limits_returns_none(self):
+ with (
+ patch(f"{self._PATH}.is_user_paywalled", AsyncMock(return_value=False)),
+ patch(
+ f"{self._PATH}.get_global_rate_limits",
+ AsyncMock(return_value=(100, 500, "BASIC")),
+ ),
+ patch(f"{self._PATH}.check_rate_limit", AsyncMock(return_value=None)),
+ ):
+ denial = await evaluate_turn_gate("user-1")
+
+ assert denial is None
diff --git a/autogpt_platform/backend/backend/platform_linking/manager.py b/autogpt_platform/backend/backend/platform_linking/manager.py
index bef93a9a11..0522f74ea6 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager.py
@@ -19,6 +19,7 @@ from .models import (
ChatTurnHandle,
CreateLinkTokenRequest,
CreateUserLinkTokenRequest,
+ EnsureSessionResult,
LinkTokenResponse,
LinkTokenStatusResponse,
ListUserChatsResponse,
@@ -89,7 +90,7 @@ class PlatformLinkingManager(AppService):
platform_user_id: str,
platform_server_id: str | None,
session_id: str | None,
- ) -> str:
+ ) -> EnsureSessionResult:
return await ensure_chat_session(
platform, platform_user_id, platform_server_id, session_id
)
diff --git a/autogpt_platform/backend/backend/platform_linking/models.py b/autogpt_platform/backend/backend/platform_linking/models.py
index 6288ebb24e..521aa67046 100644
--- a/autogpt_platform/backend/backend/platform_linking/models.py
+++ b/autogpt_platform/backend/backend/platform_linking/models.py
@@ -221,13 +221,46 @@ class DeleteLinkResponse(BaseModel):
success: bool
+class TurnDenial(BaseModel):
+ """Why a copilot turn was refused before it ran, with the message (and
+ optional CTA button) the bot should show the user.
+
+ Lets ``start_chat_turn`` enforce the same subscription paywall + usage
+ rate limits the web UI applies, since the bot bypasses both by enqueuing
+ directly into the executor.
+ """
+
+ reason: Literal["paywalled", "rate_limited", "unavailable"]
+ message: str
+ button_label: str | None = None
+ button_url: str | None = None
+
+
+class EnsureSessionResult(BaseModel):
+ """Result of resolving a session ahead of attachment uploads.
+
+ When ``denial`` is set the turn gate refused the user before anything was
+ uploaded — the bot renders the denial and skips both the upload and the
+ turn, so a capped/paywalled user's files are never scanned or stored.
+ """
+
+ session_id: str | None = None
+ denial: TurnDenial | None = None
+
+
class ChatTurnHandle(BaseModel):
- """Subscribe keys for a pending copilot turn."""
+ """Subscribe keys for a pending copilot turn.
+
+ When ``denial`` is set the turn was refused (paywall / rate limit) and
+ nothing was enqueued — the caller surfaces the denial instead of
+ subscribing to a stream.
+ """
session_id: str
turn_id: str
user_id: str
subscribe_from: str = "0-0"
+ denial: TurnDenial | None = None
class ChatSessionSummary(BaseModel):