🪢 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: add organizations (#2083)
Marc Klingend8d2a3c00c5f
diff --git a/.env.prod.example b/.env.prod.exampleindex c08d83d307..6b263b2d6c 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -98,6 +98,8 @@ ENCRYPTION_KEY="0000000000000000000000000000000000000000000000000000000000000000# Disable logging to `events` table in db# ENABLE_EVENT_LOG=false+# Allowlisted users that can create new organizations, by default all users can create organizations### START Envs to be deprecated in Langfuse v3.0@@ -139,6 +141,7 @@ ENCRYPTION_KEY="0000000000000000000000000000000000000000000000000000000000000000# TURNSTILE_SECRET_KEY=# Demo project that users can use to try the platform+# NEXT_PUBLIC_DEMO_ORG_ID=# NEXT_PUBLIC_DEMO_PROJECT_ID=# Crisp chatdiff --git a/ee/src/ee-license-check/index.ts b/ee/src/ee-license-check/index.tsindex a7ff09add7..8fdd4330d5 100644--- a/ee/src/ee-license-check/index.ts+++ b/ee/src/ee-license-check/index.ts@@ -1,4 +1,5 @@import { env } from "../env";export const isEeAvailable: boolean =- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined;+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined ||+ env.LANGFUSE_EE_LICENSE_KEY !== undefined;diff --git a/ee/src/env.ts b/ee/src/env.tsindex 20f76a8098..13f4e84ae0 100644--- a/ee/src/env.ts+++ b/ee/src/env.ts@@ -3,6 +3,7 @@ import { env as sharedEnv } from "@langfuse/shared";const EnvSchema = z.object({NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z.string().optional(),+ LANGFUSE_EE_LICENSE_KEY: z.string().optional(),});export const env = { ...sharedEnv, ...EnvSchema.parse(process.env) };diff --git a/ee/src/index.ts b/ee/src/index.tsindex d3ece4322b..e69de29bb2 100644--- a/ee/src/index.ts+++ b/ee/src/index.ts@@ -1 +0,0 @@-export { isEeAvailable } from "./ee-license-check";diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 93f26b0a6c..7ef15969d4 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -4,13 +4,14 @@ export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>: ColumnType<T, T | undefined, T>;export type Timestamp = ColumnType<Date, Date | string, Date | string>;-export const ProjectRole = {+export const Role = {OWNER: "OWNER",ADMIN: "ADMIN",MEMBER: "MEMBER",- VIEWER: "VIEWER"+ VIEWER: "VIEWER",+ NONE: "NONE"} as const;-export type ProjectRole = (typeof ProjectRole)[keyof typeof ProjectRole];+export type Role = (typeof Role)[keyof typeof Role];export const ObservationType = {SPAN: "SPAN",EVENT: "EVENT",@@ -90,8 +91,10 @@ export type AuditLog = {created_at: Generated<Timestamp>;updated_at: Generated<Timestamp>;user_id: string;- project_id: string;- user_project_role: ProjectRole;+ org_id: string;+ user_org_role: string;+ project_id: string | null;+ user_project_role: string | null;resource_type: string;resource_id: string;action: string;@@ -229,9 +232,11 @@ export type LlmApiKeys = {export type MembershipInvitation = {id: string;email: string;- role: ProjectRole;- project_id: string;- sender_id: string | null;+ org_id: string;+ org_role: Role;+ project_id: string | null;+ project_role: Role | null;+ invited_by_user_id: string | null;created_at: Generated<Timestamp>;updated_at: Generated<Timestamp>;};@@ -321,6 +326,21 @@ export type ObservationView = {latency: number | null;time_to_first_token: number | null;};+export type Organization = {+ id: string;+ name: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ cloud_config: unknown | null;+};+export type OrganizationMembership = {+ id: string;+ org_id: string;+ user_id: string;+ role: Role;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+};export type PosthogIntegration = {project_id: string;encrypted_posthog_api_key: string;@@ -331,15 +351,16 @@ export type PosthogIntegration = {};export type Project = {id: string;+ org_id: string;created_at: Generated<Timestamp>;updated_at: Generated<Timestamp>;name: string;- cloud_config: unknown | null;};export type ProjectMembership = {+ org_membership_id: string;project_id: string;user_id: string;- role: ProjectRole;+ role: Role;created_at: Generated<Timestamp>;updated_at: Generated<Timestamp>;};@@ -484,6 +505,8 @@ export type DB = {models: Model;observations: Observation;observations_view: ObservationView;+ organization_memberships: OrganizationMembership;+ organizations: Organization;posthog_integrations: PosthogIntegration;project_memberships: ProjectMembership;projects: Project;diff --git a/packages/shared/prisma/migrations/20240807111359_add_organizations_main_migration/migration.sql b/packages/shared/prisma/migrations/20240807111359_add_organizations_main_migration/migration.sqlnew file mode 100644index 0000000000..94ba9a5eca--- /dev/null+++ b/packages/shared/prisma/migrations/20240807111359_add_organizations_main_migration/migration.sql@@ -0,0 +1,164 @@+-- Table ORGANIZATIONS+-- Create empty table ORGANIZATIONS+CREATE TABLE "organizations" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "cloud_config" JSONB,++ CONSTRAINT "organizations_pkey" PRIMARY KEY ("id")+);+-- Backfill table ORGANIZATIONS: create a new organization for each project, move cloudConfig, and set the org_id on the project to project_id prefixed with 'o'+INSERT INTO "organizations" ("id", "name", "cloud_config", "created_at")+SELECT+ CONCAT('o', "id") as "id", -- This mapping is used in other migration steps as well, keep it consistent+ "name",+ "cloud_config",+ "created_at"+FROM "projects";+-- Drop column cloud_config from projects as it's now on organization level+ALTER TABLE "projects" DROP COLUMN "cloud_config";+++-- PROJECT.ORG_ID+-- Add org_id to projects+ALTER TABLE "projects" ADD COLUMN "org_id" TEXT;+-- Backfill: org_id on projects, set it to project_id prefixed with 'o'+UPDATE "projects"+SET "org_id" = CONCAT('o', "id");+-- Set not null after backfill+ALTER TABLE "projects" ALTER COLUMN "org_id" SET NOT NULL;+-- AddForeignKey+ALTER TABLE "projects" ADD CONSTRAINT "projects_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;+-- CreateIndex+CREATE INDEX "projects_org_id_idx" ON "projects"("org_id");+++-- ORGANIZATION MEMBERSHIPS+-- Create UserRole ENUM+CREATE TYPE "Role" AS ENUM ('OWNER', 'ADMIN', 'MEMBER', 'VIEWER', 'NONE');+-- Create empty table+CREATE TABLE "organization_memberships" (+ "id" TEXT NOT NULL,+ "org_id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "role" "Role" NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "organization_memberships_pkey" PRIMARY KEY ("id")+);+-- Add indexes+CREATE INDEX "organization_memberships_user_id_idx" ON "organization_memberships"("user_id");+CREATE INDEX "organization_memberships_org_id_idx" ON "organization_memberships"("org_id");+CREATE UNIQUE INDEX "organization_memberships_org_id_user_id_key" ON "organization_memberships"("org_id", "user_id");+-- AddForeignKey+ALTER TABLE "organization_memberships" ADD CONSTRAINT "organization_memberships_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;+-- AddForeignKey+ALTER TABLE "organization_memberships" ADD CONSTRAINT "organization_memberships_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;++++-- Migrate project memberships to organization memberships+INSERT INTO "organization_memberships" ("id", "org_id", "user_id", "role", "created_at", "updated_at")+SELECT+ md5(random()::text || clock_timestamp()::text || project_id::text || user_id::text)::uuid AS "id",+ CONCAT('o', "project_id") as "org_id",+ "user_id",+ "role"::text::"Role" as "role",+ "created_at",+ "updated_at"+FROM "project_memberships";++++-- Delete all project memberships after migration to organization memberships+DELETE FROM "project_memberships";++-- Add org_membership_id to project_memberships, ok to be not null as it's a new column on a now empty table+ALTER TABLE "project_memberships" ADD COLUMN "org_membership_id" TEXT NOT NULL;+-- Switch to new UserRole enum+ALTER TABLE "project_memberships" DROP COLUMN "role",+ADD COLUMN "role" "Role" NOT NULL;+-- AddForeignKey+ALTER TABLE "project_memberships" ADD CONSTRAINT "project_memberships_org_membership_id_fkey" FOREIGN KEY ("org_membership_id") REFERENCES "organization_memberships"("id") ON DELETE CASCADE ON UPDATE CASCADE;+-- CreateIndex+CREATE INDEX "project_memberships_project_id_idx" ON "project_memberships"("project_id");+-- CreateIndex+CREATE INDEX "project_memberships_org_membership_id_idx" ON "project_memberships"("org_membership_id");++++-- AUDIT LOGS+-- DropForeignKey, just index on these, should remain after project/org/user deletions+ALTER TABLE "audit_logs" DROP CONSTRAINT "audit_logs_user_id_fkey";+ALTER TABLE "audit_logs" DROP CONSTRAINT "audit_logs_project_id_fkey";+-- Drop not null on project level cols+ALTER TABLE "audit_logs" ALTER COLUMN "project_id" DROP NOT NULL;+ALTER TABLE "audit_logs" ALTER COLUMN "user_project_role" DROP NOT NULL;+-- Add org-level cols+ALTER TABLE "audit_logs" ADD COLUMN "org_id" TEXT;+ALTER TABLE "audit_logs" ADD COLUMN "user_org_role" TEXT;+-- Backfill org_id+UPDATE "audit_logs"+SET "org_id" = "projects"."org_id"+FROM "projects"+WHERE "audit_logs"."project_id" = "projects"."id";+-- Backfill user_org_role with value from user_project_role+UPDATE "audit_logs"+SET "user_org_role" = "user_project_role"::text::"Role";+-- Drop and recreate user_project_role column as text column going forward, empty for historical data as it's all on org level now+ALTER TABLE "audit_logs" DROP COLUMN "user_project_role";+ALTER TABLE "audit_logs" ADD COLUMN "user_project_role" TEXT; -- nullable+-- Add not null on org level cols+ALTER TABLE "audit_logs" ALTER COLUMN "org_id" SET NOT NULL;+ALTER TABLE "audit_logs" ALTER COLUMN "user_org_role" SET NOT NULL;+-- CreateIndex+CREATE INDEX "audit_logs_user_id_idx" ON "audit_logs"("user_id");+CREATE INDEX "audit_logs_org_id_idx" ON "audit_logs"("org_id");+++-- MEMBERSHIP INVITATIONS+-- Rename sender_id to invited_by_user_id+ALTER TABLE "membership_invitations" DROP CONSTRAINT "membership_invitations_sender_id_fkey";+ALTER TABLE "membership_invitations" RENAME COLUMN "sender_id" TO "invited_by_user_id";+ALTER TABLE "membership_invitations" ADD CONSTRAINT "membership_invitations_invited_by_user_id_fkey" FOREIGN KEY ("invited_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;+-- DropForeignKey+ALTER TABLE "membership_invitations" DROP CONSTRAINT "membership_invitations_project_id_fkey";+-- AlterTable+ALTER TABLE "membership_invitations" RENAME COLUMN "role" TO "project_role";+ALTER TABLE "membership_invitations" ADD COLUMN "org_id" TEXT;+ALTER TABLE "membership_invitations" ADD COLUMN "org_role" "Role";+ALTER TABLE "membership_invitations" ALTER COLUMN "project_id" DROP NOT NULL;+ALTER TABLE "membership_invitations" ALTER COLUMN "project_role" DROP NOT NULL;+-- Backfill org id+UPDATE "membership_invitations"+SET "org_id" = "projects"."org_id"+FROM "projects"+WHERE "membership_invitations"."project_id" = "projects"."id";+-- AddForeignKey+ALTER TABLE "membership_invitations" ADD CONSTRAINT "membership_invitations_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;+-- Backfill org role with value from project role+UPDATE "membership_invitations"+SET "org_role" = "project_role"::text::"Role";+-- Set project-level cols to null, as it's now org level for all existing invitations and role enum will change below+UPDATE "membership_invitations"+SET "project_role" = NULL, "project_id" = NULL;+-- Switch to new UserRole enum+ALTER TABLE "membership_invitations" DROP COLUMN "project_role",+ADD COLUMN "project_role" "Role";++-- AddForeignKey+ALTER TABLE "membership_invitations" ADD CONSTRAINT "membership_invitations_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- Add not null on org level cols after backfill+ALTER TABLE "membership_invitations"+ALTER COLUMN "org_id" SET NOT NULL,+ALTER COLUMN "org_role" SET NOT NULL;+-- CreateIndex+CREATE INDEX "membership_invitations_org_id_idx" ON "membership_invitations"("org_id");+++-- Drop ProjectRole enum as it is replaced by Role+DROP TYPE "ProjectRole";\ No newline at end of filediff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 8040e072a3..7977ac3daf 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -63,21 +63,21 @@ model Session {}model User {- id String @id @default(cuid())- name String?- email String? @unique- emailVerified DateTime? @map("email_verified")- password String?- image String?- admin Boolean @default(false)- accounts Account[]- sessions Session[]- projectMemberships ProjectMembership[]- invitations MembershipInvitation[]- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")- featureFlags String[] @default([]) @map("feature_flags")- AuditLog AuditLog[]+ id String @id @default(cuid())+ name String?+ email String? @unique+ emailVerified DateTime? @map("email_verified")+ password String?+ image String?+ admin Boolean @default(false)+ accounts Account[]+ sessions Session[]+ organizationMemberships OrganizationMembership[]+ projectMemberships ProjectMembership[]+ invitations MembershipInvitation[]+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ featureFlags String[] @default([]) @map("feature_flags")@@map("users")}@@ -91,13 +91,27 @@ model VerificationToken {@@map("verification_tokens")}+model Organization {+ id String @id @default(cuid())+ name String+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema+ organizationMemberships OrganizationMembership[]+ projects Project[]+ MembershipInvitation MembershipInvitation[]++ @@map("organizations")+}+model Project {id String @id @default(cuid())+ orgId String @map("org_id")createdAt DateTime @default(now()) @map("created_at")updatedAt DateTime @default(now()) @updatedAt @map("updated_at")name String- cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see projectsRouter.tsprojectMembers ProjectMembership[]+ organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)traces Trace[]observations Observation[]apiKeys ApiKey[]@@ -107,7 +121,6 @@ model Project {sessions TraceSession[]Prompt Prompt[]Model Model[]- AuditLog AuditLog[]EvalTemplate EvalTemplate[]JobConfiguration JobConfiguration[]JobExecution JobExecution[]@@ -117,6 +130,7 @@ model Project {scoreConfig ScoreConfig[]BatchExport BatchExport[]+ @@index([orgId])@@map("projects")}@@ -161,41 +175,68 @@ model LlmApiKeys {@@map("llm_api_keys")}+model OrganizationMembership {+ id String @id @default(cuid())+ orgId String @map("org_id")+ organization Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)+ userId String @map("user_id")+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ role Role @map("role")+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ ProjectMemberships ProjectMembership[]++ @@unique([orgId, userId])+ @@index([userId])+ @@index([orgId])+ @@map("organization_memberships")+}++// Set a project-specific role for a user in an organizationmodel ProjectMembership {- projectId String @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- userId String @map("user_id")- user User @relation(fields: [userId], references: [id], onDelete: Cascade)- role ProjectRole- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ orgMembershipId String @map("org_membership_id")+ organizationMembership OrganizationMembership @relation(fields: [orgMembershipId], references: [id], onDelete: Cascade)+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ userId String @map("user_id")+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ role Role+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")@@id([projectId, userId])@@index([userId])+ @@index([projectId])+ @@index([orgMembershipId])@@map("project_memberships")}model MembershipInvitation {- id String @id @unique @default(cuid())- email String- role ProjectRole- projectId String @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- senderId String? @map("sender_id")- sender User? @relation(fields: [senderId], references: [id], onDelete: SetNull)- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ id String @id @unique @default(cuid())+ email String+ orgId String @map("org_id")+ organization Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)+ orgRole Role @map("org_role")+ projectId String? @map("project_id")+ project Project? @relation(fields: [projectId], references: [id], onDelete: SetNull)+ projectRole Role? @map("project_role")+ invitedByUserId String? @map("invited_by_user_id")+ invitedByUser User? @relation(fields: [invitedByUserId], references: [id], onDelete: SetNull)+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")@@index([projectId])+ @@index([orgId])@@index([email])@@map("membership_invitations")}-enum ProjectRole {+enum Role {OWNERADMINMEMBERVIEWER+ NONE}model TraceSession {@@ -653,22 +694,25 @@ model Model {@@map("models")}+// No FK constraints to preserve audit logsmodel AuditLog {- id String @id @default(cuid())- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")- userId String @map("user_id")- user User @relation(fields: [userId], references: [id], onDelete: Cascade)- projectId String @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- userProjectRole ProjectRole @map("user_project_role")- resourceType String @map("resource_type")- resourceId String @map("resource_id")+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ userId String @map("user_id")+ orgId String @map("org_id")+ userOrgRole String @map("user_org_role")+ projectId String? @map("project_id")+ userProjectRole String? @map("user_project_role")+ resourceType String @map("resource_type")+ resourceId String @map("resource_id")action Stringbefore String? //stringified JSONafter String? // stringified JSON@@index([projectId])+ @@index([userId])+ @@index([orgId])@@index([createdAt])@@index([updatedAt])@@map("audit_logs")diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex bbad2bf36a..fa91e12692 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -34,39 +34,111 @@ async function main() {options,}).values.environment;+ const seedOrgId = "seed-org-id";+ const seedProjectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";+ const seedUserId1 = "user-1"; // Owner of org+ const seedUserId2 = "user-2"; // Member of org, admin of project+const user = await prisma.user.upsert({- where: { id: "user-1" },+ where: { id: seedUserId1 },update: {name: "Demo User",email: "[email protected]",password: await hash("password", 12),},create: {- id: "user-1",+ id: seedUserId1,name: "Demo User",email: "[email protected]",password: await hash("password", 12),image: "https://static.langfuse.com/langfuse-dev%2Fexample-avatar.png",},});+ const user2 = await prisma.user.upsert({+ where: { id: seedUserId2 },+ update: {+ name: "Demo User 2",+ email: "[email protected]",+ password: await hash("password", 12),+ },+ create: {+ id: seedUserId2,+ name: "Demo User 2",+ email: "[email protected]",+ password: await hash("password", 12),+ },+ });- const seedProjectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";+ await prisma.organization.upsert({+ where: { id: seedOrgId },+ update: {+ name: "Seed Org",+ },+ create: {+ id: seedOrgId,+ name: "Seed Org",+ },+ });const project1 = await prisma.project.upsert({where: { id: seedProjectId },update: {name: "llm-app",+ orgId: seedOrgId,},create: {id: seedProjectId,name: "llm-app",- projectMembers: {- create: {- role: "OWNER",- userId: user.id,- },+ orgId: seedOrgId,+ },+ });++ const orgMembership = await prisma.organizationMembership.upsert({+ where: {+ orgId_userId: {+ userId: user.id,+ orgId: seedOrgId,+ },+ },+ create: {+ userId: user.id,+ orgId: seedOrgId,+ role: "OWNER",+ },+ update: {},+ });++ const orgMembership2 = await prisma.organizationMembership.upsert({+ where: {+ orgId_userId: {+ userId: user2.id,+ orgId: seedOrgId,},},+ create: {+ userId: user2.id,+ orgId: seedOrgId,+ role: "MEMBER",+ },+ update: {},+ });++ const projectMembership = await prisma.projectMembership.upsert({+ where: {+ projectId_userId: {+ projectId: project1.id,+ userId: user2.id,+ },+ },+ create: {+ userId: user2.id,+ projectId: project1.id,+ role: "ADMIN",+ orgMembershipId: orgMembership2.id,+ },+ update: {+ orgMembershipId: orgMembership2.id,+ },});await prisma.prompt.upsert({@@ -114,18 +186,39 @@ async function main() {// Do not run the following for local docker compose setupif (environment === "examples" || environment === "load") {+ const seedOrgIdOrg2 = "demo-org-id";+ const project2Id = "239ad00f-562f-411d-af14-831c75ddd875";+ const org2 = await prisma.organization.upsert({+ where: { id: seedOrgIdOrg2 },+ update: {+ name: "Langfuse Demo",+ },+ create: {+ id: seedOrgIdOrg2,+ name: "Langfuse Demo",+ },+ });const project2 = await prisma.project.upsert({- where: { id: "239ad00f-562f-411d-af14-831c75ddd875" },+ where: { id: project2Id },create: {- id: "239ad00f-562f-411d-af14-831c75ddd875",+ id: project2Id,name: "demo-app",- projectMembers: {- create: {- role: "OWNER",- userId: user.id,- },+ orgId: org2.id,+ },+ update: { orgId: seedOrgIdOrg2 },+ });+ await prisma.organizationMembership.upsert({+ where: {+ orgId_userId: {+ userId: user.id,+ orgId: seedOrgIdOrg2,},},+ create: {+ userId: user.id,+ orgId: seedOrgIdOrg2,+ role: "VIEWER",+ },update: {},});diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 2d1ee5c0fc..098628cc7f 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -1,5 +1,5 @@export * from "./services/S3StorageService";-export * from "./services/email/projectInvitation/sendProjectInvitationEmail";+export * from "./services/email/organizationInvitation/sendMembershipInvitationEmail";export * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";export * from "./services/PromptService";diff --git a/packages/shared/src/server/services/email/projectInvitation/ProjectInvitationEmailTemplate.tsx b/packages/shared/src/server/services/email/organizationInvitation/MembershipInvitationEmailTemplate.tsxsimilarity index 86%rename from packages/shared/src/server/services/email/projectInvitation/ProjectInvitationEmailTemplate.tsxrename to packages/shared/src/server/services/email/organizationInvitation/MembershipInvitationEmailTemplate.tsxindex 514fc2a6eb..a85dddbaea 100644--- a/packages/shared/src/server/services/email/projectInvitation/ProjectInvitationEmailTemplate.tsx+++ b/packages/shared/src/server/services/email/organizationInvitation/MembershipInvitationEmailTemplate.tsx@@ -15,25 +15,25 @@ import {Text,} from "@react-email/components";-interface ProjectInvitationTemplateProps {+interface MembershipInvitationTemplateProps {invitedByUsername: string;invitedByUserEmail: string;- projectName: string;+ orgName: string;receiverEmail: string;inviteLink: string;emailFromAddress: string;langfuseCloudRegion?: string;}-export const ProjectInvitationTemplate = ({+export const MembershipInvitationTemplate = ({invitedByUsername,invitedByUserEmail,- projectName,+ orgName,receiverEmail,inviteLink,emailFromAddress,langfuseCloudRegion,-}: ProjectInvitationTemplateProps) => {+}: MembershipInvitationTemplateProps) => {const previewText = `Join ${invitedByUsername} on Langfuse`;return (@@ -53,7 +53,7 @@ export const ProjectInvitationTemplate = ({/></Section><Heading className="mx-0 my-[30px] p-0 text-center text-2xl font-normal text-black">- Join <strong>{projectName}</strong> on <strong>Langfuse</strong>+ Join <strong>{orgName}</strong> on <strong>Langfuse</strong></Heading><Text className="text-sm leading-6 text-black">Hello,</Text><Text className="text-sm leading-6 text-black">@@ -64,7 +64,8 @@ export const ProjectInvitationTemplate = ({>{invitedByUserEmail}</Link>- ) has invited you to the <strong>{projectName}</strong> project on+ ) has invited you to join the <strong>{orgName}</strong>{" "}+ organization on{langfuseCloudRegion? ` Langfuse (${langfuseCloudRegion} data region)`: " Langfuse"}@@ -78,7 +79,7 @@ export const ProjectInvitationTemplate = ({Accept Invitation</Button><Text className="mt-2 text-xs leading-3 text-muted-foreground">- (you need to create an account)+ (you need to create an account with this email address)</Text></Section><Text className="text-sm leading-6 text-black">@@ -102,4 +103,4 @@ export const ProjectInvitationTemplate = ({);};-export default ProjectInvitationTemplate;+export default MembershipInvitationTemplate;diff --git a/packages/shared/src/server/services/email/projectInvitation/sendProjectInvitationEmail.ts b/packages/shared/src/server/services/email/organizationInvitation/sendMembershipInvitationEmail.tssimilarity index 75%rename from packages/shared/src/server/services/email/projectInvitation/sendProjectInvitationEmail.tsrename to packages/shared/src/server/services/email/organizationInvitation/sendMembershipInvitationEmail.tsindex 40f69d52a2..490f156ca7 100644--- a/packages/shared/src/server/services/email/projectInvitation/sendProjectInvitationEmail.ts+++ b/packages/shared/src/server/services/email/organizationInvitation/sendMembershipInvitationEmail.ts@@ -2,7 +2,7 @@ import { createTransport } from "nodemailer";import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";import { render } from "@react-email/render";-import ProjectInvitationTemplate from "./ProjectInvitationEmailTemplate";+import MembershipInvitationTemplate from "./MembershipInvitationEmailTemplate";const langfuseUrls = {US: "https://us.cloud.langfuse.com",@@ -10,7 +10,7 @@ const langfuseUrls = {STAGING: "https://staging.langfuse.com",};-type SendProjectInvitationParams = {+type SendMembershipInvitationParams = {env: Partial<Record<| "EMAIL_FROM_ADDRESS"@@ -23,19 +23,19 @@ type SendProjectInvitationParams = {to: string;inviterName: string;inviterEmail: string;- projectName: string;+ orgName: string;};-export const sendProjectInvitationEmail = async ({+export const sendMembershipInvitationEmail = async ({env,to,inviterName,inviterEmail,- projectName,-}: SendProjectInvitationParams) => {+ orgName,+}: SendMembershipInvitationParams) => {if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {console.error(- "Missing environment variables for sending project invitation email."+ "Missing environment variables for sending membership invitation email.");return;}@@ -59,10 +59,10 @@ export const sendProjectInvitationEmail = async ({const mailer = createTransport(parseConnectionUrl(env.SMTP_CONNECTION_URL));const htmlTemplate = render(- ProjectInvitationTemplate({+ MembershipInvitationTemplate({invitedByUsername: inviterName,invitedByUserEmail: inviterEmail,- projectName: projectName,+ orgName: orgName,receiverEmail: to,inviteLink: authUrl,emailFromAddress: env.EMAIL_FROM_ADDRESS,@@ -72,11 +72,8 @@ export const sendProjectInvitationEmail = async ({await mailer.sendMail({to,- from: {- address: env.EMAIL_FROM_ADDRESS,- name: "Langfuse",- },- subject: `${inviterName} invited you to join "${projectName}"`,+ from: `Langfuse <${env.EMAIL_FROM_ADDRESS}>`,+ subject: `${inviterName} invited you to join "${orgName}" organization on Langfuse`,html: htmlTemplate,});} catch (error) {diff --git a/web/public/images/posthog-logo.svg b/web/public/images/posthog-logo.svgdeleted file mode 100644index 1c09be906a..0000000000--- a/web/public/images/posthog-logo.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 140"><g fill-rule="nonzero" fill="none"><path d="M55.383 75.225c-1.874 3.748-7.222 3.748-9.096 0l-4.482-8.963a5.085 5.085 0 0 1 0-4.548l4.482-8.964c1.874-3.748 7.222-3.748 9.096 0l4.482 8.964a5.084 5.084 0 0 1 0 4.548l-4.482 8.963Zm0 50.836c-1.874 3.747-7.222 3.747-9.096 0l-4.482-8.964a5.085 5.085 0 0 1 0-4.548l4.482-8.964c1.874-3.748 7.222-3.748 9.096 0l4.482 8.964a5.084 5.084 0 0 1 0 4.548l-4.482 8.964Z" fill="#1D4AFF"/><path d="M0 106.765c0-4.53 5.477-6.8 8.68-3.596l23.307 23.307c3.204 3.204.935 8.68-3.595 8.68H5.085A5.085 5.085 0 0 1 0 130.073v-23.307Zm0-24.55c0 1.35.536 2.643 1.49 3.596l47.856 47.856a5.086 5.086 0 0 0 3.595 1.49h26.286c4.53 0 6.799-5.477 3.595-8.681L8.681 52.334C5.477 49.131 0 51.4 0 55.93v26.286Zm0-50.834c0 1.348.536 2.642 1.49 3.595l98.69 98.691a5.086 5.086 0 0 0 3.596 1.49h26.285c4.53 0 6.8-5.477 3.596-8.681L8.681 1.5C5.477-1.704 0 .565 0 5.095v26.286Zm50.835 0c0 1.348.536 2.642 1.49 3.595l91.5 91.5c3.203 3.204 8.68.935 8.68-3.596V96.595a5.086 5.086 0 0 0-1.49-3.596l-91.5-91.5c-3.203-3.203-8.68-.934-8.68 3.596v26.286ZM110.35 1.5c-3.203-3.204-8.68-.935-8.68 3.595v26.286c0 1.348.536 2.642 1.49 3.595l40.664 40.665c3.204 3.204 8.68.935 8.68-3.596V45.76a5.086 5.086 0 0 0-1.489-3.596L110.35 1.5Z" fill="#F9BD2B"/><path d="m216.24 107.388-47.864-47.863c-3.204-3.204-8.681-.935-8.681 3.595v66.952a5.085 5.085 0 0 0 5.085 5.085h74.142a5.085 5.085 0 0 0 5.085-5.085v-6.097c0-2.809-2.286-5.052-5.07-5.414a39.27 39.27 0 0 1-22.698-11.173Zm-32.145 11.502a8.137 8.137 0 0 1-8.133-8.134 8.137 8.137 0 0 1 8.133-8.134 8.137 8.137 0 0 1 8.134 8.134 8.137 8.137 0 0 1-8.134 8.134Z" fill="#000"/><path d="M0 130.072a5.085 5.085 0 0 0 5.085 5.085h23.307c4.53 0 6.799-5.477 3.595-8.681L8.681 103.169C5.477 99.966 0 102.235 0 106.765v23.307Zm50.835-86.418L8.68 1.5C5.477-1.704 0 .565 0 5.095v26.286c0 1.348.536 2.642 1.49 3.595l49.345 49.346V43.654ZM8.68 52.334C5.477 49.131 0 51.4 0 55.93v26.286c0 1.348.536 2.642 1.49 3.595l49.345 49.346V94.489L8.68 52.334Z" fill="#1D4AFF"/><path d="M101.67 45.76a5.083 5.083 0 0 0-1.49-3.596L59.516 1.5c-3.204-3.204-8.681-.935-8.681 3.595v26.286c0 1.348.536 2.642 1.49 3.595l49.345 49.346V45.76Zm-50.835 89.397h28.392c4.53 0 6.799-5.477 3.595-8.681L50.835 94.489v40.668Zm0-91.503v38.562c0 1.348.536 2.642 1.49 3.595l49.345 49.346V96.595a5.084 5.084 0 0 0-1.49-3.596L50.835 43.654Z" fill="#F54E00"/><path d="M303.32 114.86h20.888V80.22h17.452c19.17 0 31.466-11.37 31.466-28.954 0-17.584-12.295-28.954-31.466-28.954h-38.34v92.547Zm20.888-52.488V40.16h15.337c7.932 0 12.692 4.23 12.692 11.105 0 6.876-4.76 11.106-12.692 11.106h-15.337Zm86.71 53.545c20.36 0 35.167-14.543 35.167-34.375 0-19.831-14.807-34.374-35.167-34.374-20.625 0-35.168 14.543-35.168 34.374 0 19.832 14.543 34.375 35.168 34.375Zm-15.866-34.375c0-10.577 6.346-17.848 15.866-17.848 9.386 0 15.733 7.271 15.733 17.848 0 10.577-6.347 17.849-15.733 17.849-9.52 0-15.866-7.272-15.866-17.849Zm84.462 34.375c15.601 0 26.178-9.784 26.178-21.286 0-26.97-35.829-18.245-35.829-28.822 0-2.908 3.04-4.759 7.404-4.759 4.495 0 9.916 2.776 11.634 8.858l15.601-6.479c-3.04-9.65-14.279-16.261-27.896-16.261-14.676 0-23.798 8.725-23.798 19.17 0 25.252 35.3 18.245 35.3 28.69 0 3.702-3.437 6.214-8.594 6.214-7.403 0-12.56-5.156-14.146-11.37l-15.601 6.081c3.438 10.048 13.486 19.964 29.747 19.964Zm76.43-1.718-1.321-16.791c-2.248 1.19-5.157 1.586-7.536 1.586-4.76 0-7.933-3.437-7.933-9.387V64.355h16.13v-16.13h-16.13V28.923h-19.435v19.302h-10.577v16.13h10.577v27.764c0 16.13 10.974 23.798 25.384 23.798 3.967 0 7.669-.66 10.842-1.718Zm67.764-91.887v35.961h-36.755v-35.96h-20.89v92.546h20.89V76.122h36.755v38.737h21.021V22.312h-21.021Zm67.386 93.605c20.36 0 35.168-14.543 35.168-34.375 0-19.831-14.807-34.374-35.168-34.374-20.625 0-35.168 14.543-35.168 34.374 0 19.832 14.543 34.375 35.168 34.375ZM675.23 81.542c0-10.577 6.346-17.848 15.865-17.848 9.387 0 15.733 7.271 15.733 17.848 0 10.577-6.346 17.849-15.733 17.849-9.519 0-15.865-7.272-15.865-17.849Zm88.545 31.202c7.272 0 13.75-2.512 17.188-6.875v6.346c0 7.404-5.95 12.56-15.072 12.56-6.479 0-12.164-3.173-13.09-8.594l-17.715 2.777c2.38 12.56 15.204 21.022 30.805 21.022 20.492 0 34.11-12.032 34.11-29.88V48.225h-19.17v5.685c-3.57-4.098-9.652-6.742-17.452-6.742-18.51 0-30.144 12.692-30.144 32.788 0 20.096 11.634 32.788 30.54 32.788ZM752.14 79.956c0-9.916 5.817-16.262 14.807-16.262 9.123 0 14.94 6.346 14.94 16.262s-5.817 16.262-14.94 16.262c-8.99 0-14.807-6.346-14.807-16.262Z" fill="#000"/></g></svg>\ No newline at end of filediff --git a/web/src/__e2e__/auth.spec.ts b/web/src/__e2e__/auth.spec.tsindex b30d285388..980e505907 100644--- a/web/src/__e2e__/auth.spec.ts+++ b/web/src/__e2e__/auth.spec.ts@@ -15,16 +15,7 @@ test("should redirect to home if signed in", async ({ page }) => {// wait 2 secondsawait page.waitForTimeout(2000);- if (process.env.CI)- await expect(page).toHaveURL(- // project id from seed.ts- "/project/7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- );- else- console.log(- "Test skipped as redirect depends on db state, URL after signing in:",- page.url(),- );+ await expect(page).toHaveURL("/");});test("Successfully sign up & able to go to homepage", async ({ page }) => {@@ -35,7 +26,7 @@ test("Successfully sign up & able to go to homepage", async ({ page }) => {await page.click('button[data-testid="submit-email-password-sign-up-form"]');await page.waitForTimeout(2000);// see get started page- await expect(page).toHaveURL("/?getStarted=1");+ await expect(page).toHaveURL("/");});test("Successfully sign up & able to go to homepage with uppercase email", async ({@@ -48,7 +39,7 @@ test("Successfully sign up & able to go to homepage with uppercase email", asyncawait page.click('button[data-testid="submit-email-password-sign-up-form"]');await page.waitForTimeout(2000);// see get started page- await expect(page).toHaveURL("/?getStarted=1");+ await expect(page).toHaveURL("/");});test("Signup input validation", async ({ page }) => {@@ -64,7 +55,7 @@ test("Signup input validation", async ({ page }) => {await page.click('button[data-testid="submit-email-password-sign-up-form"]');await page.waitForTimeout(2000);// don't see get started page- await expect(page).not.toHaveURL("/?getStarted=1");+ await expect(page).not.toHaveURL("/");});// random email address to be used in tests@@ -83,7 +74,8 @@ test("Unauthenticated user should be redirected to target URL after login", asynawait page.waitForTimeout(2000);// project id and prompt from seed.ts- const promptUrl = "/project/7a88fb47-b4e2-43b8-a06c-a5ce950dc53a/prompts/summary-prompt";+ const promptUrl =+ "/project/7a88fb47-b4e2-43b8-a06c-a5ce950dc53a/prompts/summary-prompt";await page.getByRole("button", { name: /Demo User/ }).click();diff --git a/web/src/__e2e__/create-project.spec.ts b/web/src/__e2e__/create-project.spec.tsindex 3e5cdebfc1..06d9255a5a 100644--- a/web/src/__e2e__/create-project.spec.ts+++ b/web/src/__e2e__/create-project.spec.ts@@ -1,48 +1,59 @@import { test, expect } from "@playwright/test";-test("should see new projects dialog open after clicking new project btn", async ({- page,-}) => {- await page.goto("auth/sign-up");- await page.fill('input[name="name"]', "demo user");- await page.fill('input[name="email"]', randomEmailAddress());- await page.fill('input[type="password"]', "password");- await page.click('button[data-testid="submit-email-password-sign-up-form"]');- await page.waitForTimeout(2000);- await page.waitForTimeout(2000);- expect(await page.innerHTML("data-testid=create-new-project-title")).toBe(- "Create new project",- );- await page.click('[data-testid="create-project-btn"]');- await page.waitForTimeout(2000);- await expect(page.locator("data-testid=new-project-form")).toBeVisible();-});--test("Create a project with provided name", async ({ page }) => {+test("Sign in, create an organization, create a project", async ({ page }) => {test.setTimeout(60000);+ // Sign inawait page.goto("/auth/sign-in");await page.fill('input[name="email"]', "[email protected]");await page.fill('input[type="password"]', "password");await page.click('button[data-testid="submit-email-password-sign-in-form"]');await page.waitForTimeout(2000);- await page.isVisible('[data-testid="new-project-form"]');- await page.click('[data-testid="create-project-btn"]');+ await expect(page).toHaveURL("/");++ // Start create org flow+ await page.isVisible('[data-testid="create-organization-btn"]');+ await page.click('[data-testid="create-organization-btn"]');await page.waitForTimeout(2000);- await expect(page.locator("data-testid=new-project-form")).toBeVisible();- await page.fill(- '[data-testid="new-project-name-input"]',- "my e2e demo project",+ await expect(page).toHaveURL("/setup");++ // Create an organization+ await expect(page.locator("data-testid=new-org-form")).toBeVisible();+ await page.fill('[data-testid="new-org-name-input"]', "e2e test org");+ await page.click('button[type="submit"]');+ await page.waitForTimeout(5000);+ expect(page.url()).toContain("/organization/");+ expect(page.url()).toContain("/setup?orgstep=invite-members");++ // Parse the organization ID from the URL using a simpler method+ const url = new URL(page.url());+ const organizationId = url.pathname.split("/")[2];+ console.log("organization", organizationId);++ // Skip add new members step+ await page.isVisible('[data-testid="btn-skip-add-members"]');+ await page.click('[data-testid="btn-skip-add-members"]');+ expect(page.url()).toContain(+ "/organization/" + organizationId + "/setup?orgstep=create-project",);++ // Create project+ await expect(page.locator("data-testid=new-project-form")).toBeVisible();+ await page.fill('[data-testid="new-project-name-input"]', "e2e test project");await page.click('button[type="submit"]');- await page.waitForTimeout(2000);+ await page.waitForTimeout(5000);expect(page.url()).toContain("/project/");+ expect(page.url()).toContain("/setup");++ const projectUrl = new URL(page.url());+ const projectId = projectUrl.pathname.split("/")[2];++ // check that the project exists by navigating to its dashboard+ await page.goto("/project/" + projectId);await page.waitForTimeout(2000);- expect(await page.getByTestId("project-name").textContent()).toContain(- "my e2e demo project",- );-});+ expect(page.url()).toContain("/project/" + projectId);+ expect(page.url()).not.toContain("/setup");-// random email address to be used in tests-const randomEmailAddress = () =>- Math.random().toString(36).substring(2, 11) + "@example.com";+ const headings = await page.locator("h2").allTextContents();+ expect(headings).toContain("Dashboard");+});diff --git a/web/src/__tests__/datasets.servertest.ts b/web/src/__tests__/datasets.servertest.tsindex 13e15c053a..b67183ff4e 100644--- a/web/src/__tests__/datasets.servertest.ts+++ b/web/src/__tests__/datasets.servertest.ts@@ -848,6 +848,12 @@ describe("/api/public/datasets and /api/public/dataset-items API Endpoints", ()const otherProject = await prisma.project.create({data: {name: "other-project",+ organization: {+ connectOrCreate: {+ where: { id: "other-org" },+ create: { name: "other-org", id: "other-org" },+ },+ },},});diff --git a/web/src/__tests__/generation-exports.servertest.ts b/web/src/__tests__/generation-exports.servertest.tsindex 9d52bcb130..c4b27579e5 100644--- a/web/src/__tests__/generation-exports.servertest.ts+++ b/web/src/__tests__/generation-exports.servertest.ts@@ -71,12 +71,19 @@ describe("observations.export RPC", () => {expires: "1",user: {id: "clgb17vnp000008jjere5g15i",- name: "John Doe",- projects: [+ name: "Demo User",+ organizations: [{- id: projectId,- role: "ADMIN",- name: "test",+ id: "seed-org-id",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ },+ ],},],featureFlags: {diff --git a/web/src/__tests__/ingestion.servertest.ts b/web/src/__tests__/ingestion.servertest.tsindex 57038744c2..551559d016 100644--- a/web/src/__tests__/ingestion.servertest.ts+++ b/web/src/__tests__/ingestion.servertest.ts@@ -1140,11 +1140,16 @@ describe("/api/public/ingestion API Endpoint", () => {it("should not override a trace from a different project", async () => {const traceId = v4();const newProjectId = v4();-+ await prisma.organization.upsert({+ where: { id: "other-org" },+ create: { id: "other-org", name: "other-org" },+ update: {},+ });await prisma.project.create({data: {id: newProjectId,name: "another-project",+ orgId: "other-org",},});diff --git a/web/src/__tests__/llm-api-key.servertest.ts b/web/src/__tests__/llm-api-key.servertest.tsindex 610555e311..a5a679f52e 100644--- a/web/src/__tests__/llm-api-key.servertest.ts+++ b/web/src/__tests__/llm-api-key.servertest.ts@@ -18,19 +18,26 @@ describe("llmApiKey.all RPC", () => {user: {id: "user-1",name: "Demo User",- projects: [+ organizations: [{- id: projectId,- role: "ADMIN",- name: "test",+ id: "seed-org-id",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ },+ ],},],featureFlags: {templateFlag: true,- evals: true,},admin: true,},+ environment: {} as any,};const ctx = createInnerTRPCContext({ session });diff --git a/web/src/__tests__/prompts.v2.servertest.ts b/web/src/__tests__/prompts.v2.servertest.tsindex 65ee1291d1..b72ded3e00 100644--- a/web/src/__tests__/prompts.v2.servertest.ts+++ b/web/src/__tests__/prompts.v2.servertest.ts@@ -773,19 +773,26 @@ describe("/api/public/v2/prompts API Endpoint", () => {});const otherProjectId = "239ad00f-562f-411d-af14-831c75ddd875";+ await prisma.organization.upsert({+ where: { id: "other-org" },+ create: { id: "other-org", name: "other-org" },+ update: {},+ });+ await prisma.organizationMembership.upsert({+ where: {+ orgId_userId: { orgId: "other-org", userId: "user-test" },+ },+ create: { userId: "user-test", orgId: "other-org", role: "OWNER" },+ update: { role: "OWNER" },+ });await prisma.project.upsert({where: { id: otherProjectId },create: {id: otherProjectId,name: "demo-app",- projectMembers: {- create: {- role: "OWNER",- userId: "user-test",- },- },+ orgId: "other-org",},- update: {},+ update: { name: "demo-app", orgId: "other-org" },});await createPromptInDB({diff --git a/web/src/__tests__/query-builder.servertest.ts b/web/src/__tests__/query-builder.servertest.tsindex 4bb83776c6..4cefd29e90 100644--- a/web/src/__tests__/query-builder.servertest.ts+++ b/web/src/__tests__/query-builder.servertest.ts@@ -182,13 +182,19 @@ describe("Build valid SQL queries", () => {describe("should retrieve data", () => {it("should get a simple trace", async () => {+ await prisma.organization.upsert({+ where: { id: "other-org" },+ create: { id: "other-org", name: "other-org" },+ update: {},+ });await prisma.project.upsert({where: { id: "different-project-id" },create: {id: "different-project-id",name: "test-project",+ orgId: "other-org",},- update: {},+ update: { name: "test-project", orgId: "other-org" },});await prisma.trace.createMany({diff --git a/web/src/__tests__/server/api/routers/traces.servertest.ts b/web/src/__tests__/server/api/routers/traces.servertest.tsindex 78228c23da..9fa192941a 100644--- a/web/src/__tests__/server/api/routers/traces.servertest.ts+++ b/web/src/__tests__/server/api/routers/traces.servertest.ts@@ -14,12 +14,18 @@ describe("Traces TRPC Router", () => {user: {id: "clgb17vnp000008jjere5g15i",name: "John Doe",- projects: [+ organizations: [{- id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- role: "ADMIN",- name: "test",- cloudConfig: { defaultLookBackDays: null },+ id: "seed-org-id",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ role: "ADMIN",+ },+ ],},],featureFlags: {@@ -27,6 +33,7 @@ describe("Traces TRPC Router", () => {},admin: true,},+ environment: {} as any,};const ctx = createInnerTRPCContext({ session });diff --git a/web/src/components/BatchExportTableButton.tsx b/web/src/components/BatchExportTableButton.tsxindex 810ed6155e..c9847e38f3 100644--- a/web/src/components/BatchExportTableButton.tsx+++ b/web/src/components/BatchExportTableButton.tsx@@ -15,8 +15,8 @@ import {import React from "react";import { api } from "@/src/utils/api";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";-import { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";export type BatchExportTableButtonProps = {projectId: string;@@ -31,8 +31,8 @@ export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = () => {const [isExporting, setIsExporting] = React.useState(false);const createExport = api.batchExport.create.useMutation();- const isEeEnabled = useIsEeEnabled();- const hasAccess = useHasAccess({+ const entitled = useHasOrgEntitlement("batch-export");+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "batchExport:create",});@@ -56,7 +56,7 @@ export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = (});};- if (!isEeEnabled || !hasAccess) return null;+ if (!entitled || !hasAccess) return null;return (<DropdownMenu>diff --git a/web/src/components/EnvLabel.tsx b/web/src/components/EnvLabel.tsxnew file mode 100644index 0000000000..087751c325--- /dev/null+++ b/web/src/components/EnvLabel.tsx@@ -0,0 +1,34 @@+import { AlertTriangle, Check } from "lucide-react";+import { env } from "@/src/env.mjs";+import { cn } from "@/src/utils/tailwind";+import { useSession } from "next-auth/react";++export const EnvLabel = ({ className }: { className?: string }) => {+ const session = useSession();+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return null;+ if (!session.data?.user?.email?.endsWith("@langfuse.com")) return null;+ return (+ <div+ className={cn(+ "flex items-center gap-2 self-stretch rounded-md px-1 py-1 text-xs ring-1 sm:px-3 sm:py-2 lg:-mx-2",+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"+ ? "bg-light-blue text-dark-blue ring-dark-blue"+ : env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV"+ ? "bg-light-green text-dark-green ring-dark-green"+ : "bg-light-red text-dark-red ring-dark-red",+ className,+ )}+ >+ {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV" ? (+ <Check size={16} className="hidden sm:block" />+ ) : (+ <AlertTriangle size={16} className="hidden sm:block" />+ )}+ <span className="whitespace-nowrap">+ {["EU", "US"].includes(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)+ ? `PROD-${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}`+ : env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}+ </span>+ </div>+ );+};diff --git a/web/src/components/LangfuseLogo.tsx b/web/src/components/LangfuseLogo.tsxindex 369648e433..bc14b14844 100644--- a/web/src/components/LangfuseLogo.tsx+++ b/web/src/components/LangfuseLogo.tsx@@ -1,124 +1,7 @@-import {- AlertTriangle,- BadgeCheck,- Check,- Github,- HardDriveDownload,- Map,- Newspaper,-} from "lucide-react";--import { VERSION } from "@/src/constants";-import { env } from "@/src/env.mjs";import { cn } from "@/src/utils/tailwind";-import {- DropdownMenu,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,-} from "@/src/components/ui/dropdown-menu";-import { ArrowUp } from "lucide-react";-import { api } from "@/src/utils/api";-import { Button } from "@/src/components/ui/button";import Link from "next/link";-import { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";--const VersionLabel = ({ className }: { className?: string }) => {- const checkUpdate = api.public.checkUpdate.useQuery(undefined, {- refetchOnMount: false,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- enabled: !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION, // do not check for updates on Langfuse Cloud- onError: (error) => console.error("checkUpdate error", error), // do not render default error message- });- const isEeVersion =- useIsEeEnabled() && !Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);-- const hasUpdate =- !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&- checkUpdate.data &&- checkUpdate.data.updateType;-- const color =- checkUpdate.data?.updateType === "major"- ? "text-dark-red"- : checkUpdate.data?.updateType === "minor"- ? "text-dark-yellow"- : undefined;-- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="xs" className={className}>- {VERSION}- {hasUpdate && <ArrowUp className={`ml-1 h-3 w-3 ${color}`} />}- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent>- {hasUpdate ? (- <>- <DropdownMenuLabel>- New {checkUpdate.data?.updateType} version:{" "}- {checkUpdate.data?.latestRelease}- </DropdownMenuLabel>- <DropdownMenuSeparator />- </>- ) : !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ? (- <>- <DropdownMenuLabel>This is the latest release</DropdownMenuLabel>- <DropdownMenuSeparator />- </>- ) : null}- {isEeVersion && (- <>- <DropdownMenuLabel className="flex items-center font-normal">- <BadgeCheck size={16} className="mr-2" />- Enterprise Edition- </DropdownMenuLabel>- <DropdownMenuSeparator />- </>- )}- <DropdownMenuItem asChild>- <Link- href="https://github.com/langfuse/langfuse/releases"- target="_blank"- >- <Github size={16} className="mr-2" />- Releases- </Link>- </DropdownMenuItem>- <DropdownMenuItem asChild>- <Link href="https://langfuse.com/changelog" target="_blank">- <Newspaper size={16} className="mr-2" />- Changelog- </Link>- </DropdownMenuItem>- <DropdownMenuItem asChild>- <Link href="https://langfuse.com/roadmap" target="_blank">- <Map size={16} className="mr-2" />- Roadmap- </Link>- </DropdownMenuItem>- {hasUpdate && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem asChild>- <Link- href="https://langfuse.com/docs/deployment/self-host#update"- target="_blank"- >- <HardDriveDownload size={16} className="mr-2" />- Update- </Link>- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- );-};+import { EnvLabel } from "./EnvLabel";+import { VersionLabel } from "./VersionLabel";export const LangfuseIcon = ({size = 32,@@ -152,40 +35,20 @@ export const LangfuseLogo = ({className={cn("flex flex-wrap gap-4 lg:flex-col lg:items-start", className)}>{/* Environment Labeling for Langfuse Maintainers */}- {showEnvLabel && env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && (- <div- className={cn(- "flex items-center gap-2 self-stretch rounded-md px-1 py-1 text-xs ring-1 sm:px-3 sm:py-2 lg:-mx-2",- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"- ? "bg-light-blue text-dark-blue ring-dark-blue"- : env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV"- ? "bg-light-green text-dark-green ring-dark-green"- : "bg-light-red text-dark-red ring-dark-red",- )}- >- {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV" ? (- <Check size={16} className="hidden sm:block" />- ) : (- <AlertTriangle size={16} className="hidden sm:block" />- )}- <span className="whitespace-nowrap">- {["EU", "US"].includes(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)- ? `PROD-${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}`- : env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}- </span>- </div>- )}+ {showEnvLabel && <EnvLabel />}{/* Langfuse Logo */}<div className="flex items-center">- <LangfuseIcon size={size === "sm" ? 16 : 20} />- <span- className={cn(- "ml-2 font-mono font-semibold",- size === "sm" ? "text-sm" : "text-lg",- )}- >- Langfuse- </span>+ <Link href="/" className="flex items-center">+ <LangfuseIcon size={size === "sm" ? 16 : 20} />+ <span+ className={cn(+ "ml-2 font-mono font-semibold",+ size === "sm" ? "text-sm" : "text-xl",+ )}+ >+ Langfuse+ </span>+ </Link>{version && <VersionLabel className="ml-2" />}</div></div>diff --git a/web/src/components/ModelParameters/LLMApiKeyComponent.tsx b/web/src/components/ModelParameters/LLMApiKeyComponent.tsxindex c132ea8a11..abd234d8f1 100644--- a/web/src/components/ModelParameters/LLMApiKeyComponent.tsx+++ b/web/src/components/ModelParameters/LLMApiKeyComponent.tsx@@ -1,16 +1,16 @@import Link from "next/link";import { Label } from "@/src/components/ui/label";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";import { api } from "@/src/utils/api";import { type UIModelParams } from "@langfuse/shared";import { ArrowTopRightIcon } from "@radix-ui/react-icons";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";export const LLMApiKeyComponent = (p: {projectId: string;modelParams: UIModelParams;}) => {- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: p.projectId,scope: "llmApiKeys:read",});diff --git a/web/src/components/PagedSettingsContainer.tsx b/web/src/components/PagedSettingsContainer.tsxnew file mode 100644index 0000000000..60d65f2e25--- /dev/null+++ b/web/src/components/PagedSettingsContainer.tsx@@ -0,0 +1,111 @@+import { cn } from "@/src/utils/tailwind";+import { ArrowUpRight } from "lucide-react";+import Link from "next/link";+import { type ReactNode } from "react";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { useRouter } from "next/router";++type SettingsProps = {+ pages: Array<+ {+ title: string;+ slug: string;+ show?: boolean | (() => boolean);+ } & ({ content: ReactNode } | { href: string })+ >;+ activeSlug?: string;+};++export const PagedSettingsContainer = ({+ pages,+ activeSlug,+}: SettingsProps) => {+ const router = useRouter();+ const availablePages = pages.filter((page) =>+ "show" in page+ ? typeof page.show === "function"+ ? page.show()+ : page.show+ : true,+ );++ const currentPage =+ availablePages.find((page) => page.slug === activeSlug) ??+ availablePages[0]; // Fallback to first page if not found++ const onChange = (newSlug: string) => {+ const pathSegments = router.asPath.split("/");+ if (pathSegments[pathSegments.length - 1] !== "settings")+ pathSegments.pop();+ if (newSlug !== "index") pathSegments.push(newSlug);+ router.push(pathSegments.join("/"));+ };++ return (+ <main className="flex flex-1 flex-col gap-4 py-4 md:gap-8">+ <div className="grid w-full items-start gap-4 md:grid-cols-[180px_1fr] lg:grid-cols-[220px_1fr]">+ <nav className="block md:hidden">+ <Select+ onValueChange={(slug) => {+ const page = availablePages.find((p) => p.slug === slug);+ if (page && "href" in page) router.push(page.href);+ else onChange(slug);+ }}+ value={currentPage.slug}+ >+ <SelectTrigger>+ <SelectValue placeholder="Select a page" />+ </SelectTrigger>+ <SelectContent>+ {availablePages.map((page) => (+ <SelectItem key={page.title} value={page.slug}>+ {page.title}+ {"href" in page && (+ <ArrowUpRight size={14} className="ml-1 inline" />+ )}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </nav>+ <nav+ className="hidden gap-4 text-sm text-muted-foreground md:sticky md:top-5 md:grid"+ x-chunk="dashboard-04-chunk-0"+ >+ {availablePages.map((page) =>+ "href" in page ? (+ <Link+ key={page.title}+ href={page.href}+ className="flex flex-row items-center gap-2 font-semibold"+ >+ {page.title}+ <ArrowUpRight size={14} className="inline" />+ </Link>+ ) : (+ <span+ key={page.title}+ onClick={() => onChange(page.slug)}+ className={cn(+ "cursor-pointer font-semibold",+ page.slug === currentPage.slug && "text-primary",+ )}+ >+ {page.title}+ </span>+ ),+ )}+ </nav>+ <div className="w-full overflow-hidden p-1">+ {currentPage && "content" in currentPage ? currentPage.content : null}+ </div>+ </div>+ </main>+ );+};diff --git a/web/src/components/PosthogLogo.tsx b/web/src/components/PosthogLogo.tsxnew file mode 100644index 0000000000..58438a8fc1--- /dev/null+++ b/web/src/components/PosthogLogo.tsx@@ -0,0 +1,35 @@+// https://react-svgr.com/playground/?typescript=true++import * as React from "react";+import { type SVGProps } from "react";+export const PostHogLogo = (props: SVGProps<SVGSVGElement>) => (+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 140" {...props}>+ <g fill="none">+ <path+ fill="#1D4AFF"+ d="M55.383 75.225c-1.874 3.748-7.222 3.748-9.096 0l-4.482-8.963a5.085 5.085 0 0 1 0-4.548l4.482-8.964c1.874-3.748 7.222-3.748 9.096 0l4.482 8.964a5.084 5.084 0 0 1 0 4.548l-4.482 8.963Zm0 50.836c-1.874 3.747-7.222 3.747-9.096 0l-4.482-8.964a5.085 5.085 0 0 1 0-4.548l4.482-8.964c1.874-3.748 7.222-3.748 9.096 0l4.482 8.964a5.084 5.084 0 0 1 0 4.548l-4.482 8.964Z"+ />+ <path+ fill="#F9BD2B"+ d="M0 106.765c0-4.53 5.477-6.8 8.68-3.596l23.307 23.307c3.204 3.204.935 8.68-3.595 8.68H5.085A5.085 5.085 0 0 1 0 130.073v-23.307Zm0-24.55c0 1.35.536 2.643 1.49 3.596l47.856 47.856a5.086 5.086 0 0 0 3.595 1.49h26.286c4.53 0 6.799-5.477 3.595-8.681L8.681 52.334C5.477 49.131 0 51.4 0 55.93v26.286Zm0-50.834c0 1.348.536 2.642 1.49 3.595l98.69 98.691a5.086 5.086 0 0 0 3.596 1.49h26.285c4.53 0 6.8-5.477 3.596-8.681L8.681 1.5C5.477-1.704 0 .565 0 5.095v26.286Zm50.835 0c0 1.348.536 2.642 1.49 3.595l91.5 91.5c3.203 3.204 8.68.935 8.68-3.596V96.595a5.086 5.086 0 0 0-1.49-3.596l-91.5-91.5c-3.203-3.203-8.68-.934-8.68 3.596v26.286ZM110.35 1.5c-3.203-3.204-8.68-.935-8.68 3.595v26.286c0 1.348.536 2.642 1.49 3.595l40.664 40.665c3.204 3.204 8.68.935 8.68-3.596V45.76a5.086 5.086 0 0 0-1.489-3.596L110.35 1.5Z"+ />+ <path+ fill="currentColor"+ className="bg-primary"+ d="m216.24 107.388-47.864-47.863c-3.204-3.204-8.681-.935-8.681 3.595v66.952a5.085 5.085 0 0 0 5.085 5.085h74.142a5.085 5.085 0 0 0 5.085-5.085v-6.097c0-2.809-2.286-5.052-5.07-5.414a39.27 39.27 0 0 1-22.698-11.173Zm-32.145 11.502a8.137 8.137 0 0 1-8.133-8.134 8.137 8.137 0 0 1 8.133-8.134 8.137 8.137 0 0 1 8.134 8.134 8.137 8.137 0 0 1-8.134 8.134Z"+ />+ <path+ fill="#1D4AFF"+ d="M0 130.072a5.085 5.085 0 0 0 5.085 5.085h23.307c4.53 0 6.799-5.477 3.595-8.681L8.681 103.169C5.477 99.966 0 102.235 0 106.765v23.307Zm50.835-86.418L8.68 1.5C5.477-1.704 0 .565 0 5.095v26.286c0 1.348.536 2.642 1.49 3.595l49.345 49.346V43.654ZM8.68 52.334C5.477 49.131 0 51.4 0 55.93v26.286c0 1.348.536 2.642 1.49 3.595l49.345 49.346V94.489L8.68 52.334Z"+ />+ <path+ fill="#F54E00"+ d="M101.67 45.76a5.083 5.083 0 0 0-1.49-3.596L59.516 1.5c-3.204-3.204-8.681-.935-8.681 3.595v26.286c0 1.348.536 2.642 1.49 3.595l49.345 49.346V45.76Zm-50.835 89.397h28.392c4.53 0 6.799-5.477 3.595-8.681L50.835 94.489v40.668Zm0-91.503v38.562c0 1.348.536 2.642 1.49 3.595l49.345 49.346V96.595a5.084 5.084 0 0 0-1.49-3.596L50.835 43.654Z"+ />+ <path+ fill="currentColor"+ d="M303.32 114.86h20.888V80.22h17.452c19.17 0 31.466-11.37 31.466-28.954 0-17.584-12.295-28.954-31.466-28.954h-38.34v92.547Zm20.888-52.488V40.16h15.337c7.932 0 12.692 4.23 12.692 11.105 0 6.876-4.76 11.106-12.692 11.106h-15.337Zm86.71 53.545c20.36 0 35.167-14.543 35.167-34.375 0-19.831-14.807-34.374-35.167-34.374-20.625 0-35.168 14.543-35.168 34.374 0 19.832 14.543 34.375 35.168 34.375Zm-15.866-34.375c0-10.577 6.346-17.848 15.866-17.848 9.386 0 15.733 7.271 15.733 17.848 0 10.577-6.347 17.849-15.733 17.849-9.52 0-15.866-7.272-15.866-17.849Zm84.462 34.375c15.601 0 26.178-9.784 26.178-21.286 0-26.97-35.829-18.245-35.829-28.822 0-2.908 3.04-4.759 7.404-4.759 4.495 0 9.916 2.776 11.634 8.858l15.601-6.479c-3.04-9.65-14.279-16.261-27.896-16.261-14.676 0-23.798 8.725-23.798 19.17 0 25.252 35.3 18.245 35.3 28.69 0 3.702-3.437 6.214-8.594 6.214-7.403 0-12.56-5.156-14.146-11.37l-15.601 6.081c3.438 10.048 13.486 19.964 29.747 19.964Zm76.43-1.718-1.321-16.791c-2.248 1.19-5.157 1.586-7.536 1.586-4.76 0-7.933-3.437-7.933-9.387V64.355h16.13v-16.13h-16.13V28.923h-19.435v19.302h-10.577v16.13h10.577v27.764c0 16.13 10.974 23.798 25.384 23.798 3.967 0 7.669-.66 10.842-1.718Zm67.764-91.887v35.961h-36.755v-35.96h-20.89v92.546h20.89V76.122h36.755v38.737h21.021V22.312h-21.021Zm67.386 93.605c20.36 0 35.168-14.543 35.168-34.375 0-19.831-14.807-34.374-35.168-34.374-20.625 0-35.168 14.543-35.168 34.374 0 19.832 14.543 34.375 35.168 34.375ZM675.23 81.542c0-10.577 6.346-17.848 15.865-17.848 9.387 0 15.733 7.271 15.733 17.848 0 10.577-6.346 17.849-15.733 17.849-9.519 0-15.865-7.272-15.865-17.849Zm88.545 31.202c7.272 0 13.75-2.512 17.188-6.875v6.346c0 7.404-5.95 12.56-15.072 12.56-6.479 0-12.164-3.173-13.09-8.594l-17.715 2.777c2.38 12.56 15.204 21.022 30.805 21.022 20.492 0 34.11-12.032 34.11-29.88V48.225h-19.17v5.685c-3.57-4.098-9.652-6.742-17.452-6.742-18.51 0-30.144 12.692-30.144 32.788 0 20.096 11.634 32.788 30.54 32.788ZM752.14 79.956c0-9.916 5.817-16.262 14.807-16.262 9.123 0 14.94 6.346 14.94 16.262s-5.817 16.262-14.94 16.262c-8.99 0-14.807-6.346-14.807-16.262Z"+ />+ </g>+ </svg>+);diff --git a/web/src/components/Support.tsx b/web/src/components/Support.tsxindex eae8d60de3..a94291c623 100644--- a/web/src/components/Support.tsx+++ b/web/src/components/Support.tsx@@ -27,7 +27,7 @@ const supportChannels = [description:"Create an issue on Github to report bugs or request new features.",href: "https://github.com/langfuse/langfuse/issues/new/choose",- buttonText: "Create issue",+ buttonText: "Create Issue",primary: true,},{@@ -35,7 +35,7 @@ const supportChannels = [title: "GitHub Support",description: "Create a support ticket via GitHub discussions.",href: "https://github.com/orgs/langfuse/discussions/categories/support",- buttonText: "Submit question",+ buttonText: "Submit Question",primary: true,},{diff --git a/web/src/components/VersionLabel.tsx b/web/src/components/VersionLabel.tsxnew file mode 100644index 0000000000..a94c71e361--- /dev/null+++ b/web/src/components/VersionLabel.tsx@@ -0,0 +1,117 @@+import {+ BadgeCheck,+ Github,+ HardDriveDownload,+ Map,+ Newspaper,+} from "lucide-react";+import { VERSION } from "@/src/constants";+import Link from "next/link";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+} from "@/src/components/ui/dropdown-menu";+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";++export const VersionLabel = ({ className }: { className?: string }) => {+ const checkUpdate = api.public.checkUpdate.useQuery(undefined, {+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ enabled: !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION, // do not check for updates on Langfuse Cloud+ onError: (error) => console.error("checkUpdate error", error), // do not render default error message+ });+ const isEeVersion =+ useIsEeEnabled() && !Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);++ const hasUpdate =+ !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&+ checkUpdate.data &&+ checkUpdate.data.updateType;++ const color =+ checkUpdate.data?.updateType === "major"+ ? "text-dark-red"+ : checkUpdate.data?.updateType === "minor"+ ? "text-dark-yellow"+ : undefined;++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="xs" className={className}>+ {VERSION}+ {hasUpdate && <ArrowUp className={`ml-1 h-3 w-3 ${color}`} />}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent onClick={(e) => e.stopPropagation()}>+ {hasUpdate ? (+ <>+ <DropdownMenuLabel>+ New {checkUpdate.data?.updateType} version:{" "}+ {checkUpdate.data?.latestRelease}+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ </>+ ) : !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ? (+ <>+ <DropdownMenuLabel>This is the latest release</DropdownMenuLabel>+ <DropdownMenuSeparator />+ </>+ ) : null}+ {isEeVersion && (+ <>+ <DropdownMenuLabel className="flex items-center font-normal">+ <BadgeCheck size={16} className="mr-2" />+ Enterprise Edition+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem asChild>+ <Link+ href="https://github.com/langfuse/langfuse/releases"+ target="_blank"+ >+ <Github size={16} className="mr-2" />+ Releases+ </Link>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <Link href="https://langfuse.com/changelog" target="_blank">+ <Newspaper size={16} className="mr-2" />+ Changelog+ </Link>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <Link href="https://langfuse.com/roadmap" target="_blank">+ <Map size={16} className="mr-2" />+ Roadmap+ </Link>+ </DropdownMenuItem>+ {hasUpdate && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild>+ <Link+ href="https://langfuse.com/docs/deployment/self-host#update"+ target="_blank"+ >+ <HardDriveDownload size={16} className="mr-2" />+ Update+ </Link>+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+};diff --git a/web/src/components/deleteButton.tsx b/web/src/components/deleteButton.tsxindex 5e732f307c..84336c09d8 100644--- a/web/src/components/deleteButton.tsx+++ b/web/src/components/deleteButton.tsx@@ -7,8 +7,8 @@ import {} from "@/src/components/ui/popover";import { Button } from "@/src/components/ui/button";import { TrashIcon } from "lucide-react";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";-import { type Scope } from "@/src/features/rbac/constants/roleAccessRights";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { type ProjectScope } from "@/src/features/rbac/constants/projectAccessRights";import { api } from "@/src/utils/api";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -16,7 +16,7 @@ interface DeleteButtonProps {itemId: string;projectId: string;isTableAction?: boolean;- scope: Scope;+ scope: ProjectScope;invalidateFunc: () => void;type: "trace" | "dataset";redirectUrl?: string;@@ -35,7 +35,7 @@ export function DeleteButton({const router = useRouter();const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({ projectId, scope: scope });+ const hasAccess = useHasProjectAccess({ projectId, scope: scope });const traceMutation = api.traces.deleteMany.useMutation({onSuccess: () => {setIsDeleted(true);diff --git a/web/src/components/json-editor.tsx b/web/src/components/json-editor.tsxindex 7ec38c7bc2..450e85886e 100644--- a/web/src/components/json-editor.tsx+++ b/web/src/components/json-editor.tsx@@ -7,8 +7,6 @@ import { useTheme } from "next-themes";import { cn } from "@/src/utils/tailwind";import { useState } from "react";-// todo: add json linting-export function JsonEditor({defaultValue,onChange,@@ -24,7 +22,7 @@ export function JsonEditor({}) {const { resolvedTheme } = useTheme();const codeMirrorTheme = resolvedTheme === "dark" ? tokyoNight : githubLight;-+// used to disable linter when field is emptyconst [linterEnabled, setLinterEnabled] = useState<boolean>(!!defaultValue && defaultValue !== "",diff --git a/web/src/components/layouts/header.tsx b/web/src/components/layouts/header.tsxindex b933930fb6..e9ae85c69f 100644--- a/web/src/components/layouts/header.tsx+++ b/web/src/components/layouts/header.tsx@@ -1,11 +1,41 @@-import { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/20/solid";+import { ChevronLeftIcon } from "@heroicons/react/20/solid";import Link from "next/link";-import { useRouter } from "next/router";-import { useSession } from "next-auth/react";import DocPopup from "@/src/components/layouts/doc-popup";import { type Status, StatusBadge } from "./status-badge";import { cn } from "@/src/utils/tailwind";import { Badge } from "@/src/components/ui/badge";+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbList,+ BreadcrumbSeparator,+} from "@/src/components/ui/breadcrumb";+import { Fragment } from "react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import {+ ChevronDownIcon,+ LoaderCircle,+ PlusIcon,+ Settings,+ Slash,+} from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { env } from "@/src/env.mjs";+import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";+import { useRouter } from "next/router";+import { useSession } from "next-auth/react";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import {+ createOrganizationRoute,+ createProjectRoute,+} from "@/src/features/setup/setupRoutes";export default function Header({level = "h2",@@ -20,24 +50,6 @@ export default function Header({level?: "h2" | "h3";className?: string;}) {- const router = useRouter();- const session = useSession();-- const currentPath = router.pathname;- const projectId = router.query.projectId;-- const project = session.data?.user?.projects.find((p) => p.id === projectId);- const breadcrumb = [- ...(project && projectId && currentPath !== "/project/[projectId]"- ? [- {- name: project.name,- href: `/project/${projectId as string}`,- },- ]- : []),- ...(props.breadcrumb ?? []),- ];const backHref =props.breadcrumb &&[...props.breadcrumb.map((i) => i.href).filter(Boolean)].pop();@@ -59,46 +71,19 @@ export default function Header({</Link></nav>) : null}- {(level === "h2" || props.breadcrumb) && breadcrumb.length ? (- <nav className="hidden sm:flex" aria-label="Breadcrumb">- <ol role="list" className="flex items-center space-x-4">- {breadcrumb.map(({ name, href }, index) => (- <li key={index}>- <div className="flex items-center">- {index !== 0 && (- <ChevronRightIcon- className="mr-4 h-5 w-5 flex-shrink-0 text-muted-foreground"- aria-hidden="true"- />- )}- {href ? (- <Link- href={href}- className="text-sm font-medium text-muted-foreground hover:text-primary"- >- {name}- </Link>- ) : (- <div className="text-sm font-medium text-muted-foreground">- {name}- </div>- )}- </div>- </li>- ))}- </ol>- </nav>+ {level === "h2" ? (+ <BreadcrumbComponent items={props.breadcrumb} />) : null}</div><div className="mt-2 flex flex-wrap items-center justify-between gap-2"><div className="flex items-center gap-3 md:gap-5"><div className="flex min-w-0 flex-row justify-center align-middle">{level === "h2" ? (- <h2 className="text-2xl font-bold leading-7 sm:truncate sm:text-3xl sm:tracking-tight">+ <h2 className="text-3xl font-bold leading-7 sm:tracking-tight">{props.title}</h2>) : (- <h3 className="text-lg font-bold leading-7 sm:truncate sm:text-xl sm:tracking-tight">+ <h3 className="text-xl font-bold leading-7 sm:tracking-tight">{props.title}</h3>)}@@ -133,3 +118,240 @@ export default function Header({</div>);}++const LoadingMenuItem = () => (+ <DropdownMenuItem>+ <LoaderCircle className="mr-1.5 h-4 w-4 animate-spin" /> Loading...+ </DropdownMenuItem>+);++const BreadcrumbComponent = ({+ items,+}: {+ items?: { name: string; href?: string }[];+}) => {+ const router = useRouter();+ const session = useSession();+ const { organization, project } = useQueryProjectOrOrganization();++ const organizations = session.data?.user?.organizations;++ const canCreateOrganizations = session.data?.user?.canCreateOrganizations;+ const canCreateProjects = useHasOrganizationAccess({+ organizationId: organization?.id,+ scope: "projects:create",+ });++ const getProjectPath = (projectId: string) =>+ router.query.projectId+ ? router.asPath.replace(router.query.projectId as string, projectId)+ : `/project/${projectId}`;++ const getOrgPath = (orgId: string) =>+ router.query.organizationId+ ? router.asPath.replace(router.query.organizationId as string, orgId)+ : `/organization/${orgId}`;++ return (+ <Breadcrumb>+ <BreadcrumbList>+ {organization && (+ <DropdownMenu>+ <DropdownMenuTrigger className="flex items-center gap-1">+ {organization?.name ?? "Organization"}+ <ChevronDownIcon className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <DropdownMenuItem className="font-semibold" asChild>+ <Link href="/" className="cursor-pointer">+ Organizations+ </Link>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <div className="max-h-36 overflow-y-auto">+ {organizations ? (+ organizations+ .sort((a, b) => {+ // sort demo org to the bottom+ const isDemoA = env.NEXT_PUBLIC_DEMO_ORG_ID === a.id;+ const isDemoB = env.NEXT_PUBLIC_DEMO_ORG_ID === b.id;+ if (isDemoA) return 1;+ if (isDemoB) return -1;+ return 0;+ })+ .map((dropdownOrg) => (+ <Fragment key={dropdownOrg.id}>+ {env.NEXT_PUBLIC_DEMO_ORG_ID === dropdownOrg.id && (+ <DropdownMenuSeparator />+ )}+ <DropdownMenuItem asChild>+ <Link+ href={getOrgPath(dropdownOrg.id)}+ className="flex cursor-pointer justify-between"+ >+ <span+ className="max-w-36 overflow-hidden overflow-ellipsis whitespace-nowrap"+ title={dropdownOrg.name}+ >+ {dropdownOrg.name}+ </span>+ <Button+ asChild+ variant="ghost"+ size="xs"+ className="-my-1 ml-4 mr-1 hover:bg-background"+ >+ <div+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ router.push(+ `/organization/${dropdownOrg.id}/settings`,+ );+ }}+ >+ <Settings size={12} />+ </div>+ </Button>+ </Link>+ </DropdownMenuItem>+ </Fragment>+ ))+ ) : (+ <LoadingMenuItem />+ )}+ </div>++ {canCreateOrganizations && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild>+ <Button+ variant="ghost"+ size="xs"+ data-testid="create-project-btn"+ className="h-8 w-full text-sm font-normal"+ asChild+ >+ <Link href={createOrganizationRoute}>+ <PlusIcon+ className="mr-1.5 h-4 w-4"+ aria-hidden="true"+ />+ New Organization+ </Link>+ </Button>+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {organization && project && (+ <>+ <BreadcrumbSeparator>+ <Slash />+ </BreadcrumbSeparator>+ <DropdownMenu>+ <DropdownMenuTrigger className="flex items-center gap-1">+ {project?.name ?? "Project"}+ <ChevronDownIcon className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <DropdownMenuItem asChild className="font-semibold">+ <Link+ href={`/organization/${organization.id}`}+ className="cursor-pointer"+ >+ Projects+ </Link>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <div className="max-h-36 overflow-y-auto">+ {organizations ? (+ organizations+ .find((org) => org.id === organization.id)+ ?.projects.map((dropdownProject) => (+ <DropdownMenuItem key={dropdownProject.id} asChild>+ <Link+ href={getProjectPath(dropdownProject.id)}+ className="flex cursor-pointer justify-between"+ >+ <span+ className="max-w-36 overflow-hidden overflow-ellipsis whitespace-nowrap"+ title={dropdownProject.name}+ >+ {dropdownProject.name}+ </span>+ <Button+ asChild+ variant="ghost"+ size="xs"+ className="-my-1 ml-4 mr-1 hover:bg-background"+ >+ <div+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ router.push(+ `/project/${dropdownProject.id}/settings`,+ );+ }}+ >+ <Settings size={12} />+ </div>+ </Button>+ </Link>+ </DropdownMenuItem>+ ))+ ) : (+ <LoadingMenuItem />+ )}+ </div>++ {canCreateProjects && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild>+ <Button+ variant="ghost"+ size="xs"+ data-testid="create-project-btn"+ className="h-8 w-full text-sm font-normal"+ asChild+ >+ <Link href={createProjectRoute(organization.id)}>+ <PlusIcon+ className="mr-1.5 h-4 w-4"+ aria-hidden="true"+ />+ New Project+ </Link>+ </Button>+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </>+ )}+ {items?.map((item, index) => (+ <Fragment key={index}>+ <BreadcrumbSeparator>+ <Slash />+ </BreadcrumbSeparator>+ <BreadcrumbItem key={index}>+ {item.href ? (+ <BreadcrumbLink asChild>+ <Link href={item.href}>{item.name}</Link>+ </BreadcrumbLink>+ ) : (+ <span>{item.name}</span>+ )}+ </BreadcrumbItem>+ </Fragment>+ ))}+ </BreadcrumbList>+ </Breadcrumb>+ );+};diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsxindex a987bef394..88cabba1a5 100644--- a/web/src/components/layouts/layout.tsx+++ b/web/src/components/layouts/layout.tsx@@ -2,7 +2,6 @@ import { ROUTES, type Route } from "@/src/components/layouts/routes";import { Fragment, type PropsWithChildren, useEffect, useState } from "react";import { Dialog, Disclosure, Menu, Transition } from "@headlessui/react";import { Bars3Icon, XMarkIcon } from "@heroicons/react/24/outline";-import Link from "next/link";import { useRouter } from "next/router";import clsx from "clsx";@@ -14,14 +13,13 @@ import {AvatarFallback,AvatarImage,} from "@/src/components/ui/avatar";-import { NewProjectButton } from "@/src/features/projects/components/NewProjectButton";import { FeedbackButtonWrapper } from "@/src/features/feedback/component/FeedbackButton";import { Button } from "@/src/components/ui/button";import Head from "next/head";import { env } from "@/src/env.mjs";import { LangfuseLogo } from "@/src/components/LangfuseLogo";import { Spinner } from "@/src/components/layouts/spinner";-import { hasAccess } from "@/src/features/rbac/utils/checkAccess";+import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { Toaster } from "@/src/components/ui/sonner";import {NOTIFICATIONS,@@ -29,10 +27,11 @@ import {} from "@/src/features/notifications/checkNotifications";import { ChevronDownIcon } from "@heroicons/react/20/solid";import useLocalStorage from "@/src/components/useLocalStorage";-import { ProjectNavigation } from "@/src/components/projectNavigation";import DOMPurify from "dompurify";import { ThemeToggle } from "@/src/features/theming/ThemeToggle";-import { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { EnvLabel } from "@/src/components/EnvLabel";+import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";+import { useOrgEntitlements } from "@/src/features/entitlements/hooks";const signOutUser = async () => {localStorage.clear();@@ -103,6 +102,10 @@ function useSessionWithRetryOnUnauthenticated() {export default function Layout(props: PropsWithChildren) {const [sidebarOpen, setSidebarOpen] = useState(false);const router = useRouter();+ const routerProjectId = router.query.projectId as string | undefined;+ const routerOrganizationId = router.query.organizationId as+ | string+ | undefined;const session = useSessionWithRetryOnUnauthenticated();useCheckNotification(NOTIFICATIONS, session.status === "authenticated");@@ -110,12 +113,19 @@ export default function Layout(props: PropsWithChildren) {const enableExperimentalFeatures =session.data?.environment.enableExperimentalFeatures ?? false;- const projectId = router.query.projectId as string | undefined;- const isEeEnabled = useIsEeEnabled();+ const entitlements = useOrgEntitlements();++ // project info based on projectId in the URL+ const { project, organization } = useQueryProjectOrOrganization();const mapNavigation = (route: Route): NavigationItem | null => {// Project-level routes- if (!projectId && route.pathname?.includes("[projectId]")) return null;+ if (!routerProjectId && route.pathname?.includes("[projectId]"))+ return null;++ // Organization-level routes+ if (!routerOrganizationId && route.pathname?.includes("[organizationId]"))+ return null;// Feature Flagsif (@@ -127,24 +137,21 @@ export default function Layout(props: PropsWithChildren) {)return null;- // check ee or cloud requirements+ // check entitlementsif (- route.requires !== undefined &&- !(- (route.requires === "cloud" &&- Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)) ||- (route.requires === "cloud-or-ee" && isEeEnabled)- )+ route.entitlement !== undefined &&+ !entitlements.includes(route.entitlement))return null;// RBACif (- route.rbacScope !== undefined &&- (!projectId ||- !hasAccess({- projectId,- scope: route.rbacScope,+ route.projectRbacScope !== undefined &&+ (!project ||+ !organization ||+ !hasProjectAccess({+ projectId: project.id,+ scope: route.projectRbacScope,session: session.data,})))@@ -156,7 +163,9 @@ export default function Layout(props: PropsWithChildren) {[];return {...route,- href: route.pathname?.replace("[projectId]", projectId ?? ""),+ href: route.pathname+ ?.replace("[projectId]", routerProjectId ?? "")+ .replace("[organizationId]", routerOrganizationId ?? ""),current: router.pathname === route.pathname,children:children.length > 0@@ -174,8 +183,6 @@ export default function Layout(props: PropsWithChildren) {const currentPathName = navigation.find(({ current }) => current)?.name;- const projects = session.data?.user?.projects ?? [];-if (session.status === "loading") return <Spinner message="Loading" />;// If the user has a token, but does not exist in the database, sign them out@@ -311,28 +318,11 @@ export default function Layout(props: PropsWithChildren) {</div></Transition.Child>{/* Sidebar component, swap this element with another sidebar if you like */}- <div className="flex grow flex-col gap-y-5 overflow-y-auto bg-background px-6 py-4">- <LangfuseLogo- version- size="xl"- showEnvLabel={session.data?.user?.email?.endsWith(- "@langfuse.com",- )}- />+ <div className="flex grow flex-col gap-y-5 overflow-y-auto bg-background px-4 py-3"><nav className="flex flex-1 flex-col"><ul role="list"><MainNavigation nav={navigation} /></ul>- <div className="mb-2 flex flex-row place-content-between items-center">- <div className="text-xs font-semibold text-muted-foreground">- Project- </div>- <NewProjectButton size="xs" />- </div>- <ProjectNavigation- currentProjectId={projectId ?? ""}- projects={projects}- /></nav></div></Dialog.Panel>@@ -344,17 +334,10 @@ export default function Layout(props: PropsWithChildren) {{/* Static sidebar for desktop */}<div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-56 lg:flex-col">{/* Sidebar component, swap this element with another sidebar if you like */}- <div className="flex h-screen grow flex-col border-r border-border bg-background pt-7">- <LangfuseLogo- version- size="xl"- className="mb-8 px-6"- showEnvLabel={session.data?.user?.email?.endsWith(- "@langfuse.com",- )}- />- <nav className="flex h-full flex-1 flex-col overflow-y-auto px-6 pb-3">+ <div className="flex h-screen grow flex-col border-r border-border bg-background">+ <nav className="flex h-full flex-1 flex-col overflow-y-auto px-4 py-3"><ul role="list" className="flex h-full flex-col">+ <EnvLabel className="my-2" /><MainNavigation nav={topNavigation} /><MainNavigation nav={bottomNavigation} className="mt-auto" /><FeedbackButtonWrapper@@ -371,21 +354,11 @@ export default function Layout(props: PropsWithChildren) {Feedback</li></FeedbackButtonWrapper>- <div className="mb-2 flex flex-row place-content-between items-center">- <div className="text-xs font-semibold text-muted-foreground">- Project- </div>- <NewProjectButton size="xs" />- </div>- <ProjectNavigation- currentProjectId={projectId ?? ""}- projects={projects}- /></ul></nav><Menu as="div" className="relative">- <Menu.Button className="flex w-full items-center gap-x-2 overflow-hidden p-1.5 py-3 pl-6 pr-8 text-sm font-semibold text-primary hover:bg-primary-foreground">+ <Menu.Button className="flex w-full items-center gap-x-2 overflow-hidden p-1.5 py-3 pl-3 pr-4 text-sm font-semibold text-primary hover:bg-primary-foreground"><span className="sr-only">Open user menu</span><Avatar className="h-7 w-7"><AvatarImage src={session.data?.user?.image ?? undefined} />@@ -514,10 +487,8 @@ export default function Layout(props: PropsWithChildren) {</div><div className="lg:pl-56">{env.NEXT_PUBLIC_DEMO_PROJECT_ID &&- projectId === env.NEXT_PUBLIC_DEMO_PROJECT_ID &&- (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING" ||- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "EU") &&- !session.data?.user?.email?.endsWith("@langfuse.com") ? (+ routerProjectId === env.NEXT_PUBLIC_DEMO_PROJECT_ID &&+ Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) ? (<div className="flex w-full items-center border-b border-dark-yellow bg-light-yellow px-4 py-2 lg:sticky lg:top-0 lg:z-40"><div className="flex flex-1 flex-wrap gap-1"><div className="flex items-center gap-1">@@ -528,19 +499,8 @@ export default function Layout(props: PropsWithChildren) {</div><Button size="sm" asChild className="ml-2">- <Link- href={- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "EU"- ? "https://langfuse.com/docs/demo"- : "https://docs-staging.langfuse.com/docs/demo" // staging- }- target="_blank"- >- {- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "EU"- ? "Use Chat ↗"- : "Use Chat (staging) ↗" // staging- }+ <Link href={"https://langfuse.com/docs/demo"} target="_blank">+ Use Chat ↗</Link></Button></div>@@ -584,7 +544,7 @@ const MainNavigation: React.FC<{item.current? "bg-primary-foreground text-primary-accent": "text-primary hover:bg-primary-foreground hover:text-primary-accent",- "group flex gap-x-3 rounded-md p-2 text-sm font-semibold",+ "group flex items-center gap-x-3 rounded-md p-2 text-sm font-semibold",)}onClick={onNavitemClick}target={item.newTab ? "_blank" : undefined}@@ -601,18 +561,22 @@ const MainNavigation: React.FC<{/>)}{item.name}- {item.label && (- <span- className={cn(- "-my-0.5 self-center whitespace-nowrap break-keep rounded-sm border px-1 py-0.5 text-xs",- item.current- ? "border-primary-accent text-primary-accent"- : "border-border text-muted-foreground group-hover:border-primary-accent group-hover:text-primary-accent",- )}- >- {item.label}- </span>- )}+ {item.label &&+ (typeof item.label === "string" ? (+ <span+ className={cn(+ "-my-0.5 self-center whitespace-nowrap break-keep rounded-sm border px-1 py-0.5 text-xs",+ item.current+ ? "border-primary-accent text-primary-accent"+ : "border-border text-muted-foreground group-hover:border-primary-accent group-hover:text-primary-accent",+ )}+ >+ {item.label}+ </span>+ ) : (+ // ReactNode+ item.label+ ))}</Link>) : item.children && item.children.length > 0 ? (<Disclosurediff --git a/web/src/components/layouts/routes.ts b/web/src/components/layouts/routes.tsxsimilarity index 63%rename from web/src/components/layouts/routes.tsrename to web/src/components/layouts/routes.tsxindex ff63488fe1..12888f1085 100644--- a/web/src/components/layouts/routes.ts+++ b/web/src/components/layouts/routes.tsx@@ -1,5 +1,5 @@import { type Flag } from "@/src/features/feature-flags/types";-import { type Scope } from "@/src/features/rbac/constants/roleAccessRights";+import { type ProjectScope } from "@/src/features/rbac/constants/projectAccessRights";import {Database,LayoutDashboard,@@ -12,22 +12,38 @@ import {LibraryBig,TerminalIcon,Lightbulb,+ Grid2X2,} from "lucide-react";+import { LangfuseIcon } from "@/src/components/LangfuseLogo";+import { type ReactNode } from "react";+import { VersionLabel } from "@/src/components/VersionLabel";+import { type Entitlement } from "@/src/features/entitlements/constants/entitlements";export type Route = {name: string;featureFlag?: Flag;- label?: string;- rbacScope?: Scope;- icon?: LucideIcon; // ignored for nested routes+ label?: string | ReactNode;+ projectRbacScope?: ProjectScope;+ icon?: LucideIcon | typeof LangfuseIcon; // ignored for nested routespathname?: string; // link, ignored if childrenchildren?: Array<Route>; // folderbottom?: boolean; // bottom of the sidebar, only for first level routesnewTab?: boolean; // open in new tab- requires?: "cloud" | "cloud-or-ee"; // feature requires cloud or ee+ entitlement?: Entitlement; // entitlement required};export const ROUTES: Route[] = [+ {+ name: "Langfuse",+ pathname: "/",+ icon: LangfuseIcon,+ label: <VersionLabel />,+ },+ {+ name: "Projects",+ pathname: "/organization/[organizationId]",+ icon: Grid2X2,+ },{name: "Dashboard",pathname: `/project/[projectId]`,@@ -62,26 +78,26 @@ export const ROUTES: Route[] = [{name: "Evaluation",icon: Lightbulb,- requires: "cloud",+ entitlement: "model-based-evaluations",label: "Beta",children: [{name: "Templates",pathname: `/project/[projectId]/evals/templates`,- requires: "cloud",- rbacScope: "evalTemplate:read",+ entitlement: "model-based-evaluations",+ projectRbacScope: "evalTemplate:read",},{name: "Configs",pathname: `/project/[projectId]/evals/configs`,- requires: "cloud",- rbacScope: "evalJob:read",+ entitlement: "model-based-evaluations",+ projectRbacScope: "evalJob:read",},{name: "Log",pathname: `/project/[projectId]/evals/log`,- requires: "cloud",- rbacScope: "evalJobExecution:read",+ entitlement: "model-based-evaluations",+ projectRbacScope: "evalJobExecution:read",},],},@@ -94,13 +110,13 @@ export const ROUTES: Route[] = [name: "Prompts",pathname: "/project/[projectId]/prompts",icon: PenSquareIcon,- rbacScope: "prompts:read",+ projectRbacScope: "prompts:read",},{name: "Playground",pathname: "/project/[projectId]/playground",icon: TerminalIcon,- requires: "cloud-or-ee",+ entitlement: "playground",},{name: "Datasets",@@ -113,6 +129,12 @@ export const ROUTES: Route[] = [icon: Settings,bottom: true,},+ {+ name: "Settings",+ pathname: "/organization/[organizationId]/settings",+ icon: Settings,+ bottom: true,+ },{name: "Docs",pathname: "https://langfuse.com/docs",@@ -122,7 +144,7 @@ export const ROUTES: Route[] = [},{name: "Support",- pathname: "/project/[projectId]/support",+ pathname: "/support",icon: LifeBuoy,bottom: true,},diff --git a/web/src/components/layouts/status-badge.tsx b/web/src/components/layouts/status-badge.tsxindex 8c3e2e6125..9f07365257 100644--- a/web/src/components/layouts/status-badge.tsx+++ b/web/src/components/layouts/status-badge.tsx@@ -1,7 +1,8 @@import { cn } from "@/src/utils/tailwind";const statusCategories = {- active: ["production", "live", "active", "pending"],+ active: ["production", "live", "active"],+ pending: ["pending", "waiting", "queued"],inactive: ["disabled", "inactive"],completed: ["completed", "done", "finished"],error: ["error", "failed"],@@ -20,6 +21,10 @@ export const StatusBadge = (props: { className?: string; type: Status }) => {badgeColor = "bg-light-green text-dark-green";dotColor = "animate-ping bg-dark-green";dotPingColor = "bg-dark-green";+ } else if (statusCategories.pending.includes(props.type)) {+ badgeColor = "bg-light-yellow text-dark-yellow";+ dotColor = "animate-ping bg-dark-yellow";+ dotPingColor = "bg-dark-yellow";} else if (statusCategories.error.includes(props.type)) {badgeColor = "bg-light-red text-dark-red";dotColor = "animate-ping bg-dark-red";diff --git a/web/src/components/publish-object-switch.tsx b/web/src/components/publish-object-switch.tsxindex 0b5633c03a..5a1bef8fa8 100644--- a/web/src/components/publish-object-switch.tsx+++ b/web/src/components/publish-object-switch.tsx@@ -1,6 +1,6 @@import { Switch } from "@/src/components/ui/switch";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { Link, LockIcon } from "lucide-react";import { useState } from "react";@@ -11,7 +11,7 @@ export const PublishTraceSwitch = (props: {isPublic: boolean;}) => {const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "objects:publish",});@@ -44,7 +44,7 @@ export const PublishSessionSwitch = (props: {isPublic: boolean;}) => {const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "objects:publish",});diff --git a/web/src/components/star-toggle.tsx b/web/src/components/star-toggle.tsxindex 985340e400..456ca649ef 100644--- a/web/src/components/star-toggle.tsx+++ b/web/src/components/star-toggle.tsx@@ -2,7 +2,7 @@ import { StarIcon } from "lucide-react";import { Button } from "@/src/components/ui/button";import { api } from "@/src/utils/api";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { cn } from "@/src/utils/tailwind";import { type RouterOutput, type RouterInput } from "@/src/utils/types";import { useState } from "react";@@ -54,7 +54,10 @@ export function StarTraceToggle({size?: "sm" | "xs";}) {const utils = api.useUtils();- const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "objects:bookmark",+ });const capture = usePostHogClientCapture();const [isLoading, setIsLoading] = useState(false);@@ -139,7 +142,10 @@ export function StarTraceDetailsToggle({size?: "sm" | "xs";}) {const utils = api.useUtils();- const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "objects:bookmark",+ });const capture = usePostHogClientCapture();const [isLoading, setIsLoading] = useState(false);@@ -214,7 +220,10 @@ export function StarSessionToggle({size?: "sm" | "xs";}) {const utils = api.useUtils();- const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "objects:bookmark",+ });const capture = usePostHogClientCapture();const mutBookmarkSession = api.sessions.bookmark.useMutation({onSuccess: () => {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 8b1d546ef9..553841f03b 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@@ -7,7 +7,7 @@ import {DropdownMenuItem,} from "@/src/components/ui/dropdown-menu";import { Button } from "@/src/components/ui/button";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import {@@ -34,7 +34,10 @@ export function TraceTableMultiSelectAction({const [open, setOpen] = useState(false);const capture = usePostHogClientCapture();- const hasDeleteAccess = useHasAccess({ projectId, scope: "traces:delete" });+ const hasDeleteAccess = useHasProjectAccess({+ projectId,+ scope: "traces:delete",+ });const mutDeleteTraces = api.traces.deleteMany.useMutation({onSuccess: () => {onDeleteSuccess();diff --git a/web/src/components/table/data-table-pagination.tsx b/web/src/components/table/data-table-pagination.tsxindex ee99d66b37..d0a03941d9 100644--- a/web/src/components/table/data-table-pagination.tsx+++ b/web/src/components/table/data-table-pagination.tsx@@ -63,7 +63,7 @@ export function DataTablePagination<TData>({</div><div className="flex items-center justify-center whitespace-nowrap text-sm font-medium">Page {table.getState().pagination.pageIndex + 1} of{" "}- {table.getPageCount()}+ {Math.max(table.getPageCount(), 1)}</div><div className="flex items-center space-x-2"><Buttondiff --git a/web/src/components/table/use-cases/models.tsx b/web/src/components/table/use-cases/models.tsxindex e7e0ec12f6..e5c5e25aeb 100644--- a/web/src/components/table/use-cases/models.tsx+++ b/web/src/components/table/use-cases/models.tsx@@ -9,7 +9,7 @@ import {import { useState } from "react";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { usdFormatter } from "@/src/utils/numbers";import { type Prisma, type Model } from "@langfuse/shared/src/db";@@ -333,7 +333,7 @@ const DeleteModelButton = ({},});- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId,scope: "models:CUD",});diff --git a/web/src/components/table/use-cases/score-configs.tsx b/web/src/components/table/use-cases/score-configs.tsxindex 116d3c7b40..5ec98fa780 100644--- a/web/src/components/table/use-cases/score-configs.tsx+++ b/web/src/components/table/use-cases/score-configs.tsx@@ -17,7 +17,7 @@ import {import { Archive } from "lucide-react";import { Button } from "@/src/components/ui/button";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {Popover,PopoverContent,@@ -73,7 +73,7 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {string[]>("emptySelectedConfigIds", []);- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: projectId,scope: "scoreConfigs:CUD",});diff --git a/web/src/components/ui/breadcrumb.tsx b/web/src/components/ui/breadcrumb.tsxnew file mode 100644index 0000000000..61a18ad8d0--- /dev/null+++ b/web/src/components/ui/breadcrumb.tsx@@ -0,0 +1,115 @@+import * as React from "react";+import { Slot } from "@radix-ui/react-slot";+import { ChevronRight, MoreHorizontal } from "lucide-react";++import { cn } from "@/src/utils/tailwind";++const Breadcrumb = React.forwardRef<+ HTMLElement,+ React.ComponentPropsWithoutRef<"nav"> & {+ separator?: React.ReactNode;+ }+>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);+Breadcrumb.displayName = "Breadcrumb";++const BreadcrumbList = React.forwardRef<+ HTMLOListElement,+ React.ComponentPropsWithoutRef<"ol">+>(({ className, ...props }, ref) => (+ <ol+ ref={ref}+ className={cn(+ "flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",+ className,+ )}+ {...props}+ />+));+BreadcrumbList.displayName = "BreadcrumbList";++const BreadcrumbItem = React.forwardRef<+ HTMLLIElement,+ React.ComponentPropsWithoutRef<"li">+>(({ className, ...props }, ref) => (+ <li+ ref={ref}+ className={cn("inline-flex items-center gap-1.5", className)}+ {...props}+ />+));+BreadcrumbItem.displayName = "BreadcrumbItem";++const BreadcrumbLink = React.forwardRef<+ HTMLAnchorElement,+ React.ComponentPropsWithoutRef<"a"> & {+ asChild?: boolean;+ }+>(({ asChild, className, ...props }, ref) => {+ const Comp = asChild ? Slot : "a";++ return (+ <Comp+ ref={ref}+ className={cn("transition-colors hover:text-foreground", className)}+ {...props}+ />+ );+});+BreadcrumbLink.displayName = "BreadcrumbLink";++const BreadcrumbPage = React.forwardRef<+ HTMLSpanElement,+ React.ComponentPropsWithoutRef<"span">+>(({ className, ...props }, ref) => (+ <span+ ref={ref}+ role="link"+ aria-disabled="true"+ aria-current="page"+ className={cn("font-normal text-foreground", className)}+ {...props}+ />+));+BreadcrumbPage.displayName = "BreadcrumbPage";++const BreadcrumbSeparator = ({+ children,+ className,+ ...props+}: React.ComponentProps<"li">) => (+ <li+ role="presentation"+ aria-hidden="true"+ className={cn("[&>svg]:size-3.5", className)}+ {...props}+ >+ {children ?? <ChevronRight />}+ </li>+);+BreadcrumbSeparator.displayName = "BreadcrumbSeparator";++const BreadcrumbEllipsis = ({+ className,+ ...props+}: React.ComponentProps<"span">) => (+ <span+ role="presentation"+ aria-hidden="true"+ className={cn("flex h-9 w-9 items-center justify-center", className)}+ {...props}+ >+ <MoreHorizontal className="h-4 w-4" />+ <span className="sr-only">More</span>+ </span>+);+BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";++export {+ Breadcrumb,+ BreadcrumbList,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbPage,+ BreadcrumbSeparator,+ BreadcrumbEllipsis,+};diff --git a/web/src/components/ui/button.tsx b/web/src/components/ui/button.tsxindex c2161ece52..da4c078efd 100644--- a/web/src/components/ui/button.tsx+++ b/web/src/components/ui/button.tsx@@ -6,13 +6,15 @@ import { cn } from "@/src/utils/tailwind";import { Loader2 } from "lucide-react";const buttonVariants = cva(- "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",+ "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",{variants: {variant: {default: "bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",+ "destructive-secondary":+ "bg-secondary text-secondary-foreground border border-destructive disabled:hover:bg-secondary disabled:hover:text-secondary-foreground hover:bg-destructive/90 hover:text-destructive-foreground",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:diff --git a/web/src/ee/features/evals/components/eval-config-detail.tsx b/web/src/ee/features/evals/components/eval-config-detail.tsxindex 7830ab9729..851f0f66c2 100644--- a/web/src/ee/features/evals/components/eval-config-detail.tsx+++ b/web/src/ee/features/evals/components/eval-config-detail.tsx@@ -3,7 +3,7 @@ import Header from "@/src/components/layouts/header";import { type RouterOutputs, api } from "@/src/utils/api";import { useRouter } from "next/router";import { EvalConfigForm } from "@/src/ee/features/evals/components/eval-config-form";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { Button } from "@/src/components/ui/button";import {Popover,@@ -132,7 +132,7 @@ export function DeactivateConfig({isLoading: boolean;}) {const utils = api.useUtils();- const hasAccess = useHasAccess({ projectId, scope: "evalJob:CUD" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "evalJob:CUD" });const [isOpen, setIsOpen] = useState(false);const capture = usePostHogClientCapture();diff --git a/web/src/ee/features/evals/components/eval-template-detail.tsx b/web/src/ee/features/evals/components/eval-template-detail.tsxindex a3ab06fe0a..da721bc74f 100644--- a/web/src/ee/features/evals/components/eval-template-detail.tsx+++ b/web/src/ee/features/evals/components/eval-template-detail.tsx@@ -12,7 +12,7 @@ import {SelectTrigger,SelectValue,} from "@/src/components/ui/select";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { Button } from "@/src/components/ui/button";import { Pencil } from "lucide-react";import { useState } from "react";@@ -142,7 +142,10 @@ export function UpdateTemplate({isLoading: boolean;setIsEditing: (isEditing: boolean) => void;}) {- const hasAccess = useHasAccess({ projectId, scope: "evalTemplate:create" });+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "evalTemplate:create",+ });const capture = usePostHogClientCapture();const handlePromptEdit = () => {diff --git a/web/src/ee/features/evals/pages/configs.tsx b/web/src/ee/features/evals/pages/configs.tsxindex 7bcbd25178..e641aab517 100644--- a/web/src/ee/features/evals/pages/configs.tsx+++ b/web/src/ee/features/evals/pages/configs.tsx@@ -2,7 +2,7 @@ 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 { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { Lock } from "lucide-react";import EvalConfigTable from "@/src/ee/features/evals/components/eval-config-table";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -12,7 +12,7 @@ export default function ConfigsPage() {const router = useRouter();const projectId = router.query.projectId as string;const capture = usePostHogClientCapture();- const hasWriteAccess = useHasAccess({+ const hasWriteAccess = useHasProjectAccess({projectId,scope: "evalJob:CUD",});diff --git a/web/src/ee/features/evals/pages/new-template.tsx b/web/src/ee/features/evals/pages/new-template.tsxindex c2b8d265d0..530429d156 100644--- a/web/src/ee/features/evals/pages/new-template.tsx+++ b/web/src/ee/features/evals/pages/new-template.tsx@@ -1,6 +1,6 @@import Header from "@/src/components/layouts/header";import { EvalTemplateForm } from "@/src/ee/features/evals/components/template-form";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useRouter } from "next/router";@@ -8,7 +8,10 @@ export default function NewTemplatesPage() {const router = useRouter();const projectId = router.query.projectId as string;- const hasAccess = useHasAccess({ projectId, scope: "evalTemplate:read" });+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "evalTemplate:read",+ });if (!hasAccess) {return null;diff --git a/web/src/ee/features/evals/pages/templates.tsx b/web/src/ee/features/evals/pages/templates.tsxindex 2707fe3f14..0972838118 100644--- a/web/src/ee/features/evals/pages/templates.tsx+++ b/web/src/ee/features/evals/pages/templates.tsx@@ -2,7 +2,7 @@ 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 { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { Lock } from "lucide-react";import EvalsTemplateTable from "@/src/ee/features/evals/components/eval-templates-table";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -11,7 +11,7 @@ export default function TemplatesPage() {const router = useRouter();const projectId = router.query.projectId as string;const capture = usePostHogClientCapture();- const hasWriteAccess = useHasAccess({+ const hasWriteAccess = useHasProjectAccess({projectId,scope: "evalTemplate:create",});diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.tsindex 530fa22eda..dcdb3c073a 100644--- a/web/src/ee/features/evals/server/router.ts+++ b/web/src/ee/features/evals/server/router.ts@@ -4,7 +4,7 @@ import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { auditLog } from "@/src/features/audit-logs/auditLog";import { DEFAULT_TRACE_JOB_DELAY, EvalTargetObject } from "@langfuse/shared";import {@@ -12,7 +12,7 @@ import {singleFilter,variableMapping,} from "@langfuse/shared";-import { env } from "@/src/env.mjs";+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";export const CreateEvalTemplate = z.object({name: z.string().min(1),@@ -38,11 +38,13 @@ export const evalRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalJob:read",@@ -83,10 +85,12 @@ export const evalRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalJob:read",@@ -113,10 +117,12 @@ export const evalRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalTemplate:read",@@ -140,10 +146,12 @@ export const evalRouter = createTRPCRouter({z.object({ projectId: z.string(), page: z.number(), limit: z.number() }),).query(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalTemplate:read",@@ -183,10 +191,12 @@ export const evalRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalTemplate:read",@@ -211,10 +221,12 @@ export const evalRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalTemplate:read",@@ -257,10 +269,12 @@ export const evalRouter = createTRPCRouter({).mutation(async ({ input, ctx }) => {try {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalJob:CUD",@@ -308,10 +322,12 @@ export const evalRouter = createTRPCRouter({createTemplate: protectedProjectProcedure.input(CreateEvalTemplate).mutation(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalTemplate:create",@@ -357,10 +373,12 @@ export const evalRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "evalJob:CUD",@@ -394,13 +412,15 @@ export const evalRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {- throw new Error("Evals available in cloud only");- }- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "model-based-evaluations",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,- scope: "evalJob:read",+ scope: "evalJobExecution:read",});const jobExecutions = await ctx.prisma.jobExecution.findMany({diff --git a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsxindex b424076f79..7c60b8df59 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 { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useHasOrgEntitlement } 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 isEeEnabled = useIsEeEnabled();+ const available = useHasOrgEntitlement("playground");useEffect(() => {if (props.source === "prompt") {@@ -57,7 +57,7 @@ export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (setPlaygroundCache(capturedState);};- if (!isEeEnabled) return null;+ if (!available) return null;return (<Buttondiff --git a/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsxindex 24de71db5f..988399a70c 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 { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";export const ResetPlaygroundButton: React.FC = () => {- const isEeEnabled = useIsEeEnabled();+ const available = useHasOrgEntitlement("playground");const router = useRouter();const { setPlaygroundCache } = usePlaygroundCache();@@ -16,7 +16,7 @@ export const ResetPlaygroundButton: React.FC = () => {router.reload();};- if (!isEeEnabled) return null;+ if (!available) return null;return (<Buttondiff --git a/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx b/web/src/ee/features/playground/page/components/SaveToPromptButton.tsxindex d01b6b614c..ace223794d 100644--- a/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx+++ b/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx@@ -24,10 +24,10 @@ 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 { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";export const SaveToPromptButton: React.FC = () => {- const isEeEnabled = useIsEeEnabled();+ const available = useHasOrgEntitlement("playground");const [selectedPromptId, setSelectedPromptId] = useState("");const { modelParams, messages, output, promptVariables } =usePlaygroundContext();@@ -83,7 +83,7 @@ export const SaveToPromptButton: React.FC = () => {);};- if (!isEeEnabled) return null;+ if (!available) return null;return (<Popover>diff --git a/web/src/ee/features/playground/page/hooks/usePlaygroundCache.ts b/web/src/ee/features/playground/page/hooks/usePlaygroundCache.tsindex e0842d5749..8ffc748112 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 { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";const playgroundCacheKey = "playgroundCache";export default function usePlaygroundCache() {const [cache, setCache] = useState<PlaygroundCache>(null);- const isEeEnabled = useIsEeEnabled();+ const available = useHasOrgEntitlement("playground");const setPlaygroundCache = (cache: PlaygroundCache) => {sessionStorage.setItem(playgroundCacheKey, JSON.stringify(cache));};@@ -24,7 +24,7 @@ export default function usePlaygroundCache() {}, []);return {- playgroundCache: isEeEnabled ? cache : null,- setPlaygroundCache: isEeEnabled ? setPlaygroundCache : () => {},+ playgroundCache: available ? cache : null,+ setPlaygroundCache: available ? setPlaygroundCache : () => {},};}diff --git a/web/src/ee/features/playground/page/index.tsx b/web/src/ee/features/playground/page/index.tsxindex 187d5c3a0e..91fb81a3aa 100644--- a/web/src/ee/features/playground/page/index.tsx+++ b/web/src/ee/features/playground/page/index.tsx@@ -3,11 +3,11 @@ 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 { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";export default function PlaygroundPage() {- const isEeAvailable = useIsEeEnabled();- if (!isEeAvailable) return null;+ const available = useHasOrgEntitlement("playground");+ if (!available) return null;return (<PlaygroundProvider><div className="flex h-[95vh] flex-col">diff --git a/web/src/ee/features/playground/server/authorizeRequest.ts b/web/src/ee/features/playground/server/authorizeRequest.tsindex cc0a6aa6dd..2e65539eb1 100644--- a/web/src/ee/features/playground/server/authorizeRequest.ts+++ b/web/src/ee/features/playground/server/authorizeRequest.ts@@ -3,7 +3,7 @@ import { getServerSession } from "next-auth";import { getAuthOptions } from "@/src/server/auth";import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";import { ApiError, ForbiddenError, UnauthorizedError } from "@langfuse/shared";-import { isEeEnabled } from "@/src/ee/utils/isEeEnabled";+import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";export type AuthorizeRequestResult = {userId: string;@@ -12,15 +12,20 @@ export type AuthorizeRequestResult = {export const authorizeRequestOrThrow = async (projectId: string,): Promise<AuthorizeRequestResult> => {- if (!isEeEnabled)- throw new ApiError(- "LLM Playground is not yet available in the v2 open-source version.",- );-const authOptions = await getAuthOptions();const session = await getServerSession(authOptions);if (!session?.user) throw new UnauthorizedError("Unauthenticated");+ const playgroundEntitlement = hasEntitlement({+ entitlement: "playground",+ projectId,+ sessionUser: session.user,+ });+ if (!playgroundEntitlement)+ throw new ApiError(+ "Your organization does not have access to the playground feature.",+ );+if (!isProjectMemberOrAdmin(session.user, projectId))throw new ForbiddenError("User is not a member of this project");diff --git a/web/src/env.mjs b/web/src/env.mjsindex 4a476e482d..ea5c418fdf 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -141,6 +141,14 @@ export const env = createEnv({LANGFUSE_ASYNC_INGESTION_PROCESSING: z.enum(["true", "false"]).default("false"),+ LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: z.string().optional().refine((value) => {+ if (!value) return true;++ const creators = value.split(",");+ const emailSchema = z.string().email()+ return creators.every((creator) => emailSchema.safeParse(creator).success);+ }, "LANGFUSE_ALLOWED_ORGANIZATION_CREATORS must be a comma separated list of valid email addresses")+ .transform((v) => (v === "" || v === undefined ? undefined : v)),},/**@@ -156,6 +164,7 @@ export const env = createEnv({.enum(["US", "EU", "STAGING", "DEV"]).optional(),NEXT_PUBLIC_DEMO_PROJECT_ID: z.string().optional(),+ NEXT_PUBLIC_DEMO_ORG_ID: z.string().optional(),NEXT_PUBLIC_SIGN_UP_DISABLED: z.enum(["true", "false"]).optional(),NEXT_PUBLIC_TURNSTILE_SITE_KEY: z.string().optional(),NEXT_PUBLIC_POSTHOG_KEY: z.string().optional(),@@ -170,6 +179,7 @@ export const env = createEnv({runtimeEnv: {SEED_SECRET_KEY: process.env.SEED_SECRET_KEY,NEXT_PUBLIC_DEMO_PROJECT_ID: process.env.NEXT_PUBLIC_DEMO_PROJECT_ID,+ NEXT_PUBLIC_DEMO_ORG_ID: process.env.NEXT_PUBLIC_DEMO_ORG_ID,DATABASE_URL: process.env.DATABASE_URL,NODE_ENV: process.env.NODE_ENV,NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,@@ -273,6 +283,7 @@ export const env = createEnv({process.env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS,LANGFUSE_ASYNC_INGESTION_PROCESSING:process.env.LANGFUSE_ASYNC_INGESTION_PROCESSING,+ LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,},// Skip validation in Docker builds// DOCKER_BUILD is set in Dockerfilediff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex 0cc9b9922f..da9fb72624 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -1,8 +1,9 @@-import { prisma as _prisma } from "@langfuse/shared/src/db";-import { type ProjectRole } from "@langfuse/shared";+import { prisma as _prisma, type Role } from "@langfuse/shared/src/db";export type AuditableResource =- | "membership"+ | "organization"+ | "orgMembership"+ | "projectMembership"| "membershipInvitation"| "datasetItem"| "dataset"@@ -18,7 +19,9 @@ export type AuditableResource =| "job"| "posthogIntegration"| "llmApiKey"- | "batchExport";+ | "batchExport"+ // legacy resources+ | "membership";type AuditLog = {resourceType: AuditableResource;@@ -28,30 +31,46 @@ type AuditLog = {after?: unknown;} & (| {- projectId: string;userId: string;- userProjectRole: ProjectRole;+ orgId: string;+ orgRole: Role;+ projectId?: string;+ projectRole?: Role;}| {session: {user: {id: string;};- projectRole: ProjectRole;- projectId: string;+ orgId: string;+ orgRole: Role;+ projectId?: string;+ projectRole?: Role;};});export async function auditLog(log: AuditLog, prisma?: typeof _prisma) {+ const meta =+ "session" in log+ ? {+ userId: log.session.user.id,+ orgId: log.session.orgId,+ userOrgRole: log.session.orgRole,+ projectId: log.session.projectId,+ userProjectRole: log.session.projectRole,+ }+ : {+ userId: log.userId,+ orgId: log.orgId,+ userOrgRole: log.orgRole,+ projectId: log.projectId,+ userProjectRole: log.projectRole,+ };+await (prisma ?? _prisma).auditLog.create({data: {- projectId: "projectId" in log ? log.projectId : log.session.projectId,- userId: "userId" in log ? log.userId : log.session.user.id,- userProjectRole:- "userProjectRole" in log- ? log.userProjectRole- : log.session.projectRole,+ ...meta,resourceType: log.resourceType,resourceId: log.resourceId,action: log.action,diff --git a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts b/web/src/features/auth/lib/createProjectMembershipsOnSignup.tsindex 452e1d2e18..e5772d0bc0 100644--- a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts+++ b/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts@@ -1,45 +1,45 @@import { env } from "@/src/env.mjs";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, Role } from "@langfuse/shared/src/db";export async function createProjectMembershipsOnSignup(user: {id: string;email: string | null;}) {try {- // Langfuse Cloud: Demo project access- const demoProjectId = env.NEXT_PUBLIC_DEMO_PROJECT_ID- ? (- await prisma.project.findUnique({+ // Langfuse Cloud: provide view-only access to the demo project, none access to the demo org+ const demoProject =+ env.NEXT_PUBLIC_DEMO_ORG_ID && env.NEXT_PUBLIC_DEMO_PROJECT_ID+ ? (await prisma.project.findUnique({where: {+ orgId: env.NEXT_PUBLIC_DEMO_ORG_ID,id: env.NEXT_PUBLIC_DEMO_PROJECT_ID,},- })- )?.id- : undefined;- if (demoProjectId !== undefined) {- await prisma.projectMembership.create({+ })) ?? undefined+ : undefined;+ if (demoProject !== undefined) {+ await prisma.organizationMembership.create({data: {- projectId: demoProjectId,userId: user.id,- role: "VIEWER",+ orgId: demoProject.orgId,+ role: Role.VIEWER,},});}+ // TODO: add LANGFUSE_DEFAULT_ORG_ID flow+// set default project access- const defaultProjectID = env.LANGFUSE_DEFAULT_PROJECT_ID- ? (- await prisma.project.findUnique({- where: {- id: env.LANGFUSE_DEFAULT_PROJECT_ID,- },- })- )?.id+ const defaultProject = env.LANGFUSE_DEFAULT_PROJECT_ID+ ? (await prisma.project.findUnique({+ where: {+ id: env.LANGFUSE_DEFAULT_PROJECT_ID,+ },+ })) ?? undefined: undefined;- if (defaultProjectID !== undefined) {- await prisma.projectMembership.create({+ if (defaultProject !== undefined) {+ await prisma.organizationMembership.create({data: {- projectId: defaultProjectID,+ orgId: defaultProject.orgId,userId: user.id,role: env.LANGFUSE_DEFAULT_PROJECT_ROLE ?? "VIEWER",},@@ -58,28 +58,39 @@ async function processMembershipInvitations(email: string, userId: string) {email: email.toLowerCase(),},});+ if (invitationsForUser.length === 0) return;- if (invitationsForUser.length > 0) {- const membershipsData = invitationsForUser.map((invitation) => {- return {- userId: userId,- projectId: invitation.projectId,- role: invitation.role,- };- });-- await prisma.$transaction([- prisma.projectMembership.createMany({- data: membershipsData,- }),- prisma.membershipInvitation.deleteMany({- where: {- id: {- in: invitationsForUser.map((invitation) => invitation.id),+ // Map to individual payloads instead of using createMany as we can thereby use nested writes for ProjectMemberships+ const createOrgMembershipData = invitationsForUser.map((invitation) => ({+ userId: userId,+ orgId: invitation.orgId,+ role: invitation.orgRole,+ ...(invitation.projectId && invitation.projectRole+ ? {+ ProjectMemberships: {+ create: {+ userId: userId,+ projectId: invitation.projectId,+ role: invitation.projectRole,+ },},- email: email.toLowerCase(),+ }+ : {}),+ }));++ const createOrgMembershipsPromises = createOrgMembershipData.map(+ (inviteData) => prisma.organizationMembership.create({ data: inviteData }),+ );++ await prisma.$transaction([+ ...createOrgMembershipsPromises,+ prisma.membershipInvitation.deleteMany({+ where: {+ id: {+ in: invitationsForUser.map((invitation) => invitation.id),},- }),- ]);- }+ email: email.toLowerCase(),+ },+ }),+ ]);}diff --git a/web/src/features/auth/lib/projectNameSchema.ts b/web/src/features/auth/lib/projectNameSchema.tsindex fc78481f91..405eae715f 100644--- a/web/src/features/auth/lib/projectNameSchema.ts+++ b/web/src/features/auth/lib/projectNameSchema.ts@@ -5,6 +5,7 @@ export const projectNameSchema = z.object({name: z.string().min(3, "Must have at least 3 characters")+ .max(30, "Must have at most 30 characters").refine((value) => noHtmlCheck(value), {message: "Input should not contain HTML",}),diff --git a/web/src/features/datasets/components/DatasetActionButton.tsx b/web/src/features/datasets/components/DatasetActionButton.tsxindex 99f1054af9..615da5cf80 100644--- a/web/src/features/datasets/components/DatasetActionButton.tsx+++ b/web/src/features/datasets/components/DatasetActionButton.tsx@@ -10,7 +10,7 @@ import {import { useState } from "react";import { DialogTrigger } from "@radix-ui/react-dialog";import { DatasetForm } from "@/src/features/datasets/components/DatasetForm";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { type Prisma } from "@langfuse/shared";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -47,7 +47,7 @@ type DatasetActionButtonProps =export const DatasetActionButton = (props: DatasetActionButtonProps) => {const capture = usePostHogClientCapture();const [open, setOpen] = useState(false);- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "datasets:CUD",});diff --git a/web/src/features/datasets/components/EditDatasetItem.tsx b/web/src/features/datasets/components/EditDatasetItem.tsxindex 9e789adb16..3ce50fb1cd 100644--- a/web/src/features/datasets/components/EditDatasetItem.tsx+++ b/web/src/features/datasets/components/EditDatasetItem.tsx@@ -12,7 +12,7 @@ import {FormMessage,} from "@/src/components/ui/form";import { Button } from "@/src/components/ui/button";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { JsonEditor } from "@/src/components/json-editor";import { type RouterOutput } from "@/src/utils/types";@@ -73,7 +73,7 @@ export const EditDatasetItem = ({}) => {const [formError, setFormError] = useState<string | null>(null);const [hasChanges, setHasChanges] = useState(false);- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: projectId,scope: "datasets:CUD",});diff --git a/web/src/features/datasets/components/NewDatasetItemButton.tsx b/web/src/features/datasets/components/NewDatasetItemButton.tsxindex a9c65b5816..8b3f365037 100644--- a/web/src/features/datasets/components/NewDatasetItemButton.tsx+++ b/web/src/features/datasets/components/NewDatasetItemButton.tsx@@ -8,7 +8,7 @@ import {import { useState } from "react";import { NewDatasetItemForm } from "@/src/features/datasets/components/NewDatasetItemForm";import { DialogTrigger } from "@radix-ui/react-dialog";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";export const NewDatasetItemButton = (props: {@@ -17,7 +17,7 @@ export const NewDatasetItemButton = (props: {className?: string;}) => {const [open, setOpen] = useState(false);- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "datasets:CUD",});diff --git a/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx b/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsxindex 42c1648a91..976eb86282 100644--- a/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx+++ b/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx@@ -19,7 +19,7 @@ import {import Link from "next/link";import { NewDatasetItemForm } from "@/src/features/datasets/components/NewDatasetItemForm";import { type Prisma } from "@langfuse/shared";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useSession } from "next-auth/react";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -44,7 +44,7 @@ export const NewDatasetItemFromTrace = (props: {enabled: session.status === "authenticated",},);- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "datasets:CUD",});diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.tsindex 9597be8591..37610d1a59 100644--- a/web/src/features/datasets/server/dataset-router.ts+++ b/web/src/features/datasets/server/dataset-router.ts@@ -9,7 +9,7 @@ import {Prisma,type Dataset,} from "@langfuse/shared/src/db";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { auditLog } from "@/src/features/audit-logs/auditLog";import { DB } from "@/src/server/db";import { paginationZod } from "@langfuse/shared";@@ -319,7 +319,7 @@ export const datasetRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "datasets:CUD",@@ -360,7 +360,6 @@ export const datasetRouter = createTRPCRouter({session: ctx.session,resourceType: "datasetItem",resourceId: input.datasetItemId,- projectId: input.projectId,action: "update",after: datasetItem,});@@ -376,7 +375,7 @@ export const datasetRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "datasets:CUD",@@ -399,7 +398,6 @@ export const datasetRouter = createTRPCRouter({session: ctx.session,resourceType: "dataset",resourceId: dataset.id,- projectId: input.projectId,action: "create",after: dataset,});@@ -417,7 +415,7 @@ export const datasetRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "datasets:CUD",@@ -444,7 +442,6 @@ export const datasetRouter = createTRPCRouter({session: ctx.session,resourceType: "dataset",resourceId: dataset.id,- projectId: input.projectId,action: "update",after: dataset,});@@ -454,7 +451,7 @@ export const datasetRouter = createTRPCRouter({deleteDataset: protectedProjectProcedure.input(z.object({ projectId: z.string(), datasetId: z.string() })).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "datasets:CUD",@@ -471,7 +468,6 @@ export const datasetRouter = createTRPCRouter({session: ctx.session,resourceType: "dataset",resourceId: deletedDataset.id,- projectId: input.projectId,action: "delete",before: deletedDataset,});@@ -490,7 +486,7 @@ export const datasetRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "datasets:CUD",@@ -537,7 +533,6 @@ export const datasetRouter = createTRPCRouter({session: ctx.session,resourceType: "datasetItem",resourceId: datasetItem.id,- projectId: input.projectId,action: "create",after: datasetItem,});diff --git a/web/src/features/entitlements/README.md b/web/src/features/entitlements/README.mdnew file mode 100644index 0000000000..4aa89b5b9a--- /dev/null+++ b/web/src/features/entitlements/README.md@@ -0,0 +1,15 @@+# Entitlements++This feature allows to control for availability of features. Entitlements are managed on the `organization` level.++## Concepts++- `Plan`: A plan is a a tier of features. Eg. `oss`, `cloud:pro`, `self-hosted:enterprise`. They are managed in `constants/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.++## How it works++- Plan is added to the organization object on the JWT via NextAuth.+- Mapping to 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.diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.tsnew file mode 100644index 0000000000..a10758eca9--- /dev/null+++ b/web/src/features/entitlements/constants/entitlements.ts@@ -0,0 +1,33 @@+import { type Plan } from "@/src/features/entitlements/constants/plans";++const entitlements = [+ // features+ "playground",+ "model-based-evaluations",+ "rbac-project-roles",+ "cloud-usage-metering",+ "integration-posthog",+ "batch-export",+] as const;++export type Entitlement = (typeof entitlements)[number];++const cloudAllPlansEntitlements: Entitlement[] = [+ "playground",+ "model-based-evaluations",+ "cloud-usage-metering",+ "integration-posthog",+ "batch-export",+];++export const entitlementAccess: Record<Plan, Entitlement[]> = {+ oss: [],+ "cloud:hobby": [...cloudAllPlansEntitlements],+ "cloud:pro": [...cloudAllPlansEntitlements],+ "cloud:team": [...cloudAllPlansEntitlements, "rbac-project-roles"],+ "self-hosted:enterprise": [+ "playground",+ "model-based-evaluations",+ "rbac-project-roles",+ ],+};diff --git a/web/src/features/entitlements/constants/plans.ts b/web/src/features/entitlements/constants/plans.tsnew file mode 100644index 0000000000..8ba4d9f710--- /dev/null+++ b/web/src/features/entitlements/constants/plans.ts@@ -0,0 +1,8 @@+const plans = [+ "oss",+ "cloud:hobby",+ "cloud:pro",+ "cloud:team",+ "self-hosted:enterprise",+] as const;+export type Plan = (typeof plans)[number];diff --git a/web/src/features/entitlements/hooks.ts b/web/src/features/entitlements/hooks.tsnew file mode 100644index 0000000000..3972afad09--- /dev/null+++ b/web/src/features/entitlements/hooks.ts@@ -0,0 +1,52 @@+import {+ entitlementAccess,+ type Entitlement,+} from "@/src/features/entitlements/constants/entitlements";+import { type Plan } from "@/src/features/entitlements/constants/plans";+import { useSession } from "next-auth/react";+import { useRouter } from "next/router";++/**+ * Hook to get the plan of the current organization or project.+ */+export const useOrganizationPlan = (): Plan | undefined => {+ const router = useRouter();+ const session = useSession();+ const projectId = router.query.projectId;+ const organizationId = router.query.organizationId;++ // if on an organization page, get the plan of the organization+ if (organizationId) {+ const org = session.data?.user?.organizations.find(+ (org) => org.id === organizationId,+ );+ return org?.plan ?? "oss";+ }++ // if on a project page, get the plan of the organization that the project belongs to+ if (projectId) {+ const org = session.data?.user?.organizations.find((org) =>+ org.projects.some((proj) => proj.id === projectId),+ );+ return org?.plan ?? "oss";+ }++ return undefined;+};++/**+ * Hook to get the entitlements of the current organization.+ */+export const useOrgEntitlements = (): Entitlement[] => {+ const plan = useOrganizationPlan();+ const availableEntitlements = entitlementAccess[plan ?? "oss"];+ return availableEntitlements;+};++/**+ * Hook to check if the current organization has a specific entitlement.+ */+export const useHasOrgEntitlement = (entitlement: Entitlement): boolean => {+ const orgEntitlements = useOrgEntitlements();+ return orgEntitlements.includes(entitlement);+};diff --git a/web/src/features/entitlements/server/getOrganizationPlan.ts b/web/src/features/entitlements/server/getOrganizationPlan.tsnew file mode 100644index 0000000000..2030636ac5--- /dev/null+++ b/web/src/features/entitlements/server/getOrganizationPlan.ts@@ -0,0 +1,32 @@+import { env } from "@/src/env.mjs";+import { type Plan } from "@/src/features/entitlements/constants/plans";+import { type CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";++/**+ * 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 {+ 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") {+ return "cloud:team";+ }+ if (cloudConfig) {+ switch (cloudConfig.plan) {+ case "Hobby":+ return "cloud:hobby";+ case "Pro":+ return "cloud:pro";+ case "Team":+ case "Enterprise":+ return "cloud:team";+ }+ }+ return "cloud:hobby";+ }++ if (env.LANGFUSE_EE_LICENSE_KEY !== undefined)+ return "self-hosted:enterprise";++ return "oss";+}diff --git a/web/src/features/entitlements/server/hasEntitlement.ts b/web/src/features/entitlements/server/hasEntitlement.tsnew file mode 100644index 0000000000..123e97cb6b--- /dev/null+++ b/web/src/features/entitlements/server/hasEntitlement.ts@@ -0,0 +1,38 @@+import {+ entitlementAccess,+ type Entitlement,+} from "@/src/features/entitlements/constants/entitlements";+import { TRPCError } from "@trpc/server";+import { type User } from "next-auth";++type HasEntitlementParams = {+ entitlement: Entitlement;+ sessionUser: User;+} & ({ projectId: string } | { orgId: string });++/**+ * Check if user has access to a specific entitlement based on the session user (to be used server-side).+ */+export const hasEntitlement = (p: HasEntitlementParams): Boolean => {+ if (p.sessionUser.admin) return true;+ 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";+ const availableEntitlements = entitlementAccess[plan];+ return availableEntitlements.includes(p.entitlement);+};++export const throwIfNoEntitlement = (p: HasEntitlementParams) => {+ if (!hasEntitlement(p)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message:+ "Unauthorized, user does not have access to entitlement: " ++ p.entitlement,+ });+ }+};diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.tsindex 318b6a21d0..4d348f5c1f 100644--- a/web/src/features/llm-api-key/server/router.ts+++ b/web/src/features/llm-api-key/server/router.ts@@ -1,7 +1,7 @@import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";import { CreateLlmApiKey } from "@/src/features/llm-api-key/types";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,protectedProjectProcedure,@@ -14,7 +14,6 @@ import {supportedModels,} from "@langfuse/shared";import { encrypt } from "@langfuse/shared/encryption";-import { isEeEnabled } from "@/src/ee/utils/isEeEnabled";export function getDisplaySecretKey(secretKey: string) {return "..." + secretKey.slice(-4);@@ -25,12 +24,7 @@ export const llmApiKeyRouter = createTRPCRouter({.input(CreateLlmApiKey).mutation(async ({ input, ctx }) => {try {- if (!isEeEnabled) {- throw new Error(- "LLM API keys are only required for model-based evaluations and the playground. Both are not yet available in the v2 open-source version.",- );- }- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "llmApiKeys:create",@@ -68,12 +62,7 @@ export const llmApiKeyRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- if (!isEeEnabled) {- throw new Error(- "LLM API keys are only required for model-based evaluations and the playground. Both are not yet available in the v2 open-source version.",- );- }- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "llmApiKeys:delete",@@ -100,13 +89,7 @@ export const llmApiKeyRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- if (!isEeEnabled) {- throw new Error(- "LLM API keys are only required for model-based evaluations and the playground. Both are not yet available in the v2 open-source version.",- );- }-- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "llmApiKeys:read",@@ -150,12 +133,6 @@ export const llmApiKeyRouter = createTRPCRouter({test: protectedProjectProcedure.input(CreateLlmApiKey).mutation(async ({ input }) => {- if (!isEeEnabled) {- throw new Error(- "LLM API keys are only required for model-based evaluations and the playground. Both are not yet available in the v2 open-source version.",- );- }-try {const model = input.customModels?.length? input.customModels[0]diff --git a/web/src/features/notifications/showSuccessToast.tsx b/web/src/features/notifications/showSuccessToast.tsxindex 45657bd11f..7c4267ba77 100644--- a/web/src/features/notifications/showSuccessToast.tsx+++ b/web/src/features/notifications/showSuccessToast.tsx@@ -4,15 +4,16 @@ import {type SuccessNotificationProps,} from "@/src/features/notifications/SuccessNotification";-export const showSuccessToast = (- params: Omit<SuccessNotificationProps, "onDismiss">,-) => {+export const showSuccessToast = ({+ duration = 5000,+ ...params+}: Omit<SuccessNotificationProps, "onDismiss"> & { duration?: number }) => {toast.custom((t) => (<SuccessNotification {...params} onDismiss={() => toast.dismiss(t)} />),{- duration: 5000,+ duration,style: {padding: "1rem",border: "1px solid hsl(var(--dark-green))",diff --git a/web/src/features/organizations/components/NewOrganizationForm.tsx b/web/src/features/organizations/components/NewOrganizationForm.tsxnew file mode 100644index 0000000000..94be9fbe0e--- /dev/null+++ b/web/src/features/organizations/components/NewOrganizationForm.tsx@@ -0,0 +1,84 @@+import { Button } from "@/src/components/ui/button";+import type * as z from "zod";+import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import { api } from "@/src/utils/api";+import { useSession } from "next-auth/react";+import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";++export const NewOrganizationForm = ({+ onSuccess,+}: {+ onSuccess: (orgId: string) => void;+}) => {+ const { update: updateSession } = useSession();++ const form = useForm<z.infer<typeof organizationNameSchema>>({+ resolver: zodResolver(organizationNameSchema),+ defaultValues: {+ name: "",+ },+ });+ const capture = usePostHogClientCapture();+ const createOrgMutation = api.organizations.create.useMutation({+ onError: (error) => form.setError("name", { message: error.message }),+ });++ function onSubmit(values: z.infer<typeof organizationNameSchema>) {+ capture("organizations:new_form_submit");+ createOrgMutation+ .mutateAsync({+ name: values.name,+ })+ .then((org) => {+ void updateSession();+ onSuccess(org.id);+ form.reset();+ })+ .catch((error) => {+ console.error(error);+ });+ }++ return (+ <Form {...form}>+ <form+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ onSubmit={form.handleSubmit(onSubmit)}+ className="space-y-4"+ data-testid="new-org-form"+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Organization name</FormLabel>+ <FormControl>+ <Input+ placeholder="my-org"+ {...field}+ data-testid="new-org-name-input"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Button type="submit" loading={createOrgMutation.isLoading}>+ Create+ </Button>+ </form>+ </Form>+ );+};diff --git a/web/src/features/organizations/components/ProjectOverview.tsx b/web/src/features/organizations/components/ProjectOverview.tsxnew file mode 100644index 0000000000..bc2368452c--- /dev/null+++ b/web/src/features/organizations/components/ProjectOverview.tsx@@ -0,0 +1,264 @@+import { Building2, LifeBuoy, LockIcon, Settings, Users } from "lucide-react";+import {+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import Header from "@/src/components/layouts/header";+import { Button } from "@/src/components/ui/button";+import { PlusIcon } from "lucide-react";+import Link from "next/link";+import { StringParam, useQueryParams } from "use-query-params";+import { Input } from "@/src/components/ui/input";+import { Alert, AlertTitle, AlertDescription } from "@/src/components/ui/alert";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { env } from "@/src/env.mjs";+import { Divider } from "@tremor/react";+import { Fragment } from "react";+import { useRouter } from "next/router";+import { useSession } from "next-auth/react";+import {+ createOrganizationRoute,+ createProjectRoute,+} from "@/src/features/setup/setupRoutes";++const SingleOrganizationProjectOverview = ({+ orgId,+ search,+ level = "h2",+}: {+ orgId: string;+ search?: string;+ level?: "h2" | "h3";+}) => {+ const createProjectAccess = useHasOrganizationAccess({+ organizationId: orgId,+ scope: "projects:create",+ });+ const membersViewAccess = useHasOrganizationAccess({+ organizationId: orgId,+ scope: "organizationMembers:read",+ });+ const session = useSession();+ const org = session.data?.user?.organizations.find((o) => o.id === orgId);++ if (!org) {+ return null;+ }++ const isDemoOrg =+ env.NEXT_PUBLIC_DEMO_ORG_ID === orgId &&+ org.projects.some((p) => p.id === env.NEXT_PUBLIC_DEMO_PROJECT_ID);++ if (isDemoOrg) {+ return (+ <div key={orgId}>+ {level === "h2" && <Header title="Demo Organization" />}+ <Card>+ <CardHeader>+ <CardTitle>Try Langfuse Demo</CardTitle>+ </CardHeader>+ <CardContent>+ We have built a Q&A chatbot that answers questions based on the+ Langfuse Docs. Interact with it to see traces in Langfuse.+ </CardContent>+ <CardFooter>+ <Button asChild variant="secondary">+ <Link href={`/project/${env.NEXT_PUBLIC_DEMO_PROJECT_ID}`}>+ View Demo Project+ </Link>+ </Button>+ </CardFooter>+ </Card>+ </div>+ );+ }++ return (+ <div key={orgId} className="mb-10">+ <Header+ title={org.name}+ level={level}+ status={orgId === env.NEXT_PUBLIC_DEMO_ORG_ID ? "Demo Org" : undefined}+ actionButtons={+ <>+ <Button asChild variant="ghost">+ <Link href={`/organization/${orgId}/settings`}>+ <Settings size={14} />+ </Link>+ </Button>+ {membersViewAccess && (+ <Button asChild variant="ghost">+ <Link href={`/organization/${orgId}/settings/members`}>+ <Users size={14} />+ </Link>+ </Button>+ )}+ {createProjectAccess ? (+ <Button asChild variant="secondary">+ <Link href={createProjectRoute(orgId)}>+ <PlusIcon className="mr-2 h-4 w-4" aria-hidden="true" />+ New project+ </Link>+ </Button>+ ) : (+ <Button variant="secondary" disabled>+ <LockIcon className="mr-2 h-4 w-4" aria-hidden="true" />+ New project+ </Button>+ )}+ </>+ }+ />+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">+ {org.projects+ .filter(+ (p) =>+ !search || p.name.toLowerCase().includes(search.toLowerCase()),+ )+ .map((project) => (+ <Card key={project.id}>+ <CardHeader>+ <CardTitle className="text-base">{project.name}</CardTitle>+ </CardHeader>+ <CardFooter className="gap-2">+ <Button asChild variant="secondary">+ <Link href={`/project/${project.id}`}>Go to project</Link>+ </Button>+ <Button asChild variant="ghost">+ <Link href={`/project/${project.id}/settings`}>+ <Settings size={16} />+ </Link>+ </Button>+ </CardFooter>+ </Card>+ ))}+ </div>+ </div>+ );+};++export const OrganizationProjectOverview = () => {+ const router = useRouter();+ const queryOrgId = router.query.organizationId;+ const session = useSession();+ const canCreateOrg = session.data?.user?.canCreateOrganizations;+ const organizations = session.data?.user?.organizations;+ const [{ search }, setQueryParams] = useQueryParams({ search: StringParam });++ if (organizations === undefined) {+ return "loading...";+ }++ const showOnboarding =+ organizations.filter((org) => org.id !== env.NEXT_PUBLIC_DEMO_ORG_ID)+ .length === 0 && !queryOrgId;++ return (+ <div className="md:container">+ {!queryOrgId && (+ <>+ <Header+ title="Home"+ actionButtons={+ <>+ <Input+ className="w-56"+ placeholder="Search projects"+ onChange={(e) => setQueryParams({ search: e.target.value })}+ />+ {canCreateOrg && (+ <Button data-testid="create-organization-btn" asChild>+ <Link href={createOrganizationRoute}>+ <PlusIcon className="mr-1.5 h-4 w-4" aria-hidden="true" />+ New Organization+ </Link>+ </Button>+ )}+ </>+ }+ />+ {!showOnboarding && <IntroducingOrganizations />}+ </>+ )}+ {showOnboarding && <Onboarding />}+ {organizations+ .filter((org) => queryOrgId === undefined || org.id === queryOrgId)+ .sort((a, b) => {+ // sort demo org to the bottom+ const isDemoA = env.NEXT_PUBLIC_DEMO_ORG_ID === a.id;+ const isDemoB = env.NEXT_PUBLIC_DEMO_ORG_ID === b.id;+ if (isDemoA) return 1;+ if (isDemoB) return -1;+ return 0;+ })+ .map((org) => (+ <Fragment key={org.id}>+ {!queryOrgId && org.id === env.NEXT_PUBLIC_DEMO_ORG_ID && (+ <Divider />+ )}+ <SingleOrganizationProjectOverview+ orgId={org.id}+ search={search ?? undefined}+ level={queryOrgId ? "h2" : "h3"}+ />+ </Fragment>+ ))}+ </div>+ );+};++const IntroducingOrganizations = () => (+ <Alert className="mb-10 mt-5">+ <Building2 className="h-4 w-4" />+ <AlertTitle>Introducing Organizations</AlertTitle>+ <AlertDescription>+ Organizations are a way to group projects and manage access to them. See{" "}+ <Link+ href="https://langfuse.com/changelog/2024-08-13-organizations"+ className="underline"+ target="_blank"+ >+ changelog+ </Link>{" "}+ to learn more.+ </AlertDescription>+ </Alert>+);++const Onboarding = () => {+ const session = useSession();+ const canCreateOrgs = session.data?.user?.canCreateOrganizations;+ return (+ <Card>+ <CardHeader>+ <CardTitle data-testid="create-new-project-title">+ Get Started+ </CardTitle>+ </CardHeader>+ <CardContent>+ {canCreateOrgs+ ? "Create an organization to get started. Alternatively, ask your organization admin to invite you."+ : "You need to get invited to an organization to get started with Langfuse."}+ </CardContent>+ <CardFooter className="flex gap-4">+ {canCreateOrgs && (+ <Button data-testid="create-project-btn" asChild>+ <Link href={createOrganizationRoute}>+ <PlusIcon className="mr-2 h-4 w-4" aria-hidden="true" />+ New Organization+ </Link>+ </Button>+ )}+ <Button variant="secondary" asChild>+ <Link href="/support">+ <LifeBuoy className="mr-2 h-4 w-4" aria-hidden="true" />+ Support+ </Link>+ </Button>+ </CardFooter>+ </Card>+ );+};diff --git a/web/src/features/organizations/components/RenameOrganization.tsx b/web/src/features/organizations/components/RenameOrganization.tsxnew file mode 100644index 0000000000..13042e6a6c--- /dev/null+++ b/web/src/features/organizations/components/RenameOrganization.tsx@@ -0,0 +1,130 @@+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { api } from "@/src/utils/api";+import type * as z from "zod";+import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormMessage,+} from "@/src/components/ui/form";+import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";+import Header from "@/src/components/layouts/header";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { useQueryOrganization } from "@/src/features/organizations/hooks";+import { Card } from "@/src/components/ui/card";+import { LockIcon } from "lucide-react";+import { useSession } from "next-auth/react";++export default function RenameOrganization() {+ const { update: updateSession } = useSession();+ const capture = usePostHogClientCapture();+ const organization = useQueryOrganization();+ const hasAccess = useHasOrganizationAccess({+ organizationId: organization?.id,+ scope: "organizations:update",+ });++ const orgName =+ organization && "name" in organization ? organization.name : "";++ const form = useForm<z.infer<typeof projectNameSchema>>({+ resolver: zodResolver(projectNameSchema),+ defaultValues: {+ name: "",+ },+ });+ const renameOrganization = api.organizations.update.useMutation({+ onSuccess: () => {+ void updateSession();+ },+ onError: (error) => form.setError("name", { message: error.message }),+ });++ function onSubmit(values: z.infer<typeof projectNameSchema>) {+ if (!organization || !hasAccess) return;+ capture("organization_settings:rename_form_submit");+ renameOrganization+ .mutateAsync({+ orgId: organization.id,+ name: values.name,+ })+ .then(() => {+ form.reset();+ })+ .catch((error) => {+ console.error(error);+ });+ }++ return (+ <div>+ <Header title="Organization Name" level="h3" />+ <Card className="mb-4 p-4">+ {form.getValues().name !== "" ? (+ <p className="mb-4 text-sm text-primary">+ Your Organization will be renamed from "+ {orgName}+ " to "+ <b>{form.watch().name}</b>".+ </p>+ ) : (+ <p className="mb-4 text-sm" data-testid="organization-name">+ Your Organization is currently named "<b>{orgName}</b>+ ".+ </p>+ )}+ <Form {...form}>+ <form+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ onSubmit={form.handleSubmit(onSubmit)}+ className="flex-1"+ data-testid="rename-organization-form"+ id="rename-organization-form"+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <div className="relative">+ <Input+ placeholder={orgName}+ {...field}+ className="flex-1"+ data-testid="new-organization-name-input"+ disabled={!hasAccess}+ />+ {!hasAccess && (+ <span title="No access">+ <LockIcon className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted" />+ </span>+ )}+ </div>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {hasAccess && (+ <Button+ variant="secondary"+ type="submit"+ loading={renameOrganization.isLoading}+ disabled={form.getValues().name === "" || !hasAccess}+ className="mt-4"+ >+ Save+ </Button>+ )}+ </form>+ </Form>+ </Card>+ </div>+ );+}diff --git a/web/src/features/organizations/hooks.ts b/web/src/features/organizations/hooks.tsnew file mode 100644index 0000000000..6aa3a117d0--- /dev/null+++ b/web/src/features/organizations/hooks.ts@@ -0,0 +1,24 @@+import { useSession } from "next-auth/react";+import { useRouter } from "next/router";++/**+ * Hook to get the organization of the current page.+ */+export const useQueryOrganization = () => {+ const router = useRouter();+ const organizationId = router.query.organizationId;+ return useOrganization(+ typeof organizationId === "string" ? organizationId : null,+ );+};++export const useOrganization = (organizationId: string | null) => {+ const session = useSession();+ if (organizationId === null) return null;++ const organization = session.data?.user?.organizations.find(+ (org) => org.id === organizationId,+ );++ return organization ?? null;+};diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsnew file mode 100644index 0000000000..a4f5f2c67b--- /dev/null+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -0,0 +1,86 @@+import {+ createTRPCRouter,+ protectedOrganizationProcedure,+ protectedProcedure,+} from "@/src/server/api/trpc";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";+import * as z from "zod";+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { TRPCError } from "@trpc/server";++export const organizationsRouter = createTRPCRouter({+ create: protectedProcedure+ .input(organizationNameSchema)+ .mutation(async ({ input, ctx }) => {+ if (!ctx.session.user.canCreateOrganizations)+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You do not have permission to create organizations",+ });++ const organization = await ctx.prisma.organization.create({+ data: {+ name: input.name,+ organizationMemberships: {+ create: {+ userId: ctx.session.user.id,+ role: "OWNER",+ },+ },+ },+ });+ await auditLog({+ resourceType: "organization",+ resourceId: organization.id,+ action: "create",+ orgId: organization.id,+ orgRole: "OWNER",+ userId: ctx.session.user.id,+ after: organization,+ });++ return {+ id: organization.id,+ name: organization.name,+ role: "OWNER",+ };+ }),+ update: protectedOrganizationProcedure+ .input(+ organizationNameSchema.extend({+ orgId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizations:update",+ });+ const beforeOrganization = await ctx.prisma.organization.findFirst({+ where: {+ id: input.orgId,+ },+ });+ const afterOrganization = await ctx.prisma.organization.update({+ where: {+ id: input.orgId,+ },+ data: {+ name: input.name,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "organization",+ resourceId: input.orgId,+ action: "update",+ before: beforeOrganization,+ after: afterOrganization,+ });++ return true;+ }),+});diff --git a/web/src/features/organizations/utils/cloudConfigSchema.ts b/web/src/features/organizations/utils/cloudConfigSchema.tsnew file mode 100644index 0000000000..0b43b2d3e9--- /dev/null+++ b/web/src/features/organizations/utils/cloudConfigSchema.ts@@ -0,0 +1,9 @@+import { z } from "zod";++export const CloudConfigSchema = z.object({+ plan: z.enum(["Hobby", "Pro", "Team", "Enterprise"]).optional(),+ monthlyObservationLimit: z.number().int().positive().optional(),+ // used for table and dashboard queries+ defaultLookBackDays: z.number().int().positive().optional(),+});+export type CloudConfigSchema = z.infer<typeof CloudConfigSchema>;diff --git a/web/src/features/organizations/utils/organizationNameSchema.ts b/web/src/features/organizations/utils/organizationNameSchema.tsnew file mode 100644index 0000000000..747e06a622--- /dev/null+++ b/web/src/features/organizations/utils/organizationNameSchema.ts@@ -0,0 +1,12 @@+import { noHtmlCheck } from "@langfuse/shared";+import * as z from "zod";++export const organizationNameSchema = z.object({+ name: z+ .string()+ .min(3, "Must have at least 3 characters")+ .max(30, "Must have at most 30 characters")+ .refine((value) => noHtmlCheck(value), {+ message: "Input should not contain HTML",+ }),+});diff --git a/web/src/features/organizations/utils/parseDbOrg.ts b/web/src/features/organizations/utils/parseDbOrg.tsnew file mode 100644index 0000000000..03e0ed5899--- /dev/null+++ b/web/src/features/organizations/utils/parseDbOrg.ts@@ -0,0 +1,19 @@+import { CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";+import { type Organization } from "@langfuse/shared";++type parsedOrg = Omit<Organization, "cloudConfig"> & {+ cloudConfig: CloudConfigSchema | null;+};++export function parseDbOrg(dbOrg: Organization): parsedOrg {+ const { cloudConfig, ...org } = dbOrg;++ const parsedCloudConfig = CloudConfigSchema.safeParse(cloudConfig);++ const parsedOrg = {+ ...org,+ cloudConfig: parsedCloudConfig.success ? parsedCloudConfig.data : null,+ };++ return parsedOrg;+}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex dc09dd961d..a4799932db 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -86,6 +86,7 @@ const events = {"update_form_submit","delete_form_submit",],+ organizations: ["new_form_submit", "new_form_open"],projects: ["new_form_submit", "new_form_open"],dataset_item: ["archive_toggle",@@ -116,6 +117,13 @@ const events = {"delete_membership","pricing_dialog_opened",],+ organization_settings: [+ "rename_form_submit",+ "send_membership_invitation",+ "delete_membership_invitation",+ "delete_membership",+ "pricing_dialog_opened",+ ],help_popup: ["opened", "href_clicked"],navigate_detail_pages: ["button_click_prev_or_next"],} as const;diff --git a/web/src/features/posthog-integration/posthog-integration-router.ts b/web/src/features/posthog-integration/posthog-integration-router.tsindex 172f2dc197..a1eeabde27 100644--- a/web/src/features/posthog-integration/posthog-integration-router.ts+++ b/web/src/features/posthog-integration/posthog-integration-router.ts@@ -1,7 +1,7 @@import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,protectedProjectProcedure,@@ -9,12 +9,18 @@ import {import { decrypt, encrypt } from "@langfuse/shared/encryption";import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";import { TRPCError } from "@trpc/server";+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";export const posthogIntegrationRouter = createTRPCRouter({get: protectedProjectProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "integration-posthog",+ sessionUser: ctx.session.user,+ projectId: input.projectId,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "integrations:CRUD",@@ -48,7 +54,12 @@ export const posthogIntegrationRouter = createTRPCRouter({.input(posthogIntegrationFormSchema.extend({ projectId: z.string() })).mutation(async ({ input, ctx }) => {try {- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "integration-posthog",+ sessionUser: ctx.session.user,+ projectId: input.projectId,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "integrations:CRUD",@@ -90,7 +101,12 @@ export const posthogIntegrationRouter = createTRPCRouter({.input(z.object({ projectId: z.string() })).mutation(async ({ input, ctx }) => {try {- throwIfNoAccess({+ throwIfNoEntitlement({+ entitlement: "integration-posthog",+ sessionUser: ctx.session.user,+ projectId: input.projectId,+ });+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "integrations:CRUD",diff --git a/web/src/features/pricing-page/PricingPage.tsx b/web/src/features/pricing-page/PricingPage.tsxindex b9ca4ac60f..5d56942ad1 100644--- a/web/src/features/pricing-page/PricingPage.tsx+++ b/web/src/features/pricing-page/PricingPage.tsx@@ -1,14 +1,14 @@-import { useSession } from "next-auth/react";+import { useQueryOrganization } from "@/src/features/organizations/hooks";import Script from "next/script";export function PricingPage(props: { className?: string }) {- const session = useSession();+ const org = useQueryOrganization();return (<><Script async src="https://js.stripe.com/v3/pricing-table.js" /><div className={props.className}><stripe-pricing-table- client-reference-id={session.data?.user?.id}+ client-reference-id={org?.id}pricing-table-id="prctbl_1OjTUyAWilt2EAVVMCMAMDgB"publishable-key="pk_live_51MPW00AWilt2EAVVFWfPTQhgmLA0EeacLSzAs6e3vECCcMBvwcMse81XgXO6k1bdBHbPBdpOmrXE8P1gBrxE7yhH00RPHQ8SyG"></stripe-pricing-table>diff --git a/web/src/features/projects/components/DeleteProjectButton.tsx b/web/src/features/projects/components/DeleteProjectButton.tsxindex 493a8302e7..acc2d7e619 100644--- a/web/src/features/projects/components/DeleteProjectButton.tsx+++ b/web/src/features/projects/components/DeleteProjectButton.tsx@@ -15,28 +15,22 @@ import {FormMessage,} from "@/src/components/ui/form";import { Input } from "@/src/components/ui/input";-import { useSession } from "next-auth/react";import { api } from "@/src/utils/api";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";import * as z from "zod";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import Header from "@/src/components/layouts/header";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useQueryProject } from "@/src/features/projects/hooks";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-export function DeleteProjectButton(props: { projectId: string }) {- const session = useSession();+export function DeleteProjectButton() {const capture = usePostHogClientCapture();//code for dynamic confirmation message- const userInfo = session.data?.user;- const currentProject = userInfo?.projects.find(- (project) => project.id == props.projectId,- );- const confirmMessage =- userInfo?.name?.replace(" ", "-") +- "/" +- currentProject?.name.replace(" ", "-");+ const { project, organization } = useQueryProject();+ const confirmMessage = (organization?.name + "/" + project?.name)+ .replaceAll(" ", "-")+ .toLowerCase();const formSchema = z.object({name: z.string().includes(confirmMessage, {@@ -44,8 +38,8 @@ export function DeleteProjectButton(props: { projectId: string }) {}),});- const hasAccess = useHasAccess({- projectId: props.projectId,+ const hasAccess = useHasProjectAccess({+ projectId: project?.id,scope: "project:delete",});@@ -60,10 +54,11 @@ export function DeleteProjectButton(props: { projectId: string }) {// delete project functionalityconst onSubmit = () => {+ if (!project) return;capture("project_settings:project_delete");deleteProject.mutateAsync({- projectId: props.projectId,+ projectId: project.id,}).then(() => {window.location.href = "/"; // browser reload to refresh jwt@@ -74,57 +69,54 @@ export function DeleteProjectButton(props: { projectId: string }) {};return (- <div>- <Header title="Danger Zone" level="h3" />- <Dialog>- <DialogTrigger asChild>- <Button variant="destructive" disabled={!hasAccess}>+ <Dialog>+ <DialogTrigger asChild>+ <Button variant="destructive-secondary" disabled={!hasAccess}>+ Delete Project+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle className="text-lg font-semibold ">Delete Project- </Button>- </DialogTrigger>- <DialogContent className="sm:max-w-[425px]">- <DialogHeader>- <DialogTitle className="text-lg font-semibold ">- Delete Project- </DialogTitle>- <DialogDescription className=" ">- {`To confirm, type "${confirmMessage}" in the input box `}- </DialogDescription>- </DialogHeader>- <Form {...form}>- <form- // eslint-disable-next-line @typescript-eslint/no-misused-promises- onSubmit={form.handleSubmit(onSubmit)}- className="space-y-8"+ </DialogTitle>+ <DialogDescription className=" ">+ {`To confirm, type "${confirmMessage}" in the input box `}+ </DialogDescription>+ </DialogHeader>+ <Form {...form}>+ <form+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ onSubmit={form.handleSubmit(onSubmit)}+ className="space-y-8"+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input+ placeholder={confirmMessage}+ {...field}+ data-testid="new-project-name-input"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Button+ type="submit"+ variant="destructive"+ loading={deleteProject.isLoading}+ className="w-full">- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormControl>- <Input- placeholder={confirmMessage}- {...field}- data-testid="new-project-name-input"- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <Button- type="submit"- variant="destructive"- loading={deleteProject.isLoading}- className="w-full"- >- Delete project- </Button>- </form>- </Form>- </DialogContent>- </Dialog>- </div>+ Delete project+ </Button>+ </form>+ </Form>+ </DialogContent>+ </Dialog>);}diff --git a/web/src/features/projects/components/HostNameProject.tsx b/web/src/features/projects/components/HostNameProject.tsxindex 97bd37590d..a8f8e5a6cd 100644--- a/web/src/features/projects/components/HostNameProject.tsx+++ b/web/src/features/projects/components/HostNameProject.tsx@@ -7,8 +7,8 @@ export function HostNameProject() {<div><Header title="Host Name" level="h3" /><Card className="mb-4 p-4">- <div className="mb-6">- <div className="my-2">+ <div className="">+ <div className="mb-2 text-sm">When connecting to Langfuse, use this hostname / baseurl.</div><CodeView content={window.origin} />diff --git a/web/src/features/projects/components/NewProjectButton.tsx b/web/src/features/projects/components/NewProjectButton.tsxdeleted file mode 100644index ebdbe6e0cd..0000000000--- a/web/src/features/projects/components/NewProjectButton.tsx+++ /dev/null@@ -1,136 +0,0 @@-import { Button } from "@/src/components/ui/button";-import { PlusIcon } from "lucide-react";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";-import type * as z from "zod";-import { zodResolver } from "@hookform/resolvers/zod";-import { useForm } from "react-hook-form";-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@/src/components/ui/form";-import { Input } from "@/src/components/ui/input";-import { api } from "@/src/utils/api";-import { useRouter } from "next/router";-import { cn } from "@/src/utils/tailwind";-import { useState } from "react";-import { useSession } from "next-auth/react";-import { chatRunTrigger } from "@/src/features/support-chat/chat";-import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";--interface NewProjectButtonProps {- size?: "xs" | "default";-}-export function NewProjectButton({ size = "default" }: NewProjectButtonProps) {- const [open, setOpen] = useState(false);- const { update: updateSession } = useSession();-- const form = useForm<z.infer<typeof projectNameSchema>>({- resolver: zodResolver(projectNameSchema),- defaultValues: {- name: "",- },- });- const utils = api.useUtils();- const router = useRouter();- const capture = usePostHogClientCapture();- const createProjectMutation = api.projects.create.useMutation({- onSuccess: (newProject) => {- void updateSession();- void router.push(`/project/${newProject.id}/settings`);- void utils.projects.invalidate();- },- onError: (error) => form.setError("name", { message: error.message }),- });-- function onSubmit(values: z.infer<typeof projectNameSchema>) {- capture("projects:new_form_submit");- createProjectMutation- .mutateAsync(values)- .then(() => {- setOpen(false);- form.reset();- })- .catch((error) => {- console.error(error);- });- chatRunTrigger("after-project-creation");- }-- return (- <Dialog- open={open}- onOpenChange={(open) => {- if (open) {- capture("projects:new_form_open");- }- setOpen(open);- }}- >- <DialogTrigger asChild>- <Button- size={size}- variant={size === "xs" ? "secondary" : "default"}- data-testid="create-project-btn"- >- <PlusIcon- className={cn(- "-ml-0.5 mr-1.5",- size === "xs" ? "h-4 w-4" : "h-5 w-5",- )}- aria-hidden="true"- />- {size !== "xs" ? "New project" : "New"}- </Button>- </DialogTrigger>- <DialogContent>- <DialogHeader>- <DialogTitle className="mb-5">New project</DialogTitle>- </DialogHeader>- <Form {...form}>- <form- // eslint-disable-next-line @typescript-eslint/no-misused-promises- onSubmit={form.handleSubmit(onSubmit)}- className="space-y-8"- data-testid="new-project-form"- >- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>Project name</FormLabel>- <FormControl>- <Input- placeholder="my-llm-project"- {...field}- data-testid="new-project-name-input"- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <Button- type="submit"- loading={createProjectMutation.isLoading}- className="w-full"- >- Create- </Button>- </form>- </Form>- </DialogContent>- </Dialog>- );-}diff --git a/web/src/features/projects/components/NewProjectForm.tsx b/web/src/features/projects/components/NewProjectForm.tsxnew file mode 100644index 0000000000..8422dc9273--- /dev/null+++ b/web/src/features/projects/components/NewProjectForm.tsx@@ -0,0 +1,93 @@+import { Button } from "@/src/components/ui/button";+import type * as z from "zod";+import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import { api } from "@/src/utils/api";+import { useRouter } from "next/router";+import { useSession } from "next-auth/react";+import { chatRunTrigger } from "@/src/features/support-chat/chat";+import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";++export const NewProjectForm = ({+ orgId,+ onSuccess,+}: {+ orgId: string;+ onSuccess: (projectId: string) => void;+}) => {+ const capture = usePostHogClientCapture();+ const { update: updateSession } = useSession();++ const form = useForm<z.infer<typeof projectNameSchema>>({+ resolver: zodResolver(projectNameSchema),+ defaultValues: {+ name: "",+ },+ });+ const router = useRouter();+ const createProjectMutation = api.projects.create.useMutation({+ onSuccess: (newProject) => {+ void updateSession();+ void router.push(`/project/${newProject.id}/settings`);+ },+ onError: (error) => form.setError("name", { message: error.message }),+ });++ function onSubmit(values: z.infer<typeof projectNameSchema>) {+ capture("projects:new_form_submit");+ createProjectMutation+ .mutateAsync({+ name: values.name,+ orgId,+ })+ .then((project) => {+ onSuccess(project.id);+ form.reset();+ })+ .catch((error) => {+ console.error(error);+ });+ chatRunTrigger("after-project-creation");+ }+ return (+ <Form {...form}>+ <form+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ onSubmit={form.handleSubmit(onSubmit)}+ className="space-y-4"+ data-testid="new-project-form"+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Project name</FormLabel>+ <FormControl>+ <Input+ placeholder="my-llm-project"+ {...field}+ data-testid="new-project-name-input"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Button type="submit" loading={createProjectMutation.isLoading}>+ Create+ </Button>+ </form>+ </Form>+ );+};diff --git a/web/src/features/projects/components/RenameProject.tsx b/web/src/features/projects/components/RenameProject.tsxindex ee2b6c4be0..5402489a68 100644--- a/web/src/features/projects/components/RenameProject.tsx+++ b/web/src/features/projects/components/RenameProject.tsx@@ -2,7 +2,6 @@ import { Card } from "@/src/components/ui/card";import { Button } from "@/src/components/ui/button";import { Input } from "@/src/components/ui/input";import { api } from "@/src/utils/api";-import { useSession } from "next-auth/react";import type * as z from "zod";import { zodResolver } from "@hookform/resolvers/zod";import { useForm } from "react-hook-form";@@ -13,22 +12,22 @@ import {FormItem,FormMessage,} from "@/src/components/ui/form";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";import Header from "@/src/components/layouts/header";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { LockIcon } from "lucide-react";+import { useQueryProject } from "@/src/features/projects/hooks";+import { useSession } from "next-auth/react";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-export default function RenameProject(props: { projectId: string }) {+export default function RenameProject() {+ const { update: updateSession } = useSession();+ const { project } = useQueryProject();const capture = usePostHogClientCapture();- const utils = api.useUtils();- const hasAccess = useHasAccess({- projectId: props.projectId,+ const hasAccess = useHasProjectAccess({+ projectId: project?.id,scope: "project:update",});- const { data: getSessionData, update: updateSession } = useSession();- const projectName = getSessionData?.user?.projects.find(- (p) => p.id === props.projectId,- )?.name;const form = useForm<z.infer<typeof projectNameSchema>>({resolver: zodResolver(projectNameSchema),@@ -39,16 +38,16 @@ export default function RenameProject(props: { projectId: string }) {const renameProject = api.projects.update.useMutation({onSuccess: (_) => {void updateSession();- void utils.projects.invalidate();},onError: (error) => form.setError("name", { message: error.message }),});function onSubmit(values: z.infer<typeof projectNameSchema>) {+ if (!hasAccess || !project) return;capture("project_settings:rename_form_submit");renameProject.mutateAsync({- projectId: props.projectId,+ projectId: project.id,newName: values.name,}).then(() => {@@ -59,20 +58,21 @@ export default function RenameProject(props: { projectId: string }) {});}- if (!hasAccess) return null;-return (<div><Header title="Project Name" level="h3" /><Card className="mb-4 p-4">{form.getValues().name !== "" ? (<p className="mb-4 text-sm text-primary">- Your Project will be renamed to "+ Your Project will be renamed from "+ {project?.name ?? ""}+ " to "<b>{form.watch().name}</b>".</p>) : (<p className="mb-4 text-sm text-primary" data-testid="project-name">- Your Project is currently named "<b>{projectName}</b>+ Your Project is currently named "+ <b>{project?.name ?? ""}</b>".</p>)}@@ -90,26 +90,36 @@ export default function RenameProject(props: { projectId: string }) {render={({ field }) => (<FormItem><FormControl>- <Input- placeholder={projectName}- {...field}- className="flex-1"- data-testid="new-project-name-input"- />+ <div className="relative">+ <Input+ placeholder={project?.name ?? ""}+ {...field}+ className="flex-1"+ data-testid="new-project-name-input"+ disabled={!hasAccess}+ />+ {!hasAccess && (+ <span title="No access">+ <LockIcon className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted" />+ </span>+ )}+ </div></FormControl><FormMessage /></FormItem>)}/>- <Button- variant="secondary"- type="submit"- loading={renameProject.isLoading}- disabled={form.getValues().name === ""}- className="mt-4"- >- Save- </Button>+ {hasAccess && (+ <Button+ variant="secondary"+ type="submit"+ loading={renameProject.isLoading}+ disabled={form.getValues().name === "" || !hasAccess}+ className="mt-4"+ >+ Save+ </Button>+ )}</form></Form></Card>diff --git a/web/src/features/projects/components/TransferOwnershipButton.tsx b/web/src/features/projects/components/TransferOwnershipButton.tsxdeleted file mode 100644index a4c6cfe019..0000000000--- a/web/src/features/projects/components/TransferOwnershipButton.tsx+++ /dev/null@@ -1,129 +0,0 @@-import { Button } from "@/src/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@/src/components/ui/form";-import { Input } from "@/src/components/ui/input";-import { api } from "@/src/utils/api";-import { useRouter } from "next/router";-import * as z from "zod";-import { useForm } from "react-hook-form";-import { zodResolver } from "@hookform/resolvers/zod";-import { useSession } from "next-auth/react";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";--const formSchema = z.object({- newOwnerEmail: z.string().email(),-});-export function TransferOwnershipButton(props: { projectId: string }) {- const utils = api.useUtils();- const router = useRouter();- const capture = usePostHogClientCapture();-- const session = useSession();- const project = session.data?.user?.projects.find(- (project) => project.id == props.projectId,- );- const hasAccess = useHasAccess({- projectId: props.projectId,- scope: "project:transfer",- });-- const form = useForm<z.infer<typeof formSchema>>({- resolver: zodResolver(formSchema),- defaultValues: {- newOwnerEmail: "",- },- });-- const transferProject = api.projects.transfer.useMutation({- onSuccess: () => utils.projects.invalidate(),- onError: (error) =>- form.setError("newOwnerEmail", { message: error.message }),- });-- function onSubmit(values: z.infer<typeof formSchema>) {- form.clearErrors();- transferProject- .mutateAsync({- projectId: props.projectId,- newOwnerEmail: values.newOwnerEmail,- })- .then(() => {- capture("project_settings:project_transfer");- void router.push("/");- })- .catch((error) => {- console.error(error);- });- }-- return (- <div>- <Dialog>- <DialogTrigger asChild>- <Button variant="destructive" disabled={!hasAccess}>- Transfer Ownership- </Button>- </DialogTrigger>- <DialogContent className="sm:max-w-[425px]">- <DialogHeader>- <DialogTitle className="text-lg font-semibold">- Transfer project{project?.name ? ` (${project.name})` : ""}- </DialogTitle>- <DialogDescription>- You will lose ownership of this project and will become an admin.- You cannot undo this action.- </DialogDescription>- </DialogHeader>- <Form {...form}>- <form- // eslint-disable-next-line @typescript-eslint/no-misused-promises- onSubmit={form.handleSubmit(onSubmit)}- className="space-y-8"- >- <FormField- control={form.control}- name="newOwnerEmail"- render={({ field }) => (- <FormItem>- <FormLabel>New owner</FormLabel>- <FormControl>- <Input- placeholder="[email protected]"- {...field}- data-testid="new-project-name-input"- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <Button- type="submit"- variant="destructive"- loading={transferProject.isLoading}- className="w-full"- >- Transfer project- </Button>- </form>- </Form>- </DialogContent>- </Dialog>- </div>- );-}diff --git a/web/src/features/projects/components/TransferProjectButton.tsx b/web/src/features/projects/components/TransferProjectButton.tsxnew file mode 100644index 0000000000..b63d54e45e--- /dev/null+++ b/web/src/features/projects/components/TransferProjectButton.tsx@@ -0,0 +1,204 @@+import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/src/components/ui/dialog";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import { api } from "@/src/utils/api";+import * as z from "zod";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import {+ hasOrganizationAccess,+ useHasOrganizationAccess,+} from "@/src/features/rbac/utils/checkOrganizationAccess";+import { useQueryProject } from "@/src/features/projects/hooks";+import { useSession } from "next-auth/react";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+import { TriangleAlert } from "lucide-react";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";++export function TransferProjectButton() {+ const capture = usePostHogClientCapture();+ const session = useSession();+ const { project, organization } = useQueryProject();+ const hasAccess = useHasOrganizationAccess({+ organizationId: organization?.id,+ scope: "projects:transfer_org",+ });+ const allOrgs = session.data?.user?.organizations ?? [];+ const organizationsToTransferTo =+ allOrgs.filter((org) =>+ hasOrganizationAccess({+ session: session.data,+ organizationId: org.id,+ scope: "projects:transfer_org",+ }),+ ) ?? [];+ const confirmMessage = (organization?.name + "/" + project?.name)+ .replaceAll(" ", "-")+ .toLowerCase();++ const formSchema = z.object({+ name: z.string().includes(confirmMessage, {+ message: `Please confirm with "${confirmMessage}"`,+ }),+ projectId: z.string(),+ });++ const transferProject = api.projects.transfer.useMutation({+ onSuccess: async () => {+ showSuccessToast({+ title: "Project transferred",+ description:+ "The project is successfully transferred to the new organization. Redirecting...",+ });+ await new Promise((resolve) => setTimeout(resolve, 5000));+ void session.update();+ window.location.href = "/";+ },+ });++ const form = useForm<z.infer<typeof formSchema>>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ name: "",+ projectId: "",+ },+ });++ const onSubmit = (values: z.infer<typeof formSchema>) => {+ if (!project) return;+ capture("project_settings:project_delete");+ transferProject.mutate({+ projectId: project.id,+ targetOrgId: values.projectId,+ });+ };++ return (+ <Dialog>+ <DialogTrigger asChild>+ <Button variant="destructive-secondary" disabled={!hasAccess}>+ Transfer Project+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle className="text-lg font-semibold">+ Transfer Project+ </DialogTitle>+ </DialogHeader>+ <Alert className="mt-2">+ <TriangleAlert className="h-4 w-4" />+ <AlertTitle>Warning</AlertTitle>+ <AlertDescription>+ Transferring the project will move it to a different organization:+ <ul className="list-disc pl-4">+ <li>+ Members who are not part of the new organization will lose+ access.+ </li>+ <li>+ The project remains fully operational as API keys, settings, and+ data will remain unchanged. All features (e.g. tracing, prompt+ management) will continue to work without interruption.+ </li>+ </ul>+ </AlertDescription>+ </Alert>+ <Form {...form}>+ <form+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ onSubmit={form.handleSubmit(onSubmit)}+ className="mt-8 space-y-8"+ >+ <FormField+ control={form.control}+ name="projectId"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Select New Organization</FormLabel>+ <FormControl>+ <Select+ onValueChange={field.onChange}+ value={field.value}+ disabled={transferProject.isLoading}+ >+ <SelectTrigger>+ <SelectValue placeholder="Select organization" />+ </SelectTrigger>+ <SelectContent>+ {organizationsToTransferTo+ .filter((org) => org.id !== organization?.id)+ .map((org) => (+ <SelectItem key={org.id} value={org.id}>+ {org.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormControl>+ <FormDescription>+ Transfer this project to another organization where you have+ the ability to create projects.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Confirm</FormLabel>+ <FormControl>+ <Input+ placeholder={confirmMessage}+ {...field}+ data-testid="new-project-name-input"+ />+ </FormControl>+ <FormDescription>+ {`To confirm, type "${confirmMessage}" in the input box `}+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <Button+ type="submit"+ variant="destructive"+ loading={transferProject.isLoading}+ className="w-full"+ >+ Transfer project+ </Button>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/projects/hooks.ts b/web/src/features/projects/hooks.tsnew file mode 100644index 0000000000..2bf12faf22--- /dev/null+++ b/web/src/features/projects/hooks.ts@@ -0,0 +1,41 @@+import { useQueryOrganization } from "@/src/features/organizations/hooks";+import { useSession } from "next-auth/react";+import { useRouter } from "next/router";++export const useQueryProject = () => {+ const router = useRouter();+ const projectId = router.query.projectId;+ return useProject(typeof projectId === "string" ? projectId : null);+};++export const useProject = (projectId: string | null) => {+ const session = useSession();+ if (projectId === null) return { project: null, organization: null };++ const data = session.data?.user?.organizations+ // map to {project, organization}[]+ .flatMap((org) =>+ org.projects.map((project) => ({ project, organization: org })),+ )+ // find the project with the matching id+ .find(({ project }) => project.id === projectId);++ if (!data)+ return {+ project: null,+ organization: null,+ };++ // explicitly destructuring the data object to make it clear what is being returned+ return {+ project: data.project,+ organization: data.organization,+ };+};++export const useQueryProjectOrOrganization = () => {+ const p = useQueryProject();+ const o = useQueryOrganization();++ return p.project ? p : { organization: o, project: null };+};diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.tsindex 4db2784e9a..172d5c46e1 100644--- a/web/src/features/projects/server/projectsRouter.ts+++ b/web/src/features/projects/server/projectsRouter.ts@@ -1,80 +1,40 @@import {createTRPCRouter,- protectedProcedure,+ protectedOrganizationProcedure,protectedProjectProcedure,} from "@/src/server/api/trpc";import * as z from "zod";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { TRPCError } from "@trpc/server";import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { cloudConfigSchema } from "@/src/server/auth";+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";export const projectsRouter = createTRPCRouter({- all: protectedProcedure.query(async ({ ctx }) => {- const memberships = await ctx.prisma.projectMembership.findMany({- where: {- userId: ctx.session.user.id,- },- include: {- project: true,- },- });- const projects = memberships.map((membership) => ({- id: membership.project.id,- name: membership.project.name,- role: membership.role,- }));-- return projects;- }),- byId: protectedProcedure- .input(- z.object({- projectId: z.string(),- }),- )- .query(async ({ input, ctx }) => {- const project = await ctx.prisma.project.findUnique({- where: {- id: input.projectId,- },- });- if (!project) throw new TRPCError({ code: "NOT_FOUND" });-- const cloudConfig = cloudConfigSchema.safeParse(project.cloudConfig);-- return {- ...project,- cloudConfig: cloudConfig.success ? cloudConfig.data : null,- };- }),-- create: protectedProcedure+ create: protectedOrganizationProcedure.input(z.object({name: z.string(),+ orgId: z.string(),}),).mutation(async ({ input, ctx }) => {+ throwIfNoOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "projects:create",+ });const project = await ctx.prisma.project.create({data: {name: input.name,- projectMembers: {- create: {- userId: ctx.session.user.id,- role: "OWNER",- },- },+ orgId: input.orgId,},});await auditLog({+ session: ctx.session,resourceType: "project",resourceId: project.id,action: "create",- userId: ctx.session.user.id,- projectId: project.id,- userProjectRole: "OWNER",after: project,});@@ -93,7 +53,7 @@ export const projectsRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "project:update",@@ -102,6 +62,7 @@ export const projectsRouter = createTRPCRouter({const project = await ctx.prisma.project.update({where: {id: input.projectId,+ orgId: ctx.session.orgId,},data: {name: input.newName,@@ -124,21 +85,28 @@ export const projectsRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,- projectId: input.projectId,+ projectId: ctx.session.projectId,scope: "project:delete",});+ const beforeProject = await ctx.prisma.project.findUnique({+ where: {+ id: input.projectId,+ },+ });await auditLog({session: ctx.session,resourceType: "project",resourceId: input.projectId,+ before: beforeProject,action: "delete",});await ctx.prisma.project.delete({where: {id: input.projectId,+ orgId: ctx.session.orgId,},});@@ -149,62 +117,51 @@ export const projectsRouter = createTRPCRouter({.input(z.object({projectId: z.string(),- newOwnerEmail: z.string().email(),+ targetOrgId: z.string(),}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ // source org+ throwIfNoOrganizationAccess({session: ctx.session,- projectId: input.projectId,- scope: "project:transfer",+ organizationId: ctx.session.orgId,+ scope: "projects:transfer_org",+ });+ // destination org+ throwIfNoOrganizationAccess({+ session: ctx.session,+ organizationId: input.targetOrgId,+ scope: "projects:transfer_org",});- // Check if new owner exists- const newOwner = await ctx.prisma.user.findUnique({+ const project = await ctx.prisma.project.findUnique({where: {- email: input.newOwnerEmail.toLowerCase(),+ id: input.projectId,},});- if (!newOwner) throw new Error("User not found");- if (newOwner.id === ctx.session.user.id)- throw new Error("You cannot transfer project to yourself");+ if (!project) throw new TRPCError({ code: "NOT_FOUND" });await auditLog({session: ctx.session,resourceType: "project",resourceId: input.projectId,action: "transfer",- after: { ownerId: newOwner.id },+ before: { orgId: ctx.session.orgId },+ after: { orgId: input.targetOrgId },});-- return ctx.prisma.$transaction([- // Add new owner, upsert to update role if already exists- ctx.prisma.projectMembership.upsert({+ await ctx.prisma.$transaction([+ ctx.prisma.projectMembership.deleteMany({where: {- projectId_userId: {- projectId: input.projectId,- userId: newOwner.id,- },- },- update: {- role: "OWNER",- },- create: {- userId: newOwner.id,projectId: input.projectId,- role: "OWNER",},}),- // Update old owner to admin- ctx.prisma.projectMembership.update({+ ctx.prisma.project.update({where: {- projectId_userId: {- projectId: input.projectId,- userId: ctx.session.user.id,- },+ id: input.projectId,+ orgId: ctx.session.orgId,},data: {- role: "ADMIN",+ orgId: input.targetOrgId,},}),]);diff --git a/web/src/features/prompts/components/SetPromptVersionLabels/index.tsx b/web/src/features/prompts/components/SetPromptVersionLabels/index.tsxindex 6d44a6a984..47b67e1aad 100644--- a/web/src/features/prompts/components/SetPromptVersionLabels/index.tsx+++ b/web/src/features/prompts/components/SetPromptVersionLabels/index.tsx@@ -14,7 +14,7 @@ import {PopoverContent,PopoverTrigger,} from "@/src/components/ui/popover";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";import { api } from "@/src/utils/api";import { type Prompt } from "@langfuse/shared";@@ -28,7 +28,7 @@ export function SetPromptVersionLabels({ prompt }: { prompt: Prompt }) {const projectId = useProjectIdFromURL();const utils = api.useUtils();const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({ projectId, scope: "prompts:CUD" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "prompts:CUD" });const [selectedLabels, setSelectedLabels] = useState<string[]>([]);const [labels, setLabels] = useState<string[]>([]);diff --git a/web/src/features/prompts/components/delete-prompt-version.tsx b/web/src/features/prompts/components/delete-prompt-version.tsxindex 842234cfab..8e950c46d7 100644--- a/web/src/features/prompts/components/delete-prompt-version.tsx+++ b/web/src/features/prompts/components/delete-prompt-version.tsx@@ -1,5 +1,5 @@import { Button } from "@/src/components/ui/button";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { Trash } from "lucide-react";import { useState } from "react";@@ -26,7 +26,7 @@ export function DeletePromptVersion({const utils = api.useUtils();const router = useRouter();const [isOpen, setIsOpen] = useState(false);- const hasAccess = useHasAccess({ projectId, scope: "prompts:CUD" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "prompts:CUD" });const mutDeletePromptVersion = api.prompts.deleteVersion.useMutation({onSuccess: () => {diff --git a/web/src/features/prompts/components/delete-prompt.tsx b/web/src/features/prompts/components/delete-prompt.tsxindex 842c2de9a5..75f3e27003 100644--- a/web/src/features/prompts/components/delete-prompt.tsx+++ b/web/src/features/prompts/components/delete-prompt.tsx@@ -1,5 +1,5 @@import { Button } from "@/src/components/ui/button";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { Trash } from "lucide-react";import { useState } from "react";@@ -14,7 +14,7 @@ export function DeletePrompt({ promptName }: { promptName: string }) {const projectId = useProjectIdFromURL();const utils = api.useUtils();const [isOpen, setIsOpen] = useState(false);- const hasAccess = useHasAccess({ projectId, scope: "prompts:CUD" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "prompts:CUD" });const mutDeletePrompt = api.prompts.delete.useMutation({onSuccess: () => {diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsxindex 7e6bccd3ff..5ffa8ee22a 100644--- a/web/src/features/prompts/components/prompts-table.tsx+++ b/web/src/features/prompts/components/prompts-table.tsx@@ -8,7 +8,7 @@ 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 { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";import { api } from "@/src/utils/api";import { type RouterOutput } from "@/src/utils/types";@@ -40,7 +40,7 @@ export function PromptTable() {const projectId = useProjectIdFromURL();const { setDetailPageList } = useDetailPageLists();- const hasCUDAccess = useHasAccess({+ const hasCUDAccess = useHasProjectAccess({projectId,scope: "prompts:CUD",});diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.tsindex b44db892c9..5bb16cd1e1 100644--- a/web/src/features/prompts/server/routers/promptRouter.ts+++ b/web/src/features/prompts/server/routers/promptRouter.ts@@ -2,7 +2,7 @@ import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";import { CreatePromptTRPCSchema } from "@/src/features/prompts/server/utils/validation";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,protectedProjectProcedure,@@ -34,7 +34,7 @@ export const promptRouter = createTRPCRouter({all: protectedProjectProcedure.input(PromptFilterOptions).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "prompts:read",@@ -146,7 +146,7 @@ export const promptRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "prompts:read",@@ -162,7 +162,7 @@ export const promptRouter = createTRPCRouter({.input(CreatePromptTRPCSchema).mutation(async ({ input, ctx }) => {try {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "prompts:CUD",@@ -253,7 +253,7 @@ export const promptRouter = createTRPCRouter({try {const { projectId, promptName } = input;- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId,scope: "prompts:CUD",@@ -313,7 +313,7 @@ export const promptRouter = createTRPCRouter({const { projectId } = input;try {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId,scope: "prompts:CUD",@@ -402,7 +402,7 @@ export const promptRouter = createTRPCRouter({try {const { projectId } = input;- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId,scope: "prompts:CUD",@@ -487,7 +487,7 @@ export const promptRouter = createTRPCRouter({allLabels: protectedProjectProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "prompts:read",@@ -513,7 +513,7 @@ export const promptRouter = createTRPCRouter({.mutation(async ({ input, ctx }) => {const { projectId, name: promptName } = input;- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId,scope: "objects:tag",@@ -560,7 +560,7 @@ export const promptRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "prompts:read",@@ -625,7 +625,7 @@ export const promptRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "prompts:read",diff --git a/web/src/features/public-api/components/ApiKeyList.tsx b/web/src/features/public-api/components/ApiKeyList.tsxindex 9674976da2..d0149f4820 100644--- a/web/src/features/public-api/components/ApiKeyList.tsx+++ b/web/src/features/public-api/components/ApiKeyList.tsx@@ -20,14 +20,15 @@ import {} from "@/src/components/ui/table";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { CreateApiKeyButton } from "@/src/features/public-api/components/CreateApiKeyButton";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { DialogDescription } from "@radix-ui/react-dialog";import { TrashIcon } from "lucide-react";import { useState } from "react";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";export function ApiKeyList(props: { projectId: string }) {- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "apiKeys:read",});@@ -41,11 +42,23 @@ export function ApiKeyList(props: { projectId: string }) {},);- if (!hasAccess) return null;+ if (!hasAccess) {+ return (+ <div>+ <Header title="API Keys" level="h3" />+ <Alert>+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You do not have permission to view API keys for this project.+ </AlertDescription>+ </Alert>+ </div>+ );+ }return (<div>- <Header title="API keys" level="h3" />+ <Header title="API Keys" level="h3" /><Card className="mb-4"><Table><TableHeader>@@ -61,32 +74,43 @@ export function ApiKeyList(props: { projectId: string }) {</TableRow></TableHeader><TableBody className="text-muted-foreground">- {apiKeys.data?.map((apiKey) => (- <TableRow key={apiKey.id} className="hover:bg-primary-foreground">- <TableCell className="hidden md:table-cell">- {apiKey.createdAt.toLocaleDateString()}- </TableCell>- {/* <TableCell>{apiKey.note ?? ""}</TableCell> */}- <TableCell className="font-mono">- <CodeView- className="inline-block"- content={apiKey.publicKey}- />- </TableCell>- <TableCell className="font-mono">- {apiKey.displaySecretKey}+ {apiKeys.data?.length === 0 ? (+ <TableRow>+ <TableCell colSpan={6} className="text-center">+ None</TableCell>- {/* <TableCell>+ </TableRow>+ ) : (+ apiKeys.data?.map((apiKey) => (+ <TableRow+ key={apiKey.id}+ className="hover:bg-primary-foreground"+ >+ <TableCell className="hidden md:table-cell">+ {apiKey.createdAt.toLocaleDateString()}+ </TableCell>+ {/* <TableCell>{apiKey.note ?? ""}</TableCell> */}+ <TableCell className="font-mono">+ <CodeView+ className="inline-block"+ content={apiKey.publicKey}+ />+ </TableCell>+ <TableCell className="font-mono">+ {apiKey.displaySecretKey}+ </TableCell>+ {/* <TableCell>{apiKey.lastUsedAt?.toLocaleDateString() ?? "Never"}</TableCell> */}- <TableCell>- <DeleteApiKeyButton- projectId={props.projectId}- apiKeyId={apiKey.id}- />- </TableCell>- </TableRow>- ))}+ <TableCell>+ <DeleteApiKeyButton+ projectId={props.projectId}+ apiKeyId={apiKey.id}+ />+ </TableCell>+ </TableRow>+ ))+ )}</TableBody></Table></Card>@@ -98,7 +122,7 @@ export function ApiKeyList(props: { projectId: string }) {// show dialog to let user confirm that this is a destructive actionfunction DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "apiKeys:delete",});diff --git a/web/src/features/public-api/components/CreateApiKeyButton.tsx b/web/src/features/public-api/components/CreateApiKeyButton.tsxindex b974c4dc8b..441358e2d5 100644--- a/web/src/features/public-api/components/CreateApiKeyButton.tsx+++ b/web/src/features/public-api/components/CreateApiKeyButton.tsx@@ -9,20 +9,18 @@ import {DialogTrigger,} from "@/src/components/ui/dialog";import { CodeView } from "@/src/components/ui/CodeJsonViewer";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { QuickstartExamples } from "@/src/features/public-api/components/QuickstartExamples";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";export function CreateApiKeyButton(props: { projectId: string }) {const utils = api.useUtils();const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "apiKeys:create",});- const hostname = window.origin;-const mutCreateApiKey = api.apiKeys.create.useMutation({onSuccess: () => utils.apiKeys.invalidate(),});@@ -71,29 +69,14 @@ export function CreateApiKeyButton(props: { projectId: string }) {><DialogTitle>API Keys</DialogTitle><div className="shrink overflow-x-hidden overflow-y-scroll">- <div className="mb-2">- <div className="text-md font-semibold">Secret Key</div>- <div className="my-2">- This key can only be viewed once. You can always generate a new- key.- </div>- <CodeView content={generatedKeys?.secretKey ?? "Loading ..."} />- </div>- <div>- <div className="text-md mb-2 font-semibold">Public Key</div>- <CodeView content={generatedKeys?.publicKey ?? "Loading ..."} />- </div>- <div>- <div className="text-md mb-2 font-semibold">Host</div>- <CodeView content={hostname} />- </div>+ <ApiKeyRender generatedKeys={generatedKeys ?? undefined} />{generatedKeys && (<div className="mb-2 max-w-full"><div className="text-md my-2 font-semibold">Usage</div><QuickstartExamplessecretKey={generatedKeys.secretKey}publicKey={generatedKeys.publicKey}- host={hostname}+ host={window.origin}/></div>)}@@ -102,3 +85,30 @@ export function CreateApiKeyButton(props: { projectId: string }) {</Dialog>);}++export const ApiKeyRender = ({+ generatedKeys,+}: {+ generatedKeys?: { secretKey: string; publicKey: string };+}) => {+ return (+ <>+ <div className="mb-4">+ <div className="text-md font-semibold">Secret Key</div>+ <div className="my-2">+ This key can only be viewed once. You can always create new keys in+ the project settings.+ </div>+ <CodeView content={generatedKeys?.secretKey ?? "Loading ..."} />+ </div>+ <div className="mb-4">+ <div className="text-md mb-2 font-semibold">Public Key</div>+ <CodeView content={generatedKeys?.publicKey ?? "Loading ..."} />+ </div>+ <div>+ <div className="text-md mb-2 font-semibold">Host</div>+ <CodeView content={window.origin} />+ </div>+ </>+ );+};diff --git a/web/src/features/public-api/components/CreateLLMApiKeyDialog.tsx b/web/src/features/public-api/components/CreateLLMApiKeyDialog.tsxindex 81ad8a247f..ef041dc663 100644--- a/web/src/features/public-api/components/CreateLLMApiKeyDialog.tsx+++ b/web/src/features/public-api/components/CreateLLMApiKeyDialog.tsx@@ -30,7 +30,7 @@ import {} from "@/src/components/ui/select";import { Switch } from "@/src/components/ui/switch";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { cn } from "@/src/utils/tailwind";import { zodResolver } from "@hookform/resolvers/zod";@@ -59,7 +59,7 @@ export function CreateLLMApiKeyDialog() {const capture = usePostHogClientCapture();const utils = api.useUtils();const [open, setOpen] = useState(false);- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId,scope: "llmApiKeys:create",});diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsxindex d8f57c9117..7885530b69 100644--- a/web/src/features/public-api/components/LLMApiKeyList.tsx+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx@@ -21,31 +21,49 @@ import {TableRow,} from "@/src/components/ui/table";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";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 { useIsEeEnabled } from "@/src/ee/utils/useIsEeEnabled";+import { useOrgEntitlements } from "@/src/features/entitlements/hooks";export function LlmApiKeyList(props: { projectId: string }) {- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "llmApiKeys:read",});- const isEeEnabled = useIsEeEnabled();++ // only show if the user has access to features that require LLM API keys+ const entitlements = useOrgEntitlements();+ const isAvailable =+ entitlements.includes("playground") ||+ entitlements.includes("model-based-evaluations");const apiKeys = api.llmApiKey.all.useQuery({projectId: props.projectId,},{- enabled: hasAccess && isEeEnabled,+ enabled: hasAccess && isAvailable,},);- if (!hasAccess) return null;- if (!isEeEnabled) return null;+ if (!isAvailable) return null;++ if (!hasAccess) {+ return (+ <div>+ <Header title="LLM API Keys" level="h3" />+ <Alert>+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You do not have permission to view LLM API keys for this project.+ </AlertDescription>+ </Alert>+ </div>+ );+ }return (<div id="llm-api-keys">@@ -75,29 +93,40 @@ export function LlmApiKeyList(props: { projectId: string }) {</TableRow></TableHeader><TableBody className="text-muted-foreground">- {apiKeys.data?.data.map((apiKey) => (- <TableRow key={apiKey.id} className="hover:bg-primary-foreground">- <TableCell className="hidden md:table-cell">- {apiKey.createdAt.toLocaleDateString()}- </TableCell>- <TableCell className="font-mono">{apiKey.provider}</TableCell>- <TableCell className="hidden font-mono">- {apiKey.adapter}- </TableCell>- <TableCell className="max-w-md overflow-auto font-mono">- {apiKey.baseURL ?? "default"}- </TableCell>- <TableCell className="font-mono">- {apiKey.displaySecretKey}- </TableCell>- <TableCell>- <DeleteApiKeyButton- projectId={props.projectId}- apiKeyId={apiKey.id}- />+ {apiKeys.data?.data.length === 0 ? (+ <TableRow>+ <TableCell colSpan={6} className="text-center">+ None</TableCell></TableRow>- ))}+ ) : (+ apiKeys.data?.data.map((apiKey) => (+ <TableRow+ key={apiKey.id}+ className="hover:bg-primary-foreground"+ >+ <TableCell className="hidden md:table-cell">+ {apiKey.createdAt.toLocaleDateString()}+ </TableCell>+ <TableCell className="font-mono">{apiKey.provider}</TableCell>+ <TableCell className="hidden font-mono">+ {apiKey.adapter}+ </TableCell>+ <TableCell className="max-w-md overflow-auto font-mono">+ {apiKey.baseURL ?? "default"}+ </TableCell>+ <TableCell className="font-mono">+ {apiKey.displaySecretKey}+ </TableCell>+ <TableCell>+ <DeleteApiKeyButton+ projectId={props.projectId}+ apiKeyId={apiKey.id}+ />+ </TableCell>+ </TableRow>+ ))+ )}</TableBody></Table></Card>@@ -109,7 +138,7 @@ export function LlmApiKeyList(props: { projectId: string }) {// show dialog to let user confirm that this is a destructive actionfunction DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "llmApiKeys:delete",});diff --git a/web/src/features/public-api/components/QuickstartExamples.tsx b/web/src/features/public-api/components/QuickstartExamples.tsxindex 34ccf77fca..72d30f6d4d 100644--- a/web/src/features/public-api/components/QuickstartExamples.tsx+++ b/web/src/features/public-api/components/QuickstartExamples.tsx@@ -47,9 +47,8 @@ export const QuickstartExamples = ({</TabsList></div><TabsContent value="python">- <CodeView content="pip install langfuse" className="mb-2 bg-muted" />+ <CodeView content="pip install langfuse" className="mb-2" /><CodeView- className="bg-muted"content={`from langfuse import Langfuse\n\nlangfuse = Langfuse(\n secret_key="${secretKey}",\n public_key="${publicKey}",\n host="${host}"\n)`}/><p className="mt-3 text-xs text-muted-foreground">@@ -75,9 +74,8 @@ export const QuickstartExamples = ({</p></TabsContent><TabsContent value="js">- <CodeView content="npm install langfuse" className="mb-2 bg-muted" />+ <CodeView content="npm install langfuse" className="mb-2" /><CodeView- className="bg-muted"content={`import { Langfuse } from "langfuse";\n\nconst langfuse = new Langfuse({\n secretKey: "${secretKey}",\n publicKey: "${publicKey}",\n baseUrl: "${host}"\n});`}/><p className="mt-3 text-xs text-muted-foreground">@@ -108,15 +106,15 @@ export const QuickstartExamples = ({changing the import, Langfuse will capture all LLM calls and send themto Langfuse asynchronously.</p>- <CodeView content="pip install langfuse" className="my-2 bg-muted" />+ <CodeView content="pip install langfuse" className="my-2" /><CodeViewtitle=".env"content={`LANGFUSE_SECRET_KEY=${secretKey}\nLANGFUSE_PUBLIC_KEY=${publicKey}\nLANGFUSE_HOST="${host}"`}- className="my-2 bg-muted"+ className="my-2"/><CodeViewcontent={`# remove: import openai\n\nfrom langfuse.openai import openai`}- className="my-2 bg-muted"+ className="my-2"/><p className="mt-2 text-xs text-muted-foreground">Use the OpenAI SDK as you would normally. See the{" "}@@ -136,10 +134,10 @@ export const QuickstartExamples = ({The integration uses the Langchain callback system to automaticallycapture detailed traces of your Langchain executions.</p>- <CodeView content="pip install langfuse" className="my-2 bg-muted" />+ <CodeView content="pip install langfuse" className="my-2" /><CodeViewcontent={LANGCHAIN_PYTHON_CODE({ publicKey, secretKey, host })}- className="my-2 bg-muted"+ className="my-2"/><p className="mt-2 text-xs text-muted-foreground">See the{" "}@@ -159,13 +157,10 @@ export const QuickstartExamples = ({The integration uses the Langchain callback system to automaticallycapture detailed traces of your Langchain executions.</p>- <CodeView- content="npm install langfuse-langchain"- className="my-2 bg-muted"- />+ <CodeView content="npm install langfuse-langchain" className="my-2" /><CodeViewcontent={LANGCHAIN_JS_CODE({ publicKey, secretKey, host })}- className="my-2 bg-muted"+ className="my-2"/><p className="mt-2 text-xs text-muted-foreground">See the{" "}@@ -185,13 +180,10 @@ export const QuickstartExamples = ({The integration uses the LlamaIndex callback system to automaticallycapture detailed traces of your LlamaIndex executions.</p>- <CodeView- content="pip install langfuse llama-index"- className="my-2 bg-muted"- />+ <CodeView content="pip install langfuse llama-index" className="my-2" /><CodeViewcontent={LLAMA_INDEX_CODE({ publicKey, secretKey, host })}- className="my-2 bg-muted"+ className="my-2"/><p className="mt-2 text-xs text-muted-foreground">See the{" "}diff --git a/web/src/features/public-api/server/apiKeyRouter.ts b/web/src/features/public-api/server/apiKeyRouter.tsindex 711da135a5..5a03f4b3f0 100644--- a/web/src/features/public-api/server/apiKeyRouter.ts+++ b/web/src/features/public-api/server/apiKeyRouter.ts@@ -1,6 +1,6 @@import { auditLog } from "@/src/features/audit-logs/auditLog";import { generateKeySet } from "@langfuse/shared/src/server";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,protectedProjectProcedure,@@ -17,7 +17,7 @@ export const apiKeysRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "apiKeys:read",@@ -49,7 +49,7 @@ export const apiKeysRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "apiKeys:create",@@ -91,7 +91,7 @@ export const apiKeysRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "apiKeys:delete",diff --git a/web/src/features/rbac/components/CreateProjectMemberButton.tsx b/web/src/features/rbac/components/CreateProjectMemberButton.tsxindex 58e7c936c4..f15b526243 100644--- a/web/src/features/rbac/components/CreateProjectMemberButton.tsx+++ b/web/src/features/rbac/components/CreateProjectMemberButton.tsx@@ -24,38 +24,44 @@ import {import {Select,SelectContent,- SelectItem,SelectTrigger,SelectValue,} from "@/src/components/ui/select";import { Input } from "@/src/components/ui/input";-import { ProjectRole } from "@langfuse/shared";-import { roleAccessRights } from "@/src/features/rbac/constants/roleAccessRights";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { Role } from "@langfuse/shared";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";--const availableRoles = [- ProjectRole.ADMIN,- ProjectRole.MEMBER,- ProjectRole.VIEWER,-] as const;+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";const formSchema = z.object({email: z.string().trim().email(),- role: z.enum(availableRoles),+ orgRole: z.nativeEnum(Role),+ projectRole: z.nativeEnum(Role),});-export function CreateProjectMemberButton(props: { projectId: string }) {+export function CreateProjectMemberButton(props: {+ orgId: string;+ project?: { id: string; name: string };+}) {const capture = usePostHogClientCapture();const [open, setOpen] = useState(false);- const hasAccess = useHasAccess({- projectId: props.projectId,- scope: "members:create",+ const hasOrgAccess = useHasOrganizationAccess({+ organizationId: props.orgId,+ scope: "organizationMembers:CUD",+ });+ const hasProjectAccess = useHasProjectAccess({+ projectId: props.project?.id,+ scope: "projectMembers:CUD",});+ const hasProjectRoleEntitlement = useHasOrgEntitlement("rbac-project-roles");+ const hasOnlySingleProjectAccess =+ !hasOrgAccess && hasProjectAccess && hasProjectRoleEntitlement;const utils = api.useUtils();- const mutCreateProjectMember = api.projectMembers.create.useMutation({- onSuccess: () => utils.projectMembers.invalidate(),+ const mutCreateProjectMember = api.members.create.useMutation({+ onSuccess: () => utils.members.invalidate(),onError: (error) =>form.setError("email", {type: "manual",@@ -67,21 +73,30 @@ export function CreateProjectMemberButton(props: { projectId: string }) {resolver: zodResolver(formSchema),defaultValues: {email: "",- role: ProjectRole.MEMBER,+ orgRole: hasOnlySingleProjectAccess ? Role.NONE : Role.MEMBER,+ projectRole: hasOnlySingleProjectAccess ? Role.MEMBER : Role.NONE,},});- if (!hasAccess) return null;-function onSubmit(values: z.infer<typeof formSchema>) {- capture("project_settings:send_membership_invitation", {- role: values.role,- });+ capture(+ props.project+ ? "project_settings:send_membership_invitation"+ : "organization_settings:send_membership_invitation",+ {+ orgRole: values.orgRole,+ projectRole: values.projectRole,+ },+ );return mutCreateProjectMember.mutateAsync({- projectId: props.projectId,+ orgId: props.orgId,email: values.email,- role: values.role,+ orgRole: values.orgRole,+ //optional+ projectId: props.project?.id,+ projectRole:+ values.projectRole === Role.NONE ? undefined : values.projectRole,}).then(() => {form.reset();@@ -99,14 +114,20 @@ export function CreateProjectMemberButton(props: { projectId: string }) {<Buttonvariant="secondary"loading={mutCreateProjectMember.isLoading}+ disabled={!hasOrgAccess && !hasOnlySingleProjectAccess}><PlusIcon className="-ml-0.5 mr-1.5 h-5 w-5" aria-hidden="true" />- Add new member+ {hasOnlySingleProjectAccess+ ? "Add project member"+ : "Add new member"}</Button></DialogTrigger><DialogContent><DialogHeader>- <DialogTitle>Add new member to project</DialogTitle>+ <DialogTitle>+ Add new member to the{" "}+ {hasOnlySingleProjectAccess ? "project" : "organization"}+ </DialogTitle></DialogHeader><Form {...form}><form@@ -127,41 +148,84 @@ export function CreateProjectMemberButton(props: { projectId: string }) {</FormItem>)}/>- <FormField- control={form.control}- name="role"- render={({ field }) => (- <FormItem>- <FormLabel>Role</FormLabel>- <Select- defaultValue={field.value}- onValueChange={(value) =>- field.onChange(value as (typeof availableRoles)[number])- }- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select a verified email to display" />- </SelectTrigger>- </FormControl>- <SelectContent>- {availableRoles.map((role) => (- <SelectItem value={role} key={role}>- {role}- </SelectItem>- ))}- </SelectContent>- </Select>- <FormDescription>- Rights of role:{" "}- {roleAccessRights[field.value].length- ? roleAccessRights[field.value].join(", ")- : "none"}- </FormDescription>- <FormMessage />- </FormItem>- )}- />+ {!hasOnlySingleProjectAccess && (+ <FormField+ control={form.control}+ name="orgRole"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Organization Role</FormLabel>+ <Select+ defaultValue={field.value}+ onValueChange={(value) =>+ field.onChange(+ value as (typeof Role)[keyof typeof Role],+ )+ }+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select an organization role" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {Object.values(Role).map((role) => (+ <RoleSelectItem role={role} key={role} />+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ )}+ {props.project !== undefined && hasProjectRoleEntitlement && (+ <FormField+ control={form.control}+ name="projectRole"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Project Role</FormLabel>+ <Select+ defaultValue={field.value}+ onValueChange={(value) =>+ field.onChange(+ value as (typeof Role)[keyof typeof Role],+ )+ }+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a project role" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {Object.values(Role)+ .filter(+ (role) =>+ !hasOnlySingleProjectAccess ||+ role !== Role.NONE,+ )+ .map((role) => (+ <RoleSelectItem+ role={role}+ key={role}+ isProjectRole+ />+ ))}+ </SelectContent>+ </Select>+ {!hasOnlySingleProjectAccess && (+ <FormDescription>+ This project role will override the default role for+ this current project ({props.project!.name}).+ </FormDescription>+ )}+ <FormMessage />+ </FormItem>+ )}+ />+ )}<Buttontype="submit"className="w-full"diff --git a/web/src/features/rbac/components/MembersTable.tsx b/web/src/features/rbac/components/MembersTable.tsxnew file mode 100644index 0000000000..a427771be9--- /dev/null+++ b/web/src/features/rbac/components/MembersTable.tsx@@ -0,0 +1,484 @@+import { DataTable } from "@/src/components/table/data-table";+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import {+ Avatar,+ AvatarFallback,+ AvatarImage,+} from "@/src/components/ui/avatar";+import {+ Select,+ SelectContent,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";+import { CreateProjectMemberButton } from "@/src/features/rbac/components/CreateProjectMemberButton";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { api } from "@/src/utils/api";+import type { RouterOutput } from "@/src/utils/types";+import { Role } from "@langfuse/shared";+import { type Row } from "@tanstack/react-table";+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 { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";+import { HoverCardPortal } from "@radix-ui/react-hover-card";+import Link from "next/link";++export type MembersTableRow = {+ user: {+ image: string | null;+ name: string | null;+ };+ email: string | null;+ createdAt: Date;+ orgRole: Role;+ projectRole?: Role;+ meta: {+ userId: string;+ orgMembershipId: string;+ };+};++export function MembersTable({+ orgId,+ project,+}: {+ orgId: string;+ project?: { id: string; name: string };+}) {+ const session = useSession();+ const hasOrgViewAccess = useHasOrganizationAccess({+ organizationId: orgId,+ scope: "organizationMembers:read",+ });+ const hasProjectViewAccess =+ useHasProjectAccess({+ projectId: project?.id,+ scope: "projectMembers:read",+ }) || hasOrgViewAccess;+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 10),+ });++ const membersViaOrg = api.members.allFromOrg.useQuery(+ {+ orgId,+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ },+ {+ enabled: !project && hasOrgViewAccess,+ },+ );+ const membersViaProject = api.members.allFromProject.useQuery(+ {+ orgId,+ projectId: project?.id ?? "NOT ENABLED",+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ },+ {+ enabled: project !== undefined && hasProjectViewAccess,+ },+ );+ const members = project ? membersViaProject : membersViaOrg;++ const totalCount = members.data?.totalCount ?? 0;++ const utils = api.useUtils();++ const mutDeleteMember = api.members.deleteMembership.useMutation({+ onSuccess: () => utils.members.invalidate(),+ });++ const hasCudAccessOrgLevel = useHasOrganizationAccess({+ organizationId: orgId,+ scope: "organizationMembers:CUD",+ });+ const hasCudAccessProjectLevel = useHasProjectAccess({+ projectId: project?.id,+ scope: "projectMembers:CUD",+ });++ const projectRolesEntitlement = useHasOrgEntitlement("rbac-project-roles");++ const columns: LangfuseColumnDef<MembersTableRow>[] = [+ {+ accessorKey: "user",+ id: "user",+ header: "Name",+ cell: ({ row }) => {+ const { name, image } = row.getValue("user") as MembersTableRow["user"];+ return (+ <div className="flex items-center space-x-2">+ <Avatar className="h-7 w-7">+ <AvatarImage+ src={image ?? undefined}+ alt={name ?? "User Avatar"}+ />+ <AvatarFallback>+ {name+ ? name+ .split(" ")+ .map((word) => word[0])+ .slice(0, 2)+ .concat("")+ : null}+ </AvatarFallback>+ </Avatar>+ <span>{name}</span>+ </div>+ );+ },+ },+ {+ accessorKey: "email",+ id: "email",+ header: "Email",+ },+ {+ accessorKey: "orgRole",+ id: "orgRole",+ header: "Organization Role",+ headerTooltip: {+ description:+ "The org-role is the default role for this user in this organization and applies to the organization and all its projects.",+ href: "https://langfuse.com/docs/rbac",+ },+ cell: ({ row }) => {+ const orgRole = row.getValue("orgRole") as MembersTableRow["orgRole"];+ const { orgMembershipId } = row.getValue(+ "meta",+ ) as MembersTableRow["meta"];+ const { userId } = row.getValue("meta") as MembersTableRow["meta"];+ const disableInProjectSettings = Boolean(project?.id);++ const ConfiguredOrgRoleDropdown = () => (+ <OrgRoleDropdown+ orgMembershipId={orgMembershipId}+ currentRole={orgRole}+ userId={userId}+ orgId={orgId}+ hasCudAccess={hasCudAccessOrgLevel && !disableInProjectSettings}+ />+ );++ return (+ <div className="relative">+ {disableInProjectSettings && hasCudAccessOrgLevel ? (+ <HoverCard openDelay={0} closeDelay={0}>+ <HoverCardTrigger>+ <ConfiguredOrgRoleDropdown />+ </HoverCardTrigger>+ <HoverCardPortal>+ <HoverCardContent+ hideWhenDetached={true}+ align="center"+ side="right"+ >+ <p className="text-xs">+ The organization-level role can to be edited in the{" "}+ <Link+ href={`/organization/${orgId}/settings/members`}+ className="underline"+ >+ organization settings+ </Link>+ .+ </p>+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCard>+ ) : (+ <ConfiguredOrgRoleDropdown />+ )}+ </div>+ );+ },+ },+ ...(project+ ? [+ {+ accessorKey: "projectRole",+ id: "projectRole",+ header: "Project Role",+ headerTooltip: {+ description:+ "The role for this user in this specific project. This role overrides the default project role.",+ href: "https://langfuse.com/docs/rbac",+ },+ cell: ({+ row,+ }: {+ row: Row<MembersTableRow>; // need to specify the type here due to conditional rendering+ }) => {+ const projectRole = row.getValue(+ "projectRole",+ ) as MembersTableRow["projectRole"];+ const { orgMembershipId, userId } = row.getValue(+ "meta",+ ) as MembersTableRow["meta"];++ if (!projectRolesEntitlement) return "N/A";++ return (+ <ProjectRoleDropdown+ orgMembershipId={orgMembershipId}+ userId={userId}+ currentProjectRole={projectRole ?? null}+ orgId={orgId}+ projectId={project.id}+ hasCudAccess={+ hasCudAccessOrgLevel || hasCudAccessProjectLevel+ }+ />+ );+ },+ },+ ]+ : []),+ {+ accessorKey: "createdAt",+ id: "createdAt",+ header: "Member Since",+ enableHiding: true,+ defaultHidden: true,+ cell: ({ row }) => {+ const value = row.getValue("createdAt") as MembersTableRow["createdAt"];+ return value ? new Date(value).toLocaleString() : undefined;+ },+ },+ {+ accessorKey: "meta",+ id: "meta",+ header: "Actions",+ enableHiding: false,+ cell: ({ row }) => {+ const { orgMembershipId, userId } = row.getValue(+ "meta",+ ) as MembersTableRow["meta"];+ return hasCudAccessOrgLevel ||+ (userId && userId === session.data?.user?.id) ? (+ <div className="flex space-x-2">+ <button+ onClick={() => {+ if (+ confirm(+ userId === session.data?.user?.id+ ? "Are you sure you want to leave the organization?"+ : "Are you sure you want to remove this member from the organization?",+ )+ ) {+ mutDeleteMember.mutate({ orgId, orgMembershipId });+ }+ }}+ >+ <Trash size={14} />+ </button>+ </div>+ ) : null;+ },+ },+ ];++ const [columnVisibility, setColumnVisibility] =+ useColumnVisibility<MembersTableRow>("membersColumnVisibility", columns);++ const convertToTableRow = (+ orgMembership: RouterOutput["members"]["allFromOrg"]["memberships"][0], // type of both queries is the same+ ): MembersTableRow => {+ return {+ meta: {+ userId: orgMembership.userId,+ orgMembershipId: orgMembership.id,+ },+ email: orgMembership.user.email,+ user: {+ image: orgMembership.user.image,+ name: orgMembership.user.name,+ },+ createdAt: orgMembership.createdAt,+ orgRole: orgMembership.role,+ projectRole: orgMembership.projectRole,+ };+ };++ if (project ? !hasProjectViewAccess : !hasOrgViewAccess) {+ return (+ <Alert>+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You do not have permission to view members of this organization.+ </AlertDescription>+ </Alert>+ );+ }++ return (+ <>+ <DataTableToolbar+ columns={columns}+ columnVisibility={columnVisibility}+ setColumnVisibility={setColumnVisibility}+ actionButtons={+ <CreateProjectMemberButton orgId={orgId} project={project} />+ }+ />+ <DataTable+ columns={columns}+ data={+ members.isLoading+ ? { isLoading: true, isError: false }+ : members.isError+ ? {+ isLoading: false,+ isError: true,+ error: members.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: members.data.memberships.map((t) =>+ convertToTableRow(t),+ ),+ }+ }+ pagination={{+ pageCount: Math.ceil(totalCount / paginationState.pageSize),+ onChange: setPaginationState,+ state: paginationState,+ }}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={setColumnVisibility}+ />+ </>+ );+}++const OrgRoleDropdown = ({+ orgMembershipId,+ currentRole,+ orgId,+ userId,+ hasCudAccess,+}: {+ orgMembershipId: string;+ currentRole: Role;+ orgId: string;+ userId: string;+ hasCudAccess: boolean;+}) => {+ const utils = api.useUtils();+ const session = useSession();+ const mut = api.members.updateOrgMembership.useMutation({+ onSuccess: () => {+ utils.members.invalidate();+ showSuccessToast({+ title: "Saved",+ description: "Organization role updated successfully",+ duration: 2000,+ });+ },+ });++ return (+ <Select+ disabled={!hasCudAccess || mut.isLoading}+ value={currentRole}+ onValueChange={(value) => {+ if (+ userId !== session.data?.user?.id ||+ confirm(+ "Are you sure that you want to change your own organization role?",+ )+ ) {+ mut.mutate({+ orgId,+ orgMembershipId,+ role: value as Role,+ });+ }+ }}+ >+ <SelectTrigger className="w-[120px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {Object.values(Role).map((role) => (+ <RoleSelectItem role={role} key={role} />+ ))}+ </SelectContent>+ </Select>+ );+};++const ProjectRoleDropdown = ({+ orgId,+ userId,+ orgMembershipId,+ projectId,+ currentProjectRole,+ hasCudAccess,+}: {+ orgMembershipId: string;+ userId: string;+ currentProjectRole: Role | null;+ orgId: string;+ projectId: string;+ hasCudAccess: boolean;+}) => {+ const utils = api.useUtils();+ const session = useSession();+ const mut = api.members.updateProjectRole.useMutation({+ onSuccess: () => {+ utils.members.invalidate();+ showSuccessToast({+ title: "Saved",+ description: "Project role updated successfully",+ duration: 2000,+ });+ },+ });++ return (+ <Select+ disabled={!hasCudAccess || mut.isLoading}+ value={currentProjectRole ?? Role.NONE}+ onValueChange={(value) => {+ if (+ userId !== session.data?.user?.id ||+ confirm("Are you sure that you want to change your own project role?")+ ) {+ mut.mutate({+ orgId,+ orgMembershipId,+ projectId,+ userId,+ projectRole: value as Role,+ });+ }+ }}+ >+ <SelectTrigger className="w-[120px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {Object.values(Role).map((role) => (+ <RoleSelectItem role={role} key={role} isProjectRole />+ ))}+ </SelectContent>+ </Select>+ );+};diff --git a/web/src/features/rbac/components/MembershipInvitesPage.tsx b/web/src/features/rbac/components/MembershipInvitesPage.tsxnew file mode 100644index 0000000000..1a7b972f5a--- /dev/null+++ b/web/src/features/rbac/components/MembershipInvitesPage.tsx@@ -0,0 +1,243 @@+import { DataTable } from "@/src/components/table/data-table";+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import {+ Avatar,+ AvatarFallback,+ AvatarImage,+} from "@/src/components/ui/avatar";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { api } from "@/src/utils/api";+import type { RouterOutput } from "@/src/utils/types";+import { Trash } from "lucide-react";+import { useQueryParams, withDefault, NumberParam } from "use-query-params";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+import { type Role } from "@langfuse/shared";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import Header from "@/src/components/layouts/header";++export type InvitesTableRow = {+ email: string;+ createdAt: Date;+ orgRole: Role;+ projectRole?: Role;+ invitedByUser: {+ name: string | null;+ image: string | null;+ } | null;+ meta: {+ inviteId: string;+ };+};++export function MembershipInvitesPage({+ orgId,+ projectId,+}: {+ orgId: string;+ projectId?: string;+}) {+ const hasOrgViewAccess = useHasOrganizationAccess({+ organizationId: orgId,+ scope: "organizationMembers:read",+ });+ const hasProjectViewAccess =+ useHasProjectAccess({+ projectId,+ scope: "projectMembers:read",+ }) || hasOrgViewAccess;++ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 10),+ });++ const invites = projectId+ ? api.members.allInvitesFromProject.useQuery(+ {+ orgId,+ projectId,+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ },+ {+ enabled: hasProjectViewAccess,+ },+ )+ : api.members.allInvitesFromOrg.useQuery(+ {+ orgId,+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ },+ {+ enabled: hasOrgViewAccess,+ },+ );++ const totalCount = invites.data?.totalCount ?? 0;++ const utils = api.useUtils();++ const mutDeleteInvite = api.members.deleteInvite.useMutation({+ onSuccess: () => utils.members.invalidate(),+ });++ const hasCudAccess = useHasOrganizationAccess({+ organizationId: orgId,+ scope: "organizationMembers:CUD",+ });++ const columns: LangfuseColumnDef<InvitesTableRow>[] = [+ {+ accessorKey: "email",+ id: "email",+ header: "Email",+ },+ {+ accessorKey: "orgRole",+ id: "orgRole",+ header: "Organization Role",+ },+ {+ accessorKey: "createdAt",+ id: "createdAt",+ header: "Invited On",+ cell: ({ row }) => {+ const value = row.getValue("createdAt") as InvitesTableRow["createdAt"];+ return value ? new Date(value).toLocaleString() : undefined;+ },+ },+ ...(projectId+ ? [+ {+ accessorKey: "projectRole",+ id: "projectRole",+ header: "Project Role",+ },+ ]+ : []),+ {+ accessorKey: "invitedByUser",+ id: "invitedByUser",+ header: "Invited By",+ cell: ({ row }) => {+ const invitedByUser = row.getValue(+ "invitedByUser",+ ) as InvitesTableRow["invitedByUser"];+ const { name, image } = invitedByUser || {};+ return (+ <div className="flex items-center space-x-2">+ <Avatar className="h-7 w-7">+ <AvatarImage+ src={image ?? undefined}+ alt={name ?? "User Avatar"}+ />+ <AvatarFallback>+ {name+ ? name+ .split(" ")+ .map((word) => word[0])+ .slice(0, 2)+ .concat("")+ : null}+ </AvatarFallback>+ </Avatar>+ <span>{name ?? "-"}</span>+ </div>+ );+ },+ },+ {+ accessorKey: "meta",+ id: "meta",+ header: "Actions",+ cell: ({ row }) => {+ const { inviteId } = row.getValue("meta") as InvitesTableRow["meta"];+ return hasCudAccess ? (+ <div className="flex space-x-2">+ <button+ onClick={() => {+ if (+ confirm("Are you sure you want to cancel this invitation?")+ ) {+ mutDeleteInvite.mutate({ inviteId, orgId });+ }+ }}+ >+ <Trash size={14} />+ </button>+ </div>+ ) : null;+ },+ },+ ];++ const convertToTableRow = (+ invite: RouterOutput["members"]["allInvitesFromOrg"]["invitations"][0],+ ): InvitesTableRow => {+ return {+ meta: {+ inviteId: invite.id,+ },+ email: invite.email,+ createdAt: invite.createdAt,+ orgRole: invite.orgRole,+ projectRole:+ invite.projectId === projectId+ ? invite.projectRole ?? undefined+ : undefined,+ invitedByUser: invite.invitedByUser,+ };+ };++ if (projectId ? !hasProjectViewAccess : !hasOrgViewAccess) {+ return (+ <Alert>+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You do not have permission to view invites of this organization.+ </AlertDescription>+ </Alert>+ );+ }++ if (totalCount === 0) return null;++ return (+ <>+ {/* Header included in order to hide it when there are not invites yet */}+ <Header title="Membership Invites" level="h3" />+ <DataTableToolbar+ columns={columns}+ // columnVisibility={columnVisibility}+ // setColumnVisibility={setColumnVisibility}+ />+ <DataTable+ columns={columns}+ data={+ invites.isLoading+ ? { isLoading: true, isError: false }+ : invites.isError+ ? {+ isLoading: false,+ isError: true,+ error: invites.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: invites.data.invitations.map((i) =>+ convertToTableRow(i),+ ),+ }+ }+ pagination={{+ pageCount: Math.ceil(totalCount / paginationState.pageSize),+ onChange: setPaginationState,+ state: paginationState,+ }}+ />+ </>+ );+}diff --git a/web/src/features/rbac/components/ProjectMembersTable.tsx b/web/src/features/rbac/components/ProjectMembersTable.tsxdeleted file mode 100644index 300dde7621..0000000000--- a/web/src/features/rbac/components/ProjectMembersTable.tsx+++ /dev/null@@ -1,151 +0,0 @@-import { api } from "@/src/utils/api";-import { Card } from "@/src/components/ui/card";-import {- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,-} from "@/src/components/ui/table";-import { Button } from "@/src/components/ui/button";-import { TrashIcon } from "lucide-react";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";-import { CreateProjectMemberButton } from "@/src/features/rbac/components/CreateProjectMemberButton";-import { useSession } from "next-auth/react";-import Header from "@/src/components/layouts/header";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";--export function ProjectMembersTable({ projectId }: { projectId: string }) {- const capture = usePostHogClientCapture();- const hasReadAccess = useHasAccess({- projectId: projectId,- scope: "members:read",- });- const hasDeleteAccess = useHasAccess({- projectId: projectId,- scope: "members:delete",- });-- const session = useSession();-- const utils = api.useUtils();- const data = api.projectMembers.get.useQuery(- {- projectId: projectId,- },- {- enabled: hasReadAccess,- },- );-- const memberships = data.data?.memberships ?? []; // Active Members- const invitations = data.data?.invitations ?? []; // Pending Members-- const mutDeleteMembership = api.projectMembers.delete.useMutation({- onSuccess: () => utils.projectMembers.invalidate(),- });- const mutDeleteInvitation = api.projectMembers.deleteInvitation.useMutation({- onSuccess: () => utils.projectMembers.invalidate(),- });-- if (!hasReadAccess) return null;-- return (- <div>- <Header title="Project Members" level="h3" />- <Card className="mb-4">- <Table className="text-sm">- <TableHeader>- <TableRow>- <TableHead className="text-primary">Name</TableHead>- <TableHead className="text-primary">Email</TableHead>- <TableHead className="text-primary">Role</TableHead>- {hasDeleteAccess ? <TableHead /> : null}- </TableRow>- </TableHeader>- <TableBody className="text-muted-foreground">- {memberships.map((m) => (- <TableRow key={m.userId} className="hover:bg-transparent">- <TableCell>{m.user.name}</TableCell>- <TableCell>{m.user.email}</TableCell>- <TableCell>{m.role}</TableCell>- {hasDeleteAccess &&- m.user.id !== session.data?.user?.id &&- m.role !== "OWNER" ? (- <TableCell>- <Button- variant="ghost"- size="icon"- loading={mutDeleteMembership.isLoading}- onClick={() => {- capture("project_settings:delete_membership");- mutDeleteMembership.mutate({- projectId: projectId,- userId: m.user.id,- });- }}- >- <TrashIcon className="h-4 w-4" />- </Button>- </TableCell>- ) : null}- </TableRow>- ))}- </TableBody>- </Table>- </Card>- {invitations.length > 0 ? (- <>- <h3 className="mb-3 text-sm font-semibold leading-4 text-muted-foreground">- Pending Invites- </h3>- <Card className="mb-4">- <Table className="text-sm">- <TableHeader>- <TableRow>- <TableHead className="text-primary">Email</TableHead>- <TableHead className="text-primary">Role</TableHead>- <TableHead className="text-primary">Sent by</TableHead>- {hasDeleteAccess ? <TableHead /> : null}- </TableRow>- </TableHeader>- <TableBody className="text-muted-foreground">- {invitations.map((invite) => (- <TableRow key={invite.id} className="hover:bg-transparent">- <TableCell>{invite.email}</TableCell>- <TableCell>{invite.role}</TableCell>- <TableCell>- {invite.sender ? invite.sender.name : ""}- </TableCell>- {hasDeleteAccess ? (- <TableCell>- <Button- variant="ghost"- size="icon"- loading={mutDeleteInvitation.isLoading}- onClick={() => {- capture(- "project_settings:delete_membership_invitation",- );- mutDeleteInvitation.mutate({- id: invite.id,- projectId: projectId,- });- }}- >- <TrashIcon className="h-4 w-4" />- </Button>- </TableCell>- ) : null}- </TableRow>- ))}- </TableBody>- </Table>- </Card>- </>- ) : null}- <CreateProjectMemberButton projectId={projectId} />- </div>- );-}diff --git a/web/src/features/rbac/components/RoleSelectItem.tsx b/web/src/features/rbac/components/RoleSelectItem.tsxnew file mode 100644index 0000000000..3ec8d63cc1--- /dev/null+++ b/web/src/features/rbac/components/RoleSelectItem.tsx@@ -0,0 +1,119 @@+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";+import { SelectItem } from "@/src/components/ui/select";+import { Role } from "@langfuse/shared";+import { HoverCardPortal } from "@radix-ui/react-hover-card";+import {+ organizationRoleAccessRights,+ orgNoneRoleComment,+} from "@/src/features/rbac/constants/organizationAccessRights";+import {+ projectNoneRoleComment,+ projectRoleAccessRights,+} from "@/src/features/rbac/constants/projectAccessRights";+import { orderedRoles } from "@/src/features/rbac/constants/orderedRoles";++export const RoleSelectItem = ({+ role,+ isProjectRole,+}: {+ role: Role;+ isProjectRole?: boolean;+}) => {+ const isProjectNoneRole = role === Role.NONE && isProjectRole;+ const isOrgNoneRole = role === Role.NONE && !isProjectRole;+ const orgScopes = reduceScopesToListItems(organizationRoleAccessRights, role);+ const projectScopes = reduceScopesToListItems(projectRoleAccessRights, role);++ return (+ <HoverCard openDelay={0} closeDelay={0}>+ <HoverCardTrigger asChild>+ <SelectItem value={role} className="max-w-56">+ <span>+ {formatRole(role)}+ {isProjectNoneRole ? " (keep default role)" : ""}+ </span>+ </SelectItem>+ </HoverCardTrigger>+ <HoverCardPortal>+ <HoverCardContent hideWhenDetached={true} align="center" side="right">+ {isProjectNoneRole ? (+ <div className="text-xs">{projectNoneRoleComment}</div>+ ) : isOrgNoneRole ? (+ <div className="text-xs">{orgNoneRoleComment}</div>+ ) : (+ <>+ <div className="font-bold">Role: {formatRole(role)}</div>+ <p className="mt-3 text-xs font-semibold">Organization Scopes</p>+ <ul className="list-inside list-disc text-xs">{orgScopes}</ul>+ <p className="mt-2 text-xs font-semibold">Project Scopes</p>+ <ul className="list-inside list-disc text-xs">{projectScopes}</ul>+ <p className="mt-3 border-t pt-3 text-xs">+ Note:{" "}+ <span className="text-muted-foreground">Muted scopes</span> are+ inherited from lower role.+ </p>+ </>+ )}+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCard>+ );+};++const reduceScopesToListItems = (+ accessRights: Record<string, string[]>,+ role: Role,+) => {+ const currentRoleLevel = orderedRoles[role];+ const lowerRole = Object.entries(orderedRoles).find(+ ([_role, level]) => level === currentRoleLevel - 1,+ )?.[0] as Role | undefined;+ const inheritedScopes = lowerRole ? accessRights[lowerRole] : [];++ return accessRights[role].length > 0 ? (+ <>+ {Object.entries(+ accessRights[role].reduce(+ (acc, scope) => {+ const [resource, action] = scope.split(":");+ if (!acc[resource]) {+ acc[resource] = [];+ }+ acc[resource].push(action);+ return acc;+ },+ {} as Record<string, string[]>,+ ),+ ).map(([resource, actions]) => {+ const inheritedActions = actions.filter((action) =>+ inheritedScopes.includes(`${resource}:${action}`),+ );+ const newActions = actions.filter(+ (action) => !inheritedScopes.includes(`${resource}:${action}`),+ );++ return (+ <li key={resource}>+ <span>{resource}: </span>+ <span className="text-muted-foreground">+ {inheritedActions.length > 0 ? inheritedActions.join(", ") : ""}+ {newActions.length > 0 && inheritedActions.length > 0 ? ", " : ""}+ </span>+ <span className="font-semibold">+ {newActions.length > 0 ? newActions.join(", ") : ""}+ </span>+ </li>+ );+ })}+ </>+ ) : (+ <li>None</li>+ );+};++const formatRole = (role: Role) =>+ role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();diff --git a/web/src/features/rbac/constants/orderedRoles.ts b/web/src/features/rbac/constants/orderedRoles.tsnew file mode 100644index 0000000000..bae7f4affb--- /dev/null+++ b/web/src/features/rbac/constants/orderedRoles.ts@@ -0,0 +1,9 @@+import { Role } from "@langfuse/shared";++export const orderedRoles: Record<Role, number> = {+ [Role.OWNER]: 4,+ [Role.ADMIN]: 3,+ [Role.MEMBER]: 2,+ [Role.VIEWER]: 1,+ [Role.NONE]: 0,+};diff --git a/web/src/features/rbac/constants/organizationAccessRights.ts b/web/src/features/rbac/constants/organizationAccessRights.tsnew file mode 100644index 0000000000..c27614b58f--- /dev/null+++ b/web/src/features/rbac/constants/organizationAccessRights.ts@@ -0,0 +1,37 @@+import { type Role } from "@langfuse/shared/src/db";++const organizationScopes = [+ "projects:create",+ "projects:transfer_org",+ "organizations:update",+ "organizations:delete", // todo: not implemented yet+ "organizationMembers:read",+ "organizationMembers:CUD",+] as const;++// type string of all Resource:Action, e.g. "organizationMembers:read"+export type OrganizationScope = (typeof organizationScopes)[number];++export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {+ OWNER: [+ "projects:create",+ "projects:transfer_org",+ "organizations:update",+ "organizations:delete",+ "organizationMembers:CUD",+ "organizationMembers:read",+ ],+ ADMIN: [+ "projects:create",+ "projects:transfer_org",+ "organizations:update",+ "organizationMembers:CUD",+ "organizationMembers:read",+ ],+ MEMBER: ["organizationMembers:read"],+ VIEWER: [],+ NONE: [],+};++export const orgNoneRoleComment =+ "No access to organization resources by default. User needs to be granted project-level access via project roles.";diff --git a/web/src/features/rbac/constants/roleAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tssimilarity index 79%rename from web/src/features/rbac/constants/roleAccessRights.tsrename to web/src/features/rbac/constants/projectAccessRights.tsindex 3cb97cbe4b..f3622e9641 100644--- a/web/src/features/rbac/constants/roleAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -1,10 +1,8 @@-import { type ProjectRole } from "@langfuse/shared";--const scopes = [- "members:read",- "members:create",- "members:delete",+import { type Role } from "@langfuse/shared/src/db";+const projectScopes = [+ "projectMembers:read",+ "projectMembers:CUD","apiKeys:read","apiKeys:create","apiKeys:delete",@@ -20,9 +18,10 @@ const scopes = ["scoreConfigs:CUD","scoreConfigs:read",- "project:delete",+ "project:read","project:update",- "project:transfer",+ "project:delete",+"integrations:CRUD","datasets:CUD",@@ -46,13 +45,15 @@ const scopes = [] as const;// type string of all Resource:Action, e.g. "members:read"-export type Scope = (typeof scopes)[number];+export type ProjectScope = (typeof projectScopes)[number];-export const roleAccessRights: Record<ProjectRole, Scope[]> = {+export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {OWNER: [- "members:read",- "members:create",- "members:delete",+ "project:read",+ "project:update",+ "project:delete",+ "projectMembers:read",+ "projectMembers:CUD","apiKeys:read","apiKeys:create","apiKeys:delete",@@ -64,9 +65,6 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"scores:CUD","scoreConfigs:CUD","scoreConfigs:read",- "project:delete",- "project:update",- "project:transfer","datasets:CUD","prompts:CUD","prompts:read",@@ -82,10 +80,10 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"batchExport:create",],ADMIN: [+ "project:read","project:update",- "members:read",- "members:create",- "members:delete",+ "projectMembers:read",+ "projectMembers:CUD","apiKeys:read","apiKeys:create","apiKeys:delete",@@ -112,7 +110,8 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"batchExport:create",],MEMBER: [- "members:read",+ "project:read",+ "projectMembers:read","apiKeys:read","objects:publish","objects:bookmark",@@ -132,6 +131,7 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"batchExport:create",],VIEWER: [+ "project:read","prompts:read","evalTemplate:read","scoreConfigs:read",@@ -139,4 +139,8 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"evalJobExecution:read","llmApiKeys:read",],+ NONE: [],};++export const projectNoneRoleComment =+ "Do not override the organization role for this project.";diff --git a/web/src/features/rbac/server/allInvitesRoutes.ts b/web/src/features/rbac/server/allInvitesRoutes.tsnew file mode 100644index 0000000000..2ebb5457c0--- /dev/null+++ b/web/src/features/rbac/server/allInvitesRoutes.ts@@ -0,0 +1,111 @@+import {+ throwIfNoOrganizationAccess,+ hasOrganizationAccess,+} from "@/src/features/rbac/utils/checkOrganizationAccess";+import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ protectedOrganizationProcedure,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { paginationZod, type PrismaClient, Role } from "@langfuse/shared";+import { TRPCError } from "@trpc/server";+import { z } from "zod";++const orgLevelInviteQuery = z.object({+ orgId: z.string(),+ ...paginationZod,+});+const projectLevelInviteQuery = orgLevelInviteQuery.extend({+ projectId: z.string(),+});+async function getInvites(+ prisma: PrismaClient,+ query:+ | z.infer<typeof orgLevelInviteQuery>+ | z.infer<typeof projectLevelInviteQuery>,+ showAllOrgMembers: boolean = true,+) {+ const invitations = await prisma.membershipInvitation.findMany({+ where: {+ orgId: query.orgId,+ // restrict to only invites with role in a project if projectId is set+ ...("projectId" in query && !showAllOrgMembers+ ? {+ OR: [+ {+ orgRole: {+ not: Role.NONE,+ },+ },+ {+ projectId: query.projectId,+ projectRole: {+ not: Role.NONE,+ },+ },+ ],+ }+ : {}),+ },+ include: {+ invitedByUser: {+ select: {+ name: true,+ image: true,+ },+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ take: query.limit,+ skip: query.page * query.limit,+ });++ const totalCount = await prisma.membershipInvitation.count({+ where: {+ orgId: query.orgId,+ },+ });++ return {+ invitations: invitations.map((i) => ({+ ...i,+ })),+ totalCount,+ };+}++export const allInvitesRoutes = {+ allInvitesFromOrg: protectedOrganizationProcedure+ .input(orgLevelInviteQuery)+ .query(async ({ input, ctx }) => {+ throwIfNoOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:read",+ });+ return getInvites(ctx.prisma, input);+ }),+ allInvitesFromProject: protectedProjectProcedure+ .input(projectLevelInviteQuery)+ .query(async ({ input, ctx }) => {+ const orgAccess = hasOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:read",+ });+ const projectAccess = hasProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "projectMembers:read",+ });+ if (!orgAccess && !projectAccess) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You do not have the required access rights",+ });+ }+ return getInvites(ctx.prisma, input, orgAccess);+ }),+};diff --git a/web/src/features/rbac/server/allMembersRoutes.ts b/web/src/features/rbac/server/allMembersRoutes.tsnew file mode 100644index 0000000000..776ea92e34--- /dev/null+++ b/web/src/features/rbac/server/allMembersRoutes.ts@@ -0,0 +1,140 @@+import {+ throwIfNoOrganizationAccess,+ hasOrganizationAccess,+} from "@/src/features/rbac/utils/checkOrganizationAccess";+import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ protectedOrganizationProcedure,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { paginationZod, type PrismaClient, Role } from "@langfuse/shared";+import { TRPCError } from "@trpc/server";+import { z } from "zod";++const orgLevelMemberQuery = z.object({+ orgId: z.string(),+ ...paginationZod,+});++const projectLevelMemberQuery = orgLevelMemberQuery.extend({+ projectId: z.string(), // optional, view project_role for specific project+});++async function getMembers(+ prisma: PrismaClient,+ query:+ | z.infer<typeof orgLevelMemberQuery>+ | z.infer<typeof projectLevelMemberQuery>,+ showAllOrgMembers: boolean = true,+) {+ const orgMemberships = await prisma.organizationMembership.findMany({+ where: {+ orgId: query.orgId,+ // restrict to only members with role in a project if projectId is set and showAllOrgMembers is false+ ...("projectId" in query && !showAllOrgMembers+ ? {+ // either org level role or project level role+ OR: [+ {+ role: {+ not: Role.NONE,+ },+ },+ {+ ProjectMemberships: {+ some: {+ projectId: query.projectId,+ role: {+ not: Role.NONE,+ },+ },+ },+ },+ ],+ }+ : {}),+ },+ include: {+ user: {+ select: {+ image: true,+ id: true,+ name: true,+ email: true,+ },+ },+ },+ orderBy: {+ user: {+ email: "asc",+ },+ },+ take: query.limit,+ skip: query.page * query.limit,+ });++ const totalCount = await prisma.organizationMembership.count({+ where: {+ orgId: query.orgId,+ },+ });++ const projectMemberships =+ "projectId" in query+ ? await prisma.projectMembership.findMany({+ select: {+ userId: true,+ role: true,+ },+ where: {+ orgMembershipId: {+ in: orgMemberships.map((m) => m.id),+ },+ projectId: query.projectId,+ },+ })+ : [];++ return {+ memberships: orgMemberships.map((om) => ({+ ...om,+ projectRole: projectMemberships.find((pm) => pm.userId === om.userId)+ ?.role,+ })),+ totalCount,+ };+}++export const allMembersRoutes = {+ allFromOrg: protectedOrganizationProcedure+ .input(orgLevelMemberQuery)+ .query(async ({ input, ctx }) => {+ throwIfNoOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:read",+ });+ return getMembers(ctx.prisma, input);+ }),+ allFromProject: protectedProjectProcedure+ .input(projectLevelMemberQuery)+ .query(async ({ input, ctx }) => {+ const orgAccess = hasOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:read",+ });+ const projectAccess = hasProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "projectMembers:read",+ });+ if (!orgAccess && !projectAccess) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You do not have the required access rights",+ });+ }+ return getMembers(ctx.prisma, input, orgAccess);+ }),+};diff --git a/web/src/features/rbac/server/membersRouter.ts b/web/src/features/rbac/server/membersRouter.tsnew file mode 100644index 0000000000..b7c16f8894--- /dev/null+++ b/web/src/features/rbac/server/membersRouter.ts@@ -0,0 +1,601 @@+import { auditLog } from "@/src/features/audit-logs/auditLog";+import {+ createTRPCRouter,+ protectedOrganizationProcedure,+} from "@/src/server/api/trpc";+import { TRPCError } from "@trpc/server";+import * as z from "zod";+import {+ hasOrganizationAccess,+ throwIfNoOrganizationAccess,+} from "@/src/features/rbac/utils/checkOrganizationAccess";+import { type PrismaClient, Role } from "@langfuse/shared";+import { sendMembershipInvitationEmail } from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";+import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";+import {+ hasProjectAccess,+ throwIfNoProjectAccess,+} from "@/src/features/rbac/utils/checkProjectAccess";+import { allMembersRoutes } from "@/src/features/rbac/server/allMembersRoutes";+import { allInvitesRoutes } from "@/src/features/rbac/server/allInvitesRoutes";+import { orderedRoles } from "@/src/features/rbac/constants/orderedRoles";++// Record as it allows to type check that all roles are included+function throwIfHigherRole({ ownRole, role }: { ownRole: Role; role: Role }) {+ if (orderedRoles[ownRole] < orderedRoles[role]) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You cannot grant/edit a role higher than your own",+ });+ }+}++/**+ * Throw if the user tries to set a project role that is higher than their own+ * role determined by MAX(orgRole, projectRole)+ */+async function throwIfHigherProjectRole({+ orgCtx, // context by protectedOrganizationProcedure+ projectId,+ projectRole,+}: {+ orgCtx: {+ session: {+ orgId: string;+ orgRole: Role;+ user: {+ id: string;+ };+ };+ prisma: PrismaClient;+ };+ projectId: string;+ projectRole: Role;+}) {+ const projectMembership = await orgCtx.prisma.projectMembership.findFirst({+ where: {+ projectId,+ userId: orgCtx.session.user.id,+ organizationMembership: {+ orgId: orgCtx.session.orgId,+ },+ },+ });++ const ownRoleValue: number = projectMembership+ ? Math.max(+ orderedRoles[projectMembership.role],+ orderedRoles[orgCtx.session.orgRole],+ )+ : orderedRoles[orgCtx.session.orgRole];++ if (ownRoleValue < orderedRoles[projectRole]) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You cannot grant/edit a role higher than your own",+ });+ }+}++export const membersRouter = createTRPCRouter({+ ...allMembersRoutes,+ ...allInvitesRoutes,+ create: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ email: z.string().email(),+ orgRole: z.nativeEnum(Role),+ // in case a projectRole should be set for a specific project+ projectId: z.string().optional(),+ projectRole: z.nativeEnum(Role).optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ if (+ // Require only project-level access rights if no orgRole is set but a projectId is+ input.projectId &&+ input.orgRole === Role.NONE+ ) {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "projectMembers:CUD",+ });+ } else {+ // Require org-level access rights+ throwIfNoOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:CUD",+ });+ }++ throwIfHigherRole({+ ownRole: ctx.session.orgRole,+ role: input.orgRole,+ });++ // check for entilement (project role)+ if (input.projectId && input.projectRole) {+ const entitled = hasEntitlement({+ entitlement: "rbac-project-roles",+ sessionUser: ctx.session.user,+ orgId: input.orgId,+ });+ if (!entitled)+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Organization does not have the required entitlement to set project roles",+ });+ }++ const user = await ctx.prisma.user.findUnique({+ where: {+ email: input.email.toLowerCase(),+ },+ });++ // security check if project is in org+ const project = input.projectId+ ? await ctx.prisma.project.findFirst({+ where: {+ id: input.projectId,+ orgId: input.orgId,+ },+ })+ : null;+ if (project && input.projectRole)+ await throwIfHigherProjectRole({+ orgCtx: ctx,+ projectId: project.id,+ projectRole: input.projectRole,+ });++ const org = await ctx.prisma.organization.findFirst({+ where: {+ id: input.orgId,+ },+ });+ if (!org) {+ throw new TRPCError({ code: "NOT_FOUND", message: "Org not found" });+ }++ if (user) {+ const existingOrgMembership =+ await ctx.prisma.organizationMembership.findFirst({+ where: {+ orgId: input.orgId,+ userId: user.id,+ },+ });++ // early return if user is already a member of the org+ if (existingOrgMembership) {+ // user exists and only a project role shall be added+ if (+ input.orgRole === Role.NONE &&+ project &&+ input.projectRole &&+ input.projectRole !== Role.NONE+ ) {+ // Create project role for user+ const newProjectMembership =+ await ctx.prisma.projectMembership.create({+ data: {+ userId: user.id,+ projectId: project.id,+ role: input.projectRole,+ orgMembershipId: existingOrgMembership.id,+ },+ });++ // audit log+ await auditLog({+ session: ctx.session,+ resourceType: "projectMembership",+ resourceId: project.id + "--" + user.id,+ action: "create",+ after: newProjectMembership,+ });+ return;+ } else {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "User is already a member of this organization",+ });+ }+ }++ // create org membership as user is not a member yet+ const orgMembership = await ctx.prisma.organizationMembership.create({+ data: {+ userId: user.id,+ orgId: input.orgId,+ role: input.orgRole,+ },+ });+ await auditLog({+ session: ctx.session,+ resourceType: "orgMembership",+ resourceId: orgMembership.id,+ action: "create",+ after: orgMembership,+ });+ if (project && input.projectRole && input.projectRole !== Role.NONE) {+ const projectMembership = await ctx.prisma.projectMembership.create({+ data: {+ userId: user.id,+ projectId: project.id,+ role: input.projectRole,+ orgMembershipId: orgMembership.id,+ },+ });+ await auditLog({+ session: ctx.session,+ resourceType: "projectMembership",+ resourceId:+ projectMembership.projectId + "--" + projectMembership.userId,+ action: "create",+ after: projectMembership,+ });+ }+ await sendMembershipInvitationEmail({+ inviterEmail: ctx.session.user.email!,+ inviterName: ctx.session.user.name!,+ to: input.email,+ orgName: org.name,+ env: env,+ });+ } else {+ const invitation = await ctx.prisma.membershipInvitation.create({+ data: {+ orgId: input.orgId,+ projectId:+ project && input.projectRole && input.projectRole !== Role.NONE+ ? project.id+ : null,+ email: input.email.toLowerCase(),+ orgRole: input.orgRole,+ projectRole:+ input.projectRole && input.projectRole !== Role.NONE && project+ ? input.projectRole+ : null,+ invitedByUserId: ctx.session.user.id,+ },+ });+ await auditLog({+ session: ctx.session,+ resourceType: "membershipInvitation",+ resourceId: invitation.id,+ action: "create",+ after: invitation,+ });+ await sendMembershipInvitationEmail({+ inviterEmail: ctx.session.user.email!,+ inviterName: ctx.session.user.name!,+ to: input.email,+ orgName: org.name,+ env: env,+ });++ return invitation;+ }+ }),+ deleteMembership: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ orgMembershipId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const orgMembership = await ctx.prisma.organizationMembership.findFirst({+ where: {+ orgId: input.orgId,+ id: input.orgMembershipId,+ },+ include: {+ ProjectMemberships: true,+ },+ });+ if (!orgMembership) throw new TRPCError({ code: "NOT_FOUND" });++ // Check if user has access, either by having the correct role, or being the user themselves that is being deleted+ const hasAccess = hasOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:CUD",+ });+ if (!hasAccess && orgMembership.userId !== ctx.session.user.id)+ throw new TRPCError({ code: "FORBIDDEN" });++ throwIfHigherRole({+ ownRole: ctx.session.orgRole,+ role: orgMembership.role,+ });++ if (orgMembership.role === Role.OWNER) {+ // check if there are other remaining owners+ const owners = await ctx.prisma.organizationMembership.count({+ where: {+ orgId: input.orgId,+ role: Role.OWNER,+ },+ });+ if (owners === 1) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message:+ "Cannot remove the last owner of an organization. Assign new owner or delete organization.",+ });+ }+ }++ await auditLog({+ session: ctx.session,+ resourceType: "orgMembership",+ resourceId: orgMembership.id,+ action: "delete",+ before: orgMembership,+ });++ return await ctx.prisma.organizationMembership.delete({+ where: {+ id: orgMembership.id,+ orgId: input.orgId,+ },+ });+ }),+ deleteInvite: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ inviteId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const invitation = await ctx.prisma.membershipInvitation.findFirst({+ where: {+ orgId: input.orgId,+ id: input.inviteId,+ },+ });+ if (!invitation) throw new TRPCError({ code: "NOT_FOUND" });++ if (+ !(+ hasOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:CUD",+ }) ||+ (invitation.projectId &&+ invitation.orgRole === Role.NONE &&+ hasProjectAccess({+ session: ctx.session,+ projectId: invitation.projectId,+ scope: "projectMembers:CUD",+ }))+ )+ )+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message:+ "You do not have sufficient rights to delete this invitation.",+ });++ await auditLog({+ session: ctx.session,+ resourceType: "membershipInvitation",+ resourceId: invitation.id,+ action: "delete",+ before: invitation,+ });++ return await ctx.prisma.membershipInvitation.delete({+ where: {+ id: invitation.id,+ orgId: input.orgId,+ },+ });+ }),+ updateOrgMembership: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ orgMembershipId: z.string(),+ role: z.nativeEnum(Role),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:CUD",+ });++ const membership = await ctx.prisma.organizationMembership.findFirst({+ where: {+ orgId: input.orgId,+ id: input.orgMembershipId,+ },+ });+ if (!membership) throw new TRPCError({ code: "NOT_FOUND" });++ throwIfHigherRole({+ ownRole: ctx.session.orgRole,+ role: input.role, // new+ });+ throwIfHigherRole({+ ownRole: ctx.session.orgRole,+ role: membership.role, // old+ });++ // check if this is the only remaining owner+ const otherOwners = await ctx.prisma.organizationMembership.count({+ where: {+ orgId: input.orgId,+ role: Role.OWNER,+ id: {+ not: membership.id,+ },+ },+ });+ if (otherOwners === 0) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message:+ "Cannot remove the last owner of an organization. Assign new owner or delete organization.",+ });+ }++ await auditLog({+ session: ctx.session,+ resourceType: "orgMembership",+ resourceId: membership.id,+ action: "update",+ before: membership,+ });++ return await ctx.prisma.organizationMembership.update({+ where: {+ id: membership.id,+ orgId: input.orgId,+ },+ data: {+ role: input.role,+ },+ });+ }),+ updateProjectRole: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ orgMembershipId: z.string(),+ userId: z.string(),+ projectId: z.string(),+ projectRole: z.nativeEnum(Role).nullable(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const hasAccess =+ hasOrganizationAccess({+ session: ctx.session,+ organizationId: input.orgId,+ scope: "organizationMembers:CUD",+ }) ||+ hasProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "projectMembers:CUD",+ });+ if (!hasAccess) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You do not have the required access rights",+ });+ }++ // check org membership id, can be trusted after this check+ const orgMembership = await ctx.prisma.organizationMembership.findUnique({+ where: {+ id: input.orgMembershipId,+ orgId: input.orgId,+ },+ });+ if (!orgMembership) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Organization membership not found",+ });+ }++ // cannot edit project roles of users with higher org roles+ throwIfHigherRole({+ ownRole: ctx.session.orgRole,+ role: orgMembership.role,+ });++ const projectMembership = await ctx.prisma.projectMembership.findFirst({+ where: {+ projectId: input.projectId,+ userId: input.userId,+ orgMembershipId: input.orgMembershipId,+ },+ });++ // check existing project role if it is higher than own role+ if (projectMembership) {+ await throwIfHigherProjectRole({+ orgCtx: ctx,+ projectId: input.projectId,+ projectRole: projectMembership.role,+ });+ }++ // If the project role is set to null, delete the project membership+ if (input.projectRole === null || input.projectRole === Role.NONE) {+ if (projectMembership) {+ await ctx.prisma.projectMembership.delete({+ where: {+ projectId_userId: {+ projectId: input.projectId,+ userId: input.userId,+ },+ orgMembershipId: input.orgMembershipId,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "projectMembership",+ resourceId: `${input.orgMembershipId}--${input.projectId}`,+ action: "delete",+ before: projectMembership,+ });+ }+ return null;+ }++ // check new project role if it is higher than own role+ await throwIfHigherProjectRole({+ orgCtx: ctx,+ projectId: input.projectId,+ projectRole: input.projectRole,+ });++ // Create/update+ const updatedProjectMembership =+ await ctx.prisma.projectMembership.upsert({+ where: {+ projectId_userId: {+ projectId: input.projectId,+ userId: input.userId,+ },+ orgMembershipId: input.orgMembershipId,+ },+ update: {+ role: input.projectRole,+ },+ create: {+ projectId: input.projectId,+ userId: input.userId,+ role: input.projectRole,+ orgMembershipId: input.orgMembershipId,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "projectMembership",+ resourceId: input.projectId + "--" + input.userId,+ action: "update",+ before: projectMembership,+ });++ return updatedProjectMembership;+ }),+});diff --git a/web/src/features/rbac/server/projectMembersRouter.ts b/web/src/features/rbac/server/projectMembersRouter.tsdeleted file mode 100644index 52a341a1a6..0000000000--- a/web/src/features/rbac/server/projectMembersRouter.ts+++ /dev/null@@ -1,216 +0,0 @@-import * as z from "zod";--import { env } from "@/src/env.mjs";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";-import {- createTRPCRouter,- protectedProjectProcedure,-} from "@/src/server/api/trpc";-import { ProjectRole } from "@langfuse/shared/src/db";-import { sendProjectInvitationEmail } from "@langfuse/shared/src/server";-import { TRPCError } from "@trpc/server";--export const projectMembersRouter = createTRPCRouter({- get: protectedProjectProcedure- .input(- z.object({- projectId: z.string(),- }),- )- .query(async ({ input, ctx }) => {- throwIfNoAccess({- session: ctx.session,- projectId: input.projectId,- scope: "members:read",- });-- const memberships = await ctx.prisma.projectMembership.findMany({- where: {- projectId: input.projectId,- project: {- projectMembers: {- some: {- userId: ctx.session.user.id,- },- },- },- },- include: {- user: {- select: {- id: true,- name: true,- email: true,- },- },- },- });-- const invitations = await ctx.prisma.membershipInvitation.findMany({- where: {- projectId: input.projectId,- },- include: {- sender: {- select: {- name: true,- },- },- },- });-- return { memberships: memberships, invitations: invitations };- }),- delete: protectedProjectProcedure- .input(- z.object({- projectId: z.string(),- userId: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- throwIfNoAccess({- session: ctx.session,- projectId: input.projectId,- scope: "members:delete",- });-- if (input.userId === ctx.session.user.id)- throw new Error("You cannot remove yourself from a project");-- const membership = await ctx.prisma.projectMembership.findFirst({- where: {- projectId: input.projectId,- userId: input.userId,- role: {- not: ProjectRole.OWNER,- },- },- });-- if (!membership) throw new TRPCError({ code: "NOT_FOUND" });-- await auditLog({- session: ctx.session,- resourceType: "membership",- resourceId: membership.projectId + "--" + membership.userId,- action: "delete",- before: membership,- });-- // use ids from membership to make sure owners cannot delete themselves- return await ctx.prisma.projectMembership.delete({- where: {- projectId_userId: {- projectId: membership.projectId,- userId: membership.userId,- },- },- });- }),- deleteInvitation: protectedProjectProcedure- .input(- z.object({- id: z.string(),- projectId: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- throwIfNoAccess({- session: ctx.session,- projectId: input.projectId,- scope: "members:delete",- });-- await auditLog({- session: ctx.session,- resourceType: "membershipInvitation",- resourceId: input.id,- action: "delete",- });-- return await ctx.prisma.membershipInvitation.delete({- where: {- id: input.id,- projectId: input.projectId,- },- });- }),- create: protectedProjectProcedure- .input(- z.object({- projectId: z.string(),- email: z.string().email(),- role: z.enum([- ProjectRole.ADMIN,- ProjectRole.MEMBER,- ProjectRole.VIEWER,- ]),- }),- )- .mutation(async ({ input, ctx }) => {- throwIfNoAccess({- session: ctx.session,- projectId: input.projectId,- scope: "members:create",- });-- const user = await ctx.prisma.user.findUnique({- where: {- email: input.email.toLowerCase(),- },- });- if (user) {- const membership = await ctx.prisma.projectMembership.create({- data: {- userId: user.id,- projectId: input.projectId,- role: input.role,- },- });- await auditLog({- session: ctx.session,- resourceType: "membership",- resourceId: input.projectId + "--" + user.id,- action: "create",- after: membership,- });- return membership;- } else {- const invitation = await ctx.prisma.membershipInvitation.create({- data: {- projectId: input.projectId,- email: input.email.toLowerCase(),- role: input.role,- senderId: ctx.session.user.id,- },- });- await auditLog({- session: ctx.session,- resourceType: "membershipInvitation",- resourceId: invitation.id,- action: "create",- after: invitation,- });-- const project = await ctx.prisma.project.findFirst({- where: {- id: input.projectId,- },- });-- if (!project) throw new Error("Project not found");-- await sendProjectInvitationEmail({- env,- to: input.email,- inviterName: ctx.session.user.name!,- inviterEmail: ctx.session.user.email!,- projectName: project.name,- });-- return invitation;- }- }),-});diff --git a/web/src/features/rbac/utils/checkOrganizationAccess.ts b/web/src/features/rbac/utils/checkOrganizationAccess.tsnew file mode 100644index 0000000000..08e0ca47d9--- /dev/null+++ b/web/src/features/rbac/utils/checkOrganizationAccess.ts@@ -0,0 +1,69 @@+import {+ organizationRoleAccessRights,+ type OrganizationScope,+} from "@/src/features/rbac/constants/organizationAccessRights";+import { type Role } from "@langfuse/shared/src/db";+import { TRPCError } from "@trpc/server";+import { type Session } from "next-auth";+import { useSession } from "next-auth/react";++type HasOrganizationAccessParams =+ | {+ role: Role;+ scope: OrganizationScope;+ admin?: boolean; // prop user.admin+ }+ | {+ session: null | Session;+ organizationId: string;+ scope: OrganizationScope;+ };++/**+ * Check if user has access to the given scope, for use in TRPC resolvers+ * @throws TRPCError("UNAUTHORIZED") if user does not have access+ */+export const throwIfNoOrganizationAccess = (p: HasOrganizationAccessParams) => {+ if (!hasOrganizationAccess(p))+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message:+ "Unauthorized, user does not have access to this resource or action",+ });+};++/**+ * React hook to check if user has access to the given scope+ * @returns true if user has access, false otherwise or while loading+ */+export const useHasOrganizationAccess = (p: {+ organizationId: string | undefined;+ scope: OrganizationScope;+}) => {+ const { scope, organizationId } = p;+ const session = useSession();++ if (!organizationId) return false;++ return hasOrganizationAccess({+ session: session.data,+ scope,+ organizationId,+ });+};++// For use in UI components as function, if session is already available+export function hasOrganizationAccess(p: HasOrganizationAccessParams): boolean {+ const isAdmin = "role" in p ? p.admin : p.session?.user?.admin;+ if (isAdmin) return true;++ const organizationRole: Role | undefined =+ "role" in p+ ? p.role+ : p.session?.user?.organizations.find(+ (org) => org.id === p.organizationId,+ )?.role;+ if (organizationRole === undefined) return false;++ return organizationRoleAccessRights[organizationRole].includes(p.scope);+}diff --git a/web/src/features/rbac/utils/checkAccess.ts b/web/src/features/rbac/utils/checkProjectAccess.tssimilarity index 57%rename from web/src/features/rbac/utils/checkAccess.tsrename to web/src/features/rbac/utils/checkProjectAccess.tsindex 3bb7b34779..016dc6d007 100644--- a/web/src/features/rbac/utils/checkAccess.ts+++ b/web/src/features/rbac/utils/checkProjectAccess.ts@@ -1,30 +1,30 @@import {- roleAccessRights,- type Scope,-} from "@/src/features/rbac/constants/roleAccessRights";-import { type ProjectRole } from "@langfuse/shared/src/db";+ projectRoleAccessRights,+ type ProjectScope,+} from "@/src/features/rbac/constants/projectAccessRights";+import { type Role } from "@langfuse/shared/src/db";import { TRPCError } from "@trpc/server";import { type Session } from "next-auth";import { useSession } from "next-auth/react";-type HasAccessParams =+type HasProjectAccessParams =| {- role: ProjectRole;- scope: Scope;+ role: Role;+ scope: ProjectScope;admin?: boolean; // prop user.admin}| {session: null | Session;projectId: string;- scope: Scope;+ scope: ProjectScope;};/*** Check if user has access to the given scope, for use in TRPC resolvers* @throws TRPCError("UNAUTHORIZED") if user does not have access*/-export const throwIfNoAccess = (p: HasAccessParams) => {- if (!hasAccess(p))+export const throwIfNoProjectAccess = (p: HasProjectAccessParams) => {+ if (!hasProjectAccess(p))throw new TRPCError({code: "UNAUTHORIZED",message:@@ -36,29 +36,30 @@ export const throwIfNoAccess = (p: HasAccessParams) => {* React hook to check if user has access to the given scope* @returns true if user has access, false otherwise or while loading*/-export const useHasAccess = (p: {+export const useHasProjectAccess = (p: {projectId: string | undefined;- scope: Scope;+ scope: ProjectScope;}) => {const { scope, projectId } = p;const session = useSession();if (!projectId) return false;- return hasAccess({ session: session.data, scope, projectId });+ return hasProjectAccess({ session: session.data, scope, projectId });};// For use in UI components as function, if session is already available-export function hasAccess(p: HasAccessParams): boolean {+export function hasProjectAccess(p: HasProjectAccessParams): boolean {const isAdmin = "role" in p ? p.admin : p.session?.user?.admin;if (isAdmin) return true;- const projectRole: ProjectRole | undefined =+ const projectRole: Role | undefined ="role" in p? p.role- : p.session?.user?.projects.find((project) => project.id === p.projectId)- ?.role;+ : p.session?.user?.organizations+ .flatMap((org) => org.projects)+ .find((project) => project.id === p.projectId)?.role;if (projectRole === undefined) return false;- return roleAccessRights[projectRole].includes(p.scope);+ return projectRoleAccessRights[projectRole].includes(p.scope);}diff --git a/web/src/features/scores/components/AnnotateDrawer.tsx b/web/src/features/scores/components/AnnotateDrawer.tsxindex 6255c4a91f..e8c8cb0433 100644--- a/web/src/features/scores/components/AnnotateDrawer.tsx+++ b/web/src/features/scores/components/AnnotateDrawer.tsx@@ -1,4 +1,3 @@-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";import React, { useEffect, useRef } from "react";import { Button } from "@/src/components/ui/button";import {@@ -72,6 +71,7 @@ import { CommandItem } from "@/src/components/ui/command";import { useRouter } from "next/router";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { cn } from "@/src/utils/tailwind";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { isPresent } from "@/src/utils/typeChecks";const AnnotationScoreDataSchema = z.object({@@ -195,7 +195,7 @@ function AnnotateDrawerInner({source?: "TraceDetail" | "SessionDetail";}) {const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId,scope: "scores:CUD",});diff --git a/web/src/features/scores/components/CreateScoreConfigButton.tsx b/web/src/features/scores/components/CreateScoreConfigButton.tsxindex 47cace907f..da652a4819 100644--- a/web/src/features/scores/components/CreateScoreConfigButton.tsx+++ b/web/src/features/scores/components/CreateScoreConfigButton.tsx@@ -1,6 +1,6 @@import React, { useState } from "react";import { Button } from "@/src/components/ui/button";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {Dialog,DialogContent,@@ -100,7 +100,7 @@ export function CreateScoreConfigButton({ projectId }: { projectId: string }) {const [formError, setFormError] = useState<string | null>(null);const capture = usePostHogClientCapture();- const hasAccess = useHasAccess({+ const hasAccess = useHasProjectAccess({projectId: projectId,scope: "scoreConfigs:CUD",});diff --git a/web/src/features/scores/components/ScoreConfigSettings.tsx b/web/src/features/scores/components/ScoreConfigSettings.tsxindex 61657ae7bc..f10df910a4 100644--- a/web/src/features/scores/components/ScoreConfigSettings.tsx+++ b/web/src/features/scores/components/ScoreConfigSettings.tsx@@ -1,11 +1,11 @@import React from "react";import Header from "@/src/components/layouts/header";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { CreateScoreConfigButton } from "@/src/features/scores/components/CreateScoreConfigButton";import { ScoreConfigsTable } from "@/src/components/table/use-cases/score-configs";export function ScoreConfigSettings({ projectId }: { projectId: string }) {- const hasReadAccess = useHasAccess({+ const hasReadAccess = useHasProjectAccess({projectId: projectId,scope: "scoreConfigs:read",});diff --git a/web/src/features/setup/components/SetupPage.tsx b/web/src/features/setup/components/SetupPage.tsxnew file mode 100644index 0000000000..2306bd96e8--- /dev/null+++ b/web/src/features/setup/components/SetupPage.tsx@@ -0,0 +1,261 @@+import Header from "@/src/components/layouts/header";+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbList,+ BreadcrumbPage,+ BreadcrumbSeparator,+} from "@/src/components/ui/breadcrumb";+import { Button } from "@/src/components/ui/button";+import { Card } from "@/src/components/ui/card";+import { NewOrganizationForm } from "@/src/features/organizations/components/NewOrganizationForm";+import { NewProjectForm } from "@/src/features/projects/components/NewProjectForm";+import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";+import { ApiKeyRender } from "@/src/features/public-api/components/CreateApiKeyButton";+import { QuickstartExamples } from "@/src/features/public-api/components/QuickstartExamples";+import { MembershipInvitesPage } from "@/src/features/rbac/components/MembershipInvitesPage";+import { MembersTable } from "@/src/features/rbac/components/MembersTable";+import {+ createProjectRoute,+ inviteMembersRoute,+ setupTracingRoute,+} from "@/src/features/setup/setupRoutes";+import { api } from "@/src/utils/api";+import { cn } from "@/src/utils/tailwind";+import { type RouterOutput } from "@/src/utils/types";+import { Check } from "lucide-react";+import { useRouter } from "next/router";+import { useEffect, useRef, useState } from "react";+import { StringParam, useQueryParam } from "use-query-params";++// Multi-step setup process+// 1. Create Organization: /setup+// 2. Invite Members: /organization/:orgId/setup+// 3. Create Project: /organization/:orgId/setup?step=create-project+// 4. Setup Tracing: /project/:projectId/setup+export function SetupPage() {+ const { project, organization } = useQueryProjectOrOrganization();+ const router = useRouter();+ const [orgStep] = useQueryParam("orgstep", StringParam); // "invite-members" | "create-project"++ // starts at 1 to align with breadcrumb+ const stepInt = !organization+ ? 1+ : project+ ? 4+ : orgStep === "create-project"+ ? 3+ : 2;++ const hasAnyTrace =+ api.traces.hasAny.useQuery(+ { projectId: project?.id ?? "no-project" },+ {+ enabled: !!project && stepInt === 4,+ refetchInterval: 5000,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ ).data ?? false;++ return (+ <div className="mb-12 md:container">+ <Header+ title="Setup"+ help={{+ description:+ "Create a new organization. This will be used to manage your projects and teams.",+ }}+ />+ <Breadcrumb className="mb-3">+ <BreadcrumbList>+ <BreadcrumbItem>+ <BreadcrumbPage+ className={cn(+ stepInt !== 1+ ? "text-muted-foreground"+ : "font-semibold text-foreground",+ )}+ >+ 1. Create Organization+ {stepInt > 1 && <Check className="ml-1 inline-block h-3 w-3" />}+ </BreadcrumbPage>+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbPage+ className={cn(+ stepInt !== 2+ ? "text-muted-foreground"+ : "font-semibold text-foreground",+ )}+ >+ 2. Invite Members+ {stepInt > 2 && <Check className="ml-1 inline-block h-3 w-3" />}+ </BreadcrumbPage>+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbPage+ className={cn(+ stepInt !== 3+ ? "text-muted-foreground"+ : "font-semibold text-foreground",+ )}+ >+ 3. Create Project+ {stepInt > 3 && <Check className="ml-1 inline-block h-3 w-3" />}+ </BreadcrumbPage>+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbPage+ className={cn(+ stepInt !== 4+ ? "text-muted-foreground"+ : "font-semibold text-foreground",+ )}+ >+ 4. Setup Tracing+ {stepInt === 4 && <Check className="ml-1 inline-block h-3 w-3" />}+ </BreadcrumbPage>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ <Card className="p-3">+ {+ // 1. Create Org+ stepInt === 1 && (+ <NewOrganizationForm+ onSuccess={(orgId) => {+ router.push(inviteMembersRoute(orgId));+ }}+ />+ )+ }+ {+ // 2. Invite Members+ stepInt === 2 && organization && (+ <div className="flex flex-col gap-10">+ <div>+ <Header title="Organization Members" level="h3" />+ <MembersTable orgId={organization.id} />+ </div>+ <div>+ <MembershipInvitesPage orgId={organization.id} />+ </div>+ </div>+ )+ }+ {+ // 3. Create Project+ stepInt === 3 && organization && (+ <NewProjectForm+ orgId={organization.id}+ onSuccess={(projectId) =>+ router.push(setupTracingRoute(projectId))+ }+ />+ )+ }+ {+ // 4. Setup Tracing+ stepInt === 4 && project && organization && (+ <div className="space-y-8">+ <div>+ <Header title="API Keys" level="h3" />+ <TracingSetup+ projectId={project.id}+ hasAnyTrace={hasAnyTrace}+ />+ </div>+ </div>+ )+ }+ </Card>+ {stepInt === 2 && organization && (+ <Button+ className="mt-4"+ data-testid="btn-skip-add-members"+ onClick={() => router.push(createProjectRoute(organization.id))}+ >+ Next+ </Button>+ )}+ {+ // 4. Setup Tracing+ stepInt === 4 && project && (+ <Button+ className="mt-4"+ onClick={() => router.push(`/project/${project.id}`)}+ variant={hasAnyTrace ? "default" : "secondary"}+ >+ {hasAnyTrace ? "Open Dashboard" : "Skip for now"}+ </Button>+ )+ }+ </div>+ );+}++const TracingSetup = ({+ projectId,+ hasAnyTrace,+}: {+ projectId: string;+ hasAnyTrace?: boolean;+}) => {+ const [apiKeys, setApiKeys] = useState<+ RouterOutput["apiKeys"]["create"] | null+ >(null);+ const utils = api.useUtils();+ const mutCreateApiKey = api.apiKeys.create.useMutation({+ onSuccess: () => utils.apiKeys.invalidate(),+ });+ const isLoadingRef = useRef(false);++ useEffect(() => {+ const createApiKey = async () => {+ if (projectId && !isLoadingRef.current && !apiKeys) {+ isLoadingRef.current = true;+ try {+ const apiKey = await mutCreateApiKey.mutateAsync({ projectId });+ setApiKeys(apiKey);+ } catch (error) {+ console.error("Error creating API key:", error);+ } finally {+ isLoadingRef.current = false;+ }+ }+ };+ if (!apiKeys) {+ createApiKey();+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ return (+ <div className="space-y-8">+ <div>+ <ApiKeyRender generatedKeys={apiKeys ?? undefined} />+ </div>+ {apiKeys && (+ <div>+ <Header+ title="Setup Tracing"+ level="h3"+ status={hasAnyTrace ? "active" : "pending"}+ />+ <QuickstartExamples+ secretKey={apiKeys.secretKey}+ publicKey={apiKeys.publicKey}+ host={window.origin}+ />+ </div>+ )}+ </div>+ );+};diff --git a/web/src/features/setup/components/SetupTracingButton.tsx b/web/src/features/setup/components/SetupTracingButton.tsxnew file mode 100644index 0000000000..0a303da180--- /dev/null+++ b/web/src/features/setup/components/SetupTracingButton.tsx@@ -0,0 +1,48 @@+import { Button } from "@/src/components/ui/button";+import Link from "next/link";+import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";+import { api } from "@/src/utils/api";+import { setupTracingRoute } from "@/src/features/setup/setupRoutes";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { LockIcon } from "lucide-react";++const SetupTracingButton = () => {+ const { project } = useQueryProjectOrOrganization();++ const { data: hasAnyTrace, isLoading } = api.traces.hasAny.useQuery(+ { projectId: project?.id ?? "no-project" },+ {+ enabled: project !== undefined,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ const hasAccess = useHasProjectAccess({+ projectId: project?.id,+ scope: "apiKeys:create",+ });++ if (isLoading || hasAnyTrace || !project) {+ return null;+ }++ if (!hasAccess)+ return (+ <Button disabled>+ <LockIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" />+ Configure Tracing+ </Button>+ );++ return (+ <Link href={setupTracingRoute(project.id)}>+ <Button>Configure Tracing</Button>+ </Link>+ );+};++export default SetupTracingButton;diff --git a/web/src/features/setup/setupRoutes.ts b/web/src/features/setup/setupRoutes.tsnew file mode 100644index 0000000000..ea40c48fdc--- /dev/null+++ b/web/src/features/setup/setupRoutes.ts@@ -0,0 +1,10 @@+export const createOrganizationRoute = "/setup";++export const createProjectRoute = (orgId: string) =>+ `/organization/${orgId}/setup?orgstep=create-project`;++export const inviteMembersRoute = (orgId: string) =>+ `/organization/${orgId}/setup?orgstep=invite-members`;++export const setupTracingRoute = (projectId: string) =>+ `/project/${projectId}/setup`;diff --git a/web/src/features/tag/components/TagPromptDetailsPopover.tsx b/web/src/features/tag/components/TagPromptDetailsPopover.tsxindex 371194cbb5..423638a6fa 100644--- a/web/src/features/tag/components/TagPromptDetailsPopover.tsx+++ b/web/src/features/tag/components/TagPromptDetailsPopover.tsx@@ -1,6 +1,6 @@import React, { useState } from "react";import { api } from "@/src/utils/api";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { type RouterOutput } from "@/src/utils/types";import TagManager from "@/src/features/tag/components/TagMananger";import { trpcErrorToast } from "@/src/utils/trpcErrorToast";@@ -21,7 +21,7 @@ export function TagPromptDetailsPopover({className,}: TagPromptDetailsPopoverProps) {const [isLoading, setIsLoading] = useState(false);- const hasAccess = useHasAccess({ projectId, scope: "objects:tag" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "objects:tag" });const utils = api.useUtils();const mutTags = api.prompts.updateTags.useMutation({diff --git a/web/src/features/tag/components/TagPromptPopover.tsx b/web/src/features/tag/components/TagPromptPopover.tsxindex 172cb39f48..46ed33ea1d 100644--- a/web/src/features/tag/components/TagPromptPopover.tsx+++ b/web/src/features/tag/components/TagPromptPopover.tsx@@ -1,6 +1,6 @@import React, { useState } from "react";import { api } from "@/src/utils/api";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { type RouterOutput, type RouterInput } from "@/src/utils/types";import TagManager from "@/src/features/tag/components/TagMananger";import { trpcErrorToast } from "@/src/utils/trpcErrorToast";@@ -23,7 +23,7 @@ export function TagPromptPopover({className,}: TagPromptPopverProps) {const [isLoading, setIsLoading] = useState(false);- const hasAccess = useHasAccess({ projectId, scope: "objects:tag" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "objects:tag" });const utils = api.useUtils();const mutTags = api.prompts.updateTags.useMutation({diff --git a/web/src/features/tag/components/TagTraceDetailsPopover.tsx b/web/src/features/tag/components/TagTraceDetailsPopover.tsxindex 987119b965..01ca1897f2 100644--- a/web/src/features/tag/components/TagTraceDetailsPopover.tsx+++ b/web/src/features/tag/components/TagTraceDetailsPopover.tsx@@ -1,6 +1,6 @@import React, { useState } from "react";import { api } from "@/src/utils/api";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { type RouterOutput } from "@/src/utils/types";import TagManager from "@/src/features/tag/components/TagMananger";import { trpcErrorToast } from "@/src/utils/trpcErrorToast";@@ -21,7 +21,7 @@ export function TagTraceDetailsPopover({className,}: TagTraceDetailsPopoverProps) {const [isLoading, setIsLoading] = useState(false);- const hasAccess = useHasAccess({ projectId, scope: "objects:tag" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "objects:tag" });const utils = api.useUtils();const mutTags = api.traces.updateTags.useMutation({diff --git a/web/src/features/tag/components/TagTracePopver.tsx b/web/src/features/tag/components/TagTracePopver.tsxindex ddca7de580..24603d8cd7 100644--- a/web/src/features/tag/components/TagTracePopver.tsx+++ b/web/src/features/tag/components/TagTracePopver.tsx@@ -1,6 +1,6 @@import React, { useState } from "react";import { api } from "@/src/utils/api";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { type RouterOutput, type RouterInput } from "@/src/utils/types";import TagManager from "@/src/features/tag/components/TagMananger";import { trpcErrorToast } from "@/src/utils/trpcErrorToast";@@ -23,7 +23,7 @@ export function TagTracePopover({className,}: TagTracePopoverProps) {const [isLoading, setIsLoading] = useState(false);- const hasAccess = useHasAccess({ projectId, scope: "objects:tag" });+ const hasAccess = useHasProjectAccess({ projectId, scope: "objects:tag" });const utils = api.useUtils();const mutTags = api.traces.updateTags.useMutation({diff --git a/web/src/features/usage-metering/ProjectUsageChart.tsx b/web/src/features/usage-metering/OrganizationUsageChart.tsxsimilarity index 82%rename from web/src/features/usage-metering/ProjectUsageChart.tsxrename to web/src/features/usage-metering/OrganizationUsageChart.tsxindex 1f83d80a24..390906c159 100644--- a/web/src/features/usage-metering/ProjectUsageChart.tsx+++ b/web/src/features/usage-metering/OrganizationUsageChart.tsx@@ -1,9 +1,8 @@// Langfuse Cloud onlyimport { Button } from "@/src/components/ui/button";-import { env } from "@/src/env.mjs";import { api } from "@/src/utils/api";-import { Card, Flex, MarkerBar, Metric, Text } from "@tremor/react";+import { Flex, MarkerBar, Metric, Text } from "@tremor/react";import Link from "next/link";import { PricingPage } from "@/src/features/pricing-page/PricingPage";import {@@ -14,16 +13,20 @@ import {} 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";-export const ProjectUsageChart: React.FC<{ projectId: string }> = ({- projectId,-}) => {+export const OrganizationUsageChart = () => {+ const organization = useQueryOrganization();+ const entitled = useHasOrgEntitlement("cloud-usage-metering");const usage = api.usageMetering.last30d.useQuery({- projectId,+ orgId: organization!.id,},{+ enabled: organization !== undefined && entitled,trpc: {context: {skipBatch: true,@@ -32,17 +35,16 @@ export const ProjectUsageChart: React.FC<{ projectId: string }> = ({},);const capture = usePostHogClientCapture();- const project = api.projects.byId.useQuery({ projectId });const planLimit =- project.data?.cloudConfig?.monthlyObservationLimit ?? 50_000;- const plan = project.data?.cloudConfig?.plan ?? "Hobby";+ organization?.cloudConfig?.monthlyObservationLimit ?? 50_000;+ const plan = organization?.cloudConfig?.plan ?? "Hobby";- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return null;+ if (!entitled) return null;return (<div><Header title="Usage & Billing" level="h3" />- <Card className="p-4 lg:w-1/2">+ <Card className="p-4">{usage.data !== undefined ? (<><Text>Observations / last 30d</Text>diff --git a/web/src/features/usage-metering/server/usageMeteringRouter.ts b/web/src/features/usage-metering/server/usageMeteringRouter.tsindex 1e2a3e7c37..bdf57b8622 100644--- a/web/src/features/usage-metering/server/usageMeteringRouter.ts+++ b/web/src/features/usage-metering/server/usageMeteringRouter.ts@@ -1,25 +1,40 @@+import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";import {createTRPCRouter,- protectedProjectProcedure,+ protectedOrganizationProcedure,} from "@/src/server/api/trpc";+import { TRPCError } from "@trpc/server";import * as z from "zod";export const usageMeteringRouter = createTRPCRouter({- last30d: protectedProjectProcedure+ last30d: protectedOrganizationProcedure.input(z.object({- projectId: z.string(),+ orgId: z.string(),}),).query(async ({ input, ctx }) => {+ if (+ !hasEntitlement({+ entitlement: "cloud-usage-metering",+ sessionUser: ctx.session.user,+ orgId: input.orgId,+ })+ )+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Missing cloud-usage-metering entitlement",+ });+const thirtyDaysAgo = new Date();thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);thirtyDaysAgo.setHours(0, 0, 0, 0);const usage = await ctx.prisma.observation.count({where: {- projectId: input.projectId,-+ project: {+ orgId: input.orgId,+ },startTime: {gte: thirtyDaysAgo,},diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsxindex deee23884f..c7b5aae8dd 100644--- a/web/src/pages/_app.tsx+++ b/web/src/pages/_app.tsx@@ -132,7 +132,13 @@ function UserTracking() {email: session.data.user?.email ?? undefined,name: session.data.user?.name ?? undefined,featureFlags: session.data.user?.featureFlags ?? undefined,- projects: session.data.user?.projects ?? undefined,+ projects:+ session.data.user?.organizations.flatMap((org) =>+ org.projects.map((project) => ({+ ...project,+ organization: org,+ })),+ ) ?? undefined,LANGFUSE_CLOUD_REGION: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,});const emailDomain = session.data.user?.email?.split("@")[1];@@ -152,8 +158,8 @@ function UserTracking() {email: session.data.user?.email ?? "undefined",data: {userId: session.data.user?.id ?? "undefined",- projects: session.data.user?.projects- ? JSON.stringify(session.data.user.projects)+ organizations: session.data.user?.organizations+ ? JSON.stringify(session.data.user.organizations): "undefined",featureFlags: session.data.user?.featureFlags? JSON.stringify(session.data.user.featureFlags)diff --git a/web/src/pages/auth/sign-up.tsx b/web/src/pages/auth/sign-up.tsxindex ac55942393..6f28dbd11d 100644--- a/web/src/pages/auth/sign-up.tsx+++ b/web/src/pages/auth/sign-up.tsx@@ -67,7 +67,7 @@ export default function SignIn({ authProviders }: PageProps) {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "DEV"? "/onboarding"- : "/?getStarted=1",+ : "/",turnstileToken,});} catch (err) {@@ -194,7 +194,7 @@ export default function SignIn({ authProviders }: PageProps) {Already have an account?{" "}<Linkhref="/auth/sign-in"- className="hover:text-hover-primary-accent font-semibold leading-6 text-primary-accent"+ className="font-semibold leading-6 text-primary-accent hover:text-hover-primary-accent">Sign in</Link>diff --git a/web/src/pages/index.tsx b/web/src/pages/index.tsxindex d914ba882f..02e5cadff8 100644--- a/web/src/pages/index.tsx+++ b/web/src/pages/index.tsx@@ -1,115 +1,5 @@-import { Button } from "@/src/components/ui/button";-import {- Card,- CardContent,- CardFooter,- CardHeader,- CardTitle,-} from "@/src/components/ui/card";-import Link from "next/link";-import { NewProjectButton } from "@/src/features/projects/components/NewProjectButton";-import Header from "@/src/components/layouts/header";-import { useRouter } from "next/router";-import { env } from "@/src/env.mjs";-import { cn } from "@/src/utils/tailwind";-import { useSession } from "next-auth/react";-import { Spinner } from "@/src/components/layouts/spinner";+import { OrganizationProjectOverview } from "@/src/features/organizations/components/ProjectOverview";-export default function GetStartedPage() {- const router = useRouter();- const getStarted = router.query.getStarted === "1";-- const session = useSession();- const projects = session.data?.user?.projects;- const redirectProject = projects?.filter(- (p) => p.id !== env.NEXT_PUBLIC_DEMO_PROJECT_ID,- )[0];-- if (session.status === "authenticated" && redirectProject && !getStarted) {- void router.push(`/project/${redirectProject.id}`);- return <Spinner message="Redirecting" />;- }-- if (session.status === "loading") {- return <Spinner message="Loading" />;- }-- const demoProject =- env.NEXT_PUBLIC_DEMO_PROJECT_ID !== undefined- ? projects?.find(- (project) => project.id === env.NEXT_PUBLIC_DEMO_PROJECT_ID,- )- : undefined;-- return (- <div className="md:container">- <Header- title="Get started"- actionButtons={- <Button asChild>- <Link href="https://docs.langfuse.com">Visit docs ↗</Link>- </Button>- }- />- <div className="grid grid-cols-1 gap-5 lg:grid-cols-2">- <Card className="flex-1">- <CardHeader>- <CardTitle data-testid="create-new-project-title">- Create new project- </CardTitle>- </CardHeader>- <CardContent>- <p>- Get started by yourself. You can always reach out to us later or- get help in the discord community.- </p>- </CardContent>- <CardFooter>- <NewProjectButton />- </CardFooter>- </Card>- {demoProject ? (- <Card className="flex-1">- <CardHeader>- <CardTitle>View demo project</CardTitle>- </CardHeader>- <CardContent>- <p>- Checkout the {demoProject.name} project, it tracks the Q&A- chatbot on the Langfuse documentation.- </p>- </CardContent>- <CardFooter className="flex flex-wrap gap-2">- <Button asChild>- <Link href={"/project/" + demoProject.id}>- Go to demo project- </Link>- </Button>- </CardFooter>- </Card>- ) : null}- <Card className={cn(demoProject && "col-span-full")}>- <CardHeader>- <CardTitle>Guided onboarding</CardTitle>- </CardHeader>- <CardContent>- <p>If you prefer 1:1 support, we are happy to help.</p>- </CardContent>- <CardFooter className="flex flex-wrap gap-2">- <Button asChild variant="secondary">- <Link href="https://cal.com/marc-kl/langfuse-cloud">- Schedule call with founder- </Link>- </Button>- <Button asChild variant="secondary">- <Link href="https://discord.gg/7NXusRtqYU">Discord</Link>- </Button>- <Button asChild variant="secondary">- <Link href="mailto:[email protected]">Email</Link>- </Button>- </CardFooter>- </Card>- </div>- </div>- );+export default function Home() {+ return <OrganizationProjectOverview />;}diff --git a/web/src/pages/onboarding.tsx b/web/src/pages/onboarding.tsxindex 2196a53b66..ca83adf705 100644--- a/web/src/pages/onboarding.tsx+++ b/web/src/pages/onboarding.tsx@@ -40,7 +40,7 @@ export default function ReferralSource() {$survey_response: values.referralSource,});}- void router.push("/?getStarted=1");+ void router.push("/");}return (diff --git a/web/src/pages/organization/[organizationId]/index.tsx b/web/src/pages/organization/[organizationId]/index.tsxnew file mode 100644index 0000000000..6474c77916--- /dev/null+++ b/web/src/pages/organization/[organizationId]/index.tsx@@ -0,0 +1 @@+export { OrganizationProjectOverview as default } from "@/src/features/organizations/components/ProjectOverview";diff --git a/web/src/pages/organization/[organizationId]/settings/[page].tsx b/web/src/pages/organization/[organizationId]/settings/[page].tsxnew file mode 100644index 0000000000..a7bbdfee96--- /dev/null+++ b/web/src/pages/organization/[organizationId]/settings/[page].tsx@@ -0,0 +1,3 @@+import OrgSettingsPage from "@/src/pages/organization/[organizationId]/settings";++export default OrgSettingsPage;diff --git a/web/src/pages/organization/[organizationId]/settings/index.tsx b/web/src/pages/organization/[organizationId]/settings/index.tsxnew file mode 100644index 0000000000..fd5bac7318--- /dev/null+++ b/web/src/pages/organization/[organizationId]/settings/index.tsx@@ -0,0 +1,73 @@+import { PagedSettingsContainer } from "@/src/components/PagedSettingsContainer";+import Header from "@/src/components/layouts/header";+import { MembershipInvitesPage } from "@/src/features/rbac/components/MembershipInvitesPage";+import { MembersTable } from "@/src/features/rbac/components/MembersTable";+import { JSONView } from "@/src/components/ui/CodeJsonViewer";+import { env } from "@/src/env.mjs";+import RenameOrganization from "@/src/features/organizations/components/RenameOrganization";+import { useQueryOrganization } from "@/src/features/organizations/hooks";+import { OrganizationUsageChart } from "@/src/features/usage-metering/OrganizationUsageChart";+import { useRouter } from "next/router";++const OrgSettingsPage = () => {+ const organization = useQueryOrganization();+ const router = useRouter();+ const { page } = router.query;++ if (!organization) return null;++ return (+ <div className="lg:container">+ <Header title="Organization Settings" />+ <PagedSettingsContainer+ activeSlug={page as string | undefined}+ pages={[+ {+ title: "General",+ slug: "index",+ content: (+ <div className="flex flex-col gap-10">+ <RenameOrganization />+ <div>+ <Header title="Debug Information" level="h3" />+ <JSONView+ title="Metadata"+ json={{ name: organization.name, id: organization.id }}+ />+ </div>+ </div>+ ),+ },+ {+ title: "Members",+ slug: "members",+ content: (+ <div className="flex flex-col gap-10">+ <div>+ <Header title="Organization Members" level="h3" />+ <MembersTable orgId={organization.id} />+ </div>+ <div>+ <MembershipInvitesPage orgId={organization.id} />+ </div>+ </div>+ ),+ },+ {+ title: "Billing",+ slug: "billing",+ content: <OrganizationUsageChart />,+ show: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined,+ },+ {+ title: "Projects",+ slug: "projects",+ href: `/organization/${organization.id}`,+ },+ ]}+ />+ </div>+ );+};++export default OrgSettingsPage;diff --git a/web/src/pages/organization/[organizationId]/setup.tsx b/web/src/pages/organization/[organizationId]/setup.tsxnew file mode 100644index 0000000000..e4781d98a9--- /dev/null+++ b/web/src/pages/organization/[organizationId]/setup.tsx@@ -0,0 +1,3 @@+import { SetupPage } from "@/src/features/setup/components/SetupPage";++export default SetupPage;diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex f9a9d2dbd3..f9b608ae22 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -23,8 +23,9 @@ import { useSession } from "next-auth/react";import { findClosestDashboardInterval } from "@/src/utils/date-range-utils";import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";import { useDebounce } from "@/src/hooks/useDebounce";+import SetupTracingButton from "@/src/features/setup/components/SetupTracingButton";-export default function Start() {+export default function Dashboard() {const router = useRouter();const projectId = router.query.projectId as string;const { selectedOption, dateRange, setDateRangeAndOption } =@@ -34,10 +35,6 @@ export default function Start() {const disableExpensiveDashboardComponents =session.data?.environment.disableExpensivePostgresQueries ?? true;- const project = session.data?.user?.projects.find(- (project) => project.id === projectId,- );-const traceFilterOptions = api.traces.filterOptions.useQuery({projectId,@@ -135,7 +132,7 @@ export default function Start() {return (<div className="md:container">- <Header title={project?.name ?? "Dashboard"} />+ <Header title="Dashboard" actionButtons={<SetupTracingButton />} /><div className="my-3 flex flex-wrap items-center justify-between gap-2"><div className=" flex flex-col gap-2 lg:flex-row"><DatePickerWithRangediff --git a/web/src/pages/project/[projectId]/models.tsx b/web/src/pages/project/[projectId]/models.tsxindex b4f9a164c6..34338c38ae 100644--- a/web/src/pages/project/[projectId]/models.tsx+++ b/web/src/pages/project/[projectId]/models.tsx@@ -3,7 +3,7 @@ import Header from "@/src/components/layouts/header";import { useRouter } from "next/router";import ModelTable from "@/src/components/table/use-cases/models";import { Button } from "@/src/components/ui/button";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { Lock } from "lucide-react";import Link from "next/link";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -12,7 +12,10 @@ import { FullScreenPage } from "@/src/components/layouts/full-screen-page";export default function ModelsPage() {const router = useRouter();const projectId = router.query.projectId as string;- const hasWriteAccess = useHasAccess({ projectId, scope: "models:CUD" });+ const hasWriteAccess = useHasProjectAccess({+ projectId,+ scope: "models:CUD",+ });const capture = usePostHogClientCapture();return (<FullScreenPage>diff --git a/web/src/pages/project/[projectId]/settings.tsx b/web/src/pages/project/[projectId]/settings.tsxdeleted file mode 100644index 768bfe2edd..0000000000--- a/web/src/pages/project/[projectId]/settings.tsx+++ /dev/null@@ -1,175 +0,0 @@-import { ChevronRightIcon } from "@heroicons/react/20/solid";-import { RocketLaunchIcon } from "@heroicons/react/24/outline";-import { SiOpenai } from "react-icons/si";-import Header from "@/src/components/layouts/header";-import { ApiKeyList } from "@/src/features/public-api/components/ApiKeyList";-import { useRouter } from "next/router";-import { Code, Bird, GraduationCap } from "lucide-react";-import { ProjectMembersTable } from "@/src/features/rbac/components/ProjectMembersTable";-import { DeleteProjectButton } from "@/src/features/projects/components/DeleteProjectButton";-import { HostNameProject } from "@/src/features/projects/components/HostNameProject";-import { ProjectUsageChart } from "@/src/features/usage-metering/ProjectUsageChart";-import { TransferOwnershipButton } from "@/src/features/projects/components/TransferOwnershipButton";-import RenameProject from "@/src/features/projects/components/RenameProject";-import { env } from "@/src/env.mjs";-import { Card } from "@tremor/react";-import { Button } from "@/src/components/ui/button";-import Link from "next/link";-import { LlmApiKeyList } from "@/src/features/public-api/components/LLMApiKeyList";-import { ScoreConfigSettings } from "@/src/features/scores/components/ScoreConfigSettings";--export default function SettingsPage() {- const router = useRouter();- const projectId = router.query.projectId as string;- return (- <div className="md:container">- <Header title="Settings" />- <div className="flex flex-col gap-10">- <HostNameProject />- <ApiKeyList projectId={projectId} />- <LlmApiKeyList projectId={projectId} />- <ProjectMembersTable projectId={projectId} />- <ProjectUsageChart projectId={projectId} />- <ScoreConfigSettings projectId={projectId} />- <Integrations projectId={projectId} />- <Instructions />- <RenameProject projectId={projectId} />- <div className="space-y-3">- <DeleteProjectButton projectId={projectId} />- <TransferOwnershipButton projectId={projectId} />- </div>- </div>- </div>- );-}--const instructionItems = [- {- name: "Introduction",- description:- "Understand the basics of langfuse: tracing and feedback collection",- href: "https://langfuse.com/docs",- icon: GraduationCap,- },- {- name: "Quickstart",- description: "Follow the quickstart to integrate langfuse into your app",- href: "https://langfuse.com/docs/get-started",- icon: RocketLaunchIcon,- },- {- name: "OpenAI SDK Integration",- description: "Trace your OpenAI API calls with a single line of code",- href: "https://langfuse.com/docs/integrations/openai",- icon: SiOpenai,- },- {- name: "Langchain Integration",- description:- "Trace your Langchain llm/chain/agent/... with a single line of code",- href: "https://langfuse.com/docs/integrations/langchain",- icon: Bird,- },- {- name: "LlamaIndex Integration",- description:- "Trace your Llamaindex RAG application by adding the global callback handler",- href: "https://langfuse.com/docs/integrations/llama-index",- icon: Code,- },- {- name: "Typescript SDK",- description: "npm install langfuse",- href: "https://langfuse.com/docs/sdk/typescript",- icon: Code,- },- {- name: "Python SDK (Decorator)",- description: "pip install langfuse",- href: "https://langfuse.com/docs/sdk/python",- icon: Code,- },- {- name: "API Reference (Swagger)",- description: "Custom integration",- href: "https://langfuse.com/docs/reference",- icon: Code,- },-];--function Instructions() {- return (- <div>- <Header title="Docs" level="h3" />- <ul- role="list"- className="mt-6 divide-y divide-border border-b border-t border-border"- >- {instructionItems.map((item, itemIdx) => (- <li key={itemIdx}>- <div className="group relative flex items-start space-x-3 py-4">- <div className="flex-shrink-0">- <span className="inline-flex h-10 w-10 items-center justify-center rounded-lg border border-border text-muted-foreground group-hover:border-primary-accent group-hover:text-primary-accent">- <item.icon className="h-6 w-6" aria-hidden="true" />- </span>- </div>- <div className="min-w-0 flex-1">- <div className="text-sm font-medium text-primary">- <a href={item.href} target="_blank" rel="noreferrer noopener">- <span className="absolute inset-0" aria-hidden="true" />- {item.name}- </a>- </div>- <p className="text-sm text-muted-foreground">- {item.description}- </p>- </div>- <div className="flex-shrink-0 self-center">- <ChevronRightIcon- className="h-5 w-5 text-muted-foreground group-hover:text-muted-foreground"- aria-hidden="true"- />- </div>- </div>- </li>- ))}- </ul>- </div>- );-}--const Integrations = (props: { projectId: string }) => {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) return null;-- return (- <div>- <Header title="Integrations" level="h3" />- <Card className="p-4 lg:w-1/2">- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src="/images/posthog-logo.svg"- alt="Posthog Logo"- className="mb-4 w-32"- />- <p className="mb-4 text-sm text-primary">- We have teamed up with PostHog (OSS product analytics) to make- Langfuse Events/Metrics available in your Posthog Dashboards.- </p>- <div className="flex items-center gap-2">- <Button variant="secondary" asChild>- <Link- href={`/project/${props.projectId}/settings/posthog-integration`}- >- Configure- </Link>- </Button>- <Button asChild variant="ghost">- <Link href="https://langfuse.com/docs/analytics/posthog">- Integration Docs- </Link>- </Button>- </div>- </Card>- </div>- );-};diff --git a/web/src/pages/project/[projectId]/settings/[page].tsx b/web/src/pages/project/[projectId]/settings/[page].tsxnew file mode 100644index 0000000000..eda8e05f5c--- /dev/null+++ b/web/src/pages/project/[projectId]/settings/[page].tsx@@ -0,0 +1,3 @@+import SettingsPage from "@/src/pages/project/[projectId]/settings";++export default SettingsPage;diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsxnew file mode 100644index 0000000000..f7ff179924--- /dev/null+++ b/web/src/pages/project/[projectId]/settings/index.tsx@@ -0,0 +1,180 @@+import Header from "@/src/components/layouts/header";+import { ApiKeyList } from "@/src/features/public-api/components/ApiKeyList";+import { LockIcon } from "lucide-react";+import { DeleteProjectButton } from "@/src/features/projects/components/DeleteProjectButton";+import { HostNameProject } from "@/src/features/projects/components/HostNameProject";+import RenameProject from "@/src/features/projects/components/RenameProject";+import { Button } from "@/src/components/ui/button";+import Link from "next/link";+import { LlmApiKeyList } from "@/src/features/public-api/components/LLMApiKeyList";+import { PagedSettingsContainer } from "@/src/components/PagedSettingsContainer";+import { useQueryProject } from "@/src/features/projects/hooks";+import { MembershipInvitesPage } from "@/src/features/rbac/components/MembershipInvitesPage";+import { MembersTable } from "@/src/features/rbac/components/MembersTable";+import { JSONView } from "@/src/components/ui/CodeJsonViewer";+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 { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { useRouter } from "next/router";++export default function SettingsPage() {+ const { project, organization } = useQueryProject();+ const router = useRouter();+ if (!project || !organization) return null;+ return (+ <div className="lg:container">+ <Header title="Project Settings" />+ <PagedSettingsContainer+ activeSlug={router.query.page as string | undefined}+ pages={[+ {+ title: "General",+ slug: "index",+ content: (+ <div className="flex flex-col gap-10">+ <HostNameProject />+ <RenameProject />+ <div>+ <Header title="Debug Information" level="h3" />+ <JSONView+ title="Metadata"+ json={{+ project: { name: project.name, id: project.id },+ org: { name: organization.name, id: organization.id },+ }}+ />+ </div>+ <div className="space-y-3">+ <Header title="Danger Zone" level="h3" />+ <div className="rounded border">+ {[+ {+ title: "Transfer ownership",+ description:+ "Transfer this project to another organization where you have the ability to create projects.",+ button: <TransferProjectButton />,+ },+ {+ title: "Delete this project",+ description:+ "Once you delete a project, there is no going back. Please be certain.",+ button: <DeleteProjectButton />,+ },+ ].map((item, index) => (+ <div+ key={index}+ className="flex items-center justify-between gap-4 border-b p-4 last:border-b-0"+ >+ <div>+ <h4 className="font-semibold">{item.title}</h4>+ <p className="text-sm">{item.description}</p>+ </div>+ {item.button}+ </div>+ ))}+ </div>+ </div>+ </div>+ ),+ },+ {+ title: "API Keys",+ slug: "api-keys",+ content: (+ <div className="flex flex-col gap-10">+ <ApiKeyList projectId={project.id} />+ <LlmApiKeyList projectId={project.id} />+ </div>+ ),+ },+ {+ title: "Scores / Evaluation",+ slug: "scores",+ content: <ScoreConfigSettings projectId={project.id} />,+ },+ {+ title: "Members",+ slug: "members",+ content: (+ <div>+ <Header title="Project Members" level="h3" />+ <div>+ <MembersTable+ orgId={organization.id}+ project={{ id: project.id, name: project.name }}+ />+ </div>+ <div>+ <MembershipInvitesPage+ orgId={organization.id}+ projectId={project.id}+ />+ </div>+ </div>+ ),+ },+ {+ title: "Integrations",+ slug: "integrations",+ content: <Integrations projectId={project.id} />,+ },+ {+ title: "Organization Settings",+ slug: "organization",+ href: `/organization/${organization.id}/settings`,+ },+ ]}+ />+ </div>+ );+}++const Integrations = (props: { projectId: string }) => {+ const entitled = useHasOrgEntitlement("integration-posthog");+ const hasAccess = useHasProjectAccess({+ projectId: props.projectId,+ scope: "integrations:CRUD",+ });++ return (+ <div>+ <Header title="Integrations" level="h3" />+ <Card className="p-4">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <PostHogLogo className="mb-4 w-40 text-foreground" />+ <p className="mb-4 text-sm text-primary">+ We have teamed up with PostHog (OSS product analytics) to make+ Langfuse Events/Metrics available in your Posthog Dashboards.+ </p>+ <div className="flex items-center gap-2">+ {entitled && hasAccess ? (+ <Button variant="secondary" asChild>+ <Link+ href={`/project/${props.projectId}/settings/integrations/posthog`}+ >+ Configure+ </Link>+ </Button>+ ) : (+ <Button variant="secondary" disabled>+ <LockIcon className="mr-2 h-4 w-4" />+ {!hasAccess+ ? "Configure"+ : !entitled+ ? "Public-beta on Langfuse Cloud"+ : ""}+ </Button>+ )}+ <Button asChild variant="ghost">+ <Link href="https://langfuse.com/docs/analytics/posthog">+ Integration Docs ↗+ </Link>+ </Button>+ </div>+ </Card>+ </div>+ );+};diff --git a/web/src/pages/project/[projectId]/settings/posthog-integration.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsxsimilarity index 92%rename from web/src/pages/project/[projectId]/settings/posthog-integration.tsxrename to web/src/pages/project/[projectId]/settings/integrations/posthog.tsxindex 809ca1adf6..842332237c 100644--- a/web/src/pages/project/[projectId]/settings/posthog-integration.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx@@ -1,3 +1,4 @@+import { PostHogLogo } from "@/src/components/PosthogLogo";import Header from "@/src/components/layouts/header";import { Button } from "@/src/components/ui/button";import {@@ -12,10 +13,10 @@ import {import { Input } from "@/src/components/ui/input";import { PasswordInput } from "@/src/components/ui/password-input";import { Switch } from "@/src/components/ui/switch";-import { env } from "@/src/env.mjs";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";import { type RouterOutput } from "@/src/utils/types";import { zodResolver } from "@hookform/resolvers/zod";@@ -29,14 +30,18 @@ import { type z } from "zod";export default function PosthogIntegrationSettings() {const router = useRouter();const projectId = router.query.projectId as string;- const hasAccess = useHasAccess({ projectId, scope: "integrations:CRUD" });+ const entitled = useHasOrgEntitlement("integration-posthog");+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "integrations:CRUD",+ });const state = api.posthogIntegration.get.useQuery({ projectId },{- enabled: hasAccess,+ enabled: hasAccess && entitled,},);- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) return null;+ if (!entitled) return null;return (<div className="md:container">@@ -48,7 +53,7 @@ export default function PosthogIntegrationSettings() {actionButtons={<Button asChild variant="secondary"><Link href="https://langfuse.com/docs/analytics/posthog">- Integration Docs+ Integration Docs ↗</Link></Button>}@@ -80,6 +85,7 @@ export default function PosthogIntegrationSettings() {<><Header level="h3" title="Configuration" /><Card className="p-4">+ <PostHogLogo className="mb-4 w-36 text-foreground" /><PostHogIntegrationSettingsstate={state.data}projectId={projectId}diff --git a/web/src/pages/project/[projectId]/setup.tsx b/web/src/pages/project/[projectId]/setup.tsxnew file mode 100644index 0000000000..e4781d98a9--- /dev/null+++ b/web/src/pages/project/[projectId]/setup.tsx@@ -0,0 +1,3 @@+import { SetupPage } from "@/src/features/setup/components/SetupPage";++export default SetupPage;diff --git a/web/src/pages/project/[projectId]/traces.tsx b/web/src/pages/project/[projectId]/traces.tsxindex e90b10ff4b..567641f889 100644--- a/web/src/pages/project/[projectId]/traces.tsx+++ b/web/src/pages/project/[projectId]/traces.tsx@@ -2,6 +2,7 @@ import Header from "@/src/components/layouts/header";import { useRouter } from "next/router";import TracesTable from "@/src/components/table/use-cases/traces";import { FullScreenPage } from "@/src/components/layouts/full-screen-page";+import SetupTracingButton from "@/src/features/setup/components/SetupTracingButton";export default function Traces() {const router = useRouter();@@ -16,6 +17,7 @@ export default function Traces() {"A trace represents a single function/api invocation. Traces contain observations. See docs to learn more.",href: "https://langfuse.com/docs/tracing",}}+ actionButtons={<SetupTracingButton />}/><TracesTable projectId={projectId} /></FullScreenPage>diff --git a/web/src/pages/setup.tsx b/web/src/pages/setup.tsxnew file mode 100644index 0000000000..e4781d98a9--- /dev/null+++ b/web/src/pages/setup.tsx@@ -0,0 +1,3 @@+import { SetupPage } from "@/src/features/setup/components/SetupPage";++export default SetupPage;diff --git a/web/src/pages/project/[projectId]/support.tsx b/web/src/pages/support.tsxsimilarity index 100%rename from web/src/pages/project/[projectId]/support.tsxrename to web/src/pages/support.tsxdiff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex ffa1c23fd9..380700d0d6 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -5,7 +5,7 @@ import { scoresRouter } from "./routers/scores";import { dashboardRouter } from "@/src/features/dashboard/server/dashboard-router";import { projectsRouter } from "@/src/features/projects/server/projectsRouter";import { apiKeysRouter } from "@/src/features/public-api/server/apiKeyRouter";-import { projectMembersRouter } from "@/src/features/rbac/server/projectMembersRouter";+import { membersRouter } from "@/src/features/rbac/server/membersRouter";import { userRouter } from "@/src/server/api/routers/users";import { datasetRouter } from "@/src/features/datasets/server/dataset-router";import { usageMeteringRouter } from "@/src/features/usage-metering/server/usageMeteringRouter";@@ -16,6 +16,7 @@ import { modelRouter } from "@/src/server/api/routers/models";import { evalRouter } from "@/src/ee/features/evals/server/router";import { posthogIntegrationRouter } from "@/src/features/posthog-integration/posthog-integration-router";import { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";+import { organizationsRouter } from "@/src/features/organizations/server/organizationRouter";import { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";import { publicRouter } from "@/src/server/api/routers/public";import { credentialsRouter } from "@/src/features/auth-credentials/server/credentialsRouter";@@ -35,10 +36,11 @@ export const appRouter = createTRPCRouter({scores: scoresRouter,scoreConfigs: scoreConfigsRouter,dashboard: dashboardRouter,+ organizations: organizationsRouter,projects: projectsRouter,users: userRouter,apiKeys: apiKeysRouter,- projectMembers: projectMembersRouter,+ members: membersRouter,datasets: datasetRouter,usageMetering: usageMeteringRouter,observations: observationsRouter,diff --git a/web/src/server/api/routers/batchExport.ts b/web/src/server/api/routers/batchExport.tsindex b751674c3b..403784602e 100644--- a/web/src/server/api/routers/batchExport.ts+++ b/web/src/server/api/routers/batchExport.ts@@ -1,6 +1,6 @@import { env } from "@/src/env.mjs";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { WorkerClient } from "@/src/server/api/services/WorkerClient";import {createTRPCRouter,@@ -16,14 +16,20 @@ import {import { getBatchExportQueue } 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. projectId- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "batchExport:create",diff --git a/web/src/server/api/routers/models.ts b/web/src/server/api/routers/models.tsindex 7f9c020f14..4acd27e706 100644--- a/web/src/server/api/routers/models.ts+++ b/web/src/server/api/routers/models.ts@@ -1,7 +1,7 @@import { z } from "zod";import { ModelUsageUnit } from "@langfuse/shared";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,protectedProjectProcedure,@@ -72,7 +72,7 @@ export const modelRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "models:CUD",@@ -89,7 +89,6 @@ export const modelRouter = createTRPCRouter({session: ctx.session,resourceType: "model",resourceId: input.modelId,- projectId: input.projectId,action: "delete",before: deletedModel,});@@ -112,7 +111,7 @@ export const modelRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "models:CUD",@@ -151,7 +150,6 @@ export const modelRouter = createTRPCRouter({session: ctx.session,resourceType: "model",resourceId: createdModel.id,- projectId: input.projectId,action: "create",after: createdModel,});diff --git a/web/src/server/api/routers/scoreConfigs.ts b/web/src/server/api/routers/scoreConfigs.tsindex 17ec303b75..a29ce52f4c 100644--- a/web/src/server/api/routers/scoreConfigs.ts+++ b/web/src/server/api/routers/scoreConfigs.ts@@ -1,4 +1,4 @@-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,protectedProjectProcedure,@@ -25,7 +25,7 @@ export const scoreConfigsRouter = createTRPCRouter({all: protectedProjectProcedure.input(ScoreConfigAllInputPaginated).query(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "scoreConfigs:read",@@ -67,7 +67,7 @@ export const scoreConfigsRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "scoreConfigs:CUD",@@ -90,7 +90,7 @@ export const scoreConfigsRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "scoreConfigs:CUD",diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 61bd03435b..2316b9b007 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -4,8 +4,8 @@ import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";-import { type ProjectRole, Prisma, type Score } from "@langfuse/shared/src/db";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { Prisma, type Score } from "@langfuse/shared/src/db";import {CreateAnnotationScoreData,UpdateAnnotationScoreData,@@ -141,7 +141,7 @@ export const scoresRouter = createTRPCRouter({createAnnotationScore: protectedProjectProcedure.input(CreateAnnotationScoreData).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "scores:CUD",@@ -180,6 +180,14 @@ export const scoresRouter = createTRPCRouter({authorUserId: ctx.session.user.id,},});+ await auditLog({+ session: ctx.session,+ resourceType: "score",+ resourceId: updatedScore.id,+ action: "update",+ before: existingScore,+ after: updatedScore,+ });return validateDbScore(updatedScore);}@@ -200,11 +208,7 @@ export const scoresRouter = createTRPCRouter({});await auditLog({- projectId: input.projectId,- userId: ctx.session.user.id,- userProjectRole: ctx.session.user.projects.find(- (p) => p.id === input.projectId,- )?.role as ProjectRole, // throwIfNoAccess ensures this is defined+ session: ctx.session,resourceType: "score",resourceId: score.id,action: "create",@@ -215,7 +219,7 @@ export const scoresRouter = createTRPCRouter({updateAnnotationScore: protectedProjectProcedure.input(UpdateAnnotationScoreData).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "scores:CUD",@@ -230,19 +234,6 @@ export const scoresRouter = createTRPCRouter({if (!score) {throw new Error("No annotation score with this id in this project.");}-- await auditLog({- projectId: input.projectId,- userId: ctx.session.user.id,- userProjectRole: ctx.session.user.projects.find(- (p) => p.id === input.projectId,- )?.role as ProjectRole, // throwIfNoAccess ensures this is defined- resourceType: "score",- resourceId: score.id,- action: "update",- after: score,- });-const updatedScore = await ctx.prisma.score.update({where: {id: score.id,@@ -255,12 +246,22 @@ export const scoresRouter = createTRPCRouter({authorUserId: ctx.session.user.id,},});++ await auditLog({+ session: ctx.session,+ resourceType: "score",+ resourceId: score.id,+ action: "update",+ before: score,+ after: updatedScore,+ });+return validateDbScore(updatedScore);}),deleteAnnotationScore: protectedProjectProcedure.input(z.object({ projectId: z.string(), id: z.string() })).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "scores:CUD",@@ -278,11 +279,7 @@ export const scoresRouter = createTRPCRouter({}await auditLog({- projectId: input.projectId,- userId: ctx.session.user.id,- userProjectRole: ctx.session.user.projects.find(- (p) => p.id === input.projectId,- )?.role as ProjectRole, // throwIfNoAccess ensures this is defined+ session: ctx.session,resourceType: "score",resourceId: score.id,action: "delete",diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex 6447142ab5..7312e40b0e 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -11,7 +11,8 @@ import {} from "@langfuse/shared";import { Prisma } from "@langfuse/shared/src/db";import { paginationZod } from "@langfuse/shared";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { TRPCError } from "@trpc/server";import { orderBy } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";@@ -185,7 +186,7 @@ export const sessionRouter = createTRPCRouter({).mutation(async ({ input, ctx }) => {try {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "objects:bookmark",@@ -238,7 +239,7 @@ export const sessionRouter = createTRPCRouter({).mutation(async ({ input, ctx }) => {try {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "objects:publish",diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex c67d3ea55e..b89c5183c9 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -18,7 +18,7 @@ import {datetimeFilterToPrismaSql,tableColumnsToSqlFilterAndPrefix,} from "@langfuse/shared";-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { TRPCError } from "@trpc/server";import { orderBy } from "@langfuse/shared";import { orderByToPrismaSql } from "@langfuse/shared";@@ -44,6 +44,19 @@ export type ObservationReturnType = Omit<};export const traceRouter = createTRPCRouter({+ hasAny: protectedProjectProcedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ input, ctx }) => {+ const hasAny = await ctx.prisma.trace.findFirst({+ where: {+ projectId: input.projectId,+ },+ select: {+ id: true,+ },+ });+ return hasAny !== null;+ }),all: protectedProjectProcedure.input(TraceFilterOptions).query(async ({ input, ctx }) => {@@ -343,7 +356,7 @@ export const traceRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "traces:delete",@@ -394,7 +407,7 @@ export const traceRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "objects:bookmark",@@ -443,7 +456,7 @@ export const traceRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "objects:publish",@@ -492,7 +505,7 @@ export const traceRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- throwIfNoAccess({+ throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,scope: "objects:tag",diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex d30ab7c06a..46ffd9c2cb 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -18,7 +18,7 @@ import { type CreateNextContextOptions } from "@trpc/server/adapters/next";import { type Session } from "next-auth";import { getServerAuthSession } from "@/src/server/auth";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, Role } from "@langfuse/shared/src/db";import * as Sentry from "@sentry/node";import * as z from "zod";@@ -79,7 +79,6 @@ import superjson from "superjson";import { ZodError } from "zod";import { setUpSuperjson } from "@/src/utils/superjson";import { DB } from "@/src/server/db";-import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";setUpSuperjson();@@ -160,7 +159,7 @@ const inputProjectSchema = z.object({*/const enforceUserIsAuthedAndProjectMember = t.middleware(- ({ ctx, rawInput, next }) => {+ async ({ ctx, rawInput, next }) => {if (!ctx.session || !ctx.session.user) {throw new TRPCError({ code: "UNAUTHORIZED" });}@@ -174,15 +173,49 @@ const enforceUserIsAuthedAndProjectMember = t.middleware(// check that the user is a member of this projectconst projectId = result.data.projectId;- const sessionProject = ctx.session.user.projects.find(- ({ id }) => id === projectId,- );-- if (!sessionProject && !isProjectMemberOrAdmin(ctx.session.user, projectId))+ const sessionProject = ctx.session.user.organizations+ .flatMap((org) =>+ org.projects.map((project) => ({ ...project, organization: org })),+ )+ .find((project) => project.id === projectId);++ if (!sessionProject) {+ if (ctx.session.user.admin === true) {+ // fetch org as it is not available in the session for admins+ const dbProject = await ctx.prisma.project.findFirst({+ select: {+ orgId: true,+ },+ where: {+ id: projectId,+ },+ });+ if (!dbProject) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Project not found",+ });+ }+ return next({+ ctx: {+ // infers the `session` as non-nullable+ session: {+ ...ctx.session,+ user: ctx.session.user,+ orgId: dbProject.orgId,+ orgRole: Role.OWNER,+ projectId: projectId,+ projectRole: Role.OWNER,+ },+ },+ });+ }+ // not a memberthrow new TRPCError({code: "UNAUTHORIZED",message: "User is not a member of this project",});+ }return next({ctx: {@@ -190,9 +223,10 @@ const enforceUserIsAuthedAndProjectMember = t.middleware(session: {...ctx.session,user: ctx.session.user,- projectRole:- ctx.session.user.admin === true ? "ADMIN" : sessionProject!.role,+ orgId: sessionProject.organization.id,+ orgRole: sessionProject.organization.role,projectId: projectId,+ projectRole: sessionProject.role,},},});@@ -203,6 +237,52 @@ export const protectedProjectProcedure = withSentryProcedure.use(enforceUserIsAuthedAndProjectMember,);+const inputOrganizationSchema = z.object({+ orgId: z.string(),+});++const enforceIsAuthedAndOrgMember = t.middleware(({ ctx, rawInput, next }) => {+ if (!ctx.session || !ctx.session.user) {+ throw new TRPCError({ code: "UNAUTHORIZED" });+ }++ const result = inputOrganizationSchema.safeParse(rawInput);+ if (!result.success) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid input, orgId is required",+ });+ }++ const orgId = result.data.orgId;+ const sessionOrg = ctx.session.user.organizations.find(+ (org) => org.id === orgId,+ );++ if (!sessionOrg && ctx.session.user.admin !== true) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "User is not a member of this organization",+ });+ }++ return next({+ ctx: {+ session: {+ ...ctx.session,+ user: ctx.session.user,+ orgId: orgId,+ orgRole:+ ctx.session.user.admin === true ? Role.OWNER : sessionOrg!.role,+ },+ },+ });+});++export const protectedOrganizationProcedure = withSentryProcedure.use(+ enforceIsAuthedAndOrgMember,+);+/** Protect trace-level getter routes.* - Users need to be member of the project to access the trace.@@ -239,15 +319,11 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {message: "Trace not found",});- const sessionProject = ctx.session?.user?.projects.find(- ({ id }) => id === trace.projectId,- );+ const sessionProject = ctx.session?.user?.organizations+ .flatMap((org) => org.projects)+ .find(({ id }) => id === trace.projectId);- if (- !trace.public &&- !sessionProject &&- !isProjectMemberOrAdmin(ctx.session?.user, trace.projectId)- )+ if (!trace.public && !sessionProject && ctx.session?.user?.admin !== true)throw new TRPCError({code: "UNAUTHORIZED",message:@@ -259,7 +335,7 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {session: {...ctx.session,projectRole:- ctx.session?.user?.admin === true ? "ADMIN" : sessionProject?.role,+ ctx.session?.user?.admin === true ? Role.OWNER : sessionProject?.role,},},});@@ -305,9 +381,9 @@ const enforceSessionAccess = t.middleware(async ({ ctx, rawInput, next }) => {message: "Session not found",});- const userSessionProject = ctx.session?.user?.projects.find(- ({ id }) => id === projectId,- );+ const userSessionProject = ctx.session?.user?.organizations+ .flatMap((org) => org.projects)+ .find(({ id }) => id === projectId);if (!session.public &&@@ -326,7 +402,7 @@ const enforceSessionAccess = t.middleware(async ({ ctx, rawInput, next }) => {...ctx.session,projectRole:ctx.session?.user?.admin === true- ? "ADMIN"+ ? Role.OWNER: userSessionProject?.role,},},diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex db52d94ebc..756b7ce70b 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -6,7 +6,7 @@ import {type Session,} from "next-auth";import { PrismaAdapter } from "@next-auth/prisma-adapter";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, type Role } from "@langfuse/shared/src/db";import { verifyPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";import { parseFlags } from "@/src/features/feature-flags/utils";import { env } from "@/src/env.mjs";@@ -30,15 +30,23 @@ import {} from "@/src/ee/features/multi-tenant-sso/utils";import { z } from "zod";import * as Sentry from "@sentry/nextjs";+import { CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";import {CustomSSOProvider,sendResetPasswordVerificationRequest,} from "@langfuse/shared/src/server";+import { getOrganizationPlan } from "@/src/features/entitlements/server/getOrganizationPlan";+import { projectRoleAccessRights } from "@/src/features/rbac/constants/projectAccessRights";-export const cloudConfigSchema = z.object({- plan: z.enum(["Hobby", "Pro", "Team", "Enterprise"]).optional(),- monthlyObservationLimit: z.number().int().positive().optional(),-});+function canCreateOrganizations(userEmail: string | null): boolean {+ // if no allowlist is set, allow all users to create organizations+ if (!env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS) return true;+ if (!userEmail) return false;++ const allowedOrgCreators =+ env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS.toLowerCase().split(",");+ return allowedOrgCreators.includes(userEmail.toLowerCase());+}const staticProviders: Provider[] = [CredentialsProvider({@@ -120,7 +128,8 @@ const staticProviders: Provider[] = [image: dbUser.image,emailVerified: dbUser.emailVerified?.toISOString(),featureFlags: parseFlags(dbUser.featureFlags),- projects: [],+ canCreateOrganizations: canCreateOrganizations(dbUser.email),+ organizations: [],};return userObj;@@ -301,9 +310,18 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {emailVerified: true,featureFlags: true,admin: true,- projectMemberships: {+ organizationMemberships: {include: {- project: true,+ organization: {+ include: {+ projects: true,+ },+ },+ ProjectMemberships: {+ include: {+ project: true,+ },+ },},},},@@ -329,20 +347,44 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {email: dbUser.email,image: dbUser.image,admin: dbUser.admin,+ canCreateOrganizations: canCreateOrganizations(dbUser.email),+ organizations: dbUser.organizationMemberships.map(+ (orgMembership) => {+ const parsedCloudConfig = CloudConfigSchema.safeParse(+ orgMembership.organization.cloudConfig,+ );+ return {+ id: orgMembership.organization.id,+ name: orgMembership.organization.name,+ role: orgMembership.role,+ cloudConfig: parsedCloudConfig.data,+ projects: orgMembership.organization.projects+ .map((project) => {+ const projectRole: Role =+ orgMembership.ProjectMemberships.find(+ (membership) =>+ membership.projectId === project.id,+ )?.role ?? orgMembership.role;+ return {+ id: project.id,+ name: project.name,+ role: projectRole,+ };+ })+ // Only include projects where the user has the required role+ .filter((project) =>+ projectRoleAccessRights[project.role].includes(+ "project:read",+ ),+ ),++ // 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),+ };+ },+ ),emailVerified: dbUser.emailVerified?.toISOString(),- projects: dbUser.projectMemberships.map((membership) => {- const cloudConfig = cloudConfigSchema.safeParse(- membership.project.cloudConfig,- );- return {- id: membership.project.id,- name: membership.project.name,- role: membership.role,- cloudConfig: cloudConfig.success- ? cloudConfig.data- : null,- };- }),featureFlags: parseFlags(dbUser.featureFlags),}: null,diff --git a/web/src/server/utils/checkProjectMembershipOrAdmin.ts b/web/src/server/utils/checkProjectMembershipOrAdmin.tsindex 7aebf1c0e3..e23fd106fb 100644--- a/web/src/server/utils/checkProjectMembershipOrAdmin.ts+++ b/web/src/server/utils/checkProjectMembershipOrAdmin.ts@@ -5,11 +5,12 @@ export const isProjectMemberOrAdmin = (projectId: string,): boolean => {if (!user) return false;+ if (user.admin === true) return true;- const isAdmin = user.admin === true;- const isProjectMember = user.projects.some(+ const sessionProjects = user.organizations.flatMap((org) => org.projects);+ const isProjectMember = sessionProjects.some((project) => project.id === projectId,);- return isProjectMember || isAdmin;+ return isProjectMember;};diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 551ce1206f..d2bf02640d 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -1,11 +1,13 @@import { type DefaultSession, type DefaultUser } from "next-auth";import {type User as PrismaUser,- type Membership as PrismaMembership,type Project as PrismaProject,+ type Organization as PrismaOrganization,+ type Role,} from "@langfuse/shared/src/db";import { type Flags } from "@/src/features/feature-flags/types";-import { type cloudConfigSchema } from "@/src/server/auth";+import { type CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";+import { type Plan } from "@/src/features/entitlements/constants/plans";/*** Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`@@ -32,11 +34,18 @@ declare module "next-auth" {image?: PrismaUser["image"];admin?: PrismaUser["admin"];emailVerified?: string | null; // iso datetime string, need to stringify as JWT & useSession do not support Date objects- projects: {- id: PrismaProject["id"];- name: PrismaProject["name"];- role: PrismaMembership["role"];- cloudConfig: z.infer<typeof cloudConfigSchema> | null;+ canCreateOrganizations: boolean; // default true, allowlist can be set via LANGFUSE_ALLOWED_ORGANIZATION_CREATORS+ organizations: {+ id: PrismaOrganization["id"];+ name: PrismaOrganization["name"];+ role: Role;+ cloudConfig: CloudConfigSchema | undefined;+ plan: Plan;+ projects: {+ id: PrismaProject["id"];+ name: PrismaProject["name"];+ role: Role; // include only projects where user has a role+ }[];}[];featureFlags: Flags;}diff --git a/worker/Dockerfile b/worker/Dockerfileindex 8ec2280c01..1ddc8c24f8 100644--- a/worker/Dockerfile+++ b/worker/Dockerfile@@ -35,6 +35,7 @@ RUN pnpm install --frozen-lockfile# pass public variables in build stepARG NEXT_PUBLIC_LANGFUSE_CLOUD_REGION+ARG NEXT_PUBLIC_DEMO_ORG_IDARG NEXT_PUBLIC_DEMO_PROJECT_IDARG NEXT_PUBLIC_POSTHOG_KEYARG NEXT_PUBLIC_POSTHOG_HOST