🪢 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(cloud): update entitlements to account for limits, add self-hosted pro plan (#3913)
Marc Klingen039dee045b0b
diff --git a/packages/shared/src/features/entitlements/plans.ts b/packages/shared/src/features/entitlements/plans.tsindex 4edbfbfe54..60e11d7478 100644--- a/packages/shared/src/features/entitlements/plans.ts+++ b/packages/shared/src/features/entitlements/plans.ts@@ -3,15 +3,17 @@ export const planLabels = {"cloud:hobby": "Hobby","cloud:pro": "Pro","cloud:team": "Team",- "self-hosted:enterprise": "Enterprise",+ "self-hosted:pro": "Pro (self-hosted)",+ "self-hosted:enterprise": "Enterprise (self-hosted)",} as const;export type Plan = keyof typeof planLabels;export const plans = Object.keys(planLabels) as Plan[];-// This function is kept here to ensure consistency when updating plan names in the future.+// These functions are kept here to ensure consistency when updating plan names in the future.export const isCloudPlan = (plan: Plan) => plan.startsWith("cloud");+export const isSelfHostedPlan = (plan: Plan) => plan.startsWith("self-hosted");export const isPlan = (value: string): value is Plan =>plans.includes(value as Plan);diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 9ec69c3513..e68b0f035e 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -1082,3 +1082,29 @@ export const getObservationCountsByProjectInCreationInterval = async ({count: Number(row.count),}));};++export const getObservationCountOfProjectsSinceCreationDate = async ({+ projectIds,+ start,+}: {+ projectIds: string[];+ start: Date;+}) => {+ const query = `+ SELECT+ count(*) as count+ FROM observations+ WHERE project_id IN ({projectIds: Array(String)})+ AND created_at >= {start: DateTime64(3)}+ `;++ const rows = await queryClickhouse<{ count: string }>({+ query,+ params: {+ projectIds,+ start: convertDateToClickhouseDateTime(start),+ },+ });++ return Number(rows[0]?.count ?? 0);+};diff --git a/web/src/components/ActionButton.tsx b/web/src/components/ActionButton.tsxnew file mode 100644index 0000000000..17617ddf6c--- /dev/null+++ b/web/src/components/ActionButton.tsx@@ -0,0 +1,151 @@+import { Lock, AlertCircle, Sparkle } from "lucide-react";+import { Button, type ButtonProps } from "@/src/components/ui/button";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";+import { HoverCardPortal } from "@radix-ui/react-hover-card";+import Link from "next/link";++const BUTTON_STATE_MESSAGES = {+ limitReached: (current: number, max: number) =>+ `You have reached the limit (${current}/${max}) for this resource at your current plan. Upgrade your plan to increase the limit.`,+ noAccess:+ "You do not have access to this resource, please ask your admin to grant you access.",+ entitlement: "This feature is not available in your current plan.",+} as const;++interface ActionButtonProps extends ButtonProps {+ icon?: React.ReactNode;+ loading?: boolean;+ hasAccess?: boolean;+ hasEntitlement?: boolean;+ limitValue?: number;+ limit?: number | false;+ children: React.ReactNode;+ className?: string;+ href?: string;+}++export function ActionButton({+ loading = false,+ hasAccess = true,+ hasEntitlement = true,+ limitValue,+ limit = false,+ disabled = false,+ children,+ icon,+ className,+ href,+ ...buttonProps+}: ActionButtonProps) {+ const hasReachedLimit =+ typeof limit === "number" &&+ limitValue !== undefined &&+ limitValue >= limit;+ const isDisabled =+ disabled || !hasAccess || !hasEntitlement || hasReachedLimit;++ const getMessage = () => {+ if (!hasAccess) return BUTTON_STATE_MESSAGES.noAccess;+ if (!hasEntitlement) return BUTTON_STATE_MESSAGES.entitlement;+ if (+ hasReachedLimit &&+ typeof limit === "number" &&+ limitValue !== undefined+ ) {+ return BUTTON_STATE_MESSAGES.limitReached(limitValue, limit);+ }+ return null;+ };++ const message = getMessage();++ const btnContent = (+ <ButtonContent+ icon={icon}+ isDisabled={isDisabled}+ loading={loading}+ hasAccess={hasAccess}+ hasEntitlement={hasEntitlement}+ hasReachedLimit={hasReachedLimit}+ className={className}+ buttonProps={buttonProps}+ href={href}+ >+ {children}+ </ButtonContent>+ );++ if (isDisabled && message) {+ return (+ <HoverCard openDelay={200}>+ <HoverCardTrigger asChild>+ <span>{btnContent}</span>+ </HoverCardTrigger>+ <HoverCardPortal>+ <HoverCardContent className="w-80 text-sm">+ {message}+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCard>+ );+ }++ return btnContent;+}++function ButtonContent({+ icon,+ isDisabled,+ loading,+ hasAccess,+ hasEntitlement,+ hasReachedLimit,+ className,+ buttonProps,+ children,+ href,+}: {+ icon?: React.ReactNode;+ isDisabled: boolean;+ loading: boolean;+ hasAccess: boolean;+ hasEntitlement: boolean;+ hasReachedLimit: boolean;+ className?: string;+ buttonProps: Omit<ButtonProps, "disabled" | "loading" | "className">;+ children: React.ReactNode;+ href?: string;+}) {+ const content = (+ <>+ {!hasAccess ? (+ <Lock className="mr-1 h-4 w-4" />+ ) : !hasEntitlement ? (+ <AlertCircle className="mr-1 h-4 w-4" />+ ) : hasReachedLimit ? (+ <Sparkle className="mr-1 h-4 w-4" />+ ) : icon ? (+ <div className="mr-1">{icon}</div>+ ) : null}+ {children}+ </>+ );++ const renderLink = href && !isDisabled;++ return (+ <Button+ disabled={isDisabled}+ loading={loading}+ className={className}+ {...buttonProps}+ asChild={renderLink ? true : undefined}+ >+ {renderLink ? <Link href={href}>{content}</Link> : content}+ </Button>+ );+}diff --git a/web/src/components/BatchExportTableButton.tsx b/web/src/components/BatchExportTableButton.tsxindex a6fb0a46ab..58bdadbc5a 100644--- a/web/src/components/BatchExportTableButton.tsx+++ b/web/src/components/BatchExportTableButton.tsx@@ -16,7 +16,6 @@ import React from "react";import { api } from "@/src/utils/api";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";export type BatchExportTableButtonProps = {projectId: string;@@ -41,7 +40,6 @@ export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = (});},});- const entitled = useHasOrgEntitlement("batch-export");const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "batchExport:create",@@ -61,7 +59,7 @@ export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = (});};- if (!entitled || !hasAccess) return null;+ if (!hasAccess) return null;return (<DropdownMenu>diff --git a/web/src/components/VersionLabel.tsx b/web/src/components/VersionLabel.tsxindex 49ddc07581..57d5b5f70b 100644--- a/web/src/components/VersionLabel.tsx+++ b/web/src/components/VersionLabel.tsx@@ -19,9 +19,10 @@ import {import { ArrowUp } from "lucide-react";import { api } from "@/src/utils/api";import { Button } from "@/src/components/ui/button";-import { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";import { env } from "@/src/env.mjs";import { cn } from "@/src/utils/tailwind";+import { usePlan } from "@/src/features/entitlements/hooks";+import { isSelfHostedPlan, planLabels } from "@langfuse/shared";export const VersionLabel = ({ className }: { className?: string }) => {const checkUpdate = api.public.checkUpdate.useQuery(undefined, {@@ -31,9 +32,24 @@ export const VersionLabel = ({ className }: { className?: string }) => {enabled: !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION, // do not check for updates on Langfuse CloudonError: (error) => console.error("checkUpdate error", error), // do not render default error message});- const isEeVersion = useIsEeEnabled();+ const plan = usePlan();const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);+ const selfHostedPlanLabel = !isLangfuseCloud+ ? plan && isSelfHostedPlan(plan)+ ? // self-host plan+ {+ short: plan === "self-hosted:pro" ? "Pro" : "EE",+ long: planLabels[plan],+ }+ : // no plan, oss+ {+ short: "OSS",+ long: "Open Source",+ }+ : // null on cloud+ null;+const hasUpdate =!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&checkUpdate.data &&@@ -49,9 +65,9 @@ export const VersionLabel = ({ className }: { className?: string }) => {return (<DropdownMenu><DropdownMenuTrigger asChild>- <Button variant="ghost" size="xs" className={cn("text-xs",className)}>+ <Button variant="ghost" size="xs" className={cn("text-xs", className)}>{VERSION}- {!isLangfuseCloud && (isEeVersion ? " EE" : " OSS")}+ {selfHostedPlanLabel ? ` ${selfHostedPlanLabel.short}` : null}{hasUpdate && <ArrowUp className={`ml-1 h-3 w-3 ${color}`} />}</Button></DropdownMenuTrigger>@@ -70,11 +86,11 @@ export const VersionLabel = ({ className }: { className?: string }) => {<DropdownMenuSeparator /></>) : null}- {isEeVersion && (+ {selfHostedPlanLabel && (<><DropdownMenuLabel className="flex items-center font-normal"><BadgeCheck size={16} className="mr-2" />- Enterprise Edition+ {selfHostedPlanLabel.long}</DropdownMenuLabel><DropdownMenuSeparator /></>@@ -100,12 +116,9 @@ export const VersionLabel = ({ className }: { className?: string }) => {Roadmap</Link></DropdownMenuItem>- {!isLangfuseCloud && !isEeVersion && (+ {!isLangfuseCloud && (<DropdownMenuItem asChild>- <Link- href="https://langfuse.com/docs/deployment/feature-overview"- target="_blank"- >+ <Link href="https://langfuse.com/pricing-self-host" target="_blank"><Info size={16} className="mr-2" />Compare Versions</Link>diff --git a/web/src/components/app-sidebar.tsx b/web/src/components/app-sidebar.tsxindex 59cb8cd913..a1c0509ccb 100644--- a/web/src/components/app-sidebar.tsx+++ b/web/src/components/app-sidebar.tsx@@ -33,7 +33,7 @@ export function AppSidebar({return (<Sidebar collapsible="icon" variant="sidebar" {...props}><SidebarHeader>- <div className="flex items-center gap-2 p-2">+ <div className="flex items-center gap-2 p-2 pr-0"><LangfuseLogo version /></div><DemoBadge />diff --git a/web/src/components/date-picker.tsx b/web/src/components/date-picker.tsxindex 107a19e8af..131f6a5352 100644--- a/web/src/components/date-picker.tsx+++ b/web/src/components/date-picker.tsx@@ -90,6 +90,7 @@ export type DatePickerWithRangeProps = {dateRange?: DashboardDateRange;className?: string;selectedOption: DashboardDateRangeOptions;+ disabled?: React.ComponentProps<typeof Calendar>["disabled"];setDateRangeAndOption: (option: DashboardDateRangeOptions,date?: DashboardDateRange,@@ -101,6 +102,7 @@ export function DatePickerWithRange({dateRange,selectedOption,setDateRangeAndOption,+ disabled,}: DatePickerWithRangeProps) {const [internalDateRange, setInternalDateRange] = useState<DateRange | undefined@@ -215,6 +217,7 @@ export function DatePickerWithRange({selected={internalDateRange}onSelect={onCalendarSelection}numberOfMonths={isSmallScreen ? 1 : 2}+ disabled={disabled}/>{!isSmallScreen && (<div className="flex flex-row border-t-2 py-1.5">diff --git a/web/src/components/date-range-dropdowns.tsx b/web/src/components/date-range-dropdowns.tsxindex 81ce17d1f6..10d06414ac 100644--- a/web/src/components/date-range-dropdowns.tsx+++ b/web/src/components/date-range-dropdowns.tsx@@ -17,18 +17,30 @@ import {type DashboardDateRange,TABLE_AGGREGATION_OPTIONS,getDateFromOption,+ isTableDataRangeOptionAvailable,+ isDashboardDateRangeOptionAvailable,} from "@/src/utils/date-range-utils";import { Clock } from "lucide-react";+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";+import { useMemo } from "react";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";+import { HoverCardPortal } from "@radix-ui/react-hover-card";type BaseDateRangeDropdownProps<T> = {selectedOption: T;options: readonly T[];+ limitedOptions?: readonly T[];onSelectionChange: (value: T) => void;};const BaseDateRangeDropdown = <T extends string>({selectedOption,options,+ limitedOptions,onSelectionChange,}: BaseDateRangeDropdownProps<T>) => {return (@@ -38,11 +50,33 @@ const BaseDateRangeDropdown = <T extends string>({<SelectValue placeholder="Select" /></SelectTrigger><SelectContent position="popper" defaultValue={60}>- {options.map((item) => (- <SelectItem key={item} value={item}>- {item}- </SelectItem>- ))}+ {options.map((item) => {+ const itemObj = (+ <SelectItem+ key={item}+ value={item}+ disabled={limitedOptions?.includes(item)}+ >+ {item}+ </SelectItem>+ );+ const isLimited = limitedOptions?.includes(item);++ return isLimited ? (+ <HoverCard openDelay={200}>+ <HoverCardTrigger asChild>+ <span>{itemObj}</span>+ </HoverCardTrigger>+ <HoverCardPortal>+ <HoverCardContent className="w-60 text-sm" side="right">+ This time range is not available in your current plan.+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCard>+ ) : (+ itemObj+ );+ })}</SelectContent></Select>);@@ -59,6 +93,17 @@ type DashboardDateRangeDropdownProps = {export const DashboardDateRangeDropdown: React.FC<DashboardDateRangeDropdownProps> = ({ selectedOption, setDateRangeAndOption }) => {+ const lookbackLimit = useEntitlementLimit("data-access-days");+ const disabledOptions = useMemo(() => {+ return DASHBOARD_AGGREGATION_OPTIONS.filter(+ (option) =>+ !isDashboardDateRangeOptionAvailable({+ option,+ limitDays: lookbackLimit,+ }),+ );+ }, [lookbackLimit]);+const onDropDownSelection = (value: DashboardDateRangeOptions) => {if (value === DASHBOARD_AGGREGATION_PLACEHOLDER) {setDateRangeAndOption(DASHBOARD_AGGREGATION_PLACEHOLDER, undefined);@@ -82,6 +127,7 @@ export const DashboardDateRangeDropdown: React.FC<<BaseDateRangeDropdownselectedOption={selectedOption}options={options}+ limitedOptions={disabledOptions}onSelectionChange={onDropDownSelection}/>);@@ -99,6 +145,14 @@ export const TableDateRangeDropdown: React.FC<TableDateRangeDropdownProps> = ({selectedOption,setDateRangeAndOption,}) => {+ const lookbackLimit = useEntitlementLimit("data-access-days");+ const disabledOptions = useMemo(() => {+ return TABLE_AGGREGATION_OPTIONS.filter(+ (option) =>+ !isTableDataRangeOptionAvailable({ option, limitDays: lookbackLimit }),+ );+ }, [lookbackLimit]);+const onDropDownSelection = (value: TableDateRangeOptions) => {const dateFromOption = getDateFromOption({filterSource: "TABLE",@@ -116,6 +170,7 @@ export const TableDateRangeDropdown: React.FC<TableDateRangeDropdownProps> = ({<BaseDateRangeDropdownselectedOption={selectedOption}options={TABLE_AGGREGATION_OPTIONS}+ limitedOptions={disabledOptions}onSelectionChange={onDropDownSelection}/>);diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsxindex 95c88ea817..95d02c22b9 100644--- a/web/src/components/layouts/layout.tsx+++ b/web/src/components/layouts/layout.tsx@@ -10,7 +10,7 @@ import { Toaster } from "@/src/components/ui/sonner";import DOMPurify from "dompurify";import { ThemeToggle } from "@/src/features/theming/ThemeToggle";import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";-import { useOrgEntitlements } from "@/src/features/entitlements/hooks";+import { useEntitlements } from "@/src/features/entitlements/hooks";import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";import { hasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { ClickhouseAdminToggle } from "@/src/components/layouts/ClickhouseAdminToggle";@@ -105,7 +105,7 @@ export default function Layout(props: PropsWithChildren) {const enableExperimentalFeatures =session.data?.environment.enableExperimentalFeatures ?? false;- const entitlements = useOrgEntitlements();+ const entitlements = useEntitlements();const uiCustomization = useUiCustomization();diff --git a/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx b/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsxindex 04cddc6772..508cac698b 100644--- a/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx+++ b/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx@@ -39,7 +39,7 @@ import { zodResolver } from "@hookform/resolvers/zod";import { useForm } from "react-hook-form";import { z } from "zod";import { useSession } from "next-auth/react";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";const addToQueueFormSchema = z.object({queueId: z.string(),@@ -71,7 +71,7 @@ export function TraceTableMultiSelectAction({},});- const hasEntitlement = useHasOrgEntitlement("annotation-queues");+ const hasEntitlement = useHasEntitlement("annotation-queues");const hasAddToQueueAccess = useHasProjectAccess({projectId,scope: "annotationQueues:CUD",diff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsxindex a0fddd9979..498aaea23e 100644--- a/web/src/components/table/use-cases/generations.tsx+++ b/web/src/components/table/use-cases/generations.tsx@@ -46,7 +46,7 @@ import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndiviimport TagList from "@/src/features/tag/components/TagList";import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";-import { useOrganizationPlan } from "@/src/features/entitlements/hooks";+import { usePlan } from "@/src/features/entitlements/hooks";import {DropdownMenu,DropdownMenuContent,@@ -104,7 +104,7 @@ export default function GenerationsTable({omittedFilter = [],}: GenerationsTableProps) {const capture = usePostHogClientCapture();- const plan = useOrganizationPlan();+ const plan = usePlan();const [isExporting, setIsExporting] = useState(false);const [searchQuery, setSearchQuery] = useQueryParam("search",diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsxindex e217cc3259..56990e5d65 100644--- a/web/src/components/trace/ObservationPreview.tsx+++ b/web/src/components/trace/ObservationPreview.tsx@@ -28,7 +28,7 @@ import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButtonimport { cn } from "@/src/utils/tailwind";import { NewDatasetItemFromTrace } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";import { CreateNewAnnotationQueueItem } from "@/src/ee/features/annotation-queues/components/CreateNewAnnotationQueueItem";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";import { useMemo } from "react";import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";@@ -65,7 +65,7 @@ export const ObservationPreview = ({const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<string[]>("emptySelectedConfigIds", []);- const hasEntitlement = useHasOrgEntitlement("annotation-queues");+ const hasEntitlement = useHasEntitlement("annotation-queues");const isAuthenticatedAndProjectMember =useIsAuthenticatedAndProjectMember(projectId);diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsxindex 9b0de5cc7a..8810dfd13a 100644--- a/web/src/components/trace/TracePreview.tsx+++ b/web/src/components/trace/TracePreview.tsx@@ -28,7 +28,7 @@ import { api } from "@/src/utils/api";import { cn } from "@/src/utils/tailwind";import { NewDatasetItemFromTrace } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";import { CreateNewAnnotationQueueItem } from "@/src/ee/features/annotation-queues/components/CreateNewAnnotationQueueItem";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { useMemo } from "react";import { usdFormatter } from "@/src/utils/numbers";import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";@@ -61,7 +61,7 @@ export const TracePreview = ({const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<string[]>("emptySelectedConfigIds", []);- const hasEntitlement = useHasOrgEntitlement("annotation-queues");+ const hasEntitlement = useHasEntitlement("annotation-queues");const isAuthenticatedAndProjectMember = useIsAuthenticatedAndProjectMember(trace.projectId,);diff --git a/web/src/components/ui/calendar.tsx b/web/src/components/ui/calendar.tsxindex 7ea85ea671..fdb599a400 100644--- a/web/src/components/ui/calendar.tsx+++ b/web/src/components/ui/calendar.tsx@@ -13,12 +13,14 @@ function Calendar({className,classNames,showOutsideDays = true,+ disabled,...props}: CalendarProps) {return (<DayPickershowOutsideDays={showOutsideDays}className={cn("p-3", className)}+ disabled={disabled}classNames={{months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month: "space-y-4",diff --git a/web/src/ee/features/annotation-queues/components/AnnotationQueuesItem.tsx b/web/src/ee/features/annotation-queues/components/AnnotationQueuesItem.tsxindex 7d6c21754e..04735f875d 100644--- a/web/src/ee/features/annotation-queues/components/AnnotationQueuesItem.tsx+++ b/web/src/ee/features/annotation-queues/components/AnnotationQueuesItem.tsx@@ -3,7 +3,7 @@ import Header from "@/src/components/layouts/header";import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";import useSessionStorage from "@/src/components/useSessionStorage";import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { AnnotationQueueItemPage } from "@/src/ee/features/annotation-queues/components/AnnotationQueueItemPage";import { api } from "@/src/utils/api";@@ -22,7 +22,7 @@ export const AnnotationQueuesItem = ({projectId,scope: "annotationQueues:read",});- const hasEntitlement = useHasOrgEntitlement("annotation-queues");+ const hasEntitlement = useHasEntitlement("annotation-queues");const queue = api.annotationQueues.byId.useQuery({diff --git a/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx b/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsxindex 9935e17ef8..ddf14a1189 100644--- a/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx+++ b/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx@@ -19,7 +19,7 @@ import {import { Input } from "@/src/components/ui/input";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { zodResolver } from "@hookform/resolvers/zod";-import { CircleAlert, Edit, LockIcon, PlusIcon } from "lucide-react";+import { Edit, PlusIcon } from "lucide-react";import { useForm } from "react-hook-form";import { Form } from "@/src/components/ui/form";import { Textarea } from "@/src/components/ui/textarea";@@ -34,12 +34,11 @@ import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-selimport { CommandItem } from "@/src/components/ui/command";import { useRouter } from "next/router";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useOrganizationPlan } from "@/src/features/entitlements/hooks";import {- HoverCard,- HoverCardContent,- HoverCardTrigger,-} from "@/src/components/ui/hover-card";+ useHasEntitlement,+ useEntitlementLimit,+} from "@/src/features/entitlements/hooks";+import { ActionButton } from "@/src/components/ActionButton";export const CreateOrEditAnnotationQueueButton = ({projectId,@@ -55,8 +54,9 @@ export const CreateOrEditAnnotationQueueButton = ({projectId: projectId,scope: "annotationQueues:CUD",});+ const hasEntitlement = useHasEntitlement("annotation-queues");+ const queueLimit = useEntitlementLimit("annotation-queue-count");const router = useRouter();- const plan = useOrganizationPlan();const capture = usePostHogClientCapture();const queueQuery = api.annotationQueues.byId.useQuery(@@ -119,55 +119,6 @@ export const CreateOrEditAnnotationQueueButton = ({const configs = configsData.data?.configs ?? [];- if (!hasAccess) {- return (- <Button variant={variant} disabled={true} className="justify-start">- <LockIcon className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />- <span className="text-sm">{queueId ? "Edit" : "New queue"}</span>- </Button>- );- }-- if (queueCountData.isLoading) return null;-- // gate cloud hobby usage of annotation queue- if (plan === "cloud:hobby" && !!queueCountData.data && !queueId) {- return (- <HoverCard>- <HoverCardTrigger asChild>- <Button- variant={variant}- className="relative grid grid-flow-row items-start justify-start overflow-hidden py-0 disabled:cursor-default"- disabled- >- <div className="mt-2 flex h-6 flex-row items-center justify-center">- <PlusIcon className="mr-1.5 h-4 w-4" aria-hidden="true" />- <span className="text-sm">New queue</span>- </div>- <div className="absolute top-0 flex h-3 w-full items-center justify-center bg-primary-accent">- <CircleAlert- className="mr-1 h-2 w-2 text-white"- aria-hidden="true"- />- <span className="text-xs text-white">At usage limit</span>- </div>- </Button>- </HoverCardTrigger>- <HoverCardContent className="w-80" align="start" side="right">- <div className="flex justify-between space-x-4">- <div className="space-y-1">- <h4 className="text-sm font-semibold">Usage Limit Reached</h4>- <p className="text-xs">- You have reached the maximum number of annotation queues allowed- on the Hobby plan. Upgrade your plan to create more queues.- </p>- </div>- </div>- </HoverCardContent>- </HoverCard>- );- }-const onSubmit = (data: CreateQueue) => {if (queueId) {editQueueMutation.mutateAsync({@@ -202,20 +153,26 @@ export const CreateOrEditAnnotationQueueButton = ({return (<Dialog open={isOpen} onOpenChange={setIsOpen}><DialogTrigger asChild>- <Button+ <ActionButtonvariant={variant}onClick={() => setIsOpen(true)}className="justify-start"+ icon={+ queueId ? (+ <Edit className="h-4 w-4" aria-hidden="true" />+ ) : (+ <PlusIcon className="h-4 w-4" aria-hidden="true" />+ )+ }+ hasAccess={hasAccess}+ hasEntitlement={hasEntitlement}+ limitValue={queueCountData.data}+ limit={queueLimit}>- {queueId ? (- <Edit className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />- ) : (- <PlusIcon className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />- )}<span className="ml-1 text-sm font-normal">{queueId ? "Edit" : "New queue"}</span>- </Button>+ </ActionButton></DialogTrigger>{configsData.data && (<DialogContent className="max-h-[90vh] overflow-y-auto">diff --git a/web/src/ee/features/annotation-queues/pages/AnnotationQueueItems.tsx b/web/src/ee/features/annotation-queues/pages/AnnotationQueueItems.tsxindex 3e178e0932..b7e38f2122 100644--- a/web/src/ee/features/annotation-queues/pages/AnnotationQueueItems.tsx+++ b/web/src/ee/features/annotation-queues/pages/AnnotationQueueItems.tsx@@ -12,7 +12,7 @@ import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetaimport Link from "next/link";import { CreateOrEditAnnotationQueueButton } from "@/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";import { Skeleton } from "@/src/components/ui/skeleton";import { TableWithMetadataWrapper } from "@/src/components/table/TableWithMetadataWrapper";@@ -35,7 +35,7 @@ export default function QueueItems() {projectId,scope: "annotationQueues:CUD",});- const hasEntitlement = useHasOrgEntitlement("annotation-queues");+ const hasEntitlement = useHasEntitlement("annotation-queues");if (!hasReadAccess || !hasEntitlement) return <SupportOrUpgradePage />;return (diff --git a/web/src/ee/features/annotation-queues/pages/AnnotationQueues.tsx b/web/src/ee/features/annotation-queues/pages/AnnotationQueues.tsxindex 707c290d7a..0b7bc4d2c7 100644--- a/web/src/ee/features/annotation-queues/pages/AnnotationQueues.tsx+++ b/web/src/ee/features/annotation-queues/pages/AnnotationQueues.tsx@@ -3,7 +3,7 @@ import { useRouter } from "next/router";import { FullScreenPage } from "@/src/components/layouts/full-screen-page";import { AnnotationQueuesTable } from "@/src/ee/features/annotation-queues/components/AnnotationQueuesTable";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";export default function AnnotationQueues() {@@ -13,7 +13,7 @@ export default function AnnotationQueues() {projectId: projectId,scope: "annotationQueues:read",});- const hasEntitlement = useHasOrgEntitlement("annotation-queues");+ const hasEntitlement = useHasEntitlement("annotation-queues");if (!hasAccess || !hasEntitlement) return <SupportOrUpgradePage />;return (diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsxindex cc7b3f0e7c..f5013d72c8 100644--- a/web/src/ee/features/billing/components/BillingSettings.tsx+++ b/web/src/ee/features/billing/components/BillingSettings.tsx@@ -4,20 +4,12 @@ import { Button } from "@/src/components/ui/button";import { api } from "@/src/utils/api";import { Flex, MarkerBar, Metric, Text } from "@tremor/react";import Link from "next/link";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTrigger,-} from "@/src/components/ui/dialog";import Header from "@/src/components/layouts/header";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useQueryOrganization } from "@/src/features/organizations/hooks";import { Card } from "@/src/components/ui/card";import { numberFormatter, compactNumberFormatter } from "@/src/utils/numbers";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { type Plan, planLabels } from "@langfuse/shared";-import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";import { useRouter } from "next/router";import {chatAvailable,@@ -26,7 +18,15 @@ import {import { env } from "@/src/env.mjs";import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";-import { MAX_OBSERVATIONS_FREE_PLAN } from "@/src/ee/features/billing/constants";+import { MAX_EVENTS_FREE_PLAN } from "@/src/ee/features/billing/constants";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTrigger,+} from "@/src/components/ui/dialog";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";export const BillingSettings = () => {const router = useRouter();@@ -36,7 +36,7 @@ export const BillingSettings = () => {scope: "langfuseCloudBilling:CRUD",});- const entitled = useHasOrgEntitlement("cloud-billing");+ const entitled = useHasEntitlement("cloud-billing");if (!entitled) return null;if (!hasAccess)@@ -72,11 +72,14 @@ const OrganizationUsageChart = () => {},},);- const planLimit =- organization?.cloudConfig?.monthlyObservationLimit ??- MAX_OBSERVATIONS_FREE_PLAN;+ const hobbyPlanLimit =+ organization?.cloudConfig?.monthlyObservationLimit ?? MAX_EVENTS_FREE_PLAN;const plan: Plan = organization?.plan ?? "cloud:hobby";const planLabel = planLabels[plan];+ const usageType = usage.data?.usageType+ ? usage.data.usageType.charAt(0).toUpperCase() ++ usage.data.usageType.slice(1)+ : "Events";return (<div>@@ -85,19 +88,21 @@ const OrganizationUsageChart = () => {<><Text>{usage.data.billingPeriod- ? `Observations in current billing period`- : "Observations / last 30d"}+ ? `${usageType} in current billing period`+ : `${usageType} / last 30d`}</Text>- <Metric>{numberFormatter(usage.data.countObservations, 0)}</Metric>+ <Metric>{numberFormatter(usage.data.usageCount, 0)}</Metric>{plan === "cloud:hobby" && (<><Flex className="mt-4">- <Text>{`${numberFormatter((usage.data.countObservations / planLimit) * 100)}%`}</Text>- <Text>Plan limit: {compactNumberFormatter(planLimit)}</Text>+ <Text>{`${numberFormatter((usage.data.usageCount / hobbyPlanLimit) * 100)}%`}</Text>+ <Text>+ Plan limit: {compactNumberFormatter(hobbyPlanLimit)}+ </Text></Flex><MarkerBarvalue={Math.min(- (usage.data.countObservations / planLimit) * 100,+ (usage.data.usageCount / hobbyPlanLimit) * 100,100,)}className="mt-3"@@ -138,35 +143,35 @@ const OrganizationUsageChart = () => {const BillingPortalOrPricingPageButton = () => {const organization = useQueryOrganization();+ const router = useRouter();+ const capture = usePostHogClientCapture();const billingPortalUrl = api.cloudBilling.getStripeCustomerPortalUrl.useQuery({orgId: organization?.id as string,},{enabled: organization !== undefined,+ refetchOnMount: false,+ refetchOnReconnect: false,+ refetchOnWindowFocus: false,},);- if (billingPortalUrl.isLoading) return null;- if (!billingPortalUrl.data) return <PricingPageButton />;-- return (- <Button asChild>- <Link href={billingPortalUrl.data}>Billing portal</Link>- </Button>- );-};-const PricingPageButton = () => {- const capture = usePostHogClientCapture();- const organization = useQueryOrganization();- const router = useRouter();const mutCreateCheckoutSession =api.cloudBilling.createStripeCheckoutSession.useMutation({onSuccess: (url) => {router.push(url);},});+if (!organization) return null;+ if (billingPortalUrl.isLoading) return null;+ if (billingPortalUrl.data)+ return (+ <Button asChild>+ <Link href={billingPortalUrl.data}>Billing portal</Link>+ </Button>+ );// Do not show checkout or customer portal if manual plan is set in cloud configif (organization.cloudConfig?.plan) {@@ -186,6 +191,7 @@ const PricingPageButton = () => {else return null;}+ // Show pricing page buttonreturn (<DialogonOpenChange={(open) => {diff --git a/web/src/ee/features/billing/components/UsageTracker.tsx b/web/src/ee/features/billing/components/UsageTracker.tsxindex e2e3527a8a..9f6e4c0864 100644--- a/web/src/ee/features/billing/components/UsageTracker.tsx+++ b/web/src/ee/features/billing/components/UsageTracker.tsx@@ -1,11 +1,8 @@import { api } from "@/src/utils/api";import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";-import { MAX_OBSERVATIONS_FREE_PLAN } from "@/src/ee/features/billing/constants";-import {- useHasOrgEntitlement,- useOrganizationPlan,-} from "@/src/features/entitlements/hooks";+import { MAX_EVENTS_FREE_PLAN } from "@/src/ee/features/billing/constants";+import { useHasEntitlement, usePlan } from "@/src/features/entitlements/hooks";import {Card,CardContent,@@ -18,8 +15,8 @@ import Link from "next/link";export const UsageTracker = () => {const { organization } = useQueryProjectOrOrganization();- const hasEntitlement = useHasOrgEntitlement("cloud-billing");- const plan = useOrganizationPlan();+ const hasEntitlement = useHasEntitlement("cloud-billing");+ const plan = usePlan();const hasAccess = useHasOrganizationAccess({organizationId: organization?.id,scope: "langfuseCloudBilling:CRUD",@@ -48,10 +45,11 @@ export const UsageTracker = () => {return null;}- const usage = usageQuery.data.countObservations || 0;- const percentage = (usage / MAX_OBSERVATIONS_FREE_PLAN) * 100;+ const usage = usageQuery.data.usageCount || 0;+ const usageType = usageQuery.data.usageType;+ const percentage = (usage / MAX_EVENTS_FREE_PLAN) * 100;- if (percentage < 80) {+ if (percentage < 90) {return null;}@@ -60,7 +58,7 @@ export const UsageTracker = () => {<CardHeader className="p-4 pb-0"><CardTitle className="text-sm">Hobby Plan Usage Limit</CardTitle><CardDescription>- {`${usage.toLocaleString()} / ${MAX_OBSERVATIONS_FREE_PLAN.toLocaleString()} (${percentage.toFixed(0)}%) observations in last 30 days. Please upgrade your plan to avoid interruptions.`}+ {`${usage.toLocaleString()} / ${MAX_EVENTS_FREE_PLAN.toLocaleString()} (${percentage.toFixed(0)}%) ${usageType} in last 30 days. Please upgrade your plan to avoid interruptions.`}</CardDescription></CardHeader><CardContent className="p-4 pt-2">diff --git a/web/src/ee/features/billing/constants.ts b/web/src/ee/features/billing/constants.tsindex 330420c009..88b67ff4bd 100644--- a/web/src/ee/features/billing/constants.ts+++ b/web/src/ee/features/billing/constants.ts@@ -1 +1 @@-export const MAX_OBSERVATIONS_FREE_PLAN = 50_000;+export const MAX_EVENTS_FREE_PLAN = 50_000;diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.tsindex 047dcd9939..1242388dcd 100644--- a/web/src/ee/features/billing/server/cloudBillingRouter.ts+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts@@ -12,6 +12,7 @@ import { TRPCError } from "@trpc/server";import * as z from "zod";import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { auditLog } from "@/src/features/audit-logs/auditLog";+import { getObservationCountOfProjectsSinceCreationDate } from "@langfuse/shared/src/server";export const cloudBillingRouter = createTRPCRouter({createStripeCheckoutSession: protectedOrganizationProcedure@@ -221,6 +222,13 @@ export const cloudBillingRouter = createTRPCRouter({where: {id: input.orgId,},+ include: {+ projects: {+ select: {+ id: true,+ },+ },+ },});if (!organization) {throw new TRPCError({@@ -244,6 +252,7 @@ export const cloudBillingRouter = createTRPCRouter({start: new Date(subscription.current_period_start * 1000),end: new Date(subscription.current_period_end * 1000),};+const stripeInvoice = await stripeClient.invoices.retrieveUpcoming({subscription: parsedOrg.cloudConfig.stripe.activeSubscriptionId,});@@ -251,38 +260,78 @@ export const cloudBillingRouter = createTRPCRouter({usdAmount: stripeInvoice.amount_due / 100,date: new Date(stripeInvoice.period_end * 1000),};- const usage = stripeInvoice.lines.data.reduce((acc, line) => {+ const usageInvoiceLines = stripeInvoice.lines.data.filter((line) =>+ Boolean(line.plan?.meter),+ );+ const usage = usageInvoiceLines.reduce((acc, line) => {if (line.quantity) {return acc + line.quantity;}return acc;}, 0);+ // get meter for usage type (events or observations)+ const meterId = usageInvoiceLines[0]?.plan?.meter;+ const meter = meterId+ ? await stripeClient.billing.meters.retrieve(meterId)+ : undefined;+return {- countObservations: usage,+ usageCount: usage,+ usageType: meter?.display_name.toLowerCase() ?? "events",billingPeriod,upcomingInvoice,};}}- // For non-Stripe subscriptions, we can only get usage from the LangFuse API+ // Free plan, usage not tracked on Stripeconst thirtyDaysAgo = new Date();thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);thirtyDaysAgo.setHours(0, 0, 0, 0);+ const projectIds = organization.projects.map((p) => p.id);- const usage = await ctx.prisma.observation.count({- where: {- project: {- orgId: input.orgId,- },- startTime: {- gte: thirtyDaysAgo,- },- },- });+ const countObservations =+ await getObservationCountOfProjectsSinceCreationDate({+ projectIds,+ start: thirtyDaysAgo,+ });++ // const usageArr = await Promise.all([+ // ctx.prisma.observation.count({+ // where: {+ // project: {+ // orgId: input.orgId,+ // },+ // createdAt: {+ // gte: thirtyDaysAgo,+ // },+ // },+ // }),+ // ctx.prisma.trace.count({+ // where: {+ // project: {+ // orgId: input.orgId,+ // },+ // createdAt: {+ // gte: thirtyDaysAgo,+ // },+ // },+ // }),+ // ctx.prisma.score.count({+ // where: {+ // project: {+ // orgId: input.orgId,+ // },+ // createdAt: {+ // gte: thirtyDaysAgo,+ // },+ // },+ // }),+ // ]);return {- countObservations: usage,+ usageCount: countObservations,+ usageType: "observations",};}),});diff --git a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts b/web/src/ee/features/billing/server/stripeWebhookApiHandler.tsindex 97783a908b..d3904ecb6e 100644--- a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts+++ b/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts@@ -104,6 +104,7 @@ async function handleSubscriptionChanged(});if (!checkoutSessionsResponse || checkoutSessionsResponse.data.length !== 1) {logger.error("[Stripe Webhook] No checkout session found");+ traceException("[Stripe Webhook] No checkout session found");return;}const checkoutSession = checkoutSessionsResponse.data[0];@@ -112,6 +113,7 @@ async function handleSubscriptionChanged(const clientReference = checkoutSession.client_reference_id;if (!clientReference) {logger.error("[Stripe Webhook] No client reference");+ traceException("[Stripe Webhook] No client reference");return NextResponse.json({ message: "No client reference" },{ status: 400 },@@ -133,6 +135,7 @@ async function handleSubscriptionChanged(});if (!organization) {logger.error("[Stripe Webhook] Organization not found");+ traceException("[Stripe Webhook] Organization not found");return;}const parsedOrg = parseDbOrg(organization);@@ -140,14 +143,15 @@ async function handleSubscriptionChanged(// assert that no other stripe customer id is already set on the orgconst customerId = subscription.customer;if (!customerId || typeof customerId !== "string") {- logger.error("[Stripe Webhook] Product ID not found");- traceException("[Stripe Webhook] Product ID not found");+ logger.error("[Stripe Webhook] Customer ID not found");+ traceException("[Stripe Webhook] Customer ID not found");return;}if (parsedOrg.cloudConfig?.stripe?.customerId &&parsedOrg.cloudConfig?.stripe?.customerId !== customerId) {+ logger.error("[Stripe Webhook] Another customer id already set on org");traceException("[Stripe Webhook] Another customer id already set on org");return;}@@ -159,6 +163,9 @@ async function handleSubscriptionChanged(logger.error("[Stripe Webhook] Subscription items not found or more than one",);+ traceException(+ "[Stripe Webhook] Subscription items not found or more than one",+ );return;}@@ -180,6 +187,9 @@ async function handleSubscriptionChanged(traceException("[Stripe Webhook] Another active product id already set on (one of the) org with this active subscription id",);+ logger.error(+ "[Stripe Webhook] Another active product id already set on (one of the) org with this active subscription id",+ );return;}diff --git a/web/src/ee/features/billing/utils/stripe.ts b/web/src/ee/features/billing/utils/stripe.tsindex 82be2ae291..70d6bbaf6a 100644--- a/web/src/ee/features/billing/utils/stripe.ts+++ b/web/src/ee/features/billing/utils/stripe.ts@@ -1,6 +1,7 @@import { env } from "@/src/env.mjs";import Stripe from "stripe";-export const stripeClient = env.STRIPE_SECRET_KEY- ? new Stripe(env.STRIPE_SECRET_KEY)- : undefined;+export const stripeClient =+ env.STRIPE_SECRET_KEY && env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION+ ? new Stripe(env.STRIPE_SECRET_KEY)+ : undefined;diff --git a/web/src/ee/features/billing/utils/stripeProducts.ts b/web/src/ee/features/billing/utils/stripeProducts.tsindex ba1cedfdee..ad12ad0019 100644--- a/web/src/ee/features/billing/utils/stripeProducts.ts+++ b/web/src/ee/features/billing/utils/stripeProducts.ts@@ -24,7 +24,7 @@ export const stripeProducts: StripeProduct[] = [checkout: {title: "Pro",description:- "For serious projects. Includes access to full history and higher usage.",+ "For serious projects. Includes access to full history, higher usage and access to features.",price: "$59 / month + $10/100k observations",},},diff --git a/web/src/ee/features/evals/pages/evaluators.tsx b/web/src/ee/features/evals/pages/evaluators.tsxindex 5bbe51bee1..a3e7ef1f08 100644--- a/web/src/ee/features/evals/pages/evaluators.tsx+++ b/web/src/ee/features/evals/pages/evaluators.tsx@@ -1,18 +1,26 @@import Header from "@/src/components/layouts/header";import { useRouter } from "next/router";-import { Button } from "@/src/components/ui/button";import Link from "next/link";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { Lock, Plus } from "lucide-react";+import { Plus } from "lucide-react";import EvaluatorTable from "@/src/ee/features/evals/components/evaluator-table";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { FullScreenPage } from "@/src/components/layouts/full-screen-page";import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";+import { ActionButton } from "@/src/components/ActionButton";+import { api } from "@/src/utils/api";+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";export default function EvaluatorsPage() {const router = useRouter();const projectId = router.query.projectId as string;const capture = usePostHogClientCapture();+ const evaluatorCount = api.evals.allConfigs.useQuery({+ projectId,+ }).data?.totalCount;+ const evaluatorLimit = useEntitlementLimit(+ "model-based-evaluations-count-evaluators",+ );const hasWriteAccess = useHasProjectAccess({projectId,scope: "evalJob:CUD",@@ -37,23 +45,17 @@ export default function EvaluatorsPage() {href: "https://langfuse.com/docs/scores/model-based-evals",}}actionButtons={- <Button- disabled={!hasWriteAccess}- onClick={() => capture("eval_config:new_form_open")}- asChild+ <ActionButton+ hasAccess={hasWriteAccess}+ icon={<Plus className="h-4 w-4" />}variant="secondary"+ onClick={() => capture("eval_config:new_form_open")}+ href={`/project/${projectId}/evals/new`}+ limitValue={evaluatorCount ?? 0}+ limit={evaluatorLimit}>- <Link- href={hasWriteAccess ? `/project/${projectId}/evals/new` : "#"}- >- {hasWriteAccess ? (- <Plus className="mr-2 h-4 w-4" />- ) : (- <Lock className="mr-2 h-4 w-4" />- )}- New evaluator- </Link>- </Button>+ New evaluator+ </ActionButton>}/><EvaluatorTablediff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.tsindex 8c0a336dbe..616d368db7 100644--- a/web/src/ee/features/evals/server/router.ts+++ b/web/src/ee/features/evals/server/router.ts@@ -1,5 +1,4 @@import { z } from "zod";-import {createTRPCRouter,protectedProjectProcedure,@@ -12,6 +11,7 @@ import {singleFilter,variableMapping,ChatMessageRole,+ paginationZod,type JobConfiguration,JobConfigState,JobType,@@ -111,8 +111,7 @@ export const evalRouter = createTRPCRouter({.input(z.object({projectId: z.string(),- limit: z.number(),- page: z.number(),+ ...paginationZod,}),).query(async ({ input, ctx }) => {diff --git a/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx b/web/src/ee/features/experiments/components/CreateExperimentsForm.tsxindex 3cff8521ff..3f41481a7c 100644--- a/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx+++ b/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx@@ -162,7 +162,7 @@ export const CreateExperimentsForm = ({const hasExperimentWriteAccess = useHasProjectAccess({projectId,- scope: "experiments:CUD",+ scope: "promptExperiments:CUD",});const hasEvalReadAccess = useHasProjectAccess({diff --git a/web/src/ee/features/experiments/server/router.ts b/web/src/ee/features/experiments/server/router.tsindex 92b3438a3c..875c4f9082 100644--- a/web/src/ee/features/experiments/server/router.ts+++ b/web/src/ee/features/experiments/server/router.ts@@ -74,14 +74,14 @@ export const experimentsRouter = createTRPCRouter({.output(ConfigResponse).query(async ({ input, ctx }) => {throwIfNoEntitlement({- entitlement: "experiments",+ entitlement: "prompt-experiments",projectId: input.projectId,sessionUser: ctx.session.user,});throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,- scope: "experiments:CUD",+ scope: "promptExperiments:CUD",});const prompt = await ctx.prisma.prompt.findFirst({@@ -161,14 +161,14 @@ export const experimentsRouter = createTRPCRouter({).mutation(async ({ input, ctx }) => {throwIfNoEntitlement({- entitlement: "experiments",+ entitlement: "prompt-experiments",projectId: input.projectId,sessionUser: ctx.session.user,});throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,- scope: "experiments:CUD",+ scope: "promptExperiments:CUD",});if (!redis || !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {diff --git a/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts b/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.tsindex 5b855089f8..79f1f4cfbe 100644--- a/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts+++ b/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts@@ -1,18 +1,20 @@-import { isEeEnabled } from "@/src/ee/utils/isEeEnabled";import { prisma } from "@langfuse/shared/src/db";import { encrypt } from "@langfuse/shared/encryption";import { SsoProviderSchema } from "./types";import { type NextApiRequest, type NextApiResponse } from "next";import { env } from "@/src/env.mjs";import { logger } from "@langfuse/shared/src/server";+import { multiTenantSsoAvailable } from "@/src/ee/features/multi-tenant-sso/multiTenantSsoAvailable";export async function createNewSsoConfigHandler(req: NextApiRequest,res: NextApiResponse,) {try {- if (!isEeEnabled) {- res.status(403).json({ error: "EE is not available" });+ if (!multiTenantSsoAvailable) {+ res+ .status(403)+ .json({ error: "Multi-tenant SSO is not available on your instance" });return;}// allow only POST requestsdiff --git a/web/src/ee/features/multi-tenant-sso/multiTenantSsoAvailable.ts b/web/src/ee/features/multi-tenant-sso/multiTenantSsoAvailable.tsnew file mode 100644index 0000000000..a750a4ce0a--- /dev/null+++ b/web/src/ee/features/multi-tenant-sso/multiTenantSsoAvailable.ts@@ -0,0 +1,5 @@+import { env } from "@/src/env.mjs";++export const multiTenantSsoAvailable = Boolean(+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,+);diff --git a/web/src/ee/features/multi-tenant-sso/utils.ts b/web/src/ee/features/multi-tenant-sso/utils.tsindex 1573b26598..cbd29bb58d 100644--- a/web/src/ee/features/multi-tenant-sso/utils.ts+++ b/web/src/ee/features/multi-tenant-sso/utils.ts@@ -6,7 +6,7 @@ import OktaProvider from "next-auth/providers/okta";import CognitoProvider from "next-auth/providers/cognito";import Auth0Provider from "next-auth/providers/auth0";import AzureADProvider from "next-auth/providers/azure-ad";-import { isEeEnabled } from "@/src/ee/utils/isEeEnabled";+import { multiTenantSsoAvailable } from "@/src/ee/features/multi-tenant-sso/multiTenantSsoAvailable";import { type SsoConfig, prisma } from "@langfuse/shared/src/db";import { decrypt } from "@langfuse/shared/encryption";import { SsoProviderSchema } from "./types";@@ -32,7 +32,7 @@ let cachedSsoConfigs: {* @returns {Promise<SsoProviderSchema[]>} - A list of all SSO configurations. Empty array if none are configured or EE is not available.*/async function getSsoConfigs(): Promise<SsoProviderSchema[]> {- if (!isEeEnabled) return [];+ if (!multiTenantSsoAvailable) return [];const CACHE_TTL = 60 * 60 * 1000; // 1 hourconst FAILEDTOFETCH_RETRY_AFTER = 60 * 1000; // 1 minute@@ -96,7 +96,7 @@ async function getSsoConfigs(): Promise<SsoProviderSchema[]> {* @returns {Promise<Provider[]>} - A list of all custom SSO providers.*/export async function loadSsoProviders(): Promise<Provider[]> {- if (!isEeEnabled) return [];+ if (!multiTenantSsoAvailable) return [];const ssoConfigs = await getSsoConfigs();@@ -114,7 +114,7 @@ export async function loadSsoProviders(): Promise<Provider[]> {* @returns `true` if any custom SSO provider is configured in the database.*/export async function isAnySsoConfigured(): Promise<boolean> {- if (!isEeEnabled) return false;+ if (!multiTenantSsoAvailable) return false;const ssoConfigs = await getSsoConfigs();return ssoConfigs.length > 0;}@@ -128,7 +128,7 @@ export async function isAnySsoConfigured(): Promise<boolean> {export async function getSsoAuthProviderIdForDomain(domain: string,): Promise<string | null> {- if (!isEeEnabled) return null;+ if (!multiTenantSsoAvailable) return null;const ssoConfig = (await getSsoConfigs()).find((ssoConfig) => ssoConfig.domain === domain.toLowerCase(),);diff --git a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsxindex 29626bb81f..bfb417c786 100644--- a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx+++ b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx@@ -18,7 +18,7 @@ import {type UIModelParams,ZodModelConfig,} from "@langfuse/shared";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";type JumpToPlaygroundButtonProps = (| {@@ -42,7 +42,7 @@ export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (const projectId = useProjectIdFromURL();const { setPlaygroundCache } = usePlaygroundCache();const [capturedState, setCapturedState] = useState<PlaygroundCache>(null);- const available = useHasOrgEntitlement("playground");+ const available = useHasEntitlement("playground");useEffect(() => {if (props.source === "prompt") {diff --git a/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsxindex 49b91b35ef..e5d77553b6 100644--- a/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsx+++ b/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsx@@ -3,10 +3,10 @@ import { useRouter } from "next/router";import { Button } from "@/src/components/ui/button";import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";export const ResetPlaygroundButton: React.FC = () => {- const available = useHasOrgEntitlement("playground");+ const available = useHasEntitlement("playground");const router = useRouter();const { setPlaygroundCache } = usePlaygroundCache();diff --git a/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx b/web/src/ee/features/playground/page/components/SaveToPromptButton.tsxindex d1fa2159cc..1158789d56 100644--- a/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx+++ b/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx@@ -24,11 +24,11 @@ import { PromptType } from "@/src/features/prompts/server/utils/validation";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";import { api } from "@/src/utils/api";import { cn } from "@/src/utils/tailwind";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import DocPopup from "@/src/components/layouts/doc-popup";export const SaveToPromptButton: React.FC = () => {- const available = useHasOrgEntitlement("playground");+ const available = useHasEntitlement("playground");const [selectedPromptId, setSelectedPromptId] = useState("");const { modelParams, messages, output, promptVariables } =usePlaygroundContext();diff --git a/web/src/ee/features/playground/page/hooks/usePlaygroundCache.ts b/web/src/ee/features/playground/page/hooks/usePlaygroundCache.tsindex 8ffc748112..109bd6a879 100644--- a/web/src/ee/features/playground/page/hooks/usePlaygroundCache.ts+++ b/web/src/ee/features/playground/page/hooks/usePlaygroundCache.ts@@ -1,13 +1,13 @@import { useEffect, useState } from "react";import { type PlaygroundCache } from "../types";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";const playgroundCacheKey = "playgroundCache";export default function usePlaygroundCache() {const [cache, setCache] = useState<PlaygroundCache>(null);- const available = useHasOrgEntitlement("playground");+ const available = useHasEntitlement("playground");const setPlaygroundCache = (cache: PlaygroundCache) => {sessionStorage.setItem(playgroundCacheKey, JSON.stringify(cache));};diff --git a/web/src/ee/features/playground/page/index.tsx b/web/src/ee/features/playground/page/index.tsxindex e99b33a7cf..35ec9e1567 100644--- a/web/src/ee/features/playground/page/index.tsx+++ b/web/src/ee/features/playground/page/index.tsx@@ -4,10 +4,10 @@ import { ResetPlaygroundButton } from "@/src/ee/features/playground/page/componeimport { SaveToPromptButton } from "@/src/ee/features/playground/page/components/SaveToPromptButton";import { PlaygroundProvider } from "@/src/ee/features/playground/page/context";import Playground from "@/src/ee/features/playground/page/playground";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";export default function PlaygroundPage() {- const available = useHasOrgEntitlement("playground");+ const available = useHasEntitlement("playground");if (!available) return null;return (<PlaygroundProvider>diff --git a/web/src/ee/features/ui-customization/uiCustomizationRouter.ts b/web/src/ee/features/ui-customization/uiCustomizationRouter.tsindex 539223beff..75ebd32af2 100644--- a/web/src/ee/features/ui-customization/uiCustomizationRouter.ts+++ b/web/src/ee/features/ui-customization/uiCustomizationRouter.ts@@ -1,9 +1,14 @@import { env } from "@/src/env.mjs";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";export const uiCustomizationRouter = createTRPCRouter({get: protectedProcedure.query(({ ctx }) => {- if (!ctx.session.environment.eeEnabled) return null;+ const hasEntitlement = hasEntitlementBasedOnPlan({+ plan: ctx.session.environment.selfHostedInstancePlan,+ entitlement: "self-host-ui-customization",+ });+ if (!hasEntitlement) return null;return {hostname: env.LANGFUSE_UI_API_HOST,diff --git a/web/src/ee/features/ui-customization/useUiCustomization.ts b/web/src/ee/features/ui-customization/useUiCustomization.tsindex 4c9b4e8901..72ca7c88dc 100644--- a/web/src/ee/features/ui-customization/useUiCustomization.ts+++ b/web/src/ee/features/ui-customization/useUiCustomization.ts@@ -1,16 +1,16 @@-import { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { api } from "@/src/utils/api";export const useUiCustomization = () => {- const isEeVersion = useIsEeEnabled();+ const hasEntitlement = useHasEntitlement("self-host-ui-customization");const customization = api.uiCustomization.get.useQuery(undefined, {- enabled: isEeVersion,+ enabled: hasEntitlement,refetchOnMount: false,refetchOnWindowFocus: false,refetchOnReconnect: false,});- if (!isEeVersion) return null;+ if (!hasEntitlement) return null;return customization.data ?? null;};diff --git a/web/src/ee/utils/isEeEnabled.ts b/web/src/ee/utils/isEeEnabled.tsdeleted file mode 100644index 86b34528f0..0000000000--- a/web/src/ee/utils/isEeEnabled.ts+++ /dev/null@@ -1,15 +0,0 @@-import { env } from "@/src/env.mjs";--/**- * Function to determine if the enterprise edition (EE) features are enabled. Do not use in frontend code as env variables are not available in the browser.- *- * This hook checks two conditions:- * 1. If Langfuse is running on Langfuse Cloud- * 2. If EE license is provided based on the user's session- *- * @returns {boolean}- */--export const isEeEnabled =- Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) ||- Boolean(env.LANGFUSE_EE_LICENSE_KEY);diff --git a/web/src/ee/utils/useIsEeEnabled.ts b/web/src/ee/utils/useIsEeEnabled.tsdeleted file mode 100644index d9b977d9a5..0000000000--- a/web/src/ee/utils/useIsEeEnabled.ts+++ /dev/null@@ -1,10 +0,0 @@-import { useSession } from "next-auth/react";--/**- * Custom React frontend hook to determine if the enterprise edition (EE) features are enabled.- */--export const useIsEeEnabled: () => boolean = () => {- const session = useSession();- return Boolean(session.data?.environment.eeEnabled);-};diff --git a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts b/web/src/features/auth/lib/createProjectMembershipsOnSignup.tsindex 94a2ce0288..994f8a791e 100644--- a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts+++ b/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts@@ -10,12 +10,12 @@ export async function createProjectMembershipsOnSignup(user: {// Langfuse Cloud: provide view-only access to the demo project, none access to the demo orgconst demoProject =env.NEXT_PUBLIC_DEMO_ORG_ID && env.NEXT_PUBLIC_DEMO_PROJECT_ID- ? (await prisma.project.findUnique({+ ? ((await prisma.project.findUnique({where: {orgId: env.NEXT_PUBLIC_DEMO_ORG_ID,id: env.NEXT_PUBLIC_DEMO_PROJECT_ID,},- })) ?? undefined+ })) ?? undefined): undefined;if (demoProject !== undefined) {await prisma.organizationMembership.create({@@ -27,13 +27,13 @@ export async function createProjectMembershipsOnSignup(user: {});}- // LANGFUSE_DEFAULT_ORG_ID+ // self-hosted: LANGFUSE_DEFAULT_ORG_IDconst defaultOrg = env.LANGFUSE_DEFAULT_ORG_ID- ? (await prisma.organization.findUnique({+ ? ((await prisma.organization.findUnique({where: {id: env.LANGFUSE_DEFAULT_ORG_ID,},- })) ?? undefined+ })) ?? undefined): undefined;const defaultOrgMembership =defaultOrg !== undefined@@ -46,13 +46,13 @@ export async function createProjectMembershipsOnSignup(user: {}): undefined;- // LANGFUSE_DEFAULT_PROJECT_ID+ // self-hosted: LANGFUSE_DEFAULT_PROJECT_IDconst defaultProject = env.LANGFUSE_DEFAULT_PROJECT_ID- ? (await prisma.project.findUnique({+ ? ((await prisma.project.findUnique({where: {id: env.LANGFUSE_DEFAULT_PROJECT_ID,},- })) ?? undefined+ })) ?? undefined): undefined;if (defaultProject !== undefined) {if (defaultOrgMembership) {diff --git a/web/src/features/entitlements/README.md b/web/src/features/entitlements/README.mdindex 4aa89b5b9a..5ca6b64dd5 100644--- a/web/src/features/entitlements/README.md+++ b/web/src/features/entitlements/README.md@@ -4,12 +4,21 @@ This feature allows to control for availability of features. Entitlements are ma## Concepts-- `Plan`: A plan is a a tier of features. Eg. `oss`, `cloud:pro`, `self-hosted:enterprise`. They are managed in `constants/plans.ts`.+- `Plan`: A plan is a a tier of features. Eg. `oss`, `cloud:pro`, `self-hosted:enterprise`. They are managed in `plans.ts`.- `Entitlement`: An entitlement is a feature that is available to a user. Eg. `playground`. They are managed in `constants/entitlements.ts`. `entitlements.ts` also includes the mapping of entitlements to plans.+ - `EntitlementLimit`: An entitlement limit is a limit on the number of resources that can be created/used. Eg. `annotation-queue-count`. They are managed in `constants/entitlements.ts`.## How it works-- Plan is added to the organization object on the JWT via NextAuth.-- Mapping to entitlements+- Plan+ - Cloud: added to the organization object on the JWT via NextAuth+ - Self-hosted+ - Added to JWT via NextAuth on `environment` as `selfHostedInstancePlan`+ - In addition, also added to the organization object on the JWT via NextAuth+ - Available based on license key outside of TRPC apis and react hooks via `getSelfHostedInstancePlanServerSide`+ - Use of plan+ - Hook: `usePlan`+ - Server side: `getOrganizationPlanServerSide` based on cloudConfig, or `getSelfHostedInstancePlanServerSide` for instance-level plan+- Use of Entitlements- Client side: react hooks in `hooks.ts` make entitlements of current organization available to the components.- - Server side: `hasEntitlement.ts` allows to check for an entitlement given a session user object.+ - Server side: `hasEntitlement.ts` and `hasEntitlementLimit.ts` allow to check for entitlements and entitlement limits given a session user object.diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.tsindex 3724eb44b2..599b9a28c6 100644--- a/web/src/features/entitlements/constants/entitlements.ts+++ b/web/src/features/entitlements/constants/entitlements.ts@@ -1,5 +1,6 @@import { type Plan } from "@langfuse/shared";+// Entitlements: Binary feature accessconst entitlements = [// features"playground",@@ -7,11 +8,11 @@ const entitlements = ["rbac-project-roles","cloud-billing","integration-posthog",- "batch-export","annotation-queues",- "experiments",+ "self-host-ui-customization",+ "self-host-allowed-organization-creators",+ "prompt-experiments",] as const;-export type Entitlement = (typeof entitlements)[number];const cloudAllPlansEntitlements: Entitlement[] = [@@ -19,20 +20,104 @@ const cloudAllPlansEntitlements: Entitlement[] = ["model-based-evaluations","cloud-billing","integration-posthog",- "batch-export","annotation-queues",- "experiments",+ "prompt-experiments",];-export const entitlementAccess: Record<Plan, Entitlement[]> = {- oss: [],- "cloud:hobby": [...cloudAllPlansEntitlements],- "cloud:pro": [...cloudAllPlansEntitlements],- "cloud:team": [...cloudAllPlansEntitlements, "rbac-project-roles"],- "self-hosted:enterprise": [- "annotation-queues",- "playground",- "rbac-project-roles",- // `LANGFUSE_ALLOWED_ORGANIZATION_CREATORS` -> directly checked on instance level in auth.ts- ],+// Entitlement Limits: Limits on the number of resources that can be created/used+const entitlementLimits = [+ "annotation-queue-count",+ "organization-member-count",+ "data-access-days",+ "model-based-evaluations-count-evaluators",+ "prompt-management-count-prompts",+] as const;+export type EntitlementLimit = (typeof entitlementLimits)[number];++export type EntitlementLimits = Record<+ EntitlementLimit,+ | number // if limited+ | false // unlimited+>;++export const entitlementAccess: Record<+ Plan,+ {+ entitlements: Entitlement[];+ entitlementLimits: EntitlementLimits;+ }+> = {+ "cloud:hobby": {+ entitlements: [...cloudAllPlansEntitlements],+ entitlementLimits: {+ "organization-member-count": 2,+ "data-access-days": 30,+ "annotation-queue-count": 1,+ "model-based-evaluations-count-evaluators": 1,+ "prompt-management-count-prompts": false,+ },+ },+ "cloud:pro": {+ entitlements: [...cloudAllPlansEntitlements],+ entitlementLimits: {+ "annotation-queue-count": 3,+ "organization-member-count": false,+ "data-access-days": false,+ "model-based-evaluations-count-evaluators": false,+ "prompt-management-count-prompts": false,+ },+ },+ "cloud:team": {+ entitlements: [...cloudAllPlansEntitlements, "rbac-project-roles"],+ entitlementLimits: {+ "annotation-queue-count": false,+ "organization-member-count": false,+ "data-access-days": false,+ "model-based-evaluations-count-evaluators": false,+ "prompt-management-count-prompts": false,+ },+ },+ oss: {+ entitlements: [],+ entitlementLimits: {+ "annotation-queue-count": 0,+ "organization-member-count": false,+ "data-access-days": false,+ "model-based-evaluations-count-evaluators": false,+ "prompt-management-count-prompts": false,+ },+ },+ "self-hosted:pro": {+ entitlements: [+ "annotation-queues",+ "model-based-evaluations",+ "playground",+ "prompt-experiments",+ ],+ entitlementLimits: {+ "annotation-queue-count": false,+ "organization-member-count": false,+ "data-access-days": false,+ "model-based-evaluations-count-evaluators": false,+ "prompt-management-count-prompts": false,+ },+ },+ "self-hosted:enterprise": {+ entitlements: [+ "annotation-queues",+ "model-based-evaluations",+ "playground",+ "prompt-experiments",+ "rbac-project-roles",+ "self-host-allowed-organization-creators",+ "self-host-ui-customization",+ ],+ entitlementLimits: {+ "annotation-queue-count": false,+ "organization-member-count": false,+ "data-access-days": false,+ "model-based-evaluations-count-evaluators": false,+ "prompt-management-count-prompts": false,+ },+ },};diff --git a/web/src/features/entitlements/hooks.ts b/web/src/features/entitlements/hooks.tsindex 4f3f934e5c..ea82dd99ed 100644--- a/web/src/features/entitlements/hooks.ts+++ b/web/src/features/entitlements/hooks.ts@@ -1,20 +1,27 @@import {entitlementAccess,+ type EntitlementLimits,type Entitlement,+ type EntitlementLimit,} from "@/src/features/entitlements/constants/entitlements";import { type Plan } from "@langfuse/shared";import { useSession } from "next-auth/react";import { useRouter } from "next/router";/**- * Hook to get the plan of the current organization or project.+ * Hook to get the plan of the current organization or self-hosted instance.*/-export const useOrganizationPlan = (): Plan | undefined => {+export const usePlan = (): Plan | undefined => {const router = useRouter();const session = useSession();const projectId = router.query.projectId;const organizationId = router.query.organizationId;+ // if on a self-hosted instance with an active license, get the plan of the self-hosted instance+ const selfHostedInstancePlan =+ session.data?.environment.selfHostedInstancePlan;+ if (selfHostedInstancePlan) return selfHostedInstancePlan;+// if on an organization page, get the plan of the organizationif (organizationId) {const org = session.data?.user?.organizations.find(@@ -35,22 +42,44 @@ export const useOrganizationPlan = (): Plan | undefined => {};/**- * Hook to get the entitlements of the current organization.+ * Hook to get the entitlements of the current organization or self-hosted instance.*/-export const useOrgEntitlements = (): Entitlement[] => {- const plan = useOrganizationPlan();- const availableEntitlements = entitlementAccess[plan ?? "oss"];+export const useEntitlements = (): Entitlement[] => {+ const plan = usePlan();+ const availableEntitlements = entitlementAccess[plan ?? "oss"].entitlements;return availableEntitlements;};/**- * Hook to check if the current organization has a specific entitlement.+ * Hook to check if the current organization or self-hosted instance has a specific entitlement.*/-export const useHasOrgEntitlement = (entitlement: Entitlement): boolean => {- const orgEntitlements = useOrgEntitlements();-+export const useHasEntitlement = (entitlement: Entitlement): boolean => {+ const entitlements = useEntitlements();const session = useSession();if (session.data?.user?.admin) return true;+ return entitlements.includes(entitlement);+};++/**+ * Hook to get the entitlement limits of the current organization or self-hosted instance.+ * @returns the entitlement limits of the current organization or self-hosted instance, including values of limits and false if unlimited.+ */+export const useEntitlementLimits = (): EntitlementLimits => {+ const plan = usePlan();+ return entitlementAccess[plan ?? "oss"].entitlementLimits;+};++/**+ * Hook to use the entitlement limit of the current organization or self-hosted instance.+ * @returns the limit value or false if unlimited+ */+export const useEntitlementLimit = (+ limit: EntitlementLimit,+): number | false => {+ const limits = useEntitlementLimits();++ const session = useSession();+ if (session.data?.user?.admin) return false;- return orgEntitlements.includes(entitlement);+ return limits[limit];};diff --git a/web/src/features/entitlements/server/getOrganizationPlan.ts b/web/src/features/entitlements/server/getPlan.tssimilarity index 71%rename from web/src/features/entitlements/server/getOrganizationPlan.tsrename to web/src/features/entitlements/server/getPlan.tsindex de9c8f07d0..49f0dac9a2 100644--- a/web/src/features/entitlements/server/getOrganizationPlan.ts+++ b/web/src/features/entitlements/server/getPlan.ts@@ -6,7 +6,9 @@ import { type CloudConfigSchema } from "@langfuse/shared";/*** Get the plan of the organization based on the cloud configuration. Used to add this plan to the organization object in JWT via NextAuth.*/-export function getOrganizationPlan(cloudConfig?: CloudConfigSchema): Plan {+export function getOrganizationPlanServerSide(+ cloudConfig?: CloudConfigSchema,+): Plan {if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {// in dev, grant team plan to all organizations// if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV") {@@ -38,8 +40,22 @@ export function getOrganizationPlan(cloudConfig?: CloudConfigSchema): Plan {return "cloud:hobby";}- if (env.LANGFUSE_EE_LICENSE_KEY !== undefined)- return "self-hosted:enterprise";+ const selfHostedPlan = getSelfHostedInstancePlanServerSide();+ if (selfHostedPlan) {+ return selfHostedPlan;+ }return "oss";}++export function getSelfHostedInstancePlanServerSide(): Plan | null {+ const licenseKey = env.LANGFUSE_EE_LICENSE_KEY;+ if (!licenseKey) return null;+ if (licenseKey.startsWith("langfuse_ee_")) {+ return "self-hosted:enterprise";+ }+ if (licenseKey.startsWith("langfuse_pro_")) {+ return "self-hosted:pro";+ }+ return null;+}diff --git a/web/src/features/entitlements/server/hasEntitlement.ts b/web/src/features/entitlements/server/hasEntitlement.tsindex 7e0039bc4b..8d8db66cb5 100644--- a/web/src/features/entitlements/server/hasEntitlement.ts+++ b/web/src/features/entitlements/server/hasEntitlement.ts@@ -4,6 +4,7 @@ import {} from "@/src/features/entitlements/constants/entitlements";import { TRPCError } from "@trpc/server";import { type User } from "next-auth";+import { type Plan } from "@langfuse/shared";type HasEntitlementParams = {entitlement: Entitlement;@@ -22,8 +23,21 @@ export const hasEntitlement = (p: HasEntitlementParams): Boolean => {): p.sessionUser.organizations.find((org) => org.id === p.orgId);const plan = org?.plan ?? "oss";- const availableEntitlements = entitlementAccess[plan];- return availableEntitlements.includes(p.entitlement);+ return hasEntitlementBasedOnPlan({ plan, entitlement: p.entitlement });+};++/**+ * Check if user has access to a specific entitlement based on the plan.+ */+export const hasEntitlementBasedOnPlan = ({+ plan,+ entitlement,+}: {+ plan: Plan | null;+ entitlement: Entitlement;+}) => {+ if (!plan) return false;+ return entitlementAccess[plan].entitlements.includes(entitlement);};export const throwIfNoEntitlement = (p: HasEntitlementParams) => {diff --git a/web/src/features/entitlements/server/hasEntitlementLimit.ts b/web/src/features/entitlements/server/hasEntitlementLimit.tsnew file mode 100644index 0000000000..38484157d1--- /dev/null+++ b/web/src/features/entitlements/server/hasEntitlementLimit.ts@@ -0,0 +1,72 @@+import {+ entitlementAccess,+ type EntitlementLimit,+} from "@/src/features/entitlements/constants/entitlements";+import { type Plan } from "@langfuse/shared";+import { TRPCError } from "@trpc/server";+import { type User } from "next-auth";++type HasEntitlementLimitParams = {+ entitlementLimit: EntitlementLimit;+ sessionUser: User;+} & ({ projectId: string } | { orgId: string });++/**+ * Get the limit for a specific entitlement based on the session user (to be used server-side).+ * @returns false if unlimited, or a number representing the limit+ */+export const hasEntitlementLimit = (+ p: HasEntitlementLimitParams,+): number | false => {+ if (p.sessionUser.admin) return false; // Admins have unlimited access++ const org =+ "projectId" in p+ ? p.sessionUser.organizations.find((org) =>+ org.projects.some((proj) => proj.id === p.projectId),+ )+ : p.sessionUser.organizations.find((org) => org.id === p.orgId);++ const plan = org?.plan ?? "oss";+ return hasEntitlementLimitBasedOnPlan({+ plan,+ entitlementLimit: p.entitlementLimit,+ });+};++export const hasEntitlementLimitBasedOnPlan = ({+ plan,+ entitlementLimit,+}: {+ plan: Plan | null;+ entitlementLimit: EntitlementLimit;+}) => {+ return entitlementAccess[plan ?? "oss"].entitlementLimits[entitlementLimit];+};++/**+ * Check if a specific usage is within the entitlement limit+ * @returns true if usage is allowed, false if it exceeds the limit+ */+export const isWithinEntitlementLimit = (+ p: HasEntitlementLimitParams & { currentUsage: number },+): boolean => {+ const limit = hasEntitlementLimit(p);+ if (limit === false) return true; // No limit+ return p.currentUsage < limit;+};++/**+ * Throws if usage exceeds the entitlement limit+ */+export const throwIfExceedsLimit = (+ p: HasEntitlementLimitParams & { currentUsage: number },+) => {+ if (!isWithinEntitlementLimit(p)) {+ const limit = hasEntitlementLimit(p);+ throw new TRPCError({+ code: "FORBIDDEN",+ message: `Usage (${p.currentUsage}) exceeds the limit (${limit}) for entitlement: ${p.entitlementLimit}`,+ });+ }+};diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsxindex 2973252e01..9ea54eb891 100644--- a/web/src/features/prompts/components/prompt-detail.tsx+++ b/web/src/features/prompts/components/prompt-detail.tsx@@ -40,7 +40,7 @@ import {} from "@/src/components/ui/dialog";import { CreateExperimentsForm } from "@/src/ee/features/experiments/components/CreateExperimentsForm";import { useState } from "react";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";export const PromptDetail = () => {@@ -51,7 +51,7 @@ export const PromptDetail = () => {"version",NumberParam,);- const hasEntitlement = useHasOrgEntitlement("experiments");+ const hasEntitlement = useHasEntitlement("prompt-experiments");const [isCreateExperimentDialogOpen, setIsCreateExperimentDialogOpen] =useState(false);const hasAccess = useHasProjectAccess({@@ -60,7 +60,7 @@ export const PromptDetail = () => {});const hasExperimentWriteAccess = useHasProjectAccess({projectId,- scope: "experiments:CUD",+ scope: "promptExperiments:CUD",});const promptHistory = api.prompts.allVersions.useQuery({diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsxindex cf174be2b7..cb2f622ebc 100644--- a/web/src/features/prompts/components/prompts-table.tsx+++ b/web/src/features/prompts/components/prompts-table.tsx@@ -1,11 +1,9 @@-import { LockIcon, PlusIcon } from "lucide-react";-import Link from "next/link";+import { PlusIcon } from "lucide-react";import { useEffect } from "react";import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";import { DataTable } from "@/src/components/table/data-table";import TableLink from "@/src/components/table/table-link";import { type LangfuseColumnDef } from "@/src/components/table/types";-import { Button } from "@/src/components/ui/button";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { DeletePrompt } from "@/src/features/prompts/components/delete-prompt";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";@@ -23,6 +21,8 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePosimport { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";import { Skeleton } from "@/src/components/ui/skeleton";import { useDebounce } from "@/src/hooks/useDebounce";+import { ActionButton } from "@/src/components/ActionButton";+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";type PromptTableRow = {name: string;@@ -129,6 +129,8 @@ export function PromptTable() {const capture = usePostHogClientCapture();const totalCount = prompts.data?.totalCount ?? null;+ const promptLimit = useEntitlementLimit("prompt-management-count-prompts");+useEffect(() => {if (prompts.isSuccess) {setDetailPageList(@@ -251,29 +253,19 @@ export function PromptTable() {setFilterState={useDebounce(setFilterState)}columnsWithCustomSelect={["labels", "tags"]}actionButtons={- <Link href={`/project/${projectId}/prompts/new`}>- <Button- variant="secondary"- disabled={!hasCUDAccess}- aria-label="Create New Prompt"- onClick={() => {- capture("prompts:new_form_open");- }}- >- {hasCUDAccess ? (- <PlusIcon- className="-ml-0.5 mr-1.5 h-4 w-4"- aria-hidden="true"- />- ) : (- <LockIcon- className="-ml-0.5 mr-1.5 h-3 w-3"- aria-hidden="true"- />- )}- New prompt- </Button>- </Link>+ <ActionButton+ icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}+ hasAccess={hasCUDAccess}+ href={`/project/${projectId}/prompts/new`}+ variant="secondary"+ limit={promptLimit}+ limitValue={totalCount ?? 0}+ onClick={() => {+ capture("prompts:new_form_open");+ }}+ >+ New prompt+ </ActionButton>}/><DataTablediff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsxindex e187cd8777..2ef9c26642 100644--- a/web/src/features/public-api/components/LLMApiKeyList.tsx+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx@@ -26,7 +26,7 @@ import { api } from "@/src/utils/api";import { DialogDescription } from "@radix-ui/react-dialog";import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";import { CreateLLMApiKeyDialog } from "./CreateLLMApiKeyDialog";-import { useOrgEntitlements } from "@/src/features/entitlements/hooks";+import { useEntitlements } from "@/src/features/entitlements/hooks";export function LlmApiKeyList(props: { projectId: string }) {const hasAccess = useHasProjectAccess({@@ -35,7 +35,7 @@ export function LlmApiKeyList(props: { projectId: string }) {});// only show if the user has access to features that require LLM API keys- const entitlements = useOrgEntitlements();+ const entitlements = useEntitlements();const isAvailable =entitlements.includes("playground") ||entitlements.includes("model-based-evaluations");diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.tsindex 4a251100f1..8b2e3953f2 100644--- a/web/src/features/public-api/server/RateLimitService.ts+++ b/web/src/features/public-api/server/RateLimitService.ts@@ -184,6 +184,7 @@ const getPlanBasedRateLimitConfig = (): z.infer<typeof RateLimitConfig> => {switch (plan) {case "oss":+ case "self-hosted:pro":case "self-hosted:enterprise":return {resource,diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 00d6f3064b..ca4427d76f 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -16,7 +16,7 @@ import {} from "@langfuse/shared/src/db";import { isPrismaException } from "@/src/utils/exceptions";import { type Redis } from "ioredis";-import { getOrganizationPlan } from "@/src/features/entitlements/server/getOrganizationPlan";+import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";import { API_KEY_NON_EXISTENT } from "@langfuse/shared/src/server";import { type z } from "zod";import { CloudConfigSchema, isPlan } from "@langfuse/shared";@@ -211,7 +211,7 @@ export class ApiAuthService {projectId: dbKey.projectId,accessLevel: "scores",orgId: dbKey.project.organization.id,- plan: getOrganizationPlan(cloudConfig),+ plan: getOrganizationPlanServerSide(cloudConfig),rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],},};@@ -384,7 +384,7 @@ export const convertToRedisRepresentation = (...apiKeyAndOrganisation,createdAt: apiKeyAndOrganisation.createdAt?.toISOString(),orgId,- plan: getOrganizationPlan(parsedCloudConfig),+ plan: getOrganizationPlanServerSide(parsedCloudConfig),rateLimitOverrides: parsedCloudConfig?.rateLimitOverrides,});diff --git a/web/src/features/rbac/components/CreateProjectMemberButton.tsx b/web/src/features/rbac/components/CreateProjectMemberButton.tsxindex f15b526243..874631ce44 100644--- a/web/src/features/rbac/components/CreateProjectMemberButton.tsx+++ b/web/src/features/rbac/components/CreateProjectMemberButton.tsx@@ -31,9 +31,13 @@ import { Input } from "@/src/components/ui/input";import { Role } from "@langfuse/shared";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import {+ useHasEntitlement,+ useEntitlementLimit,+} from "@/src/features/entitlements/hooks";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";+import { ActionButton } from "@/src/components/ActionButton";const formSchema = z.object({email: z.string().trim().email(),@@ -55,7 +59,24 @@ export function CreateProjectMemberButton(props: {projectId: props.project?.id,scope: "projectMembers:CUD",});- const hasProjectRoleEntitlement = useHasOrgEntitlement("rbac-project-roles");+ const orgMemberLimit = useEntitlementLimit("organization-member-count");+ const orgMemberCount = api.members.allFromOrg.useQuery(+ {+ orgId: props.orgId,+ },+ {+ enabled: hasOrgAccess,+ },+ ).data?.totalCount;+ const inviteCount = api.members.allInvitesFromOrg.useQuery(+ {+ orgId: props.orgId,+ },+ {+ enabled: hasOrgAccess,+ },+ ).data?.totalCount;+ const hasProjectRoleEntitlement = useHasEntitlement("rbac-project-roles");const hasOnlySingleProjectAccess =!hasOrgAccess && hasProjectAccess && hasProjectRoleEntitlement;@@ -111,16 +132,18 @@ export function CreateProjectMemberButton(props: {<><Dialog open={open} onOpenChange={setOpen}><DialogTrigger asChild>- <Button+ <ActionButtonvariant="secondary"loading={mutCreateProjectMember.isLoading}- disabled={!hasOrgAccess && !hasOnlySingleProjectAccess}+ hasAccess={hasOrgAccess || hasOnlySingleProjectAccess}+ limit={orgMemberLimit}+ limitValue={(orgMemberCount ?? 0) + (inviteCount ?? 0)}+ icon={<PlusIcon className="h-5 w-5" aria-hidden="true" />}>- <PlusIcon className="-ml-0.5 mr-1.5 h-5 w-5" aria-hidden="true" />{hasOnlySingleProjectAccess? "Add project member": "Add new member"}- </Button>+ </ActionButton></DialogTrigger><DialogContent><DialogHeader>diff --git a/web/src/features/rbac/components/MembersTable.tsx b/web/src/features/rbac/components/MembersTable.tsxindex 354da5f24a..4737b83dfc 100644--- a/web/src/features/rbac/components/MembersTable.tsx+++ b/web/src/features/rbac/components/MembersTable.tsx@@ -23,7 +23,7 @@ import { Trash } from "lucide-react";import { useSession } from "next-auth/react";import { useQueryParams, withDefault, NumberParam } from "use-query-params";import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";@@ -116,7 +116,7 @@ export function MembersTable({scope: "projectMembers:CUD",});- const projectRolesEntitlement = useHasOrgEntitlement("rbac-project-roles");+ const projectRolesEntitlement = useHasEntitlement("rbac-project-roles");const columns: LangfuseColumnDef<MembersTableRow>[] = [{@@ -235,7 +235,7 @@ export function MembersTable({"meta",) as MembersTableRow["meta"];- if (!projectRolesEntitlement) return "N/A";+ if (!projectRolesEntitlement) return "N/A on plan";return (<ProjectRoleDropdowndiff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tsindex 538abe709c..9ffe45b744 100644--- a/web/src/features/rbac/constants/projectAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -49,8 +49,8 @@ const projectScopes = ["comments:CUD","comments:read",- "experiments:CUD",- "experiments:read",+ "promptExperiments:CUD",+ "promptExperiments:read",] as const;// type string of all Resource:Action, e.g. "members:read"@@ -91,8 +91,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"comments:read","annotationQueues:read","annotationQueues:CUD",- "experiments:CUD",- "experiments:read",+ "promptExperiments:CUD",+ "promptExperiments:read",],ADMIN: ["project:read",@@ -127,8 +127,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"comments:read","annotationQueues:read","annotationQueues:CUD",- "experiments:CUD",- "experiments:read",+ "promptExperiments:CUD",+ "promptExperiments:read",],MEMBER: ["project:read",@@ -154,8 +154,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"comments:read","annotationQueues:read","annotationQueues:CUD",- "experiments:CUD",- "experiments:read",+ "promptExperiments:CUD",+ "promptExperiments:read",],VIEWER: ["project:read",@@ -167,7 +167,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"llmApiKeys:read","comments:read","annotationQueues:read",- "experiments:read",+ "promptExperiments:read",],NONE: [],};diff --git a/web/src/pages/organization/[organizationId]/settings/index.tsx b/web/src/pages/organization/[organizationId]/settings/index.tsxindex f138128edf..b9a84b292b 100644--- a/web/src/pages/organization/[organizationId]/settings/index.tsx+++ b/web/src/pages/organization/[organizationId]/settings/index.tsx@@ -9,14 +9,14 @@ import { useRouter } from "next/router";import { SettingsDangerZone } from "@/src/components/SettingsDangerZone";import { DeleteOrganizationButton } from "@/src/features/organizations/components/DeleteOrganizationButton";import { BillingSettings } from "@/src/ee/features/billing/components/BillingSettings";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { ScrollScreenPage } from "@/src/components/layouts/scroll-screen-page";const OrgSettingsPage = () => {const organization = useQueryOrganization();const router = useRouter();const { page } = router.query;- const showBillingSettings = useHasOrgEntitlement("cloud-billing");+ const showBillingSettings = useHasEntitlement("cloud-billing");if (!organization) return null;diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsxindex 1401697ae5..37237f33e8 100644--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx@@ -24,7 +24,7 @@ import {} from "@/src/components/ui/dialog";import { CreateExperimentsForm } from "@/src/ee/features/experiments/components/CreateExperimentsForm";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import Link from "next/link";export default function DatasetCompare() {@@ -43,9 +43,9 @@ export default function DatasetCompare() {const hasExperimentWriteAccess = useHasProjectAccess({projectId,- scope: "experiments:CUD",+ scope: "promptExperiments:CUD",});- const hasEntitlement = useHasOrgEntitlement("experiments");+ const hasEntitlement = useHasEntitlement("prompt-experiments");const dataset = api.datasets.byId.useQuery({datasetId,diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsxindex 1091d604ac..791b185a59 100644--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx@@ -16,7 +16,7 @@ import { CommandItem } from "@/src/components/ui/command";import { ExternalLink, FlaskConical } from "lucide-react";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useMemo } from "react";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import {Dialog,DialogContent,@@ -34,8 +34,8 @@ export default function Dataset() {const projectId = router.query.projectId as string;const datasetId = router.query.datasetId as string;const utils = api.useUtils();- const hasEntitlement = useHasOrgEntitlement("model-based-evaluations");- const hasExperimentEntitlement = useHasOrgEntitlement("experiments");+ const hasEntitlement = useHasEntitlement("model-based-evaluations");+ const hasExperimentEntitlement = useHasEntitlement("prompt-experiments");const [isCreateExperimentDialogOpen, setIsCreateExperimentDialogOpen] =useState(false);@@ -51,7 +51,7 @@ export default function Dataset() {const hasExperimentWriteAccess = useHasProjectAccess({projectId,- scope: "experiments:CUD",+ scope: "promptExperiments:CUD",});const evaluators = api.evals.jobConfigsByDatasetId.useQuery(diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex ec94fe0d68..4bd276c237 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -28,6 +28,7 @@ import SetupTracingButton from "@/src/features/setup/components/SetupTracingButtimport { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";import { ScrollScreenPage } from "@/src/components/layouts/scroll-screen-page";import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";export default function Dashboard() {const router = useRouter();@@ -37,6 +38,8 @@ export default function Dashboard() {const uiCustomization = useUiCustomization();+ const lookbackLimit = useEntitlementLimit("data-access-days");+const session = useSession();const disableExpensiveDashboardComponents =session.data?.environment.disableExpensivePostgresQueries ?? true;@@ -152,6 +155,16 @@ export default function Dashboard() {setDateRangeAndOption={useDebounce(setDateRangeAndOption)}selectedOption={selectedOption}className="my-0 max-w-full overflow-x-auto"+ disabled={+ lookbackLimit+ ? {+ before: new Date(+ new Date().getTime() -+ lookbackLimit * 24 * 60 * 60 * 1000,+ ),+ }+ : undefined+ }/><PopoverFilterBuildercolumns={filterColumns}diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsxindex 092ea32267..2fd410b4d2 100644--- a/web/src/pages/project/[projectId]/settings/index.tsx+++ b/web/src/pages/project/[projectId]/settings/index.tsx@@ -16,7 +16,7 @@ import { PostHogLogo } from "@/src/components/PosthogLogo";import { Card } from "@/src/components/ui/card";import { ScoreConfigSettings } from "@/src/features/scores/components/ScoreConfigSettings";import { TransferProjectButton } from "@/src/features/projects/components/TransferProjectButton";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useRouter } from "next/router";import { SettingsDangerZone } from "@/src/components/SettingsDangerZone";@@ -24,7 +24,7 @@ import { SettingsDangerZone } from "@/src/components/SettingsDangerZone";export default function SettingsPage() {const { project, organization } = useQueryProject();const router = useRouter();- const showBillingSettings = useHasOrgEntitlement("cloud-billing");+ const showBillingSettings = useHasEntitlement("cloud-billing");if (!project || !organization) return null;return (<div className="lg:container">@@ -127,7 +127,7 @@ export default function SettingsPage() {}const Integrations = (props: { projectId: string }) => {- const entitled = useHasOrgEntitlement("integration-posthog");+ const entitled = useHasEntitlement("integration-posthog");const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "integrations:CRUD",diff --git a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsxindex 7475947e49..f7f1328019 100644--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx@@ -13,7 +13,7 @@ import {import { Input } from "@/src/components/ui/input";import { PasswordInput } from "@/src/components/ui/password-input";import { Switch } from "@/src/components/ui/switch";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";@@ -30,7 +30,7 @@ import { type z } from "zod";export default function PosthogIntegrationSettings() {const router = useRouter();const projectId = router.query.projectId as string;- const entitled = useHasOrgEntitlement("integration-posthog");+ const entitled = useHasEntitlement("integration-posthog");const hasAccess = useHasProjectAccess({projectId,scope: "integrations:CRUD",diff --git a/web/src/server/api/routers/batchExport.ts b/web/src/server/api/routers/batchExport.tsindex a16606a424..62d62792ff 100644--- a/web/src/server/api/routers/batchExport.ts+++ b/web/src/server/api/routers/batchExport.ts@@ -1,4 +1,3 @@-import { env } from "@/src/env.mjs";import { auditLog } from "@/src/features/audit-logs/auditLog";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {@@ -14,19 +13,12 @@ import {QueueJobs,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";-import { redis } from "@langfuse/shared/src/server";-import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";export const batchExportRouter = createTRPCRouter({create: protectedProjectProcedure.input(CreateBatchExportSchema).mutation(async ({ input, ctx }) => {try {- throwIfNoEntitlement({- entitlement: "batch-export",- sessionUser: ctx.session.user,- projectId: input.projectId,- });// Check permissions, esp. projectIdthrowIfNoProjectAccess({session: ctx.session,@@ -72,15 +64,12 @@ export const batchExportRouter = createTRPCRouter({},};- if (redis && env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {- await BatchExportQueue.getInstance()?.add(event.name, {- id: event.payload.batchExportId, // Use the batchExportId to deduplicate when the same job is sent multiple times- name: QueueJobs.BatchExportJob,- timestamp: new Date(),- payload: event.payload,- });- }- return;+ await BatchExportQueue.getInstance()?.add(event.name, {+ id: event.payload.batchExportId, // Use the batchExportId to deduplicate when the same job is sent multiple times+ name: QueueJobs.BatchExportJob,+ timestamp: new Date(),+ payload: event.payload,+ });} catch (e) {logger.error(e);if (e instanceof TRPCError) {diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex c3bdefc303..3ac3f24d6d 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -39,14 +39,23 @@ import {instrumentAsync,logger,} from "@langfuse/shared/src/server";-import { getOrganizationPlan } from "@/src/features/entitlements/server/getOrganizationPlan";+import {+ getOrganizationPlanServerSide,+ getSelfHostedInstancePlanServerSide,+} from "@/src/features/entitlements/server/getPlan";import { projectRoleAccessRights } from "@/src/features/rbac/constants/projectAccessRights";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";function canCreateOrganizations(userEmail: string | null): boolean {- // if no allowlist is set or no active EE key, allow all users to create organizations+ const instancePlan = getSelfHostedInstancePlanServerSide();++ // if no allowlist is set or no entitlement for self-host-allowed-organization-creators, allow all users to create organizationsif (!env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS ||- !env.LANGFUSE_EE_LICENSE_KEY+ !hasEntitlementBasedOnPlan({+ plan: instancePlan,+ entitlement: "self-host-allowed-organization-creators",+ }))return true;@@ -376,7 +385,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES === "true",// 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)- eeEnabled: env.LANGFUSE_EE_LICENSE_KEY !== undefined,+ selfHostedInstancePlan: getSelfHostedInstancePlanServerSide(),},user:dbUser !== null@@ -422,7 +431,9 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {// Enables features/entitlements based on the plan of the organization, either cloud or EE version when self-hosting// If you edit this line, you risk executing code that is not MIT licensed (contained in /ee folders, see LICENSE)- plan: getOrganizationPlan(parsedCloudConfig.data),+ plan: getOrganizationPlanServerSide(+ parsedCloudConfig.data,+ ),};},),diff --git a/web/src/utils/date-range-utils.ts b/web/src/utils/date-range-utils.tsindex f1cba7af80..16a37a8c1c 100644--- a/web/src/utils/date-range-utils.ts+++ b/web/src/utils/date-range-utils.ts@@ -76,11 +76,11 @@ export const dashboardDateRangeAggregationSettings: DashboardDateRangeAggregatio},"3 months": {date_trunc: "week",- minutes: 3 * 28 * 24 * 60,+ minutes: 3 * 30 * 24 * 60,},"1 month": {date_trunc: "day",- minutes: 28 * 24 * 60,+ minutes: 30 * 24 * 60,},"7 days": {date_trunc: "day",@@ -121,14 +121,27 @@ export const SelectedTimeOptionSchema = z]).optional();+export const isDashboardDateRangeOptionAvailable = ({+ option,+ limitDays,+}: {+ option: DashboardDateRangeAggregationOption;+ limitDays: number | false;+}) => {+ if (limitDays === false) return true;++ const { minutes } = dashboardDateRangeAggregationSettings[option];+ return limitDays >= minutes / (24 * 60);+};+type SelectedTimeOption = z.infer<typeof SelectedTimeOptionSchema>;const TABLE_DATE_RANGE_AGGREGATION_SETTINGS = new Map<TableDateRangeAggregationOption,number | null>([- ["3 months", 3 * 28 * 24 * 60],- ["1 month", 28 * 24 * 60],+ ["3 months", 3 * 30 * 24 * 60],+ ["1 month", 30 * 24 * 60],["14 days", 14 * 24 * 60],["7 days", 7 * 24 * 60],["3 days", 3 * 24 * 60],@@ -139,6 +152,21 @@ const TABLE_DATE_RANGE_AGGREGATION_SETTINGS = new Map<["All time", null],]);+export const isTableDataRangeOptionAvailable = ({+ option,+ limitDays,+}: {+ option: TableDateRangeAggregationOption;+ limitDays: number | false;+}) => {+ if (limitDays === false) return true;++ const durationMinutes = TABLE_DATE_RANGE_AGGREGATION_SETTINGS.get(option);+ if (!durationMinutes) return false;++ return limitDays >= durationMinutes / (24 * 60);+};+export const getDateFromOption = (selectedTimeOption: SelectedTimeOption,): Date | undefined => {diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 0a3ff7adc3..95630129a2 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -22,8 +22,8 @@ declare module "next-auth" {// Run-time environment variables that need to be available client-sideenableExperimentalFeatures: boolean;disableExpensivePostgresQueries: boolean;- // Enables features that are only available under an enterprise license when self-hosting Langfuse- eeEnabled: boolean;+ // Enables features that are only available under an enterprise/commercial license when self-hosting Langfuse+ selfHostedInstancePlan: Plan | null;};}