Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): surface clear file-size errors on image/logo uploads (#13684)

Abhimanyu Yadav97574d6afaa6
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/__tests__/OAuthAppsSection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/__tests__/OAuthAppsSection.test.tsx
new file mode 100644
index 0000000000..9f73b2ddcc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/__tests__/OAuthAppsSection.test.tsx
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+
+import { OAuthAppsSection } from "../OAuthAppsSection";
+
+const toastSpy = vi.hoisted(() => vi.fn());
+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/components/molecules/Toast/use-toast")
+ >();
+ return {
+ ...actual,
+ useToast: () => ({ toast: toastSpy, dismiss: () => {}, toasts: [] }),
+ };
+});
+
+const uploadSpy = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/direct-upload", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/direct-upload")>();
+ return { ...actual, uploadOAuthAppLogoDirect: uploadSpy };
+});
+
+const app = {
+ id: "app-1",
+ name: "My App",
+ client_id: "client-abc",
+ description: "An app",
+ logo_url: null,
+ redirect_uris: ["https://app.test/cb"],
+ grant_types: ["authorization_code"],
+ scopes: [],
+ owner_id: "user-1",
+ is_active: true,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+};
+
+vi.mock("@/app/api/__generated__/endpoints/oauth/oauth", () => ({
+ useGetOauthListMyOauthApps: () => ({ data: [app], isLoading: false }),
+ usePatchOauthUpdateAppStatus: () => ({ mutateAsync: vi.fn() }),
+ getGetOauthListMyOauthAppsQueryKey: () => ["oauth-apps"],
+}));
+
+function logoInput() {
+ return document.querySelector('input[type="file"]') as HTMLInputElement;
+}
+
+describe("OAuthAppsSection - logo upload", () => {
+ beforeEach(() => {
+ toastSpy.mockClear();
+ uploadSpy.mockClear();
+ });
+
+ it("uploads a logo and shows a success toast", async () => {
+ uploadSpy.mockResolvedValueOnce(undefined);
+
+ render(<OAuthAppsSection />);
+ await screen.findByText("My App");
+
+ const file = new File(["x"], "logo.png", { type: "image/png" });
+ fireEvent.change(logoInput(), { target: { files: [file] } });
+
+ await waitFor(() => {
+ expect(uploadSpy).toHaveBeenCalledWith("app-1", file);
+ expect(toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Success" }),
+ );
+ });
+ });
+
+ it("rejects an oversized logo before uploading and explains the 3MB limit", async () => {
+ render(<OAuthAppsSection />);
+ await screen.findByText("My App");
+
+ const bigFile = new File(["x"], "logo.png", { type: "image/png" });
+ Object.defineProperty(bigFile, "size", { value: 4 * 1024 * 1024 });
+ fireEvent.change(logoInput(), { target: { files: [bigFile] } });
+
+ await waitFor(() => {
+ expect(toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "File too large",
+ variant: "destructive",
+ }),
+ );
+ });
+ expect(uploadSpy).not.toHaveBeenCalled();
+ });
+
+ it("surfaces a destructive toast when the upload fails", async () => {
+ uploadSpy.mockRejectedValueOnce(new Error("boom"));
+
+ render(<OAuthAppsSection />);
+ await screen.findByText("My App");
+
+ const file = new File(["x"], "logo.png", { type: "image/png" });
+ fireEvent.change(logoInput(), { target: { files: [file] } });
+
+ await waitFor(() => {
+ expect(toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Error", variant: "destructive" }),
+ );
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.ts
index cf9749c53a..aa76e6fcf1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.ts
@@ -4,11 +4,15 @@ import { useState } from "react";
import {
useGetOauthListMyOauthApps,
usePatchOauthUpdateAppStatus,
- usePostOauthUploadAppLogo,
getGetOauthListMyOauthAppsQueryKey,
} from "@/app/api/__generated__/endpoints/oauth/oauth";
import { okData } from "@/app/api/helpers";
import { useToast } from "@/components/molecules/Toast/use-toast";
+import {
+ isFileTooLarge,
+ OAUTH_LOGO_MAX_SIZE_MB,
+ uploadOAuthAppLogoDirect,
+} from "@/lib/direct-upload";
import { getQueryClient } from "@/lib/react-query/queryClient";
export const useOAuthApps = () => {
@@ -31,16 +35,6 @@ export const useOAuthApps = () => {
},
});
- const { mutateAsync: uploadLogo } = usePostOauthUploadAppLogo({
- mutation: {
- onSettled: () => {
- return queryClient.invalidateQueries({
- queryKey: getGetOauthListMyOauthAppsQueryKey(),
- });
- },
- },
- });
-
const handleToggleStatus = async (appId: string, currentStatus: boolean) => {
try {
setUpdatingAppId(appId);
@@ -69,21 +63,16 @@ export const useOAuthApps = () => {
};
const handleUploadLogo = async (appId: string, file: File) => {
+ if (isFileTooLarge({ file, maxSizeMB: OAUTH_LOGO_MAX_SIZE_MB, toast }))
+ return;
+
try {
setUploadingAppId(appId);
- const result = await uploadLogo({
- appId,
- data: { file },
+ await uploadOAuthAppLogoDirect(appId, file);
+ toast({
+ title: "Success",
+ description: "Logo uploaded successfully",
});
-
- if (result.status === 200) {
- toast({
- title: "Success",
- description: "Logo uploaded successfully",
- });
- } else {
- throw new Error("Failed to upload logo");
- }
} catch (error) {
console.error("Failed to upload logo:", error);
const errorMessage =
@@ -95,6 +84,9 @@ export const useOAuthApps = () => {
});
} finally {
setUploadingAppId(null);
+ void queryClient.invalidateQueries({
+ queryKey: getGetOauthListMyOauthAppsQueryKey(),
+ });
}
};
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx
index 28dd1f8a88..34a9f6f9d4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx
@@ -14,8 +14,6 @@ import {
getGetV2GetUserProfileMockHandler401,
getPostV2UpdateUserProfileMockHandler200,
getPostV2UpdateUserProfileMockHandler422,
- getPostV2UploadSubmissionMediaMockHandler200,
- getPostV2UploadSubmissionMediaMockHandler401,
} from "@/app/api/__generated__/endpoints/store/store.msw";
import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
@@ -23,11 +21,20 @@ import SettingsProfilePage from "../page";
const mockUseSupabase = vi.hoisted(() => vi.fn());
const toastSpy = vi.hoisted(() => vi.fn());
+const uploadAvatarSpy = vi.hoisted(() => vi.fn());
vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
useSupabase: mockUseSupabase,
}));
+vi.mock("@/lib/direct-upload", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/direct-upload")>();
+ return {
+ ...actual,
+ uploadSubmissionMediaDirect: uploadAvatarSpy,
+ };
+});
+
vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
const actual =
await importOriginal<
@@ -597,11 +604,9 @@ describe("SettingsProfilePage - save & discard", () => {
describe("SettingsProfilePage - avatar upload", () => {
test("uploading an avatar updates the form state", async () => {
- server.use(
- getGetV2GetUserProfileMockHandler200(makeProfile()),
- getPostV2UploadSubmissionMediaMockHandler200(
- "https://cdn.example.com/uploaded.png",
- ),
+ server.use(getGetV2GetUserProfileMockHandler200(makeProfile()));
+ uploadAvatarSpy.mockResolvedValueOnce(
+ "https://cdn.example.com/uploaded.png",
);
render(<SettingsProfilePage />);
@@ -628,10 +633,8 @@ describe("SettingsProfilePage - avatar upload", () => {
});
test("upload error surfaces a destructive toast", async () => {
- server.use(
- getGetV2GetUserProfileMockHandler200(makeProfile()),
- getPostV2UploadSubmissionMediaMockHandler401(),
- );
+ server.use(getGetV2GetUserProfileMockHandler200(makeProfile()));
+ uploadAvatarSpy.mockRejectedValueOnce(new Error("Unauthorized"));
render(<SettingsProfilePage />);
@@ -652,6 +655,33 @@ describe("SettingsProfilePage - avatar upload", () => {
);
});
});
+
+ test("rejects an oversized avatar before uploading and explains the limit", async () => {
+ server.use(getGetV2GetUserProfileMockHandler200(makeProfile()));
+ toastSpy.mockClear();
+ uploadAvatarSpy.mockClear();
+
+ render(<SettingsProfilePage />);
+
+ await screen.findByLabelText(/display name/i);
+
+ const fileInput = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const bigFile = new File(["x"], "avatar.png", { type: "image/png" });
+ Object.defineProperty(bigFile, "size", { value: 51 * 1024 * 1024 });
+ fireEvent.change(fileInput, { target: { files: [bigFile] } });
+
+ await waitFor(() => {
+ expect(toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "File too large",
+ variant: "destructive",
+ }),
+ );
+ });
+ expect(uploadAvatarSpy).not.toHaveBeenCalled();
+ });
});
describe("SettingsProfilePage - skeleton & nullish profile fields", () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts b/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts
index 395b323a45..4594d46ae2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts
@@ -7,10 +7,14 @@ import {
getGetV2GetUserProfileQueryKey,
useGetV2GetUserProfile,
usePostV2UpdateUserProfile,
- usePostV2UploadSubmissionMedia,
} from "@/app/api/__generated__/endpoints/store/store";
import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
import { toast } from "@/components/molecules/Toast/use-toast";
+import {
+ isFileTooLarge,
+ SUBMISSION_MEDIA_MAX_SIZE_MB,
+ uploadSubmissionMediaDirect,
+} from "@/lib/direct-upload";
import { ApiError, isLogoutInProgress } from "@/lib/autogpt-server-api/helpers";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
@@ -148,28 +152,29 @@ export function useProfilePage() {
setFormState(pristineState);
}
- const uploadMutation = usePostV2UploadSubmissionMedia({
- mutation: {
- onError: (err) => {
- toast({
- title: "Failed to upload photo",
- description: err instanceof Error ? err.message : undefined,
- variant: "destructive",
- });
- },
- },
- });
+ const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
async function uploadAvatar(file: File): Promise<string | null> {
+ if (
+ isFileTooLarge({ file, maxSizeMB: SUBMISSION_MEDIA_MAX_SIZE_MB, toast })
+ )
+ return null;
+
+ setIsUploadingAvatar(true);
try {
- const res = await uploadMutation.mutateAsync({ data: { file } });
- if (res.status !== 200) return null;
- const url = String(res.data ?? "").trim();
+ const url = (await uploadSubmissionMediaDirect(file)).trim();
if (!url) return null;
patchField("avatar_url", url);
return url;
- } catch {
+ } catch (err) {
+ toast({
+ title: "Failed to upload photo",
+ description: err instanceof Error ? err.message : undefined,
+ variant: "destructive",
+ });
return null;
+ } finally {
+ setIsUploadingAvatar(false);
}
}
@@ -220,7 +225,7 @@ export function useProfilePage() {
removeLink,
discardChanges,
uploadAvatar,
- isUploading: uploadMutation.isPending,
+ isUploading: isUploadingAvatar,
saveProfile,
isSaving: updateMutation.isPending,
dirty,
diff --git a/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx b/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
index 5d52449a8f..d96a79224d 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
+++ b/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
@@ -7,12 +7,18 @@ import Image from "next/image";
import { IconPersonFill } from "@/components/__legacy__/ui/icons";
import { Separator } from "@/components/__legacy__/ui/separator";
import { postV2UpdateUserProfile } from "@/app/api/__generated__/endpoints/store/store";
-import { postV2UploadSubmissionMedia } from "@/app/api/__generated__/endpoints/store/store";
import { resolveResponse } from "@/app/api/helpers";
import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import {
+ isFileTooLarge,
+ SUBMISSION_MEDIA_MAX_SIZE_MB,
+ uploadSubmissionMediaDirect,
+} from "@/lib/direct-upload";
import { Button } from "./Button";
export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
+ const { toast } = useToast();
const [isSubmitting, setIsSubmitting] = useState(false);
const [profileData, setProfileData] = useState<ProfileDetails>(profile);
@@ -42,11 +48,13 @@ export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
}
async function handleImageUpload(file: File) {
+ if (
+ isFileTooLarge({ file, maxSizeMB: SUBMISSION_MEDIA_MAX_SIZE_MB, toast })
+ )
+ return;
+
try {
- const mediaRes = await resolveResponse(
- postV2UploadSubmissionMedia({ file }),
- );
- const mediaUrl = String(mediaRes ?? "");
+ const mediaUrl = await uploadSubmissionMediaDirect(file);
const updatedProfile = {
...profileData,
@@ -58,7 +66,11 @@ export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
);
if (returnedProfile) setProfileData(returnedProfile);
} catch (error) {
- console.error("Error uploading image:", error);
+ toast({
+ title: "Failed to upload photo",
+ description: error instanceof Error ? error.message : undefined,
+ variant: "destructive",
+ });
}
}
diff --git a/autogpt_platform/frontend/src/components/__legacy__/__tests__/ProfileInfoForm.test.tsx b/autogpt_platform/frontend/src/components/__legacy__/__tests__/ProfileInfoForm.test.tsx
index 3ee732912c..49b0a3a37e 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/__tests__/ProfileInfoForm.test.tsx
+++ b/autogpt_platform/frontend/src/components/__legacy__/__tests__/ProfileInfoForm.test.tsx
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import {
fireEvent,
render,
@@ -14,6 +14,28 @@ import { server } from "@/mocks/mock-server";
import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
import { ProfileInfoForm } from "../ProfileInfoForm";
+const toastSpy = vi.hoisted(() => vi.fn());
+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/components/molecules/Toast/use-toast")
+ >();
+ return {
+ ...actual,
+ useToast: () => ({ toast: toastSpy, dismiss: () => {}, toasts: [] }),
+ };
+});
+
+const uploadSpy = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/direct-upload", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/direct-upload")>();
+ return { ...actual, uploadSubmissionMediaDirect: uploadSpy };
+});
+
+function fileInput() {
+ return document.querySelector('input[type="file"]') as HTMLInputElement;
+}
+
function makeProfile(overrides: Partial<ProfileDetails> = {}): ProfileDetails {
return {
name: "Initial Name",
@@ -91,4 +113,45 @@ describe("ProfileInfoForm", () => {
).toBeGreaterThan(0);
});
});
+
+ it("uploads a new avatar and persists it via the profile update", async () => {
+ toastSpy.mockClear();
+ uploadSpy.mockClear();
+ uploadSpy.mockResolvedValueOnce("https://cdn.test/new-avatar.png");
+ server.use(
+ getPostV2UpdateUserProfileMockHandler200(async () =>
+ makeProfile({ avatar_url: "https://cdn.test/new-avatar.png" }),
+ ),
+ );
+
+ render(<ProfileInfoForm profile={makeProfile()} />);
+
+ const file = new File(["x"], "avatar.png", { type: "image/png" });
+ fireEvent.change(fileInput(), { target: { files: [file] } });
+
+ await waitFor(() => {
+ expect(uploadSpy).toHaveBeenCalledWith(file);
+ });
+ });
+
+ it("rejects an oversized avatar before uploading and explains the limit", async () => {
+ toastSpy.mockClear();
+ uploadSpy.mockClear();
+
+ render(<ProfileInfoForm profile={makeProfile()} />);
+
+ const bigFile = new File(["x"], "avatar.png", { type: "image/png" });
+ Object.defineProperty(bigFile, "size", { value: 51 * 1024 * 1024 });
+ fireEvent.change(fileInput(), { target: { files: [bigFile] } });
+
+ await waitFor(() => {
+ expect(toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "File too large",
+ variant: "destructive",
+ }),
+ );
+ });
+ expect(uploadSpy).not.toHaveBeenCalled();
+ });
});
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsx b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsx
index 8c2e15c270..8aebf3ab6f 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsx
@@ -1,10 +1,6 @@
import { describe, expect, it, vi } from "vitest";
-import {
- getPostV2GenerateSubmissionImageMockHandler,
- getPostV2UploadSubmissionMediaMockHandler,
- getPostV2UploadSubmissionMediaMockHandler422,
-} from "@/app/api/__generated__/endpoints/store/store.msw";
+import { getPostV2GenerateSubmissionImageMockHandler } from "@/app/api/__generated__/endpoints/store/store.msw";
import { server } from "@/mocks/mock-server";
import {
fireEvent,
@@ -31,6 +27,20 @@ vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
};
});
+const uploadSpy = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/direct-upload", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/direct-upload")>();
+ return {
+ ...actual,
+ uploadSubmissionMediaDirect: uploadSpy,
+ };
+});
+
+function selectFile(input: HTMLInputElement, file: File) {
+ Object.defineProperty(input, "files", { value: [file], configurable: true });
+ fireEvent.change(input);
+}
+
describe("ThumbnailImages", () => {
it("renders the empty state with an Add image label and Generate button", () => {
render(
@@ -77,11 +87,7 @@ describe("ThumbnailImages", () => {
});
it("uploads a file via the empty-state input and shows the new image", async () => {
- server.use(
- getPostV2UploadSubmissionMediaMockHandler(
- "https://cdn.test/uploaded.png",
- ),
- );
+ uploadSpy.mockResolvedValueOnce("https://cdn.test/uploaded.png");
const onImagesChange = vi.fn();
render(
@@ -93,9 +99,7 @@ describe("ThumbnailImages", () => {
);
const input = document.getElementById("image-upload") as HTMLInputElement;
- const file = new File(["data"], "thumb.png", { type: "image/png" });
- Object.defineProperty(input, "files", { value: [file] });
- fireEvent.change(input);
+ selectFile(input, new File(["data"], "thumb.png", { type: "image/png" }));
await waitFor(() => {
expect(onImagesChange).toHaveBeenCalledWith([
@@ -104,9 +108,9 @@ describe("ThumbnailImages", () => {
});
});
- it("shows a destructive toast when the upload endpoint fails", async () => {
+ it("shows a destructive toast when the upload fails", async () => {
toastSpy.mockClear();
- server.use(getPostV2UploadSubmissionMediaMockHandler422());
+ uploadSpy.mockRejectedValueOnce(new Error("Upload failed on server"));
render(
<ThumbnailImages
@@ -117,9 +121,7 @@ describe("ThumbnailImages", () => {
);
const input = document.getElementById("image-upload") as HTMLInputElement;
- const file = new File(["data"], "thumb.png", { type: "image/png" });
- Object.defineProperty(input, "files", { value: [file] });
- fireEvent.change(input);
+ selectFile(input, new File(["data"], "thumb.png", { type: "image/png" }));
await waitFor(() => {
expect(toastSpy).toHaveBeenCalledWith(
@@ -131,6 +133,34 @@ describe("ThumbnailImages", () => {
});
});
+ it("rejects an oversized file before uploading and explains the size limit", async () => {
+ toastSpy.mockClear();
+ uploadSpy.mockClear();
+
+ render(
+ <ThumbnailImages
+ agentId="agent-1"
+ onImagesChange={() => {}}
+ initialImages={[]}
+ />,
+ );
+
+ const input = document.getElementById("image-upload") as HTMLInputElement;
+ const bigFile = new File(["x"], "big.png", { type: "image/png" });
+ Object.defineProperty(bigFile, "size", { value: 51 * 1024 * 1024 });
+ selectFile(input, bigFile);
+
+ await waitFor(() => {
+ expect(toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "File too large",
+ variant: "destructive",
+ }),
+ );
+ });
+ expect(uploadSpy).not.toHaveBeenCalled();
+ });
+
it("generates an image when the Generate button is clicked", async () => {
server.use(
getPostV2GenerateSubmissionImageMockHandler({
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts
index 4ea15ef2fc..23df674161 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts
@@ -1,10 +1,12 @@
import { useState, useRef, useEffect } from "react";
-import {
- postV2UploadSubmissionMedia,
- postV2GenerateSubmissionImage,
-} from "@/app/api/__generated__/endpoints/store/store";
+import { postV2GenerateSubmissionImage } from "@/app/api/__generated__/endpoints/store/store";
import { resolveResponse } from "@/app/api/helpers";
import { useToast } from "@/components/molecules/Toast/use-toast";
+import {
+ isFileTooLarge,
+ SUBMISSION_MEDIA_MAX_SIZE_MB,
+ uploadSubmissionMediaDirect,
+} from "@/lib/direct-upload";
interface UseThumbnailImagesProps {
agentId: string | null;
@@ -102,12 +104,14 @@ export function useThumbnailImages({
}
async function uploadImage(file: File) {
+ if (
+ isFileTooLarge({ file, maxSizeMB: SUBMISSION_MEDIA_MAX_SIZE_MB, toast })
+ )
+ return;
+
setIsUploading(true);
try {
- const mediaRes = await resolveResponse(
- postV2UploadSubmissionMedia({ file }),
- );
- const imageUrl = mediaRes.replace(/^"(.*)"$/, "$1");
+ const imageUrl = await uploadSubmissionMediaDirect(file);
setImagesWithValidation([...images, imageUrl]);
if (!selectedImage) {
diff --git a/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts b/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts
new file mode 100644
index 0000000000..1d92358acc
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts
@@ -0,0 +1,239 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ getFileSizeError,
+ OAUTH_LOGO_MAX_SIZE_MB,
+ SUBMISSION_MEDIA_MAX_SIZE_MB,
+ uploadFileDirect,
+ uploadOAuthAppLogoDirect,
+ uploadSubmissionMediaDirect,
+} from "../direct-upload";
+
+const getTokenMock = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/supabase/actions", () => ({
+ getWebSocketToken: getTokenMock,
+}));
+
+beforeEach(() => {
+ getTokenMock.mockResolvedValue({ token: "test-token" });
+});
+
+vi.mock("@/services/environment", () => ({
+ environment: {
+ getAGPTServerBaseUrl: () => "http://backend.test",
+ },
+}));
+
+interface FakeResponse {
+ ok: boolean;
+ status: number;
+ statusText?: string;
+ json?: () => unknown;
+ text?: () => string | Promise<string>;
+}
+
+function mockFetchOnce(response: FakeResponse) {
+ const fetchMock = vi.fn(
+ async (_url: string, _init?: RequestInit) =>
+ response as unknown as Response,
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function makeFile(sizeBytes: number, type = "image/png"): File {
+ return new File(["x".repeat(sizeBytes)], "logo.png", { type });
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+describe("getFileSizeError", () => {
+ it("returns null when the file is within the limit", () => {
+ const file = makeFile(1024);
+ expect(getFileSizeError(file, SUBMISSION_MEDIA_MAX_SIZE_MB)).toBeNull();
+ });
+
+ it("returns a message naming the limit when the file is too large", () => {
+ const file = makeFile(OAUTH_LOGO_MAX_SIZE_MB * 1024 * 1024 + 1);
+ const message = getFileSizeError(file, OAUTH_LOGO_MAX_SIZE_MB);
+ expect(message).toContain("too large");
+ expect(message).toContain(`${OAUTH_LOGO_MAX_SIZE_MB}MB`);
+ });
+});
+
+describe("uploadSubmissionMediaDirect", () => {
+ it("bypasses the proxy and hits the backend directly", async () => {
+ const fetchMock = mockFetchOnce({
+ ok: true,
+ status: 200,
+ json: () => "https://cdn.test/uploaded.png",
+ });
+
+ const url = await uploadSubmissionMediaDirect(makeFile(10));
+
+ expect(url).toBe("https://cdn.test/uploaded.png");
+ expect(fetchMock).toHaveBeenCalledWith(
+ "http://backend.test/api/store/submissions/media",
+ expect.objectContaining({
+ method: "POST",
+ headers: { Authorization: "Bearer test-token" },
+ }),
+ );
+ expect(fetchMock.mock.calls[0]?.[1]?.body).toBeInstanceOf(FormData);
+ });
+
+ it("surfaces a clear size message on HTTP 413 instead of a bare status", async () => {
+ mockFetchOnce({ ok: false, status: 413, statusText: "Payload Too Large" });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ /too large/i,
+ );
+ });
+
+ it("surfaces the backend detail message when the backend rejects the size", async () => {
+ mockFetchOnce({
+ ok: false,
+ status: 400,
+ text: () =>
+ JSON.stringify({ detail: "File too large. Maximum size is 50MB" }),
+ });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ "File too large. Maximum size is 50MB",
+ );
+ });
+});
+
+describe("uploadOAuthAppLogoDirect", () => {
+ it("posts to the app-scoped logo endpoint", async () => {
+ const fetchMock = mockFetchOnce({
+ ok: true,
+ status: 200,
+ json: () => ({}),
+ });
+
+ await uploadOAuthAppLogoDirect("app-123", makeFile(10));
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "http://backend.test/api/oauth/apps/app-123/logo/upload",
+ expect.objectContaining({
+ method: "POST",
+ headers: { Authorization: "Bearer test-token" },
+ }),
+ );
+ expect(fetchMock.mock.calls[0]?.[1]?.body).toBeInstanceOf(FormData);
+ });
+
+ it("throws a clear size message on 413", async () => {
+ mockFetchOnce({ ok: false, status: 413, statusText: "Payload Too Large" });
+
+ await expect(
+ uploadOAuthAppLogoDirect("app-123", makeFile(10)),
+ ).rejects.toThrow(/too large/i);
+ });
+});
+
+describe("uploadFileDirect (workspace)", () => {
+ it("hits the workspace endpoint with overwrite and session params", async () => {
+ const fetchMock = mockFetchOnce({
+ ok: true,
+ status: 200,
+ json: () => ({
+ file_id: "f1",
+ name: "a.png",
+ path: "p",
+ mime_type: "image/png",
+ size_bytes: 10,
+ }),
+ });
+
+ const result = await uploadFileDirect(makeFile(10), "sess-1");
+
+ expect(result.file_id).toBe("f1");
+ const calledUrl = fetchMock.mock.calls[0]?.[0] as string;
+ expect(calledUrl).toContain(
+ "http://backend.test/api/workspace/files/upload",
+ );
+ expect(calledUrl).toContain("overwrite=true");
+ expect(calledUrl).toContain("session_id=sess-1");
+ });
+});
+
+describe("authentication", () => {
+ it("throws an auth error when no token is available", async () => {
+ getTokenMock.mockResolvedValueOnce({ token: null, error: "no session" });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ /sign in again/i,
+ );
+ });
+});
+
+describe("readUploadError fallbacks", () => {
+ it("surfaces the raw response body when it is not JSON", async () => {
+ mockFetchOnce({
+ ok: false,
+ status: 500,
+ statusText: "Internal Server Error",
+ text: () => "upstream connection reset",
+ });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ "upstream connection reset",
+ );
+ });
+
+ it("falls back to statusText when the body is empty", async () => {
+ mockFetchOnce({
+ ok: false,
+ status: 500,
+ statusText: "Internal Server Error",
+ text: () => "",
+ });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ "Internal Server Error",
+ );
+ });
+
+ it("falls back to the HTTP status when there is no statusText or body", async () => {
+ mockFetchOnce({
+ ok: false,
+ status: 500,
+ statusText: "",
+ text: () => "",
+ });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ "Upload failed (HTTP 500)",
+ );
+ });
+
+ it("reads a nested detail.message object", async () => {
+ mockFetchOnce({
+ ok: false,
+ status: 400,
+ text: () =>
+ JSON.stringify({ detail: { message: "nested detail message" } }),
+ });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ "nested detail message",
+ );
+ });
+
+ it("reads a top-level message field", async () => {
+ mockFetchOnce({
+ ok: false,
+ status: 400,
+ text: () => JSON.stringify({ message: "top level message" }),
+ });
+
+ await expect(uploadSubmissionMediaDirect(makeFile(10))).rejects.toThrow(
+ "top level message",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/direct-upload.ts b/autogpt_platform/frontend/src/lib/direct-upload.ts
index c6050fc84a..b41078915e 100644
--- a/autogpt_platform/frontend/src/lib/direct-upload.ts
+++ b/autogpt_platform/frontend/src/lib/direct-upload.ts
@@ -1,7 +1,7 @@
import { getWebSocketToken } from "@/lib/supabase/actions";
import { environment } from "@/services/environment";
-interface UploadFileResponse {
+interface WorkspaceUploadResponse {
file_id: string;
name: string;
path: string;
@@ -10,49 +10,156 @@ interface UploadFileResponse {
}
/**
- * Upload a file directly to the Python backend, bypassing the Next.js proxy.
- * The Next.js serverless proxy has a ~4.5MB body size limit (Vercel) which
- * rejects larger files with HTTP 413.
+ * Uploads here go straight to the Python backend, bypassing the Next.js
+ * serverless proxy. The proxy has a ~4.5MB body size limit (Vercel) that
+ * rejects larger files with HTTP 413 *before* the request reaches the backend,
+ * where the 413 body carries no useful message. Going direct lets the real
+ * backend size limits apply and surfaces the backend's own error messages.
*/
-export async function uploadFileDirect(
- file: File,
- sessionID?: string,
-): Promise<UploadFileResponse> {
+
+// Backend upload size limits (keep in sync with the backend):
+// - store submission media (agent thumbnails, profile avatars): 50MB
+// (backend/api/features/store/media.py)
+// - OAuth app logos: 3MB (backend/api/features/oauth.py)
+export const SUBMISSION_MEDIA_MAX_SIZE_MB = 50;
+export const OAUTH_LOGO_MAX_SIZE_MB = 3;
+
+const BYTES_PER_MB = 1024 * 1024;
+const UPLOAD_TIMEOUT_MS = 5 * 60 * 1000;
+
+/**
+ * Returns a user-facing message when a file exceeds `maxSizeMB`, or null when
+ * it is within the limit. Lets callers reject oversized files before uploading.
+ */
+export function getFileSizeError(file: File, maxSizeMB: number): string | null {
+ if (file.size <= maxSizeMB * BYTES_PER_MB) return null;
+ const sizeMB = (file.size / BYTES_PER_MB).toFixed(1);
+ return `File is too large (${sizeMB}MB). Maximum size is ${maxSizeMB}MB — please choose a smaller file.`;
+}
+
+interface FileSizeGuardArgs {
+ file: File;
+ maxSizeMB: number;
+ toast: (options: {
+ title: string;
+ description?: string;
+ variant?: "destructive";
+ }) => void;
+}
+
+export function isFileTooLarge({
+ file,
+ maxSizeMB,
+ toast,
+}: FileSizeGuardArgs): boolean {
+ const error = getFileSizeError(file, maxSizeMB);
+ if (!error) return false;
+ toast({
+ title: "File too large",
+ description: error,
+ variant: "destructive",
+ });
+ return true;
+}
+
+interface DirectUploadArgs {
+ path: string;
+ file: File;
+ searchParams?: Record<string, string>;
+}
+
+async function postFileToBackend({
+ path,
+ file,
+ searchParams,
+}: DirectUploadArgs): Promise<Response> {
const { token, error: tokenError } = await getWebSocketToken();
if (tokenError || !token) {
throw new Error("Authentication error — please sign in again.");
}
- const backendBase = environment.getAGPTServerBaseUrl();
- const url = new URL("/api/workspace/files/upload", backendBase);
- if (sessionID) {
- url.searchParams.set("session_id", sessionID);
+ const url = new URL(path, environment.getAGPTServerBaseUrl());
+ for (const [key, value] of Object.entries(searchParams ?? {})) {
+ url.searchParams.set(key, value);
}
- url.searchParams.set("overwrite", "true");
const formData = new FormData();
formData.append("file", file);
- const res = await fetch(url.toString(), {
+ return fetch(url.toString(), {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
body: formData,
+ // Guard against a stalled connection leaving the UI stuck "Uploading…".
+ // Generous so large (up to 50MB) uploads on slow links aren't cut off.
+ signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
});
+}
- if (!res.ok) {
- let message: string;
- try {
- const body = await res.json();
- // Backend returns { detail: "..." } or { detail: { message: "..." } }
- message =
- typeof body.detail === "string"
- ? body.detail
- : (body.detail?.message ?? res.statusText);
- } catch {
- message = res.statusText;
- }
- throw new Error(message);
+async function readUploadError(res: Response): Promise<string> {
+ // A proxy/ingress in front of the backend may still reject an oversized body
+ // with a 413 whose payload isn't backend JSON — surface a clear size message
+ // instead of a bare "HTTP 413".
+ if (res.status === 413) {
+ return "File is too large. Please choose a smaller file.";
+ }
+ const text = await res.text();
+ try {
+ const body = JSON.parse(text) as {
+ detail?: string | { message?: string };
+ message?: string;
+ };
+ // Backend returns { detail: "..." } or { detail: { message: "..." } }.
+ const detail = body?.detail;
+ if (typeof detail === "string") return detail;
+ if (typeof detail?.message === "string") return detail.message;
+ if (typeof body?.message === "string") return body.message;
+ } catch {
+ // Response body wasn't JSON — surface the raw text so it reaches the toast.
+ if (text) return text;
}
+ return res.statusText || `Upload failed (HTTP ${res.status})`;
+}
+export async function uploadFileDirect(
+ file: File,
+ sessionID?: string,
+): Promise<WorkspaceUploadResponse> {
+ const res = await postFileToBackend({
+ path: "/api/workspace/files/upload",
+ file,
+ searchParams: {
+ overwrite: "true",
+ ...(sessionID ? { session_id: sessionID } : {}),
+ },
+ });
+ if (!res.ok) throw new Error(await readUploadError(res));
return res.json();
}
+
+/**
+ * Uploads store submission media (agent thumbnails, profile avatars) directly
+ * to the backend. Returns the public URL of the stored media.
+ */
+export async function uploadSubmissionMediaDirect(file: File): Promise<string> {
+ const res = await postFileToBackend({
+ path: "/api/store/submissions/media",
+ file,
+ });
+ if (!res.ok) throw new Error(await readUploadError(res));
+ // The endpoint returns the URL as a JSON string.
+ const url = (await res.json()) as unknown;
+ return typeof url === "string" ? url : String(url);
+}
+
+/** Uploads an OAuth application logo directly to the backend. */
+export async function uploadOAuthAppLogoDirect(
+ appId: string,
+ file: File,
+): Promise<void> {
+ const res = await postFileToBackend({
+ path: `/api/oauth/apps/${encodeURIComponent(appId)}/logo/upload`,
+ file,
+ });
+ if (!res.ok) throw new Error(await readUploadError(res));
+}