🪢 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
feat(topics): one gate for Topics visibility (#19091)
Lysander Kiesel2744ddc4b1d6
diff --git a/packages/shared/src/server/topics/config.test.ts b/packages/shared/src/server/topics/config.test.tsindex f2345fe8af..e97262d50e 100644--- a/packages/shared/src/server/topics/config.test.ts+++ b/packages/shared/src/server/topics/config.test.ts@@ -5,6 +5,7 @@ beforeEach(() => {vi.stubEnv("LANGFUSE_TOPICS_ENABLED", undefined);vi.stubEnv("LANGFUSE_TOPICS_ENABLED_PROJECT_IDS", undefined);vi.stubEnv("LANGFUSE_TOPICS_TRACING_ENABLED_PROJECT_IDS", undefined);+ vi.stubEnv("NEXT_PUBLIC_LANGFUSE_CLOUD_REGION", "EU");});afterEach(() => {@@ -62,6 +63,16 @@ describe("Topics project allowlist", () => {},);+ it("stays disabled outside Langfuse Cloud even when switched on and allowlisted", async () => {+ vi.stubEnv("NEXT_PUBLIC_LANGFUSE_CLOUD_REGION", undefined);+ vi.stubEnv("LANGFUSE_TOPICS_ENABLED", "true");+ vi.stubEnv("LANGFUSE_TOPICS_ENABLED_PROJECT_IDS", "project-a");+ const { isTopicsEnabled, isTopicsProjectEnabled } =+ await import("./config.js");+ expect(isTopicsEnabled()).toBe(false);+ expect(isTopicsProjectEnabled("project-a")).toBe(false);+ });+it.each([undefined, ""])("allows no projects when Topics is enabled and the allowlist is absent or empty: %s",async (value) => {diff --git a/packages/shared/src/server/topics/config.ts b/packages/shared/src/server/topics/config.tsindex 9fc1b0b0fb..323c6a6ce6 100644--- a/packages/shared/src/server/topics/config.ts+++ b/packages/shared/src/server/topics/config.ts@@ -1,7 +1,11 @@import { env } from "../../env";+/** Deployment switch: Langfuse Cloud only for now, so self-hosted instances never enable Topics. */export function isTopicsEnabled(): boolean {- return env.LANGFUSE_TOPICS_ENABLED === "true";+ return (+ env.LANGFUSE_TOPICS_ENABLED === "true" &&+ Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)+ );}export function isTopicsProjectEnabled(projectId: string): boolean {diff --git a/web/src/__tests__/server/unit/topics.servertest.ts b/web/src/__tests__/server/unit/topics.servertest.tsindex f7651ed717..b34d72a607 100644--- a/web/src/__tests__/server/unit/topics.servertest.ts+++ b/web/src/__tests__/server/unit/topics.servertest.ts@@ -1,4 +1,5 @@import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";+import { canViewTopics } from "@/src/features/topics/topicsAccess";import type { Session } from "next-auth";import type * as topicsServer from "@langfuse/shared/topics/server";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -32,9 +33,8 @@ const mocks = vi.hoisted(() => ({getTopicRun: vi.fn(),getTopicRuns: vi.fn(),readTopicMapAssignments: vi.fn(),- isTopicsEnabled: vi.fn(),- isTopicsProjectEnabled: vi.fn(),getTopicsModels: vi.fn(),+ isTopicsProjectEnabled: vi.fn(),checkTopicsModelSettings: vi.fn(),saveTopicsSetup: vi.fn(),setTopicsAutomaticProcessing: vi.fn(),@@ -185,9 +185,8 @@ const summary = {beforeEach(() => {vi.resetAllMocks();- mocks.queryClickhouse.mockResolvedValue([]);- mocks.isTopicsEnabled.mockReturnValue(true);mocks.isTopicsProjectEnabled.mockReturnValue(true);+ mocks.queryClickhouse.mockResolvedValue([]);mocks.getTopicsModels.mockResolvedValue({summary: { model: "us.openai.gpt-5.6-luna" },embedding: { model: "eu.cohere.embed-v4:0", dimensions: 1024 },@@ -227,13 +226,53 @@ describe("Topics feature access", () => {});describe("Topics project allowlist", () => {- it("rejects triggers before reading or creating execution state", async () => {+ // Every Topics API is behind the visibility gate: outside the allowlist it+ // answers NOT_FOUND before reading or writing anything.+ const outside = () => {mocks.isTopicsProjectEnabled.mockReturnValue(false);- await expect(caller().trigger(input)).rejects.toMatchObject({- code: "BAD_REQUEST",- message: "Topics processing is not enabled for this project.",+ return caller();+ };+ const reads = [+ [+ "current results",+ () => outside().currentResults({ projectId, timeRange }),+ ],+ [+ "topic map",+ () => outside().map({ projectId, runId: "run-a", timeRange }),+ ],+ [+ "summary counts",+ () =>+ outside().summaryCounts({+ projectId,+ facets: selectedFacets,+ timeRange,+ }),+ ],+ ["facets", () => outside().facets({ projectId })],+ ["rules", () => outside().rules({ projectId })],+ ["runs", () => outside().executions({ projectId })],+ ["model settings", () => outside().modelSettings({ projectId })],+ ] as const;++ it.each(reads)("hides %s", async (_name, call) => {+ await expect(call()).rejects.toMatchObject({ code: "NOT_FOUND" });+ expect(mocks.queryClickhouse).not.toHaveBeenCalled();+ expect(mocks.getLatestFacetSummaries).not.toHaveBeenCalled();+ expect(mocks.readLatestTopicAssignments).not.toHaveBeenCalled();+ expect(mocks.readTopicMapAssignments).not.toHaveBeenCalled();+ expect(mocks.getTopicSummaryCounts).not.toHaveBeenCalled();+ expect(mocks.listTopicFacets).not.toHaveBeenCalled();+ expect(mocks.listTopicRules).not.toHaveBeenCalled();+ expect(mocks.listTopicExecutions).not.toHaveBeenCalled();+ expect(mocks.getTopicsModels).not.toHaveBeenCalled();+ });++ it("rejects triggers before reading or creating execution state", async () => {+ await expect(outside().trigger(input)).rejects.toMatchObject({+ code: "NOT_FOUND",});- expect(mocks.isTopicsProjectEnabled).toHaveBeenCalledWith(projectId);expect(mocks.readTopicExecutionForRequest).not.toHaveBeenCalled();expect(mocks.getTopicFacetVersion).not.toHaveBeenCalled();expect(mocks.queryClickhouse).not.toHaveBeenCalled();@@ -242,25 +281,61 @@ describe("Topics project allowlist", () => {});it("rejects retries before reading or changing execution state", async () => {- mocks.isTopicsProjectEnabled.mockReturnValue(false);await expect(- caller().retry({ projectId, executionId: "execution-a" }),- ).rejects.toMatchObject({- code: "BAD_REQUEST",- message: "Topics processing is not enabled for this project.",- });- expect(mocks.isTopicsProjectEnabled).toHaveBeenCalledWith(projectId);+ outside().retry({ projectId, executionId: "execution-a" }),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });expect(mocks.readTopicExecutionSummary).not.toHaveBeenCalled();expect(mocks.getTopicExecutionQueueState).not.toHaveBeenCalled();expect(mocks.enqueueTopicExecution).not.toHaveBeenCalled();});- it("keeps reads and facet configuration available when processing is disabled", async () => {- mocks.isTopicsProjectEnabled.mockReturnValue(false);- mocks.listTopicFacets.mockResolvedValue([]);+ it("rejects turning automatic processing on", async () => {+ await expect(+ outside().setAutomaticProcessing({ projectId, enabled: true }),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });+ expect(mocks.setTopicsAutomaticProcessing).not.toHaveBeenCalled();+ });+});- await expect(caller().facets({ projectId })).resolves.toEqual([]);- expect(mocks.listTopicFacets).toHaveBeenCalledWith(projectId);+describe("Topics visibility gate", () => {+ const session = ({+ admin = false,+ langfuseTopics = true,+ role = "VIEWER",+ }: {+ admin?: boolean;+ langfuseTopics?: boolean;+ role?: string | null;+ }) =>+ ({+ expires: "1",+ user: {+ id: "user-a",+ admin,+ featureFlags: testFeatureFlags({ langfuseTopics }),+ organizations: role+ ? [{ id: "org-a", role, projects: [{ id: projectId, role }] }]+ : [],+ },+ }) as unknown as Session;++ // Page, sidebar and API all call this one gate.+ it.each([+ ["a member on an allowlisted project", {}, true, true],+ ["a project outside the allowlist", {}, false, false],+ ["the feature preview turned off", { langfuseTopics: false }, true, false],+ ["a role without topics:read", { role: "NONE" }, true, false],+ ["an admin outside the project", { admin: true, role: null }, true, true],+ [+ "an admin outside a non-allowlisted project",+ { admin: true, role: null },+ false,+ false,+ ],+ ] as const)("%s", (_case, user, topicsEnabled, expected) => {+ expect(canViewTopics(session(user), { id: projectId, topicsEnabled })).toBe(+ expected,+ );});});@@ -1428,7 +1503,6 @@ describe("Topics automatic processing", () => {};it("turns processing on with sampling and audit-logs the sampling change", async () => {- mocks.isTopicsProjectEnabled.mockReturnValue(true);mocks.setTopicsAutomaticProcessing.mockResolvedValue({ruleBefore: { ...rule, sampling: 1 },ruleAfter: { ...rule, sampling: 0.25 },@@ -1457,17 +1531,7 @@ describe("Topics automatic processing", () => {);});- it("refuses to turn on a project that is not on the Topics allowlist", async () => {- mocks.isTopicsProjectEnabled.mockReturnValue(false);-- await expect(- caller().setAutomaticProcessing({ projectId, enabled: true }),- ).rejects.toMatchObject({ code: "BAD_REQUEST" });- expect(mocks.setTopicsAutomaticProcessing).not.toHaveBeenCalled();- });-- it("turns processing off for a project that is not on the allowlist", async () => {- mocks.isTopicsProjectEnabled.mockReturnValue(false);+ it("turns processing off without logging an unchanged sampling", async () => {mocks.setTopicsAutomaticProcessing.mockResolvedValue({ruleBefore: { ...rule, sampling: 1 },ruleAfter: { ...rule, sampling: 1 },diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.clienttest.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.clienttest.tsindex 5b638a8823..7eef008a29 100644--- a/web/src/components/layouts/app-layout/utils/navigationFilters.clienttest.ts+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.clienttest.ts@@ -71,3 +71,43 @@ it.each([expect(applyNavigationFilters([route], context, undefined)).toEqual([]);},);++it.each([+ { topicsEnabled: true, visible: true },+ { topicsEnabled: false, visible: false },+])(+ "shows the Topics entry only when the gate passes for the current project (allowlisted: $topicsEnabled)",+ ({ topicsEnabled, visible }) => {+ const route = ROUTES.find((route) => route.title === "Topics")!;+ const project = { id: "project-1", role: "VIEWER", topicsEnabled };+ const organization = {+ id: "org-1",+ role: "VIEWER",+ projects: [project],+ } as unknown as NonNullable<Session["user"]>["organizations"][number];+ const context: NavigationFilterContext = {+ routerProjectId: "project-1",+ routerOrganizationId: undefined,+ session: {+ user: {+ admin: false,+ featureFlags: testFeatureFlags({ langfuseTopics: true }),+ organizations: [organization],+ },+ } as Session,+ enableExperimentalFeatures: false,+ internalFeaturesEnabled: false,+ cloudAdmin: false,+ entitlements: [],+ uiCustomization: null,+ isLangfuseCloud: true,+ hasActiveCloudIncident: false,+ forceV3Experience: false,+ currentPath: "/project/project-1",+ };++ expect(applyNavigationFilters([route], context, organization)).toEqual(+ visible ? [route] : [],+ );+ },+);diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.tsindex 05326b2607..091c83ee7e 100644--- a/web/src/components/layouts/app-layout/utils/navigationFilters.ts+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.ts@@ -9,6 +9,7 @@ import { hasProjectAccess, hasOrganizationAccess } from "@/src/features/rbac";import type { Session } from "next-auth";import { isAdminOnlyFeaturePreviewFlag } from "@/src/features/feature-flags/available-flags";import { getContextualFeatureFlags } from "@/src/features/feature-flags/utils";+import { canViewTopics } from "@/src/features/topics/topicsAccess";/** Organization type from user session (can be null when not in project/org context) */type Organization =@@ -200,6 +201,12 @@ const filters = {return route.show({organization: organization ?? undefined,projectId: ctx.routerProjectId,+ canViewTopics: canViewTopics(+ ctx.session,+ organization?.projects.find(+ (project) => project.id === ctx.routerProjectId,+ ),+ ),isLangfuseCloud: ctx.isLangfuseCloud,hasActiveCloudIncident: ctx.hasActiveCloudIncident,canToggleV4: ctx.session?.user?.canToggleV4 === true,diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsxindex 944d593784..b62f91b6a9 100644--- a/web/src/components/layouts/routes.tsx+++ b/web/src/components/layouts/routes.tsx@@ -72,6 +72,7 @@ export type Route = {| NonNullable<Session["user"]>["organizations"][number]| undefined;projectId: string | undefined;+ canViewTopics: boolean;isLangfuseCloud: boolean;hasActiveCloudIncident: boolean;canToggleV4: boolean;@@ -153,8 +154,7 @@ export const ROUTES: Route[] = [title: "Topics",href: "/project/[projectId]/topics",icon: Grid2X2,- featureFlag: "langfuseTopics",- projectRbacScopes: ["topics:read"],+ show: ({ canViewTopics }) => canViewTopics,group: RouteGroup.Observability,section: RouteSection.Main,},diff --git a/web/src/features/organizations/server/adminOrgContext.ts b/web/src/features/organizations/server/adminOrgContext.tsindex ed2056e44d..6ca83c3761 100644--- a/web/src/features/organizations/server/adminOrgContext.ts+++ b/web/src/features/organizations/server/adminOrgContext.ts@@ -1,4 +1,5 @@import { CloudConfigSchema } from "@langfuse/shared";+import { isTopicsProjectEnabled } from "@langfuse/shared/topics/server";import { Role, type PrismaClient } from "@langfuse/shared/src/db";import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server";import { type Session } from "next-auth";@@ -76,6 +77,7 @@ export async function buildAdminOrgContext(ctx: {role: Role.OWNER,retentionDays: project.retentionDays,hasTraces: project.hasTraces,+ topicsEnabled: isTopicsProjectEnabled(project.id),deletedAt: project.deletedAt,metadata: (project.metadata as Record<string, unknown>) ?? {},createdAt: project.createdAt.toISOString(),diff --git a/web/src/features/topics/AutomaticProcessingControl.tsx b/web/src/features/topics/AutomaticProcessingControl.tsxindex 8a38d6f7f8..ef3629d034 100644--- a/web/src/features/topics/AutomaticProcessingControl.tsx+++ b/web/src/features/topics/AutomaticProcessingControl.tsx@@ -65,15 +65,12 @@ function statusLabel(state: AutomaticProcessingState) {function disabledReason(state: AutomaticProcessingState, canWrite: boolean) {if (state.status === "unconfigured") return "Configure Topics first.";- if (state.status === "unavailable")- return "Topics processing is not enabled for this project.";if (!canWrite) return "You need permission to edit Topics.";return null;}export type AutomaticProcessingState =| { status: "unconfigured" }- | { status: "unavailable" }| { status: "off" }| { status: "on" }| { status: "paused"; shortLabel: string };diff --git a/web/src/features/topics/ManualTopicsFormContent.tsx b/web/src/features/topics/ManualTopicsFormContent.tsxindex fe6d468d10..2edbf78f54 100644--- a/web/src/features/topics/ManualTopicsFormContent.tsx+++ b/web/src/features/topics/ManualTopicsFormContent.tsx@@ -115,8 +115,6 @@ export function ManualTopicsFormContent({return "Choose the Topics models in Configure Topics first.";if (settings.stored.blockedAt)return `Topics is paused. ${settings.stored.blockMessage ?? "Fix the model connection in Configure Topics."}`;- if (!settings.stored.processingAvailable)- return "Topics processing is not enabled for this project.";if (running) return "A Topics run is in progress. Wait for it to finish.";if (operation === "update" && regenerate.disabledReason)return regenerate.disabledReason;diff --git a/web/src/features/topics/TopicModelSettings.tsx b/web/src/features/topics/TopicModelSettings.tsxindex cd50d6035e..fbca05f1fa 100644--- a/web/src/features/topics/TopicModelSettings.tsx+++ b/web/src/features/topics/TopicModelSettings.tsx@@ -16,7 +16,6 @@ export type ConfigureTopicsSettingsInput = {};export type TopicSetupNoticeState = {- unavailable: boolean;status:| { kind: "paused"; message: string }| { kind: "setup" }@@ -108,7 +107,6 @@ export function useTopicModelSettings({},},notice: {- unavailable: Boolean(settings.data && !settings.data.processingAvailable),status,} satisfies TopicSetupNoticeState,};diff --git a/web/src/features/topics/TopicSetupNotice.stories.tsx b/web/src/features/topics/TopicSetupNotice.stories.tsxindex 8006e73fab..161400393e 100644--- a/web/src/features/topics/TopicSetupNotice.stories.tsx+++ b/web/src/features/topics/TopicSetupNotice.stories.tsx@@ -6,7 +6,7 @@ const meta = preview.meta({ component: TopicSetupNotice });export const Setup = meta.story({args: {- notice: { unavailable: false, status: { kind: "setup" } },+ notice: { status: { kind: "setup" } },canWrite: true,canConfigure: true,onConfigure: fn(),@@ -22,7 +22,7 @@ export const ReadyToProcess = meta.story({onConfigure: fn(),onKeepOff: fn(),onTurnBackOn: fn(),- notice: { unavailable: false, status: null },+ notice: { status: null },showOnboarding: true,configured: true,canProcess: true,@@ -33,7 +33,7 @@ export const ReadyToProcess = meta.story({export const Processing = meta.story({args: {- notice: { unavailable: false, status: null },+ notice: { status: null },canWrite: true,canConfigure: true,onConfigure: fn(),diff --git a/web/src/features/topics/TopicSetupNotice.tsx b/web/src/features/topics/TopicSetupNotice.tsxindex 79f41e6d9d..22f1689156 100644--- a/web/src/features/topics/TopicSetupNotice.tsx+++ b/web/src/features/topics/TopicSetupNotice.tsx@@ -41,12 +41,9 @@ export function TopicSetupNotice({const processingChoiceDescription = automaticEnabled? "Automatic processing is on for new traces. You can also summarize existing traces in manual batches.": "Enable automatic processing for incoming traces, or summarize existing traces in manual batches of up to 1,000.";- const availableProcessingDescription = running+ const processingDescription = running? "Your traces are being processed. Summaries will appear here as they become available.": processingChoiceDescription;- const processingDescription = notice.unavailable- ? "Topics processing is not enabled for this project. You can configure Topics, but an administrator needs to enable processing before you can analyze traces."- : availableProcessingDescription;return (<>{status?.kind === "paused" ? (@@ -73,12 +70,6 @@ export function TopicSetupNotice({</Alert.Description></Alert>) : null}- {notice.unavailable && !showOnboarding ? (- <p role="status" className="text-muted-foreground text-sm">- Topics processing is not enabled for this project. Existing summaries- and topics remain available.- </p>- ) : null}{showOnboarding ? (<div className="mx-auto flex w-full max-w-xl flex-col items-center overflow-y-auto pt-12"><Sparkles aria-hidden="true" size="xl" color="muted" />diff --git a/web/src/features/topics/TopicsPage.clienttest.tsx b/web/src/features/topics/TopicsPage.clienttest.tsxindex b849b72f5b..001213720d 100644--- a/web/src/features/topics/TopicsPage.clienttest.tsx+++ b/web/src/features/topics/TopicsPage.clienttest.tsx@@ -13,6 +13,7 @@ import { rangeToString, type TimeRange } from "@/src/utils/date-range-utils";import { type TopicFacet } from "@langfuse/shared/topics";const state = vi.hoisted(() => ({+ canViewTopics: true,status: "failed",executionUpdatedAt: 110,updatedAt: "2026-09-23T12:00:00Z",@@ -110,8 +111,11 @@ vi.mock("@/src/components/table/peek/peek-trace-detail", () => ({vi.mock("@/src/features/rbac/utils/checkProjectAccess", () => ({useHasProjectAccess: () => state.canWrite,}));-vi.mock("@/src/features/feature-flags/hooks/useIsFeatureEnabled", () => ({- default: () => true,+vi.mock("@/src/components/error-page", () => ({+ ErrorPage: ({ message }: { message: string }) => <p>{message}</p>,+}));+vi.mock("@/src/features/topics/topicsAccess", () => ({+ useCanViewTopics: () => state.canViewTopics,}));vi.mock("./TopicTraceSelector", () => ({useTopicTraceSelector: () => ({@@ -318,6 +322,7 @@ beforeEach(() => {},);state.showGenerateCTA = false;+ state.canViewTopics = true;state.resultsDataAvailable = true;state.hasStoredSummaries = true;state.status = "failed";@@ -337,7 +342,6 @@ beforeEach(() => {embedding: { model: "embedding" },embeddingDimensions: 1024,clustering: { model: "clustering" },- processingAvailable: true,blockedAt: null,blockMessage: null,};@@ -362,6 +366,13 @@ afterEach(() => {vi.useRealTimers();});+it("shows Not found instead of the workspace when the Topics gate is closed", () => {+ state.canViewTopics = false;+ render(<TopicsPage />);+ expect(screen.getByText("This page is not available.")).toBeTruthy();+ expect(state.currentTopics).not.toHaveBeenCalled();+});+it.each([["30d", 30 * 24 * 60],["5m", 5],diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsxindex df6ac58436..2c8d0d93c2 100644--- a/web/src/features/topics/TopicsPage.tsx+++ b/web/src/features/topics/TopicsPage.tsx@@ -31,7 +31,7 @@ import { Badge } from "@/src/components/design-system/Badge/Badge";import { api, type RouterOutputs } from "@/src/utils/api";import { costFormatter } from "@/src/utils/numbers";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";+import { useCanViewTopics } from "@/src/features/topics/topicsAccess";import {type TopicFacet,type TopicExecutionStatus,@@ -104,7 +104,7 @@ export default function TopicsPage() {const router = useRouter();const projectId =typeof router.query.projectId === "string" ? router.query.projectId : "";- const topicsEnabled = useIsFeatureEnabled("langfuseTopics", { projectId });+ const topicsEnabled = useCanViewTopics(projectId);if (!topicsEnabled) {return (<ErrorPage title="Not found" message="This page is not available." />@@ -482,7 +482,7 @@ function TopicsWorkspaceContent({onTurnBackOn={turnAutomaticProcessingBackOn}showOnboarding={showOnboarding}configured={configured}- canProcess={canWrite && !modelSettings.notice.unavailable}+ canProcess={canWrite}automaticEnabled={automaticProcessing.state.status === "on"}running={running}onAutomaticProcessing={openAutomaticProcessingFromHeader}@@ -595,12 +595,7 @@ function TopicsWorkspaceContent({traceFilters={traceFilters}tracePanelRef={setTracePanel}onGenerateTopics={openTopicGeneration}- canGenerateTopics={- canWrite &&- !modelSettings.notice.unavailable &&- !running &&- configured- }+ canGenerateTopics={canWrite && !running && configured}/></TopicsFilters>)}diff --git a/web/src/features/topics/server/topicsRouter.ts b/web/src/features/topics/server/topicsRouter.tsindex c80adcee29..371e42c38d 100644--- a/web/src/features/topics/server/topicsRouter.ts+++ b/web/src/features/topics/server/topicsRouter.ts@@ -25,6 +25,7 @@ import {getTopicSummaryCounts,listTopicExecutions,listTopicFacets,+ isTopicsProjectEnabled,getTopicFacetVersion,getLatestFacetSummaries,createTopicFacet,@@ -34,8 +35,6 @@ import {saveTopicRule,getTopicRun,readTopicMapAssignments,- isTopicsEnabled,- isTopicsProjectEnabled,getTopicsModels,readTopicsModelSettings,checkTopicsModelSettings,@@ -52,7 +51,7 @@ import {import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { auditLog } from "@/src/features/audit-logs/auditLog";import { JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";-import { getContextualFeatureFlags } from "@/src/features/feature-flags/utils";+import { canViewTopics } from "@/src/features/topics/topicsAccess";import {previewTopicTraces,resolveTopicTraceSelection,@@ -74,18 +73,13 @@ const mapInput = resultInput.extend({ runId: topicIdSchema });const topicsProcedure = protectedProjectProcedureWithoutTracing.input(projectInput).use(({ ctx, input, next }) => {- if (- !isTopicsEnabled() ||- getContextualFeatureFlags(ctx.session.user, {- projectId: input.projectId,- })?.langfuseTopics !== true- )+ // The allowlist comes from env here, so admins outside the project are covered too.+ const project = {+ id: input.projectId,+ topicsEnabled: isTopicsProjectEnabled(input.projectId),+ };+ if (!canViewTopics(ctx.session, project))throw new LangfuseNotFoundError("Topics is not available.");- throwIfNoProjectAccess({- session: ctx.session,- projectId: input.projectId,- scope: "topics:read",- });return next();});const topicsWriteProcedure = topicsProcedure.use(({ ctx, input, next }) => {@@ -360,10 +354,9 @@ export const topicsRouter = createTRPCRouter({});return rule;}),- modelSettings: topicsProcedure.query(async ({ input }) => ({- ...(await readTopicsModelSettings(input.projectId)),- processingAvailable: isTopicsProjectEnabled(input.projectId),- })),+ modelSettings: topicsProcedure.query(({ input }) =>+ readTopicsModelSettings(input.projectId),+ ),tracingReadinessSettings: topicsProcedure.query(({ input }) =>getTracingReadinessSettings(input.projectId),),@@ -390,10 +383,6 @@ export const topicsRouter = createTRPCRouter({setAutomaticProcessing: topicsWriteProcedure.input(topicsAutomaticProcessingSchema.extend({ projectId: topicIdSchema })).mutation(async ({ input: { projectId, ...input }, ctx }) => {- if (input.enabled && !isTopicsProjectEnabled(projectId))- throw new InvalidRequestError(- "Topics processing is not enabled for this project.",- );const { ruleBefore, ruleAfter } = await auditedTopicConfigSave(ctx,projectId,@@ -469,10 +458,6 @@ export const topicsRouter = createTRPCRouter({trigger: topicsWriteProcedure.input(topicTriggerInputSchema).mutation(async ({ input, ctx }) => {- if (!isTopicsProjectEnabled(input.projectId))- throw new InvalidRequestError(- "Topics processing is not enabled for this project.",- );const { summary, embedding } = await requireTopicsModels(input.projectId);const models = {summaryModel: summary.model,@@ -554,10 +539,6 @@ export const topicsRouter = createTRPCRouter({retry: topicsWriteProcedure.input(executionInput).mutation(async ({ input }) => {- if (!isTopicsProjectEnabled(input.projectId))- throw new InvalidRequestError(- "Topics processing is not enabled for this project.",- );const execution = await executionWithRecovery(input.projectId,input.executionId,diff --git a/web/src/features/topics/topicsAccess.ts b/web/src/features/topics/topicsAccess.tsnew file mode 100644index 0000000000..e95d4ea14f--- /dev/null+++ b/web/src/features/topics/topicsAccess.ts@@ -0,0 +1,33 @@+import { type Session } from "next-auth";+import { useSession } from "next-auth/react";+import { getContextualFeatureFlags } from "@/src/features/feature-flags/utils";+import { useProject } from "@/src/features/projects/hooks";+import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";++type TopicsProject = { id: string; topicsEnabled?: boolean };++/** Visibility gate for every Topics surface: project gate, the user's feature preview and topics:read. */+export function canViewTopics(+ session: Session | null,+ project: TopicsProject | null | undefined,+) {+ return (+ !!project &&+ isTopicsEnabledForProject(project) &&+ getContextualFeatureFlags(session?.user, { projectId: project.id })+ ?.langfuseTopics === true &&+ hasProjectAccess({ session, projectId: project.id, scope: "topics:read" })+ );+}++/** Resolves the project like the rest of the app, including the admin fallback for non-member admins. */+export function useCanViewTopics(projectId: string) {+ const session = useSession().data;+ const { project } = useProject(projectId);+ return canViewTopics(session, project);+}++/** Project gate: Topics is enabled for the project (deployment allowlist, resolved on the server). */+function isTopicsEnabledForProject(project: TopicsProject | null | undefined) {+ return project?.topicsEnabled === true;+}diff --git a/web/src/features/topics/useAutomaticProcessing.tsx b/web/src/features/topics/useAutomaticProcessing.tsxindex 26ece6faad..10fa8a1004 100644--- a/web/src/features/topics/useAutomaticProcessing.tsx+++ b/web/src/features/topics/useAutomaticProcessing.tsx@@ -53,7 +53,5 @@ export function automaticProcessingState(: "Paused",};if (stored.enabled) return { status: "on" };- // Only turning on needs the allowlist, so a running setup can still be turned off.- if (!stored.processingAvailable) return { status: "unavailable" };return { status: "off" };}diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 9649eca276..108bc51af0 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -1,5 +1,6 @@/* eslint-disable no-nested-ternary */import { type GetServerSidePropsContext } from "next";+import { isTopicsProjectEnabled } from "@langfuse/shared/topics/server";import {getServerSession,type NextAuthOptions,@@ -987,6 +988,9 @@ export async function getAuthOptions(role: projectRole,retentionDays: project.retentionDays,hasTraces: project.hasTraces,+ topicsEnabled: isTopicsProjectEnabled(+ project.id,+ ),deletedAt: project.deletedAt,metadata:(project.metadata as Record<diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 42ed5434aa..a441f2fde3 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -50,6 +50,7 @@ declare module "next-auth" {deletedAt: PrismaProject["deletedAt"];retentionDays: PrismaProject["retentionDays"];hasTraces: PrismaProject["hasTraces"];+ topicsEnabled?: boolean; // deployment allowlist, resolved server-side; absent = offmetadata: Record<string, unknown>;role: Role; // include only projects where user has a rolecreatedAt: string; // iso datetime string — JWT does not support Date objects