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.
This commit is contained in:
Hyeonsang Cho 2026-11-27 12:05:17 +09:00 committed by GitHub
parent 9157cf1293
commit b21a4db159
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 120 additions and 14 deletions

View File

@ -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
```

View File

@ -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.

View File

@ -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);

View File

@ -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<Uint8Array>({
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");
}
});