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.

feat(frontend): correlate Sentry errors with PostHog (#15690)

Nicholas Tindle47f943782751
diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.default
index 2ff1b300f3..058652f58e 100644
--- a/autogpt_platform/frontend/.env.default
+++ b/autogpt_platform/frontend/.env.default
@@ -130,6 +130,11 @@ NEXT_PUBLIC_TURNSTILE=disabled
# PostHog Analytics
NEXT_PUBLIC_POSTHOG_KEY=
NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com
+# Build-only PostHog source-map upload (personal API key with source-map write
+# access, and the destination project ID). Never NEXT_PUBLIC_: the key is
+# private, and it is not the backend's public POSTHOG_API_KEY.
+POSTHOG_SOURCEMAP_UPLOAD_KEY=
+POSTHOG_SOURCEMAP_PROJECT_ID=
# DataFast server-side goal tracking (Website Settings > API, df_ key)
DATAFAST_API_KEY=
diff --git a/autogpt_platform/frontend/Dockerfile b/autogpt_platform/frontend/Dockerfile
index 5fd70c6ba7..e7e0a7a698 100644
--- a/autogpt_platform/frontend/Dockerfile
+++ b/autogpt_platform/frontend/Dockerfile
@@ -1,3 +1,4 @@
+# syntax=docker/dockerfile:1
# Base stage for both dev and prod
FROM node:24.22.1-alpine3.23 AS base
WORKDIR /app
@@ -17,6 +18,9 @@ ARG NEXT_PUBLIC_FRONTEND_BASE_URL
# Keep Docker builds defaulting to false to avoid the memory hit.
ARG NEXT_PUBLIC_SOURCEMAPS="false"
ENV NEXT_PUBLIC_SOURCEMAPS=$NEXT_PUBLIC_SOURCEMAPS
+# Optional PostHog source-map upload; the key comes in as a BuildKit secret below.
+ARG POSTHOG_SOURCEMAP_PROJECT_ID
+ENV POSTHOG_SOURCEMAP_PROJECT_ID=$POSTHOG_SOURCEMAP_PROJECT_ID
# Allow CI's e2e build to skip Next.js's lint and type checks (CI runs them as their own jobs).
ARG NEXT_SKIP_BUILD_CHECKS="false"
ENV NEXT_SKIP_BUILD_CHECKS=$NEXT_SKIP_BUILD_CHECKS
@@ -35,7 +39,7 @@ RUN if [ -f .env.production ]; then \
RUN pnpm run generate:api
# In CI, we want NEXT_PUBLIC_PW_TEST=true during build so Next.js inlines it
# The cache mount keeps Next.js's webpack cache between builds (CI restores it too)
-RUN --mount=type=cache,target=/app/.next/cache,id=next-build-cache if [ "$NEXT_PUBLIC_PW_TEST" = "true" ]; then NEXT_PUBLIC_PW_TEST=true NODE_OPTIONS="--max-old-space-size=8192" pnpm build; else NODE_OPTIONS="--max-old-space-size=8192" pnpm build; fi
+RUN --mount=type=cache,target=/app/.next/cache,id=next-build-cache --mount=type=secret,id=POSTHOG_SOURCEMAP_UPLOAD_KEY,env=POSTHOG_SOURCEMAP_UPLOAD_KEY if [ "$NEXT_PUBLIC_PW_TEST" = "true" ]; then NEXT_PUBLIC_PW_TEST=true NODE_OPTIONS="--max-old-space-size=8192" pnpm build; else NODE_OPTIONS="--max-old-space-size=8192" pnpm build; fi
# Prod stage - based on NextJS reference Dockerfile https://github.com/vercel/next.js/blob/64271354533ed16da51be5dce85f0dbd15f17517/examples/with-docker/Dockerfile
FROM node:24.22.1-alpine3.23 AS prod
diff --git a/autogpt_platform/frontend/instrumentation-client.ts b/autogpt_platform/frontend/instrumentation-client.ts
index 321c5ffe90..6ca14e40af 100644
--- a/autogpt_platform/frontend/instrumentation-client.ts
+++ b/autogpt_platform/frontend/instrumentation-client.ts
@@ -16,10 +16,12 @@ import {
import { getSentryTunnelURL } from "@/lib/sentry-tunnel";
import { redactEventURLs, redactSpanURLs } from "@/lib/sentry-url-redaction";
import { holdReplayBackFor, setupSessionReplay } from "@/lib/session-replay";
+import { createPostHogSentryProcessor } from "@/services/analytics/sentry-posthog";
import { environment } from "@/services/environment";
import * as Sentry from "@sentry/nextjs";
const dsn = environment.getSentryDSN();
+const mirrorSentryEvent = createPostHogSentryProcessor(dsn);
Sentry.init({
dsn,
@@ -54,7 +56,11 @@ Sentry.init({
if (isFromBot(navigator.userAgent)) return null;
if (isLoggedRequestFailure(event)) return null;
if (isInjectedIframeProbe(event)) return null;
- return isNextRSCNavigationFallback(event) ? null : redactEventURLs(event);
+ if (isNextRSCNavigationFallback(event)) return null;
+ // Mirror last: after our filters (an integration would run before
+ // beforeSend) and on the stripped, URL-masked event, so PostHog never
+ // gets an email, IP address or credential Sentry doesn't keep either.
+ return mirrorSentryEvent(redactEventURLs(event));
},
beforeSendTransaction(event) {
return isFromBot(navigator.userAgent)
diff --git a/autogpt_platform/frontend/next.config.mjs b/autogpt_platform/frontend/next.config.mjs
index 27b1306327..fa16d3f512 100644
--- a/autogpt_platform/frontend/next.config.mjs
+++ b/autogpt_platform/frontend/next.config.mjs
@@ -1,3 +1,4 @@
+import { withPostHogConfig } from "@posthog/nextjs-config";
import { withSentryConfig } from "@sentry/nextjs";
// Allow Docker builds to skip source-map generation (halves memory usage).
@@ -190,7 +191,7 @@ const skipSentryPlugin =
!enableSourceMaps ||
!process.env.SENTRY_AUTH_TOKEN;
-export default skipSentryPlugin
+const configWithSentry = skipSentryPlugin
? nextConfig
: withSentryConfig(nextConfig, {
// For all available options, see:
@@ -236,3 +237,26 @@ export default skipSentryPlugin
// https://vercel.com/docs/cron-jobs
automaticVercelMonitors: true,
});
+
+// Build-only credentials, never NEXT_PUBLIC_ and never in `env` above, so they
+// stay out of the browser bundle. Named apart from the backend's public
+// POSTHOG_API_KEY so the two keys can't be mixed up.
+const postHogUploadConfigured = Boolean(
+ process.env.NODE_ENV === "production" &&
+ enableSourceMaps &&
+ process.env.POSTHOG_SOURCEMAP_UPLOAD_KEY &&
+ process.env.POSTHOG_SOURCEMAP_PROJECT_ID,
+);
+
+export default postHogUploadConfigured
+ ? withPostHogConfig(configWithSentry, {
+ personalApiKey: process.env.POSTHOG_SOURCEMAP_UPLOAD_KEY,
+ projectId: process.env.POSTHOG_SOURCEMAP_PROJECT_ID,
+ host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ sourcemaps: {
+ enabled: enableSourceMaps,
+ // Sentry also uploads these maps; neither plugin should delete them first.
+ deleteAfterUpload: false,
+ },
+ })
+ : configWithSentry;
diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.json
index 1d55dd3f0b..821682dcc2 100644
--- a/autogpt_platform/frontend/package.json
+++ b/autogpt_platform/frontend/package.json
@@ -46,6 +46,7 @@
"@hugeicons/core-free-icons": "^4.2.3",
"@hugeicons/react": "^1.1.9",
"@phosphor-icons/react": "2.1.10",
+ "@posthog/nextjs-config": "1.11.1",
"@posthog/react": "1.7.0",
"@radix-ui/react-accordion": "1.2.12",
"@radix-ui/react-checkbox": "1.3.3",
diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yaml
index cc472be0fd..fb1a70c463 100644
--- a/autogpt_platform/frontend/pnpm-lock.yaml
+++ b/autogpt_platform/frontend/pnpm-lock.yaml
@@ -40,6 +40,9 @@ importers:
'@phosphor-icons/react':
specifier: 2.1.10
+ '@posthog/nextjs-config':
+ specifier: 1.11.1
'@posthog/react':
specifier: 1.7.0
@@ -2818,9 +2821,26 @@ packages:
webpack-plugin-serve:
optional: true
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-h8bpf9ffBUH/Z9IoyGV+wiI+vS8rIPorKT3eKQXuzuwawO0G7Qvy+hDd7HQ9YJjHByYZ77yPPQvrSs4WsqTUCg==}
+ engines: {node: '>=14.14', npm: '>=6'}
+ hasBin: true
+
'@posthog/[email protected]':
resolution: {integrity: sha512-knjncrk7qRmssFRbGzBl1Tunt21GRpe0Wv+uVelyL0Rh7PdQUsgguulzXFTps8hA6wPwTU4kq85qnbAJ3eH6Wg==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-KRq26v5fXYnwV5wqTAXzPyQLCrBzzhK78QRl7UyEaPFZ4RPmVo1pBObRDbK350ah+8hTfQPanu5mM8c4CaSn5g==}
+
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-Mk9olw1ECIaK371L3NWTzM1fnkxYuCmQfU6VQpOSoBFq51Y7xj1R66zazKJLsi7hcjMAqqTkzMs+DqiFF+Jz+w==}
+ engines: {node: ^20.20.0 || >=22.22.0}
+ peerDependencies:
+ next: '>12.1.0'
+
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-ZiQfUcgY65EjF2vkqL4Aau6sx0aqvSWoXaGSGu9Solnmv6e6VRjQbAU0SCKbxpJxcEsCJof9vmvnrFTQIEOUAQ==}
+
'@posthog/[email protected]':
resolution: {integrity: sha512-pM7GL7z/rKjiIwosbRiQA3buhLI6vUo+wg+T/ZrVZC7O5bVU07TfgNZTcuOj8E9dx7vDbfNrc1kjDN7PKMM8ug==}
peerDependencies:
@@ -2834,6 +2854,14 @@ packages:
'@posthog/[email protected]':
resolution: {integrity: sha512-ypFnwTO7qbV7icylLbujbamPdQXbJq0a61GUUBnJAeTbBw/qYPIss5IRYICcbCj0uunQrwD7/CGxVb5TOYKWgA==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-0/9+02s/0uDyrH4G/qUg1yyl6gXUg8Uuxw/PlDad3KLzo9FFS9zS/kAQaEshx/saVGupj1aAy/4EUBxWisBogw==}
+
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-BMXDlpuilZR3XuTWPE3HcLEYkaStAgA3Ox3B88eCSVzFP2YY39+7sCbnjyOkeO5yY6I2TYMowSlQ49QaI8P+fA==}
+ peerDependencies:
+ webpack: ^5
+
'@prisma/[email protected]':
resolution: {integrity: sha512-QcuYy25pkXM8BJ37wVFBO7Zh34nyRV1GOb2n3lPkkbRYfl4hWl3PTcImP41P0KrzVXfa/45p6eVCos27x3exIg==}
peerDependencies:
@@ -8703,6 +8731,11 @@ packages:
engines: {node: '>=10'}
hasBin: true
+ resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
+ engines: {node: '>=10'}
+ hasBin: true
+
resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==}
@@ -12094,10 +12127,32 @@ snapshots:
type-fest: 4.41.0
webpack-hot-middleware: 2.26.1
+ '@posthog/[email protected]':
+ dependencies:
+ detect-libc: 2.1.2
+
'@posthog/[email protected]':
dependencies:
cross-spawn: 7.0.6
+ '@posthog/[email protected]':
+ dependencies:
+ '@posthog/types': 1.416.0
+
+ dependencies:
+ '@posthog/cli': 0.16.2
+ '@posthog/plugin-utils': 2.0.1
+ '@posthog/webpack-plugin': 1.7.1([email protected]([email protected]))
+ semver: 7.8.5
+ transitivePeerDependencies:
+ - webpack
+
+ '@posthog/[email protected]':
+ dependencies:
+ cross-spawn: 7.0.6
+
dependencies:
posthog-js: 1.334.1
@@ -12107,6 +12162,15 @@ snapshots:
'@posthog/[email protected]': {}
+ '@posthog/[email protected]': {}
+
+ dependencies:
+ '@posthog/cli': 0.16.2
+ '@posthog/core': 1.59.0
+ '@posthog/plugin-utils': 2.0.1
+ webpack: 5.104.1([email protected])
+
'@prisma/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.0
@@ -15263,8 +15327,7 @@ snapshots:
- optional: true
@@ -15621,8 +15684,8 @@ snapshots:
'@typescript-eslint/parser': 8.52.0([email protected])([email protected])
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected])
+ eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))([email protected])
eslint-plugin-jsx-a11y: 6.10.2([email protected])
eslint-plugin-react: 7.37.5([email protected])
eslint-plugin-react-hooks: 5.2.0([email protected])
@@ -15641,7 +15704,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -15652,22 +15715,22 @@ snapshots:
tinyglobby: 0.2.15
unrs-resolver: 1.11.1
optionalDependencies:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.52.0([email protected])([email protected])
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected])
+ eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -15678,7 +15741,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3
@@ -19076,6 +19139,8 @@ snapshots:
+
dependencies:
randombytes: 2.1.0
diff --git a/autogpt_platform/frontend/src/__tests__/instrumentation-client.test.ts b/autogpt_platform/frontend/src/__tests__/instrumentation-client.test.ts
index 5e25246db8..75799a0ef4 100644
--- a/autogpt_platform/frontend/src/__tests__/instrumentation-client.test.ts
+++ b/autogpt_platform/frontend/src/__tests__/instrumentation-client.test.ts
@@ -1,4 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ErrorEvent } from "@sentry/nextjs";
+
+const mirrorEvent = vi.hoisted(() => vi.fn((event: ErrorEvent) => event));
+vi.mock("@/services/analytics/sentry-posthog", () => ({
+ createPostHogSentryProcessor: () => mirrorEvent,
+}));
const { initMock, reportingObserverIntegrationMock, holdReplayBackForMock } =
vi.hoisted(() => ({
@@ -120,8 +126,11 @@ describe("Sentry client instrumentation", () => {
};
expect(beforeSend).toBeTypeOf("function");
+ mirrorEvent.mockClear();
expect(beforeSend(rscFallback, {})).toBeNull();
+ expect(mirrorEvent).not.toHaveBeenCalled();
expect(beforeSend(fetchError, {})).toBe(fetchError);
+ expect(mirrorEvent).toHaveBeenCalledExactlyOnceWith(fetchError);
});
it("sends errors whose trace context carries no IP address or email", async () => {
@@ -188,9 +197,12 @@ describe("Sentry client instrumentation", () => {
},
};
+ mirrorEvent.mockClear();
expect(beforeSend(injectedProbe, {})).toBeNull();
+ expect(mirrorEvent).not.toHaveBeenCalled();
expect(beforeSend(blocked, {})).toBe(blocked);
expect(beforeSend(ourWarning, {})).toBe(ourWarning);
+ expect(mirrorEvent).toHaveBeenCalledTimes(2);
});
it("traces every transaction but profiles one in ten", async () => {
diff --git a/autogpt_platform/frontend/src/__tests__/next-config-posthog-sourcemaps.test.ts b/autogpt_platform/frontend/src/__tests__/next-config-posthog-sourcemaps.test.ts
new file mode 100644
index 0000000000..4cd37328b6
--- /dev/null
+++ b/autogpt_platform/frontend/src/__tests__/next-config-posthog-sourcemaps.test.ts
@@ -0,0 +1,70 @@
+import { join } from "node:path";
+import type { NextConfig } from "next";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const uploadKey = "private-upload-key-value";
+const publicProjectKey = "public-project-key-value";
+
+type NextConfigFunction = (
+ phase: string,
+ context: { defaultConfig: NextConfig },
+) => Promise<NextConfig>;
+
+async function loadConfig() {
+ vi.resetModules();
+ const { default: config } = await vi.importActual<{
+ default: NextConfig | NextConfigFunction;
+ }>(join(process.cwd(), "next.config.mjs"));
+ return config;
+}
+
+beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("NEXT_PUBLIC_SOURCEMAPS", "true");
+ vi.stubEnv("SENTRY_AUTH_TOKEN", "");
+ vi.stubEnv("POSTHOG_SOURCEMAP_UPLOAD_KEY", "");
+ vi.stubEnv("POSTHOG_SOURCEMAP_PROJECT_ID", "");
+ vi.stubEnv("POSTHOG_API_KEY", "");
+ vi.stubEnv("POSTHOG_PROJECT_ID", "");
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("next.config.mjs PostHog source-map upload", () => {
+ it("uploads with both build-only credentials and keeps the key out of the browser bundle", async () => {
+ vi.stubEnv("POSTHOG_SOURCEMAP_UPLOAD_KEY", uploadKey);
+ vi.stubEnv("POSTHOG_SOURCEMAP_PROJECT_ID", "117338");
+
+ const config = await loadConfig();
+
+ expect(config).toBeTypeOf("function");
+ const resolved = await (config as NextConfigFunction)(
+ "phase-production-build",
+ { defaultConfig: {} },
+ );
+ expect(resolved.productionBrowserSourceMaps).toBe(true);
+ expect(JSON.stringify(resolved.env)).not.toContain(uploadKey);
+ expect(Object.keys(resolved.env ?? {})).not.toContain(
+ "POSTHOG_SOURCEMAP_UPLOAD_KEY",
+ );
+ });
+
+ it.each([
+ ["only the upload key", { POSTHOG_SOURCEMAP_UPLOAD_KEY: uploadKey }],
+ ["only the project", { POSTHOG_SOURCEMAP_PROJECT_ID: "117338" }],
+ // The backend's public project key must never be taken for the upload key.
+ [
+ "the backend's variable names",
+ { POSTHOG_API_KEY: publicProjectKey, POSTHOG_PROJECT_ID: "117338" },
+ ],
+ ])("skips the upload with %s", async (_, env) => {
+ for (const [name, value] of Object.entries(env)) vi.stubEnv(name, value);
+
+ const config = await loadConfig();
+
+ expect(config).toBeTypeOf("object");
+ expect(JSON.stringify((config as NextConfig).env)).not.toContain(uploadKey);
+ });
+});
diff --git a/autogpt_platform/frontend/src/playwright/journeys/copilot-chat.ts b/autogpt_platform/frontend/src/playwright/journeys/copilot-chat.ts
index 145975f30f..117d172f6e 100644
--- a/autogpt_platform/frontend/src/playwright/journeys/copilot-chat.ts
+++ b/autogpt_platform/frontend/src/playwright/journeys/copilot-chat.ts
@@ -6,7 +6,16 @@ import {
/** Opens AutoPilot and sends the first message of a new chat. */
export async function startChat(page: Page, message: string) {
- await page.goto("/home");
+ const [transports] = await Promise.all([
+ page.waitForResponse(
+ (response) =>
+ response.request().method() === "GET" &&
+ new URL(response.url()).pathname === "/api/proxy/api/chat/transports",
+ ),
+ page.goto("/home"),
+ ]);
+ expect(transports.status()).toBe(200);
+ await transports.finished();
const input = page.getByRole("textbox", { name: "Chat message input" });
await expect(input).toBeVisible();
await input.fill(message);
diff --git a/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
index e3c617803d..299d1b5626 100644
--- a/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
@@ -64,6 +64,7 @@ describe("PostHogProvider", () => {
expect.objectContaining({
api_host: "/relay/pnosthog",
ui_host: "https://eu.posthog.com",
+ capture_exceptions: false,
}),
);
});
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
index f65116adab..a593847fe0 100644
--- a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
@@ -45,6 +45,7 @@ export function PostHogProvider({ children }: { children: ReactNode }) {
capture_pageview: false,
capture_pageleave: true,
autocapture: true,
+ capture_exceptions: false,
...(anonymousID && {
bootstrap: { distinctID: anonymousID, isIdentifiedID: false },
}),
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/sentry-posthog-instrumentation.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/sentry-posthog-instrumentation.test.ts
new file mode 100644
index 0000000000..f88987bc26
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/sentry-posthog-instrumentation.test.ts
@@ -0,0 +1,233 @@
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import * as Sentry from "@sentry/nextjs";
+import posthog from "posthog-js";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ it,
+ vi,
+} from "vitest";
+
+vi.mock("@sentry/nextjs", async () => {
+ const { createRequire } = await import("node:module");
+ const nextjs = createRequire(import.meta.url).resolve(
+ "@sentry/nextjs/package.json",
+ );
+ const react = createRequire(nextjs).resolve("@sentry/react/package.json");
+ const browser = createRequire(react).resolve("@sentry/browser/package.json");
+ const sdk = await import(
+ browser.replace("package.json", "build/npm/esm/prod/index.js")
+ );
+ return { ...sdk, captureRouterTransitionStart: () => undefined };
+});
+
+const sent: Sentry.ErrorEvent[] = [];
+const consoleErrors = vi.fn();
+const rateLimitMessage =
+ "[PostHog.js] This capture call is ignored due to client rate limiting.";
+
+beforeAll(async () => {
+ vi.spyOn(console, "error").mockImplementation(consoleErrors);
+ vi.stubEnv("NEXT_PUBLIC_SENTRY_DSN", "https://[email protected]/1");
+ posthog.init("phc_test", {
+ api_host: "https://posthog.example.com",
+ persistence: "memory",
+ capture_pageview: false,
+ capture_pageleave: false,
+ autocapture: false,
+ capture_exceptions: false,
+ disable_session_recording: true,
+ advanced_disable_flags: true,
+ disable_external_dependency_loading: true,
+ opt_out_capturing_by_default: true,
+ opt_out_useragent_filter: true,
+ before_send: () => null,
+ });
+ await import("../../../../instrumentation-client");
+ vi.spyOn(Sentry.getClient()!.getTransport()!, "send").mockImplementation(
+ async ([, items]) => {
+ for (const [header, payload] of items) {
+ if (header.type === "event") sent.push(payload as Sentry.ErrorEvent);
+ }
+ return {};
+ },
+ );
+});
+
+beforeEach(({ task }) => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "phc_test");
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_HOST", "https://eu.i.posthog.com");
+ configureCookiebot();
+ installCookiebot({ statistics: true });
+ posthog.reset();
+ posthog.opt_in_capturing({ captureEventName: false });
+ posthog.set_config({
+ rate_limiting: { events_per_second: 100, events_burst_limit: 100 },
+ });
+ vi.spyOn(posthog, "capture");
+ consoleErrors.mockClear();
+ sent.length = 0;
+ Sentry.getCurrentScope().setFingerprint([task.name]);
+});
+
+afterEach(() => {
+ posthog.opt_out_capturing();
+ removeCookiebot();
+ vi.mocked(posthog.capture).mockRestore();
+ vi.useRealTimers();
+});
+
+afterAll(async () => {
+ await Sentry.close(2000);
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+it("does not feed an exhausted PostHog rate limiter's console error back into capture", async () => {
+ posthog.set_config({
+ rate_limiting: { events_per_second: 1, events_burst_limit: 1 },
+ });
+ posthog.capture("fill-bucket");
+ expect(posthog.is_capturing()).toBe(true);
+ vi.mocked(posthog.capture).mockClear();
+
+ Sentry.captureException(
+ new Error("Application failure during an error burst"),
+ );
+ await Sentry.flush(2000);
+
+ expect(consoleErrors).toHaveBeenCalledExactlyOnceWith(
+ "[PostHog.js]",
+ "This capture call is ignored due to client rate limiting.",
+ );
+ expect(sent).toHaveLength(2);
+ expect(sent.find((event) => event.logger !== "console")).toMatchObject({
+ exception: {
+ values: [{ value: "Application failure during an error burst" }],
+ },
+ });
+ expect(sent.find((event) => event.logger === "console")).toMatchObject({
+ message: rateLimitMessage,
+ level: "error",
+ });
+ expect(
+ vi
+ .mocked(posthog.capture)
+ .mock.calls.filter(([name]) => name === "$exception"),
+ ).toHaveLength(1);
+});
+
+it("keeps the rate-limit diagnostic in Sentry without mirroring or adding PostHog tags", async () => {
+ console.error(
+ "[PostHog.js]",
+ "This capture call is ignored due to client rate limiting.",
+ );
+ await Sentry.flush(2000);
+
+ expect(sent).toHaveLength(1);
+ expect(sent[0]).toMatchObject({
+ logger: "console",
+ message: rateLimitMessage,
+ });
+ expect(sent[0].tags ?? {}).not.toHaveProperty("PostHog Person URL");
+ expect(posthog.capture).not.toHaveBeenCalled();
+});
+
+it.each([
+ "Workflow failed",
+ "This capture call is ignored due to client rate limiting.",
+])("still mirrors an application console error: %s", async (message) => {
+ console.error(message);
+ await Sentry.flush(2000);
+
+ expect(sent).toHaveLength(1);
+ expect(posthog.capture).toHaveBeenCalledExactlyOnceWith(
+ "$exception",
+ expect.objectContaining({ $sentry_event_id: sent[0].event_id }),
+ expect.anything(),
+ );
+});
+
+it("still mirrors a directly captured application message matching the diagnostic", async () => {
+ Sentry.captureMessage(rateLimitMessage, "error");
+ await Sentry.flush(2000);
+
+ expect(sent).toHaveLength(1);
+ expect(posthog.capture).toHaveBeenCalledExactlyOnceWith(
+ "$exception",
+ expect.objectContaining({ $sentry_event_id: sent[0].event_id }),
+ expect.anything(),
+ );
+});
+
+it("mirrors only the PII-stripped error: no email, IP address, headers or breadcrumbs reach PostHog", async () => {
+ const delivered: unknown[] = [];
+ posthog.set_config({
+ before_send: (event) => {
+ delivered.push(event);
+ return null;
+ },
+ });
+ const email = "[email protected]";
+ const ip = "203.0.113.7";
+ const token = "secret-reset-token";
+ Sentry.setUser({ id: "user-123", email, ip_address: ip, username: "person" });
+ Sentry.addBreadcrumb({
+ category: "fetch",
+ data: { url: `https://api.example.com/reset?token=${token}` },
+ });
+
+ Sentry.captureEvent({
+ level: "error",
+ exception: { values: [{ type: "TypeError", value: "Workflow failed" }] },
+ request: {
+ url: `https://platform.example.com/reset-password?token=${token}`,
+ headers: { "X-Forwarded-For": ip, "X-Real-IP": ip },
+ },
+ contexts: {
+ trace: {
+ trace_id: "0123456789abcdef0123456789abcdef",
+ span_id: "0123456789abcdef",
+ data: { "client.address": ip, "user.email": email },
+ },
+ },
+ extra: { email },
+ });
+ await Sentry.flush(2000);
+ Sentry.setUser(null);
+ Sentry.getCurrentScope().clearBreadcrumbs();
+ posthog.set_config({ before_send: () => null });
+
+ expect(sent).toHaveLength(1);
+ expect(sent[0].user).toEqual({ id: "user-123" });
+ const captures = vi
+ .mocked(posthog.capture)
+ .mock.calls.filter(([name]) => name === "$exception");
+ expect(captures).toHaveLength(1);
+ expect(Object.keys(captures[0][1] ?? {}).sort()).toEqual([
+ "$exception_level",
+ "$exception_list",
+ "$exception_message",
+ "$exception_type",
+ "$sentry_event_id",
+ "$sentry_exception",
+ "$sentry_exception_message",
+ "$sentry_exception_type",
+ "$sentry_tags",
+ ]);
+ expect(delivered).toHaveLength(1);
+ const mirrored = JSON.stringify([captures[0][1], delivered]);
+ expect(mirrored).toContain(sent[0].event_id);
+ for (const secret of [email, ip, token, "X-Forwarded-For", "X-Real-IP"]) {
+ expect(mirrored).not.toContain(secret);
+ }
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/sentry-posthog.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/sentry-posthog.test.ts
new file mode 100644
index 0000000000..4eb8f1502c
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/sentry-posthog.test.ts
@@ -0,0 +1,231 @@
+import type { ErrorEvent } from "@sentry/nextjs";
+import posthog from "posthog-js";
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import {
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import { createPostHogSentryProcessor } from "../sentry-posthog";
+
+const dsn =
+ "https://[email protected]/4507946746380288";
+const processEvent = createPostHogSentryProcessor(dsn);
+
+function sentryEvent(level: ErrorEvent["level"] = "error"): ErrorEvent {
+ return {
+ type: undefined,
+ event_id: "0123456789abcdef0123456789abcdef",
+ level,
+ exception: {
+ values: [
+ {
+ type: "TypeError",
+ value: "Could not load workflow",
+ stacktrace: {
+ frames: [
+ { filename: "https://app.example.com/app.js", lineno: 42 },
+ ],
+ },
+ },
+ ],
+ },
+ tags: { environment: "test" },
+ };
+}
+
+beforeAll(() => {
+ posthog.init("phc_test", {
+ api_host: "https://posthog.example.com",
+ ui_host: "https://eu.posthog.com",
+ persistence: "memory",
+ capture_pageview: false,
+ capture_pageleave: false,
+ autocapture: false,
+ capture_exceptions: false,
+ disable_session_recording: true,
+ advanced_disable_flags: true,
+ disable_external_dependency_loading: true,
+ opt_out_capturing_by_default: true,
+ });
+});
+
+beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "phc_test");
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_HOST", "https://eu.i.posthog.com");
+ configureCookiebot();
+ installCookiebot({ statistics: true });
+ vi.spyOn(posthog, "capture").mockReturnValue(undefined);
+ posthog.opt_in_capturing({ captureEventName: false });
+ posthog.identify("user-123");
+ vi.mocked(posthog.capture).mockClear();
+});
+
+afterEach(() => {
+ posthog.opt_out_capturing();
+ removeCookiebot();
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+});
+
+describe("Sentry to PostHog correlation", () => {
+ it.each(["error", "fatal"] as const)(
+ "mirrors one %s with exact event, person and replay links",
+ (level) => {
+ vi.spyOn(posthog, "sessionRecordingStarted").mockReturnValue(true);
+ vi.spyOn(posthog, "get_session_replay_url").mockReturnValue(
+ "https://eu.posthog.com/replay/session?t=42",
+ );
+ const event = sentryEvent(level);
+
+ expect(processEvent(event)).toBe(event);
+
+ expect(posthog.capture).toHaveBeenCalledOnce();
+ expect(posthog.capture).toHaveBeenCalledWith(
+ "$exception",
+ expect.objectContaining({
+ $sentry_event_id: event.event_id,
+ $sentry_url: `https://sentry.io/organizations/significant-gravitas/issues/?project=4507946746380288&query=${event.event_id}`,
+ $exception_message: "Could not load workflow",
+ $exception_level: level,
+ $exception_list: [
+ expect.objectContaining({
+ stacktrace: expect.objectContaining({
+ frames: [expect.objectContaining({ lineno: 42 })],
+ }),
+ }),
+ ],
+ }),
+ expect.anything(),
+ );
+ expect(event.tags).toEqual({
+ environment: "test",
+ "PostHog Person URL":
+ "https://eu.posthog.com/project/phc_test/person/user-123",
+ "PostHog Recording URL": "https://eu.posthog.com/replay/session?t=42",
+ });
+ expect(posthog.get_session_replay_url).toHaveBeenCalledWith({
+ withTimestamp: true,
+ });
+ },
+ );
+
+ it("links anonymous visitors without inventing a recording", () => {
+ posthog.reset();
+ posthog.opt_in_capturing({ captureEventName: false });
+ vi.mocked(posthog.capture).mockClear();
+ const event = sentryEvent();
+ processEvent(event);
+ expect(event.tags?.["PostHog Person URL"]).toContain(
+ `/person/${posthog.get_distinct_id()}`,
+ );
+ expect(event.tags).not.toHaveProperty("PostHog Recording URL");
+ expect(posthog.capture).toHaveBeenCalledOnce();
+ });
+
+ it.each(["warning", "info", "debug", "log"] as const)(
+ "does not mirror %s events",
+ (level) => {
+ const event = sentryEvent(level);
+ expect(processEvent(event)).toBe(event);
+ expect(event.tags).toEqual({ environment: "test" });
+ expect(posthog.capture).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(["fetch", "xhr"])(
+ "does not mirror a failed %s response the HttpClient integration reports",
+ (type) => {
+ const event = sentryEvent();
+ event.exception!.values![0].mechanism = {
+ type: `auto.http.client.${type}`,
+ handled: false,
+ };
+ expect(processEvent(event)).toBe(event);
+ expect(event.tags).toEqual({ environment: "test" });
+ expect(posthog.capture).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([undefined, { statistics: false }, { marketing: true }])(
+ "requires analytics consent: %j",
+ (answer) => {
+ installCookiebot(answer);
+ const event = sentryEvent();
+ expect(processEvent(event)).toBe(event);
+ expect(event.tags).toEqual({ environment: "test" });
+ expect(posthog.capture).not.toHaveBeenCalled();
+ },
+ );
+
+ it("stops immediately on consent withdrawal", () => {
+ processEvent(sentryEvent());
+ answerCookiebot({ statistics: false });
+ const event = sentryEvent();
+ processEvent(event);
+ expect(posthog.capture).toHaveBeenCalledOnce();
+ expect(event.tags).toEqual({ environment: "test" });
+ });
+
+ it("respects SDK opt-out even with banner consent", () => {
+ posthog.opt_out_capturing();
+ const event = sentryEvent();
+ processEvent(event);
+ expect(event.tags).toEqual({ environment: "test" });
+ expect(posthog.capture).not.toHaveBeenCalled();
+ });
+
+ it("does not mirror when PostHog is disabled", () => {
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "");
+ const event = sentryEvent();
+ processEvent(event);
+ expect(event.tags).toEqual({ environment: "test" });
+ expect(posthog.capture).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ "https://[email protected]/123",
+ "https://[email protected]/123",
+ ])("uses the configured preview project from %s", (previewDSN) => {
+ createPostHogSentryProcessor(previewDSN)(sentryEvent());
+ expect(posthog.capture).toHaveBeenCalledWith(
+ "$exception",
+ expect.objectContaining({
+ $sentry_url: expect.stringContaining("project=123&query="),
+ }),
+ expect.anything(),
+ );
+ });
+
+ it.each([
+ undefined,
+ "invalid",
+ "https://[email protected]/7",
+ "https://[email protected]/7",
+ ])("does not invent an AutoGPT Sentry link for %s", (otherDSN) => {
+ createPostHogSentryProcessor(otherDSN)(sentryEvent());
+ expect(posthog.capture).toHaveBeenCalledOnce();
+ expect(vi.mocked(posthog.capture).mock.calls[0][1]).not.toHaveProperty(
+ "$sentry_url",
+ );
+ });
+
+ it("keeps Sentry reporting when PostHog fails", () => {
+ vi.mocked(posthog.capture).mockImplementation(() => {
+ throw new Error("PostHog unavailable");
+ });
+ const event = sentryEvent();
+ expect(processEvent(event)).toBe(event);
+ expect(posthog.capture).toHaveBeenCalledOnce();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/sentry-posthog.ts b/autogpt_platform/frontend/src/services/analytics/sentry-posthog.ts
new file mode 100644
index 0000000000..10fe3e0c45
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/sentry-posthog.ts
@@ -0,0 +1,80 @@
+import { hasConsentFor } from "@/services/consent/consent";
+import { environment, HOSTED_SENTRY_DSN } from "@/services/environment";
+import type { ErrorEvent } from "@sentry/nextjs";
+import posthog from "posthog-js";
+
+export function createPostHogSentryProcessor(dsn: string | undefined) {
+ const integration = posthog.sentryIntegration({
+ ...getSentryProject(dsn),
+ severityAllowList: ["error", "fatal"],
+ });
+
+ return function mirrorSentryEvent(event: ErrorEvent) {
+ if (isPostHogRateLimitNotice(event) || isFailedHTTPResponse(event)) {
+ return event;
+ }
+ try {
+ if (
+ environment.isPostHogEnabled() &&
+ hasConsentFor("analytics") &&
+ !posthog.has_opted_out_capturing()
+ ) {
+ integration.processEvent(event);
+ }
+ } catch {
+ // An analytics failure must not drop the original Sentry event.
+ }
+ return event;
+ };
+}
+
+// posthog-js's own wording, matched whole so an app error that merely quotes
+// it still mirrors. sentry-posthog-instrumentation.test.ts drives the real
+// rate limiter, so a reworded notice fails CI instead of looping silently.
+function isPostHogRateLimitNotice(event: ErrorEvent) {
+ return (
+ event.logger === "console" &&
+ event.message ===
+ "[PostHog.js] This capture call is ignored due to client rate limiting."
+ );
+}
+
+// A failed response the HttpClient integration reports is not a bug in the
+// page, and one from the PostHog relay would be mirrored back into PostHog.
+// These events carry no level today, so the allow-list skips them already;
+// this keeps them out if Sentry starts setting one.
+function isFailedHTTPResponse(event: ErrorEvent) {
+ return Boolean(
+ event.exception?.values?.some((exception) =>
+ exception.mechanism?.type?.startsWith("auto.http.client."),
+ ),
+ );
+}
+
+// The organization the hosted DSN reports to; next.config.mjs uploads source
+// maps under the same slug.
+const SENTRY_ORG_SLUG = "significant-gravitas";
+const SENTRY_INGEST_HOST = /^(o\d+)\.ingest(?:\.[a-z]{2})?\.sentry\.io$/;
+
+function getIngestOrg(dsn: string) {
+ return new URL(dsn).hostname.match(SENTRY_INGEST_HOST)?.[1];
+}
+
+function getSentryProject(dsn: string | undefined) {
+ if (!dsn) return {};
+ try {
+ const projectID = Number(new URL(dsn).pathname.slice(1));
+ const org = getIngestOrg(dsn);
+ if (
+ org &&
+ org === getIngestOrg(HOSTED_SENTRY_DSN) &&
+ Number.isSafeInteger(projectID) &&
+ projectID > 0
+ ) {
+ return { organization: SENTRY_ORG_SLUG, projectId: projectID };
+ }
+ } catch {
+ // Unknown DSNs can still receive PostHog links without a guessed Sentry URL.
+ }
+ return {};
+}
diff --git a/autogpt_platform/frontend/src/services/environment/index.ts b/autogpt_platform/frontend/src/services/environment/index.ts
index 58b85aa59e..88f755bf3a 100644
--- a/autogpt_platform/frontend/src/services/environment/index.ts
+++ b/autogpt_platform/frontend/src/services/environment/index.ts
@@ -159,7 +159,7 @@ function isVercel() {
// AutoGPT's own Sentry project. Only our hosted deployments (on Vercel) report
// to it; a self-hosted build reports nowhere unless its operator sets their own
// NEXT_PUBLIC_SENTRY_DSN, so no self-hoster sends us errors without opting in.
-const HOSTED_SENTRY_DSN =
+export const HOSTED_SENTRY_DSN =
"https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288";
function getSentryDSN() {
diff --git a/docs/engineering/sentry-posthog-correlation.md b/docs/engineering/sentry-posthog-correlation.md
new file mode 100644
index 0000000000..83ebecca7a
--- /dev/null
+++ b/docs/engineering/sentry-posthog-correlation.md
@@ -0,0 +1,100 @@
+# Sentry and PostHog error correlation
+
+The browser's Sentry `beforeSend` forwards surviving error/fatal events through
+PostHog's Sentry integration. PostHog records `$exception` with `$sentry_event_id`
+and a `$sentry_url` pointing to that exact event in Sentry. Sentry receives
+`PostHog Person URL` and, while PostHog recording is active, a timestamped
+`PostHog Recording URL` tag. Anonymous visitors use their current PostHog ID;
+signed-in visitors use the identified user ID.
+
+Both SDKs deliver independently. Mirroring runs before Sentry's transport
+acknowledges the event. Sentry rate limits, quota rejection, or network failure
+can leave a PostHog exception with a Sentry link that has no stored event.
+PostHog delivery can also fail independently. Event counts and billed usage
+can therefore differ; a correlation ID does not confirm storage in both products.
+
+Forwarding and links require analytics consent and an initialized, opted-in
+PostHog client. Consent is checked for each error. Early startup errors and
+errors without consent still go to Sentry, but are not queued for later mirroring.
+Sentry's existing filters run first. Failed HTTP responses the HttpClient
+integration reports (mechanism `auto.http.client.*`) stay in Sentry only: they
+are not page bugs, and a failing PostHog relay would otherwise be mirrored
+back into PostHog. Warnings, transactions, backend errors, and
+historical events are outside this bridge. PostHog failures do not stop Sentry
+reporting. PostHog exception autocapture stays disabled to avoid a second capture
+of the same browser error.
+
+Disabling Sentry with `DISABLE_SENTRY=true` also stops PostHog exception mirroring.
+The same applies when no Sentry DSN is configured or available through the hosted
+fallback. PostHog product analytics continues independently.
+
+The Sentry link uses the configured DSN's project in AutoGPT's Sentry organization,
+including preview projects. Other organizations and self-hosted DSNs still get
+PostHog tags, but no guessed Sentry URL.
+
+## What PostHog receives
+
+`beforeSend` first strips the event the way every Sentry event is stripped
+(the user reduced to id and role, IP-like span attributes dropped), runs the
+filters, and only then mirrors it. PostHog's integration copies just these
+fields of the Sentry event into `$exception`:
+
+- `$exception_list` and `$sentry_exception`: the exception type, message,
+ mechanism and stack frames (file URLs, functions, lines and columns).
+- `$exception_message`, `$exception_type`, `$sentry_exception_message`,
+ `$sentry_exception_type` and `$exception_level`.
+- `$sentry_event_id`, `$sentry_url` and `$sentry_tags` (the Sentry tags,
+ including the PostHog person and recording links).
+
+It never copies the Sentry user, request (URL, headers), contexts, extra data
+or breadcrumbs; `sentry-posthog-instrumentation.test.ts` checks that no email,
+IP address, IP header or breadcrumb URL reaches PostHog. PostHog then adds the
+standard properties it puts on every consented event (current URL, browser,
+device, session and person).
+
+## Deploy
+
+The bridge uses the existing public PostHog key/host, Sentry DSN, and Cookiebot
+configuration. Deploying the frontend enables it for future eligible events.
+The Sentry warehouse connector is independent: it imports tables, and does not
+install this browser bridge or synchronize issue resolution status.
+
+Source-map upload additionally requires these **build-time** variables:
+
+- `POSTHOG_SOURCEMAP_UPLOAD_KEY`: a private PostHog personal API key with source-map
+ write access. Not the backend's `POSTHOG_API_KEY`, which is the public project key.
+- `POSTHOG_SOURCEMAP_PROJECT_ID`: the destination project ID (`117338` for production).
+- `NEXT_PUBLIC_POSTHOG_HOST`: the matching PostHog Cloud region.
+- `NEXT_PUBLIC_SOURCEMAPS=true`: explicit opt-in for Docker builds; Vercel builds
+ already enable source maps unless explicitly disabled.
+
+Set the private key in the deployment platform's secret store, never in a public
+environment variable or committed file. On Vercel, add both variables to the
+Production environment only; Next.js inlines only `NEXT_PUBLIC_` variables and
+`env` from `next.config.mjs` into the browser, so neither reaches the bundle.
+Without them, builds still pass and PostHog shows minified stack traces. For Docker, pass it using BuildKit
+`--secret id=POSTHOG_SOURCEMAP_UPLOAD_KEY,env=POSTHOG_SOURCEMAP_UPLOAD_KEY`, plus
+`--build-arg POSTHOG_SOURCEMAP_PROJECT_ID=117338 --build-arg NEXT_PUBLIC_SOURCEMAPS=true`.
+The Dockerfile mounts the key only for the build command. Existing Sentry upload
+credentials remain necessary for Sentry's own source maps. Both plugins retain
+maps, matching the existing public-source policy and avoiding deletion races.
+Without PostHog upload credentials, builds continue with the existing config.
+
+## Verify in a preview
+
+1. Accept analytics consent, sign in, and trigger one controlled browser error
+ through Sentry in the preview's project.
+2. Find the `$exception` in PostHog. Follow `$sentry_url` and verify the Sentry event
+ ID equals `$sentry_event_id`. Verify the stack resolves to the original source.
+3. Follow the Sentry `PostHog Person URL` tag. If recording is active, follow its
+ recording tag and verify the session and timestamp.
+4. Repeat anonymously, then revoke analytics consent and repeat. The anonymous
+ event should link to that anonymous person; the revoked event should only
+ reach Sentry, without PostHog tags.
+5. Verify a warning and an error matching an existing Sentry filter do not create
+ PostHog exceptions. One accepted error should create at most one exception.
+
+Mirroring adds a PostHog exception for each eligible Sentry event, subject to SDK
+delivery limits. It does not reduce Sentry usage. Warehouse sync has its separate
+row-based usage. The bridge reuses the existing PostHog SDK and asynchronous
+transport; its synchronous work is consent checking and event/property mapping.