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): re-land proxy streaming + medium-impact auth cleanup (#13024)
Ubbe3a1e21160cbf
diff --git a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.tsindex 89b17866c3..6f6a28e590 100644--- a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts@@ -183,3 +183,83 @@ describe("customMutator — Sentry trace propagation", () => {(Sentry as { getTraceData?: unknown }).getTraceData = mockGetTraceData;});});++describe("customMutator — empty body handling", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockIsClientSide.mockReturnValue(true);+ mockGetSystemHeaders.mockReturnValue({});+ mockGetTraceData.mockReturnValue({});+ });++ it("returns null data for 204 No Content even when Content-Type is application/json", async () => {+ // FastAPI sets Content-Type: application/json on 204 by default; the proxy+ // forwards it. Calling .json() on the empty body would throw — verify we+ // short-circuit and return null instead.+ const jsonSpy = vi.fn();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ status: 204,+ headers: new Headers({ "content-type": "application/json" }),+ json: jsonSpy,+ }),+ );++ const result = await customMutator<{+ data: unknown;+ status: number;+ headers: Headers;+ }>("/api/executions/abc", { method: "DELETE" });++ expect(result.status).toBe(204);+ expect(result.data).toBeNull();+ expect(jsonSpy).not.toHaveBeenCalled();+ });++ it("returns null data when Content-Length is 0", async () => {+ const jsonSpy = vi.fn();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: new Headers({+ "content-type": "application/json",+ "content-length": "0",+ }),+ json: jsonSpy,+ }),+ );++ const result = await customMutator<{+ data: unknown;+ status: number;+ headers: Headers;+ }>("/api/foo", { method: "DELETE" });++ expect(result.data).toBeNull();+ expect(jsonSpy).not.toHaveBeenCalled();+ });++ it("still parses JSON body for non-empty 200 responses", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: new Headers({ "content-type": "application/json" }),+ json: () => Promise.resolve({ ok: true }),+ }),+ );++ const result = await customMutator<{+ data: unknown;+ status: number;+ headers: Headers;+ }>("/api/foo", { method: "GET" });++ expect(result.data).toEqual({ ok: true });+ });+});diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.tsindex 019e911fbf..f4c6656f29 100644--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts@@ -21,7 +21,18 @@ const getBaseUrl = (): string => {}};-const getBody = <T>(c: Response | Request): Promise<T> => {+const getBody = async <T>(c: Response | Request): Promise<T> => {+ // 204 No Content responses (and 200s with Content-Length: 0) have no body.+ // Calling .json() on them throws "Unexpected end of JSON input" because the+ // backend may still set Content-Type: application/json on 204s. Short-circuit+ // to null so callers see a normal success rather than a parse error.+ if (+ "status" in c &&+ (c.status === 204 || c.headers.get("Content-Length") === "0")+ ) {+ return null as T;+ }+const contentType = c.headers.get("content-type");if (contentType && contentType.includes("application/json")) {diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.tsnew file mode 100644index 0000000000..e088c12680--- /dev/null+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts@@ -0,0 +1,264 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@/lib/autogpt-server-api/helpers", () => ({+ getServerAuthToken: vi.fn(),+}));++vi.mock("@/services/environment", () => ({+ environment: {+ getAGPTServerBaseUrl: vi.fn(() => "https://backend.test"),+ },+}));++import { getServerAuthToken } from "@/lib/autogpt-server-api/helpers";+import { GET, POST } from "../route";++const BACKEND = "https://backend.test";++function makeParams(path: string[]) {+ return { params: Promise.resolve({ path }) };+}++describe("proxy route — handler pass-through", () => {+ beforeEach(() => {+ vi.mocked(getServerAuthToken).mockResolvedValue("test-token");+ vi.stubGlobal("fetch", vi.fn());+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("forwards GET with Authorization header injected from server token", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response(JSON.stringify({ hello: "world" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items");+ const res = await GET(req, makeParams(["api", "v1", "items"]));++ expect(fetch).toHaveBeenCalledOnce();+ const [calledUrl, init] = vi.mocked(fetch).mock.calls[0];+ expect(calledUrl).toBe(`${BACKEND}/api/v1/items`);+ const sentHeaders = init!.headers as Headers;+ expect(sentHeaders.get("authorization")).toBe("Bearer test-token");++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ hello: "world" });+ });++ it("preserves status, statusText, and body on 4xx error responses", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response(JSON.stringify({ detail: "not found" }), {+ status: 404,+ statusText: "Not Found",+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/missing");+ const res = await GET(req, makeParams(["api", "v1", "missing"]));++ expect(res.status).toBe(404);+ expect(res.statusText).toBe("Not Found");+ expect(await res.json()).toEqual({ detail: "not found" });+ });++ it("passes 204 No Content through with empty body even when backend sets Content-Type: application/json", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response(null, {+ status: 204,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/x", {+ method: "DELETE",+ });+ const { DELETE } = await import("../route");+ const res = await DELETE(req, makeParams(["api", "v1", "x"]));++ expect(res.status).toBe(204);+ const text = await res.text();+ expect(text).toBe("");+ });++ it("strips content-length and content-encoding from response headers but preserves others", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ status: 200,+ headers: {+ "Content-Type": "application/json",+ "Content-Length": "1234",+ "Content-Encoding": "gzip",+ "Cache-Control": "no-store",+ "X-Custom-Header": "preserved",+ },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items");+ const res = await GET(req, makeParams(["api", "v1", "items"]));++ expect(res.headers.get("content-encoding")).toBeNull();+ expect(res.headers.get("content-length")).toBeNull();+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(res.headers.get("x-custom-header")).toBe("preserved");+ expect(res.headers.get("content-type")).toBe("application/json");+ });++ it("strips Set-Cookie so backend cookies cannot attach to the frontend origin", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ status: 200,+ headers: {+ "Content-Type": "application/json",+ "Set-Cookie": "session=leak; Path=/; HttpOnly",+ },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items");+ const res = await GET(req, makeParams(["api", "v1", "items"]));++ expect(res.headers.get("set-cookie")).toBeNull();+ });++ it("forwards POST body with duplex: 'half' for streaming", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response(JSON.stringify({ created: true }), {+ status: 201,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items", {+ method: "POST",+ body: JSON.stringify({ name: "foo" }),+ headers: { "Content-Type": "application/json" },+ });+ const res = await POST(req, makeParams(["api", "v1", "items"]));++ const init = vi.mocked(fetch).mock.calls[0][1] as RequestInit & {+ duplex?: string;+ };+ expect(init.method).toBe("POST");+ expect(init.duplex).toBe("half");+ expect(init.body).toBeDefined();+ expect(res.status).toBe(201);+ });++ it("does NOT forward the request Cookie header to the backend", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response("{}", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items", {+ headers: {+ Cookie: "sb-access-token=secret; sb-refresh-token=secret-refresh",+ },+ });+ await GET(req, makeParams(["api", "v1", "items"]));++ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;+ expect(sentHeaders.get("cookie")).toBeNull();+ expect(sentHeaders.get("authorization")).toBe("Bearer test-token");+ });++ it("forwards allowlisted Sentry trace headers", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response("{}", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items", {+ headers: {+ "sentry-trace": "abc123-def456-1",+ baggage: "sentry-trace_id=abc123",+ },+ });+ await GET(req, makeParams(["api", "v1", "items"]));++ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;+ expect(sentHeaders.get("sentry-trace")).toBe("abc123-def456-1");+ expect(sentHeaders.get("baggage")).toBe("sentry-trace_id=abc123");+ });++ it("omits Authorization header when no token is available", async () => {+ vi.mocked(getServerAuthToken).mockResolvedValueOnce(null);+ vi.mocked(fetch).mockResolvedValue(+ new Response("{}", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items");+ await GET(req, makeParams(["api", "v1", "items"]));++ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;+ expect(sentHeaders.get("authorization")).toBeNull();+ });++ it("returns 502 with error detail when backend fetch throws (network error)", async () => {+ vi.mocked(fetch).mockRejectedValue(new Error("ECONNRESET"));+ const consoleErr = vi.spyOn(console, "error").mockImplementation(() => {});++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items");+ const res = await GET(req, makeParams(["api", "v1", "items"]));++ expect(res.status).toBe(502);+ const body = await res.json();+ expect(body).toEqual({+ error: "Proxy request failed",+ detail: "ECONNRESET",+ });+ consoleErr.mockRestore();+ });++ it("sends accept-encoding restricted to encodings undici (Node 22) can decompress — must NOT include zstd", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest("https://app.test/api/proxy/api/v1/items");+ await GET(req, makeParams(["api", "v1", "items"]));++ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;+ const acceptEncoding = sentHeaders.get("accept-encoding") ?? "";+ expect(acceptEncoding).not.toBe("");+ expect(acceptEncoding.toLowerCase()).not.toContain("zstd");+ expect(acceptEncoding.toLowerCase()).toMatch(/gzip|br|deflate/);+ });++ it("forwards query string to the backend URL", async () => {+ vi.mocked(fetch).mockResolvedValue(+ new Response("{}", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const req = new NextRequest(+ "https://app.test/api/proxy/api/v1/items?page=2&size=20",+ );+ await GET(req, makeParams(["api", "v1", "items"]));++ expect(vi.mocked(fetch).mock.calls[0][0]).toBe(+ `${BACKEND}/api/v1/items?page=2&size=20`,+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.tsindex 605d4cf16c..95a0ed6045 100644--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts@@ -1,38 +1,103 @@import {- ApiError,- getServerAuthToken,- makeAuthenticatedFileUpload,- makeAuthenticatedRequest,-} from "@/lib/autogpt-server-api/helpers";+ API_KEY_HEADER_NAME,+ IMPERSONATION_HEADER_NAME,+} from "@/lib/constants";+import { getServerAuthToken } from "@/lib/autogpt-server-api/helpers";import { environment } from "@/services/environment";import { NextRequest, NextResponse } from "next/server";-// Increase body size limit to 256MB to match backend file upload limit-export const maxDuration = 300; // 5 minutes timeout for large uploads-export const dynamic = "force-dynamic";-import {fetchWorkspaceDownloadWithRetry,getWorkspaceDownloadErrorMessage,isWorkspaceDownloadRequest,} from "./route.helpers";+// 5 minutes for large uploads. Most calls finish in well under a second.+export const maxDuration = 300;+export const dynamic = "force-dynamic";++const FORWARDED_REQUEST_HEADERS: ReadonlyArray<string> = [+ "content-type",+ "content-length",+ "accept",+ "accept-language",+ IMPERSONATION_HEADER_NAME.toLowerCase(),+ API_KEY_HEADER_NAME.toLowerCase(),+ "sentry-trace",+ "baggage",+];++// Browsers advertise `zstd` in Accept-Encoding, but undici (Node 22's fetch)+// only auto-decompresses gzip/deflate/br. If we forwarded the browser value,+// Cloudflare in front of the backend would pick zstd, Node would hand us raw+// zstd bytes, the response handler would strip Content-Encoding, and Vercel's+// edge would then brotli-wrap those bytes — leaving the browser to decode br+// over zstd and fail JSON.parse on a 200 response.+const BACKEND_ACCEPT_ENCODING = "gzip, deflate, br";++// Headers that must not be forwarded from the backend to the client.+// Hop-by-hop entries are listed in RFC 7230 §6.1; content-encoding and+// content-length are stripped because Node's fetch auto-decompresses the+// backend body when reading response.body, so the streamed payload's actual+// byte length and encoding no longer match what the backend advertised.+// Letting Node recompute framing (via Transfer-Encoding: chunked) keeps+// HTTP parsing on the client side correct.+// `set-cookie` is stripped defensively so any backend cookie without an+// explicit Domain attribute can't attach to the frontend origin.+const STRIPPED_RESPONSE_HEADERS: ReadonlySet<string> = new Set([+ "connection",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization",+ "te",+ "trailer",+ "transfer-encoding",+ "upgrade",+ "content-encoding",+ "content-length",+ "set-cookie",+]);+function buildBackendUrl(path: string[], queryString: string): string {- const backendPath = path.join("/");- return `${environment.getAGPTServerBaseUrl()}/${backendPath}${queryString}`;+ return `${environment.getAGPTServerBaseUrl()}/${path.join("/")}${queryString}`;}-/**- * Handle workspace file download requests with proper binary response streaming.- */+function buildForwardHeaders(req: NextRequest, token: string | null): Headers {+ const headers = new Headers();+ for (const name of FORWARDED_REQUEST_HEADERS) {+ const value = req.headers.get(name);+ if (value) headers.set(name, value);+ }+ headers.set("accept-encoding", BACKEND_ACCEPT_ENCODING);+ if (token) {+ headers.set("authorization", `Bearer ${token}`);+ }+ return headers;+}++function filterResponseHeaders(src: Headers): Headers {+ const out = new Headers();+ src.forEach((value, key) => {+ if (!STRIPPED_RESPONSE_HEADERS.has(key.toLowerCase())) {+ out.set(key, value);+ }+ });+ return out;+}++const METHODS_WITHOUT_BODY: ReadonlySet<string> = new Set([+ "GET",+ "HEAD",+ "DELETE",+ "OPTIONS",+]);+async function handleWorkspaceDownload(- req: NextRequest,backendUrl: string,+ token: string | null,): Promise<NextResponse> {- const token = await getServerAuthToken();-const headers: Record<string, string> = {};- if (token && token !== "no-token-found") {+ if (token) {headers["Authorization"] = `Bearer ${token}`;}@@ -47,7 +112,7 @@ async function handleWorkspaceDownload(return await createWorkspaceDownloadErrorResponse(response);}- // Fully buffer the response before forwarding. Passing response.body as a+ // Fully buffer the response before forwarding. Passing response.body as a// ReadableStream causes silent truncation in Next.js / Vercel — the last// ~10 KB of larger files are dropped, corrupting PNGs and truncating CSVs.const buffer = await response.arrayBuffer();@@ -99,152 +164,16 @@ async function createWorkspaceDownloadErrorResponse(}}-async function handleJsonRequest(- req: NextRequest,- method: string,- backendUrl: string,-): Promise<any> {- let payload;-- try {- payload = await req.json();- } catch (error) {- // Handle cases where request body is empty, invalid JSON, or already consumed- console.warn("Failed to parse JSON from request body:", error);- payload = null;- }-- return await makeAuthenticatedRequest(- method,- backendUrl,- payload,- "application/json",- req,- );-}--async function handleFormDataRequest(- req: NextRequest,- backendUrl: string,-): Promise<any> {- const formData = await req.formData();- return await makeAuthenticatedFileUpload(backendUrl, formData, req);-}--async function handleUrlEncodedRequest(- req: NextRequest,- method: string,- backendUrl: string,-): Promise<any> {- const textPayload = await req.text();- const params = new URLSearchParams(textPayload);- const payload = Object.fromEntries(params.entries());- return await makeAuthenticatedRequest(- method,- backendUrl,- payload,- "application/x-www-form-urlencoded",- req,- );-}--async function handleGetDeleteRequest(- method: string,- backendUrl: string,- req: NextRequest,-): Promise<any> {- return await makeAuthenticatedRequest(- method,- backendUrl,- undefined,- "application/json",- req,- );-}--function createUnsupportedContentTypeResponse(- contentType: string | null,-): NextResponse {- return NextResponse.json(- {- error:- "Unsupported Content-Type for proxying with authentication helpers.",- receivedContentType: contentType,- supportedContentTypes: [- "application/json",- "multipart/form-data",- "application/x-www-form-urlencoded",- ],- },- { status: 415 },- );-}--function createResponse(- responseBody: any,- responseStatus: number,- responseHeaders: Record<string, string>,-): NextResponse {- if (responseStatus === 204) {- return new NextResponse(null, { status: responseStatus });- } else {- return NextResponse.json(responseBody, {- status: responseStatus,- headers: responseHeaders,- });- }-}--function createErrorResponse(- error: unknown,- path: string,- method: string,-): NextResponse {- if (- error &&- typeof error === "object" &&- "status" in error &&- [401, 403].includes(error.status as number)- ) {- // Log this since it indicates a potential frontend bug- console.warn(- `Authentication error in API proxy for ${method} ${path}:`,- "message" in error ? error.message : error,- );- }-- // If it's our custom ApiError, preserve the original status and response- if (error instanceof ApiError) {- return NextResponse.json(error.response || { error: error.message }, {- status: error.status,- });- }-- // For JSON parsing errors, provide more context- if (error instanceof SyntaxError && error.message.includes("JSON")) {- return NextResponse.json(- {- error: "Invalid response from backend",- detail: error.message ?? "Backend returned non-JSON response",- },- { status: 502 },- );- }-- // For other errors, use generic response- const detail =- error instanceof Error ? error.message : "An unknown error occurred";- return NextResponse.json(- { error: "Proxy request failed", detail },- { status: 500 },- );-}-/**- * A simple proxy route that forwards requests to the backend API.- * It injects the server-side authentication token into the Authorization header.- * It uses the makeAuthenticatedRequest and makeAuthenticatedFileUpload helpers- * to handle request body parsing and authentication.+ * Forwards browser API requests to the backend with the JWT pulled from+ * httpOnly cookies attached to the Authorization header.+ *+ * Body and response are streamed end-to-end so JSON / FormData / SSE bodies+ * pass through without parse → re-serialise round-trips. Status codes and+ * non-hop-by-hop response headers are preserved.+ *+ * Workspace file downloads have a dedicated buffering path because Vercel's+ * stream forwarding silently truncates large binary responses.*/async function handler(req: NextRequest,@@ -254,39 +183,41 @@ async function handler(const url = new URL(req.url);const queryString = url.search;const backendUrl = buildBackendUrl(path, queryString);-const method = req.method;- const contentType = req.headers.get("Content-Type");-- let responseBody: any;- const responseHeaders: Record<string, string> = {- "Content-Type": "application/json",- };try {- // Handle workspace file downloads separately (binary response)+ const token = await getServerAuthToken();+if (method === "GET" && isWorkspaceDownloadRequest(path)) {- return await handleWorkspaceDownload(req, backendUrl);+ return await handleWorkspaceDownload(backendUrl, token);}- if (method === "GET" || method === "DELETE") {- responseBody = await handleGetDeleteRequest(method, backendUrl, req);- } else if (contentType?.includes("application/json")) {- responseBody = await handleJsonRequest(req, method, backendUrl);- } else if (contentType?.includes("multipart/form-data")) {- responseBody = await handleFormDataRequest(req, backendUrl);- } else if (contentType?.includes("application/x-www-form-urlencoded")) {- responseBody = await handleUrlEncodedRequest(req, method, backendUrl);- } else {- return createUnsupportedContentTypeResponse(contentType);- }+ const headers = buildForwardHeaders(req, token);+ const hasBody = !METHODS_WITHOUT_BODY.has(method);- return createResponse(responseBody, 200, responseHeaders);- } catch (error) {- return createErrorResponse(- error,- path.map((s) => `/${s}`).join(""),+ const backendResponse = await fetch(backendUrl, {method,+ headers,+ body: hasBody ? req.body : undefined,+ // `duplex: "half"` is required by Node's fetch when sending a+ // ReadableStream body. Cast because TS lib types haven't caught up.+ ...(hasBody ? ({ duplex: "half" } as RequestInit) : {}),+ redirect: "manual",+ });++ return new NextResponse(backendResponse.body, {+ status: backendResponse.status,+ statusText: backendResponse.statusText,+ headers: filterResponseHeaders(backendResponse.headers),+ });+ } catch (error) {+ console.error(`Proxy error for ${method} /${path.join("/")}:`, error);+ return NextResponse.json(+ {+ error: "Proxy request failed",+ detail: error instanceof Error ? error.message : "Unknown error",+ },+ { status: 502 },);}}diff --git a/autogpt_platform/frontend/src/app/api/transcribe/route.ts b/autogpt_platform/frontend/src/app/api/transcribe/route.tsindex 10c182cdfa..8347176704 100644--- a/autogpt_platform/frontend/src/app/api/transcribe/route.ts+++ b/autogpt_platform/frontend/src/app/api/transcribe/route.ts@@ -12,7 +12,7 @@ function getExtensionFromMimeType(mimeType: string): string {export async function POST(request: NextRequest) {const token = await getServerAuthToken();- if (!token || token === "no-token-found") {+ if (!token) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}diff --git a/autogpt_platform/frontend/src/app/api/workspace/files/upload/route.ts b/autogpt_platform/frontend/src/app/api/workspace/files/upload/route.tsindex 2da5e41aec..b90d0a6466 100644--- a/autogpt_platform/frontend/src/app/api/workspace/files/upload/route.ts+++ b/autogpt_platform/frontend/src/app/api/workspace/files/upload/route.ts@@ -16,7 +16,7 @@ export async function POST(request: NextRequest) {}const headers: Record<string, string> = {};- if (token && token !== "no-token-found") {+ if (token) {headers["Authorization"] = `Bearer ${token}`;}diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.tsindex 524064f6e1..ccbed9b2e8 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import BackendAPI, { buildOAuthLoginQuery } from "../client";describe("BackendAPI.oAuthLogin", () => {@@ -71,3 +71,50 @@ describe("buildOAuthLoginQuery", () => {});});});++describe("BackendAPI._makeClientRequest 204 handling", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ function mockFetch(response: Response) {+ return vi.spyOn(globalThis, "fetch").mockResolvedValue(response);+ }++ it("returns null for 204 No Content without parsing body", async () => {+ const api = new BackendAPI("http://test", "ws://test");+ mockFetch(new Response(null, { status: 204 }));++ const result = await (api as any)._makeClientRequest(+ "DELETE",+ "/library/agents/abc",+ );++ expect(result).toBeNull();+ });++ it("returns null when Content-Length is 0", async () => {+ const api = new BackendAPI("http://test", "ws://test");+ mockFetch(+ new Response("", { status: 200, headers: { "Content-Length": "0" } }),+ );++ const result = await (api as any)._makeClientRequest("DELETE", "/x");++ expect(result).toBeNull();+ });++ it("parses JSON body for non-empty 200 responses", async () => {+ const api = new BackendAPI("http://test", "ws://test");+ mockFetch(+ new Response(JSON.stringify({ ok: true }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const result = await (api as any)._makeClientRequest("GET", "/x");++ expect(result).toEqual({ ok: true });+ });+});diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/helpers.test.tsindex 562e493819..df60c5c114 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/helpers.test.ts@@ -78,8 +78,8 @@ describe("createRequestHeaders — basics", () => {expect(headers["Authorization"]).toBe("Bearer token-abc");});- it("omits Authorization when token is the 'no-token-found' sentinel", () => {- const headers = createRequestHeaders("no-token-found", false);+ it("omits Authorization when token is null", () => {+ const headers = createRequestHeaders(null, false);expect(headers["Authorization"]).toBeUndefined();});diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.tsindex 22169d1c4d..98178a5c19 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts@@ -1,11 +1,11 @@import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";import { ImpersonationState } from "@/lib/impersonation";import { getWebSocketToken } from "@/lib/supabase/actions";+import { ensureSupabaseClient } from "@/lib/supabase/hooks/helpers";import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";import { environment } from "@/services/environment";import { Key, storage } from "@/services/storage/local-storage";import * as Sentry from "@sentry/nextjs";-import { createBrowserClient } from "@supabase/ssr";import type { SupabaseClient } from "@supabase/supabase-js";import type {AddUserCreditsResponse,@@ -113,15 +113,7 @@ export default class BackendAPI {}private async getSupabaseClient(): Promise<SupabaseClient | null> {- return isClient- ? createBrowserClient(- environment.getSupabaseUrl(),- environment.getSupabaseAnonKey(),- {- isSingleton: true,- },- )- : await getServerSupabase();+ return isClient ? ensureSupabaseClient() : await getServerSupabase();}async isAuthenticated(): Promise<boolean> {@@ -687,19 +679,6 @@ export default class BackendAPI {return this._request("GET", path, query);}- private async getAuthToken(): Promise<string> {- // Only try client-side session (for WebSocket connections)- // This will return "no-token-found" with httpOnly cookies, which is expected- const supabaseClient = await this.getSupabaseClient();- const {- data: { session },- } = (await supabaseClient?.auth.getSession()) || {- data: { session: null },- };-- return session?.access_token || "no-token-found";- }-private async _uploadFile(path: string, file: File): Promise<string> {const formData = new FormData();formData.append("file", file);@@ -932,6 +911,12 @@ export default class BackendAPI {throw error;}+ if (+ response.status === 204 ||+ response.headers.get("Content-Length") === "0"+ ) {+ return null;+ }return await response.json();}diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.tsindex 3a61ab8724..e903ed5bea 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts@@ -5,6 +5,7 @@ import {import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";import { environment } from "@/services/environment";import { Key, storage } from "@/services/storage/local-storage";+import { cache } from "react";import { GraphValidationErrorResponse } from "./types";@@ -110,32 +111,23 @@ export async function handleFetchError(response: Response): Promise<ApiError> {);}-export async function getServerAuthToken(): Promise<string> {+export const getServerAuthToken = cache(async (): Promise<string | null> => {const supabase = await getServerSupabase();- if (!supabase) {- throw new Error("Supabase client not available");- }-try {const {data: { session },- error,} = await supabase.auth.getSession();- if (error || !session || !session.access_token) {- return "no-token-found";- }-- return session.access_token;+ return session?.access_token ?? null;} catch (error) {console.error("Failed to get auth token:", error);- return "no-token-found";+ return null;}-}+});export function createRequestHeaders(- token: string,+ token: string | null,hasRequestBody: boolean,contentType: string = "application/json",originalRequest?: Request,@@ -146,7 +138,7 @@ export function createRequestHeaders(headers["Content-Type"] = contentType;}- if (token && token !== "no-token-found") {+ if (token) {headers["Authorization"] = `Bearer ${token}`;}diff --git a/autogpt_platform/frontend/src/lib/supabase/actions.ts b/autogpt_platform/frontend/src/lib/supabase/actions.tsindex 1c7f17440f..23ad50d84a 100644--- a/autogpt_platform/frontend/src/lib/supabase/actions.ts+++ b/autogpt_platform/frontend/src/lib/supabase/actions.ts@@ -1,7 +1,6 @@"use server";import * as Sentry from "@sentry/nextjs";import type { User } from "@supabase/supabase-js";-import { revalidatePath } from "next/cache";import { getRedirectPath } from "./helpers";import { getServerSupabase } from "./server/getServerSupabase";@@ -164,8 +163,6 @@ export async function serverLogout(options: ServerLogoutOptions = {}) {scope: options.globalLogout ? "global" : "local",});- revalidatePath("/");-if (error) {console.error("Error logging out:", error);return { success: false, error: error.message };@@ -178,7 +175,10 @@ export async function serverLogout(options: ServerLogoutOptions = {}) {};}- revalidatePath("/", "layout");+ // No `revalidatePath`: `/` is a client-only spinner that redirects to+ // `/copilot`, so there is no RSC payload to invalidate. The cross-tab+ // storage listener calls `router.refresh()` for any visible page, and+ // the React Query cache is cleared client-side.return { success: true };},);@@ -211,9 +211,6 @@ export async function refreshSession() {};}- // Revalidate the layout to update server components- revalidatePath("/", "layout");-return { user };} catch (error) {console.error("Refresh session error:", error);diff --git a/autogpt_platform/frontend/src/lib/supabase/helpers.ts b/autogpt_platform/frontend/src/lib/supabase/helpers.tsindex dcf75d2ef8..eea44cf43d 100644--- a/autogpt_platform/frontend/src/lib/supabase/helpers.ts+++ b/autogpt_platform/frontend/src/lib/supabase/helpers.ts@@ -84,7 +84,6 @@ export interface EventListeners {export function setupSessionEventListeners(onVisibilityChange: () => void,- onFocus: () => void,onStorageChange: (e: StorageEvent) => void,): EventListeners {if (environment.isServerSide()) {@@ -92,13 +91,11 @@ export function setupSessionEventListeners(}document.addEventListener("visibilitychange", onVisibilityChange);- window.addEventListener("focus", onFocus);window.addEventListener("storage", onStorageChange);return {cleanup: () => {document.removeEventListener("visibilitychange", onVisibilityChange);- window.removeEventListener("focus", onFocus);window.removeEventListener("storage", onStorageChange);},};diff --git a/autogpt_platform/frontend/src/lib/supabase/hooks/__tests__/useSupabaseStore.test.ts b/autogpt_platform/frontend/src/lib/supabase/hooks/__tests__/useSupabaseStore.test.tsnew file mode 100644index 0000000000..4731a0f2e4--- /dev/null+++ b/autogpt_platform/frontend/src/lib/supabase/hooks/__tests__/useSupabaseStore.test.ts@@ -0,0 +1,121 @@+import type BackendAPI from "@/lib/autogpt-server-api/client";+import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";+import { afterEach, describe, expect, it, vi } from "vitest";++// The store imports a chain of modules (server actions, supabase helpers,+// react-query). Stub them so we can exercise `setCurrentRequestContext` —+// the new behavior introduced by this PR — in isolation, without pulling+// in next/headers or a real Supabase client at test time.+vi.mock("../../actions", () => ({+ serverLogout: vi.fn(),+}));+vi.mock("../../helpers", () => ({+ broadcastLogout: vi.fn(),+ setWebSocketDisconnectIntent: vi.fn(),+ setupSessionEventListeners: vi.fn(() => ({ cleanup: vi.fn() })),+}));+vi.mock("../helpers", () => ({+ ensureSupabaseClient: vi.fn(() => null),+ fetchUser: vi.fn(),+ handleStorageEvent: vi.fn(),+ refreshSession: vi.fn(),+ validateSession: vi.fn(),+}));++import { useSupabaseStore } from "../useSupabaseStore";++function makeRouter() {+ return {+ push: vi.fn(),+ replace: vi.fn(),+ refresh: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ } as unknown as AppRouterInstance;+}++function makeApi() {+ return {} as BackendAPI;+}++function snapshot() {+ const { routerRef, apiRef, currentPath } = useSupabaseStore.getState();+ return { routerRef, apiRef, currentPath };+}++describe("useSupabaseStore.setCurrentRequestContext", () => {+ afterEach(() => {+ useSupabaseStore.setState({+ routerRef: null,+ apiRef: null,+ currentPath: "",+ });+ });++ it("writes refs and path to the store on first call", () => {+ const router = makeRouter();+ const api = makeApi();++ useSupabaseStore+ .getState()+ .setCurrentRequestContext({ router, api, path: "/library" });++ expect(snapshot()).toEqual({+ routerRef: router,+ apiRef: api,+ currentPath: "/library",+ });+ });++ it("is a no-op when refs and path are identical to current state", () => {+ const router = makeRouter();+ const api = makeApi();+ const { setCurrentRequestContext } = useSupabaseStore.getState();++ setCurrentRequestContext({ router, api, path: "/library" });+ const setSpy = vi.spyOn(useSupabaseStore, "setState");++ setCurrentRequestContext({ router, api, path: "/library" });++ expect(setSpy).not.toHaveBeenCalled();+ setSpy.mockRestore();+ });++ it.each([+ {+ label: "router changes",+ next: { router: makeRouter() },+ },+ {+ label: "api changes",+ next: { api: makeApi() },+ },+ {+ label: "path changes",+ next: { path: "/build" },+ },+ ])("writes when $label", ({ next }) => {+ const baseRouter = makeRouter();+ const baseApi = makeApi();+ const basePath = "/library";++ const { setCurrentRequestContext } = useSupabaseStore.getState();+ setCurrentRequestContext({+ router: baseRouter,+ api: baseApi,+ path: basePath,+ });++ setCurrentRequestContext({+ router: next.router ?? baseRouter,+ api: next.api ?? baseApi,+ path: next.path ?? basePath,+ });++ const after = snapshot();+ expect(after.routerRef).toBe(next.router ?? baseRouter);+ expect(after.apiRef).toBe(next.api ?? baseApi);+ expect(after.currentPath).toBe(next.path ?? basePath);+ });+});diff --git a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.tsindex 5f362397f6..af0fc75914 100644--- a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts+++ b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts@@ -1,8 +1,9 @@"use client";+import { useMountEffect } from "@/hooks/useMountEffect";import { useBackendAPI } from "@/lib/autogpt-server-api/context";import { usePathname, useRouter, useSearchParams } from "next/navigation";-import { useEffect, useMemo } from "react";+import { useEffect } from "react";import { useShallow } from "zustand/react/shallow";import type { ServerLogoutOptions } from "../actions";import { useSupabaseStore } from "./useSupabaseStore";@@ -13,17 +14,15 @@ export function useSupabase() {const searchParams = useSearchParams();const api = useBackendAPI();- // Combine pathname and search params to get full path for redirect preservation- const fullPath = useMemo(() => {- const search = searchParams.toString();- return search ? `${pathname}?${search}` : pathname;- }, [pathname, searchParams]);+ const search = searchParams.toString();+ const fullPath = search ? `${pathname}?${search}` : pathname;const {user,supabase,isUserLoading,initialize,+ setCurrentRequestContext,logOut,validateSession,refreshSession,@@ -33,19 +32,23 @@ export function useSupabase() {supabase: state.supabase,isUserLoading: state.isUserLoading,initialize: state.initialize,+ setCurrentRequestContext: state.setCurrentRequestContext,logOut: state.logOut,validateSession: state.validateSession,refreshSession: state.refreshSession,})),);+ useMountEffect(() => {+ void initialize({ api, router, path: fullPath });+ });++ // Push the latest router/api/path into the store so the window-level event+ // handlers (handleStorageEventInternal, handleVisibilityChange) can read+ // them. Runs after commit so we don't mutate external state during render.useEffect(() => {- void initialize({- api,- router,- path: fullPath,- });- }, [api, initialize, fullPath, router]);+ setCurrentRequestContext({ api, router, path: fullPath });+ }, [api, router, fullPath, setCurrentRequestContext]);function handleLogout(options: ServerLogoutOptions = {}) {return logOut({diff --git a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabaseStore.ts b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabaseStore.tsindex 5207397ee4..9c73bb8049 100644--- a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabaseStore.ts+++ b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabaseStore.ts@@ -49,6 +49,7 @@ interface SupabaseStoreState {apiRef: BackendAPI | null;currentPath: string;initialize: (params: InitializeParams) => Promise<void>;+ setCurrentRequestContext: (params: InitializeParams) => void;logOut: (params?: LogOutParams) => Promise<void>;validateSession: (params?: ValidateParams) => Promise<boolean>;refreshSession: () => ReturnType<typeof refreshSessionHelper>;@@ -56,12 +57,24 @@ interface SupabaseStoreState {}export const useSupabaseStore = create<SupabaseStoreState>((set, get) => {- async function initialize(params: InitializeParams): Promise<void> {+ function setCurrentRequestContext(params: InitializeParams): void {+ const state = get();+ if (+ state.routerRef === params.router &&+ state.apiRef === params.api &&+ state.currentPath === params.path+ ) {+ return;+ }set({routerRef: params.router,apiRef: params.api,currentPath: params.path,});+ }++ async function initialize(params: InitializeParams): Promise<void> {+ setCurrentRequestContext(params);const supabaseClient = ensureSupabaseClient();if (supabaseClient !== get().supabase) {@@ -106,7 +119,6 @@ export const useSupabaseStore = create<SupabaseStoreState>((set, get) => {const cleanup = setupSessionEventListeners(handleVisibilityChange,- handleFocus,handleStorageEventInternal,);set({ listenersCleanup: cleanup.cleanup });@@ -215,10 +227,6 @@ export const useSupabaseStore = create<SupabaseStoreState>((set, get) => {void validateSessionInternal();}- function handleFocus(): void {- void validateSessionInternal();- }-function handleStorageEventInternal(event: StorageEvent): void {const result = handleStorageEventHelper({event,@@ -285,6 +293,7 @@ export const useSupabaseStore = create<SupabaseStoreState>((set, get) => {apiRef: null,currentPath: "",initialize,+ setCurrentRequestContext,logOut,validateSession: validateSessionInternal,refreshSession: refreshSessionInternal,diff --git a/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.tsindex 04ad5ecdc3..f0ba4f2f57 100644--- a/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts+++ b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts@@ -1,44 +1,39 @@import { createServerClient, type CookieOptions } from "@supabase/ssr";+import { cache } from "react";import { getCookieSettings } from "../helpers";import { environment } from "@/services/environment";type Cookies = { name: string; value: string; options?: CookieOptions }[];-export async function getServerSupabase() {+export const getServerSupabase = cache(async () => {// Need require here, so Next.js doesn't complain about importing this on client side// eslint-disable-next-line @typescript-eslint/no-require-importsconst { cookies } = require("next/headers");const cookieStore = await cookies();- try {- const supabase = createServerClient(- environment.getSupabaseUrl(),- environment.getSupabaseAnonKey(),- {- cookies: {- getAll() {- return cookieStore.getAll();- },- setAll(cookiesToSet: Cookies) {- try {- cookiesToSet.forEach(({ name, value, options }) => {- cookieStore.set(name, value, {- ...options,- ...getCookieSettings(),- });+ return createServerClient(+ environment.getSupabaseUrl(),+ environment.getSupabaseAnonKey(),+ {+ cookies: {+ getAll() {+ return cookieStore.getAll();+ },+ setAll(cookiesToSet: Cookies) {+ try {+ cookiesToSet.forEach(({ name, value, options }) => {+ cookieStore.set(name, value, {+ ...options,+ ...getCookieSettings(),});- } catch {- // The `setAll` method was called from a Server Component.- // This can be ignored if you have middleware refreshing- // user sessions.- }- },+ });+ } catch {+ // The `setAll` method was called from a Server Component.+ // This can be ignored if you have middleware refreshing+ // user sessions.+ }},},- );-- return supabase;- } catch (error) {- throw error;- }-}+ },+ );+});diff --git a/autogpt_platform/frontend/src/middleware.ts b/autogpt_platform/frontend/src/middleware.tsindex 411e2fe498..b98280a3a2 100644--- a/autogpt_platform/frontend/src/middleware.ts+++ b/autogpt_platform/frontend/src/middleware.ts@@ -23,11 +23,14 @@ export const config = {* - /_next/image (image optimization files)* - /favicon.ico (favicon file)* - /auth/callback (OAuth callback - needs to work without auth)+ * - /api/proxy (backend API proxy - the route handler authenticates+ * itself via httpOnly cookies; running supabase.auth.getUser() here+ * adds a Supabase auth-server round-trip to every API call)* Feel free to modify this pattern to include more paths.** Note: /auth/authorize and /auth/integrations/* ARE protected and need* middleware to run for authentication checks.*/- "/((?!_next/static|_next/image|favicon.ico|auth/callback|auth/integrations/mcp_callback|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",+ "/((?!_next/static|_next/image|favicon.ico|auth/callback|auth/integrations/mcp_callback|api/proxy|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",],};diff --git a/autogpt_platform/frontend/src/playwright/utils/signup.ts b/autogpt_platform/frontend/src/playwright/utils/signup.tsindex c83c760102..7a2a3abd6b 100644--- a/autogpt_platform/frontend/src/playwright/utils/signup.ts+++ b/autogpt_platform/frontend/src/playwright/utils/signup.ts@@ -32,8 +32,10 @@ export async function signupTestUser(const confirmPasswordInput = page.locator("#confirmPassword");await confirmPasswordInput.fill(userPassword);- // Agree to terms and submit- await getRole("checkbox").click();+ // Agree to terms and submit. Scope to the Terms checkbox by accessible+ // name — in dev/local the AgentationDevtool renders extra checkboxes+ // globally, so a bare getByRole("checkbox") trips Playwright strict mode.+ await getRole("checkbox", /agree to the terms/i).click();const signupButton = getButton("Sign up");await signupButton.click();diff --git a/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx b/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsxindex c4931856bc..04e26fa169 100644--- a/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx+++ b/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx@@ -1,9 +1,23 @@-import { beforeAll, afterAll, afterEach } from "vitest";+import { beforeAll, afterAll, afterEach, vi } from "vitest";import { server } from "@/mocks/mock-server";import { mockNextjsModules } from "./setup-nextjs-mocks";import { mockSupabaseRequest } from "./mock-supabase-request";import { cleanup } from "@testing-library/react";+// React 18.3 only ships `cache` under the `react-server` export condition.+// Vitest doesn't set that condition, so any module that imports `cache` from+// "react" (e.g. server-only helpers wrapped for per-request memoization) blows+// up with "cache is not a function" the moment its file is evaluated. Shim it+// to identity here — the cache contract degrades to "no deduplication," which+// is the correct semantics in a unit-test context.+vi.mock("react", async (importActual) => {+ const actual = await importActual<typeof import("react")>();+ return {+ ...actual,+ cache: <T extends (...args: unknown[]) => unknown>(fn: T): T => fn,+ };+});+beforeAll(() => {mockNextjsModules();mockSupabaseRequest(); // If you need user's data - please mock supabase actions in your specific test - it sends null user [It's only to avoid cookies() call]