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(platform): tag Vercel previews as preview in Sentry, and stop pytest runs reporting (#14392)
Reinier van der Leer4f3786345822
diff --git a/autogpt_platform/backend/backend/util/metrics.py b/autogpt_platform/backend/backend/util/metrics.pyindex fb29e33986..8a24b6057b 100644--- a/autogpt_platform/backend/backend/util/metrics.py+++ b/autogpt_platform/backend/backend/util/metrics.py@@ -1,5 +1,7 @@import logging+import osimport re+import sysfrom enum import Enumfrom types import TracebackType@@ -260,6 +262,9 @@ def _before_send(event, hint):def sentry_init():+ if _running_under_pytest():+ return+sentry_dsn = settings.secrets.sentry_dsnintegrations = []if feature_flag.is_configured() and LaunchDarklyIntegration is not None:@@ -287,6 +292,13 @@ def sentry_init():)+def _running_under_pytest() -> bool:+ """sentry_init() runs at import time (AppProcess class body), before pytest+ sets PYTEST_CURRENT_TEST; the env var covers spawned service subprocesses,+ which do not inherit sys.modules. Self-hosted instances match neither."""+ return "pytest" in sys.modules or "PYTEST_CURRENT_TEST" in os.environ++def sentry_capture_error(error: BaseException):_sentry_capture_exception(error)_sentry_flush()diff --git a/autogpt_platform/backend/backend/util/metrics_test.py b/autogpt_platform/backend/backend/util/metrics_test.pyindex 1cbbf3b7c0..b2001f5a81 100644--- a/autogpt_platform/backend/backend/util/metrics_test.py+++ b/autogpt_platform/backend/backend/util/metrics_test.py@@ -12,9 +12,14 @@ from __future__ import annotationsimport jsonimport sys+import sentry_sdkfrom sentry_sdk.consts import DEFAULT_OPTIONSfrom sentry_sdk.utils import event_from_exception+# Imported at module scope on purpose: AppProcess calls sentry_init() in its+# class body, so the guard has to hold at collection time, not just in a test.+import backend.util.process+from backend.util import metricsfrom backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.metrics import (_FALKORDB_DRIVER_LOGGER,@@ -312,3 +317,56 @@ def test_falkordb_teardown_signatures_cover_known_patterns() -> None:graphiti FalkorDB driver docstring pairs together."""expected = {"buffer is closed", "connection closed by server"}assert expected == set(_FALKORDB_TEARDOWN_SIGNATURES)+++# ---------- pytest runs must not reach Sentry ----------++_FAKE_DSN = "https://[email protected]/1"+++def _spy_on_sentry_init(monkeypatch) -> list[dict]:+ calls: list[dict] = []+ monkeypatch.setattr(metrics, "_sentry_init", lambda **kw: calls.append(kw))+ monkeypatch.setattr(metrics.settings.secrets, "sentry_dsn", _FAKE_DSN)+ return calls+++def test_no_sentry_client_is_active_under_pytest() -> None:+ """End-to-end. AppProcess runs sentry_init() in its class body, so this+ module's import above is what a live client here would have come from."""+ assert backend.util.process.AppProcess+ assert sentry_sdk.get_client().is_active() is False+++def test_sentry_init_skipped_at_collection_time(monkeypatch) -> None:+ """pytest only sets PYTEST_CURRENT_TEST once a test item runs, so the+ import-time call that AppProcess makes is covered by sys.modules alone."""+ calls = _spy_on_sentry_init(monkeypatch)+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)++ metrics.sentry_init()++ assert calls == []+++def test_sentry_init_runs_outside_pytest(monkeypatch) -> None:+ calls = _spy_on_sentry_init(monkeypatch)+ monkeypatch.delitem(sys.modules, "pytest")+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)++ metrics.sentry_init()++ assert len(calls) == 1+ assert calls[0]["dsn"] == _FAKE_DSN+++def test_sentry_init_skipped_in_subprocess_spawned_by_pytest(monkeypatch) -> None:+ """A spawned service subprocess does not inherit sys.modules, but does+ inherit PYTEST_CURRENT_TEST from the environment."""+ calls = _spy_on_sentry_init(monkeypatch)+ monkeypatch.delitem(sys.modules, "pytest")+ monkeypatch.setenv("PYTEST_CURRENT_TEST", "backend/util/metrics_test.py::t (call)")++ metrics.sentry_init()++ assert calls == []diff --git a/autogpt_platform/frontend/instrumentation-client.ts b/autogpt_platform/frontend/instrumentation-client.tsindex eb580e9cbc..a7808e5365 100644--- a/autogpt_platform/frontend/instrumentation-client.ts+++ b/autogpt_platform/frontend/instrumentation-client.ts@@ -6,11 +6,7 @@ import { consent } from "@/services/consent/cookies";import { environment } from "@/services/environment";import * as Sentry from "@sentry/nextjs";-const isProdOrDev = environment.isProd() || environment.isDev();-const isCloud = environment.isCloud();-const isDisabled = process.env.DISABLE_SENTRY === "true";--const shouldEnable = !isDisabled && isProdOrDev && isCloud;+const shouldEnable = environment.isSentryEnabled();// Check for monitoring consent (includes session replay)const hasMonitoringConsent = consent.hasConsentFor("monitoring");diff --git a/autogpt_platform/frontend/next.config.mjs b/autogpt_platform/frontend/next.config.mjsindex 292841a7c0..18ed83c5d4 100644--- a/autogpt_platform/frontend/next.config.mjs+++ b/autogpt_platform/frontend/next.config.mjs@@ -6,6 +6,11 @@ const enableSourceMaps = process.env.NEXT_PUBLIC_SOURCEMAPS !== "false";/** @type {import('next').NextConfig} */const nextConfig = {+ // VERCEL_ENV is server-only. Mirror it into the browser bundle so Sentry can+ // tag preview deployments as previews rather than as production.+ env: {+ NEXT_PUBLIC_VERCEL_ENV: process.env.VERCEL_ENV ?? "",+ },// Suppress the "X-Powered-By: Next.js" header (framework fingerprinting).poweredByHeader: false,productionBrowserSourceMaps: enableSourceMaps,@@ -156,11 +161,6 @@ export default skipSentryPluginorg: "significant-gravitas",project: "builder",- // Expose Vercel env to the client- env: {- NEXT_PUBLIC_VERCEL_ENV: process.env.VERCEL_ENV,- },-// Only print logs for uploading source maps in CIsilent: !process.env.CI,diff --git a/autogpt_platform/frontend/sentry.edge.config.ts b/autogpt_platform/frontend/sentry.edge.config.tsindex dbf642f521..b2f762e745 100644--- a/autogpt_platform/frontend/sentry.edge.config.ts+++ b/autogpt_platform/frontend/sentry.edge.config.ts@@ -6,11 +6,7 @@import { environment } from "@/services/environment";import * as Sentry from "@sentry/nextjs";-const isProdOrDev = environment.isProd() || environment.isDev();-const isCloud = environment.isCloud();-const isDisabled = process.env.DISABLE_SENTRY === "true";--const shouldEnable = !isDisabled && isProdOrDev && isCloud;+const shouldEnable = environment.isSentryEnabled();Sentry.init({dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",diff --git a/autogpt_platform/frontend/sentry.server.config.ts b/autogpt_platform/frontend/sentry.server.config.tsindex 97c159737a..269e2c9098 100644--- a/autogpt_platform/frontend/sentry.server.config.ts+++ b/autogpt_platform/frontend/sentry.server.config.ts@@ -6,11 +6,7 @@ import { environment } from "@/services/environment";import * as Sentry from "@sentry/nextjs";// import { NodeProfilingIntegration } from "@sentry/profiling-node";-const isProdOrDev = environment.isProd() || environment.isDev();-const isCloud = environment.isCloud();-const isDisabled = process.env.DISABLE_SENTRY === "true";--const shouldEnable = !isDisabled && isProdOrDev && isCloud;+const shouldEnable = environment.isSentryEnabled();Sentry.init({dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",diff --git a/autogpt_platform/frontend/src/services/environment/__tests__/index.test.ts b/autogpt_platform/frontend/src/services/environment/__tests__/index.test.tsindex 412ecadbe7..b1114f5db6 100644--- a/autogpt_platform/frontend/src/services/environment/__tests__/index.test.ts+++ b/autogpt_platform/frontend/src/services/environment/__tests__/index.test.ts@@ -70,3 +70,72 @@ describe("AutoGPT server URL resolution", () => {);});});++describe("Sentry environment tagging", () => {+ function stubDeployment(appEnv: string, vercelEnv: string) {+ vi.stubEnv("NEXT_PUBLIC_APP_ENV", appEnv);+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");+ vi.stubEnv("NEXT_PUBLIC_VERCEL_ENV", vercelEnv);+ }++ it("tags a Vercel preview as preview, not as the app env it inherits", () => {+ stubDeployment("prod", "preview");++ expect(environment.getEnvironmentStr()).toBe("app:preview-behave:cloud");+ });++ it("tags the production deployment as prod", () => {+ stubDeployment("prod", "production");++ expect(environment.getEnvironmentStr()).toBe("app:prod-behave:cloud");+ });++ it("keeps the dev deployment distinct from production", () => {+ stubDeployment("dev", "production");++ expect(environment.getEnvironmentStr()).toBe("app:dev-behave:cloud");+ });++ it("tags a self-hosted instance by its own env", () => {+ vi.stubEnv("NEXT_PUBLIC_APP_ENV", "local");+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");+ vi.stubEnv("NEXT_PUBLIC_VERCEL_ENV", "");++ expect(environment.getEnvironmentStr()).toBe("app:local-behave:local");+ });++ it("detects a preview from the server-only VERCEL_ENV as well", () => {+ vi.stubEnv("NEXT_PUBLIC_VERCEL_ENV", "");+ vi.stubEnv("VERCEL_ENV", "preview");++ expect(environment.isVercelPreview()).toBe(true);+ });+});++describe("Sentry enablement", () => {+ it("stays off under the test runner, where no cloud deployment env is set", () => {+ expect(environment.isSentryEnabled()).toBe(false);+ });++ it("is on for a cloud deployment", () => {+ vi.stubEnv("NEXT_PUBLIC_APP_ENV", "prod");+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");++ expect(environment.isSentryEnabled()).toBe(true);+ });++ it("is off for a self-hosted instance", () => {+ vi.stubEnv("NEXT_PUBLIC_APP_ENV", "prod");+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");++ expect(environment.isSentryEnabled()).toBe(false);+ });++ it("honours the DISABLE_SENTRY kill switch on a cloud deployment", () => {+ vi.stubEnv("NEXT_PUBLIC_APP_ENV", "prod");+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");+ vi.stubEnv("DISABLE_SENTRY", "true");++ expect(environment.isSentryEnabled()).toBe(false);+ });+});diff --git a/autogpt_platform/frontend/src/services/environment/index.ts b/autogpt_platform/frontend/src/services/environment/index.tsindex f564bbde9e..5007e49932 100644--- a/autogpt_platform/frontend/src/services/environment/index.ts+++ b/autogpt_platform/frontend/src/services/environment/index.ts@@ -59,7 +59,10 @@ function resolveBrowserURL(url: string) {}function getEnvironmentStr() {- return `app:${getAppEnv().toLowerCase()}-behave:${getBehaveAs().toLowerCase()}`;+ // Vercel injects one NEXT_PUBLIC_APP_ENV into preview and production builds+ // alike, so without this previews report as the production environment.+ const appEnv = isVercelPreview() ? "preview" : getAppEnv().toLowerCase();+ return `app:${appEnv}-behave:${getBehaveAs().toLowerCase()}`;}function getPreviewStealingDev() {@@ -130,7 +133,15 @@ function isClientSide() {}function isVercelPreview() {- return process.env.VERCEL_ENV === "preview";+ // VERCEL_ENV is server-only; next.config.mjs mirrors it into the+ // NEXT_PUBLIC_ copy so the browser bundle can read it too.+ return (+ (process.env.NEXT_PUBLIC_VERCEL_ENV || process.env.VERCEL_ENV) === "preview"+ );+}++function isSentryEnabled() {+ return process.env.DISABLE_SENTRY !== "true" && (isProd() || isDev());}function areFeatureFlagsEnabled() {@@ -171,6 +182,7 @@ export const environment = {isCloud,isLocal,isVercelPreview,+ isSentryEnabled,isPostHogEnabled,areFeatureFlagsEnabled,};