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(frontend): one paywall toast with an upgrade link when a copilot send is refused (#15407)
Nicholas Tindleb3c5a3be6cfc
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatErrorGuidance.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatErrorGuidance.test.tsindex 570540e9ae..34720b939c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatErrorGuidance.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatErrorGuidance.test.ts@@ -44,6 +44,14 @@ describe("describeChatError", () => {new Error("SDK stream error: Prompt is too long"),"new-chat",],+ [+ "an account without a plan",+ new SendRefusedError(+ '{"detail":"A subscription is required to use this feature."}',+ 402,+ ),+ "plans",+ ],])("%s points to what works instead of a resend", (_state, error, action) => {const guidance = describeChatError(error);expect(guidance.action).toBe(action);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 f5bc2f8afa..a2fba9075a 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@@ -51,6 +51,27 @@ describe("handleStreamError", () => {mockToast.mockClear();});+ it("hands a refusal for want of a plan to onPaywall, and nothing else", () => {+ const onRateLimit = vi.fn();+ const onReconnect = vi.fn();+ const onPaywall = vi.fn();+ const noPlan = Object.assign(+ new Error("A subscription is required to use this feature."),+ { status: 402 },+ );+ handleStreamError({+ error: noPlan,+ onRateLimit,+ onReconnect,+ onPaywall,+ isUserStoppingRef: makeRef(false),+ });+ expect(onPaywall).toHaveBeenCalledOnce();+ expect(mockToast).not.toHaveBeenCalled();+ expect(onRateLimit).not.toHaveBeenCalled();+ expect(onReconnect).not.toHaveBeenCalled();+ });+it("routes rate-limit messages (case-insensitive 'usage limit') to onRateLimit", () => {const onRateLimit = vi.fn();const onReconnect = vi.fn();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.tsindex 8c4c56fe0f..d91d70b85b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts@@ -23,6 +23,7 @@ vi.mock("../tokenDevtool/usageTap", () => ({createUsageCapturingFetch(sessionId),}));+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { createCopilotTransport } from "../copilotStreamTransport";import { buildKickoffMessage } from "../expertKickoff";@@ -73,6 +74,45 @@ describe("copilotStreamTransport devtool wiring", () => {});});+describe("copilotStreamTransport refusals", () => {+ it("keeps a 402's status, so the chat can offer plans", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ detail:+ "A subscription is required to use this feature. Upgrade to continue.",+ }),+ { status: 402, headers: { "Content-Type": "application/json" } },+ ),+ ),+ );+ try {+ const transport = createCopilotTransport({+ sessionId: "sess-no-plan",+ ...makeRefs(),+ });+ const sent = transport.sendMessages({+ trigger: "submit-message",+ chatId: "sess-no-plan",+ messageId: undefined,+ messages: lastMessage("one more thing"),+ abortSignal: undefined,+ });++ await expect(sent).rejects.toBeInstanceOf(ApiError);+ await expect(sent).rejects.toMatchObject({+ status: 402,+ message:+ "A subscription is required to use this feature. Upgrade to continue.",+ });+ } finally {+ vi.unstubAllGlobals();+ }+ });+});+describe("copilotStreamTransport.prepareSendMessagesRequest", () => {it("reaches fetch when crypto.randomUUID is unavailable on a LAN HTTP origin", async () => {const originalCrypto = globalThis.crypto;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paywall-send.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paywall-send.test.tsxnew file mode 100644index 0000000000..7fcf57d7bb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paywall-send.test.tsx@@ -0,0 +1,176 @@+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { http, HttpResponse } from "msw";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useChatInput } from "../components/ChatInput/useChatInput";+import { useChatSession } from "../useChatSession";++// The first send of a new chat creates the session, and two layers used to+// report that one failure: useChatSession toasted "Please try again" and the+// composer toasted the server's reason, so a paywalled user saw two stacked+// red toasts and no way to upgrade. These run the real session hook into the+// real composer hook to pin the failure to one toast.++const toast = vi.hoisted(() => vi.fn());+const transports = vi.hoisted(() => ({ loaded: true }));+const billing = vi.hoisted(() => ({ enabled: true }));++vi.mock("@/hooks/useIsBillingEnabled", () => ({+ useIsBillingEnabled: () => billing.enabled,+}));++vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => toast(...args),+ useToast: () => ({ toast, dismiss: vi.fn() }),+}));++vi.mock(+ "@/app/api/__generated__/endpoints/chat/chat",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/app/api/__generated__/endpoints/chat/chat")+ >()),+ useGetV2ListChatTransports: () => ({+ data: !transports.loaded+ ? undefined+ : {+ status: 200,+ data: {+ transports: [+ {+ auth_provider: "platform",+ credential_id: null,+ label: "AutoGPT Platform",+ available: true,+ default: true,+ },+ ],+ },+ },+ isError: false,+ }),+ }),+);++function Composer() {+ const { createSession } = useChatSession();+ const { value, handleChange, handleSubmit } = useChatInput({+ onSend: async () => {+ await createSession();+ },+ });+ return (+ <form onSubmit={handleSubmit}>+ <textarea aria-label="Message" value={value} onChange={handleChange} />+ </form>+ );+}++function answerSessionCreate(status: number, detail: string) {+ server.use(+ http.post("*/api/chat/sessions", () =>+ HttpResponse.json({ detail }, { status }),+ ),+ );+}++async function send(text: string) {+ render(<Composer />);+ const textarea = screen.getByRole<HTMLTextAreaElement>("textbox", {+ name: "Message",+ });+ fireEvent.change(textarea, { target: { value: text } });+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() => expect(toast).toHaveBeenCalled());+ return textarea;+}++afterEach(() => {+ server.resetHandlers();+ toast.mockReset();+ transports.loaded = true;+ billing.enabled = true;+});++describe("a refused first send", () => {+ it("offers plans once for a paywalled account and keeps the message", async () => {+ answerSessionCreate(+ 402,+ "A subscription is required to use this feature. Upgrade to continue.",+ );+ const textarea = await send("draft my weekly report");++ expect(toast).toHaveBeenCalledOnce();+ const [paywall] = toast.mock.calls[0];+ expect(paywall).toMatchObject({+ title: "Sending needs an active plan",+ variant: "destructive",+ });+ render(+ <>+ {paywall.description}+ {paywall.action}+ </>,+ );+ expect(+ screen.getByText(+ "Choose one to keep chatting — your message is back in the composer.",+ ),+ ).toBeDefined();+ expect(+ screen.getByRole("link", { name: "See plans" }).getAttribute("href"),+ ).toBe("/settings/billing");+ expect(textarea.value).toBe("draft my weekly report");+ });++ it("offers no plans link where this install doesn't bill", async () => {+ billing.enabled = false;+ answerSessionCreate(+ 402,+ "A subscription is required to use this feature. Upgrade to continue.",+ );+ await send("draft my weekly report");++ expect(toast).toHaveBeenCalledOnce();+ const [paywall] = toast.mock.calls[0];+ render(+ <>+ {paywall.description}+ {paywall.action}+ </>,+ );+ expect(screen.getByText(/Ask whoever runs this server/)).toBeDefined();+ expect(screen.queryByRole("link", { name: "See plans" })).toBeNull();+ });++ it("reports any other failure once, with the server's reason", async () => {+ answerSessionCreate(500, "Database unavailable");+ const textarea = await send("hello");++ expect(toast).toHaveBeenCalledOnce();+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Couldn't send message",+ variant: "destructive",+ }),+ );+ expect(toast.mock.calls[0][0].action).toBeUndefined();+ expect(textarea.value).toBe("hello");+ });++ it("says once that AI connections are still loading", async () => {+ transports.loaded = false;+ const textarea = await send("too quick");++ expect(toast).toHaveBeenCalledOnce();+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({ title: "AI connections are still loading" }),+ );+ expect(textarea.value).toBe("too quick");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/chatErrorGuidance.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/chatErrorGuidance.tsindex fa3ac621e0..e425f09b14 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/chatErrorGuidance.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/chatErrorGuidance.ts@@ -5,7 +5,7 @@ import {MessageTooLongError,} from "./stream/turnRuntime";-export type ChatErrorAction = "sign-in" | "new-chat";+export type ChatErrorAction = "sign-in" | "new-chat" | "plans";export interface ChatErrorGuidance {/** What happened, and what will work next. */@@ -43,6 +43,11 @@ export function describeChatError(error: Error): ChatErrorGuidance {"This conversation is too long to continue. Start a new chat to keep going.",action: "new-chat",};+ if (status === 402)+ return {+ title: "Sending needs an active plan, so this message wasn't sent.",+ action: "plans",+ };if (status === 429 || /usage limit/i.test(error.message))return {title: "You've reached a usage limit, so this message wasn't sent.",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex 56d7a4c954..d802b12375 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -5,7 +5,6 @@ import {TooltipContent,TooltipTrigger,} from "@/components/atoms/Tooltip/BaseTooltip";-import { toast } from "@/components/molecules/Toast/use-toast";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { UIDataTypes, UIMessage, UITools } from "ai";import { LayoutGroup, motion } from "framer-motion";@@ -44,7 +43,7 @@ import { breakdownCacheKey } from "../../tokenDevtool/tokenMath";import type { SentFrom } from "../../sentFrom";import type { AutopilotMode } from "../../autopilotModeStore";import { AutopilotModeSelector } from "../ChatInput/components/AutopilotModeSelector/AutopilotModeSelector";-import { describeSendFailure } from "../ChatInput/helpers";+import { toastSendFailure } from "../../helpers/sendFailureToast";import { isHeldCallRow } from "../ChatMessagesContainer/heldCallRows";import {getKickoffAttemptToken,@@ -279,8 +278,13 @@ export const ChatContainer = ({requestVoiceStart();try {await onCreateSession();- } catch {+ } catch (error) {takeVoiceStart();+ toastSendFailure({+ title: "Could not start a new chat session",+ error,+ recovery: "voice mode did not start",+ });}}@@ -327,13 +331,10 @@ export const ChatContainer = ({);}} catch (error) {- toast({+ toastSendFailure({title: "Couldn't retry message",- description: describeSendFailure(- error,- "your previous message is still in the chat",- ),- variant: "destructive",+ error,+ recovery: "your previous message is still in the chat",});} finally {isRetryingRef.current = false;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.tsindex 985b120962..4ef3553a56 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts@@ -1,7 +1,5 @@import { useCopilotUIStore } from "@/app/(platform)/copilot/store";-import { ReportedSendError } from "@/app/(platform)/copilot/helpers/reportedSendError";-import { describeSendFailure } from "./helpers";-import { toast } from "@/components/molecules/Toast/use-toast";+import { toastSendFailure } from "../../helpers/sendFailureToast";import { ChangeEvent, FormEvent, useEffect, useRef, useState } from "react";interface Args {@@ -89,14 +87,10 @@ export function useChatInput({notifyMessageSent();} catch (error) {setValue((current) => restoreFailedDraft(current, message));- if (error instanceof ReportedSendError) return;- toast({+ toastSendFailure({title: "Couldn't send message",- description: describeSendFailure(- error,- "your message is back in the composer",- ),- variant: "destructive",+ error,+ recovery: "your message is back in the composer",});} finally {isSubmittingRef.current = false;@@ -120,14 +114,10 @@ export function useChatInput({await onEnqueue(trimmedMessage);} catch (error) {setValue((current) => restoreFailedDraft(current, message));- if (error instanceof ReportedSendError) return;- toast({+ toastSendFailure({title: "Couldn't send message",- description: describeSendFailure(- error,- "your message is back in the composer",- ),- variant: "destructive",+ error,+ recovery: "your message is back in the composer",});} finally {isEnqueueingRef.current = false;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/ChatErrorBanner.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/ChatErrorBanner.tsxindex 66b9e4f0be..6aae02e731 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/ChatErrorBanner.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/ChatErrorBanner.tsx@@ -1,4 +1,5 @@import { Button } from "@/components/atoms/Button/Button";+import { useIsBillingEnabled } from "@/hooks/useIsBillingEnabled";import {describeChatError,@@ -10,7 +11,16 @@ interface Props {}export function ChatErrorBanner({ error }: Props) {- const { title, action, note } = describeChatError(error);+ const guidance = describeChatError(error);+ const isBillingEnabled = useIsBillingEnabled();+ // Without billing (most self-hosted installs) there are no plans to pick+ // and /settings/billing is a 404, so point at whoever runs the server.+ const noPlans = guidance.action === "plans" && !isBillingEnabled;+ const { title } = guidance;+ const action = noPlans ? null : guidance.action;+ const note = noPlans+ ? "Ask whoever runs this server to set one up."+ : guidance.note;return (<divdata-testid="chat-error-banner"@@ -31,15 +41,22 @@ export function ChatErrorBanner({ error }: Props) {size="small"className="mt-3">- {action === "sign-in" ? "Sign in" : "Start a new chat"}+ {ACTION_LABELS[action]}</Button>) : null}</div>);}+const ACTION_LABELS: Record<ChatErrorAction, string> = {+ "sign-in": "Sign in",+ "new-chat": "Start a new chat",+ plans: "See plans",+};+function hrefFor(action: ChatErrorAction) {if (action === "new-chat") return "/copilot";+ if (action === "plans") return "/settings/billing";const here =typeof window === "undefined"? "/copilot"diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/__tests__/ChatErrorBanner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/__tests__/ChatErrorBanner.test.tsxindex 89c080d947..be4226eeef 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/__tests__/ChatErrorBanner.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/__tests__/ChatErrorBanner.test.tsx@@ -1,5 +1,5 @@import { render, screen } from "@/tests/integrations/test-utils";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { CopilotAuthError } from "../../../../../helpers";import {@@ -8,8 +8,19 @@ import {} from "../../../../../stream/turnRuntime";import { ChatErrorBanner } from "../ChatErrorBanner";+const billing = vi.hoisted(() => ({ enabled: true }));+vi.mock("@/hooks/useIsBillingEnabled", () => ({+ useIsBillingEnabled: () => billing.enabled,+}));++const NO_PLAN = new SendRefusedError(+ '{"detail":"A subscription is required to use this feature. Upgrade to continue."}',+ 402,+);+afterEach(() => {window.history.replaceState(null, "", "/");+ billing.enabled = true;});describe("ChatErrorBanner", () => {@@ -25,6 +36,30 @@ describe("ChatErrorBanner", () => {).toBe(`/login?next=${encodeURIComponent("/copilot?sessionId=s-1")}`);});+ it("no plan: offers plans instead of a reload", () => {+ render(<ChatErrorBanner error={NO_PLAN} />);++ expect(+ screen.getByText(+ "Sending needs an active plan, so this message wasn't sent.",+ ),+ ).toBeDefined();+ expect(+ screen.getByRole("link", { name: "See plans" }).getAttribute("href"),+ ).toBe("/settings/billing");+ expect(screen.queryByText(/maintainer has been notified/)).toBeNull();+ });++ it("no plan where this install doesn't bill: no plans link, asks the operator", () => {+ billing.enabled = false;+ render(<ChatErrorBanner error={NO_PLAN} />);++ expect(screen.queryByRole("link", { name: "See plans" })).toBeNull();+ expect(+ screen.getByText("Ask whoever runs this server to set one up."),+ ).toBeDefined();+ });+it("a chat that is gone: offers a new chat", () => {render(<ChatErrorBanner error={new ChatUnavailableError()} />);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PaywallToast/PaywallToast.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PaywallToast/PaywallToast.tsxnew file mode 100644index 0000000000..dfab64a5b8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PaywallToast/PaywallToast.tsx@@ -0,0 +1,38 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { useIsBillingEnabled } from "@/hooks/useIsBillingEnabled";+import { toast as sonnerToast } from "sonner";++export const PAYWALL_TOAST_KEY = "copilot-send-paywall";+const BILLING_PATH = "/settings/billing";++interface DescriptionProps {+ recovery: string;+}++// Rendered inside the Toaster, so it can read whether this install bills at+// all. Without billing (most self-hosted installs) there is no plan to pick+// and /settings/billing is a 404, so it points at whoever runs the server.+export function PaywallToastDescription({ recovery }: DescriptionProps) {+ const isBillingEnabled = useIsBillingEnabled();+ return isBillingEnabled+ ? `Choose one to keep chatting — ${recovery}.`+ : `Ask whoever runs this server to set one up — ${recovery}.`;+}++export function PaywallToastAction() {+ const isBillingEnabled = useIsBillingEnabled();+ if (!isBillingEnabled) return null;+ return (+ <Button+ as="NextLink"+ href={BILLING_PATH}+ size="small"+ variant="secondary"+ onClick={() => sonnerToast.dismiss(PAYWALL_TOAST_KEY)}+ >+ See plans+ </Button>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsxindex 19207be24f..9ef022e3e1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx@@ -17,11 +17,10 @@ import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";-import { toast } from "@/components/molecules/Toast/use-toast";import { cn } from "@/lib/utils";import { GenericTool } from "../../tools/GenericTool/GenericTool";import { type ArtifactRef, useCopilotUIStore } from "../../store";-import { describeSendFailure } from "../ChatInput/helpers";+import { toastSendFailure } from "../../helpers/sendFailureToast";import { CopilotChatActionsContext } from "../CopilotChatActionsProvider/useCopilotChatActions";import { asObject, str } from "./resultHelpers";@@ -460,13 +459,12 @@ export function ExpertChangeGroup({// The card stays marked sent because the message is already in the// thread for Retry — the failure only needs saying.void Promise.resolve(actions.onSend(message)).catch((error: unknown) =>- toast({+ toastSendFailure({title: "Couldn't send message",- description: describeSendFailure(- error,- "it is still in the thread, use Retry to send it again",- ),- variant: "destructive",+ error,+ recovery: "it is still in the thread, use Retry to send it again",+ paywallRecovery:+ "it is still in the thread, use Retry once you have a plan",}),);setSent(true);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsxindex 289c299c0f..0b2e889899 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx@@ -23,8 +23,7 @@ import {} from "react";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";-import { toast } from "@/components/molecules/Toast/use-toast";-import { describeSendFailure } from "../ChatInput/helpers";+import { toastSendFailure } from "../../helpers/sendFailureToast";import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";import { ChainActionCard } from "../ChainActionCard/ChainActionCard";import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";@@ -225,13 +224,12 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {// points at the thread rather than the composer.function sendReply(message: string) {void Promise.resolve(onSend(message)).catch((error: unknown) =>- toast({+ toastSendFailure({title: "Couldn't send message",- description: describeSendFailure(- error,- "it is still in the thread, use Retry to send it again",- ),- variant: "destructive",+ error,+ recovery: "it is still in the thread, use Retry to send it again",+ paywallRecovery:+ "it is still in the thread, use Retry once you have a plan",}),);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.tsindex d94486e59b..590053d5f0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts@@ -156,6 +156,12 @@ interface HandleStreamErrorArgs {origin?: UsageLimitOrigin,) => void;onReconnect: () => void;+ /**+ * The account has no plan (HTTP 402). The backend refuses before saving the+ * prompt, so the caller puts it back in the composer; the chat's error+ * banner is the one message and carries the upgrade path, so no toast.+ */+ onPaywall?: () => void;isUserStoppingRef: React.MutableRefObject<boolean>;/*** The typed envelope, when this turn sent one. It is the only source here@@ -170,6 +176,7 @@ interface HandleStreamErrorArgs {* (or rate-limit UI), and decides whether to retry via reconnect.** Dispatch order (exclusive branches):+ * -. HTTP 402 (no plan) → `onPaywall`; the error banner says the rest.* 0. A typed provider-failure envelope → its own copy.* 1. `[code:<id>]` backend prefix → curated or generic backend toast.* 2. Legacy `usage limit` substring → rate-limit UI via `onRateLimit`.@@ -183,9 +190,14 @@ export function handleStreamError({error,onRateLimit,onReconnect,+ onPaywall,isUserStoppingRef,providerFailure: streamedProviderFailure,}: HandleStreamErrorArgs): void {+ if ((error as { status?: unknown }).status === 402) {+ onPaywall?.();+ return;+ }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.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.tsindex c290a2200f..4ae6ef5466 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts@@ -1,5 +1,6 @@import { WORKSPACE_FOLDER_PART_TYPE } from "./helpers/workspaceAttachments";import { environment } from "@/services/environment";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { DefaultChatTransport } from "ai";import type { ChatTransport, FileUIPart, UIMessage } from "ai";import { v4 as uuidv4 } from "uuid";@@ -66,11 +67,13 @@ export function createCopilotTransport({api: baseUrl,// Tee the raw SSE into the stream converter's shadow, and in dev into the// token devtool, which reads the `: usage {...}` comments the SDK drops.- fetch: createShadowFetch(- sessionId,- isTokenDevtoolEnabled()- ? createUsageCapturingFetch(sessionId)- : undefined,+ fetch: keepPaywallStatus(+ createShadowFetch(+ sessionId,+ isTokenDevtoolEnabled()+ ? createUsageCapturingFetch(sessionId)+ : undefined,+ ),),prepareSendMessagesRequest: async ({ messages }) => ({body: streamRequestBody(@@ -99,6 +102,23 @@ export function createCopilotTransport({}/** The POST body for a new turn, whichever client sends it. */+// The SDK turns a non-OK response into a bare Error carrying only the body,+// so a refusal for want of a plan would read as an unexplained failure. Keep+// its status so the error banner can offer plans instead of "reload".+function keepPaywallStatus(inner: typeof fetch): typeof fetch {+ return async (input, init) => {+ const response = await inner(input, init);+ if (response.status !== 402) return response;+ const body = await response.json().catch(() => null);+ const detail = (body as { detail?: unknown } | null)?.detail;+ throw new ApiError(+ typeof detail === "string" ? detail : "A plan is required to send",+ 402,+ body,+ );+ };+}+export function streamRequestBody(sessionId: string,last: UIMessage,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsxnew file mode 100644index 0000000000..f7aa65c371--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx@@ -0,0 +1,55 @@+import { toast } from "@/components/molecules/Toast/use-toast";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { describeSendFailure } from "../components/ChatInput/helpers";+import {+ PAYWALL_TOAST_KEY,+ PaywallToastAction,+ PaywallToastDescription,+} from "../components/PaywallToast/PaywallToast";+import { ReportedSendError } from "./reportedSendError";++const PAYWALL_TOAST_DURATION_MS = 15_000;++/** The backend answers 402 when the account has no plan (or its trial+ * lapsed). Retrying can never succeed, so it gets an upgrade path instead of+ * a "try again". */+export function isPaywallError(error: unknown) {+ return error instanceof ApiError && error.status === 402;+}++interface Args {+ title: string;+ error: unknown;+ /** Lowercase clause saying where the user's text went. */+ recovery: string;+ /** Replaces `recovery` on the paywall toast when `recovery` tells the user+ * to retry, which can't succeed until they have a plan. */+ paywallRecovery?: string;+}++/** The single toast for a send that failed. Every send path reports through+ * here so one failure is one toast. */+export function toastSendFailure({+ title,+ error,+ recovery,+ paywallRecovery = recovery,+}: Args) {+ if (error instanceof ReportedSendError) return;+ if (isPaywallError(error)) {+ toast({+ title: "Sending needs an active plan",+ description: <PaywallToastDescription recovery={paywallRecovery} />,+ variant: "destructive",+ duration: PAYWALL_TOAST_DURATION_MS,+ replaceKey: PAYWALL_TOAST_KEY,+ action: <PaywallToastAction />,+ });+ return;+ }+ toast({+ title,+ description: describeSendFailure(error, recovery),+ variant: "destructive",+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.tsindex 41f85f146b..ab41d7658b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts@@ -794,7 +794,7 @@ describe("refusals no retry can change", () => {expect(report).not.toHaveBeenCalled();});- it.each([401, 404, 429])(+ it.each([401, 402, 404, 429])("does not report a send refused %i, which the user's state explains",async (status) => {backend.respond(() => ({ status, body: { detail: "refused" } }));diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.tsindex 1743ab2c75..d90aff87cd 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts@@ -1495,7 +1495,8 @@ export function isUnexpectedRefusal(status: number) {return status >= 400 && status < 500 && !EXPECTED_4XX.has(status);}-const EXPECTED_4XX = new Set([401, 404, 408, 409, 425, 429]);+// 402: the account has no plan, a state the app expects and offers plans for.+const EXPECTED_4XX = new Set([401, 402, 404, 408, 409, 425, 429]);/** A send the server refused; its status says whether a resend can help. */export class SendRefusedError extends Error {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex ca11c9be2d..908ed06de0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -21,6 +21,7 @@ import {type TurnStatsMap,} from "./helpers/convertChatSessionToUiMessages";import { resolveSessionDryRun } from "./helpers";+import { isPaywallError } from "./helpers/sendFailureToast";import { getSessionSentFrom } from "./sentFrom";import {getAvailableLLMTransports,@@ -328,11 +329,6 @@ export function useChatSession({Sentry.captureException(error, {extra: { status: response.status },});- toast({- variant: "destructive",- title: "Could not start a new chat session",- description: "Please try again.",- });throw error;}useCopilotStreamStore@@ -348,18 +344,17 @@ export function useChatSession({});return response.data.id;} catch (error) {+ // The caller owns the one toast for this failure (see+ // toastSendFailure); toasting here as well stacked two contradictory+ // messages. A paywall is an account state, not a fault.if (- error instanceof Error &&- error.message === "Failed to create session"+ !isPaywallError(error) &&+ !(+ error instanceof Error && error.message === "Failed to create session"+ )) {- throw error; // already handled above+ Sentry.captureException(error);}- Sentry.captureException(error);- toast({- variant: "destructive",- title: "Could not start a new chat session",- description: "Please try again.",- });throw error;}}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.tsindex f17395d419..ba147a4486 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts@@ -165,20 +165,23 @@ export function useCopilotRuntimeStream({lastSubmittedKickoffExpertId: null,lastSubmittedKickoffAttemptToken: null,});+ // The backend refuses a turn over our cap (429) or without a plan (402)+ // before persisting its prompt: put the text back in an empty composer+ // and drop the bubble.+ function restoreUnsentSend() {+ if (!coord.lastSubmittedMessageText) return;+ if (kickoffExpertId) clearRecovery();+ else if (isComposerEmpty()) {+ setInitialPrompt(coord.lastSubmittedMessageText);+ clearRecovery();+ }+ runtime?.dropUnsentUserRow();+ }handleStreamError({error,providerFailure: parseProviderFailure(rawFailure),onRateLimit: (message, limitFailure, origin) => {- // The backend refuses a turn over our cap before persisting its- // prompt: put the text back in an empty composer and drop the bubble.- if (coord.lastSubmittedMessageText) {- if (kickoffExpertId) clearRecovery();- else if (isComposerEmpty()) {- setInitialPrompt(coord.lastSubmittedMessageText);- clearRecovery();- }- runtime?.dropUnsentUserRow();- }+ restoreUnsentSend();if (limitFailure && origin === "provider") {dismissedProviderFailureRef.current = null;setProviderLimit(limitFailure);@@ -188,6 +191,7 @@ export function useCopilotRuntimeStream({}},onReconnect: () => runtime?.ensureConnected(),+ onPaywall: restoreUnsentSend,isUserStoppingRef,});if (!kickoffExpertId) return;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex aa81c3941d..8b9fe22c72 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -255,57 +255,60 @@ export function useCopilotStream({clearKickoffPending(userId, kickoffExpertId, kickoffAttemptToken);}).catch(() => undefined);}- const failureForThisTurn = providerFailureRef.current;- providerFailureRef.current = null;- handleStreamError({- error,- providerFailure: failureForThisTurn,- 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- // drop the unsent bubble so the user can edit/resend after reset.- const coord = useCopilotStreamStore.getState().getCoord(sessionId);- const unsentText = coord.lastSubmittedMessageText;- if (unsentText) {- // The expert-kickoff control prompt must never surface in the- // user's composer — drop the recovery slot instead of restoring- // it. Its bubble below is dropped too; the once-per-expert- // pending latch expires so a later visit can retry the kickoff.- if (kickoffExpertId) {+ // Backend raises 429 and 402 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+ // drop the unsent bubble so the user can edit/resend.+ const restoreUnsentSend = () => {+ const coord = useCopilotStreamStore.getState().getCoord(sessionId);+ const unsentText = coord.lastSubmittedMessageText;+ if (unsentText) {+ // The expert-kickoff control prompt must never surface in the+ // user's composer — drop the recovery slot instead of restoring+ // it. Its bubble below is dropped too; the once-per-expert+ // pending latch expires so a later visit can retry the kickoff.+ if (kickoffExpertId) {+ useCopilotStreamStore.getState().updateCoord(sessionId, {+ lastSubmittedMessageText: null,+ lastSubmittedKickoffExpertId: null,+ lastSubmittedKickoffAttemptToken: null,+ });+ } else {+ // The refusal lands async — by the time it does, the user+ // may have started typing a new draft. Only restore + clear the+ // recovery slot when the composer is empty; otherwise leave the+ // unsent text in the per-session store so a reload / resume can+ // surface it later instead of silently dropping it.+ const composer = document.getElementById(+ "chat-input",+ ) as HTMLTextAreaElement | null;+ const composerEmpty = !composer || composer.value.length === 0;+ if (composerEmpty) {+ setInitialPrompt(unsentText);useCopilotStreamStore.getState().updateCoord(sessionId, {lastSubmittedMessageText: null,lastSubmittedKickoffExpertId: null,lastSubmittedKickoffAttemptToken: null,});- } else {- // The 429 callback fires async — by the time it lands, the user- // may have started typing a new draft. Only restore + clear the- // recovery slot when the composer is empty; otherwise leave the- // unsent text in the per-session store so a reload / resume can- // surface it later instead of silently dropping it.- const composer = document.getElementById(- "chat-input",- ) as HTMLTextAreaElement | null;- const composerEmpty = !composer || composer.value.length === 0;- if (composerEmpty) {- setInitialPrompt(unsentText);- useCopilotStreamStore.getState().updateCoord(sessionId, {- lastSubmittedMessageText: null,- lastSubmittedKickoffExpertId: null,- lastSubmittedKickoffAttemptToken: null,- });- }}- setMessages((prev) => {- const last = prev[prev.length - 1];- const next = last?.role === "user" ? prev.slice(0, -1) : prev;- useCopilotStreamStore- .getState()- .setMessageSnapshot(sessionId, next);- return next;- });}+ setMessages((prev) => {+ const last = prev[prev.length - 1];+ const next = last?.role === "user" ? prev.slice(0, -1) : prev;+ useCopilotStreamStore+ .getState()+ .setMessageSnapshot(sessionId, next);+ return next;+ });+ }+ };+ const failureForThisTurn = providerFailureRef.current;+ providerFailureRef.current = null;+ handleStreamError({+ error,+ providerFailure: failureForThisTurn,+ onRateLimit: (message, limitFailure, origin) => {+ restoreUnsentSend();// A provider's own limit is not answered by upgrading with us, so// it opens the continue path instead of the plan dialog.//@@ -334,6 +337,7 @@ export function useCopilotStream({}},onReconnect: () => handleReconnectRef.current(),+ onPaywall: restoreUnsentSend,isUserStoppingRef,});if (kickoffExpertId) {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.tsindex 113cb0062d..18533ccf6b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts@@ -8,7 +8,7 @@ import {type PendingUploadAttachment,type PendingUploadSend,} from "./copilotStreamStore";-import { describeSendFailure } from "./components/ChatInput/helpers";+import { toastSendFailure } from "./helpers/sendFailureToast";import type { ExpertKickoffMetadata } from "./expertKickoff";import {buildStoredAttachmentParts,@@ -349,15 +349,12 @@ export function recoverFailedDeferredSend(if (text) useCopilotUIStore.getState().setInitialPrompt(text);if (parts.length > 0)useCopilotStreamStore.getState().setPendingFileParts(parts);- toast({+ toastSendFailure({title: "Couldn't send message",- description: describeSendFailure(- error,- text- ? "your message is back in the composer"- : "your files were not sent",- ),- variant: "destructive",+ error,+ recovery: text+ ? "your message is back in the composer"+ : "your files were not sent",});}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-canceled-popup.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-canceled-popup.test.tsxindex f59318f640..30ee18aaa7 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-canceled-popup.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-canceled-popup.test.tsx@@ -201,7 +201,7 @@ describe("post-cancel popup", () => {});it.each(["billing", "onboarding"] as const)(- "sends Subscribe now from the %s card to billing and closes",+ "sends Subscribe now from the %s card to the plan confirmation and closes",async (returnTo) => {mockCancelFlow();render(<TrialCard returnTo={returnTo} />);@@ -210,7 +210,9 @@ describe("post-cancel popup", () => {within(popup).getByRole("button", { name: "Subscribe now" }),);await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());- expect(mockPush).toHaveBeenCalledExactlyOnceWith("/settings/billing");+ expect(mockPush).toHaveBeenCalledExactlyOnceWith(+ "/settings/billing?subscribe=trial-plan",+ );expect(posthog.capture).toHaveBeenCalledWith("trial_subscribe_now_clicked",{ days_left: 5 },diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-subscribe-now.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-subscribe-now.test.tsxnew file mode 100644index 0000000000..2bf9964ad5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-subscribe-now.test.tsx@@ -0,0 +1,74 @@+import { render, screen } from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import SettingsBillingPage from "../page";+import { mockBilling } from "./trial-plan-fixtures";++const mockSearchParams = vi.hoisted(() => ({+ current: new URLSearchParams(),+}));+const mockReplace = vi.hoisted(() => vi.fn());+vi.mock("next/navigation", async (importOriginal) => ({+ ...(await importOriginal<typeof import("next/navigation")>()),+ useSearchParams: () => mockSearchParams.current,+ useRouter: () => ({+ push: vi.fn(),+ replace: mockReplace,+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+ }),+ usePathname: () => "/settings/billing",+ useParams: () => ({}),+}));++vi.mock("@/hooks/useIsBillingEnabled", () => ({+ useIsBillingEnabled: () => true,+ useBillingStatus: () => ({ isBillingEnabled: true, isResolved: true }),+}));++beforeEach(() => setTrialUser());+afterEach(() => {+ setTrialUser(null);+ mockSearchParams.current = new URLSearchParams();+ mockReplace.mockReset();+});++describe("arriving from the canceled-trial popup's Subscribe now", () => {+ it("opens the trial plan's confirmation and drops the marker", async () => {+ mockSearchParams.current = new URLSearchParams({ subscribe: "trial-plan" });+ mockBilling();+ render(<SettingsBillingPage />);++ expect(+ await screen.findByRole("dialog", { name: "Start Pro today?" }),+ ).toBeDefined();+ expect(mockReplace).toHaveBeenCalledWith("/settings/billing");+ });++ it("opens nothing once a paid plan has replaced the trial", async () => {+ mockSearchParams.current = new URLSearchParams({ subscribe: "trial-plan" });+ const { state } = mockBilling(+ trialResponse({+ active: false,+ status: "canceled",+ cancel_at_period_end: true,+ }),+ );+ state.subscription = { ...state.subscription, tier: "PRO" };+ render(<SettingsBillingPage />);++ // The plan card reads "Active" only once the PRO subscription has+ // loaded, so nothing below can pass on a response still in flight.+ expect(await screen.findByText("Active")).toBeDefined();+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ expect(+ screen.queryByRole("dialog", { name: "Start Pro today?" }),+ ).toBeNull();+ expect(mockReplace).not.toHaveBeenCalledWith("/settings/billing");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.tsindex 55faab843e..cebeffb54d 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts@@ -1,10 +1,16 @@"use client";+import { useRouter, useSearchParams } from "next/navigation";import { useEffect, useState } from "react";import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";+import {+ BILLING_PATH,+ SUBSCRIBE_NOW_PARAM,+ SUBSCRIBE_NOW_VALUE,+} from "@/components/organisms/TrialCard/helpers";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";import {trackPaywallViewed,@@ -52,6 +58,15 @@ export function useTrialPlanChoices(offer: TrialOfferResponse) {if (isVisible) trackPaywallViewed("billing");}, [isVisible]);+ const router = useRouter();+ const isSubscribeNow =+ useSearchParams().get(SUBSCRIBE_NOW_PARAM) === SUBSCRIBE_NOW_VALUE;+ useEffect(() => {+ if (!isSubscribeNow || !isVisible || !userID) return;+ selectPlan(ownPlan);+ router.replace(BILLING_PATH);+ }, [isSubscribeNow, isVisible, userID]);+function selectPlan(plan: PlanChoiceDetails) {trackPlanSelected({subscription_tier: plan.tier,diff --git a/autogpt_platform/frontend/src/components/molecules/Toast/use-toast.tsx b/autogpt_platform/frontend/src/components/molecules/Toast/use-toast.tsxindex fa18b129dc..95e2a9b864 100644--- a/autogpt_platform/frontend/src/components/molecules/Toast/use-toast.tsx+++ b/autogpt_platform/frontend/src/components/molecules/Toast/use-toast.tsx@@ -10,6 +10,8 @@ export interface ToastProps {duration?: number;action?: React.ReactNode;dismissable?: boolean;+ /** Reusing a key replaces the toast already showing under it. */+ replaceKey?: string;}type ToasterToast = ToastProps & {@@ -31,12 +33,14 @@ function toast({duration = 5000,action,dismissable = true,+ replaceKey,..._props}: Toast) {const message = title || description || "";const descriptionText = title && description ? description : undefined;const toastOptions = {+ id: replaceKey,duration: dismissable ? duration : Infinity,action,description: descriptionText,diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.tsindex 859f5863d2..bf21b50100 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts@@ -7,6 +7,12 @@ export const trialPlanLabels: Record<TrialOfferResponse["tier"], string> = {BUSINESS: "Team",};+// "Subscribe now" lands on billing with this marker, which opens the trial+// plan's own confirmation there instead of leaving the person to find it.+export const SUBSCRIBE_NOW_PARAM = "subscribe";+export const SUBSCRIBE_NOW_VALUE = "trial-plan";+export const BILLING_PATH = "/settings/billing";+export function formatTrialPrice(offer: TrialOfferResponse) {const amount = currencyFormatter(offer.currency).format(getTrialChargeAmount(offer),diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCanceledDialog.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCanceledDialog.tsindex 02a146c078..254a7a180c 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCanceledDialog.ts+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCanceledDialog.ts@@ -3,7 +3,12 @@ import { TrialEvent } from "@/services/analytics/posthog-events";import { usePostHog } from "@posthog/react";import { useRouter } from "next/navigation";import { useState } from "react";-import { getTrialDaysLeft } from "./helpers";+import {+ BILLING_PATH,+ getTrialDaysLeft,+ SUBSCRIBE_NOW_PARAM,+ SUBSCRIBE_NOW_VALUE,+} from "./helpers";type EndsAt = TrialStatusResponse["ends_at"];@@ -36,7 +41,9 @@ export function useTrialCanceledDialog({ userID, endsAt }: Args) {days_left: getTrialDaysLeft(endsAt),});setOpenFor(null);- router.push("/settings/billing");+ router.push(+ `${BILLING_PATH}?${SUBSCRIBE_NOW_PARAM}=${SUBSCRIBE_NOW_VALUE}`,+ );}return {diff --git a/autogpt_platform/frontend/src/playwright/journeys/paywall-send-journey.spec.ts b/autogpt_platform/frontend/src/playwright/journeys/paywall-send-journey.spec.tsnew file mode 100644index 0000000000..39a015c90b--- /dev/null+++ b/autogpt_platform/frontend/src/playwright/journeys/paywall-send-journey.spec.ts@@ -0,0 +1,84 @@+import type { Page } from "@playwright/test";+import { CopilotPage } from "../pages/copilot.page";+import { expect, test } from "./fixtures";++const SUBSCRIPTION_PATH = "/api/proxy/api/credits/subscription";++test.use({+ // The backend's own paywall answers this send: a NO_TIER account with+ // `enable-platform-payment` on gets a 402 from session creation.+ expectedResponses: [+ { status: 402, url: "/api/proxy/api/chat/sessions", method: "POST" },+ ],+});++test("a send after the plan lapses offers one way to upgrade and keeps the message", async ({+ page,+ journeyUser: _journeyUser,+}) => {+ test.skip(+ Boolean(process.env.PLAYWRIGHT_JOURNEY_EMAIL),+ "cancels the user's plan, so it never runs as a real account",+ );+ expect(+ await currentTier(page),+ "the journey user starts on a plan (PLAYWRIGHT_JOURNEY_TIER, e.g. PRO)",+ ).not.toBe("NO_TIER");++ const copilot = new CopilotPage(page);+ // Sending before the AI connections load is refused client-side ("AI+ // connections are still loading"), which is not what this journey is about.+ const connectionsLoaded = page.waitForResponse(+ (response) =>+ response.url().includes("/api/chat/transports") && response.ok(),+ );+ await copilot.open();+ await connectionsLoaded;+ const composer = page.locator("#chat-input-empty");+ await expect(composer).toBeEditable();++ // The plan ends while the page is open: a cancelled plan or a lapsed trial+ // drops the account to NO_TIER, and nothing tells the open page.+ await cancelPlan(page);++ const message = `paywall journey ${Date.now()}`;+ await composer.fill(message);+ await composer.press("Enter");++ const toasts = page.locator("[data-sonner-toast]");+ const upgrade = toasts.getByRole("link", { name: "See plans" });+ await expect(upgrade).toBeVisible();+ await expect(+ toasts,+ "a paywalled send must show one message, not a stack of contradictory ones",+ ).toHaveCount(1);+ await expect(page.getByText("Please try again")).toHaveCount(0);+ await expect(+ composer,+ "the unsent message stays in the composer",+ ).toHaveValue(message);++ await upgrade.click();+ await expect(page).toHaveURL(/\/settings\/billing/);+ await expect(page.getByRole("heading", { name: "Billing" })).toBeVisible();+ await expect(toasts).toHaveCount(0);+});++async function currentTier(page: Page) {+ const status = await page.request.get(SUBSCRIPTION_PATH);+ expect(status.ok(), `reading the plan failed: ${status.status()}`).toBe(true);+ return (await status.json()).tier as string;+}++// A plan granted without Stripe (no customer) is downgraded in the database at+// once, the same state a lapsed trial or an ended subscription leaves.+async function cancelPlan(page: Page) {+ const cancel = await page.request.post(SUBSCRIPTION_PATH, {+ data: { tier: "NO_TIER" },+ });+ expect(+ cancel.ok(),+ `cancelling the plan failed: ${cancel.status()} ${await cancel.text()}`,+ ).toBe(true);+ expect(await currentTier(page)).toBe("NO_TIER");+}diff --git a/autogpt_platform/frontend/src/services/network-status/useNetworkStatus.ts b/autogpt_platform/frontend/src/services/network-status/useNetworkStatus.tsindex 472a6e0e90..d5a2e1e6db 100644--- a/autogpt_platform/frontend/src/services/network-status/useNetworkStatus.ts+++ b/autogpt_platform/frontend/src/services/network-status/useNetworkStatus.ts@@ -3,17 +3,29 @@import { useEffect } from "react";import { toast } from "sonner";+// One slot for both states, so "Connection restored" replaces "You're+// offline" instead of stacking on it. Pinned to the top: the default+// bottom-center sits over the chat composer and swallows clicks on it.+const NETWORK_TOAST = { id: "network-status", position: "top-center" } as const;+// Explicit because a replacement keeps the old toast's options: without it+// "Connection restored" inherits the offline toast's Infinity and never goes.+const RESTORED_DURATION_MS = 4_000;+export function useNetworkStatus() {useEffect(function monitorNetworkStatus() {function handleOnline() {toast.success("Connection restored", {+ ...NETWORK_TOAST,description: "You're back online",+ duration: RESTORED_DURATION_MS,});}function handleOffline() {toast.error("You're offline", {+ ...NETWORK_TOAST,description: "Check your internet connection",+ duration: Infinity,});}