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): unify copilot auth headers and propagate impersonation header (#12718)

Zamil Majdy87539c03a413
diff --git a/.claude/skills/orchestrate/SKILL.md b/.claude/skills/orchestrate/SKILL.md
index 6fbb3681ae..58a7e45c79 100644
--- a/.claude/skills/orchestrate/SKILL.md
+++ b/.claude/skills/orchestrate/SKILL.md
@@ -458,8 +458,8 @@ When run-loop marks an agent `pending_evaluation` and you're notified, do all of
**When multiple PRs reach `pending_evaluation` at the same time, use TodoWrite to queue them:**
```
-- [ ] /pr-test PR #12636 — fix copilot retry logic
-- [ ] /pr-test PR #12699 — builder chat panel
+- [ ] /pr-test https://github.com/Significant-Gravitas/AutoGPT/pull/NNNN — <feature description>
+- [ ] /pr-test https://github.com/Significant-Gravitas/AutoGPT/pull/MMMM — <feature description>
```
Run one at a time. Check off as you go.
@@ -507,7 +507,7 @@ Only one `/pr-test` at a time — they share ports and DB.
**Rule: only ALL-PASS qualifies for approval.** A mix of PASS + PARTIAL is a failure.
-> **Why this matters**: PR #12699 was wrongly approved with S5 PARTIAL — the AI never output JSON action blocks so the Apply button never appeared. The fix was already in the agent's reach but slipped through because PARTIAL was not treated as blocking.
+> **Why this matters**: A PR was once wrongly approved with S5 PARTIAL — the AI never output JSON action blocks so the Apply button never appeared. The fix was already in the agent's reach but slipped through because PARTIAL was not treated as blocking.
### 2. Do your own evaluation
diff --git a/.claude/skills/pr-address/SKILL.md b/.claude/skills/pr-address/SKILL.md
index 9f989f3dc4..cae35a170b 100644
--- a/.claude/skills/pr-address/SKILL.md
+++ b/.claude/skills/pr-address/SKILL.md
@@ -31,26 +31,32 @@ gh pr view {N} --json body --jq '.body'
> ⚠️ **WARNING — PAGINATE ALL PAGES BEFORE ADDRESSING ANYTHING**
>
-> `reviewThreads(first: 100)` returns at most 100 threads per page. A PR with many review cycles can have 140+ threads across 2+ pages. **If you start addressing threads after fetching only page 1, you will miss all threads on subsequent pages and silently leave them unresolved.**
+> `reviewThreads(first: 100)` returns at most 100 threads per page AND returns threads **oldest-first**. On a PR with many review cycles (e.g. 373 threads), the oldest 100–200 threads are from past cycles and are **all already resolved**. Filtering client-side with `select(.isResolved == false)` on page 1 therefore yields **0 results** — even though pages 2–4 contain many unresolved threads from recent review cycles.
>
-> PR #12636 had 142 total threads: page 1 returned 69 unresolved, page 2 had 42 more (111 total unresolved). An agent that stopped after page 1 addressed only 69 and falsely reported "done".
+> **This is the most common failure mode:** agent fetches page 1, sees 0 unresolved after filtering, stops pagination, reports "done" — while hundreds of unresolved threads sit on later pages.
>
-> **The rule: collect ALL thread IDs from ALL pages into a single list, then address them.**
+> One observed PR had 142 total threads: page 1 returned 0 unresolved (all old/resolved), while pages 2–3 had 111 unresolved. Another with 373 threads across 4 pages also had page 1 entirely resolved.
+>
+> **The rule: ALWAYS paginate to `hasNextPage == false` regardless of the per-page unresolved count. Never stop early because a page returns 0 unresolved.**
-**Step 1 — Fetch total count first:**
+**Step 1 — Fetch total count and sanity-check the newest threads:**
```bash
+# Get total count and the newest 100 threads (last: 100 returns newest-first)
gh api graphql -f query='
{
repository(owner: "Significant-Gravitas", name: "AutoGPT") {
pullRequest(number: {N}) {
reviewThreads { totalCount }
+ newest: reviewThreads(last: 100) {
+ nodes { isResolved }
+ }
}
}
-}' | jq '.data.repository.pullRequest.reviewThreads.totalCount'
+}' | jq '{ total: .data.repository.pullRequest.reviewThreads.totalCount, newest_unresolved: [.data.repository.pullRequest.newest.nodes[] | select(.isResolved == false)] | length }'
```
-If `totalCount > 100`, you have multiple pages. Fetch them all before doing anything else.
+If `total > 100`, you have multiple pages — you **must** paginate all of them regardless of what `newest_unresolved` shows. The `last: 100` check is a sanity signal only; the full loop below is mandatory.
**Step 2 — Collect all unresolved thread IDs across all pages:**
@@ -87,6 +93,10 @@ while true; do
[ "$HAS_NEXT" = "false" ] && break
done
+# Reverse so newest threads (last pages) are addressed first — GitHub returns oldest-first
+# and the most recent review cycle's comments are the ones blocking approval.
+ALL_THREADS=$(echo "$ALL_THREADS" | jq 'reverse')
+
echo "Total unresolved threads: $(echo "$ALL_THREADS" | jq 'length')"
echo "$ALL_THREADS" | jq '[.[] | {id, path, line, body: .comments.nodes[0].body[:200]}]'
```
@@ -95,6 +105,8 @@ echo "$ALL_THREADS" | jq '[.[] | {id, path, line, body: .comments.nodes[0].body[
Only after this loop completes (all pages fetched, count confirmed) should you begin making fixes.
+> **Why reverse?** GraphQL returns threads oldest-first and exposes no `orderBy` option. A PR with 373 threads has ~4 pages; threads from the latest review cycle land on the last pages. Processing in reverse ensures the newest, most blocking comments are addressed first — the earlier pages mostly contain outdated threads from prior cycles.
+
**Filter to unresolved threads only** — skip any thread where `isResolved: true`. `comments(last: 1)` returns the most recent comment in the thread — act on that; it reflects the reviewer's final ask. Use the thread `id` (Relay global ID) to track threads across polls.
### 2. Top-level reviews — REST (MUST paginate)
diff --git a/.secrets.baseline b/.secrets.baseline
index 4b3deeb6b5..c2b1f3430a 100644
--- a/.secrets.baseline
+++ b/.secrets.baseline
@@ -90,6 +90,10 @@
{
"path": "detect_secrets.filters.allowlist.is_line_allowlisted"
},
+ {
+ "path": "detect_secrets.filters.common.is_baseline_file",
+ "filename": ".secrets.baseline"
+ },
{
"path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
"min_level": 2
@@ -450,7 +454,7 @@
"filename": "autogpt_platform/frontend/src/lib/constants.ts",
"hashed_secret": "27b924db06a28cc755fb07c54f0fddc30659fe4d",
"is_verified": false,
- "line_number": 10
+ "line_number": 13
}
],
"autogpt_platform/frontend/src/tests/credentials/index.ts": [
@@ -463,5 +467,5 @@
}
]
},
- "generated_at": "2026-04-02T13:10:54Z"
+ "generated_at": "2026-04-09T14:20:23Z"
}
diff --git a/autogpt_platform/backend/backend/util/test_json.py b/autogpt_platform/backend/backend/util/test_json.py
index 2e30dafec6..65569a902c 100644
--- a/autogpt_platform/backend/backend/util/test_json.py
+++ b/autogpt_platform/backend/backend/util/test_json.py
@@ -482,7 +482,7 @@ class TestSafeJson:
def test_dict_containing_pydantic_models(self):
"""Test that dicts containing Pydantic models are properly serialized."""
- # This reproduces the bug from PR #11187 where credential_inputs failed
+ # This reproduces the bug where credential_inputs failed
model1 = SamplePydanticModel(name="Alice", age=30)
model2 = SamplePydanticModel(name="Bob", age=25)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..712aaaf508
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";
+import { getCopilotAuthHeaders } from "../helpers";
+
+vi.mock("@/lib/supabase/actions", () => ({
+ getWebSocketToken: vi.fn(),
+}));
+
+vi.mock("@/lib/impersonation", () => ({
+ getSystemHeaders: vi.fn(),
+}));
+
+import { getWebSocketToken } from "@/lib/supabase/actions";
+import { getSystemHeaders } from "@/lib/impersonation";
+
+const mockGetWebSocketToken = vi.mocked(getWebSocketToken);
+const mockGetSystemHeaders = vi.mocked(getSystemHeaders);
+
+describe("getCopilotAuthHeaders", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetSystemHeaders.mockReturnValue({});
+ });
+
+ it("returns Authorization header when token is present and no impersonation active", async () => {
+ mockGetWebSocketToken.mockResolvedValue({
+ token: "test-jwt-token",
+ error: undefined,
+ });
+
+ const headers = await getCopilotAuthHeaders();
+
+ expect(headers).toEqual({ Authorization: "Bearer test-jwt-token" });
+ });
+
+ it("includes X-Act-As-User-Id header when impersonation is active", async () => {
+ mockGetWebSocketToken.mockResolvedValue({
+ token: "test-jwt-token",
+ error: undefined,
+ });
+ mockGetSystemHeaders.mockReturnValue({
+ [IMPERSONATION_HEADER_NAME]: "impersonated-user-123",
+ });
+
+ const headers = await getCopilotAuthHeaders();
+
+ expect(headers).toEqual({
+ Authorization: "Bearer test-jwt-token",
+ [IMPERSONATION_HEADER_NAME]: "impersonated-user-123",
+ });
+ });
+
+ it("throws when getWebSocketToken returns an error", async () => {
+ mockGetWebSocketToken.mockResolvedValue({
+ token: null,
+ error: "Token fetch failed",
+ });
+
+ await expect(getCopilotAuthHeaders()).rejects.toThrow(
+ "Authentication failed — please sign in again.",
+ );
+ });
+
+ it("throws when getWebSocketToken returns no token and no error", async () => {
+ mockGetWebSocketToken.mockResolvedValue({
+ token: null,
+ error: undefined,
+ });
+
+ await expect(getCopilotAuthHeaders()).rejects.toThrow(
+ "Authentication failed — please sign in again.",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/useMessageFeedback.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/useMessageFeedback.ts
index 720258bd20..718135a4dc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/useMessageFeedback.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/useMessageFeedback.ts
@@ -1,6 +1,6 @@
import { toast } from "@/components/molecules/Toast/use-toast";
-import { getWebSocketToken } from "@/lib/supabase/actions";
import { environment } from "@/services/environment";
+import { getCopilotAuthHeaders } from "@/app/(platform)/copilot/helpers";
import { useState } from "react";
interface Args {
@@ -16,16 +16,14 @@ async function submitFeedbackToBackend(args: {
comment?: string;
}) {
try {
- const { token } = await getWebSocketToken();
- if (!token) return;
-
+ const authHeaders = await getCopilotAuthHeaders();
await fetch(
`${environment.getAGPTServerBaseUrl()}/api/chat/sessions/${args.sessionID}/feedback`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
- Authorization: `Bearer ${token}`,
+ ...authHeaders,
},
body: JSON.stringify({
message_id: args.messageID,
@@ -35,8 +33,9 @@ async function submitFeedbackToBackend(args: {
}),
},
);
- } catch {
+ } catch (err) {
// Feedback submission is best-effort; silently ignore failures
+ console.debug("[Copilot] Feedback submission failed:", err);
}
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
index 4ee845c53f..6462b72d27 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
@@ -1,7 +1,29 @@
+import { getSystemHeaders } from "@/lib/impersonation";
+import { getWebSocketToken } from "@/lib/supabase/actions";
import type { UIMessage } from "ai";
export const ORIGINAL_TITLE = "AutoGPT";
+/**
+ * Returns HTTP headers required for direct backend requests from copilot:
+ * - Authorization Bearer token (JWT)
+ * - X-Act-As-User-Id impersonation header (if an admin is impersonating a user)
+ *
+ * Use this for all direct-to-backend fetch/SSE calls so that admin user
+ * impersonation works consistently across the entire copilot feature.
+ */
+export async function getCopilotAuthHeaders(): Promise<Record<string, string>> {
+ const { token, error } = await getWebSocketToken();
+ if (error || !token) {
+ console.warn("[Copilot] Failed to get auth token:", error);
+ throw new Error("Authentication failed — please sign in again.");
+ }
+ return {
+ Authorization: `Bearer ${token}`,
+ ...getSystemHeaders(),
+ };
+}
+
/**
* Build the document title showing how many sessions are ready.
* Returns the base title when count is 0.
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
index ab04c81bee..92f04d1e54 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
@@ -4,7 +4,6 @@ import {
postV2CancelSessionTask,
} from "@/app/api/__generated__/endpoints/chat/chat";
import { toast } from "@/components/molecules/Toast/use-toast";
-import { getWebSocketToken } from "@/lib/supabase/actions";
import { environment } from "@/services/environment";
import { useChat } from "@ai-sdk/react";
import { useQueryClient } from "@tanstack/react-query";
@@ -12,6 +11,7 @@ import { DefaultChatTransport } from "ai";
import type { FileUIPart, UIMessage } from "ai";
import { useEffect, useMemo, useRef, useState } from "react";
import {
+ getCopilotAuthHeaders,
deduplicateMessages,
extractSendMessageText,
hasActiveBackendStream,
@@ -26,16 +26,6 @@ const RECONNECT_MAX_ATTEMPTS = 3;
/** Minimum time the page must have been hidden to trigger a wake re-sync. */
const WAKE_RESYNC_THRESHOLD_MS = 30_000;
-/** Fetch a fresh JWT for direct backend requests (same pattern as WebSocket). */
-async function getAuthHeaders(): Promise<Record<string, string>> {
- const { token, error } = await getWebSocketToken();
- if (error || !token) {
- console.warn("[Copilot] Failed to get auth token:", error);
- throw new Error("Authentication failed — please sign in again.");
- }
- return { Authorization: `Bearer ${token}` };
-}
-
interface UseCopilotStreamArgs {
sessionId: string | null;
hydratedMessages: UIMessage[] | undefined;
@@ -94,12 +84,12 @@ export function useCopilotStream({
file_ids: fileIds && fileIds.length > 0 ? fileIds : null,
mode: copilotModeRef.current ?? null,
},
- headers: await getAuthHeaders(),
+ headers: await getCopilotAuthHeaders(),
};
},
prepareReconnectToStreamRequest: async () => ({
api: `${environment.getAGPTServerBaseUrl()}/api/chat/sessions/${sessionId}/stream`,
- headers: await getAuthHeaders(),
+ headers: await getCopilotAuthHeaders(),
}),
})
: null,
@@ -224,7 +214,7 @@ export function useCopilotStream({
return;
}
- // Detect authentication failures (from getAuthHeaders or 401 responses)
+ // Detect authentication failures (from getCopilotAuthHeaders or 401 responses)
const isAuthError =
errorDetail.includes("Authentication failed") ||
errorDetail.includes("Unauthorized") ||
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.ts
new file mode 100644
index 0000000000..7debeb3f5a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
@@ -0,0 +1,90 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/lib/impersonation", () => ({
+ getSystemHeaders: vi.fn(),
+}));
+
+vi.mock("@/services/environment", () => ({
+ environment: {
+ isClientSide: vi.fn(),
+ isServerSide: vi.fn(),
+ getAGPTServerBaseUrl: vi.fn(() => "http://localhost:8006"),
+ },
+}));
+
+vi.mock("@/lib/autogpt-server-api/helpers", () => ({
+ ApiError: class ApiError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ public data: unknown,
+ ) {
+ super(message);
+ }
+ },
+ createRequestHeaders: vi.fn(() => ({})),
+ getServerAuthToken: vi.fn(),
+}));
+
+import { customMutator } from "../custom-mutator";
+import { getSystemHeaders } from "@/lib/impersonation";
+import { environment } from "@/services/environment";
+import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";
+
+const mockIsClientSide = vi.mocked(environment.isClientSide);
+const mockGetSystemHeaders = vi.mocked(getSystemHeaders);
+
+describe("customMutator — impersonation header", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockIsClientSide.mockReturnValue(true);
+ mockGetSystemHeaders.mockReturnValue({});
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ headers: new Headers({ "content-type": "application/json" }),
+ json: () => Promise.resolve({}),
+ }),
+ );
+ });
+
+ it("adds impersonation header when impersonation is active", async () => {
+ mockGetSystemHeaders.mockReturnValue({
+ [IMPERSONATION_HEADER_NAME]: "impersonated-user-abc",
+ });
+
+ await customMutator("/test", { method: "GET" });
+
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
+ const headers = fetchCall[1]?.headers as Record<string, string>;
+ expect(headers[IMPERSONATION_HEADER_NAME]).toBe("impersonated-user-abc");
+ });
+
+ it("does not add impersonation header when no impersonation active", async () => {
+ mockGetSystemHeaders.mockReturnValue({});
+
+ await customMutator("/test", { method: "GET" });
+
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
+ const headers = fetchCall[1]?.headers as Record<string, string>;
+ expect(headers[IMPERSONATION_HEADER_NAME]).toBeUndefined();
+ });
+
+ it("coexists with pre-existing caller-supplied headers without overwriting them", async () => {
+ mockGetSystemHeaders.mockReturnValue({
+ [IMPERSONATION_HEADER_NAME]: "impersonated-user-abc",
+ });
+
+ await customMutator("/test", {
+ method: "GET",
+ headers: { "X-Custom-Header": "custom-value" },
+ });
+
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
+ const headers = fetchCall[1]?.headers as Record<string, string>;
+ expect(headers[IMPERSONATION_HEADER_NAME]).toBe("impersonated-user-abc");
+ expect(headers["X-Custom-Header"]).toBe("custom-value");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
index 3c9eda7785..05b49f10e7 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
@@ -4,10 +4,7 @@ import {
getServerAuthToken,
} from "@/lib/autogpt-server-api/helpers";
-import {
- IMPERSONATION_HEADER_NAME,
- IMPERSONATION_STORAGE_KEY,
-} from "@/lib/constants";
+import { getSystemHeaders } from "@/lib/impersonation";
import { environment } from "@/services/environment";
import { transformDates } from "./date-transformer";
@@ -56,19 +53,7 @@ export const customMutator = async <
};
if (environment.isClientSide()) {
- try {
- const impersonatedUserId = sessionStorage.getItem(
- IMPERSONATION_STORAGE_KEY,
- );
- if (impersonatedUserId) {
- headers[IMPERSONATION_HEADER_NAME] = impersonatedUserId;
- }
- } catch (error) {
- console.error(
- "Admin impersonation: Failed to access sessionStorage:",
- error,
- );
- }
+ Object.assign(headers, getSystemHeaders());
}
const isFormData = data instanceof FormData;
diff --git a/autogpt_platform/frontend/src/lib/__tests__/impersonation.test.ts b/autogpt_platform/frontend/src/lib/__tests__/impersonation.test.ts
new file mode 100644
index 0000000000..bce1b9301c
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/__tests__/impersonation.test.ts
@@ -0,0 +1,255 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/services/environment", () => ({
+ environment: {
+ isClientSide: vi.fn(),
+ isServerSide: vi.fn(),
+ },
+}));
+
+import { environment } from "@/services/environment";
+import {
+ ImpersonationCookie,
+ ImpersonationSession,
+ ImpersonationState,
+ getSystemHeaders,
+} from "../impersonation";
+import {
+ IMPERSONATION_COOKIE_NAME,
+ IMPERSONATION_HEADER_NAME,
+ IMPERSONATION_STORAGE_KEY,
+} from "../constants";
+
+const mockIsClientSide = vi.mocked(environment.isClientSide);
+
+// ---------- helpers ----------
+
+function setCookieRaw(name: string, value: string) {
+ Object.defineProperty(document, "cookie", {
+ writable: true,
+ value: `${name}=${value}`,
+ });
+}
+
+function clearCookieRaw() {
+ Object.defineProperty(document, "cookie", {
+ writable: true,
+ value: "",
+ });
+}
+
+// ---------- ImpersonationCookie ----------
+
+describe("ImpersonationCookie", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockIsClientSide.mockReturnValue(true);
+ clearCookieRaw();
+ });
+
+ describe("get()", () => {
+ it("returns null on server-side", () => {
+ mockIsClientSide.mockReturnValue(false);
+ expect(ImpersonationCookie.get()).toBeNull();
+ });
+
+ it("returns null when cookie is absent", () => {
+ expect(ImpersonationCookie.get()).toBeNull();
+ });
+
+ it("returns decoded user ID from cookie", () => {
+ setCookieRaw(IMPERSONATION_COOKIE_NAME, "user-123");
+ expect(ImpersonationCookie.get()).toBe("user-123");
+ });
+
+ it("decodes percent-encoded characters", () => {
+ setCookieRaw(
+ IMPERSONATION_COOKIE_NAME,
+ encodeURIComponent("[email protected]"),
+ );
+ expect(ImpersonationCookie.get()).toBe("[email protected]");
+ });
+ });
+
+ describe("set()", () => {
+ it("does nothing on server-side (sessionStorage stays empty)", () => {
+ mockIsClientSide.mockReturnValue(false);
+ ImpersonationCookie.set("user-123");
+ // We can't spy on document.cookie directly in happy-dom, so just verify
+ // ImpersonationState.get() sees nothing (no sessionStorage write and no cookie)
+ expect(ImpersonationCookie.get()).toBeNull();
+ });
+ });
+
+ describe("clear()", () => {
+ it("does nothing on server-side", () => {
+ mockIsClientSide.mockReturnValue(false);
+ // Simply verify it doesn't throw
+ expect(() => ImpersonationCookie.clear()).not.toThrow();
+ });
+ });
+});
+
+// ---------- ImpersonationSession ----------
+
+describe("ImpersonationSession", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockIsClientSide.mockReturnValue(true);
+ sessionStorage.clear();
+ });
+
+ describe("get()", () => {
+ it("returns null on server-side", () => {
+ mockIsClientSide.mockReturnValue(false);
+ expect(ImpersonationSession.get()).toBeNull();
+ });
+
+ it("returns null when key is absent", () => {
+ expect(ImpersonationSession.get()).toBeNull();
+ });
+
+ it("returns stored user ID", () => {
+ sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, "user-456");
+ expect(ImpersonationSession.get()).toBe("user-456");
+ });
+
+ it("returns null when sessionStorage throws", () => {
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("storage unavailable");
+ });
+ expect(ImpersonationSession.get()).toBeNull();
+ });
+ });
+
+ describe("set()", () => {
+ it("does nothing on server-side", () => {
+ mockIsClientSide.mockReturnValue(false);
+ ImpersonationSession.set("user-123");
+ expect(sessionStorage.getItem(IMPERSONATION_STORAGE_KEY)).toBeNull();
+ });
+
+ it("stores user ID in sessionStorage", () => {
+ ImpersonationSession.set("user-789");
+ expect(sessionStorage.getItem(IMPERSONATION_STORAGE_KEY)).toBe(
+ "user-789",
+ );
+ });
+ });
+
+ describe("clear()", () => {
+ it("removes user ID from sessionStorage", () => {
+ sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, "user-789");
+ ImpersonationSession.clear();
+ expect(sessionStorage.getItem(IMPERSONATION_STORAGE_KEY)).toBeNull();
+ });
+ });
+});
+
+// ---------- ImpersonationState ----------
+
+describe("ImpersonationState", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockIsClientSide.mockReturnValue(true);
+ sessionStorage.clear();
+ clearCookieRaw();
+ });
+
+ describe("get()", () => {
+ it("returns null when neither sessionStorage nor cookie has a value", () => {
+ expect(ImpersonationState.get()).toBeNull();
+ });
+
+ it("returns sessionStorage value when present (same-tab path)", () => {
+ sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, "session-user");
+ expect(ImpersonationState.get()).toBe("session-user");
+ });
+
+ it("falls back to cookie when sessionStorage is empty (cross-tab path)", () => {
+ setCookieRaw(IMPERSONATION_COOKIE_NAME, "cookie-user");
+ expect(ImpersonationState.get()).toBe("cookie-user");
+ });
+
+ it("syncs cookie value back into sessionStorage on cookie fallback", () => {
+ setCookieRaw(IMPERSONATION_COOKIE_NAME, "cookie-user");
+ ImpersonationState.get();
+ expect(sessionStorage.getItem(IMPERSONATION_STORAGE_KEY)).toBe(
+ "cookie-user",
+ );
+ });
+
+ it("prefers sessionStorage over cookie when both are present", () => {
+ sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, "session-user");
+ setCookieRaw(IMPERSONATION_COOKIE_NAME, "cookie-user");
+ expect(ImpersonationState.get()).toBe("session-user");
+ });
+
+ it("returns null on server-side", () => {
+ mockIsClientSide.mockReturnValue(false);
+ expect(ImpersonationState.get()).toBeNull();
+ });
+ });
+
+ describe("set()", () => {
+ it("stores user ID in sessionStorage", () => {
+ ImpersonationState.set("new-user");
+ expect(sessionStorage.getItem(IMPERSONATION_STORAGE_KEY)).toBe(
+ "new-user",
+ );
+ });
+
+ it("also writes the impersonation cookie", () => {
+ ImpersonationState.set("new-user");
+ expect(ImpersonationCookie.get()).toBe("new-user");
+ });
+ });
+
+ describe("clear()", () => {
+ it("removes user ID from sessionStorage", () => {
+ sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, "user-to-clear");
+ ImpersonationState.clear();
+ expect(sessionStorage.getItem(IMPERSONATION_STORAGE_KEY)).toBeNull();
+ });
+
+ it("also clears the impersonation cookie", () => {
+ ImpersonationState.set("user-to-clear");
+ ImpersonationState.clear();
+ expect(ImpersonationCookie.get()).toBeNull();
+ });
+ });
+});
+
+// ---------- getSystemHeaders ----------
+
+describe("getSystemHeaders", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockIsClientSide.mockReturnValue(true);
+ sessionStorage.clear();
+ clearCookieRaw();
+ });
+
+ it("returns empty object when no impersonation is active", () => {
+ expect(getSystemHeaders()).toEqual({});
+ });
+
+ it("returns impersonation header when impersonation is active via sessionStorage", () => {
+ sessionStorage.setItem(IMPERSONATION_STORAGE_KEY, "user-abc");
+ expect(getSystemHeaders()).toEqual({
+ [IMPERSONATION_HEADER_NAME]: "user-abc",
+ });
+ });
+
+ it("returns impersonation header when impersonation is active via cookie (cross-tab)", () => {
+ setCookieRaw(IMPERSONATION_COOKIE_NAME, "cookie-user");
+ expect(getSystemHeaders()).toEqual({
+ [IMPERSONATION_HEADER_NAME]: "cookie-user",
+ });
+ });
+
+ it("returns empty object on server-side", () => {
+ mockIsClientSide.mockReturnValue(false);
+ expect(getSystemHeaders()).toEqual({});
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/constants.ts b/autogpt_platform/frontend/src/lib/constants.ts
index 19365a56ac..f1c9132e3e 100644
--- a/autogpt_platform/frontend/src/lib/constants.ts
+++ b/autogpt_platform/frontend/src/lib/constants.ts
@@ -4,7 +4,10 @@
// Admin impersonation
export const IMPERSONATION_HEADER_NAME = "X-Act-As-User-Id";
+// Intentionally identical strings: the cookie and sessionStorage key share the same name
+// so both storage mechanisms use a predictable, consistent identifier for the same value.
export const IMPERSONATION_STORAGE_KEY = "admin-impersonate-user-id";
+export const IMPERSONATION_COOKIE_NAME = "admin-impersonate-user-id";
// API key authentication
export const API_KEY_HEADER_NAME = "X-API-Key";
diff --git a/autogpt_platform/frontend/src/lib/impersonation.ts b/autogpt_platform/frontend/src/lib/impersonation.ts
index 47c92b89ed..65e41850be 100644
--- a/autogpt_platform/frontend/src/lib/impersonation.ts
+++ b/autogpt_platform/frontend/src/lib/impersonation.ts
@@ -3,11 +3,13 @@
* Handles reading, writing, and managing impersonation state across tabs and server/client contexts
*/
-import { IMPERSONATION_STORAGE_KEY } from "./constants";
+import {
+ IMPERSONATION_COOKIE_NAME,
+ IMPERSONATION_HEADER_NAME,
+ IMPERSONATION_STORAGE_KEY,
+} from "./constants";
import { environment } from "@/services/environment";
-const COOKIE_NAME = "admin-impersonate-user-id";
-
/**
* Cookie utility functions
*/
@@ -19,7 +21,7 @@ export const ImpersonationCookie = {
if (!environment.isClientSide()) return;
const encodedUserId = encodeURIComponent(userId);
- document.cookie = `${COOKIE_NAME}=${encodedUserId}; path=/; SameSite=Lax; Secure`;
+ document.cookie = `${IMPERSONATION_COOKIE_NAME}=${encodedUserId}; path=/; SameSite=Lax; Secure`;
},
/**
@@ -28,7 +30,7 @@ export const ImpersonationCookie = {
clear(): void {
if (!environment.isClientSide()) return;
- document.cookie = `${COOKIE_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax; Secure`;
+ document.cookie = `${IMPERSONATION_COOKIE_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax; Secure`;
},
/**
@@ -40,7 +42,7 @@ export const ImpersonationCookie = {
try {
const cookieValue = document.cookie
.split("; ")
- .find((row) => row.startsWith(`${COOKIE_NAME}=`))
+ .find((row) => row.startsWith(`${IMPERSONATION_COOKIE_NAME}=`))
?.split("=")[1];
return cookieValue ? decodeURIComponent(cookieValue) : null;
@@ -59,7 +61,7 @@ export const ImpersonationCookie = {
try {
const { cookies } = await import("next/headers");
const cookieStore = await cookies();
- const impersonationCookie = cookieStore.get(COOKIE_NAME);
+ const impersonationCookie = cookieStore.get(IMPERSONATION_COOKIE_NAME);
return impersonationCookie?.value || null;
} catch (error) {
console.debug("Could not access server-side cookies:", error);
@@ -165,3 +167,23 @@ export const ImpersonationState = {
return await ImpersonationCookie.getServerSide();
},
};
+
+/**
+ * Returns system headers to attach to every backend request.
+ *
+ * Currently adds the impersonation header (X-Act-As-User-Id) when an admin
+ * is impersonating a user. Extend this function to add other cross-cutting
+ * request headers rather than scattering them across callers.
+ *
+ * @remarks Client-side only — returns `{}` in server components where
+ * `ImpersonationState.get()` has no access to sessionStorage or client cookies.
+ * For server-side impersonation, use `ImpersonationState.getServerSide()` instead.
+ */
+export function getSystemHeaders(): Record<string, string> {
+ const headers: Record<string, string> = {};
+ const impersonatedUserId = ImpersonationState.get();
+ if (impersonatedUserId) {
+ headers[IMPERSONATION_HEADER_NAME] = impersonatedUserId;
+ }
+ return headers;
+}