From b21a4db159f3491bc127a59e643a75e37b9401ad Mon Sep 17 00:00:00 2001 From: Hyeonsang Cho Date: Fri, 27 Nov 2026 12:05:17 +0900 Subject: [PATCH] fix(frontend): send the Gateway session with LangGraph SDK requests (#8649) The SDK clients' onRequest hook added only the CSRF header and the SDK never sets credentials, so the browser used same-origin. With the documented direct Gateway URL (a different origin from the frontend), every chat request left the session cookie behind and returned 401 while REST calls through fetcher.ts kept working. The shared hook, now withGatewaySession, also returns credentials: "include" on every request. --- frontend/README.md | 5 ++ frontend/src/AGENTS.md | 4 + frontend/src/core/api/api-client.ts | 35 +++++--- .../tests/unit/core/api/api-client.test.ts | 90 +++++++++++++++++++ 4 files changed, 120 insertions(+), 14 deletions(-) diff --git a/frontend/README.md b/frontend/README.md index 5aa4fc3c81..0ef80b9316 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -95,6 +95,11 @@ NEXT_PUBLIC_BACKEND_BASE_URL="http://localhost:8001" NEXT_PUBLIC_LANGGRAPH_BASE_URL="http://localhost:8001/api" ``` +A direct Gateway URL is a different origin from the frontend. Add the frontend +origin, for example `http://localhost:3000`, to the Gateway's +`GATEWAY_CORS_ORIGINS`. REST and LangGraph requests then both send the session +cookie. + ## Project Structure ``` diff --git a/frontend/src/AGENTS.md b/frontend/src/AGENTS.md index 20f8b5d001..6087e3642b 100644 --- a/frontend/src/AGENTS.md +++ b/frontend/src/AGENTS.md @@ -22,6 +22,10 @@ pnpm test:e2e # Playwright, for anything that depends on a re - **Creating a run is not retried.** Only the first `POST /runs/stream` has retries off, because a retry after an ambiguous failure creates a second run. Stream reads keep the SDK retry budget. +- **Every LangGraph SDK client takes `withGatewaySession` as `onRequest`.** The + SDK leaves fetch at the browser's `same-origin` credentials. A client without + the hook sends no session cookie to a directly configured Gateway, so its + requests return 401 while REST calls through `fetcher.ts` still work. - **A stream gap is not the end of a run.** When the server reports a replay gap, reload durable state and rejoin. Do not finish the turn and do not cancel the backend run. diff --git a/frontend/src/core/api/api-client.ts b/frontend/src/core/api/api-client.ts index ea1502ae0b..b630d767b7 100644 --- a/frontend/src/core/api/api-client.ts +++ b/frontend/src/core/api/api-client.ts @@ -18,27 +18,32 @@ import { isStateChangingMethod, readCsrfCookie } from "./fetcher"; import { forceChatRunStreamOptions } from "./stream-mode"; /** - * SDK ``onRequest`` hook that mints the ``X-CSRF-Token`` header from the - * live ``csrf_token`` cookie just before each outbound fetch. + * SDK ``onRequest`` hook that sends the Gateway session with every LangGraph + * request, the way ``fetcher.ts:fetch`` does for the REST endpoints. * - * Reading the cookie per-request (rather than baking it into the SDK's - * ``defaultHeaders`` at construction) handles login / logout / password - * change cookie rotation transparently. Both the ``/api/langgraph/*`` SDK - * path and the direct REST endpoints in ``fetcher.ts:fetchWithAuth`` - * share :func:`readCsrfCookie` and :const:`STATE_CHANGING_METHODS` so - * the contract stays in lockstep. + * - ``credentials: "include"``: the SDK leaves fetch at the browser default + * (``same-origin``). A directly configured Gateway URL such as + * ``http://localhost:8001/api`` is a different origin from the frontend, so + * without this the session cookie stays behind and every chat request 401s. + * - ``X-CSRF-Token``: minted from the live ``csrf_token`` cookie for + * state-changing methods. Reading the cookie per request (rather than + * baking it into the SDK's ``defaultHeaders`` at construction) handles + * login / logout / password change cookie rotation transparently. The SDK + * path and ``fetcher.ts`` share :func:`readCsrfCookie` and + * :const:`STATE_CHANGING_METHODS` so the contract stays in lockstep. */ -function injectCsrfHeader(_url: URL, init: RequestInit): RequestInit { +function withGatewaySession(_url: URL, init: RequestInit): RequestInit { + const prepared: RequestInit = { ...init, credentials: "include" }; if (!isStateChangingMethod(init.method ?? "GET")) { - return init; + return prepared; } const token = readCsrfCookie(); - if (!token) return init; + if (!token) return prepared; const headers = new Headers(init.headers); if (!headers.has("X-CSRF-Token")) { headers.set("X-CSRF-Token", token); } - return { ...init, headers }; + return { ...prepared, headers }; } // Run statuses that have reached a terminal state where no further streaming @@ -475,13 +480,15 @@ function createCompatibleClient(isMock?: boolean): LangGraphClient { const apiUrl = getLangGraphBaseURL(isMock); const client = new LangGraphClient({ apiUrl, - onRequest: injectCsrfHeader, + onRequest: withGatewaySession, }); // Creating a run is not idempotent. Retrying an ambiguous gateway failure // can create the same run more than once after the backend accepted the // original request. The SDK also uses this client's transport for recovery // GETs, which must retain normal HTTP retries (including transient 5xx). + // Those GETs arrive already prepared by ``withGatewaySession`` below, so the + // recovery client needs no hook of its own. const streamRecoveryClient = new StreamRecoveryClient({ apiUrl }); const runCreationClient = new RunsClient({ apiUrl, @@ -492,7 +499,7 @@ function createCompatibleClient(isMock?: boolean): LangGraphClient { ? streamRecoveryClient.fetchWithRetries(...args) : fetch(...args), }, - onRequest: injectCsrfHeader, + onRequest: withGatewaySession, }); const originalRunStream = runCreationClient.stream.bind(runCreationClient); const originalJoinStream = client.runs.joinStream.bind(client.runs); diff --git a/frontend/tests/unit/core/api/api-client.test.ts b/frontend/tests/unit/core/api/api-client.test.ts index 1c95aa322a..e0da49748b 100644 --- a/frontend/tests/unit/core/api/api-client.test.ts +++ b/frontend/tests/unit/core/api/api-client.test.ts @@ -1495,3 +1495,93 @@ test.each(["initial", "join"] as const)( expect(sessionStorage.setItem).not.toHaveBeenCalled(); }, ); + +test("sends the Gateway session with every LangGraph request", async () => { + // A direct Gateway URL is cross-origin, and the browser drops the session + // cookie unless the request asks for credentials. The SDK never does, so + // every request (including stream recovery GETs) must get it from the hook. + const encoder = new TextEncoder(); + let interruptStream: (() => void) | undefined; + const interruptedBody = new ReadableStream({ + start(controller) { + controller.enqueue( + encoder.encode("id: 1-0\nevent: custom\ndata: {}\n\n"), + ); + interruptStream = () => { + controller.error(new TypeError("connection interrupted")); + }; + }, + }); + const requests: Array<{ + method: string; + path: string; + credentials: RequestCredentials | undefined; + csrf: string | null; + }> = []; + const fetchFn = rs.fn(async (url: string | URL, init?: RequestInit) => { + const method = init?.method ?? "GET"; + const path = new URL(url).pathname.replace("/mock/api", ""); + requests.push({ + method, + path, + credentials: init?.credentials, + csrf: new Headers(init?.headers).get("X-CSRF-Token"), + }); + if (path === "/threads/t-session/runs/stream") { + return new Response(interruptedBody, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Content-Location": "/threads/t-session/runs/r-session", + Location: "/threads/t-session/runs/r-session/stream", + }, + }); + } + if (path.endsWith("/stream")) { + return makeSSEResponse("id: 2-0\nevent: end\ndata: null\n\n"); + } + if (path === "/threads/t-session/runs/r-session") { + return Response.json({ run_id: "r-session", status: "running" }); + } + return Response.json([]); + }); + rs.stubGlobal("window", { + location: { origin: "http://localhost:2026" }, + sessionStorage: makeSessionStorage(), + }); + rs.stubGlobal("document", { cookie: "csrf_token=csrf-session" }); + rs.stubGlobal("fetch", fetchFn); + rs.stubGlobal("setTimeout", (callback: () => void) => { + callback(); + return 0; + }); + + const client = getAPIClient(true); + await client.threads.search({ limit: 1 }); + await client.threads.getHistory("t-session"); + for await (const entry of client.runs.stream("t-session", "lead_agent", { + input: { messages: [] }, + })) { + if ("id" in entry && entry.id === "1-0") { + interruptStream?.(); + } + } + for await (const entry of client.runs.joinStream("t-session", "r-session")) { + void entry; + } + await client.runs.cancel("t-session", "r-session"); + + expect(requests.map(({ method, path }) => `${method} ${path}`)).toEqual([ + "POST /threads/search", + "POST /threads/t-session/history", + "POST /threads/t-session/runs/stream", + "GET /threads/t-session/runs/r-session/stream", + "GET /threads/t-session/runs/r-session", + "GET /threads/t-session/runs/r-session/stream", + "POST /threads/t-session/runs/r-session/cancel", + ]); + for (const request of requests) { + expect(request.credentials).toBe("include"); + expect(request.csrf).toBe(request.method === "GET" ? null : "csrf-session"); + } +});