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(frontend/copilot): send at reset, the out-of-budget panel for Max, and a running-low hint (#15403)
Nicholas Tindle57aa6d0c7c16
diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.pyindex a2f7e847e6..66b9aaf7ec 100644--- a/autogpt_platform/backend/backend/blocks/autopilot.py+++ b/autogpt_platform/backend/backend/blocks/autopilot.py@@ -736,10 +736,12 @@ class AutoPilotBlock(Block):def _out_of_budget_message(pause: "TurnPause") -> str:"""What a graph run shows for a turn refused for want of budget.- The executor runs a block turn on the credit balance once the plan's- allowance is used up, so a refusal means the balance can't pay for one- either: the message says both, how to add credits, and when the- allowance resets, if it does.+ Where credits can pay for block turns (``credits_can_pay_block_turns``),+ the executor runs one on the credit balance once the plan's allowance is+ used up, so a refusal means the balance can't pay for it either: the+ message says both and how to add credits. Elsewhere it says only that the+ allowance is used up. Either way it ends with when the allowance resets,+ if it does."""allowance = "the trial's" if pause.reason == "trial" else "your plan's"credits_url = f"{Settings().config.frontend_base_url.rstrip('/')}/profile/credits"diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.pyindex 65fec252c4..d85494c65f 100644--- a/autogpt_platform/backend/backend/executor/scheduler.py+++ b/autogpt_platform/backend/backend/executor/scheduler.py@@ -2971,9 +2971,9 @@ class Scheduler(AppService):if job is None:return Falsejob.remove()- # Its index row stays: a row with no job is skipped on read, while the- # chat's next turn at reset reuses this id, so deleting the row could- # hide a job set again meanwhile from the chat's listing.+ # Its index row stays for the next listing to drop. The chat's next+ # turn at reset reuses this id, and that drop puts back the row of a+ # job set again meanwhile, which a delete here would not.self._invalidate_jobs_cache()logger.info(f"Removed {kind}-at-reset job for session {session_id[:12]}")return True@@ -3341,6 +3341,7 @@ class Scheduler(AppService):return full_scan()if self.scheduler.running:self._delete_schedule_index_rows(dangling)+ self._restore_reused_index_rows(dangling)return jobsdef _upsert_schedule_index_row(@@ -3373,6 +3374,30 @@ class Scheduler(AppService):except Exception:logger.warning("Failed to remove stale schedule index rows", exc_info=True)+ def _restore_reused_index_rows(self, job_ids: list[str]) -> None:+ """Put back the row of any job set again under one of *job_ids*, the+ rows just dropped for having no job.++ A chat's turn at the budget reset reuses its id, so a new one can be+ set between a listing finding the old job gone and the drop, and the+ drop would hide it from the chat's listings until the next reconcile.+ Every schedule is added before its row is written, so reading the job+ after the drop catches each such row.+ """+ for job_id in job_ids:+ try:+ job = self.scheduler.get_job(job_id, jobstore=Jobstores.EXECUTION.value)+ except Exception:+ logger.warning(+ "Could not load job %s to check its dropped index row",+ job_id,+ exc_info=True,+ )+ continue+ info = _job_to_info(job) if job else None+ if info is not None:+ self._upsert_schedule_index_row(job_id, info)+def _mark_schedule_index_ready(self, failure_version: int) -> None:with self._jobs_cache_lock:if self._schedule_index_failure_version == failure_version:@@ -3445,6 +3470,7 @@ class Scheduler(AppService):if not self.scheduler.running:returnindex.delete_many(confirmed_gone)+ self._restore_reused_index_rows(confirmed_gone)self._mark_schedule_index_ready(failure_version)logger.info(diff --git a/autogpt_platform/backend/backend/executor/scheduler_index_read_test.py b/autogpt_platform/backend/backend/executor/scheduler_index_read_test.pyindex 00ae786ef8..aafc4025aa 100644--- a/autogpt_platform/backend/backend/executor/scheduler_index_read_test.py+++ b/autogpt_platform/backend/backend/executor/scheduler_index_read_test.py@@ -2,6 +2,7 @@from unittest.mock import MagicMock, patch+from backend.copilot.at_reset import at_reset_schedule_idfrom backend.executor.schedule_index_test_helpers import (_graph_job_kwargs,_mock_job,@@ -128,6 +129,70 @@ def test_get_schedule_jobs_loads_candidates_and_drops_dangling_rows():assert scheduler._schedule_index.all_job_ids() == {"live"}+def _at_reset_send() -> CopilotTurnJobArgs:+ return CopilotTurnJobArgs(+ schedule_id=at_reset_schedule_id("send", "sess-1"),+ user_id="u1",+ session_id="sess-1",+ message="Draft the launch post",+ cron="0 0 * * *",+ )+++def _set_again_after_one_miss(scheduler: Scheduler, args: CopilotTurnJobArgs):+ """The job is gone at the first lookup, then set again under its id."""+ set_again = _mock_job(args.model_dump(mode="json"))+ lookups = iter([None])+ scheduler.scheduler.get_job.side_effect = lambda job_id, jobstore=None: next(+ lookups, set_again+ )+++def test_get_schedule_jobs_keeps_the_row_of_a_turn_set_again_under_its_id():+ # A chat's turn at the reset reuses its id: one set again between the+ # listing finding the old job gone and dropping its row keeps the row.+ scheduler = _scheduler_with_index()+ index = scheduler._schedule_index+ assert index is not None+ args = _at_reset_send()+ index.upsert(_index_entry(args.schedule_id, args))+ _set_again_after_one_miss(scheduler, args)++ with patch.object(scheduler, "_get_active_jobs_cached"):+ scheduler._get_schedule_jobs(+ user_id="u1",+ graph_id=None,+ session_id="sess-1",+ kind=None,+ organization_id=None,+ )++ assert index.all_job_ids() == {args.schedule_id}+++def test_get_schedule_jobs_leaves_a_row_dropped_when_its_job_cant_be_read_again():+ # Nothing shows a turn was set again, so the listing still answers and the+ # next reconcile restores the row if one was.+ scheduler = _scheduler_with_index()+ index = scheduler._schedule_index+ assert index is not None+ args = _at_reset_send()+ index.upsert(_index_entry(args.schedule_id, args))+ scheduler.scheduler.get_job.side_effect = [None, RuntimeError("store down")]++ with patch.object(scheduler, "_get_active_jobs_cached"):+ jobs = scheduler._get_schedule_jobs(+ user_id="u1",+ graph_id=None,+ session_id="sess-1",+ kind=None,+ organization_id=None,+ )++ assert jobs == []+ assert index.all_job_ids() == set()++def test_get_schedule_jobs_index_error_falls_back_to_full_scan():scheduler = _scheduler_with_index()full_scan = [MagicMock()]@@ -269,3 +334,20 @@ def test_reconcile_rebuilds_index_and_keeps_racing_rows():assert index.all_job_ids() == {"in-store", "racing"}assert scheduler._schedule_index_ready is True+++def test_reconcile_keeps_the_row_of_a_turn_set_again_during_the_sweep():+ scheduler = _scheduler_with_index()+ index = scheduler._schedule_index+ assert index is not None+ in_store = GraphExecutionJobArgs(**_graph_job_kwargs("in-store", "u1", "g1"))+ scheduler.scheduler.get_jobs.return_value = [+ _mock_job(in_store.model_dump(mode="json"))+ ]+ args = _at_reset_send()+ index.upsert(_index_entry(args.schedule_id, args))+ _set_again_after_one_miss(scheduler, args)++ scheduler._reconcile_schedule_index()++ assert index.all_job_ids() == {"in-store", args.schedule_id}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxindex caae9959c7..ba3bbaa265 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -76,6 +76,7 @@ function ChatHostBody({sessionChatStatus,sessionSentFrom,sessionAutopilotMode,+ chatLlmAuthProvider,expertIdentity,isResolvingExpertIdentity,isAdoptingExpertSession,@@ -106,6 +107,8 @@ function ChatHostBody({usageFailure={platformLimitFailure}onDismissUsage={dismissAfterProviderChange}usageRefresh={usageRefresh}+ usage={usage}+ chatAuthProvider={chatLlmAuthProvider}messages={messages}status={status}error={error}@@ -150,6 +153,7 @@ function ChatHostBody({failure={platformLimitFailure}sessionId={sessionId}onDismiss={dismissRateLimit}+ onSendNow={onSend}/><ProviderLimitDialogfailure={providerLimit}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/budget-helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/budget-helpers.tsxnew file mode 100644index 0000000000..3e47434b0a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/budget-helpers.tsx@@ -0,0 +1,219 @@+import {+ getGetV2GetChatShareStateMockHandler200,+ getGetV2GetCopilotUsageMockHandler200,+ getGetV2GetPendingMessagesMockHandler200,+ getGetV2ListChatConnectionsMockHandler200,+ getGetV2ListChatTransportsMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { getGetSubscriptionStatusMockHandler200 } from "@/app/api/__generated__/endpoints/credits/credits.msw";+import { getGetTrialsGetTrialStatusMockHandler200 } from "@/app/api/__generated__/endpoints/trials/trials.msw";+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import type { AtResetTurn } from "@/app/api/__generated__/models/atResetTurn";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";+import type { SubscriptionTier } from "@/app/api/__generated__/models/subscriptionTier";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";+import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";+import OnboardingProvider from "@/providers/onboarding/onboarding-provider";+import { ProActivationProvider } from "@/services/pro-activation/ProActivationProvider";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import { NuqsTestingAdapter } from "nuqs/adapters/testing";+import type { ReactNode } from "react";+import { CopilotChatHost } from "../CopilotChatHost";+import { sessionHandler, TEST_SESSION_ID } from "./sse-helpers";++// Local wall-clock times, so the copy reads the same in any time zone.+export const SATURDAY_1AM = new Date(2026, 9, 10, 1, 0);+export const SATURDAY_848PM = new Date(2026, 9, 10, 20, 48);+export const SUNDAY_1AM = new Date(2026, 9, 11, 1, 0);+export const MONDAY_1AM = new Date(2026, 9, 12, 1, 0);+export const MONDAY_107AM = new Date(2026, 9, 12, 1, 7);++export function weeklyExhausted(+ over: Partial<CoPilotUsagePublic> = {},+): CoPilotUsagePublic {+ return {+ tier: "MAX",+ daily: { percent_used: 100, resets_at: SUNDAY_1AM },+ weekly: { percent_used: 100, resets_at: MONDAY_1AM },+ reset_cost: 0,+ state: "exhausted",+ limiting_window: "weekly",+ resets_at: MONDAY_1AM,+ ...over,+ };+}++const NOT_A_TRIAL: TrialStatusResponse = {+ active: false,+ converted: true,+ eligible: false,+ offer: null,+ ends_at: null,+ status: "active",+};++export function connection(+ provider: "platform" | "codex" | "microsoft_365_copilot",+): AIConnectionOffer {+ const names = {+ platform: "AutoGPT Platform",+ codex: "ChatGPT",+ microsoft_365_copilot: "Microsoft 365 Copilot",+ };+ return {+ offer_id:+ provider === "platform" ? "platform:deployment" : `${provider}:c1`,+ provider_family: provider,+ auth_provider: provider,+ display_name: names[provider],+ auth_method: provider === "platform" ? "deployment" : "oauth",+ credential_id: provider === "platform" ? null : "c1",+ backed_by_label: "",+ description: "",+ state: "ready",+ selectable: true,+ is_default: provider === "platform",+ tiers: [],+ limitations: [],+ lock_reason: null,+ unlock_href: null,+ };+}++interface ChatSetup {+ usage: CoPilotUsagePublic;+ provider?: "platform" | "codex" | "microsoft_365_copilot";+ offers?: AIConnectionOffer[];+ trial?: TrialStatusResponse;+}++/** The endpoints a chat reads around its AutoPilot budget, pinned. */+export function budgetHandlers({+ usage,+ provider = "platform",+ offers = [connection("platform")],+ trial = NOT_A_TRIAL,+}: ChatSetup) {+ return [+ sessionHandler({+ metadata: {+ dry_run: false,+ builder_graph_id: null,+ llm_auth_provider: provider,+ },+ }),+ getGetV2GetCopilotUsageMockHandler200(usage),+ getGetSubscriptionStatusMockHandler200({+ tier: (usage.tier ?? "PRO") as SubscriptionTier,+ monthly_cost: 0,+ tier_costs: { PRO: 5000, MAX: 32000 },+ proration_credit_cents: 0,+ }),+ getGetTrialsGetTrialStatusMockHandler200(trial),+ getGetV2GetPendingMessagesMockHandler200({ count: 0, messages: [] }),+ getGetV2ListChatConnectionsMockHandler200({ offers }),+ getGetV2GetChatShareStateMockHandler200({+ is_shared: false,+ share_token: null,+ auto_share_executions: false,+ message_count: 0,+ linked_run_count: 0,+ file_count: 0,+ }),+ getGetV2ListChatTransportsMockHandler200({+ transports: [+ {+ auth_provider: "platform",+ credential_id: null,+ label: "AutoGPT",+ available: true,+ default: true,+ },+ ],+ }),+ ];+}++/** The at-reset endpoints, backed by a list the test can read. */+export function fakeAtReset(jobs: AtResetTurn[] = []) {+ const state = {+ jobs: [...jobs],+ scheduled: [] as { sessionId: string; body: unknown }[],+ cancelled: [] as string[],+ refusal: null as "not_out_of_budget" | "no_reset" | null,+ // The longest a single message may be; the real server allows 64,000.+ maxMessageChars: Infinity,+ };+ const handlers = [+ http.get("*/api/chat/sessions/:sessionId/at-reset", () =>+ HttpResponse.json({ jobs: state.jobs }),+ ),+ http.post(+ "*/api/chat/sessions/:sessionId/at-reset",+ async ({ request, params }) => {+ const body = (await request.json()) as {+ kind: "send";+ message: string;+ };+ state.scheduled.push({ sessionId: String(params.sessionId), body });+ if (state.refusal) {+ return HttpResponse.json({ detail: state.refusal }, { status: 409 });+ }+ // As the server does: a send joins the message already waiting.+ const waiting = state.jobs.find((j) => j.kind === body.kind);+ const message = waiting?.message+ ? `${waiting.message}\n\n${body.message}`+ : body.message;+ if (message.length > state.maxMessageChars) {+ return HttpResponse.json(+ { detail: "message_too_long" },+ { status: 413 },+ );+ }+ const job = { kind: body.kind, run_at: MONDAY_107AM, message };+ state.jobs = [...state.jobs.filter((j) => j.kind !== body.kind), job];+ return HttpResponse.json(job);+ },+ ),+ http.delete(+ "*/api/chat/sessions/:sessionId/at-reset/:kind",+ ({ params }) => {+ state.cancelled.push(String(params.kind));+ state.jobs = state.jobs.filter((job) => job.kind !== params.kind);+ return new HttpResponse(null, { status: 204 });+ },+ ),+ ];+ return { state, handlers };+}++export function renderChat(+ searchParams: string = `?sessionId=${TEST_SESSION_ID}`,+) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function Providers({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <NuqsTestingAdapter searchParams={searchParams} hasMemory>+ <BackendAPIProvider>+ <OnboardingProvider>+ <TooltipProvider>+ <ProActivationProvider>{children}</ProActivationProvider>+ </TooltipProvider>+ </OnboardingProvider>+ </BackendAPIProvider>+ </NuqsTestingAdapter>+ </QueryClientProvider>+ );+ }+ const view = render(+ <CopilotChatHost droppedFiles={[]} onDroppedFilesConsumed={() => {}} />,+ { wrapper: Providers },+ );+ return { ...view, queryClient };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/out-of-budget.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/out-of-budget.test.tsxnew file mode 100644index 0000000000..9331295f9b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/out-of-budget.test.tsx@@ -0,0 +1,537 @@+import { getGetV2GetCopilotUsageQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";+import {+ getGetV2GetCopilotUsageMockHandler200,+ getPostV2CreateSessionMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { server } from "@/mocks/mock-server";+import {+ assistantTextChunks,+ copilotStreamErrorHandler,+ streamSseResponse,+} from "@/tests/integrations/copilot-sse";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { resetCopilotChatRegistry } from "../copilotChatRegistry";+import { useCopilotStreamStore } from "../copilotStreamStore";+import { useCopilotUIStore } from "../store";+import {+ budgetHandlers,+ connection,+ fakeAtReset,+ MONDAY_1AM,+ renderChat,+ SATURDAY_1AM,+ SATURDAY_848PM,+ SUNDAY_1AM,+ weeklyExhausted,+} from "./budget-helpers";+import { TEST_BACKEND_BASE_URL, TEST_SESSION_ID } from "./sse-helpers";++vi.mock("@/services/environment", async (importActual) => {+ const actual = await importActual<typeof import("@/services/environment")>();+ return {+ ...actual,+ environment: {+ ...actual.environment,+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,+ },+ };+});++vi.mock("../helpers", async (importActual) => {+ const actual = await importActual<typeof import("../helpers")>();+ return {+ ...actual,+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),+ };+});++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: { id: "test-user" },+ isUserLoading: false,+ isLoggedIn: true,+ }),+}));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useGetFlag: (flag: string) => flag === actual.Flag.ENABLE_PLATFORM_PAYMENT,+ useFlagStatus: () => ({ enabled: false, ready: true }),+ };+});++const toast = vi.hoisted(() => vi.fn());++vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast,+ useToast: () => ({ toast, dismiss: vi.fn() }),+}));++const SCHEDULE_PLACEHOLDER = "Write now, and it sends when your budget resets…";++beforeEach(() => {+ toast.mockClear();+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(SATURDAY_1AM);+ resetCopilotChatRegistry();+ useCopilotStreamStore.getState().resetAll();+ useCopilotUIStore.setState({ initialPrompt: null });+ sessionStorage.clear();+ setTrialUser("test-user");+});++afterEach(() => {+ vi.useRealTimers();+ useAuthStore.setState({ user: null, hasLoadedUser: false });+});++function composer() {+ return screen.getByLabelText(/chat message input/i) as HTMLTextAreaElement;+}++function scheduledChip() {+ return screen.queryByRole("status", { name: "Scheduled message" });+}++async function scheduleDraft(text: string) {+ const user = userEvent.setup();+ const input = await screen.findByPlaceholderText(SCHEDULE_PLACEHOLDER);+ await waitFor(() =>+ expect((input as HTMLTextAreaElement).disabled).toBe(false),+ );+ await user.type(input, text);+ await user.click(screen.getByRole("button", { name: "Send at reset" }));+ return user;+}++describe("Send at reset", () => {+ it("schedules the draft, shows when it sends, and Edit and Cancel take it back", async () => {+ const atReset = fakeAtReset();+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted() }),+ ...atReset.handlers,+ );+ renderChat();++ const user = await scheduleDraft("Draft the launch post");++ const chip = await screen.findByRole("status", {+ name: "Scheduled message",+ });+ expect(within(chip).getByText("Sends Monday at 1:07 AM")).toBeDefined();+ expect(within(chip).getByText("Draft the launch post")).toBeDefined();+ expect(atReset.state.scheduled).toEqual([+ {+ sessionId: TEST_SESSION_ID,+ body: { kind: "send", message: "Draft the launch post" },+ },+ ]);+ expect(composer().value).toBe("");++ await user.click(within(chip).getByRole("button", { name: "Edit" }));+ await waitFor(() => expect(scheduledChip()).toBeNull());+ expect(atReset.state.cancelled).toEqual(["send"]);+ expect(composer().value).toBe("Draft the launch post");++ await user.click(screen.getByRole("button", { name: "Send at reset" }));+ const rescheduled = await screen.findByRole("status", {+ name: "Scheduled message",+ });+ expect(atReset.state.scheduled).toHaveLength(2);+ await user.click(+ within(rescheduled).getByRole("button", { name: "Cancel" }),+ );+ await waitFor(() => expect(scheduledChip()).toBeNull());+ expect(atReset.state.cancelled).toEqual(["send", "send"]);+ expect(atReset.state.jobs).toEqual([]);+ expect(composer().value).toBe("");+ });++ it("adds a second message to the one already waiting instead of replacing it", async () => {+ const atReset = fakeAtReset();+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted() }),+ ...atReset.handlers,+ );+ renderChat();+ await scheduleDraft("Draft the launch post");+ await screen.findByRole("status", { name: "Scheduled message" });++ await scheduleDraft("Also the changelog");++ await waitFor(() => expect(atReset.state.scheduled).toHaveLength(2));+ // The client posts what was written; the server joins it on.+ expect(atReset.state.scheduled[1].body).toEqual({+ kind: "send",+ message: "Also the changelog",+ });+ expect(atReset.state.jobs[0].message).toBe(+ "Draft the launch post\n\nAlso the changelog",+ );+ const chip = await screen.findByRole("status", {+ name: "Scheduled message",+ });+ expect(within(chip).getByText(/Also the changelog/)).toBeDefined();+ expect(within(chip).getByText(/Draft the launch post/)).toBeDefined();+ });++ it("says when a message is too long to join the one waiting, and keeps it", async () => {+ const atReset = fakeAtReset();+ atReset.state.maxMessageChars = 40;+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted() }),+ ...atReset.handlers,+ );+ renderChat();+ await scheduleDraft("Draft the launch post");+ await screen.findByRole("status", { name: "Scheduled message" });++ await scheduleDraft("Also the changelog for this week");++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Couldn’t schedule your message",+ description:+ "Too long to add to the message already waiting — your message is back in the composer.",+ }),+ ),+ );+ expect(composer().value).toBe("Also the changelog for this week");+ expect(atReset.state.jobs[0].message).toBe("Draft the launch post");+ });++ it("still shows the scheduled message after a reload", async () => {+ const atReset = fakeAtReset();+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted() }),+ ...atReset.handlers,+ );+ const first = renderChat();+ await scheduleDraft("Draft the launch post");+ await screen.findByRole("status", { name: "Scheduled message" });+ first.unmount();++ renderChat();+ const chip = await screen.findByRole("status", {+ name: "Scheduled message",+ });+ expect(within(chip).getByText("Sends Monday at 1:07 AM")).toBeDefined();+ expect(within(chip).getByText("Draft the launch post")).toBeDefined();+ });++ it("sends right away when the budget turns out to be back", async () => {+ const atReset = fakeAtReset();+ atReset.state.refusal = "not_out_of_budget";+ const streamed: string[] = [];+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted() }),+ ...atReset.handlers,+ http.post(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ async ({ request }) => {+ streamed.push(await request.clone().text());+ return streamSseResponse(assistantTextChunks("On it."), {+ abortSignal: request.signal,+ });+ },+ ),+ );+ renderChat();++ await scheduleDraft("Draft the launch post");++ await waitFor(() => expect(streamed).toHaveLength(1));+ expect(streamed[0]).toContain("Draft the launch post");+ expect(scheduledChip()).toBeNull();+ });++ it("schedules the message a refused send put back, from the plan dialog", async () => {+ const atReset = fakeAtReset();+ let usageReads = 0;+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted() }),+ ...atReset.handlers,+ copilotStreamErrorHandler({+ baseUrl: TEST_BACKEND_BASE_URL,+ sessionId: TEST_SESSION_ID,+ status: 429,+ body: {+ detail: {+ kind: "usage_limit",+ message: "You've reached your weekly usage limit.",+ authProvider: "platform",+ credentialId: null,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ },+ },+ }),+ );+ server.use(+ getGetV2GetCopilotUsageMockHandler200(() =>+ usageReads++ === 0+ ? weeklyExhausted({+ state: "ok",+ limiting_window: null,+ resets_at: null,+ daily: null,+ weekly: null,+ })+ : weeklyExhausted(),+ ),+ );+ renderChat();++ const user = userEvent.setup();+ const input = (await screen.findByPlaceholderText(+ "What else can I help with?",+ )) as HTMLTextAreaElement;+ await waitFor(() => expect(input.disabled).toBe(false));+ await user.type(input, "Draft the launch post");+ await user.click(screen.getByRole("button", { name: "Submit" }));++ const dialog = await screen.findByRole("dialog", undefined, {+ timeout: 5000,+ });+ await within(dialog).findByText(+ "You’re out of AutoPilot budget for this week",+ undefined,+ { timeout: 5000 },+ );+ await user.click(+ within(dialog).getByRole("button", { name: "Send at reset" }),+ );++ await screen.findByRole("status", { name: "Scheduled message" });+ expect(atReset.state.scheduled).toEqual([+ {+ sessionId: TEST_SESSION_ID,+ body: { kind: "send", message: "Draft the launch post" },+ },+ ]);+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(composer().value).toBe("");+ });++ it("creates the chat first from the new-chat screen, then schedules it", async () => {+ const atReset = fakeAtReset();+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted() }),+ ...atReset.handlers,+ getPostV2CreateSessionMockHandler200({+ id: "new-chat-1",+ created_at: "2026-10-10T06:00:00Z",+ user_id: "test-user",+ }),+ );+ renderChat("");++ await scheduleDraft("Plan the offsite");++ const chip = await screen.findByRole(+ "status",+ { name: "Scheduled message" },+ { timeout: 5000 },+ );+ expect(within(chip).getByText("Sends Monday at 1:07 AM")).toBeDefined();+ expect(atReset.state.scheduled).toEqual([+ {+ sessionId: "new-chat-1",+ body: { kind: "send", message: "Plan the offsite" },+ },+ ]);+ });+});++describe("Out of AutoPilot budget", () => {+ it("gives a top-tier plan the reset time, the meters, and ChatGPT to continue on", async () => {+ server.use(+ ...budgetHandlers({+ usage: weeklyExhausted(),+ offers: [+ connection("platform"),+ connection("microsoft_365_copilot"),+ connection("codex"),+ ],+ }),+ );+ renderChat();++ const notice = await screen.findByRole("status", { name: "Usage notice" });+ await within(notice).findByText(+ "You’re out of AutoPilot budget for this week",+ );+ expect(+ within(notice).getByText(+ "It resets Monday at 1:00 AM, in 2 days. You can still browse, edit workflows and read results.",+ ),+ ).toBeDefined();+ for (const meter of ["Today", "This week"]) {+ expect(+ within(notice)+ .getByRole("progressbar", { name: meter })+ .getAttribute("aria-valuenow"),+ ).toBe("100");+ }+ expect(+ await within(notice).findByRole("button", {+ name: "Continue on ChatGPT",+ }),+ ).toBeDefined();+ expect(screen.getByRole("button", { name: "Send at reset" })).toBeDefined();+ expect(screen.queryByText(/budget left/)).toBeNull();+ });++ it("never offers Microsoft 365 Copilot to continue on", async () => {+ let offersRead = 0;+ server.use(...budgetHandlers({ usage: weeklyExhausted() }));+ server.use(+ http.get("*/api/chat/connections", () => {+ offersRead += 1;+ return HttpResponse.json({+ offers: [connection("platform"), connection("microsoft_365_copilot")],+ });+ }),+ );+ renderChat();++ await screen.findByText("You’re out of AutoPilot budget for this week");+ await waitFor(() => expect(offersRead).toBeGreaterThan(0));+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(screen.queryByRole("button", { name: /Continue on/ })).toBeNull();+ });++ it.each([+ [+ "a spent trial allowance",+ {+ tier: "TRIAL" as const,+ daily: null,+ limiting_window: "trial" as const,+ resets_at: null,+ },+ trialResponse({ usage_policy: "lifetime", allowance_used_percent: 100 }),+ ],+ [+ "an account without a plan",+ { tier: "NO_TIER" as const, resets_at: null },+ undefined,+ ],+ ])(+ "offers only an upgrade for %s, which never refills",+ async (_, over, trial) => {+ server.use(...budgetHandlers({ usage: weeklyExhausted(over), trial }));+ renderChat();++ const notice = await screen.findByRole("status", {+ name: "Usage notice",+ });+ expect(+ await within(notice).findByRole("button", { name: /^Start Pro/ }),+ ).toBeDefined();+ expect(within(notice).queryByText(/resets|refreshes/)).toBeNull();+ expect(+ screen.queryByRole("button", { name: "Send at reset" }),+ ).toBeNull();+ expect(screen.queryByPlaceholderText(SCHEDULE_PLACEHOLDER)).toBeNull();+ expect(+ screen.getByRole("button", { name: "Submit" }).hasAttribute("disabled"),+ ).toBe(true);+ },+ );++ it("lets a trial wait for its own weekly cap, which does refill", async () => {+ server.use(+ ...budgetHandlers({+ usage: weeklyExhausted({+ tier: "TRIAL",+ daily: { percent_used: 40, resets_at: SUNDAY_1AM },+ }),+ trial: trialResponse({+ usage_policy: "lifetime",+ allowance_used_percent: 60,+ }),+ }),+ );+ renderChat();++ await screen.findByText("You’re out of AutoPilot budget for this week");+ expect(+ await screen.findByRole("button", { name: "Send at reset" }),+ ).toBeDefined();+ });++ it("doesn't lock a ChatGPT chat, which its own plan pays for", async () => {+ server.use(+ ...budgetHandlers({ usage: weeklyExhausted(), provider: "codex" }),+ );+ const { queryClient } = renderChat();++ await waitFor(() =>+ expect(+ queryClient.getQueryState(getGetV2GetCopilotUsageQueryKey())?.status,+ ).toBe("success"),+ );+ const user = userEvent.setup();+ const input = await screen.findByPlaceholderText(+ "What else can I help with?",+ );+ await user.type(input, "Keep going");+ expect(+ screen.getByRole("button", { name: "Submit" }).hasAttribute("disabled"),+ ).toBe(false);+ expect(screen.queryByRole("status", { name: "Usage notice" })).toBeNull();+ });+});++describe("Running low", () => {+ it.each([+ ["an open chat", `?sessionId=${TEST_SESSION_ID}`],+ ["the new-chat screen", ""],+ ])("warns under the composer in %s", async (_, searchParams) => {+ vi.setSystemTime(SATURDAY_848PM);+ server.use(+ ...budgetHandlers({+ usage: {+ tier: "PRO",+ daily: { percent_used: 86, resets_at: SUNDAY_1AM },+ weekly: { percent_used: 61, resets_at: MONDAY_1AM },+ reset_cost: 0,+ state: "low",+ limiting_window: "daily",+ resets_at: SUNDAY_1AM,+ },+ }),+ );+ renderChat(searchParams);++ expect(+ await screen.findByText(+ "About 14% of today’s budget left. A long task may pause partway.",+ ),+ ).toBeDefined();+ // One small gauge for the window that is running low, not a meter per+ // window: under the composer, every line costs typing room on a phone.+ expect(+ screen+ .getByRole("progressbar", { name: "Today" })+ .getAttribute("aria-valuenow"),+ ).toBe("86");+ expect(screen.queryByRole("progressbar", { name: "This week" })).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsxindex 767e2f294f..4a3cc023e3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx@@ -330,6 +330,23 @@ function renderResumedSession(return { getResumeRequests: () => resumeRequests };}+/**+ * The replay streams through Streamdown, which renders a text part's updates+ * in a transition. The replayed persisted half mounts empty at its+ * `text-start` and fills in a commit after the half behind it, which mounted+ * with its text. So wait until a replayed row (not a hydrated `-seq-N` one)+ * shows `text`, then check that is the only copy on the page.+ */+async function expectReplayedOnce(text: string) {+ const hydratedRow = `[data-message-id^="${TEST_SESSION_ID}-seq-"]`;+ await waitFor(() =>+ expect(+ screen.getAllByText(text).some((el) => !el.closest(hydratedRow)),+ ).toBe(true),+ );+ expect(screen.getAllByText(text)).toHaveLength(1);+}+beforeEach(() => {resetChatRuntimes();// Message snapshots are keyed by session id in a module-level store, so@@ -368,7 +385,7 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {// The heart of the regression: the replay re-emits the persisted half,// so leaving the `-seq-N` hydrated message in place would show it twice// (two assistant bubbles, two tool chains) for one backend turn.- expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ await expectReplayedOnce(PERSISTED_HALF);},);@@ -421,7 +438,7 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {"midturn-pm-1","resumed-turn-2",]);- expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ await expectReplayedOnce(PERSISTED_HALF);expect(screen.getAllByText(MIDTURN_FOLLOWUP)).toHaveLength(1);},);@@ -459,7 +476,7 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {]);expect(ids).not.toContain(`promoted-midturn-${TEST_SESSION_ID}-seq-5`);expect(screen.getAllByText(MIDTURN_FOLLOWUP)).toHaveLength(1);- expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ await expectReplayedOnce(PERSISTED_HALF);},);@@ -485,7 +502,7 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {// the only copy — it must survive the resume cut. The assistant halves// still come from the replay alone.expect(screen.getAllByText(MIDTURN_FOLLOWUP)).toHaveLength(1);- expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ await expectReplayedOnce(PERSISTED_HALF);expect(screen.getAllByText(REPLAYED_HALF)).toHaveLength(1);expect(screen.getAllByText(RESUMED_PROMPT)).toHaveLength(1);expect(@@ -572,7 +589,7 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {expect(screen.getAllByText(EARLIER_PROMPT)).toHaveLength(1);// The running turn's persisted half is still trimmed, so the replay// does not double it.- expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ await expectReplayedOnce(PERSISTED_HALF);},);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 03b5aa1177..2034013b22 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@@ -21,6 +21,11 @@ import { EmptySession } from "../EmptySession/EmptySession";import { UsageLimitReachedCard } from "../UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard";import type { UsageNoticeContext } from "../UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard";import { useIsUsageLimitReached } from "../UsageLimits/useIsUsageLimitReached";+import { BudgetLowHint } from "../UsageLimits/BudgetLowHint";+import { ScheduledSendChip } from "../SendAtReset/ScheduledSendChip";+import { SESSION_COMPOSER_ID, sessionDraftKey } from "../SendAtReset/helpers";+import { useComposerBudget } from "./useComposerBudget";+import type { UsageSnapshot } from "@/services/usageExperience/useUsageExperience";import { TaskProgressBar } from "../TaskProgressBar/TaskProgressBar";import { getLatestTaskList } from "../TaskProgressBar/helpers";import { ContextPanelToggle } from "../ContextPanel/ContextPanelToggle";@@ -62,6 +67,12 @@ export interface ChatContainerProps {usageFailure?: import("../../providerFailure").ProviderFailure | null;onDismissUsage?: () => void;usageRefresh?: UsageNoticeContext["refresh"];+ /** The account's AutoPilot budget: drives Send at reset and the+ * running-low hint. */+ usage?: UsageSnapshot | null;+ /** The connection the chat runs on, or for a new chat the one it will+ * start on. Only a platform chat waits for the AutoPilot budget. */+ chatAuthProvider?: string | null;messages: UIMessage<unknown, UIDataTypes, UITools>[];status: string;error: Error | undefined;@@ -171,6 +182,8 @@ export const ChatContainer = ({usageFailure,onDismissUsage,usageRefresh,+ usage = null,+ chatAuthProvider = null,isResolvingExpertIdentity,isAdoptingExpertSession,isKickoffStarting,@@ -198,12 +211,9 @@ export const ChatContainer = ({// state from the backend).const isSessionUnavailable =!!isReconnecting || isLoadingSession || !!isSessionError;- const isUsageExhausted = useIsUsageLimitReached(sessionId);+ const isUsageExhausted = useIsUsageLimitReached(chatAuthProvider);const isLimitReached = isUsageExhausted || isUsageRefused;const [isUsageTooltipOpen, setIsUsageTooltipOpen] = useState(false);- useEffect(() => {- if (!isLimitReached) setIsUsageTooltipOpen(false);- }, [isLimitReached]);const isInputDisabled =isSessionUnavailable || !!isResolvingExpertIdentity || !!isKickoffStarting;// A fired (archived) expert's threads stay as read-only history — the@@ -227,6 +237,25 @@ export const ChatContainer = ({// across renders — otherwise every consumer of `guardedOnSend` (the actions// provider, ChatInput, EmptySession, handleRetry) re-renders on each pass.const guardedOnSend = isTurnLocked ? NO_OP_SEND : onSend;+ const composer = useComposerBudget({+ sessionId,+ authProvider: chatAuthProvider,+ budget: usage?.budget,+ isLimitReached,+ isOtherwiseLocked: isTurnLocked,+ onSend,+ onCreateSession,+ inputId: SESSION_COMPOSER_ID,+ });+ // While a turn still runs, the limit keeps follow-ups from queueing.+ const atReset = isStreaming ? undefined : composer.atReset;+ // Send at reset takes the paused tooltip's place. Radix reports no close+ // for a tooltip held shut, so an open recorded then would show it, unhovered,+ // once a turn starts: record none, and forget one Send at reset cut short.+ const canShowUsageTooltip = Boolean(isLimitReached && !atReset);+ useEffect(() => {+ if (!canShowUsageTooltip) setIsUsageTooltipOpen(false);+ }, [canShowUsageTooltip]);const isVoiceModeEnabled = useGetFlag(Flag.COPILOT_VOICE_MODE);const isAutoModeEnabled = useGetFlag(Flag.COPILOT_AUTO_MODE);@@ -431,7 +460,7 @@ export const ChatContainer = ({) : (<ChatComposerFrameclassName={cn(hasComposerTab && "max-lg:pt-0")}- paused={isLimitReached}+ paused={isLimitReached && !atReset}noticeRef={usageCardRef}notice={isLimitReached ? (@@ -454,26 +483,38 @@ export const ChatContainer = ({/></div>)}+ {composer.scheduled.pending && (+ <ScheduledSendChip+ job={composer.scheduled.pending}+ onEdit={() => void composer.scheduled.edit()}+ onCancel={() => void composer.scheduled.cancel()}+ isBusy={composer.scheduled.isBusy}+ />+ )}<Tooltip- open={Boolean(isLimitReached && isUsageTooltipOpen)}+ open={canShowUsageTooltip && isUsageTooltipOpen}onOpenChange={(open) =>- setIsUsageTooltipOpen(open && isLimitReached)+ setIsUsageTooltipOpen(open && canShowUsageTooltip)}><TooltipTrigger asChild><div><ChatInput- inputId="chat-input-session"- draftKey={`session:${sessionId}`}+ inputId={SESSION_COMPOSER_ID}+ draftKey={sessionDraftKey(sessionId)}onSend={guardedOnSend}disabled={isInputDisabled}- sendDisabled={isLimitReached}+ sendDisabled={isLimitReached && !atReset}+ atReset={atReset}isStreaming={isStreaming}isTurnStarting={status === "submitted"}isUploadingFiles={isUploadingFiles}onStop={onStop}onEnqueue={onEnqueue}- placeholder="What else can I help with?"+ placeholder={+ (atReset && composer.placeholder) ||+ "What else can I help with?"+ }droppedFiles={droppedFiles}onDroppedFilesConsumed={onDroppedFilesConsumed}hasSession={!!sessionId}@@ -520,6 +561,9 @@ export const ChatContainer = ({editing it.</TooltipContent></Tooltip>+ {composer.showLowHint && usage && (+ <BudgetLowHint usage={usage} />+ )}</ChatComposerFrame>)}</div>@@ -543,7 +587,20 @@ export const ChatContainer = ({isUploadingFiles={isUploadingFiles}droppedFiles={droppedFiles}onDroppedFilesConsumed={onDroppedFilesConsumed}- isInteractionLocked={isSendLocked || !!isAdoptingExpertSession}+ isInteractionLocked={+ (isSendLocked && !composer.atReset) || !!isAdoptingExpertSession+ }+ atReset={composer.atReset}+ usageNotice={+ isLimitReached ? (+ <UsageLimitReachedCard refresh={usageRefresh} />+ ) : undefined+ }+ lowHint={+ composer.showLowHint && usage ? (+ <BudgetLowHint usage={usage} />+ ) : undefined+ }isKickoffStarting={isKickoffStarting}expertName={expertIdentity?.name}expertId={expertIdentity?.id ?? null}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsxindex eb7ddd1625..e5006b44b3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx@@ -2,6 +2,7 @@ import React from "react";import { getGetV2GetChatShareStateMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";import type { ChatShareStateResponse } from "@/app/api/__generated__/models/chatShareStateResponse";import { server } from "@/mocks/mock-server";+import { getUsageExperience } from "@/services/usageExperience/helpers";import {act,render,@@ -205,6 +206,22 @@ const baseProps = {historicalDurations: new Map<string, number>(),};+// A platform chat whose daily budget is out and resets: the composer offers+// Send at reset in place of the paused notice.+const sendAtResetProps = {+ chatAuthProvider: "platform",+ usage: {+ budget: {+ state: "exhausted" as const,+ window: "daily" as const,+ resetsAt: new Date("2026-10-16T00:00:00Z"),+ percentUsed: 100,+ },+ usage: undefined,+ experience: getUsageExperience(),+ },+};+describe("ChatContainer", () => {beforeEach(() => {mockIsUsageLimitReached.mockReturnValue(false);@@ -289,6 +306,38 @@ describe("ChatContainer", () => {expect(screen.queryByRole("tooltip")).toBeNull();});+ it("doesn't pop the usage tooltip open when a turn starts after Send at reset hid it", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ mockIsUsageLimitReached.mockReturnValue(true);+ const atReset = { ...baseProps, ...sendAtResetProps };+ const { rerender } = render(<ChatContainer {...atReset} />);+ const trigger = screen.getByTestId("chat-input").parentElement!;++ await hoverUsageTooltipTrigger(trigger);+ expect(screen.queryByRole("tooltip")).toBeNull();+ fireEvent.pointerLeave(trigger, { pointerType: "mouse" });+ // A running turn ends Send at reset while the limit still holds.+ rerender(<ChatContainer {...atReset} status="streaming" />);++ expect(screen.queryByRole("tooltip")).toBeNull();+ });++ it("doesn't reopen a usage tooltip Send at reset closed once a turn starts", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ mockIsUsageLimitReached.mockReturnValue(true);+ const { rerender } = render(<ChatContainer {...baseProps} />);+ const trigger = screen.getByTestId("chat-input").parentElement!;+ await hoverUsageTooltipTrigger(trigger);+ expect(screen.getByRole("tooltip")).toBeDefined();++ const atReset = { ...baseProps, ...sendAtResetProps };+ rerender(<ChatContainer {...atReset} />);+ fireEvent.pointerLeave(trigger, { pointerType: "mouse" });+ rerender(<ChatContainer {...atReset} status="streaming" />);++ expect(screen.queryByRole("tooltip")).toBeNull();+ });+it("keeps the draft editable while the usage notice pauses sending", () => {mockIsUsageLimitReached.mockReturnValue(true);render(<ChatContainer {...baseProps} />);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/new-chat-onboarding.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/new-chat-onboarding.test.tsxindex 5838c5d111..67e1d37176 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/new-chat-onboarding.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/new-chat-onboarding.test.tsx@@ -1,3 +1,5 @@+import { getGetV2GetCopilotUsageMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { getGetSubscriptionStatusMockHandler200 } from "@/app/api/__generated__/endpoints/credits/credits.msw";import { server } from "@/mocks/mock-server";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import {@@ -8,7 +10,7 @@ import {waitFor,} from "@/tests/integrations/test-utils";import { http, HttpResponse } from "msw";-import { describe, expect, test, vi } from "vitest";+import { beforeEach, describe, expect, test, vi } from "vitest";import { ChatContainer, type ChatContainerProps } from "../ChatContainer";vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {@@ -63,6 +65,28 @@ function mockOnboarding(completed = false) {return request;}+// The chat locks on the AutoPilot budget, and onboarding stays hidden while it+// does: pin a budget with room left instead of faker's random usage and tier.+beforeEach(() => {+ server.use(+ getGetV2GetCopilotUsageMockHandler200({+ tier: "PRO",+ daily: null,+ weekly: null,+ reset_cost: 0,+ state: "ok",+ limiting_window: null,+ resets_at: null,+ }),+ getGetSubscriptionStatusMockHandler200({+ tier: "PRO",+ monthly_cost: 0,+ tier_costs: {},+ proration_credit_cents: 0,+ }),+ );+});+describe("new full-page expert chats", () => {test("keeps draft answers when onboarding status refetches", async () => {mockOnboarding();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useComposerBudget.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useComposerBudget.tsnew file mode 100644index 0000000000..957459ac8c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useComposerBudget.ts@@ -0,0 +1,58 @@+import {+ getResetWait,+ type UsageBudget,+} from "@/services/usageExperience/budget";+import { SEND_AT_RESET_PLACEHOLDER } from "../SendAtReset/helpers";+import { useScheduledSendHandoff } from "../SendAtReset/scheduledSendHandoff";+import { useHandedOffSend } from "../SendAtReset/useHandedOffSend";+import { useScheduledSend } from "../SendAtReset/useScheduledSend";+import { spendsPlatformBudget } from "../usageHelpers";++interface Args {+ sessionId: string | null;+ authProvider?: string | null;+ budget?: UsageBudget | null;+ isLimitReached: boolean;+ /** A lock that waiting for the budget doesn't lift (an archived expert). */+ isOtherwiseLocked: boolean;+ onSend: (message: string) => void | Promise<void>;+ onCreateSession: () => void | Promise<string>;+ inputId: string;+}++export function useComposerBudget({+ sessionId,+ authProvider,+ budget,+ isLimitReached,+ isOtherwiseLocked,+ onSend,+ onCreateSession,+ inputId,+}: Args) {+ const isPlatformChat = spendsPlatformBudget(authProvider);+ const canWaitForReset =+ isLimitReached &&+ !isOtherwiseLocked &&+ isPlatformChat &&+ getResetWait(budget) !== null;+ const scheduled = useScheduledSend({ sessionId, onSendNow: onSend, inputId });+ useHandedOffSend(sessionId, scheduled.scheduleQuietly);++ // A new chat has no session to set the send on: create it, then hand the+ // message to its composer, which sets the send once the page is on it.+ async function scheduleInNewChat(message: string) {+ const created = await onCreateSession();+ if (typeof created !== "string") throw new Error("Couldn’t start a chat");+ useScheduledSendHandoff.getState().hold(created, message);+ }++ return {+ atReset: canWaitForReset+ ? { onSchedule: sessionId ? scheduled.schedule : scheduleInNewChat }+ : undefined,+ placeholder: canWaitForReset ? SEND_AT_RESET_PLACEHOLDER : undefined,+ showLowHint: isPlatformChat && !isLimitReached && budget?.state === "low",+ scheduled,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsxindex 5c080cce91..91cc4254e3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx@@ -28,6 +28,7 @@ import {workspaceItemToAttachment,} from "../../helpers/workspaceAttachments";import type { PickedItem } from "./components/WorkspaceFilePicker/useWorkspaceFilePicker";+import { AtResetFilesNotice } from "./components/AtResetFilesNotice";import { AttachmentCapNotice } from "./components/AttachmentCapNotice";import {ComposerPlusMenu,@@ -46,6 +47,10 @@ import { WorkspaceFilePicker } from "./components/WorkspaceFilePicker/WorkspaceFimport { useCopilotUIStore } from "../../store";import { isTokenDevtoolEnabled } from "../../tokenDevtool/gate";import { TokenDevtoolBadge } from "../TokenDevtoolBadge/TokenDevtoolBadge";+import {+ sendAtResetFailureTitle,+ SEND_AT_RESET_LABEL,+} from "../SendAtReset/helpers";import {CARD_ICON_BUTTON_CLASS,CARD_SEND_BUTTON_CLASS,@@ -118,6 +123,9 @@ interface Props {expertId?: string | null;/** Names that expert in the picker's filter row. */expertName?: string | null;+ /** Out of AutoPilot budget with a reset ahead: the text stays editable and+ * submitting sets it to send at the reset. Text only. */+ atReset?: { onSchedule: (message: string) => Promise<void> };}export function ChatInput({@@ -146,6 +154,7 @@ export function ChatInput({variant = "default",expertId = null,expertName = null,+ atReset,}: Props) {const { isDryRun, setIsDryRun } = useCopilotUIStore();// Still the CHAT_MODE_OPTION flag, which no longer names what it gates: the@@ -189,35 +198,39 @@ export function ChatInput({// during normal streaming (users can type and queue the next message).const isTextareaDisabled = disabled || isUploadingFiles;+ async function sendWithAttachments(message: string) {+ const { localFiles, workspaceAttachments } =+ partitionAttachments(attachments);+ // Chips clear eagerly for the same reason the text does (see+ // useChatInput.handleSend); a failed send restores them unless the+ // user already attached new ones in the meantime.+ const sent = attachments;+ setAttachments([]);+ setRefusedCount(0);+ try {+ await onSend(+ message,+ localFiles.length > 0 ? localFiles : undefined,+ workspaceAttachments.length > 0 ? workspaceAttachments : undefined,+ );+ } catch (error) {+ setAttachments((prev) => (prev.length > 0 ? prev : sent));+ throw error;+ }+ }+const { value, setValue, handleSubmit, handleEnqueue, isEnqueueing } =useChatInput({- onSend: async (message: string) => {- const { localFiles, workspaceAttachments } =- partitionAttachments(attachments);- // Chips clear eagerly for the same reason the text does (see- // useChatInput.handleSend); a failed send restores them unless the- // user already attached new ones in the meantime.- const sent = attachments;- setAttachments([]);- setRefusedCount(0);- try {- await onSend(- message,- localFiles.length > 0 ? localFiles : undefined,- workspaceAttachments.length > 0 ? workspaceAttachments : undefined,- );- } catch (error) {- setAttachments((prev) => (prev.length > 0 ? prev : sent));- throw error;- }- },+ onSend: atReset?.onSchedule ?? sendWithAttachments,onEnqueue,isStreaming,hasAttachments,- disabled: isTextareaDisabled || sendDisabled,- canSendEmpty: hasAttachments,+ // A scheduled send carries text only, so attachments hold it back.+ disabled: isTextareaDisabled || (atReset ? hasAttachments : sendDisabled),+ canSendEmpty: hasAttachments && !atReset,inputId,draftKey,+ failureTitle: atReset ? sendAtResetFailureTitle : undefined,});const integrations = useConnectedIntegrations(expertId);@@ -274,7 +287,7 @@ export function ChatInput({}function handlePaste(e: ClipboardEvent<HTMLElement>) {- if (isBusy) return;+ if (isBusy || atReset) return;const files = getFilesFromClipboard(e.clipboardData);if (files.length === 0) return;e.preventDefault();@@ -291,8 +304,9 @@ export function ChatInput({const devtoolSessionId = isTokenDevtoolEnabled() ? sessionId : null;const canSend =!disabled &&- !sendDisabled &&- (!!value.trim() || hasAttachments) &&+ (atReset+ ? !!value.trim() && !hasAttachments+ : !sendDisabled && (!!value.trim() || hasAttachments)) &&!isRecording &&!isTranscribing;@@ -437,6 +451,9 @@ export function ChatInput({className={stacked ? undefined : "mt-1.5"}/>)}+ {atReset && hasAttachments && (+ <AtResetFilesNotice className={stacked ? undefined : "mt-1.5"} />+ )}<FileChipsattachments={attachments}onRemove={handleRemoveAttachment}@@ -464,7 +481,7 @@ export function ChatInput({onFilesSelected={handleFilesSelected}onUseWorkspaceFile={() => setIsPickerOpen(true)}onClearGuidedPrompt={handleClearGuidedPrompt}- disabled={isBusy}+ disabled={isBusy || !!atReset}isAtCap={isAtCap}extraItems={plusMenuItems}className={@@ -583,6 +600,14 @@ export function ChatInput({/>) : isStreaming ? (<StopButton onStop={onStop} className={sendButtonClass} />+ ) : atReset ? (+ <PromptInputSubmit+ disabled={!canSend}+ aria-label={SEND_AT_RESET_LABEL}+ className={cn(sendButtonClass, "!w-auto px-4 font-medium")}+ >+ {SEND_AT_RESET_LABEL}+ </PromptInputSubmit>) : hideSubmitWhenEmpty && !canSend ? null : (<PromptInputSubmitdisabled={!canSend}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsxindex 9d5b0ba1b2..71364cce85 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx@@ -919,6 +919,25 @@ describe("ChatInput clipboard paste", () => {expect(files).toHaveLength(1);});+ it("says why Send at reset is off for files attached before it", async () => {+ const onSchedule = vi.fn().mockResolvedValue(undefined);+ const { rerender } = render(<ChatInput onSend={vi.fn()} />);+ const textarea = screen.getByTestId("textarea") as HTMLTextAreaElement;+ const image = new File(["png-bytes"], "image.png", { type: "image/png" });+ pasteFiles(textarea, [image]);+ expect(screen.queryByText(/Only text can wait for the reset/)).toBeNull();++ // The budget runs out with the file still attached.+ rerender(<ChatInput onSend={vi.fn()} atReset={{ onSchedule }} />);+ fireEvent.change(textarea, { target: { value: "see screenshot" } });+ fireEvent.submit(textarea.closest("form")!);++ expect(+ await screen.findByText(/Only text can wait for the reset/),+ ).toBeDefined();+ expect(onSchedule).not.toHaveBeenCalled();+ });+it("keeps the original name of pasted non-generic files", async () => {const onSend = vi.fn().mockResolvedValue(undefined);render(<ChatInput onSend={onSend} />);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/chatDraft.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/chatDraft.test.tsxindex 4003314f8d..ee37cd3941 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/chatDraft.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/chatDraft.test.tsx@@ -16,6 +16,7 @@ vi.mock("@/app/(platform)/copilot/store", () => ({notifyMessageSent: vi.fn(),}),}));+import { useChatDraftAccess } from "../useChatDraft";import { useChatInput } from "../useChatInput";beforeEach(() => {@@ -164,3 +165,36 @@ describe("platform chat drafts", () => {).toBe("");});});+describe("acting on a draft without showing it", () => {+ it("reads what was typed, and writes it back where the composer shows it", () => {+ const draft = renderHook(() => useChatDraftAccess("session:chat-quiet"));+ const composer = renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-quiet" }),+ );+ act(() => composer.result.current.setValue("Then the newsletter"));+ expect(draft.result.current.read()).toBe("Then the newsletter");+ act(() =>+ draft.result.current.write((current) => `Draft the post\n\n${current}`),+ );+ expect(composer.result.current.value).toBe(+ "Draft the post\n\nThen the newsletter",+ );+ });+ it("still reads what was typed when browser storage refuses it", () => {+ const setItem = vi+ .spyOn(window.sessionStorage, "setItem")+ .mockImplementation(() => {+ throw new Error("QuotaExceededError");+ });+ try {+ const draft = renderHook(() => useChatDraftAccess("session:chat-full"));+ const composer = renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-full" }),+ );+ act(() => composer.result.current.setValue("Kept on this page"));+ expect(draft.result.current.read()).toBe("Kept on this page");+ } finally {+ setItem.mockRestore();+ }+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AtResetFilesNotice.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AtResetFilesNotice.tsxnew file mode 100644index 0000000000..3abd1d0a6e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AtResetFilesNotice.tsx@@ -0,0 +1,29 @@+"use client";++import { Icon } from "@/components/atoms/Icon/Icon";+import { cn } from "@/lib/utils";+import { Alert02Icon } from "@hugeicons/core-free-icons";++interface Props {+ className?: string;+}++/** Why Send at reset is off while files are attached: a message set for the+ * reset carries text only. */+export function AtResetFilesNotice({ className }: Props) {+ return (+ <div+ role="status"+ className={cn(+ "flex w-full items-center gap-1.5 rounded-2xl bg-amber-50 px-3 py-1.5 text-sm text-amber-800",+ className,+ )}+ >+ <Icon icon={Alert02Icon} className="h-4 w-4 shrink-0" aria-hidden />+ <span className="min-w-0 flex-1">+ Only text can wait for the reset. Remove the files to schedule this+ message.+ </span>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatDraft.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatDraft.tsindex 0fb5125e37..8f64e6a90b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatDraft.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatDraft.ts@@ -2,6 +2,9 @@ import { useEffect, useRef, useState, type SetStateAction } from "react";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";const subscribers = new Map<string, Set<(value: string) => void>>();+// Each draft as last set on this page, for a reader that doesn't follow it+// while browser storage is unavailable.+const written = new Map<string, string>();function readDraft(key: string | null) {if (!key || typeof window === "undefined") return "";@@ -14,6 +17,7 @@ function readDraft(key: string | null) {function writeDraft(key: string | null, value: string) {if (!key || typeof window === "undefined") return;+ written.set(key, value);try {if (value) sessionStorage.setItem(key, value);else sessionStorage.removeItem(key);@@ -23,12 +27,15 @@ function writeDraft(key: string | null, value: string) {subscribers.get(key)?.forEach((receive) => receive(value));}-export function useChatDraft(draftKey?: string) {+function useDraftKey(draftKey?: string) {const userID = useAuthStore((state) => state.user?.id);- const key =- draftKey && userID- ? `autogpt:chat-draft:${encodeURIComponent(userID)}:${encodeURIComponent(draftKey)}`- : null;+ return draftKey && userID+ ? `autogpt:chat-draft:${encodeURIComponent(userID)}:${encodeURIComponent(draftKey)}`+ : null;+}++export function useChatDraft(draftKey?: string) {+ const key = useDraftKey(draftKey);const [snapshot, setSnapshot] = useState(() => ({key,value: readDraft(key),@@ -74,3 +81,16 @@ export function useChatDraft(draftKey?: string) {}return [visible.value, setValue] as const;}++/** The draft for a hook that acts on it without showing it. It is read when+ * asked rather than followed, so typing doesn't re-render the hook's host. */+export function useChatDraftAccess(draftKey?: string) {+ const key = useDraftKey(draftKey);+ function read() {+ return (key && written.get(key)) ?? readDraft(key);+ }+ function write(update: SetStateAction<string>) {+ writeDraft(key, typeof update === "function" ? update(read()) : update);+ }+ return { read, write };+}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 aae40d8533..7253da6135 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@@ -17,6 +17,8 @@ interface Args {canSendEmpty?: boolean;inputId?: string;draftKey?: string;+ /** Names what failed in the toast, e.g. a scheduled send. */+ failureTitle?: string | ((error: unknown) => string);}export function useChatInput({@@ -28,6 +30,7 @@ export function useChatInput({canSendEmpty = false,inputId = "chat-input",draftKey,+ failureTitle = "Couldn't send message",}: Args) {const [value, setValue] = useChatDraft(draftKey);const [isSending, setIsSending] = useState(false);@@ -91,7 +94,10 @@ export function useChatInput({} catch (error) {setValue((current) => restoreFailedDraft(current, message));toastSendFailure({- title: "Couldn't send message",+ title:+ typeof failureTitle === "function"+ ? failureTitle(error)+ : failureTitle,error,recovery: "your message is back in the composer",});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsxindex 97cd276061..60963ab441 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx@@ -4,7 +4,8 @@ import { ChatInput } from "@/app/(platform)/copilot/components/ChatInput/ChatInpimport { useAuth } from "@/lib/auth/hooks/useAuth";import { cn } from "@/lib/utils";import { motion } from "framer-motion";-import type { ReactNode } from "react";+import type { ComponentProps, ReactNode } from "react";+import { SEND_AT_RESET_PLACEHOLDER } from "../SendAtReset/helpers";import {getExpertInputPlaceholder,getGreetingName,@@ -44,6 +45,13 @@ interface Props {voiceToggle?: ReactNode;/** The chat's approval-mode selector. Absent when the flag is off. */modeSelector?: ReactNode;+ /** Out of AutoPilot budget with a reset ahead: the composer sets the new+ * chat's first message to send at the reset. */+ atReset?: ComponentProps<typeof ChatInput>["atReset"];+ /** Shown above the composer while sending is paused. */+ usageNotice?: ReactNode;+ /** The running-low hint, shown under the composer. */+ lowHint?: ReactNode;}export function EmptySession({@@ -58,6 +66,9 @@ export function EmptySession({expertId = null,voiceToggle,modeSelector,+ atReset,+ usageNotice,+ lowHint,}: Props) {const { user } = useAuth();const greetingName = getGreetingName(user);@@ -129,7 +140,7 @@ export function EmptySession({prompts={intro.prompts}transcript={intro.transcript}onSelectPrompt={onSend}- disabled={isComposerDisabled}+ disabled={isComposerDisabled || !!atReset}/>) : intro.isAwaitingGreeting ? (// Behind the welcome modal's blur and for as long as the@@ -167,6 +178,9 @@ export function EmptySession({: "mx-auto w-full max-w-[42rem]"),)}>+ {usageNotice && (+ <div className="mb-3 text-left">{usageNotice}</div>+ )}<ChatInputinputId="chat-input-empty"draftKey={`new:${selectedExpert?.id ?? expertId ?? "default"}`}@@ -175,11 +189,14 @@ export function EmptySession({modeSelector={modeSelector}onSend={onSend}disabled={isComposerDisabled}+ atReset={atReset}isUploadingFiles={isUploadingFiles}placeholder={- selectedExpert- ? getExpertInputPlaceholder(selectedExpert.name)- : inputPlaceholder+ atReset+ ? SEND_AT_RESET_PLACEHOLDER+ : selectedExpert+ ? getExpertInputPlaceholder(selectedExpert.name)+ : inputPlaceholder}className={cn("w-full max-md:[&_[data-slot=input-group-control]]:min-h-16",@@ -193,6 +210,7 @@ export function EmptySession({intro.isVisible ? recipientPicker : undefined}/>+ {lowHint}</div></div>)}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.tsindex f8b3d925f0..8183060626 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts@@ -38,6 +38,18 @@ function chatgpt(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {});}+function microsoft365(): AIConnectionOffer {+ return offer({+ offer_id: "microsoft_365_copilot:cred-9",+ provider_family: "microsoft",+ auth_provider: "microsoft_365_copilot",+ display_name: "Microsoft 365 Copilot",+ auth_method: "oauth",+ credential_id: "cred-9",+ is_default: false,+ });+}+function limitOn(authProvider: string | null,credentialId: string | null = null,@@ -103,6 +115,62 @@ describe("alternativeConnection", () => {expect(found).toBeNull();});+ it("continues an out-of-budget platform chat on ChatGPT, never Microsoft 365 Copilot", () => {+ expect(+ alternativeConnection([offer(), microsoft365()], limitOn("platform")),+ ).toBeNull();+ expect(+ alternativeConnection(+ [offer(), microsoft365(), chatgpt()],+ limitOn("platform"),+ )?.display_name,+ ).toBe("ChatGPT");+ });++ it("never offers Microsoft 365 Copilot when ChatGPT runs out either", () => {+ // It answers plain messages: none of AutoPilot's tools, none of the task.+ expect(+ alternativeConnection(+ [offer({ selectable: false }), microsoft365(), chatgpt()],+ limitOn("codex", "cred-1"),+ ),+ ).toBeNull();+ });++ it("knows the connection that failed by its provider, not its id", () => {+ expect(+ alternativeConnection(+ [+ offer({ selectable: false }),+ chatgpt({ offer_id: "personal-account" }),+ ],+ limitOn("codex", "cred-1"),+ ),+ ).toBeNull();+ });++ it("goes by each connection's provider, not the shape of its id", () => {+ const workAccount = { ...microsoft365(), offer_id: "work-account" };+ const personal = chatgpt({ offer_id: "personal-account" });++ expect(+ alternativeConnection(+ [offer(), workAccount, personal],+ limitOn("platform"),+ ),+ ).toEqual({+ display_name: "ChatGPT",+ auth_provider: "codex",+ credential_id: "cred-1",+ });+ expect(+ alternativeConnection(+ [offer({ selectable: false }), workAccount],+ limitOn("codex", "cred-1"),+ ),+ ).toBeNull();+ });+it("has nothing to offer when there are no other connections", () => {expect(alternativeConnection([], limitOn("codex", "cred-1"))).toBeNull();expect(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/helpers.tsindex 9770e3f374..1f026a139d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/helpers.ts@@ -14,8 +14,11 @@ export interface Alternative {** The PRD's priority order starts with the platform, because it is the one* connection a user is guaranteed to be able to fall back to. Anything else- * that is selectable will do after that; the one thing excluded is the- * connection that just refused the turn, which would fail again immediately.+ * that is selectable will do after that; excluded are the connection that+ * just refused the turn, which would fail again immediately, and Microsoft+ * 365 Copilot, which answers plain messages with none of AutoPilot's tools or+ * the task so far, so it can't carry a task on. Out of AutoPilot budget, a+ * chat continues on ChatGPT only.*/export function alternativeConnection(offers: AIConnectionOffer[] | undefined,@@ -27,6 +30,9 @@ export function alternativeConnection((offer) =>offer.selectable &&!isTheOneThatFailed(offer, failure) &&+ offer.auth_provider !== "microsoft_365_copilot" &&+ (failure.authProvider !== "platform" ||+ offer.auth_provider === "codex") &&(offer.auth_method === "deployment" || offer.credential_id !== null),);if (usable.length === 0) return null;@@ -36,9 +42,7 @@ export function alternativeConnection(return {display_name: platform.display_name,- auth_provider: platform.offer_id.split(- ":",- )[0] as ChangeSessionConnectionRequestLlmAuthProvider,+ auth_provider: platform.auth_provider,credential_id: platform.credential_id ?? null,};}@@ -47,8 +51,7 @@ function isTheOneThatFailed(offer: AIConnectionOffer,failure: ProviderFailure,): boolean {- const provider = offer.offer_id.split(":")[0];- if (provider !== failure.authProvider) return false;+ if (offer.auth_provider !== failure.authProvider) return false;// A provider with no credential is a single connection, so the provider// matching is enough. With one, only the account that failed is excluded --// a second ChatGPT account has its own quota.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.tsindex 417dcc9515..88ead920c9 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts@@ -56,9 +56,11 @@ export function useProviderLimitDialog({usePutV2ChangeTheConnectionAnExistingChatRunsOn({mutation: {onSuccess: async () => {- // The composer already holds the message the provider refused, so- // the user resends when they are ready. Never automatic: the whole- // point is that moving the bill is their call.+ // What follows the switch is the caller's: the limit dialog leaves+ // the refused message in the composer for the user to resend, and+ // the Paused card picks its task up, as its button said it would.+ // The switch itself only ever comes from the user's click, since+ // moving the bill is their call.await Promise.all([queryClient.invalidateQueries({queryKey: getGetV2ListChatConnectionsQueryKey(),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 ce9ebbfd35..2b80c0df72 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@@ -5,6 +5,8 @@ import type { ProviderFailure } from "../../providerFailure";import { useProviderLimitDialog } from "../ProviderLimitDialog/useProviderLimitDialog";import { RateLimitResetDialog } from "./RateLimitResetDialog";import { useUsageActions } from "@/services/usageExperience/useUsageActions";+import { getResetWait } from "@/services/usageExperience/budget";+import { useSendDraftAtReset } from "../SendAtReset/useSendDraftAtReset";interface Props {rateLimitMessage: string | null;@@ -13,6 +15,8 @@ interface Props {onDismiss: () => void;onRefreshingChange?: (refreshing: boolean) => void;refreshState?: ReturnType<typeof useRateLimitRefresh>;+ /** Sends the draft now if "Send at reset" finds the budget already back. */+ onSendNow?: (message: string) => void | Promise<void>;}export function RateLimitGate({@@ -22,6 +26,7 @@ export function RateLimitGate({onDismiss,onRefreshingChange,refreshState,+ onSendNow,}: Props) {const state = useUsageActions();const localRefresh = useRateLimitRefresh(@@ -38,6 +43,12 @@ export function RateLimitGate({onDismiss();},});+ const { sendDraftAtReset, isScheduling } = useSendDraftAtReset({+ sessionId,+ onSendNow,+ onClose: onDismiss,+ });+ const wait = getResetWait(state.budget);const failureWindow = /\b(weekly|daily|trial)\b/i.exec(rateLimitMessage ?? "")?.[1]?.toLowerCase();@@ -60,6 +71,12 @@ export function RateLimitGate({alternative={alternative}onContinue={continueHere}isSwitching={isSwitching}+ wait={wait}+ meters={state.usage}+ onSendAtReset={+ sessionId && wait ? () => void sendDraftAtReset() : undefined+ }+ isSchedulingAtReset={isScheduling}/>);}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 cfc2a7cb90..67629807ec 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@@ -15,8 +15,14 @@ import {} from "@/services/usageExperience/helpers";import { formatPaymentDue } from "@/services/usageExperience/payment";import { usagePresentation } from "@/services/usageExperience/presentation";+import {+ budgetOutTitle,+ budgetResetSentence,+ type ResetWait,+} from "@/services/usageExperience/budget";import { useRouter } from "next/navigation";import type { ComponentProps } from "react";+import { ResetWaitBox } from "./components/ResetWaitBox";interface Props {isOpen: boolean;@@ -34,6 +40,11 @@ interface Props {alternative?: { display_name: string } | null;onContinue?: () => void;isSwitching?: boolean;+ /** The reset a blocked chat can wait for, when it has one. */+ wait?: ResetWait | null;+ meters?: ComponentProps<typeof ResetWaitBox>["meters"];+ onSendAtReset?: () => void;+ isSchedulingAtReset?: boolean;}export function RateLimitResetDialog({@@ -52,6 +63,10 @@ export function RateLimitResetDialog({alternative,onContinue,isSwitching,+ wait = null,+ meters,+ onSendAtReset,+ isSchedulingAtReset,}: Props) {const router = useRouter();const model =@@ -64,6 +79,10 @@ export function RateLimitResetDialog({},});const copy = usagePresentation(model, offer?.usageMultiplier);+ // A top-tier plan has no upgrade to lead with, so waiting for the reset+ // leads instead.+ const waitTitle =+ wait && model.isTopTier ? budgetOutTitle(wait.window) : null;const payment = formatPaymentDue(model.payment);const fallbackTitle =failureWindow === "trial"@@ -97,7 +116,7 @@ export function RateLimitResetDialog({? "One moment. Your work is saved.": unavailable? fallbackTitle- : copy.title}+ : (waitTitle ?? copy.title)}</Text></div>}@@ -133,7 +152,7 @@ export function RateLimitResetDialog({unmask={!payment}className="mb-5 !text-sm !leading-6 !text-zinc-500">- {copy.description}+ {waitTitle && wait ? budgetResetSentence(wait) : copy.description}</Text>{copy.trialSpent && (<div className="mb-5">@@ -144,6 +163,13 @@ export function RateLimitResetDialog({/></div>)}+ {wait && (+ <ResetWaitBox+ meters={meters}+ onSendAtReset={onSendAtReset}+ isScheduling={isSchedulingAtReset}+ />+ )}{isBillingEnabled && model.targetTier && (<PlanOffertier={model.targetTier}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 439643ca90..6201555b4d 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@@ -120,6 +120,84 @@ describe("Usage limit dialog", () => {fireEvent.click(screen.getByRole("button", { name: "Try again" }));expect(retry).toHaveBeenCalledOnce();});+ it("leads a top-tier plan with the reset, the meters and Send at reset", () => {+ const onSendAtReset = vi.fn();+ render(+ <RateLimitResetDialog+ isOpen+ onClose={vi.fn()}+ experience={getUsageExperience({ ...usage, tier: "MAX" })}+ wait={{ window: "weekly", resetsAt: new Date(Date.now() + 3e8) }}+ meters={usage}+ onSendAtReset={onSendAtReset}+ />,+ );+ expect(+ screen.getByText("You’re out of AutoPilot budget for this week"),+ ).toBeDefined();+ expect(screen.queryByText("A little pause. Everything is saved.")).toBe(+ null,+ );+ expect(screen.getByText(/^It resets \w+ at .+, in 3 days\./)).toBeDefined();+ expect(screen.getAllByRole("progressbar")).toHaveLength(2);+ fireEvent.click(screen.getByRole("button", { name: "Send at reset" }));+ expect(onSendAtReset).toHaveBeenCalledOnce();+ expect(screen.getByRole("link", { name: "Contact us" })).toBeDefined();+ });+ it("keeps the upgrade as the lead for other plans and names the reset once", () => {+ const resetsAt = new Date(Date.now() + 6.03e6);+ const pro = {+ ...usage,+ daily: { percent_used: 100, resets_at: resetsAt },+ weekly: { ...usage.weekly, percent_used: 62 },+ state: "exhausted",+ limiting_window: "daily" as const,+ resets_at: resetsAt,+ };+ render(+ <RateLimitResetDialog+ isOpen+ onClose={vi.fn()}+ experience={getUsageExperience(pro)}+ wait={{ window: "daily", resetsAt }}+ meters={pro}+ onSendAtReset={vi.fn()}+ />,+ );+ expect(screen.getByText("You’ve hit today’s limit")).toBeDefined();+ expect(+ screen.getByText(+ /^You can continue .+, or upgrade to Max for more usage\.$/,+ ),+ ).toBeDefined();+ expect(screen.queryByText(/It resets/)).toBeNull();+ expect(screen.getAllByRole("progressbar")).toHaveLength(2);+ expect(screen.getByRole("button", { name: "Send at reset" })).toBeDefined();+ expect(+ screen.getByRole("button", { name: "Upgrade to Max" }),+ ).toBeDefined();+ });+ it("offers no waiting when the window allows nothing", () => {+ render(+ <RateLimitResetDialog+ isOpen+ onClose={vi.fn()}+ experience={getUsageExperience({+ ...usage,+ tier: "NO_TIER",+ state: "exhausted",+ limiting_window: "weekly",+ resets_at: null,+ })}+ />,+ );+ expect(screen.queryByText(/You can continue after|resets/)).toBeNull();+ expect(screen.queryByRole("button", { name: "Send at reset" })).toBeNull();+ expect(screen.getByRole("button", { name: /^Start Pro/ })).toBeDefined();+ expect(+ screen.getByRole("button", { name: "Back to my work" }),+ ).toBeDefined();+ });it("hides billing actions when platform payments are disabled", () => {render(<RateLimitResetDialogdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/components/ResetWaitBox.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/components/ResetWaitBox.tsxnew file mode 100644index 0000000000..5b68aacf0c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/components/ResetWaitBox.tsx@@ -0,0 +1,31 @@+import { Button } from "@/components/atoms/Button/Button";+import { UsageMeters } from "@/components/organisms/UsageExperience/UsageMeters";+import { SEND_AT_RESET_LABEL } from "../../SendAtReset/helpers";++interface Reading {+ percent_used: number;+}++interface Props {+ meters?: { daily?: Reading | null; weekly?: Reading | null } | null;+ onSendAtReset?: () => void;+ isScheduling?: boolean;+}++export function ResetWaitBox({ meters, onSendAtReset, isScheduling }: Props) {+ return (+ <div className="mb-5 space-y-4 rounded-xl border border-zinc-200 bg-zinc-50 p-4">+ <UsageMeters daily={meters?.daily} weekly={meters?.weekly} />+ {onSendAtReset && (+ <Button+ size="small"+ className="w-full"+ onClick={onSendAtReset}+ loading={isScheduling}+ >+ {SEND_AT_RESET_LABEL}+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/ScheduledSendChip.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/ScheduledSendChip.tsxnew file mode 100644index 0000000000..52bf9c3895--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/ScheduledSendChip.tsx@@ -0,0 +1,59 @@+"use client";++import type { AtResetTurn } from "@/app/api/__generated__/models/atResetTurn";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { Clock01Icon } from "@hugeicons/core-free-icons";+import { scheduledSendLabel } from "./helpers";+import { useScheduledSendDue } from "./useScheduledSendDue";++interface Props {+ job: AtResetTurn;+ onEdit: () => void;+ onCancel: () => void;+ isBusy?: boolean;+}++export function ScheduledSendChip({ job, onEdit, onCancel, isBusy }: Props) {+ // Once due it may already have gone: editing it then could send it twice.+ const isDue = useScheduledSendDue(job.run_at);+ return (+ <div+ role="status"+ aria-label="Scheduled message"+ className="mb-2 flex items-center justify-between gap-3 rounded-2xl border border-purple-200 bg-purple-50 px-3 py-2"+ >+ <div className="flex min-w-0 items-center gap-2">+ <Icon+ icon={Clock01Icon}+ size={16}+ className="shrink-0 text-purple-600"+ />+ <Text variant="small-medium" className="shrink-0 !text-purple-900">+ {isDue ? "Sending…" : scheduledSendLabel(job.run_at)}+ </Text>+ {job.message && (+ <Text variant="small" className="min-w-0 truncate !text-zinc-500">+ {job.message}+ </Text>+ )}+ </div>+ {!isDue && (+ <div className="flex shrink-0 items-center gap-1">+ <Button size="xs" variant="ghost" onClick={onEdit} disabled={isBusy}>+ Edit+ </Button>+ <Button+ size="xs"+ variant="ghost"+ onClick={onCancel}+ disabled={isBusy}+ >+ Cancel+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/ScheduledSendChip.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/ScheduledSendChip.test.tsxnew file mode 100644index 0000000000..601b6b4e1b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/ScheduledSendChip.test.tsx@@ -0,0 +1,61 @@+import { act, render, screen } from "@/tests/integrations/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ScheduledSendChip } from "../ScheduledSendChip";++const NOW = new Date(2026, 9, 12, 1, 0);++function chip(runAt: Date) {+ return (+ <ScheduledSendChip+ job={{ kind: "send", run_at: runAt, message: "Draft the launch post" }}+ onEdit={() => {}}+ onCancel={() => {}}+ />+ );+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+});++afterEach(() => {+ vi.useRealTimers();+});++describe("ScheduledSendChip", () => {+ it("offers Edit and Cancel until the send is due", () => {+ render(chip(new Date(2026, 9, 12, 1, 7)));+ expect(screen.getByText("Sends at 1:07 AM")).toBeDefined();+ expect(screen.getByRole("button", { name: "Edit" })).toBeDefined();+ });++ it("shows it going, with no Edit, once it is due", () => {+ render(chip(new Date(2026, 9, 12, 1, 7)));+ act(() => {+ vi.advanceTimersByTime(7 * 60_000);+ });+ expect(screen.getByText("Sending…")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Edit" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Cancel" })).toBeNull();+ });++ it("is due straight away when its time has already passed", () => {+ render(chip(new Date(2026, 9, 12, 0, 59)));+ expect(screen.getByText("Sending…")).toBeDefined();+ });++ it("goes at its new time when the send moves while the chip is up", () => {+ const view = render(chip(new Date(2026, 9, 12, 1, 7)));+ act(() => {+ vi.advanceTimersByTime(5 * 60_000);+ });+ view.rerender(chip(new Date(2026, 9, 12, 1, 10)));+ expect(screen.getByText("Sends at 1:10 AM")).toBeDefined();+ act(() => {+ vi.advanceTimersByTime(5 * 60_000);+ });+ expect(screen.getByText("Sending…")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Edit" })).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/helpers.test.tsnew file mode 100644index 0000000000..12544d8691--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/helpers.test.ts@@ -0,0 +1,91 @@+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { describe, expect, it } from "vitest";+import {+ atResetRefusal,+ isJoinedSendTooLong,+ returnToDraft,+ SCHEDULE_FAILED_TITLE,+ scheduledSendLabel,+ sendAtResetFailureTitle,+ SentNowError,+} from "../helpers";++const NOW = new Date(2026, 9, 11, 20, 48); // Sunday 8:48 PM, local++describe("scheduledSendLabel", () => {+ it("gives the time alone for a send later today", () => {+ expect(scheduledSendLabel(new Date(2026, 9, 11, 23, 5), NOW)).toBe(+ "Sends at 11:05 PM",+ );+ });++ it("names the day for a send on another day", () => {+ expect(scheduledSendLabel(new Date(2026, 9, 12, 1, 7), NOW)).toBe(+ "Sends Monday at 1:07 AM",+ );+ });+});++describe("atResetRefusal", () => {+ it.each(["not_out_of_budget", "no_reset"])("reads a %s refusal", (detail) => {+ expect(atResetRefusal(new ApiError("refused", 409, { detail }))).toBe(+ detail,+ );+ });++ it("leaves any other failure alone", () => {+ expect(atResetRefusal(new ApiError("busy", 409, { detail: "busy" }))).toBe(+ null,+ );+ expect(+ atResetRefusal(new ApiError("down", 503, { detail: "no_reset" })),+ ).toBe(null);+ expect(atResetRefusal(new Error("offline"))).toBe(null);+ });+});++describe("isJoinedSendTooLong", () => {+ it("reads the server refusing to join a send that would be too long", () => {+ expect(+ isJoinedSendTooLong(+ new ApiError("message_too_long", 413, { detail: "message_too_long" }),+ ),+ ).toBe(true);+ });++ it("leaves any other failure alone", () => {+ expect(+ isJoinedSendTooLong(new ApiError("too big", 413, { detail: "other" })),+ ).toBe(false);+ expect(+ isJoinedSendTooLong(+ new ApiError("refused", 409, { detail: "message_too_long" }),+ ),+ ).toBe(false);+ expect(isJoinedSendTooLong(new Error("message_too_long"))).toBe(false);+ });+});++describe("returnToDraft", () => {+ it("keeps a draft written meanwhile after the returned message", () => {+ expect(returnToDraft("", "Scheduled")).toBe("Scheduled");+ expect(returnToDraft("Scheduled", "Scheduled")).toBe("Scheduled");+ expect(returnToDraft("New thought", "Scheduled")).toBe(+ "Scheduled\n\nNew thought",+ );+ });+});++describe("sendAtResetFailureTitle", () => {+ it("calls a send that went out now a send", () => {+ const error = new SentNowError(new Error("Network down"));+ expect(sendAtResetFailureTitle(error)).toBe("Couldn't send message");+ expect(error.message).toBe("Network down");+ });++ it("calls anything else a failed schedule", () => {+ expect(sendAtResetFailureTitle(new Error("409"))).toBe(+ SCHEDULE_FAILED_TITLE,+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/scheduledSendHandoff.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/scheduledSendHandoff.test.tsnew file mode 100644index 0000000000..aa0a8f441f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/scheduledSendHandoff.test.ts@@ -0,0 +1,33 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++async function freshStore() {+ vi.resetModules();+ const { useScheduledSendHandoff } = await import("../scheduledSendHandoff");+ return useScheduledSendHandoff;+}++beforeEach(() => {+ sessionStorage.clear();+});++describe("useScheduledSendHandoff", () => {+ it("keeps a message waiting for its new chat through a reload", async () => {+ const before = await freshStore();+ before.getState().hold("chat-new", "Draft the launch post");++ const after = await freshStore();++ expect(after.getState().take("chat-new")).toBe("Draft the launch post");+ expect(after.getState().take("chat-new")).toBeNull();+ });++ it("hands a message over once, even after a reload", async () => {+ const before = await freshStore();+ before.getState().hold("chat-new", "Draft the launch post");+ expect(before.getState().take("chat-new")).toBe("Draft the launch post");++ const after = await freshStore();++ expect(after.getState().take("chat-new")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/useAtResetJobs.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/useAtResetJobs.test.tsxnew file mode 100644index 0000000000..5e9bc5421c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/useAtResetJobs.test.tsx@@ -0,0 +1,73 @@+import { server } from "@/mocks/mock-server";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook } from "@testing-library/react";+import { delay, http, HttpResponse } from "msw";+import type { ReactNode } from "react";+import { describe, expect, it, vi } from "vitest";+import { useAtResetJobs } from "../useAtResetJobs";++const JOB = {+ kind: "send" as const,+ run_at: new Date(2026, 9, 12, 1, 7),+ message: "Draft the launch post",+};++function withQueryClient() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ };+}++describe("useAtResetJobs", () => {+ it("keeps a write that a read already on its way would otherwise undo", async () => {+ server.use(+ http.get("*/api/chat/sessions/:sessionId/at-reset", async () => {+ await delay(150);+ return HttpResponse.json({ jobs: [] });+ }),+ );+ const { result } = renderHook(() => useAtResetJobs("session-1"), {+ wrapper: withQueryClient(),+ });++ await act(async () => {+ await result.current.writeJobs(() => [JOB]);+ });+ await act(() => delay(300));++ expect(result.current.jobs?.map((job) => job.message)).toEqual([+ "Draft the launch post",+ ]);+ });++ it("looks again as a set turn comes due, then often until it has gone", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ vi.setSystemTime(JOB.run_at.getTime() - 20_000);+ let reads = 0;+ server.use(+ http.get("*/api/chat/sessions/:sessionId/at-reset", () => {+ reads += 1;+ return HttpResponse.json({ jobs: [JOB] });+ }),+ );+ try {+ renderHook(() => useAtResetJobs("session-1"), {+ wrapper: withQueryClient(),+ });+ await vi.waitFor(() => expect(reads).toBe(1));++ await act(() => vi.advanceTimersByTimeAsync(21_000));+ expect(reads).toBe(2);++ await act(() => vi.advanceTimersByTimeAsync(10_000));+ expect(reads).toBe(3);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/useScheduledSend.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/useScheduledSend.test.tsxnew file mode 100644index 0000000000..b70e02f196--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/__tests__/useScheduledSend.test.tsx@@ -0,0 +1,169 @@+import { server } from "@/mocks/mock-server";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook, waitFor } from "@testing-library/react";+import { delay, http, HttpResponse } from "msw";+import type { ReactNode } from "react";+import { describe, expect, it, vi } from "vitest";+import { useChatDraft } from "../../ChatInput/useChatDraft";+import { sessionDraftKey } from "../helpers";+import { useScheduledSend } from "../useScheduledSend";++vi.mock("@/lib/auth/hooks/useAuthStore", () => ({+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>+ selector({ user: { id: "user-a" } }),+}));++function withQueryClient() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ };+}++describe("useScheduledSend", () => {+ // It runs in ChatContainer, which re-rendered on every keystroke while it+ // followed the draft it only ever writes.+ it("leaves the chat alone while its draft is typed", async () => {+ let reads = 0;+ server.use(+ http.get("*/api/chat/sessions/:sessionId/at-reset", () => {+ reads += 1;+ return HttpResponse.json({ jobs: [] });+ }),+ );+ let renders = 0;+ renderHook(+ () => {+ renders += 1;+ return useScheduledSend({ sessionId: "chat-typing" });+ },+ { wrapper: withQueryClient() },+ );+ await waitFor(() => expect(reads).toBe(1));+ await act(() => delay(100));+ const composer = renderHook(() =>+ useChatDraft(sessionDraftKey("chat-typing")),+ );+ const settled = renders;++ act(() => composer.result.current[1]("Draft the launch post"));+ act(() => composer.result.current[1]("Draft the launch post today"));++ expect(renders).toBe(settled);+ });++ describe("Edit", () => {+ const RUN_AT = new Date(2026, 9, 17, 1, 7).toISOString();++ function serverHolding(jobs: () => unknown[]) {+ const calls = { cancelled: 0 };+ server.use(+ http.get("*/api/chat/sessions/:sessionId/at-reset", () =>+ HttpResponse.json({ jobs: jobs() }),+ ),+ http.delete("*/api/chat/sessions/:sessionId/at-reset/:kind", () => {+ calls.cancelled += 1;+ return new HttpResponse(null, { status: 204 });+ }),+ );+ return calls;+ }++ // Another tab or client can add to the waiting send after this one last+ // read the list.+ it("puts back the send as the server holds it now", async () => {+ let message = "Draft the launch post";+ const calls = serverHolding(() => [+ { kind: "send", run_at: RUN_AT, message },+ ]);+ const { result } = renderHook(+ () => useScheduledSend({ sessionId: "chat-edit" }),+ { wrapper: withQueryClient() },+ );+ await waitFor(() =>+ expect(result.current.pending?.message).toBe("Draft the launch post"),+ );+ message = "Draft the launch post\n\nThen the newsletter";+ const composer = renderHook(() =>+ useChatDraft(sessionDraftKey("chat-edit")),+ );++ await act(() => result.current.edit());++ expect(calls.cancelled).toBe(1);+ expect(composer.result.current[0]).toBe(+ "Draft the launch post\n\nThen the newsletter",+ );+ });++ it("leaves a send that has already gone out of the draft", async () => {+ let jobs: unknown[] = [+ { kind: "send", run_at: RUN_AT, message: "Draft the launch post" },+ ];+ const calls = serverHolding(() => jobs);+ const { result } = renderHook(+ () => useScheduledSend({ sessionId: "chat-sent" }),+ { wrapper: withQueryClient() },+ );+ await waitFor(() => expect(result.current.pending).not.toBeNull());+ jobs = [];+ const composer = renderHook(() =>+ useChatDraft(sessionDraftKey("chat-sent")),+ );++ await act(() => result.current.edit());++ expect(calls.cancelled).toBe(0);+ expect(composer.result.current[0]).toBe("");+ await waitFor(() => expect(result.current.pending).toBeNull());+ });++ // Cancelling on the copy this tab last read could drop text the server+ // holds, so a failed read changes nothing.+ it("changes nothing when it can't read the server's copy", async () => {+ let reads = 0;+ let cancelled = 0;+ server.use(+ http.get("*/api/chat/sessions/:sessionId/at-reset", () => {+ reads += 1;+ return reads === 1+ ? HttpResponse.json({+ jobs: [+ {+ kind: "send",+ run_at: RUN_AT,+ message: "Draft the launch post",+ },+ ],+ })+ : HttpResponse.json(+ { detail: "Scheduler unavailable" },+ { status: 503 },+ );+ }),+ http.delete("*/api/chat/sessions/:sessionId/at-reset/:kind", () => {+ cancelled += 1;+ return new HttpResponse(null, { status: 204 });+ }),+ );+ const { result } = renderHook(+ () => useScheduledSend({ sessionId: "chat-unread" }),+ { wrapper: withQueryClient() },+ );+ await waitFor(() => expect(result.current.pending).not.toBeNull());+ const composer = renderHook(() =>+ useChatDraft(sessionDraftKey("chat-unread")),+ );++ await act(() => result.current.edit());++ expect(reads).toBe(2);+ expect(cancelled).toBe(0);+ expect(composer.result.current[0]).toBe("");+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/helpers.tsnew file mode 100644index 0000000000..0612dbdd8d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/helpers.ts@@ -0,0 +1,68 @@+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import {+ formatResetClock,+ formatWeekday,+} from "@/services/usageExperience/budget";++export const SEND_AT_RESET_LABEL = "Send at reset";+export const SCHEDULE_FAILED_TITLE = "Couldn’t schedule your message";+export const SEND_AT_RESET_PLACEHOLDER =+ "Write now, and it sends when your budget resets…";++/** Thrown when the budget turned out to be back, so the message went out+ * straight away instead, and that send failed; `cause` is how it failed. */+export class SentNowError extends Error {+ constructor(cause: unknown) {+ super(cause instanceof Error ? cause.message : "", { cause });+ this.name = "SentNowError";+ }+}++/** What the toast calls a failed Send at reset: a send, if it went out now. */+export function sendAtResetFailureTitle(error: unknown): string {+ return error instanceof SentNowError+ ? "Couldn't send message"+ : SCHEDULE_FAILED_TITLE;+}++/** The input id of an open chat's composer. */+export const SESSION_COMPOSER_ID = "chat-input-session";++export function sessionDraftKey(sessionId: string) {+ return `session:${sessionId}`;+}++/** Why the server would not set a send for the reset: the budget is already+ * back, or it never refills on its own. Null for any other failure. */+export function atResetRefusal(error: unknown) {+ if (!(error instanceof ApiError) || error.status !== 409) return null;+ const detail: unknown = error.response?.detail;+ return detail === "not_out_of_budget" || detail === "no_reset"+ ? detail+ : null;+}++/** The server joins a send onto the one already waiting, and refuses when the+ * two together would be longer than one message may be. */+export function isJoinedSendTooLong(error: unknown) {+ return (+ error instanceof ApiError &&+ error.status === 413 &&+ error.response?.detail === "message_too_long"+ );+}++export function scheduledSendLabel(runAt: Date | string, now = new Date()) {+ const date = new Date(runAt);+ const clock = formatResetClock(date);+ return date.toDateString() === now.toDateString()+ ? `Sends at ${clock}`+ : `Sends ${formatWeekday(date)} at ${clock}`;+}++/** Puts a message back in front of whatever the composer holds now, keeping+ * both: a draft written meanwhile must never be lost to it. */+export function returnToDraft(current: string, message: string) {+ if (!current.trim() || current === message) return message;+ return `${message}\n\n${current}`;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/scheduledSendHandoff.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/scheduledSendHandoff.tsnew file mode 100644index 0000000000..57dae7cf79--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/scheduledSendHandoff.ts@@ -0,0 +1,48 @@+import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";++/**+ * "Send at reset" from the new-chat screen: the chat is created first, and+ * creating it remounts the page under the new session id. The message waits+ * here until that session's composer picks it up and sets the send. The+ * composer that took it has already cleared, so the wait is kept in the+ * tab's session storage: a reload in between still sets the send.+ */+interface ScheduledSendHandoff {+ messages: Record<string, string>;+ hold: (sessionId: string, message: string) => void;+ take: (sessionId: string) => string | null;+}++export const useScheduledSendHandoff = create<ScheduledSendHandoff>()(+ persist(+ (set, get) => ({+ messages: {},+ hold(sessionId, message) {+ set((state) => ({+ messages: { ...state.messages, [sessionId]: message },+ }));+ },+ take(sessionId) {+ const message = get().messages[sessionId] ?? null;+ if (message === null) return null;+ set((state) => {+ const rest = { ...state.messages };+ delete rest[sessionId];+ return { messages: rest };+ });+ return message;+ },+ }),+ {+ name: "copilot-scheduled-send-handoff",+ // No-op storage where there is no window (SSR), as in the stream store.+ storage: createJSONStorage(() =>+ typeof window !== "undefined" && window.sessionStorage+ ? window.sessionStorage+ : { getItem: () => null, setItem: () => {}, removeItem: () => {} },+ ),+ partialize: (state) => ({ messages: state.messages }),+ },+ ),+);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useAtResetJobs.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useAtResetJobs.tsnew file mode 100644index 0000000000..2b1b293924--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useAtResetJobs.ts@@ -0,0 +1,51 @@+import {+ getGetV2ListTurnsAtBudgetResetQueryKey,+ useGetV2ListTurnsAtBudgetReset,+ type getV2ListTurnsAtBudgetResetResponse,+} from "@/app/api/__generated__/endpoints/chat/chat";+import type { AtResetTurn } from "@/app/api/__generated__/models/atResetTurn";+import { useQueryClient } from "@tanstack/react-query";++/** The chat's turns set for the budget reset, and a way to update them+ * without waiting for the next read. */+export function useAtResetJobs(sessionId: string | null) {+ const queryClient = useQueryClient();+ const { data: jobs } = useGetV2ListTurnsAtBudgetReset(sessionId ?? "", {+ query: {+ enabled: !!sessionId,+ select: (response) => (response.status === 200 ? response.data.jobs : []),+ // A set turn disappears once it fires; look again now and then, as+ // one comes due, and often while it is, to show it went (or was moved+ // on).+ refetchInterval: (query) =>+ query.state.data?.status === 200+ ? refetchEvery(query.state.data.data.jobs)+ : false,+ },+ });++ async function writeJobs(update: (jobs: AtResetTurn[]) => AtResetTurn[]) {+ const queryKey = getGetV2ListTurnsAtBudgetResetQueryKey(sessionId ?? "");+ // A read already on its way would land after this and put the old+ // list back.+ await queryClient.cancelQueries({ queryKey });+ queryClient.setQueryData<getV2ListTurnsAtBudgetResetResponse>(+ queryKey,+ (old) => ({+ status: 200,+ headers: old?.headers ?? new Headers(),+ data: { jobs: update(old?.status === 200 ? old.data.jobs : []) },+ }),+ );+ }++ return { jobs, writeJobs };+}++function refetchEvery(jobs: AtResetTurn[]) {+ if (!jobs.length) return false;+ const untilDue =+ Math.min(...jobs.map((job) => new Date(job.run_at).getTime())) - Date.now();+ if (untilDue <= 0) return 10_000;+ return Math.min(Math.max(untilDue, 1_000), 60_000);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useHandedOffSend.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useHandedOffSend.tsnew file mode 100644index 0000000000..4717268b50--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useHandedOffSend.ts@@ -0,0 +1,19 @@+import { useEffect, useRef } from "react";+import { useScheduledSendHandoff } from "./scheduledSendHandoff";++/** Sets the send a new-chat screen handed this session when it created it. */+export function useHandedOffSend(+ sessionId: string | null,+ scheduleQuietly: (message: string) => Promise<void>,+) {+ const waiting = useScheduledSendHandoff((state) =>+ sessionId ? (state.messages[sessionId] ?? null) : null,+ );+ const latest = useRef(scheduleQuietly);+ latest.current = scheduleQuietly;+ useEffect(() => {+ if (!sessionId || waiting === null) return;+ const message = useScheduledSendHandoff.getState().take(sessionId);+ if (message !== null) void latest.current(message);+ }, [sessionId, waiting]);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useScheduledSend.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useScheduledSend.tsnew file mode 100644index 0000000000..77a0572458--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useScheduledSend.ts@@ -0,0 +1,157 @@+"use client";++import {+ getGetV2GetCopilotUsageQueryKey,+ getGetV2ListTurnsAtBudgetResetQueryKey,+ getV2ListTurnsAtBudgetReset,+ useDeleteV2CancelTurnAtBudgetReset,+ usePostV2ScheduleTurnAtBudgetReset,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { toast } from "@/components/molecules/Toast/use-toast";+import { useQueryClient } from "@tanstack/react-query";+import { toastSendFailure } from "../../helpers/sendFailureToast";+import { describeSendFailure } from "../ChatInput/helpers";+import { useChatDraftAccess } from "../ChatInput/useChatDraft";+import {+ atResetRefusal,+ isJoinedSendTooLong,+ returnToDraft,+ sendAtResetFailureTitle,+ SentNowError,+ sessionDraftKey,+} from "./helpers";+import { useAtResetJobs } from "./useAtResetJobs";++interface Args {+ sessionId: string | null;+ /** Sends right away instead, when the budget turns out to be back. */+ onSendNow?: (message: string) => void | Promise<void>;+ /** The composer to focus once Edit has put the message back in it. */+ inputId?: string;+}++export function useScheduledSend({ sessionId, onSendNow, inputId }: Args) {+ const queryClient = useQueryClient();+ const { jobs, writeJobs } = useAtResetJobs(sessionId);+ const draft = useChatDraftAccess(+ sessionId ? sessionDraftKey(sessionId) : undefined,+ );+ const scheduleSend = usePostV2ScheduleTurnAtBudgetReset();+ const cancelSend = useDeleteV2CancelTurnAtBudgetReset();+ const pending = jobs?.find((job) => job.kind === "send") ?? null;++ async function schedule(message: string) {+ if (!sessionId) throw new Error("This chat isn’t ready yet");+ // A chat sends one message at the reset; the server adds this one to+ // any already waiting and answers with the joined message.+ try {+ const response = await scheduleSend.mutateAsync({+ sessionId,+ data: { kind: "send", message },+ });+ if (response.status !== 200) return;+ const job = response.data;+ await writeJobs((all) => [...all.filter((j) => j.kind !== "send"), job]);+ } catch (error) {+ if (isJoinedSendTooLong(error)) {+ throw new Error("Too long to add to the message already waiting");+ }+ const refusal = atResetRefusal(error);+ if (!refusal) throw error;+ void queryClient.invalidateQueries({+ queryKey: getGetV2GetCopilotUsageQueryKey(),+ });+ if (refusal === "not_out_of_budget" && onSendNow) {+ try {+ return await onSendNow(message);+ } catch (sendError) {+ throw new SentNowError(sendError);+ }+ }+ throw new Error(+ refusal === "no_reset"+ ? "Your budget doesn’t reset on its own"+ : "Your budget is already back",+ );+ }+ }++ /** For a message no composer is holding: a failure goes back into the+ * chat's draft instead of being thrown. */+ async function scheduleQuietly(message: string) {+ try {+ await schedule(message);+ } catch (error) {+ draft.write((current) => returnToDraft(current, message));+ toastSendFailure({+ title: sendAtResetFailureTitle(error),+ error,+ recovery: "your message is back in the composer",+ });+ }+ }++ async function unschedule() {+ if (!sessionId) return false;+ try {+ await cancelSend.mutateAsync({ sessionId, kind: "send" });+ } catch (error) {+ toastChangeFailure(error);+ return false;+ }+ await writeJobs((all) => all.filter((job) => job.kind !== "send"));+ return true;+ }++ async function edit() {+ const read = await readSend();+ // Without the server's copy, cancelling could drop text it holds.+ if ("error" in read) {+ toastChangeFailure(read.error);+ return;+ }+ const { send } = read;+ // Already sent, or cancelled elsewhere: the read has updated the list.+ if (!send) return;+ if (!(await unschedule())) return;+ draft.write((current) => returnToDraft(current, send.message ?? ""));+ if (inputId) document.getElementById(inputId)?.focus();+ }++ /** The send as the server holds it now, since another tab or client may+ * have added to it after this one last read the list. */+ async function readSend() {+ if (!sessionId) return { send: pending };+ try {+ const response = await queryClient.fetchQuery({+ queryKey: getGetV2ListTurnsAtBudgetResetQueryKey(sessionId),+ queryFn: ({ signal }) =>+ getV2ListTurnsAtBudgetReset(sessionId, { signal }),+ staleTime: 0,+ });+ if (response.status !== 200) return { error: response };+ return {+ send: response.data.jobs.find((job) => job.kind === "send") ?? null,+ };+ } catch (error) {+ return { error };+ }+ }++ function toastChangeFailure(error: unknown) {+ toast({+ title: "Couldn’t change your scheduled message",+ description: describeSendFailure(error, "it still sends at the reset"),+ variant: "destructive",+ });+ }++ return {+ pending,+ schedule,+ scheduleQuietly,+ edit,+ cancel: unschedule,+ isBusy: scheduleSend.isPending || cancelSend.isPending,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useScheduledSendDue.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useScheduledSendDue.tsnew file mode 100644index 0000000000..26721bcd09--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useScheduledSendDue.ts@@ -0,0 +1,23 @@+"use client";++import { useEffect, useState } from "react";++/** Whether a scheduled send's time has come: it may be going out or gone,+ * so it can't be taken back to edit. Flips on its own at that time. */+export function useScheduledSendDue(runAt: Date | string) {+ const [now, setNow] = useState(() => Date.now());+ const due = new Date(runAt).getTime();++ useEffect(+ function flipWhenDue() {+ if (due <= now) return;+ // Timed from the clock, not `now`: the send can move while this is up.+ const wait = Math.max(0, due - Date.now());+ const timer = setTimeout(() => setNow(Date.now()), wait);+ return () => clearTimeout(timer);+ },+ [due, now],+ );++ return due <= now;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useSendDraftAtReset.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useSendDraftAtReset.tsnew file mode 100644index 0000000000..42c21b8c63--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SendAtReset/useSendDraftAtReset.ts@@ -0,0 +1,31 @@+import { useChatDraftAccess } from "../ChatInput/useChatDraft";+import { SESSION_COMPOSER_ID, sessionDraftKey } from "./helpers";+import { useScheduledSend } from "./useScheduledSend";++interface Args {+ sessionId: string | null;+ onSendNow?: (message: string) => void | Promise<void>;+ onClose: () => void;+}++/** "Send at reset" outside the composer: sets the chat's unsent draft to+ * send at the reset, or with nothing written yet, opens the composer. */+export function useSendDraftAtReset({ sessionId, onSendNow, onClose }: Args) {+ const scheduled = useScheduledSend({ sessionId, onSendNow });+ const draft = useChatDraftAccess(+ sessionId ? sessionDraftKey(sessionId) : undefined,+ );++ async function sendDraftAtReset() {+ const message = draft.read().trim();+ onClose();+ if (!message) {+ document.getElementById(SESSION_COMPOSER_ID)?.focus();+ return;+ }+ draft.write("");+ await scheduled.scheduleQuietly(message);+ }++ return { sendDraftAtReset, isScheduling: scheduled.isBusy };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/TurnPausedCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/TurnPausedCard.test.tsxindex ee2353dba4..4f9c6b070f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/TurnPausedCard.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/TurnPausedCard.test.tsx@@ -1,4 +1,4 @@-import { http, HttpResponse } from "msw";+import { delay, http, HttpResponse } from "msw";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {@@ -463,6 +463,29 @@ describe("TurnPausedCard — Keep going", () => {expect(onBackendTurn).not.toHaveBeenCalled();});+ it("points to the plans when picking up needs one", async () => {+ backend();+ server.use(+ http.post("*/api/chat/sessions/:id/continue", () =>+ HttpResponse.json(+ { detail: "Choose a plan to keep using AutoPilot" },+ { status: 402 },+ ),+ ),+ );+ renderCard(pause({ reason: "task", resets_at: null }));++ fireEvent.click(screen.getByRole("button", { name: "Keep going" }));++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Couldn't pick this back up",+ description: "Choose a plan to keep going.",+ variant: "destructive",+ }),+ );+ });+it("turns into the budget pause when the account ran out meanwhile", async () => {backend();server.use(@@ -675,6 +698,41 @@ describe("TurnPausedCard — Continue on ChatGPT", () => {expect(calls.continued).toEqual([{ model: "standard" }]);});+ it("spins on the button that was clicked while the task is picked up", async () => {+ backend({ offers: [PLATFORM, CHATGPT] });+ let pickUps = 0;+ server.use(+ http.post("*/api/chat/sessions/:id/continue", async () => {+ pickUps += 1;+ await delay("infinite");+ return HttpResponse.json({});+ }),+ );+ // The budget is back, so Keep going sits beside Continue on ChatGPT.+ renderCard(+ pause({ resets_at: new Date(2026, 9, 11, 20, 0).toISOString() }),+ );++ fireEvent.click(+ await screen.findByRole("button", { name: "Continue on ChatGPT" }),+ );++ // Past the switch, the pick-up itself is running.+ await waitFor(() => expect(pickUps).toBe(1));+ await waitFor(() =>+ expect(+ screen+ .getByRole("button", { name: "Continue on ChatGPT" })+ .querySelector(".animate-spin"),+ ).not.toBeNull(),+ );+ expect(+ screen+ .getByRole("button", { name: "Keep going" })+ .querySelector(".animate-spin"),+ ).toBeNull();+ });+it("never offers Microsoft 365 Copilot, which runs no tools, nor a locked ChatGPT", async () => {backend({offers: [diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/components/PausedCardActions.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/components/PausedCardActions.tsxindex 4679797d47..f1aa8d202c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/components/PausedCardActions.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/components/PausedCardActions.tsx@@ -1,4 +1,5 @@import { ArrowRight02Icon, Clock01Icon } from "@hugeicons/core-free-icons";+import { useState } from "react";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";@@ -14,6 +15,11 @@ interface Props {export function PausedCardActions({ card, onStop }: Props) {const { keep, resume, chatGpt } = card;+ // Continue on ChatGPT picks the task up too, once it has switched, so the+ // spinner follows the button that started it.+ const [pickUpVia, setPickUpVia] = useState<"keep_going" | "chatgpt">(+ "keep_going",+ );const isBusy =keep.isContinuing ||resume.isScheduling ||@@ -52,8 +58,11 @@ export function PausedCardActions({ card, onStop }: Props) {{card.primary === "keep_going" && (<Buttonsize="small"- onClick={() => void keep.keepGoing()}- loading={keep.isContinuing}+ onClick={() => {+ setPickUpVia("keep_going");+ void keep.keepGoing();+ }}+ loading={keep.isContinuing && pickUpVia === "keep_going"}disabled={isBusy}>Keep going@@ -63,11 +72,13 @@ export function PausedCardActions({ card, onStop }: Props) {<Buttonsize="small"variant="secondary"- onClick={() => void chatGpt.continueHere()}- // After the switch, the pick-up runs under this button too.+ onClick={() => {+ setPickUpVia("chatgpt");+ void chatGpt.continueHere();+ }}loading={chatGpt.isSwitching ||- (keep.isContinuing && card.primary !== "keep_going")+ (keep.isContinuing && pickUpVia === "chatgpt")}disabled={isBusy}>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/BudgetLowHint.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/BudgetLowHint.tsxnew file mode 100644index 0000000000..70e5f04c9b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/BudgetLowHint.tsx@@ -0,0 +1,43 @@+import { Text } from "@/components/atoms/Text/Text";+import { budgetLowHint } from "@/services/usageExperience/budget";+import type { UsageSnapshot } from "@/services/usageExperience/useUsageExperience";+import { cn } from "@/lib/utils";+import { BudgetRing } from "./BudgetRing";++interface Props {+ usage: UsageSnapshot;+ className?: string;+}++const WINDOW_LABEL = {+ daily: "Today",+ weekly: "This week",+ trial: "Trial allowance",+} as const;++export function BudgetLowHint({ usage, className }: Props) {+ const { budget, experience } = usage;+ if (budget.state !== "low" || !budget.window) return null;+ const trialPercent = experience.isLifetimeTrial+ ? experience.trialPercent+ : null;+ const percent =+ budget.window === "trial"+ ? (trialPercent ?? budget.percentUsed)+ : budget.percentUsed;+ if (percent === null) return null;+ return (+ <div+ aria-label="AutoPilot budget"+ className={cn(+ "mx-auto mt-2 flex w-full items-center gap-2 px-3 text-left",+ className,+ )}+ >+ <BudgetRing label={WINDOW_LABEL[budget.window]} percent={percent} />+ <Text variant="small" className="!text-xs !text-zinc-500">+ {budgetLowHint(budget.window, percent)}+ </Text>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/BudgetRing.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/BudgetRing.tsxnew file mode 100644index 0000000000..2eabfb0613--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/BudgetRing.tsx@@ -0,0 +1,54 @@+interface Props {+ label: string;+ percent: number;+}++const SIZE = 18;+const STROKE = 3;+const RADIUS = (SIZE - STROKE) / 2;+const CIRCUMFERENCE = 2 * Math.PI * RADIUS;++export function BudgetRing({ label, percent }: Props) {+ const value = Math.min(100, Math.max(0, percent));+ const center = SIZE / 2;+ return (+ <span+ role="progressbar"+ aria-label={label}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={value}+ className="inline-flex shrink-0"+ >+ <svg+ width={SIZE}+ height={SIZE}+ viewBox={`0 0 ${SIZE} ${SIZE}`}+ aria-hidden="true"+ >+ <circle+ cx={center}+ cy={center}+ r={RADIUS}+ fill="none"+ stroke="currentColor"+ strokeWidth={STROKE}+ className="text-zinc-200"+ />+ <circle+ cx={center}+ cy={center}+ r={RADIUS}+ fill="none"+ stroke="currentColor"+ strokeWidth={STROKE}+ strokeLinecap="round"+ strokeDasharray={CIRCUMFERENCE}+ strokeDashoffset={CIRCUMFERENCE * (1 - value / 100)}+ transform={`rotate(-90 ${center} ${center})`}+ className="text-purple-500"+ />+ </svg>+ </span>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsxindex 703903c7de..65638d6d69 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsx@@ -9,6 +9,11 @@ import { formatPaymentDue } from "@/services/usageExperience/payment";import { usagePresentation } from "@/services/usageExperience/presentation";import { PaymentDueAction } from "@/components/organisms/UsageExperience/PaymentDueAction";import { ProviderContinuation } from "@/components/organisms/UsageExperience/ProviderContinuation";+import { UsageMeters } from "@/components/organisms/UsageExperience/UsageMeters";+import {+ budgetOutTitle,+ budgetResetSentence,+} from "@/services/usageExperience/budget";import type { UsageNoticeContext } from "./useUsageLimitReachedCard";import { useUsageLimitReachedCard } from "./useUsageLimitReachedCard";@@ -54,7 +59,9 @@ export function UsageLimitReachedCard(props: UsageNoticeContext = {}) {? "Checking your usage": state.isError? "We couldn’t check your usage."- : copy.noticeTitle}+ : state.wait+ ? budgetOutTitle(state.wait.window)+ : copy.noticeTitle}</Text><Textvariant="small"@@ -65,8 +72,17 @@ export function UsageLimitReachedCard(props: UsageNoticeContext = {}) {? "Refreshing your plan and usage…": state.isError? "Your work is saved. Try again to check your allowance."- : copy.description}+ : state.wait+ ? budgetResetSentence(state.wait)+ : copy.description}</Text>+ {state.wait && (+ <UsageMeters+ className="mt-4"+ daily={state.usage?.daily}+ weekly={state.usage?.weekly}+ />+ )}{isOffer && (<div className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-2"><Buttondiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.tsindex 6203dbd522..285e7a2cba 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.ts@@ -1,3 +1,4 @@+import { getResetWait } from "@/services/usageExperience/budget";import { useUsageActions } from "@/services/usageExperience/useUsageActions";import type { ProviderFailure } from "../../../providerFailure";import { useProviderLimitDialog } from "../../ProviderLimitDialog/useProviderLimitDialog";@@ -37,10 +38,12 @@ export function useUsageLimitReachedCard({sessionId: sessionID,onDismiss,});+ const isError = state.isError || !!refresh?.failed || !!refresh?.checking;return {...state,isLoading: state.isLoading && !refresh?.checking && !refresh?.failed,- isError: state.isError || !!refresh?.failed || !!refresh?.checking,+ isError,+ wait: isError ? null : getResetWait(state.budget),isRefreshing: !!refresh?.checking,retry: refresh?.refresh ?? state.retry,alternative: sessionID ? provider.alternative : null,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/useIsUsageLimitReached.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/useIsUsageLimitReached.test.tsxindex 5b38ee5194..9c7ae0b1a4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/useIsUsageLimitReached.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/useIsUsageLimitReached.test.tsx@@ -1,55 +1,52 @@import { renderHook } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-const mocks = vi.hoisted(() => ({ usage: vi.fn(), session: vi.fn() }));+const mocks = vi.hoisted(() => ({ usage: vi.fn() }));vi.mock("@/services/usageExperience/useUsageExperience", () => ({useUsageExperience: mocks.usage,}));-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- useGetV2GetSession: mocks.session,-}));import { useIsUsageLimitReached } from "../useIsUsageLimitReached";beforeEach(() => {mocks.usage.mockReturnValue({experience: { blocked: true },isError: false,});- mocks.session.mockReturnValue({- data: {- status: 200,- data: { metadata: { llm_auth_provider: "platform" } },- },- });});describe("chat usage gating", () => {it("keeps platform-funded messages blocked after the allowance is exhausted", () => {expect(- renderHook(() => useIsUsageLimitReached("chat")).result.current,+ renderHook(() => useIsUsageLimitReached("platform")).result.current,).toBe(true);});it("unblocks the same conversation only after a confirmed provider switch", () => {- const { result, rerender } = renderHook(() =>- useIsUsageLimitReached("chat"),+ const { result, rerender } = renderHook(+ ({ provider }) => useIsUsageLimitReached(provider),+ { initialProps: { provider: "platform" } },);expect(result.current).toBe(true);- mocks.session.mockReturnValue({- data: { status: 200, data: { metadata: { llm_auth_provider: "codex" } } },- });- rerender();+ rerender({ provider: "codex" });expect(result.current).toBe(false);});- it("does not infer a provider exemption from missing session data", () => {- mocks.session.mockReturnValue({ data: undefined });+ it("lets a Microsoft 365 Copilot chat carry on, which its own plan pays for", () => {expect(- renderHook(() => useIsUsageLimitReached("chat")).result.current,- ).toBe(true);+ renderHook(() => useIsUsageLimitReached("microsoft_365_copilot")).result+ .current,+ ).toBe(false);});+ it.each([null, undefined, "some_new_provider"])(+ "does not infer a provider exemption from %s",+ (provider) => {+ expect(+ renderHook(() => useIsUsageLimitReached(provider)).result.current,+ ).toBe(true);+ },+ );it("pauses platform sending while usage is unavailable", () => {mocks.usage.mockReturnValue({experience: { blocked: false },isError: true,});expect(- renderHook(() => useIsUsageLimitReached("chat")).result.current,+ renderHook(() => useIsUsageLimitReached("platform")).result.current,).toBe(true);});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.tsindex 9007f93aeb..9711e6f497 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.ts@@ -1,15 +1,10 @@-import { useGetV2GetSession } from "@/app/api/__generated__/endpoints/chat/chat";import { useUsageExperience } from "@/services/usageExperience/useUsageExperience";+import { spendsPlatformBudget } from "../usageHelpers";-export function useIsUsageLimitReached(sessionID?: string | null) {+/** The connection the chat runs on decides: only a platform chat waits for+ * the AutoPilot budget. */+export function useIsUsageLimitReached(authProvider?: string | null) {const state = useUsageExperience();- const session = useGetV2GetSession(sessionID ?? "", undefined, {- query: { enabled: !!sessionID },- });- const provider =- session.data?.status === 200- ? session.data.data.metadata?.llm_auth_provider- : null;- if (provider && provider !== "platform") return false;+ if (!spendsPlatformBudget(authProvider)) return false;return state.experience.blocked || state.isError;}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.tsindex 510e8c0168..9f79c49163 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts@@ -53,6 +53,13 @@ interface UsageLike {weekly?: UsageWindowLike | null;}+/** Whether a chat on this connection spends the AutoPilot budget. ChatGPT and+ * Microsoft 365 Copilot turns are paid by the user's own subscription; any+ * other value, including one not loaded yet, counts as the platform. */+export function spendsPlatformBudget(authProvider: string | null | undefined) {+ return authProvider !== "codex" && authProvider !== "microsoft_365_copilot";+}+export function isUsageExhausted(usage: UsageLike | null | undefined): boolean {if (!usage) return false;const daily = usage.daily?.percent_used ?? 0;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/sendFailureToast.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/sendFailureToast.test.tsxnew file mode 100644index 0000000000..68b3209d34--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/sendFailureToast.test.tsx@@ -0,0 +1,39 @@+import { toast } from "@/components/molecules/Toast/use-toast";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { SentNowError } from "../../components/SendAtReset/helpers";+import { ReportedSendError } from "../reportedSendError";+import { toastSendFailure } from "../sendFailureToast";++vi.mock("@/components/molecules/Toast/use-toast", () => ({ toast: vi.fn() }));++const ARGS = {+ title: "Couldn't send message",+ recovery: "your message is back in the composer",+};++// Send at reset sends at once when the budget turns out to be back, and+// reports that send's failure under its own title.+describe("a send Send at reset made at once", () => {+ beforeEach(() => {+ vi.mocked(toast).mockClear();+ });++ it("adds no toast to a refusal the chat already showed", () => {+ const shown = new ReportedSendError("The plan dialog is open");++ toastSendFailure({ ...ARGS, error: new SentNowError(shown) });++ expect(toast).not.toHaveBeenCalled();+ });++ it("offers plans when the account needs one", () => {+ const paywall = new ApiError("Payment required", 402, {});++ toastSendFailure({ ...ARGS, error: new SentNowError(paywall) });++ expect(vi.mocked(toast).mock.calls[0][0]).toMatchObject({+ title: "Sending needs an active plan",+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsxindex f7aa65c371..569291fec3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx@@ -6,6 +6,7 @@ import {PaywallToastAction,PaywallToastDescription,} from "../components/PaywallToast/PaywallToast";+import { SentNowError } from "../components/SendAtReset/helpers";import { ReportedSendError } from "./reportedSendError";const PAYWALL_TOAST_DURATION_MS = 15_000;@@ -35,8 +36,10 @@ export function toastSendFailure({recovery,paywallRecovery = recovery,}: Args) {- if (error instanceof ReportedSendError) return;- if (isPaywallError(error)) {+ // A send Send at reset made at once fails the way that send did.+ const failure = error instanceof SentNowError ? error.cause : error;+ if (failure instanceof ReportedSendError) return;+ if (isPaywallError(failure)) {toast({title: "Sending needs an active plan",description: <PaywallToastDescription recovery={paywallRecovery} />,@@ -49,7 +52,7 @@ export function toastSendFailure({}toast({title,- description: describeSendFailure(error, recovery),+ description: describeSendFailure(failure, recovery),variant: "destructive",});}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex 908ed06de0..2ed1608e73 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -400,6 +400,12 @@ export function useChatSession({sessionId && sessionQuery.data?.status === 200? (sessionQuery.data.data.metadata?.llm_credential_id ?? null): null;+ // What the AutoPilot budget follows: the session's own connection, or for a+ // new chat the one it will start on (null until that is known).+ const chatLlmAuthProvider = sessionId+ ? sessionLlmAuthProvider+ : (resolveCopilotLLMAuthSelection(chatTransports, copilotLlmAuth)+ ?.authProvider ?? null);// The expert this session actually belongs to, straight off the session// response rather than the URL — the ?expertId= param only describes what@@ -428,6 +434,7 @@ export function useChatSession({sessionView: freshSessionData,sessionLlmAuthProvider,sessionLlmCredentialId,+ chatLlmAuthProvider,sessionExpertId,isAdoptingExpertSession,hydratedMessages,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex d82d20b7b8..f63fdc1598 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -133,6 +133,7 @@ export function useCopilotPage({sessionView,sessionLlmAuthProvider,sessionLlmCredentialId,+ chatLlmAuthProvider,sessionExpertId,isAdoptingExpertSession,hydratedMessages,@@ -550,6 +551,7 @@ export function useCopilotPage({sessionChatStatus,sessionSentFrom,sessionAutopilotMode,+ chatLlmAuthProvider,expertIdentity,isResolvingExpertIdentity,isAdoptingExpertSession,diff --git a/autogpt_platform/frontend/src/components/organisms/UsageExperience/UsageMeters.tsx b/autogpt_platform/frontend/src/components/organisms/UsageExperience/UsageMeters.tsxnew file mode 100644index 0000000000..16ac062db5--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/UsageExperience/UsageMeters.tsx@@ -0,0 +1,38 @@+import { cn } from "@/lib/utils";+import { UsageMeter } from "./UsageMeter";++interface Reading {+ percent_used: number;+}++interface Props {+ daily?: Reading | null;+ weekly?: Reading | null;+ /** A lifetime trial has one allowance instead of daily and weekly ones. */+ trialPercent?: number | null;+ className?: string;+}++export function UsageMeters({ daily, weekly, trialPercent, className }: Props) {+ const meters =+ trialPercent != null+ ? [{ label: "Trial allowance", percent: trialPercent }]+ : [+ ...(daily ? [{ label: "Today", percent: daily.percent_used }] : []),+ ...(weekly+ ? [{ label: "This week", percent: weekly.percent_used }]+ : []),+ ];+ if (meters.length === 0) return null;+ return (+ <div className={cn("grid gap-x-6 gap-y-3 sm:grid-cols-2", className)}>+ {meters.map((meter) => (+ <UsageMeter+ key={meter.label}+ label={meter.label}+ percent={meter.percent}+ />+ ))}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/mocks/mock-handlers.ts b/autogpt_platform/frontend/src/mocks/mock-handlers.tsindex f1bd224aec..cf0ba81d7d 100644--- a/autogpt_platform/frontend/src/mocks/mock-handlers.ts+++ b/autogpt_platform/frontend/src/mocks/mock-handlers.ts@@ -9,7 +9,10 @@ import {getGetBrainDumpRecommendedProvidersMockHandler200,} from "@/app/api/__generated__/endpoints/brain-dump/brain-dump.msw";import { getBriefingsMock } from "@/app/api/__generated__/endpoints/briefings/briefings.msw";-import { getChatMock } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import {+ getChatMock,+ getGetV2ListTurnsAtBudgetResetMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";import { getCreditsMock } from "@/app/api/__generated__/endpoints/credits/credits.msw";import { getDefaultMock } from "@/app/api/__generated__/endpoints/default/default.msw";import { getEmailMock } from "@/app/api/__generated__/endpoints/email/email.msw";@@ -59,6 +62,9 @@ export const mockHandlers = [providers: [],}),...getBriefingsMock(),+ // Nothing set to send at a budget reset unless a test sets it up; random+ // jobs would put a scheduled-message chip above every chat's composer.+ getGetV2ListTurnsAtBudgetResetMockHandler200({ jobs: [] }),...getChatMock(),...getCreditsMock(),...getDefaultMock(),diff --git a/autogpt_platform/frontend/src/services/usageExperience/__tests__/budget.test.ts b/autogpt_platform/frontend/src/services/usageExperience/__tests__/budget.test.tsnew file mode 100644index 0000000000..07a96119fa--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/__tests__/budget.test.ts@@ -0,0 +1,171 @@+import { describe, expect, it } from "vitest";+import {+ budgetLowHint,+ budgetOutTitle,+ budgetResetSentence,+ formatCountdown,+ getResetWait,+ getUsageBudget,+} from "../budget";+import { getUsageExperience } from "../helpers";++// Local times, so the copy reads the same in any time zone.+const NOW = new Date(2026, 9, 11, 20, 48); // Sunday 8:48 PM+const TONIGHT_1AM = new Date(2026, 9, 12, 1, 0); // Monday 1:00 AM+const NEXT_MONDAY_1AM = new Date(2026, 9, 19, 1, 0);++function usage(over: Record<string, unknown> = {}) {+ return {+ tier: "MAX",+ daily: { percent_used: 100, resets_at: TONIGHT_1AM },+ weekly: { percent_used: 100, resets_at: NEXT_MONDAY_1AM },+ ...over,+ } as Parameters<typeof getUsageBudget>[0];+}++describe("the AutoPilot budget verdict", () => {+ it("waits for the window the server says decides", () => {+ const budget = getUsageBudget(+ usage({+ state: "exhausted",+ limiting_window: "weekly",+ resets_at: NEXT_MONDAY_1AM,+ }),+ );+ expect(getResetWait(budget)).toEqual({+ window: "weekly",+ resetsAt: NEXT_MONDAY_1AM,+ });+ expect(budget.percentUsed).toBe(100);+ });++ it.each([+ ["a spent trial allowance", "trial"],+ ["a plan that allows nothing", "weekly"],+ ])("has nothing to wait for with %s", (_, limitingWindow) => {+ const budget = getUsageBudget(+ usage({+ state: "exhausted",+ limiting_window: limitingWindow,+ resets_at: null,+ }),+ );+ expect(budget.state).toBe("exhausted");+ expect(getResetWait(budget)).toBeNull();+ });++ it("waits for a trial's own weekly cap, which does refill", () => {+ const trialUsage = usage({+ tier: "TRIAL",+ daily: { percent_used: 40, resets_at: TONIGHT_1AM },+ state: "exhausted",+ limiting_window: "weekly",+ resets_at: NEXT_MONDAY_1AM,+ });+ expect(getResetWait(getUsageBudget(trialUsage))?.window).toBe("weekly");+ const experience = getUsageExperience(trialUsage, {+ active: true,+ converted: false,+ usage_policy: "lifetime",+ allowance_used_percent: 60,+ });+ expect(experience.blocked).toBe(true);+ expect(experience.window).toBe("weekly");+ });++ it("shows no reset time for a window that allows nothing", () => {+ const experience = getUsageExperience(+ usage({+ tier: "NO_TIER",+ state: "exhausted",+ limiting_window: "weekly",+ resets_at: null,+ }),+ );+ expect(experience.blocked).toBe(true);+ expect(experience.resetsAt).toBeNull();+ });++ it("estimates a low budget from the meters when the server sends no verdict", () => {+ const budget = getUsageBudget(+ usage({+ daily: { percent_used: 86, resets_at: TONIGHT_1AM },+ weekly: { percent_used: 61, resets_at: NEXT_MONDAY_1AM },+ }),+ );+ expect(budget).toEqual({+ state: "low",+ window: "daily",+ resetsAt: TONIGHT_1AM,+ percentUsed: 86,+ });+ });++ it("never promises a reset it had to estimate", () => {+ const budget = getUsageBudget(usage());+ expect(budget.state).toBe("exhausted");+ expect(getResetWait(budget)).toBeNull();+ });++ it("is ok below 80% of every window", () => {+ expect(+ getUsageBudget(+ usage({+ daily: { percent_used: 79, resets_at: TONIGHT_1AM },+ weekly: { percent_used: 10, resets_at: NEXT_MONDAY_1AM },+ }),+ ).state,+ ).toBe("ok");+ });+});++describe("budget copy", () => {+ it("titles the window that is used up", () => {+ expect(budgetOutTitle("weekly")).toBe(+ "You’re out of AutoPilot budget for this week",+ );+ expect(budgetOutTitle("daily")).toBe(+ "You’re out of AutoPilot budget for today",+ );+ });++ it("says when a weekly budget resets, by day", () => {+ expect(+ budgetResetSentence(+ { window: "weekly", resetsAt: new Date(2026, 9, 13, 21, 0) },+ NOW,+ ),+ ).toBe(+ "It resets Tuesday at 9:00 PM, in 2 days. You can still browse, edit workflows and read results.",+ );+ });++ it("says when today's budget resets, by the clock", () => {+ expect(+ budgetResetSentence({ window: "daily", resetsAt: TONIGHT_1AM }, NOW),+ ).toBe(+ "It resets at 1:00 AM, in 4 h 12 min. You can still browse, edit workflows and read results.",+ );+ });++ it.each([+ [new Date(2026, 9, 11, 20, 48, 30), "in under a minute"],+ [new Date(2026, 9, 11, 21, 23), "in 35 min"],+ [new Date(2026, 9, 12, 0, 48), "in 4 h"],+ [new Date(2026, 9, 12, 22, 0), "in 1 day"],+ ])("counts down to %s as %s", (resetsAt, expected) => {+ expect(formatCountdown(resetsAt, NOW)).toBe(expected);+ });++ it("names the budget that is running low", () => {+ expect(budgetLowHint("daily", 86)).toBe(+ "About 14% of today’s budget left. A long task may pause partway.",+ );+ expect(budgetLowHint("weekly", 80.4)).toBe(+ "About 20% of this week’s budget left. A long task may pause partway.",+ );+ expect(budgetLowHint("trial", 99.9)).toBe(+ "About 1% of your trial allowance left. A long task may pause partway.",+ );+ });+});diff --git a/autogpt_platform/frontend/src/services/usageExperience/budget.ts b/autogpt_platform/frontend/src/services/usageExperience/budget.tsnew file mode 100644index 0000000000..9c21f15263--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/budget.ts@@ -0,0 +1,158 @@+type BudgetWindow = "daily" | "weekly" | "trial";+type RecurringWindow = "daily" | "weekly";++interface UsageWindowLike {+ percent_used: number;+ resets_at: string | Date;+}++interface UsageLike {+ daily?: UsageWindowLike | null;+ weekly?: UsageWindowLike | null;+ state?: "ok" | "low" | "exhausted";+ limiting_window?: BudgetWindow | null;+ resets_at?: string | Date | null;+}++export interface UsageBudget {+ state: "ok" | "low" | "exhausted";+ window: BudgetWindow | null;+ /** When the limiting window refills; null when nothing refills on its own. */+ resetsAt: Date | null;+ percentUsed: number | null;+}++export interface ResetWait {+ window: RecurringWindow;+ resetsAt: Date;+}++const LOW_PERCENT_USED = 80;+const NOTHING_LIMITING: UsageBudget = {+ state: "ok",+ window: null,+ resetsAt: null,+ percentUsed: null,+};++export function getUsageBudget(usage?: UsageLike | null): UsageBudget {+ if (!usage) return NOTHING_LIMITING;+ if (!usage.state) return estimateBudget(usage);+ const window = usage.limiting_window ?? null;+ return {+ state: usage.state,+ window,+ resetsAt: usage.state === "ok" ? null : toDate(usage.resets_at),+ percentUsed: window ? windowPercent(usage, window) : null,+ };+}++/** The reset a blocked chat can wait for, or null: trials, accounts without a+ * plan and an unknown reset have nothing that refills on its own. */+export function getResetWait(budget?: UsageBudget | null): ResetWait | null {+ if (!budget || budget.state !== "exhausted" || !budget.resetsAt) return null;+ if (budget.window !== "daily" && budget.window !== "weekly") return null;+ return { window: budget.window, resetsAt: budget.resetsAt };+}++export function budgetOutTitle(window: RecurringWindow) {+ return `You’re out of AutoPilot budget for ${window === "weekly" ? "this week" : "today"}`;+}++export function budgetResetSentence(wait: ResetWait, now = new Date()) {+ return `It resets ${formatResetMoment(wait, now)}. You can still browse, edit workflows and read results.`;+}++export function budgetLowHint(window: BudgetWindow, percentUsed: number) {+ const left = Math.max(1, Math.round(100 - percentUsed));+ const budget =+ window === "trial"+ ? "your trial allowance"+ : window === "weekly"+ ? "this week’s budget"+ : "today’s budget";+ return `About ${left}% of ${budget} left. A long task may pause partway.`;+}++export function formatResetClock(date: Date) {+ // Some ICU versions put a narrow no-break space before AM/PM.+ return date+ .toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })+ .replace(/ /g, " ");+}++export function formatWeekday(date: Date) {+ return date.toLocaleDateString(undefined, { weekday: "long" });+}++export function formatCountdown(date: Date, now = new Date()) {+ const minutes = Math.floor((date.getTime() - now.getTime()) / 60_000);+ if (minutes < 1) return "in under a minute";+ if (minutes < 60) return `in ${minutes} min`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) {+ const rest = minutes % 60;+ return rest ? `in ${hours} h ${rest} min` : `in ${hours} h`;+ }+ const days = Math.round(hours / 24);+ return days === 1 ? "in 1 day" : `in ${days} days`;+}++function formatResetMoment(wait: ResetWait, now: Date) {+ const clock = formatResetClock(wait.resetsAt);+ const when =+ wait.window === "weekly"+ ? `${formatWeekday(wait.resetsAt)} at ${clock}`+ : `at ${clock}`;+ return `${when}, ${formatCountdown(wait.resetsAt, now)}`;+}++// Older backends don't send the verdict. Without it there is no telling a+// window that refills from one that never does (a trial, or no plan), so an+// estimate never promises a reset.+function estimateBudget(usage: UsageLike): UsageBudget {+ const windows = (["daily", "weekly"] as const).flatMap((name) => {+ const reading = usage[name];+ return reading+ ? [{ name, percent: reading.percent_used, resetsAt: reading.resets_at }]+ : [];+ });+ const exhausted = windows.filter((reading) => reading.percent >= 100);+ if (exhausted.length > 0) {+ const last = exhausted.reduce((a, b) =>+ time(b.resetsAt) >= time(a.resetsAt) ? b : a,+ );+ return {+ state: "exhausted",+ window: last.name,+ resetsAt: null,+ percentUsed: 100,+ };+ }+ const tightest = windows.reduce<(typeof windows)[number] | null>(+ (a, b) => (!a || b.percent >= a.percent ? b : a),+ null,+ );+ if (!tightest || tightest.percent < LOW_PERCENT_USED) return NOTHING_LIMITING;+ return {+ state: "low",+ window: tightest.name,+ resetsAt: toDate(tightest.resetsAt),+ percentUsed: tightest.percent,+ };+}++function windowPercent(usage: UsageLike, window: BudgetWindow) {+ const reading = window === "trial" ? usage.weekly : usage[window];+ return reading?.percent_used ?? null;+}++function toDate(value: string | Date | null | undefined) {+ if (!value) return null;+ const date = new Date(value);+ return Number.isFinite(date.getTime()) ? date : null;+}++function time(value: string | Date) {+ return new Date(value).getTime() || 0;+}diff --git a/autogpt_platform/frontend/src/services/usageExperience/helpers.ts b/autogpt_platform/frontend/src/services/usageExperience/helpers.tsindex 1840805606..cb40cdbfa9 100644--- a/autogpt_platform/frontend/src/services/usageExperience/helpers.ts+++ b/autogpt_platform/frontend/src/services/usageExperience/helpers.ts@@ -6,6 +6,9 @@ interface Usage {tier?: string | null;daily?: UsageWindow | null;weekly?: UsageWindow | null;+ state?: string;+ limiting_window?: "daily" | "weekly" | "trial" | null;+ resets_at?: string | Date | null;}interface Trial {status?: string | null;@@ -66,15 +69,25 @@ export function getUsageExperience(: (["daily", "weekly"] as const).filter((key) => (usage?.[key]?.percent_used ?? 0) >= 100,);- const window = exhausted+ const clientWindow = exhausted? "trial": (recurring.sort((a, b) =>new Date(usage?.[b]?.resets_at ?? "").getTime() -new Date(usage?.[a]?.resets_at ?? "").getTime(),)[0] ?? null);+ // When a turn can't start, the server names the limit that decides, down+ // to a trial's own daily or weekly cap that the client can't tell apart+ // from its allowance.+ const window =+ usage?.state === "exhausted" && usage.limiting_window+ ? usage.limiting_window+ : clientWindow;const isTopTier =tier === "MAX" || tier === "BUSINESS" || tier === "ENTERPRISE";+ // The server knows when a window allows nothing (no plan, or a trial that+ // is over): it reports no reset, and none is shown.+ const refills = !(usage?.state === "exhausted" && usage.resets_at === null);return {tier,isActiveTrial,@@ -92,7 +105,7 @@ export function getUsageExperience(blocked: window !== null || !!inactiveTrialStatus,window,resetsAt:- window && window !== "trial"+ refills && window && window !== "trial"? (usage?.[window]?.resets_at ?? null): null,targetTier:diff --git a/autogpt_platform/frontend/src/services/usageExperience/presentation.ts b/autogpt_platform/frontend/src/services/usageExperience/presentation.tsindex 038894aa51..d18fbaaf04 100644--- a/autogpt_platform/frontend/src/services/usageExperience/presentation.ts+++ b/autogpt_platform/frontend/src/services/usageExperience/presentation.ts@@ -63,9 +63,11 @@ export function usagePresentation(: "Choose your next plan to continue. Your chats, agents and results are saved.": isTopTier? "Your chats, agents and results are saved."- : tier === "PRO"- ? `${resume}, or upgrade to Max for ${usageMultiplier ? `${usageMultiplier} times the usage` : "more usage"}.`- : `${resume}, or ${tier === "BASIC" ? "upgrade to Pro" : "start Pro"}.`,+ : !experience.resetsAt+ ? "Choose a plan to continue. Your chats, agents and results are saved."+ : tier === "PRO"+ ? `${resume}, or upgrade to Max for ${usageMultiplier ? `${usageMultiplier} times the usage` : "more usage"}.`+ : `${resume}, or ${tier === "BASIC" ? "upgrade to Pro" : "start Pro"}.`,supportLabel:tier === "ENTERPRISE"? "Contact your account team"@@ -76,7 +78,9 @@ export function usagePresentation(? experience.freshProUsage && trialDate? `Wait until ${trialDate}`: "Back to my work"- : "Wait for reset",+ : experience.resetsAt+ ? "Wait for reset"+ : "Back to my work",trialSpent,};}diff --git a/autogpt_platform/frontend/src/services/usageExperience/useUsageExperience.ts b/autogpt_platform/frontend/src/services/usageExperience/useUsageExperience.tsindex 8ac46504c0..29dd9a669c 100644--- a/autogpt_platform/frontend/src/services/usageExperience/useUsageExperience.ts+++ b/autogpt_platform/frontend/src/services/usageExperience/useUsageExperience.ts@@ -4,8 +4,14 @@ import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credimport { useCopilotUsage } from "@/app/(platform)/copilot/components/UsageLimits/useCopilotUsage";import { useTrialStatus } from "@/services/trials/useTrialStatus";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { getUsageBudget } from "./budget";import { getUsageExperience } from "./helpers";+export type UsageSnapshot = Pick<+ ReturnType<typeof useUsageExperience>,+ "budget" | "usage" | "experience"+>;+export function useUsageExperience() {const usage = useCopilotUsage();const trial = useTrialStatus();@@ -25,6 +31,7 @@ export function useUsageExperience() {experience.tier === "TRIAL" && (trial.isError || !trial.data);return {experience,+ budget: getUsageBudget(usage.data),usage: usage.data,trial: trial.data,subscription: subscription.data,