🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): Hide AI telemetry when tracing when LANGFUSE_AI_FEATURES_PROJECT_ID is unset (#16771)
Lysander Kiesel927605d77787
diff --git a/web/src/__tests__/server/organization-ai-features.servertest.ts b/web/src/__tests__/server/organization-ai-features.servertest.tsindex a6d4eb39f7..e6c1437a0e 100644--- a/web/src/__tests__/server/organization-ai-features.servertest.ts+++ b/web/src/__tests__/server/organization-ai-features.servertest.ts@@ -12,6 +12,7 @@ describe("organization AI feature settings", () => {const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;const originalSharedInAppAgentEnabled =sharedEnv.LANGFUSE_IN_APP_AGENT_ENABLED;+ const originalAiFeaturesProjectId = sharedEnv.LANGFUSE_AI_FEATURES_PROJECT_ID;beforeEach(() => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;@@ -21,6 +22,9 @@ describe("organization AI feature settings", () => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;(sharedEnv as any).LANGFUSE_IN_APP_AGENT_ENABLED =originalSharedInAppAgentEnabled;+ (+ sharedEnv as { LANGFUSE_AI_FEATURES_PROJECT_ID?: string }+ ).LANGFUSE_AI_FEATURES_PROJECT_ID = originalAiFeaturesProjectId;});it("allows a self-hosted organization administrator to opt in to AI features", async () => {@@ -88,6 +92,47 @@ describe("organization AI feature settings", () => {message: "AI telemetry controls are only available on Langfuse Cloud.",});});++ it("rejects AI telemetry updates when the AI-features project is not configured", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";+ (+ sharedEnv as { LANGFUSE_AI_FEATURES_PROJECT_ID?: string }+ ).LANGFUSE_AI_FEATURES_PROJECT_ID = undefined;++ const { caller, orgId } = await createCaller();++ await expect(+ caller.organizations.update({+ orgId,+ aiTelemetryEnabled: false,+ }),+ ).rejects.toMatchObject({+ code: "PRECONDITION_FAILED",+ message:+ "AI telemetry controls are only available when the AI-features project is configured.",+ });+ });++ it("allows Cloud organizations to update AI telemetry when the AI-features project is configured", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";+ (+ sharedEnv as { LANGFUSE_AI_FEATURES_PROJECT_ID?: string }+ ).LANGFUSE_AI_FEATURES_PROJECT_ID = "test-ai-features-project";++ const { caller, orgId } = await createCaller();++ await caller.organizations.update({+ orgId,+ aiTelemetryEnabled: false,+ });++ await expect(+ prisma.organization.findUniqueOrThrow({+ where: { id: orgId },+ select: { aiTelemetryEnabled: true },+ }),+ ).resolves.toEqual({ aiTelemetryEnabled: false });+ });});async function createCaller() {diff --git a/web/src/features/organizations/components/AIFeatureSwitch.clienttest.tsx b/web/src/features/organizations/components/AIFeatureSwitch.clienttest.tsxnew file mode 100644index 0000000000..739361bb84--- /dev/null+++ b/web/src/features/organizations/components/AIFeatureSwitch.clienttest.tsx@@ -0,0 +1,115 @@+import { render, screen } from "@testing-library/react";++import AIFeatureSwitch from "./AIFeatureSwitch";++const mocks = vi.hoisted(() => ({+ isLangfuseCloud: true,+ aiFeaturesTracingConfigured: true,+ organization: {+ id: "org-1",+ aiFeaturesEnabled: true,+ aiTelemetryEnabled: true,+ } as {+ id: string;+ aiFeaturesEnabled: boolean;+ aiTelemetryEnabled: boolean;+ } | null,+ hasAccess: true,+}));++vi.mock("next-auth/react", () => ({+ useSession: () => ({+ data: {+ environment: {+ aiFeaturesTracingConfigured: mocks.aiFeaturesTracingConfigured,+ },+ },+ update: vi.fn(),+ }),+}));++vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => vi.fn(),+}));++vi.mock("@/src/features/rbac/utils/checkOrganizationAccess", () => ({+ useHasOrganizationAccess: () => mocks.hasAccess,+}));++vi.mock("@/src/features/organizations/hooks", () => ({+ useLangfuseCloudRegion: () => ({+ isLangfuseCloud: mocks.isLangfuseCloud,+ region: mocks.isLangfuseCloud ? "US" : undefined,+ }),+ useQueryOrganization: () => mocks.organization,+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ useUtils: () => ({+ organizations: { byId: { invalidate: vi.fn() } },+ }),+ organizations: {+ update: {+ useMutation: () => ({+ mutate: vi.fn(),+ isPending: false,+ }),+ },+ },+ },+}));++vi.mock("@/src/components/layouts/header", () => ({+ default: ({ title }: { title: string }) => <h2>{title}</h2>,+}));++describe("AIFeatureSwitch", () => {+ beforeEach(() => {+ mocks.isLangfuseCloud = true;+ mocks.aiFeaturesTracingConfigured = true;+ mocks.organization = {+ id: "org-1",+ aiFeaturesEnabled: true,+ aiTelemetryEnabled: true,+ };+ mocks.hasAccess = true;+ });++ it("hides product-improvement telemetry when the AI-features project is not configured", () => {+ mocks.aiFeaturesTracingConfigured = false;++ render(<AIFeatureSwitch />);++ expect(+ screen.getByText("Enable AI powered features for your organization"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("AI Data Use for Product/Service Improvement"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(/Traces are sent to Langfuse Cloud/),+ ).not.toBeInTheDocument();+ });++ it("shows product-improvement telemetry on Cloud when AI features and tracing are on", () => {+ render(<AIFeatureSwitch />);++ expect(+ screen.getByText("AI Data Use for Product/Service Improvement"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(/Traces are sent to Langfuse Cloud/),+ ).not.toBeInTheDocument();+ });++ it("hides product-improvement telemetry on self-hosted even when tracing is configured", () => {+ mocks.isLangfuseCloud = false;++ render(<AIFeatureSwitch />);++ expect(+ screen.queryByText("AI Data Use for Product/Service Improvement"),+ ).not.toBeInTheDocument();+ });+});diff --git a/web/src/features/organizations/components/AIFeatureSwitch.tsx b/web/src/features/organizations/components/AIFeatureSwitch.tsxindex 72d1efd02d..48c0166418 100644--- a/web/src/features/organizations/components/AIFeatureSwitch.tsx+++ b/web/src/features/organizations/components/AIFeatureSwitch.tsx@@ -22,9 +22,11 @@ import { LockIcon, ExternalLink } from "lucide-react";import { useSession } from "next-auth/react";export default function AIFeatureSwitch() {- const { update: updateSession } = useSession();+ const { data: session, update: updateSession } = useSession();const utils = api.useUtils();const { isLangfuseCloud } = useLangfuseCloudRegion();+ const aiFeaturesTracingConfigured =+ session?.environment.aiFeaturesTracingConfigured === true;const capture = usePostHogClientCapture();const organization = useQueryOrganization();const aiFeaturesEnabled = organization?.aiFeaturesEnabled;@@ -127,9 +129,9 @@ export default function AIFeatureSwitch() {<p className="text-sm">This setting applies to all users and projects. Any data{" "}<i>can</i> be sent to AWS Bedrock within the Langfuse data- region. Traces are sent to Langfuse Cloud in your data region.- Your data will not be used for training models. Applicable- HIPAA, SOC2, GDPR, and ISO 27001 compliance remains intact.{" "}+ region. Your data will not be used for training models.+ Applicable HIPAA, SOC2, GDPR, and ISO 27001 compliance remains+ intact.{" "}<ahref="https://langfuse.com/security/ai-features"target="_blank"@@ -161,31 +163,33 @@ export default function AIFeatureSwitch() {)}</div></div>- {isLangfuseCloud && isAIFeatureSwitchEnabled && (- <div className="mt-4 flex flex-row items-center justify-between border-t pt-4">- <div className="flex flex-col gap-1">- <h4 className="font-bold">- AI Data Use for Product/Service Improvement- </h4>- <p className="text-sm">- Share data about your use of AI with Langfuse for product and- service improvement.- </p>+ {isLangfuseCloud &&+ isAIFeatureSwitchEnabled &&+ aiFeaturesTracingConfigured && (+ <div className="mt-4 flex flex-row items-center justify-between border-t pt-4">+ <div className="flex flex-col gap-1">+ <h4 className="font-bold">+ AI Data Use for Product/Service Improvement+ </h4>+ <p className="text-sm">+ Share data about your use of AI with Langfuse for product and+ service improvement.+ </p>+ </div>+ <div className="relative">+ <Switch+ checked={isAITelemetrySwitchEnabled}+ onCheckedChange={handleTelemetrySwitchChange}+ disabled={!hasAccess || updateAITelemetry.isPending}+ />+ {!hasAccess && (+ <span title="No access">+ <LockIcon className="text-muted absolute top-1/2 right-3 h-4 w-4 -translate-y-1/2 transform" />+ </span>+ )}+ </div></div>- <div className="relative">- <Switch- checked={isAITelemetrySwitchEnabled}- onCheckedChange={handleTelemetrySwitchChange}- disabled={!hasAccess || updateAITelemetry.isPending}- />- {!hasAccess && (- <span title="No access">- <LockIcon className="text-muted absolute top-1/2 right-3 h-4 w-4 -translate-y-1/2 transform" />- </span>- )}- </div>- </div>- )}+ )}</Card><Dialogdiff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsindex adf9e7e1d2..dc6614cad3 100644--- a/web/src/features/organizations/server/organizationRouter.ts+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -14,6 +14,7 @@ import { TRPCError } from "@trpc/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import {getLastTraceTimestampsByProjects,+ isLangfuseAITracingConfigured,redis,} from "@langfuse/shared/src/server";import { resolveBillingService } from "@/src/ee/features/billing/server/resolveBillingService";@@ -315,15 +316,22 @@ export const organizationsRouter = createTRPCRouter({scope: "organization:update",});- if (- input.aiTelemetryEnabled !== undefined &&- !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION- ) {- throw new TRPCError({- code: "PRECONDITION_FAILED",- message:- "AI telemetry controls are only available on Langfuse Cloud.",- });+ if (input.aiTelemetryEnabled !== undefined) {+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message:+ "AI telemetry controls are only available on Langfuse Cloud.",+ });+ }++ if (!isLangfuseAITracingConfigured()) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message:+ "AI telemetry controls are only available when the AI-features project is configured.",+ });+ }}const beforeOrganization = await ctx.prisma.organization.findFirst({diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 354c2caa55..7693551e03 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -67,6 +67,7 @@ import {instrumentAsync,logger,resolveProjectRole,+ isLangfuseAITracingConfigured,} from "@langfuse/shared/src/server";import {getOrganizationPlanServerSide,@@ -898,6 +899,7 @@ export async function getAuthOptions(signupAttribution?: {enableExperimentalFeatures:env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",inAppAgentEnabled: isInAppAgentInstanceEnabled(),+ aiFeaturesTracingConfigured: isLangfuseAITracingConfigured(),// Enables features that are only available under an enterprise license when self-hosting Langfuse// If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)selfHostedInstancePlan: getSelfHostedInstancePlanServerSide(),diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 507de7eed5..78c950a78a 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -66,6 +66,10 @@ declare module "next-auth" {// Instance-wide in-app agent switch. Populated by the session callback.// Optional so existing session mocks need not set it.inAppAgentEnabled?: boolean;+ // Whether LANGFUSE_AI_FEATURES_PROJECT_ID is set, so Cloud orgs can+ // opt out of product traces. Optional so existing session mocks need+ // not set it.+ aiFeaturesTracingConfigured?: boolean;// Enables features that are only available under an enterprise/commercial license when self-hosting LangfuseselfHostedInstancePlan: Plan | null;// V4 migration write mode. Mirrors LANGFUSE_MIGRATION_V4_WRITE_MODE so the