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.
fix(copilot): surface structured usage-limit envelope on 429 so BYOSUB reconnect unblocks chat (#14602)
AutoGPTa4a88df60304
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 2670e38fc8..418a75a4ea 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -73,6 +73,7 @@ from backend.copilot.pending_messages import (clear_pending_messages_unsafe,peek_pending_messages,)+from backend.copilot.provider_failure import ProviderFailure, ProviderFailureKindfrom backend.copilot.provider_tiers import (ProviderTiersResponse,describe_provider_tiers,@@ -1870,7 +1871,18 @@ async def stream_chat_post(weekly_cost_limit=weekly_limit,)except RateLimitExceeded as e:- raise HTTPException(status_code=429, detail=str(e)) from e+ # Structured envelope (not a bare string) so the frontend can+ # offer "switch to another connection" (e.g. a connected+ # BYOSUB/Codex credential) instead of only "upgrade your plan" --+ # the platform cap does not apply once the turn is billed to a+ # user-supplied credential instead of platform dollars.+ failure = ProviderFailure(+ kind=ProviderFailureKind.USAGE_LIMIT,+ message=str(e),+ auth_provider="platform",+ resets_at=int(e.resets_at.timestamp()),+ )+ raise HTTPException(status_code=429, detail=failure.as_part()) from eexcept RateLimitUnavailable as e:# Fail-closed on Redis brown-out: the user may already be at or# past their USD cap and we cannot prove otherwise. 503 + a shortdiff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex cad4a2625e..44e22c0090 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -829,7 +829,9 @@ def test_stream_chat_returns_429_on_daily_rate_limit(mocker: pytest_mock.MockerFjson={"message": "hello"},)assert response.status_code == 429- assert "daily" in response.json()["detail"].lower()+ detail = response.json()["detail"]+ assert "daily" in detail["message"].lower()+ assert detail["kind"] == "usage_limit"def test_stream_chat_codex_skips_platform_paywall_and_cost_limit(@@ -902,9 +904,10 @@ def test_stream_chat_returns_429_on_weekly_rate_limit(json={"message": "hello"},)assert response.status_code == 429- detail = response.json()["detail"].lower()- assert "weekly" in detail- assert "resets in" in detail+ detail = response.json()["detail"]+ message = detail["message"].lower()+ assert "weekly" in message+ assert "resets in" in messagedef test_stream_chat_429_includes_reset_time(mocker: pytest_mock.MockerFixture):@@ -927,8 +930,41 @@ def test_stream_chat_429_includes_reset_time(mocker: pytest_mock.MockerFixture):)assert response.status_code == 429detail = response.json()["detail"]- assert "2h" in detail- assert "Resets in" in detail+ assert "2h" in detail["message"]+ assert "Resets in" in detail["message"]+++def test_stream_chat_429_carries_provider_failure_envelope_for_switch_connection(+ mocker: pytest_mock.MockerFixture,+):+ """The platform usage-cap 429 must be a structured ProviderFailure, not a+ bare string, so the frontend can offer "switch to another connection"+ (e.g. a connected BYOSUB/Codex credential) instead of only "upgrade your+ plan". A plain string here silently drops that UI even though the+ frontend already supports it end-to-end.+ """+ from backend.copilot.rate_limit import RateLimitExceeded++ _mock_stream_internals(mocker)+ mocker.patch.object(chat_routes.config, "daily_cost_limit_microdollars", 10000)+ mocker.patch.object(chat_routes.config, "weekly_cost_limit_microdollars", 50000)+ resets_at = datetime.now(UTC) + timedelta(hours=1)+ mocker.patch(+ "backend.api.features.chat.routes.check_rate_limit",+ side_effect=RateLimitExceeded("daily", resets_at),+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "hello"},+ )++ assert response.status_code == 429+ detail = response.json()["detail"]+ assert isinstance(detail, dict)+ assert detail["kind"] == "usage_limit"+ assert detail["authProvider"] == "platform"+ assert detail["resetsAt"] == int(resets_at.timestamp())def test_stream_chat_returns_503_with_retry_after_when_rate_limit_unavailable(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxindex b8dfe860f9..1a2f97fcc6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -50,6 +50,7 @@ export function CopilotChatHost({loadMore,turnStats,rateLimitMessage,+ platformLimitFailure,dismissRateLimit,providerLimit,dismissProviderLimit,@@ -112,6 +113,8 @@ export function CopilotChatHost({</div><RateLimitGaterateLimitMessage={rateLimitMessage}+ failure={platformLimitFailure}+ sessionId={sessionId}onDismiss={dismissRateLimit}/><ProviderLimitDialogdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsxindex fd56a2689b..85f2465a52 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx@@ -1,9 +1,15 @@+import {+ getGetV2ListChatConnectionsMockHandler200,+ getPutV2ChangeTheConnectionAnExistingChatRunsOnMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";import { server } from "@/mocks/mock-server";import {copilotStreamErrorHandler,copilotStreamHandler,} from "@/tests/integrations/copilot-sse";import { screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import type { UIMessageChunk } from "ai";import { http, HttpResponse } from "msw";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -248,3 +254,185 @@ describe("Otto streaming — error paths", () => {expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();});});++describe("AutoPilot streaming — our usage cap next to a linked subscription", () => {+ function platformOffer(): AIConnectionOffer {+ return {+ offer_id: "platform:deployment",+ provider_family: "autogpt",+ auth_provider: "platform",+ display_name: "AutoGPT Platform",+ auth_method: "deployment",+ credential_id: null,+ backed_by_label: "Your AutoGPT plan",+ description: "Runs on your AutoGPT plan.",+ state: "ready",+ selectable: true,+ is_default: true,+ tiers: [],+ limitations: [],+ lock_reason: null,+ unlock_href: null,+ };+ }++ function chatgptOffer(): AIConnectionOffer {+ return {+ ...platformOffer(),+ offer_id: "codex:cred-1",+ provider_family: "openai",+ auth_provider: "codex",+ display_name: "ChatGPT",+ auth_method: "chatgpt_oauth",+ credential_id: "cred-1",+ is_default: false,+ };+ }++ // What the backend's admission check sends once it refuses on our own+ // daily budget: a 429 whose body is the typed envelope, not a bare string.+ const ourCap = {+ detail: {+ kind: "usage_limit",+ message: "You've reached your daily usage limit. Resets in 1h 0m.",+ authProvider: "platform",+ credentialId: null,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ },+ };++ it("keeps the plan dialog for our cap and offers the linked subscription beside the upgrade", async () => {+ let switchedTo: unknown = null;+ server.use(+ copilotStreamErrorHandler({+ baseUrl: TEST_BACKEND_BASE_URL,+ sessionId: TEST_SESSION_ID,+ status: 429,+ body: ourCap,+ }),+ getGetV2ListChatConnectionsMockHandler200({+ offers: [platformOffer(), chatgptOffer()],+ }),+ getPutV2ChangeTheConnectionAnExistingChatRunsOnMockHandler200(+ async ({ request }) => {+ switchedTo = await request.json();+ return {};+ },+ ),+ );++ renderHost();+ await typeAndSend("over the cap");++ // Our own cap, so our own dialog: the upgrade path survives ...+ expect(+ await screen.findByText(/daily usage limit reached/i, undefined, {+ timeout: 5000,+ }),+ ).toBeDefined();+ expect(screen.queryByText(/hit this connection's limit/i)).toBeNull();+ expect(+ screen.getByRole("button", { name: /upgrade plan|contact us/i }),+ ).toBeDefined();++ // ... and the linked subscription is offered next to it, because the cap+ // does not apply to a turn billed to the user's own credential.+ const user = userEvent.setup();+ await user.click(+ await screen.findByRole(+ "button",+ { name: /continue on chatgpt/i },+ { timeout: 5000 },+ ),+ );++ await waitFor(() =>+ expect(switchedTo).toEqual({+ llm_auth_provider: "codex",+ llm_credential_id: "cred-1",+ }),+ );+ await waitFor(() =>+ expect(screen.queryByText(/daily usage limit reached/i)).toBeNull(),+ );+ });++ it("offers nothing to continue on when the platform is the only connection", async () => {+ server.use(+ copilotStreamErrorHandler({+ baseUrl: TEST_BACKEND_BASE_URL,+ sessionId: TEST_SESSION_ID,+ status: 429,+ body: ourCap,+ }),+ getGetV2ListChatConnectionsMockHandler200({+ offers: [platformOffer()],+ }),+ );++ renderHost();+ await typeAndSend("over the cap");++ expect(+ await screen.findByText(/daily usage limit reached/i, undefined, {+ timeout: 5000,+ }),+ ).toBeDefined();+ expect(+ screen.getByRole("button", { name: /upgrade plan|contact us/i }),+ ).toBeDefined();+ // The connection that just refused is never offered back. Were it not+ // excluded, "Continue on AutoGPT Platform" would appear once the offers+ // load, so give that long enough to have happened.+ await expect(+ screen.findByRole("button", { name: /continue on/i }, { timeout: 1500 }),+ ).rejects.toThrow();+ });++ it("treats a mid-turn limit on the platform route as the provider's, not ours", async () => {+ // A self-host runs its own OpenRouter or local gateway on the "platform"+ // route, so its upstream 429 arrives with the same authProvider as our+ // cap. It came on the stream, mid-turn, which our cap never does -- and+ // it must not be answered with "upgrade your plan" for an account we+ // do not bill.+ const chunks: UIMessageChunk[] = [+ { type: "start", messageId: "msg-1" },+ { type: "start-step" },+ {+ type: "data-provider-failure",+ data: {+ kind: "usage_limit",+ message: "OpenRouter rate-limited this deployment.",+ authProvider: "platform",+ credentialId: null,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ },+ },+ { type: "error", errorText: "OpenRouter rate-limited this deployment." },+ ];+ server.use(+ copilotStreamHandler({+ baseUrl: TEST_BACKEND_BASE_URL,+ sessionId: TEST_SESSION_ID,+ chunks,+ }),+ getGetV2ListChatConnectionsMockHandler200({+ offers: [platformOffer()],+ }),+ );++ renderHost();+ await typeAndSend("hi");++ expect(+ await screen.findByText(/hit this connection's limit/i, undefined, {+ timeout: 5000,+ }),+ ).toBeDefined();+ expect(screen.queryByText(/daily usage limit reached/i)).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.tsindex 24ec435933..a10eced46a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts@@ -231,6 +231,7 @@ describe("handleStreamError — telling the two usage limits apart", () => {expect(onRateLimit.mock.calls[0][1]).toEqual(expect.objectContaining({ kind: "usage_limit", authProvider: "codex" }),);+ expect(onRateLimit.mock.calls[0][2]).toBe("provider");});it("still routes our own limit the same way, so the composer text survives", () => {@@ -248,4 +249,121 @@ describe("handleStreamError — telling the two usage limits apart", () => {expect(onRateLimit.mock.calls[0][1]?.authProvider).toBe("platform");expect(mockToast).not.toHaveBeenCalled();});++ it("names a streamed envelope on the platform route as the provider's refusal", () => {+ // A self-host runs its own OpenRouter or local gateway on the "platform"+ // route, so its upstream 429 carries the same authProvider as our+ // admission cap. What tells them apart is that it came mid-turn, on the+ // stream: our cap never gets that far. Routing it as our cap would tell+ // a self-host to upgrade a plan we do not bill them for.+ const onRateLimit = vi.fn();++ handleStreamError({+ error: new Error("boom"),+ providerFailure: limit("platform"),+ onRateLimit,+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });++ expect(onRateLimit.mock.calls[0][2]).toBe("provider");+ });+});++describe("handleStreamError — structured detail from a pre-stream 429/etc.", () => {+ beforeEach(() => {+ mockToast.mockClear();+ });++ it("recovers a ProviderFailure from an object `detail` and opens the switch-connection path", () => {+ // The platform usage-cap 429 raises before streaming starts, so it+ // never rides the live-stream envelope `handleStreamError` normally gets+ // — it only reaches the client as FastAPI's `{"detail": ...}` body. If+ // `detail` is an object (the structured envelope) rather than a string,+ // it must still be recognised, not silently dropped to string-guessing.+ const onRateLimit = vi.fn();++ handleStreamError({+ error: new Error(+ JSON.stringify({+ detail: {+ kind: "usage_limit",+ message: "You've reached your daily usage limit. Resets in 1h 0m.",+ authProvider: "platform",+ credentialId: null,+ resetsAt: 1999999999,+ retryable: false,+ reconnectFixesIt: false,+ },+ }),+ ),+ onRateLimit,+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });++ expect(onRateLimit).toHaveBeenCalledTimes(1);+ expect(onRateLimit.mock.calls[0][1]).toEqual(+ expect.objectContaining({+ kind: "usage_limit",+ authProvider: "platform",+ }),+ );+ // An envelope in the HTTP body means the turn was refused before the+ // stream opened, which only our own cap does. The caller keeps the plan+ // dialog for it and merely adds the switch offer.+ expect(onRateLimit.mock.calls[0][2]).toBe("admission");+ expect(mockToast).not.toHaveBeenCalled();+ });++ it("prefers the streamed envelope, and its origin, when both are in hand", () => {+ const onRateLimit = vi.fn();++ handleStreamError({+ error: new Error(+ JSON.stringify({+ detail: {+ kind: "usage_limit",+ message: "admission",+ authProvider: "platform",+ },+ }),+ ),+ providerFailure: {+ kind: "usage_limit",+ message: "streamed",+ authProvider: "codex",+ credentialId: "cred-1",+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ },+ onRateLimit,+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });++ expect(onRateLimit.mock.calls[0][1]?.message).toBe("streamed");+ expect(onRateLimit.mock.calls[0][2]).toBe("provider");+ });++ it("still handles a plain string `detail` the old way (backward compat)", () => {+ const onRateLimit = vi.fn();++ handleStreamError({+ error: new Error(+ '{"detail":"You\'ve reached your daily usage limit. Resets in 1h."}',+ ),+ onRateLimit,+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });++ expect(onRateLimit).toHaveBeenCalledTimes(1);+ // No structured envelope was recoverable, so the second arg is undefined+ // — same behaviour as before this fix, for every backend that still+ // sends a bare string.+ expect(onRateLimit.mock.calls[0][1]).toBeUndefined();+ expect(onRateLimit.mock.calls[0][2]).toBeUndefined();+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsxindex ca8c4bb19a..c205bdda0e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx@@ -7,10 +7,20 @@ import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/import type { SubscriptionTier } from "@/app/api/__generated__/models/subscriptionTier";import { toast } from "@/components/molecules/Toast/use-toast";import { useEffect } from "react";+import type { ProviderFailure } from "../../providerFailure";+import { useProviderLimitDialog } from "../ProviderLimitDialog/useProviderLimitDialog";import { RateLimitResetDialog } from "./RateLimitResetDialog";interface Props {rateLimitMessage: string | null;+ /**+ * The typed envelope behind our cap, when the backend sent one. With it+ * the dialog can also offer a linked subscription to continue on. Without+ * it (an older backend, or a 429 that is not the usage cap) the dialog is+ * exactly as it always was.+ */+ failure?: ProviderFailure | null;+ sessionId?: string | null;onDismiss: () => void;}@@ -18,7 +28,22 @@ interface Props {* Renders the rate-limit dialog when the user hits their daily limit.* Falls back to a toast when the usage query fails.*/-export function RateLimitGate({ rateLimitMessage, onDismiss }: Props) {+export function RateLimitGate({+ rateLimitMessage,+ failure = null,+ sessionId = null,+ onDismiss,+}: Props) {+ // The switch itself is the provider-limit dialog's: the same offers list,+ // the same exclusion of the connection that just refused, the same session+ // mutation. Only the framing differs. Here the cap is ours, so the upgrade+ // stays on offer and the switch is offered beside it, never instead.+ const { alternative, continueHere, isSwitching } = useProviderLimitDialog({+ failure,+ sessionId,+ onDismiss,+ });+const {data: usage,isSuccess: hasUsage,@@ -64,6 +89,9 @@ export function RateLimitGate({ rateLimitMessage, onDismiss }: Props) {onClose={onDismiss}resetsAt={usage?.daily?.resets_at ?? usage?.weekly?.resets_at ?? null}tier={tier ?? null}+ alternative={alternative}+ onContinue={continueHere}+ isSwitching={isSwitching}/>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsxindex f814d824ea..ad7a099068 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx@@ -12,6 +12,15 @@ interface Props {onClose: () => void;resetsAt?: string | Date | null;tier?: SubscriptionTier | null;+ /**+ * A linked subscription this chat could continue on instead. The platform+ * cap does not apply to a turn billed to the user's own credential, so when+ * the account holds one, switching is a way out that costs nothing more.+ * Offered beside the upgrade, never instead of it: the cap is still ours.+ */+ alternative?: { display_name: string } | null;+ onContinue?: () => void;+ isSwitching?: boolean;}const CONTACT_US_URL = "mailto:[email protected]";@@ -30,10 +39,14 @@ export function RateLimitResetDialog({onClose,resetsAt,tier,+ alternative = null,+ onContinue,+ isSwitching = false,}: Props) {const router = useRouter();const resetTimeLabel = resetsAt ? formatResetTime(resetsAt) : null;const isTopTier = !!tier && TOP_TIERS.has(tier);+ const canContinue = alternative !== null && onContinue !== undefined;const ctaLabel = isTopTier ? "Contact us" : "Upgrade plan";const bodyTrailer = isTopTier@@ -69,13 +82,31 @@ export function RateLimitResetDialog({You can still browse, edit agents, and view results —{" "}{bodyTrailer}</Text>+ {canContinue && (+ <Text variant="small" className="mt-3 !text-zinc-500">+ Or continue on {alternative.display_name}: the rest of this chat+ runs there instead, and everything already said stays as it is.+ </Text>+ )}<Dialog.Footer className="!justify-center"><Button variant="secondary" onClick={onClose}>Wait for reset</Button>- <Button variant="primary" onClick={handleCtaClick}>+ <Button+ variant={canContinue ? "secondary" : "primary"}+ onClick={handleCtaClick}+ >{ctaLabel}</Button>+ {canContinue && (+ <Button+ variant="primary"+ onClick={onContinue}+ loading={isSwitching}+ >+ Continue on {alternative.display_name}+ </Button>+ )}</Dialog.Footer></Dialog.Content></Dialog>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsxindex 62865b18ac..82115c024d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx@@ -1,5 +1,5 @@import { cleanup, render } from "@/tests/integrations/test-utils";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mockToast = vi.fn();vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {@@ -25,6 +25,15 @@ vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({mockUseGetSubscriptionStatus(...args),}));+// The switch-connection mechanics are borrowed from the provider-limit+// dialog's hook. Stubbed here so these tests stay about the gate: what it+// asks that hook for, and what it hands the dialog back.+const mockUseProviderLimitDialog = vi.fn();+vi.mock("../../ProviderLimitDialog/useProviderLimitDialog", () => ({+ useProviderLimitDialog: (...args: unknown[]) =>+ mockUseProviderLimitDialog(...args),+}));+// Capture props the dialog was rendered with so we can assert on them.const dialogSpy = vi.fn();vi.mock("../RateLimitResetDialog", () => ({@@ -33,6 +42,9 @@ vi.mock("../RateLimitResetDialog", () => ({onClose: () => void;resetsAt?: string | Date | null;tier?: string | null;+ alternative?: { display_name: string } | null;+ onContinue?: () => void;+ isSwitching?: boolean;}) => {dialogSpy(props);return <div data-testid="reset-dialog" data-open={String(props.isOpen)} />;@@ -41,11 +53,28 @@ vi.mock("../RateLimitResetDialog", () => ({import { RateLimitGate } from "../RateLimitGate";+function noAlternative() {+ mockUseProviderLimitDialog.mockReturnValue({+ alternative: null,+ continueHere: vi.fn(),+ isSwitching: false,+ isLoadingOffers: false,+ failedToLoadOffers: false,+ retryOffers: vi.fn(),+ resetHint: null,+ });+}++beforeEach(() => {+ noAlternative();+});+afterEach(() => {cleanup();mockToast.mockReset();mockUseGetV2GetCopilotUsage.mockReset();mockUseGetSubscriptionStatus.mockReset();+ mockUseProviderLimitDialog.mockReset();dialogSpy.mockReset();});@@ -305,3 +334,87 @@ describe("RateLimitGate", () => {expect(lastProps.resetsAt).toBe(dailyFuture);});});++describe("RateLimitGate — continuing on a linked subscription", () => {+ const capFailure = {+ kind: "usage_limit" as const,+ message: "You've reached your daily usage limit. Resets in 1h 0m.",+ authProvider: "platform",+ credentialId: null,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ };++ function usageLoaded() {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: { daily: { percent_used: 100, resets_at: null }, weekly: null },+ isSuccess: true,+ isError: false,+ });+ setSubscription("MAX");+ }++ it("asks for an alternative only when the cap came with an envelope", () => {+ usageLoaded();++ render(+ <RateLimitGate+ rateLimitMessage="limit reached"+ sessionId="sess-1"+ onDismiss={vi.fn()}+ />,+ );++ // A bare-string 429 -- an older backend, or a 429 that is not the usage+ // cap -- has no envelope to name the failed connection with, so there is+ // nothing to exclude and nothing to offer. The hook is told so.+ expect(mockUseProviderLimitDialog).toHaveBeenCalledWith(+ expect.objectContaining({ failure: null, sessionId: "sess-1" }),+ );+ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.alternative).toBeNull();+ });++ it("hands the envelope to the switch hook and the offer to the dialog", () => {+ usageLoaded();+ const continueHere = vi.fn();+ mockUseProviderLimitDialog.mockReturnValue({+ alternative: {+ display_name: "ChatGPT",+ auth_provider: "codex",+ credential_id: "cred-1",+ },+ continueHere,+ isSwitching: true,+ isLoadingOffers: false,+ failedToLoadOffers: false,+ retryOffers: vi.fn(),+ resetHint: null,+ });+ const onDismiss = vi.fn();++ render(+ <RateLimitGate+ rateLimitMessage={capFailure.message}+ failure={capFailure}+ sessionId="sess-1"+ onDismiss={onDismiss}+ />,+ );++ expect(mockUseProviderLimitDialog).toHaveBeenCalledWith({+ failure: capFailure,+ sessionId: "sess-1",+ onDismiss,+ });+ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.isOpen).toBe(true);+ expect(lastProps.alternative?.display_name).toBe("ChatGPT");+ expect(lastProps.onContinue).toBe(continueHere);+ expect(lastProps.isSwitching).toBe(true);+ // The upgrade path is untouched by the offer: the tier still reaches the+ // dialog so it can keep its Upgrade / Contact us CTA beside the switch.+ expect(lastProps.tier).toBe("MAX");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsxindex 839316bad7..9a58665ac6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx@@ -161,4 +161,59 @@ describe("RateLimitResetDialog", () => {expect(screen.queryByText("Daily usage limit reached")).toBeNull();});++ it("offers nothing to continue on by default", () => {+ render(+ <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,+ );++ expect(screen.queryByText(/Continue on/)).toBeNull();+ expect(screen.queryByText(/Or continue on/)).toBeNull();+ });++ it("offers a linked subscription beside the upgrade, never instead of it", () => {+ const onClose = vi.fn();+ const onContinue = vi.fn();+ render(+ <RateLimitResetDialog+ isOpen={true}+ onClose={onClose}+ resetsAt={null}+ tier="MAX"+ alternative={{ display_name: "ChatGPT" }}+ onContinue={onContinue}+ />,+ );++ // The cap is still ours, so every answer it always had is still here.+ expect(screen.getByText("Wait for reset")).toBeDefined();+ expect(screen.getByText("Contact us")).toBeDefined();+ expect(screen.getByText(/Or continue on ChatGPT/)).toBeDefined();++ fireEvent.click(screen.getByText("Continue on ChatGPT"));+ expect(onContinue).toHaveBeenCalledTimes(1);+ // Closing is the switch's job once it lands, not the click's: the+ // composer still holds the refused message for the user to resend.+ expect(onClose).not.toHaveBeenCalled();+ expect(mockPush).not.toHaveBeenCalled();+ expect(mockWindowOpen).not.toHaveBeenCalled();+ });++ it("keeps the upgrade path working with a switch on offer", () => {+ const onClose = vi.fn();+ render(+ <RateLimitResetDialog+ isOpen={true}+ onClose={onClose}+ resetsAt={null}+ tier="PRO"+ alternative={{ display_name: "ChatGPT" }}+ onContinue={vi.fn()}+ />,+ );++ fireEvent.click(screen.getByText("Upgrade plan"));+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(mockPush).toHaveBeenCalledWith("/settings/billing");+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.tsindex 5aa0e0c738..592b6d7da8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts@@ -2,6 +2,7 @@ import { toast } from "@/components/molecules/Toast/use-toast";import {describeProviderFailure,+ parseProviderFailure,type ProviderFailure,} from "./providerFailure";@@ -97,9 +98,53 @@ function extractErrorDetail(error: Error): string {return error.message;}+/**+ * A typed provider-failure envelope, when FastAPI's `{"detail": ...}` wraps+ * an object instead of a string (e.g. the 429 raised for the platform usage+ * cap). `extractErrorDetail` above only unwraps string details, so a+ * structured refusal used to fall through to substring guessing and never+ * reached the "switch connection" UI. Checked separately so the string path+ * stays untouched for every other error shape.+ */+function extractProviderFailureDetail(error: Error): ProviderFailure | null {+ try {+ const parsed = JSON.parse(error.message) as unknown;+ if (+ typeof parsed === "object" &&+ parsed !== null &&+ "detail" in parsed &&+ typeof (parsed as { detail: unknown }).detail === "object" &&+ (parsed as { detail: unknown }).detail !== null+ ) {+ return parseProviderFailure((parsed as { detail: unknown }).detail);+ }+ } catch {+ // Not JSON+ }+ return null;+}++/**+ * Where a usage limit was refused. The two limits do not share an answer:+ *+ * - `"admission"`: the backend refused the turn before the stream opened,+ * which only our own budget does. The envelope came in the HTTP error body.+ * - `"provider"`: the connection the turn ran on refused it mid-turn. The+ * envelope rode the live stream.+ *+ * Told apart by origin rather than by `authProvider` because a self-host+ * runs its own OpenRouter or local gateway on the "platform" route, so its+ * upstream 429 carries the same `authProvider` as our admission cap.+ */+export type UsageLimitOrigin = "admission" | "provider";+interface HandleStreamErrorArgs {error: Error;- onRateLimit: (message: string, providerFailure?: ProviderFailure) => void;+ onRateLimit: (+ message: string,+ providerFailure?: ProviderFailure,+ origin?: UsageLimitOrigin,+ ) => void;onReconnect: () => void;isUserStoppingRef: React.MutableRefObject<boolean>;/**@@ -130,9 +175,13 @@ export function handleStreamError({onRateLimit,onReconnect,isUserStoppingRef,- providerFailure,+ providerFailure: streamedProviderFailure,}: HandleStreamErrorArgs): void {const errorDetail = extractErrorDetail(error);+ // The live stream's typed envelope wins when present; otherwise recover+ // one from a structured 429/etc. body raised before streaming started.+ const providerFailure =+ streamedProviderFailure ?? extractProviderFailureDetail(error);// 0. The server said what went wrong, so stop guessing.if (providerFailure) {@@ -142,13 +191,20 @@ export function handleStreamError({// text for a message the backend refused before persisting, which a// toast alone would lose.//- // The failure travels with it so the caller can tell the two limits- // apart. They are not the same event: our own credits running out is- // answered by upgrading a plan with us, and a linked subscription- // running out is answered by continuing on a different connection.- // Offering the first for the second asks someone to pay us because- // OpenAI said no.- onRateLimit(`${copy.title}. ${copy.description}`, providerFailure);+ // The failure travels with it, and so does where it was refused, so+ // the caller can tell the two limits apart. They are not the same+ // event: our own credits running out is answered by upgrading a plan+ // with us, and a linked subscription running out is answered by+ // continuing on a different connection. Offering the first for the+ // second asks someone to pay us because OpenAI said no.+ const origin: UsageLimitOrigin = streamedProviderFailure+ ? "provider"+ : "admission";+ onRateLimit(+ `${copy.title}. ${copy.description}`,+ providerFailure,+ origin,+ );return;}toast({diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex fe71f52356..bee625203f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -180,6 +180,7 @@ export function useCopilotPage() {isUserStoppingRef,isUserStopping,rateLimitMessage,+ platformLimitFailure,dismissRateLimit,providerLimit,dismissProviderLimit,@@ -428,6 +429,7 @@ export function useCopilotPage() {loadMore,turnStats,rateLimitMessage,+ platformLimitFailure,dismissRateLimit,providerLimit,dismissProviderLimit,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex b3842371ff..f94438863c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -114,6 +114,13 @@ export function useCopilotStream({const queryClient = useQueryClient();const setInitialPrompt = useCopilotUIStore((s) => s.setInitialPrompt);const [rateLimitMessage, setRateLimitMessage] = useState<string | null>(null);+ // The envelope behind our own cap, when the backend sent one. It rides+ // along to the plan dialog so that dialog can also offer a linked+ // subscription to continue on: the cap does not apply to a turn billed to+ // the user's own credential, so a connected ChatGPT account is a way out+ // that costs them nothing more.+ const [platformLimitFailure, setPlatformLimitFailure] =+ useState<ProviderFailure | null>(null);// A linked subscription that stopped accepting turns, as opposed to our own// credits running out. Held separately because the answer is different.const [providerLimit, setProviderLimit] = useState<ProviderFailure | null>(@@ -125,6 +132,7 @@ export function useCopilotStream({} | null>(null);function dismissRateLimit() {setRateLimitMessage(null);+ setPlatformLimitFailure(null);}const chatRuntime = useMemo(() => {if (!sessionId) return null;@@ -251,7 +259,7 @@ export function useCopilotStream({handleStreamError({error,providerFailure: failureForThisTurn,- onRateLimit: (message, limitFailure) => {+ onRateLimit: (message, limitFailure, origin) => {// Backend raises 429 BEFORE persisting the user message, so the// optimistic user bubble added by useChat is a lie. Restore the text// into the composer (via the same store slot URL pre-fills use) and@@ -300,22 +308,28 @@ export function useCopilotStream({// A provider's own limit is not answered by upgrading with us, so// it opens the continue path instead of the plan dialog.//- // Which limit it is turns on whether the server sent a failure- // envelope, not on which connection the turn ran on. Our own daily- // budget is refused at admission and arrives with no envelope; an- // upstream 429 always carries one. Reading the connection instead- // meant a self-host -- where the route is "platform" because the- // deployment holds the key -- was told "Daily usage limit- // reached, upgrade your plan" when its own OpenRouter or local- // gateway had rate-limited it. That is a claim about an account we- // do not bill, offering a plan that would not help.- if (limitFailure) {+ // Which limit it is turns on where the turn was refused, not on+ // which connection it ran on. Our own budget is refused at+ // admission, before the stream opens; a provider refuses mid-turn,+ // on the stream. Both carry an envelope now, so the envelope alone+ // no longer says which. Reading the connection instead meant a+ // self-host -- where the route is "platform" because the deployment+ // holds the key -- was told "Daily usage limit reached, upgrade+ // your plan" when its own OpenRouter or local gateway had+ // rate-limited it. That is a claim about an account we do not bill,+ // offering a plan that would not help.+ if (limitFailure && origin === "provider") {// A later turn can fail in exactly the same way as an earlier one// the user dismissed. Live stream evidence is a new occurrence.dismissedProviderFailureRef.current = null;setProviderLimit(limitFailure);} else {- setRateLimitMessage(message);+ // Our own cap. The envelope, when there is one, lets the plan+ // dialog offer a linked subscription to continue on beside the+ // upgrade it always offered. Older backends send a bare string+ // here and get the dialog exactly as it was.+ setPlatformLimitFailure(limitFailure ?? null);+ setRateLimitMessage(limitFailure?.message || message);}},onReconnect: () => handleReconnectRef.current(),@@ -855,6 +869,7 @@ export function useCopilotStream({isUserStoppingRef,isUserStopping,rateLimitMessage,+ platformLimitFailure,providerLimit,dismissProviderLimit: () => {if (sessionId && providerLimit) {